Compare commits
52 Commits
ed9a79f94a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| ca7709ebff | |||
| 9bf701f05a | |||
| f5875e5b87 | |||
| f79efd88e5 | |||
| cf3c7ee01a | |||
| 41e8dc30fd | |||
| 4949a03e68 | |||
| d889dc7b2a | |||
| 8393734dc3 | |||
| 25fe93231f | |||
| 8fb8b08c93 | |||
| 2b856ff6dc | |||
| cff2c73b6a | |||
| 9c095a7229 | |||
| 09bbedda18 | |||
| 727c24fb1f | |||
| 00b85b5bf2 | |||
| f954f77a6d | |||
| 027f971f5a | |||
| 30b56de709 | |||
| 24314b84ac | |||
| 4164ea2109 | |||
| 51eb5f3732 | |||
| d7d85ac834 | |||
| 118c86a73c | |||
| 3388f787c7 | |||
| 889899080a | |||
| a18071b7ec | |||
| b9e17df32c | |||
| 96f961b0f8 | |||
| ad479a2069 | |||
| 300927c7ea | |||
| 8d75e47abc | |||
| c72bf12d41 | |||
| 01871c3e13 | |||
| d521b6baad | |||
| 908e11879d | |||
| eba19126ef | |||
| 0be829b97b | |||
| 810d3a8f7f | |||
| efb99ea8d5 | |||
| bd39717e86 | |||
| d832171325 | |||
| cfaaae9360 | |||
| 27694a3a7d | |||
| 609fd5a1da | |||
| 388753ba31 | |||
| 68486d2283 | |||
| e24cf8a105 | |||
| 7879c3d9b5 | |||
| 1c18ae96f7 | |||
| a591b79656 |
3
.env.dev
3
.env.dev
@@ -2,7 +2,8 @@
|
||||
|
||||
# Django Settings
|
||||
DEBUG=True
|
||||
ENVIRONMENT=development
|
||||
# ENVIRONMENT=development
|
||||
DJANGO_ENVIRONMENT=development
|
||||
DJANGO_SETTINGS_MODULE=dbapp.settings.development
|
||||
SECRET_KEY=django-insecure-dev-key-only-for-development
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
DEBUG=False
|
||||
ENVIRONMENT=production
|
||||
# ENVIRONMENT=production
|
||||
DJANGO_ENVIRONMENT=production
|
||||
DJANGO_SETTINGS_MODULE=dbapp.settings.production
|
||||
SECRET_KEY=django-insecure-dev-key-only-for-production
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -34,3 +34,4 @@ tiles
|
||||
# docker-*
|
||||
maplibre-gl-js-5.10.0.zip
|
||||
cert.pem
|
||||
templ.json
|
||||
@@ -1,249 +0,0 @@
|
||||
# Чеклист для деплоя в Production
|
||||
|
||||
## Перед деплоем
|
||||
|
||||
### 1. Безопасность
|
||||
|
||||
- [ ] Сгенерирован новый `SECRET_KEY`
|
||||
```bash
|
||||
python generate_secret_key.py
|
||||
```
|
||||
|
||||
- [ ] Изменены все пароли в `.env`:
|
||||
- [ ] `DB_PASSWORD` - сильный пароль для PostgreSQL
|
||||
- [ ] `POSTGRES_PASSWORD` - должен совпадать с `DB_PASSWORD`
|
||||
|
||||
- [ ] Настроен `ALLOWED_HOSTS` в `.env`:
|
||||
```
|
||||
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
|
||||
```
|
||||
|
||||
- [ ] `DEBUG=False` в `.env`
|
||||
|
||||
### 2. База данных
|
||||
|
||||
- [ ] Проверены все миграции:
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml exec web python manage.py showmigrations
|
||||
```
|
||||
|
||||
- [ ] Настроен backup БД (cron job):
|
||||
```bash
|
||||
0 2 * * * cd /path/to/project && make backup
|
||||
```
|
||||
|
||||
### 3. Статические файлы
|
||||
|
||||
- [ ] Проверена директория для статики:
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml exec web python manage.py collectstatic --noinput
|
||||
```
|
||||
|
||||
### 4. SSL/HTTPS (опционально, но рекомендуется)
|
||||
|
||||
- [ ] Получены SSL сертификаты (Let's Encrypt, Certbot)
|
||||
- [ ] Сертификаты размещены в `nginx/ssl/`
|
||||
- [ ] Переименован `nginx/conf.d/ssl.conf.example` в `ssl.conf`
|
||||
- [ ] Обновлен `server_name` в `ssl.conf`
|
||||
|
||||
### 5. Nginx
|
||||
|
||||
- [ ] Проверена конфигурация Nginx:
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml exec nginx nginx -t
|
||||
```
|
||||
|
||||
- [ ] Настроены правильные домены в `nginx/conf.d/default.conf`
|
||||
|
||||
### 6. Docker
|
||||
|
||||
- [ ] Проверен `.dockerignore` - исключены ненужные файлы
|
||||
- [ ] Проверен `.gitignore` - не коммитятся секреты
|
||||
|
||||
### 7. Переменные окружения
|
||||
|
||||
Проверьте `.env` файл:
|
||||
|
||||
```bash
|
||||
# Django
|
||||
DEBUG=False
|
||||
ENVIRONMENT=production
|
||||
DJANGO_SETTINGS_MODULE=dbapp.settings.production
|
||||
SECRET_KEY=<ваш-длинный-секретный-ключ>
|
||||
|
||||
# Database
|
||||
DB_NAME=geodb
|
||||
DB_USER=geralt
|
||||
DB_PASSWORD=<сильный-пароль>
|
||||
DB_HOST=db
|
||||
DB_PORT=5432
|
||||
|
||||
# Allowed Hosts
|
||||
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
|
||||
|
||||
# PostgreSQL
|
||||
POSTGRES_DB=geodb
|
||||
POSTGRES_USER=geralt
|
||||
POSTGRES_PASSWORD=<тот-же-сильный-пароль>
|
||||
|
||||
# Gunicorn
|
||||
GUNICORN_WORKERS=3
|
||||
GUNICORN_TIMEOUT=120
|
||||
```
|
||||
|
||||
## Деплой
|
||||
|
||||
### 1. Клонирование репозитория
|
||||
|
||||
```bash
|
||||
git clone <your-repo-url>
|
||||
cd <project-directory>
|
||||
```
|
||||
|
||||
### 2. Настройка окружения
|
||||
|
||||
```bash
|
||||
cp .env.prod .env
|
||||
nano .env # Отредактируйте все необходимые переменные
|
||||
```
|
||||
|
||||
### 3. Запуск контейнеров
|
||||
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml up -d --build
|
||||
```
|
||||
|
||||
### 4. Проверка статуса
|
||||
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml ps
|
||||
docker-compose -f docker-compose.prod.yaml logs -f
|
||||
```
|
||||
|
||||
### 5. Создание суперпользователя
|
||||
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml exec web python manage.py createsuperuser
|
||||
```
|
||||
|
||||
### 6. Проверка работоспособности
|
||||
|
||||
- [ ] Открыть http://yourdomain.com
|
||||
- [ ] Открыть http://yourdomain.com/admin
|
||||
- [ ] Проверить статические файлы
|
||||
- [ ] Проверить медиа файлы
|
||||
- [ ] Проверить TileServer GL: http://yourdomain.com:8080
|
||||
|
||||
## После деплоя
|
||||
|
||||
### 1. Мониторинг
|
||||
|
||||
- [ ] Настроить мониторинг логов:
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml logs -f web
|
||||
```
|
||||
|
||||
- [ ] Проверить использование ресурсов:
|
||||
```bash
|
||||
docker stats
|
||||
```
|
||||
|
||||
### 2. Backup
|
||||
|
||||
- [ ] Настроить автоматический backup БД
|
||||
- [ ] Проверить восстановление из backup
|
||||
- [ ] Настроить backup медиа файлов
|
||||
|
||||
### 3. Обновления
|
||||
|
||||
- [ ] Документировать процесс обновления
|
||||
- [ ] Тестировать обновления на dev окружении
|
||||
|
||||
### 4. Безопасность
|
||||
|
||||
- [ ] Настроить firewall (UFW, iptables)
|
||||
- [ ] Ограничить доступ к портам:
|
||||
- Открыть: 80, 443
|
||||
- Закрыть: 5432, 8000 (доступ только внутри Docker сети)
|
||||
|
||||
- [ ] Настроить fail2ban (опционально)
|
||||
|
||||
### 5. Производительность
|
||||
|
||||
- [ ] Настроить кэширование (Redis, Memcached)
|
||||
- [ ] Оптимизировать количество Gunicorn workers
|
||||
- [ ] Настроить CDN для статики (опционально)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Проблема: Контейнеры не запускаются
|
||||
|
||||
```bash
|
||||
# Проверить логи
|
||||
docker-compose -f docker-compose.prod.yaml logs
|
||||
|
||||
# Проверить конфигурацию
|
||||
docker-compose -f docker-compose.prod.yaml config
|
||||
```
|
||||
|
||||
### Проблема: База данных недоступна
|
||||
|
||||
```bash
|
||||
# Проверить статус БД
|
||||
docker-compose -f docker-compose.prod.yaml exec db pg_isready -U geralt
|
||||
|
||||
# Проверить логи БД
|
||||
docker-compose -f docker-compose.prod.yaml logs db
|
||||
```
|
||||
|
||||
### Проблема: Статические файлы не загружаются
|
||||
|
||||
```bash
|
||||
# Пересобрать статику
|
||||
docker-compose -f docker-compose.prod.yaml exec web python manage.py collectstatic --noinput
|
||||
|
||||
# Проверить права доступа
|
||||
docker-compose -f docker-compose.prod.yaml exec web ls -la /app/staticfiles
|
||||
```
|
||||
|
||||
### Проблема: 502 Bad Gateway
|
||||
|
||||
```bash
|
||||
# Проверить, что Django запущен
|
||||
docker-compose -f docker-compose.prod.yaml ps web
|
||||
|
||||
# Проверить логи Gunicorn
|
||||
docker-compose -f docker-compose.prod.yaml logs web
|
||||
|
||||
# Проверить конфигурацию Nginx
|
||||
docker-compose -f docker-compose.prod.yaml exec nginx nginx -t
|
||||
```
|
||||
|
||||
## Полезные команды
|
||||
|
||||
```bash
|
||||
# Перезапуск сервисов
|
||||
docker-compose -f docker-compose.prod.yaml restart web
|
||||
docker-compose -f docker-compose.prod.yaml restart nginx
|
||||
|
||||
# Обновление кода
|
||||
git pull
|
||||
docker-compose -f docker-compose.prod.yaml up -d --build
|
||||
|
||||
# Backup БД
|
||||
docker-compose -f docker-compose.prod.yaml exec db pg_dump -U geralt geodb > backup.sql
|
||||
|
||||
# Восстановление БД
|
||||
docker-compose -f docker-compose.prod.yaml exec -T db psql -U geralt geodb < backup.sql
|
||||
|
||||
# Просмотр логов
|
||||
docker-compose -f docker-compose.prod.yaml logs -f --tail=100 web
|
||||
|
||||
# Очистка старых образов
|
||||
docker system prune -a
|
||||
```
|
||||
|
||||
## Контакты для поддержки
|
||||
|
||||
- Документация: [DOCKER_README.md](DOCKER_README.md)
|
||||
- Быстрый старт: [QUICKSTART.md](QUICKSTART.md)
|
||||
@@ -1,102 +0,0 @@
|
||||
# Инструкция по развертыванию изменений
|
||||
|
||||
## Шаг 1: Применение миграций
|
||||
|
||||
```bash
|
||||
cd dbapp
|
||||
python manage.py migrate
|
||||
```
|
||||
|
||||
Это создаст таблицу `lyngsatapp_lyngsat` в базе данных.
|
||||
|
||||
## Шаг 2: Запуск FlareSolver (если еще не запущен)
|
||||
|
||||
FlareSolver необходим для обхода защиты Cloudflare на сайте Lyngsat.
|
||||
|
||||
### Вариант 1: Docker
|
||||
```bash
|
||||
docker run -d -p 8191:8191 --name flaresolverr ghcr.io/flaresolverr/flaresolverr:latest
|
||||
```
|
||||
|
||||
### Вариант 2: Docker Compose
|
||||
Добавьте в `docker-compose.yaml`:
|
||||
```yaml
|
||||
services:
|
||||
flaresolverr:
|
||||
image: ghcr.io/flaresolverr/flaresolverr:latest
|
||||
container_name: flaresolverr
|
||||
ports:
|
||||
- "8191:8191"
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
Затем запустите:
|
||||
```bash
|
||||
docker-compose up -d flaresolverr
|
||||
```
|
||||
|
||||
## Шаг 3: Проверка работоспособности
|
||||
|
||||
1. Запустите сервер разработки:
|
||||
```bash
|
||||
python manage.py runserver
|
||||
```
|
||||
|
||||
2. Откройте браузер и перейдите на:
|
||||
```
|
||||
http://localhost:8000/actions/
|
||||
```
|
||||
|
||||
3. Найдите карточку "Заполнение данных Lyngsat" и нажмите на кнопку
|
||||
|
||||
4. Выберите один-два спутника для тестирования
|
||||
|
||||
5. Выберите регионы (например, только Europe)
|
||||
|
||||
6. Нажмите "Заполнить данные" и дождитесь завершения
|
||||
|
||||
## Шаг 4: Проверка результатов
|
||||
|
||||
1. Перейдите в админ-панель Django:
|
||||
```
|
||||
http://localhost:8000/admin/
|
||||
```
|
||||
|
||||
2. Откройте раздел "Lyngsatapp" → "Источники LyngSat"
|
||||
|
||||
3. Проверьте, что данные загружены корректно
|
||||
|
||||
## Возможные проблемы и решения
|
||||
|
||||
### Проблема: FlareSolver не отвечает
|
||||
**Решение**: Проверьте, что FlareSolver запущен:
|
||||
```bash
|
||||
curl http://localhost:8191/v1
|
||||
```
|
||||
|
||||
### Проблема: Спутники не найдены в базе
|
||||
**Решение**: Убедитесь, что спутники добавлены в базу данных. Используйте функцию "Добавление списка спутников" на странице действий.
|
||||
|
||||
### Проблема: Долгое выполнение
|
||||
**Решение**: Это нормально. Процесс может занять несколько минут на спутник. Начните с 1-2 спутников для тестирования.
|
||||
|
||||
### Проблема: Ошибки при парсинге
|
||||
**Решение**: Проверьте логи. Некоторые ошибки (например, некорректные частоты) не критичны и не прерывают процесс.
|
||||
|
||||
## Откат изменений (если необходимо)
|
||||
|
||||
Если нужно откатить изменения:
|
||||
|
||||
```bash
|
||||
# Откатить миграцию
|
||||
python manage.py migrate lyngsatapp zero
|
||||
|
||||
# Откатить изменения в коде
|
||||
git checkout HEAD -- dbapp/
|
||||
```
|
||||
|
||||
## Дополнительная информация
|
||||
|
||||
- Подробное руководство пользователя: `LYNGSAT_FILL_GUIDE.md`
|
||||
- Сводка изменений: `CHANGES_SUMMARY.md`
|
||||
- Документация по проекту: `README.md`
|
||||
262
DOCKER_README.md
262
DOCKER_README.md
@@ -1,262 +0,0 @@
|
||||
# Docker Setup для Django + PostGIS + TileServer GL
|
||||
|
||||
## Структура проекта
|
||||
|
||||
```
|
||||
.
|
||||
├── dbapp/ # Django приложение
|
||||
│ ├── Dockerfile # Универсальный Dockerfile
|
||||
│ ├── entrypoint.sh # Скрипт запуска
|
||||
│ └── ...
|
||||
├── nginx/ # Конфигурация Nginx (только для prod)
|
||||
│ └── conf.d/
|
||||
│ └── default.conf
|
||||
├── tiles/ # Тайлы для TileServer GL
|
||||
├── docker-compose.yaml # Development окружение
|
||||
├── docker-compose.prod.yaml # Production окружение
|
||||
├── .env.dev # Переменные для development
|
||||
└── .env.prod # Переменные для production
|
||||
```
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### Development
|
||||
|
||||
1. Скопируйте файл окружения:
|
||||
```bash
|
||||
cp .env.dev .env
|
||||
```
|
||||
|
||||
2. Запустите контейнеры:
|
||||
```bash
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
3. Создайте суперпользователя:
|
||||
```bash
|
||||
docker-compose exec web python manage.py createsuperuser
|
||||
```
|
||||
|
||||
4. Приложение доступно:
|
||||
- Django: http://localhost:8000
|
||||
- TileServer GL: http://localhost:8080
|
||||
- PostgreSQL: localhost:5432
|
||||
|
||||
### Production
|
||||
|
||||
1. Скопируйте и настройте файл окружения:
|
||||
```bash
|
||||
cp .env.prod .env
|
||||
# Отредактируйте .env и измените SECRET_KEY, пароли и ALLOWED_HOSTS
|
||||
```
|
||||
|
||||
2. Запустите контейнеры:
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml up -d --build
|
||||
```
|
||||
|
||||
3. Создайте суперпользователя:
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yaml exec web python manage.py createsuperuser
|
||||
```
|
||||
|
||||
4. Приложение доступно:
|
||||
- Nginx: http://localhost (порт 80)
|
||||
- Django (напрямую): http://localhost:8000
|
||||
- TileServer GL: http://localhost:8080
|
||||
- PostgreSQL: localhost:5432
|
||||
|
||||
## Основные команды
|
||||
|
||||
### Development
|
||||
|
||||
```bash
|
||||
# Запуск
|
||||
docker-compose up -d
|
||||
|
||||
# Остановка
|
||||
docker-compose down
|
||||
|
||||
# Просмотр логов
|
||||
docker-compose logs -f web
|
||||
|
||||
# Выполнение команд Django
|
||||
docker-compose exec web python manage.py migrate
|
||||
docker-compose exec web python manage.py createsuperuser
|
||||
docker-compose exec web python manage.py shell
|
||||
|
||||
# Пересборка после изменений в Dockerfile
|
||||
docker-compose up -d --build
|
||||
|
||||
# Полная очистка (включая volumes)
|
||||
docker-compose down -v
|
||||
```
|
||||
|
||||
### Production
|
||||
|
||||
```bash
|
||||
# Запуск
|
||||
docker-compose -f docker-compose.prod.yaml up -d
|
||||
|
||||
# Остановка
|
||||
docker-compose -f docker-compose.prod.yaml down
|
||||
|
||||
# Просмотр логов
|
||||
docker-compose -f docker-compose.prod.yaml logs -f web
|
||||
|
||||
# Выполнение команд Django
|
||||
docker-compose -f docker-compose.prod.yaml exec web python manage.py migrate
|
||||
docker-compose -f docker-compose.prod.yaml exec web python manage.py createsuperuser
|
||||
|
||||
# Пересборка
|
||||
docker-compose -f docker-compose.prod.yaml up -d --build
|
||||
```
|
||||
|
||||
## Различия между Dev и Prod
|
||||
|
||||
### Development
|
||||
- Django development server (runserver)
|
||||
- DEBUG=True
|
||||
- Код монтируется как volume (изменения применяются сразу)
|
||||
- Без Nginx
|
||||
- Простые пароли (для локальной разработки)
|
||||
|
||||
### Production
|
||||
- Gunicorn WSGI server
|
||||
- DEBUG=False
|
||||
- Код копируется в образ (не монтируется)
|
||||
- Nginx как reverse proxy
|
||||
- Сильные пароли и SECRET_KEY
|
||||
- Сбор статики (collectstatic)
|
||||
- Оптимизированные настройки безопасности
|
||||
|
||||
## Переменные окружения
|
||||
|
||||
### Основные переменные (.env)
|
||||
|
||||
```bash
|
||||
# Django
|
||||
DEBUG=True/False
|
||||
ENVIRONMENT=development/production
|
||||
DJANGO_SETTINGS_MODULE=dbapp.settings.development/production
|
||||
SECRET_KEY=your-secret-key
|
||||
|
||||
# Database
|
||||
DB_NAME=geodb
|
||||
DB_USER=geralt
|
||||
DB_PASSWORD=your-password
|
||||
DB_HOST=db
|
||||
DB_PORT=5432
|
||||
|
||||
# Allowed Hosts
|
||||
ALLOWED_HOSTS=localhost,127.0.0.1,yourdomain.com
|
||||
|
||||
# Gunicorn (только для production)
|
||||
GUNICORN_WORKERS=3
|
||||
GUNICORN_TIMEOUT=120
|
||||
```
|
||||
|
||||
## Volumes
|
||||
|
||||
### Development
|
||||
- `postgres_data_dev` - данные PostgreSQL
|
||||
- `static_volume_dev` - статические файлы
|
||||
- `media_volume_dev` - медиа файлы
|
||||
- `logs_volume_dev` - логи
|
||||
- `./dbapp:/app` - код приложения (live reload)
|
||||
|
||||
### Production
|
||||
- `postgres_data_prod` - данные PostgreSQL
|
||||
- `static_volume_prod` - статические файлы
|
||||
- `media_volume_prod` - медиа файлы
|
||||
- `logs_volume_prod` - логи
|
||||
|
||||
## TileServer GL
|
||||
|
||||
Для работы TileServer GL поместите ваши тайлы в директорию `./tiles/`.
|
||||
|
||||
Пример структуры:
|
||||
```
|
||||
tiles/
|
||||
├── config.json
|
||||
└── your-tiles.mbtiles
|
||||
```
|
||||
|
||||
## Backup и восстановление БД
|
||||
|
||||
### Backup
|
||||
```bash
|
||||
# Development
|
||||
docker-compose exec db pg_dump -U geralt geodb > backup.sql
|
||||
|
||||
# Production
|
||||
docker-compose -f docker-compose.prod.yaml exec db pg_dump -U geralt geodb > backup.sql
|
||||
```
|
||||
|
||||
### Восстановление
|
||||
```bash
|
||||
# Development
|
||||
docker-compose exec -T db psql -U geralt geodb < backup.sql
|
||||
|
||||
# Production
|
||||
docker-compose -f docker-compose.prod.yaml exec -T db psql -U geralt geodb < backup.sql
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Проблемы с миграциями
|
||||
```bash
|
||||
docker-compose exec web python manage.py migrate --fake-initial
|
||||
```
|
||||
|
||||
### Проблемы с правами доступа
|
||||
```bash
|
||||
docker-compose exec -u root web chown -R app:app /app
|
||||
```
|
||||
|
||||
### Очистка всех данных
|
||||
```bash
|
||||
docker-compose down -v
|
||||
docker system prune -a
|
||||
```
|
||||
|
||||
### Проверка логов
|
||||
```bash
|
||||
# Все сервисы
|
||||
docker-compose logs -f
|
||||
|
||||
# Конкретный сервис
|
||||
docker-compose logs -f web
|
||||
docker-compose logs -f db
|
||||
```
|
||||
|
||||
## Безопасность для Production
|
||||
|
||||
1. **Измените SECRET_KEY** - используйте длинный случайный ключ
|
||||
2. **Измените пароли БД** - используйте сильные пароли
|
||||
3. **Настройте ALLOWED_HOSTS** - укажите ваш домен
|
||||
4. **Настройте SSL** - добавьте сертификаты в `nginx/ssl/`
|
||||
5. **Ограничьте доступ к портам** - не открывайте порты БД наружу
|
||||
|
||||
## Генерация SECRET_KEY
|
||||
|
||||
```python
|
||||
python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
|
||||
```
|
||||
|
||||
## Мониторинг
|
||||
|
||||
### Проверка статуса контейнеров
|
||||
```bash
|
||||
docker-compose ps
|
||||
```
|
||||
|
||||
### Использование ресурсов
|
||||
```bash
|
||||
docker stats
|
||||
```
|
||||
|
||||
### Healthcheck
|
||||
```bash
|
||||
curl http://localhost:8000/admin/
|
||||
```
|
||||
307
DOCKER_SETUP.md
307
DOCKER_SETUP.md
@@ -1,307 +0,0 @@
|
||||
# Docker Setup - Полное руководство
|
||||
|
||||
## 📋 Обзор
|
||||
|
||||
Этот проект использует Docker для развертывания Django приложения с PostGIS и TileServer GL.
|
||||
|
||||
**Основные компоненты:**
|
||||
- Django 5.2 с PostGIS
|
||||
- PostgreSQL 17 с расширением PostGIS 3.4
|
||||
- TileServer GL для работы с картографическими тайлами
|
||||
- Nginx (только для production)
|
||||
- Gunicorn WSGI сервер (production)
|
||||
|
||||
## 🚀 Быстрый старт
|
||||
|
||||
### Development
|
||||
```bash
|
||||
cp .env.dev .env
|
||||
make dev-up
|
||||
make createsuperuser
|
||||
```
|
||||
Откройте http://localhost:8000
|
||||
|
||||
### Production
|
||||
```bash
|
||||
cp .env.prod .env
|
||||
# Отредактируйте .env (SECRET_KEY, пароли, домены)
|
||||
make prod-up
|
||||
make prod-createsuperuser
|
||||
```
|
||||
Откройте http://yourdomain.com
|
||||
|
||||
## 📁 Структура файлов
|
||||
|
||||
```
|
||||
.
|
||||
├── dbapp/ # Django приложение
|
||||
│ ├── Dockerfile # Универсальный Dockerfile
|
||||
│ ├── entrypoint.sh # Скрипт инициализации
|
||||
│ ├── .dockerignore # Исключения для Docker
|
||||
│ └── ...
|
||||
│
|
||||
├── nginx/ # Nginx конфигурация (prod)
|
||||
│ ├── conf.d/
|
||||
│ │ ├── default.conf # HTTP конфигурация
|
||||
│ │ └── ssl.conf.example # HTTPS конфигурация (пример)
|
||||
│ └── ssl/ # SSL сертификаты
|
||||
│
|
||||
├── tiles/ # Тайлы для TileServer GL
|
||||
│ ├── README.md # Инструкция по настройке
|
||||
│ ├── config.json.example # Пример конфигурации
|
||||
│ └── .gitignore
|
||||
│
|
||||
├── docker-compose.yaml # Development окружение
|
||||
├── docker-compose.prod.yaml # Production окружение
|
||||
│
|
||||
├── .env.dev # Переменные для dev
|
||||
├── .env.prod # Переменные для prod (шаблон)
|
||||
│
|
||||
├── Makefile # Удобные команды
|
||||
├── generate_secret_key.py # Генератор SECRET_KEY
|
||||
│
|
||||
└── Документация:
|
||||
├── QUICKSTART.md # Быстрый старт
|
||||
├── DOCKER_README.md # Подробная документация
|
||||
├── DEPLOYMENT_CHECKLIST.md # Чеклист для деплоя
|
||||
└── DOCKER_SETUP.md # Этот файл
|
||||
```
|
||||
|
||||
## 🔧 Конфигурация
|
||||
|
||||
### Dockerfile
|
||||
|
||||
**Один универсальный Dockerfile** для dev и prod:
|
||||
- Multi-stage build для оптимизации размера
|
||||
- Установка GDAL, PostGIS зависимостей
|
||||
- Использование uv для управления зависимостями
|
||||
- Non-root пользователь для безопасности
|
||||
- Healthcheck для мониторинга
|
||||
|
||||
### entrypoint.sh
|
||||
|
||||
Скрипт автоматически:
|
||||
- Ждет готовности PostgreSQL
|
||||
- Выполняет миграции
|
||||
- Собирает статику (только prod)
|
||||
- Запускает runserver (dev) или Gunicorn (prod)
|
||||
|
||||
Поведение определяется переменной `ENVIRONMENT`:
|
||||
- `development` → Django development server
|
||||
- `production` → Gunicorn WSGI server
|
||||
|
||||
### docker-compose.yaml (Development)
|
||||
|
||||
**Сервисы:**
|
||||
- `db` - PostgreSQL с PostGIS
|
||||
- `web` - Django приложение
|
||||
- `tileserver` - TileServer GL
|
||||
|
||||
**Особенности:**
|
||||
- Код монтируется как volume (live reload)
|
||||
- DEBUG=True
|
||||
- Django development server
|
||||
- Простые пароли для локальной разработки
|
||||
|
||||
### docker-compose.prod.yaml (Production)
|
||||
|
||||
**Сервисы:**
|
||||
- `db` - PostgreSQL с PostGIS
|
||||
- `web` - Django с Gunicorn
|
||||
- `tileserver` - TileServer GL
|
||||
- `nginx` - Reverse proxy
|
||||
|
||||
**Особенности:**
|
||||
- Код копируется в образ (не монтируется)
|
||||
- DEBUG=False
|
||||
- Gunicorn WSGI server
|
||||
- Nginx для статики и проксирования
|
||||
- Сильные пароли из .env
|
||||
- Сбор статики (collectstatic)
|
||||
|
||||
## 🔐 Безопасность
|
||||
|
||||
### Для Production обязательно:
|
||||
|
||||
1. **Сгенерируйте SECRET_KEY:**
|
||||
```bash
|
||||
python generate_secret_key.py
|
||||
```
|
||||
|
||||
2. **Измените пароли БД** в `.env`
|
||||
|
||||
3. **Настройте ALLOWED_HOSTS:**
|
||||
```
|
||||
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
|
||||
```
|
||||
|
||||
4. **Настройте SSL/HTTPS** (рекомендуется):
|
||||
- Получите сертификаты (Let's Encrypt)
|
||||
- Поместите в `nginx/ssl/`
|
||||
- Используйте `nginx/conf.d/ssl.conf.example`
|
||||
|
||||
5. **Ограничьте доступ к портам:**
|
||||
- Открыть: 80, 443
|
||||
- Закрыть: 5432, 8000
|
||||
|
||||
## 📊 Мониторинг
|
||||
|
||||
### Логи
|
||||
```bash
|
||||
# Development
|
||||
make dev-logs
|
||||
|
||||
# Production
|
||||
make prod-logs
|
||||
|
||||
# Конкретный сервис
|
||||
docker-compose logs -f web
|
||||
docker-compose logs -f db
|
||||
```
|
||||
|
||||
### Статус
|
||||
```bash
|
||||
make status # Development
|
||||
make prod-status # Production
|
||||
docker stats # Использование ресурсов
|
||||
```
|
||||
|
||||
### Healthcheck
|
||||
```bash
|
||||
curl http://localhost:8000/admin/
|
||||
```
|
||||
|
||||
## 💾 Backup и восстановление
|
||||
|
||||
### Backup
|
||||
```bash
|
||||
make backup
|
||||
# или
|
||||
docker-compose exec db pg_dump -U geralt geodb > backup_$(date +%Y%m%d).sql
|
||||
```
|
||||
|
||||
### Восстановление
|
||||
```bash
|
||||
docker-compose exec -T db psql -U geralt geodb < backup.sql
|
||||
```
|
||||
|
||||
### Автоматический backup (cron)
|
||||
```bash
|
||||
# Добавьте в crontab
|
||||
0 2 * * * cd /path/to/project && make backup
|
||||
```
|
||||
|
||||
## 🔄 Обновление
|
||||
|
||||
### Development
|
||||
```bash
|
||||
git pull
|
||||
make dev-build
|
||||
```
|
||||
|
||||
### Production
|
||||
```bash
|
||||
git pull
|
||||
make prod-build
|
||||
make prod-migrate
|
||||
```
|
||||
|
||||
## 🗺️ TileServer GL
|
||||
|
||||
Поместите `.mbtiles` файлы в директорию `tiles/`:
|
||||
|
||||
```bash
|
||||
tiles/
|
||||
├── world.mbtiles
|
||||
└── satellite.mbtiles
|
||||
```
|
||||
|
||||
Доступ: http://localhost:8080
|
||||
|
||||
Подробнее: [tiles/README.md](tiles/README.md)
|
||||
|
||||
## 🛠️ Makefile команды
|
||||
|
||||
### Development
|
||||
```bash
|
||||
make dev-up # Запустить
|
||||
make dev-down # Остановить
|
||||
make dev-build # Пересобрать
|
||||
make dev-logs # Логи
|
||||
make dev-restart # Перезапустить web
|
||||
```
|
||||
|
||||
### Production
|
||||
```bash
|
||||
make prod-up # Запустить
|
||||
make prod-down # Остановить
|
||||
make prod-build # Пересобрать
|
||||
make prod-logs # Логи
|
||||
make prod-restart # Перезапустить web
|
||||
```
|
||||
|
||||
### Django
|
||||
```bash
|
||||
make shell # Django shell
|
||||
make migrate # Миграции
|
||||
make makemigrations # Создать миграции
|
||||
make createsuperuser # Создать суперпользователя
|
||||
make collectstatic # Собрать статику
|
||||
```
|
||||
|
||||
### Утилиты
|
||||
```bash
|
||||
make backup # Backup БД
|
||||
make status # Статус контейнеров
|
||||
make clean # Очистка (с volumes)
|
||||
make clean-all # Полная очистка
|
||||
```
|
||||
|
||||
## 📚 Дополнительная документация
|
||||
|
||||
- **[QUICKSTART.md](QUICKSTART.md)** - Быстрый старт для нетерпеливых
|
||||
- **[DOCKER_README.md](DOCKER_README.md)** - Подробная документация по Docker
|
||||
- **[DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md)** - Чеклист для деплоя
|
||||
- **[tiles/README.md](tiles/README.md)** - Настройка TileServer GL
|
||||
|
||||
## ❓ Troubleshooting
|
||||
|
||||
### Контейнеры не запускаются
|
||||
```bash
|
||||
docker-compose logs
|
||||
docker-compose config
|
||||
```
|
||||
|
||||
### База данных недоступна
|
||||
```bash
|
||||
docker-compose exec db pg_isready -U geralt
|
||||
docker-compose logs db
|
||||
```
|
||||
|
||||
### Статические файлы не загружаются
|
||||
```bash
|
||||
docker-compose exec web python manage.py collectstatic --noinput
|
||||
docker-compose exec web ls -la /app/staticfiles
|
||||
```
|
||||
|
||||
### 502 Bad Gateway
|
||||
```bash
|
||||
docker-compose ps web
|
||||
docker-compose logs web
|
||||
docker-compose exec nginx nginx -t
|
||||
```
|
||||
|
||||
## 🎯 Следующие шаги
|
||||
|
||||
1. ✅ Прочитайте [QUICKSTART.md](QUICKSTART.md)
|
||||
2. ✅ Запустите development окружение
|
||||
3. ✅ Изучите [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) перед деплоем
|
||||
4. ✅ Настройте TileServer GL ([tiles/README.md](tiles/README.md))
|
||||
5. ✅ Настройте SSL для production
|
||||
|
||||
## 📞 Поддержка
|
||||
|
||||
При возникновении проблем:
|
||||
1. Проверьте логи: `make dev-logs` или `make prod-logs`
|
||||
2. Изучите документацию в этой директории
|
||||
3. Проверьте [DOCKER_README.md](DOCKER_README.md) для подробностей
|
||||
@@ -1,240 +0,0 @@
|
||||
# Обзор созданных файлов Docker Setup
|
||||
|
||||
## 🐳 Docker файлы
|
||||
|
||||
### `dbapp/Dockerfile`
|
||||
**Универсальный Dockerfile** для dev и prod окружений.
|
||||
- Multi-stage build для оптимизации
|
||||
- Установка GDAL, PostGIS, PostgreSQL клиента
|
||||
- Использование uv для управления зависимостями
|
||||
- Non-root пользователь для безопасности
|
||||
- Healthcheck для мониторинга
|
||||
|
||||
### `dbapp/entrypoint.sh`
|
||||
**Скрипт инициализации контейнера.**
|
||||
- Ожидание готовности PostgreSQL
|
||||
- Автоматические миграции
|
||||
- Сбор статики (только prod)
|
||||
- Запуск runserver (dev) или Gunicorn (prod)
|
||||
|
||||
### `dbapp/.dockerignore`
|
||||
**Исключения для Docker build.**
|
||||
- Исключает ненужные файлы из образа
|
||||
- Уменьшает размер образа
|
||||
- Ускоряет сборку
|
||||
|
||||
## 🔧 Docker Compose файлы
|
||||
|
||||
### `docker-compose.yaml`
|
||||
**Development окружение.**
|
||||
- PostgreSQL с PostGIS
|
||||
- Django с development server
|
||||
- TileServer GL
|
||||
- Код монтируется как volume (live reload)
|
||||
- DEBUG=True
|
||||
|
||||
### `docker-compose.prod.yaml`
|
||||
**Production окружение.**
|
||||
- PostgreSQL с PostGIS
|
||||
- Django с Gunicorn
|
||||
- TileServer GL
|
||||
- Nginx reverse proxy
|
||||
- Код копируется в образ
|
||||
- DEBUG=False
|
||||
- Оптимизированные настройки
|
||||
|
||||
## 🌐 Nginx конфигурация
|
||||
|
||||
### `nginx/conf.d/default.conf`
|
||||
**HTTP конфигурация для production.**
|
||||
- Проксирование к Django
|
||||
- Раздача статики и медиа
|
||||
- Оптимизированные таймауты
|
||||
- Кэширование статики
|
||||
|
||||
### `nginx/conf.d/ssl.conf.example`
|
||||
**HTTPS конфигурация (пример).**
|
||||
- SSL/TLS настройки
|
||||
- Редирект с HTTP на HTTPS
|
||||
- Security headers
|
||||
- Оптимизированные SSL параметры
|
||||
|
||||
### `nginx/ssl/.gitkeep`
|
||||
**Директория для SSL сертификатов.**
|
||||
- Поместите сюда fullchain.pem и privkey.pem
|
||||
|
||||
## 🗺️ TileServer GL
|
||||
|
||||
### `tiles/README.md`
|
||||
**Инструкция по настройке TileServer GL.**
|
||||
- Как добавить тайлы
|
||||
- Примеры конфигурации
|
||||
- Использование в Django/Leaflet
|
||||
- Где взять тайлы
|
||||
|
||||
### `tiles/config.json.example`
|
||||
**Пример конфигурации TileServer GL.**
|
||||
- Настройки путей
|
||||
- Форматы и качество
|
||||
- Домены
|
||||
|
||||
### `tiles/.gitignore`
|
||||
**Исключения для git.**
|
||||
- Игнорирует большие .mbtiles файлы
|
||||
- Сохраняет примеры конфигурации
|
||||
|
||||
## 🔐 Переменные окружения
|
||||
|
||||
### `.env.dev`
|
||||
**Переменные для development.**
|
||||
- DEBUG=True
|
||||
- Простые пароли для локальной разработки
|
||||
- Настройки БД для dev
|
||||
|
||||
### `.env.prod`
|
||||
**Шаблон переменных для production.**
|
||||
- DEBUG=False
|
||||
- Требует изменения SECRET_KEY и паролей
|
||||
- Настройки для production
|
||||
|
||||
## 🛠️ Утилиты
|
||||
|
||||
### `Makefile`
|
||||
**Удобные команды для работы с Docker.**
|
||||
- `make dev-up` - запуск dev
|
||||
- `make prod-up` - запуск prod
|
||||
- `make migrate` - миграции
|
||||
- `make backup` - backup БД
|
||||
- И многое другое
|
||||
|
||||
### `generate_secret_key.py`
|
||||
**Генератор Django SECRET_KEY.**
|
||||
```bash
|
||||
python generate_secret_key.py
|
||||
```
|
||||
|
||||
## 📚 Документация
|
||||
|
||||
### `QUICKSTART.md`
|
||||
**Быстрый старт.**
|
||||
- Минимальные команды для запуска
|
||||
- Development и Production
|
||||
- Основные команды
|
||||
|
||||
### `DOCKER_README.md`
|
||||
**Подробная документация.**
|
||||
- Полное описание структуры
|
||||
- Все команды с примерами
|
||||
- Troubleshooting
|
||||
- Backup и восстановление
|
||||
|
||||
### `DOCKER_SETUP.md`
|
||||
**Полное руководство.**
|
||||
- Обзор всей системы
|
||||
- Конфигурация
|
||||
- Безопасность
|
||||
- Мониторинг
|
||||
|
||||
### `DEPLOYMENT_CHECKLIST.md`
|
||||
**Чеклист для деплоя.**
|
||||
- Пошаговая инструкция
|
||||
- Проверка безопасности
|
||||
- Настройка production
|
||||
- Troubleshooting
|
||||
|
||||
### `FILES_OVERVIEW.md`
|
||||
**Этот файл.**
|
||||
- Описание всех созданных файлов
|
||||
- Назначение каждого файла
|
||||
|
||||
## 📝 Обновленные файлы
|
||||
|
||||
### `.gitignore`
|
||||
**Обновлен для Docker.**
|
||||
- Исключает .env файлы
|
||||
- Исключает логи и backup
|
||||
- Исключает временные файлы
|
||||
|
||||
## 🎯 Как использовать
|
||||
|
||||
### Для начала работы:
|
||||
1. Прочитайте **QUICKSTART.md**
|
||||
2. Выберите окружение (dev или prod)
|
||||
3. Скопируйте соответствующий .env файл
|
||||
4. Запустите с помощью Makefile
|
||||
|
||||
### Для деплоя:
|
||||
1. Прочитайте **DEPLOYMENT_CHECKLIST.md**
|
||||
2. Следуйте чеклисту пошагово
|
||||
3. Используйте **DOCKER_README.md** для справки
|
||||
|
||||
### Для настройки TileServer:
|
||||
1. Прочитайте **tiles/README.md**
|
||||
2. Добавьте .mbtiles файлы
|
||||
3. Настройте config.json (опционально)
|
||||
|
||||
## 📊 Структура проекта
|
||||
|
||||
```
|
||||
.
|
||||
├── Docker конфигурация
|
||||
│ ├── dbapp/Dockerfile
|
||||
│ ├── dbapp/entrypoint.sh
|
||||
│ ├── dbapp/.dockerignore
|
||||
│ ├── docker-compose.yaml
|
||||
│ └── docker-compose.prod.yaml
|
||||
│
|
||||
├── Nginx
|
||||
│ ├── nginx/conf.d/default.conf
|
||||
│ ├── nginx/conf.d/ssl.conf.example
|
||||
│ └── nginx/ssl/.gitkeep
|
||||
│
|
||||
├── TileServer GL
|
||||
│ ├── tiles/README.md
|
||||
│ ├── tiles/config.json.example
|
||||
│ └── tiles/.gitignore
|
||||
│
|
||||
├── Переменные окружения
|
||||
│ ├── .env.dev
|
||||
│ └── .env.prod
|
||||
│
|
||||
├── Утилиты
|
||||
│ ├── Makefile
|
||||
│ └── generate_secret_key.py
|
||||
│
|
||||
└── Документация
|
||||
├── QUICKSTART.md
|
||||
├── DOCKER_README.md
|
||||
├── DOCKER_SETUP.md
|
||||
├── DEPLOYMENT_CHECKLIST.md
|
||||
└── FILES_OVERVIEW.md
|
||||
```
|
||||
|
||||
## ✅ Что было сделано
|
||||
|
||||
1. ✅ Создан универсальный Dockerfile (один для dev и prod)
|
||||
2. ✅ Настроен entrypoint.sh с автоматической инициализацией
|
||||
3. ✅ Созданы docker-compose.yaml для dev и prod
|
||||
4. ✅ Настроен Nginx для production
|
||||
5. ✅ Добавлена поддержка TileServer GL
|
||||
6. ✅ Созданы .env файлы для разных окружений
|
||||
7. ✅ Добавлен Makefile с удобными командами
|
||||
8. ✅ Написана подробная документация
|
||||
9. ✅ Создан чеклист для деплоя
|
||||
10. ✅ Добавлены утилиты (генератор SECRET_KEY)
|
||||
|
||||
## 🚀 Следующие шаги
|
||||
|
||||
1. Запустите development окружение
|
||||
2. Протестируйте все функции
|
||||
3. Подготовьте production окружение
|
||||
4. Следуйте DEPLOYMENT_CHECKLIST.md
|
||||
5. Настройте мониторинг и backup
|
||||
|
||||
## 💡 Полезные ссылки
|
||||
|
||||
- Django Documentation: https://docs.djangoproject.com/
|
||||
- Docker Documentation: https://docs.docker.com/
|
||||
- PostGIS Documentation: https://postgis.net/documentation/
|
||||
- TileServer GL: https://github.com/maptiler/tileserver-gl
|
||||
- Nginx Documentation: https://nginx.org/en/docs/
|
||||
@@ -1,167 +0,0 @@
|
||||
### Шаг 2: Применение миграций
|
||||
|
||||
```bash
|
||||
cd dbapp
|
||||
python manage.py migrate
|
||||
```
|
||||
|
||||
Это создаст:
|
||||
- Таблицу `lyngsatapp_lyngsat` для данных Lyngsat
|
||||
- Таблицы `django_celery_results_*` для результатов Celery
|
||||
|
||||
### Шаг 3: Запуск сервисов
|
||||
|
||||
```bash
|
||||
# Запуск Redis и FlareSolver
|
||||
docker-compose up -d redis flaresolverr
|
||||
|
||||
# Проверка
|
||||
redis-cli ping # Должно вернуть PONG
|
||||
curl http://localhost:8191/v1 # Должно вернуть JSON
|
||||
```
|
||||
|
||||
### Шаг 4: Запуск приложения
|
||||
|
||||
**Терминал 1 - Django:**
|
||||
```bash
|
||||
cd dbapp
|
||||
python manage.py runserver
|
||||
```
|
||||
|
||||
**Терминал 2 - Celery Worker:**
|
||||
```bash
|
||||
cd dbapp
|
||||
celery -A dbapp worker --loglevel=info
|
||||
```
|
||||
|
||||
### Шаг 5: Тестирование
|
||||
|
||||
1. Откройте `http://localhost:8000/actions/`
|
||||
2. Нажмите "Заполнить данные Lyngsat"
|
||||
3. Выберите спутники и регионы
|
||||
4. Наблюдайте за прогрессом!
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Проверка Django
|
||||
```bash
|
||||
python dbapp/manage.py check
|
||||
# Должно вывести: System check identified no issues (0 silenced).
|
||||
```
|
||||
|
||||
### Проверка Celery (если установлен)
|
||||
```bash
|
||||
celery -A dbapp inspect ping
|
||||
# Должно вывести: pong
|
||||
```
|
||||
|
||||
### Проверка Redis (если установлен)
|
||||
```bash
|
||||
redis-cli ping
|
||||
# Должно вывести: PONG
|
||||
```
|
||||
|
||||
### Проверка FlareSolver
|
||||
```bash
|
||||
curl http://localhost:8191/v1
|
||||
# Должно вернуть JSON с информацией о сервисе
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Проблема: FlareSolver не отвечает
|
||||
|
||||
**Решение**: Запустите FlareSolver
|
||||
```bash
|
||||
docker-compose up -d flaresolverr
|
||||
# или
|
||||
docker run -d -p 8191:8191 ghcr.io/flaresolverr/flaresolverr:latest
|
||||
```
|
||||
|
||||
|
||||
## Дополнительные инструменты
|
||||
|
||||
### Flower - мониторинг Celery
|
||||
|
||||
```bash
|
||||
pip install flower
|
||||
celery -A dbapp flower
|
||||
# Откройте http://localhost:5555
|
||||
```
|
||||
|
||||
### Redis Commander - GUI для Redis
|
||||
|
||||
```bash
|
||||
docker run -d -p 8081:8081 --name redis-commander \
|
||||
--env REDIS_HOSTS=local:localhost:6379 \
|
||||
rediscommander/redis-commander
|
||||
# Откройте http://localhost:8081
|
||||
```
|
||||
|
||||
### pgAdmin - GUI для PostgreSQL
|
||||
|
||||
```bash
|
||||
docker run -d -p 5050:80 --name pgadmin \
|
||||
-e PGADMIN_DEFAULT_EMAIL=admin@admin.com \
|
||||
-e PGADMIN_DEFAULT_PASSWORD=admin \
|
||||
dpage/pgadmin4
|
||||
# Откройте http://localhost:5050
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Остановка сервисов
|
||||
|
||||
```bash
|
||||
# Остановка Docker контейнеров
|
||||
docker-compose down
|
||||
|
||||
# Остановка Celery Worker
|
||||
pkill -f "celery worker"
|
||||
```
|
||||
|
||||
### Удаление данных
|
||||
|
||||
```bash
|
||||
# Удаление Docker volumes
|
||||
docker-compose down -v
|
||||
|
||||
# Удаление виртуального окружения
|
||||
rm -rf dbapp/.venv
|
||||
|
||||
# Удаление миграций (опционально)
|
||||
find dbapp -path "*/migrations/*.py" -not -name "__init__.py" -delete
|
||||
find dbapp -path "*/migrations/*.pyc" -delete
|
||||
```
|
||||
|
||||
# Systemd service для запуска с хоста
|
||||
|
||||
[Unit]
|
||||
Description=Django Application
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=notify
|
||||
User=www-data
|
||||
Group=www-data
|
||||
WorkingDirectory=/path/to/your/app
|
||||
Environment=PATH=/path/to/venv/bin
|
||||
Environment=DATABASE_URL=postgresql://user:pass@localhost/geodb
|
||||
ExecStart=/path/to/venv/bin/python manage.py runserver 0.0.0.0:8000
|
||||
ExecReload=/bin/kill -s HUP $MAINPID
|
||||
TimeoutSec=300
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
## Поддержка
|
||||
|
||||
1. Проверьте логи:
|
||||
- Django: консоль где запущен runserver
|
||||
- Celery: `dbapp/logs/celery_worker.log`
|
||||
- Docker: `docker-compose logs`
|
||||
|
||||
38
Makefile
38
Makefile
@@ -2,14 +2,26 @@
|
||||
|
||||
help:
|
||||
@echo "Доступные команды:"
|
||||
@echo ""
|
||||
@echo "Development:"
|
||||
@echo " make dev-up - Запустить development окружение"
|
||||
@echo " make dev-down - Остановить development окружение"
|
||||
@echo " make dev-build - Пересобрать development контейнеры"
|
||||
@echo " make dev-logs - Показать логи development"
|
||||
@echo ""
|
||||
@echo "Production:"
|
||||
@echo " make prod-up - Запустить production окружение"
|
||||
@echo " make prod-down - Остановить production окружение"
|
||||
@echo " make prod-build - Пересобрать production контейнеры"
|
||||
@echo " make prod-logs - Показать логи production"
|
||||
@echo ""
|
||||
@echo "Celery (Production):"
|
||||
@echo " make prod-worker-logs - Логи Celery worker"
|
||||
@echo " make prod-beat-logs - Логи Celery beat"
|
||||
@echo " make prod-celery-status - Статус Celery"
|
||||
@echo " make prod-celery-test - Тест Celery подключения"
|
||||
@echo ""
|
||||
@echo "Django:"
|
||||
@echo " make shell - Открыть Django shell"
|
||||
@echo " make migrate - Выполнить миграции"
|
||||
@echo " make createsuperuser - Создать суперпользователя"
|
||||
@@ -97,3 +109,29 @@ status:
|
||||
|
||||
prod-status:
|
||||
docker-compose -f docker-compose.prod.yaml ps
|
||||
|
||||
# Celery команды для production
|
||||
prod-worker-logs:
|
||||
docker-compose -f docker-compose.prod.yaml logs -f worker
|
||||
|
||||
prod-beat-logs:
|
||||
docker-compose -f docker-compose.prod.yaml logs -f beat
|
||||
|
||||
prod-celery-status:
|
||||
docker-compose -f docker-compose.prod.yaml exec web uv run celery -A dbapp inspect active
|
||||
|
||||
prod-celery-test:
|
||||
docker-compose -f docker-compose.prod.yaml exec web uv run python test_celery.py
|
||||
|
||||
prod-redis-test:
|
||||
docker-compose -f docker-compose.prod.yaml exec web uv run python check_redis.py
|
||||
|
||||
# Celery команды для development
|
||||
celery-status:
|
||||
cd dbapp && uv run celery -A dbapp inspect active
|
||||
|
||||
celery-test:
|
||||
cd dbapp && uv run python test_celery.py
|
||||
|
||||
redis-test:
|
||||
cd dbapp && uv run python check_redis.py
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
# ObjItemListView Query Optimization Report
|
||||
|
||||
## Дата: 2025-11-18
|
||||
|
||||
## Проблема
|
||||
|
||||
При загрузке страницы списка ObjItems с большой пагинацией (500-1000 элементов) возникало **292+ дублирующихся SQL запросов** для получения mirrors (зеркал) через отношение ManyToMany:
|
||||
|
||||
```sql
|
||||
SELECT ••• FROM "mainapp_satellite"
|
||||
INNER JOIN "mainapp_geo_mirrors" ON ("mainapp_satellite"."id" = "mainapp_geo_mirrors"."satellite_id")
|
||||
WHERE "mainapp_geo_mirrors"."geo_id" = 4509
|
||||
ORDER BY 1 ASC
|
||||
```
|
||||
|
||||
Это классическая проблема N+1 запросов, где для каждого ObjItem выполнялся отдельный запрос для получения связанных mirrors.
|
||||
|
||||
## Решение
|
||||
|
||||
### 1. Добавлен импорт Prefetch
|
||||
|
||||
```python
|
||||
from django.db.models import F, Prefetch
|
||||
```
|
||||
|
||||
### 2. Создан оптимизированный Prefetch для mirrors
|
||||
|
||||
```python
|
||||
mirrors_prefetch = Prefetch(
|
||||
'geo_obj__mirrors',
|
||||
queryset=Satellite.objects.only('id', 'name').order_by('id')
|
||||
)
|
||||
```
|
||||
|
||||
### 3. Применен Prefetch в обоих ветках queryset
|
||||
|
||||
Для случая с выбранными спутниками:
|
||||
```python
|
||||
objects = (
|
||||
ObjItem.objects.select_related(
|
||||
"geo_obj",
|
||||
"source",
|
||||
"updated_by__user",
|
||||
"created_by__user",
|
||||
"lyngsat_source",
|
||||
"parameter_obj",
|
||||
"parameter_obj__id_satellite",
|
||||
"parameter_obj__polarization",
|
||||
"parameter_obj__modulation",
|
||||
"parameter_obj__standard",
|
||||
"transponder",
|
||||
"transponder__sat_id",
|
||||
"transponder__polarization",
|
||||
)
|
||||
.prefetch_related(
|
||||
"parameter_obj__sigma_parameter",
|
||||
"parameter_obj__sigma_parameter__polarization",
|
||||
mirrors_prefetch, # ← Оптимизированный prefetch
|
||||
)
|
||||
.filter(parameter_obj__id_satellite_id__in=selected_satellites)
|
||||
)
|
||||
```
|
||||
|
||||
### 4. Добавлены select_related для transponder
|
||||
|
||||
Также добавлены оптимизации для transponder, которые ранее отсутствовали:
|
||||
- `"transponder"`
|
||||
- `"transponder__sat_id"`
|
||||
- `"transponder__polarization"`
|
||||
|
||||
## Результаты
|
||||
|
||||
### До оптимизации
|
||||
- **50 элементов**: ~295 запросов
|
||||
- **100 элементов**: ~295 запросов
|
||||
- **500 элементов**: ~295 запросов
|
||||
- **1000 элементов**: ~295 запросов
|
||||
|
||||
### После оптимизации
|
||||
- **50 элементов**: **3 запроса** ✓
|
||||
- **100 элементов**: **3 запроса** ✓
|
||||
- **500 элементов**: **3 запроса** ✓
|
||||
- **1000 элементов**: **3 запроса** ✓
|
||||
|
||||
### Улучшение производительности
|
||||
|
||||
| Метрика | До | После | Улучшение |
|
||||
|---------|-----|-------|-----------|
|
||||
| Запросов на 50 элементов | ~295 | 3 | **98.9%** ↓ |
|
||||
| Запросов на 1000 элементов | ~295 | 3 | **98.9%** ↓ |
|
||||
| Запросов на элемент | ~5.9 | 0.003 | **99.9%** ↓ |
|
||||
|
||||
## Структура запросов после оптимизации
|
||||
|
||||
1. **Основной запрос** - получение всех ObjItems с JOIN для всех select_related отношений
|
||||
2. **Prefetch для sigma_parameter** - один запрос для всех sigma параметров
|
||||
3. **Prefetch для mirrors** - один запрос для всех mirrors через geo_obj
|
||||
|
||||
## Тестирование
|
||||
|
||||
Созданы тестовые скрипты для проверки оптимизации:
|
||||
|
||||
1. `test_objitem_query_optimization.py` - базовый тест
|
||||
2. `test_objitem_detailed_queries.py` - детальный тест с доступом ко всем данным
|
||||
3. `test_objitem_scale.py` - тест масштабируемости (50, 100, 500, 1000 элементов)
|
||||
|
||||
Все тесты подтверждают, что количество запросов остается константным (3 запроса) независимо от размера страницы.
|
||||
|
||||
## Соответствие требованиям
|
||||
|
||||
Задача 29 из `.kiro/specs/django-refactoring/tasks.md`:
|
||||
|
||||
- ✅ Добавлен select_related() для всех связанных моделей
|
||||
- ✅ Добавлен prefetch_related() для mirrors (через Prefetch объект)
|
||||
- ✅ Проверено количество запросов до и после оптимизации
|
||||
- ✅ Требования 8.1, 8.2, 8.3, 8.4, 8.6 выполнены
|
||||
|
||||
## Дополнительные улучшения
|
||||
|
||||
1. Использован `Prefetch` объект вместо простой строки для более точного контроля
|
||||
2. Добавлен `.only('id', 'name')` для mirrors, чтобы загружать только необходимые поля
|
||||
3. Добавлен `.order_by('id')` для стабильного порядка результатов
|
||||
|
||||
## Заключение
|
||||
|
||||
Оптимизация успешно устранила проблему N+1 запросов для mirrors. Количество SQL запросов сокращено с ~295 до 3 (сокращение на **98.9%**), что значительно улучшает производительность страницы, особенно при больших размерах пагинации.
|
||||
@@ -1,192 +0,0 @@
|
||||
# SQL Query Optimization Report: SourceListView
|
||||
|
||||
## Summary
|
||||
|
||||
Successfully optimized SQL queries in `SourceListView` to eliminate N+1 query problems and improve performance.
|
||||
|
||||
## Optimization Results
|
||||
|
||||
### Query Count
|
||||
- **Total queries**: 22 (constant regardless of page size)
|
||||
- **Variation across page sizes**: 0 (perfectly stable)
|
||||
- **Status**: ✅ EXCELLENT
|
||||
|
||||
### Test Results
|
||||
|
||||
| Page Size | Query Count | Status |
|
||||
|-----------|-------------|--------|
|
||||
| 10 items | 22 queries | ✅ Stable |
|
||||
| 50 items | 22 queries | ✅ Stable |
|
||||
| 100 items | 22 queries | ✅ Stable |
|
||||
|
||||
**Key Achievement**: Query count remains constant at 22 regardless of the number of items displayed, proving there are no N+1 query problems.
|
||||
|
||||
## Optimizations Applied
|
||||
|
||||
### 1. select_related() for ForeignKey/OneToOne Relationships
|
||||
|
||||
Added `select_related()` to fetch related objects in a single query using SQL JOINs:
|
||||
|
||||
```python
|
||||
sources = Source.objects.select_related(
|
||||
'info', # ForeignKey to ObjectInfo
|
||||
'created_by', # ForeignKey to CustomUser
|
||||
'created_by__user', # OneToOne to User (through CustomUser)
|
||||
'updated_by', # ForeignKey to CustomUser
|
||||
'updated_by__user', # OneToOne to User (through CustomUser)
|
||||
)
|
||||
```
|
||||
|
||||
**Impact**: Eliminates separate queries for each Source's info, created_by, and updated_by relationships.
|
||||
|
||||
### 2. prefetch_related() for Reverse ForeignKey and ManyToMany
|
||||
|
||||
Added comprehensive `prefetch_related()` to fetch related collections efficiently:
|
||||
|
||||
```python
|
||||
.prefetch_related(
|
||||
# ObjItems and their nested relationships
|
||||
'source_objitems',
|
||||
'source_objitems__parameter_obj',
|
||||
'source_objitems__parameter_obj__id_satellite',
|
||||
'source_objitems__parameter_obj__polarization',
|
||||
'source_objitems__parameter_obj__modulation',
|
||||
'source_objitems__parameter_obj__standard',
|
||||
'source_objitems__geo_obj',
|
||||
'source_objitems__geo_obj__mirrors', # ManyToMany
|
||||
'source_objitems__lyngsat_source',
|
||||
'source_objitems__lyngsat_source__satellite',
|
||||
'source_objitems__transponder',
|
||||
'source_objitems__created_by',
|
||||
'source_objitems__created_by__user',
|
||||
'source_objitems__updated_by',
|
||||
'source_objitems__updated_by__user',
|
||||
|
||||
# Marks and their relationships
|
||||
'marks',
|
||||
'marks__created_by',
|
||||
'marks__created_by__user'
|
||||
)
|
||||
```
|
||||
|
||||
**Impact**: Fetches all related ObjItems, Parameters, Geo objects, Marks, and their nested relationships in separate optimized queries instead of one query per item.
|
||||
|
||||
### 3. annotate() for Efficient Counting
|
||||
|
||||
Used `annotate()` with `Count()` to calculate objitem counts in the database:
|
||||
|
||||
```python
|
||||
.annotate(
|
||||
objitem_count=Count('source_objitems', filter=objitem_filter_q, distinct=True)
|
||||
if has_objitem_filter
|
||||
else Count('source_objitems')
|
||||
)
|
||||
```
|
||||
|
||||
**Impact**: Counts are calculated in the database using GROUP BY instead of Python loops, and the count is available as an attribute on each Source object.
|
||||
|
||||
## Query Breakdown
|
||||
|
||||
The 22 queries consist of:
|
||||
|
||||
1. **1 COUNT query**: For pagination (total count)
|
||||
2. **1 Main SELECT**: Source objects with JOINs for select_related fields
|
||||
3. **~20 Prefetch queries**: For all prefetch_related relationships
|
||||
- ObjItems
|
||||
- Parameters
|
||||
- Satellites
|
||||
- Polarizations
|
||||
- Modulations
|
||||
- Standards
|
||||
- Geo objects
|
||||
- Mirrors (ManyToMany)
|
||||
- Transponders
|
||||
- LyngsatSources
|
||||
- CustomUsers
|
||||
- Auth Users
|
||||
- ObjectMarks
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
### Before Optimization (Estimated)
|
||||
Without proper optimization, the query count would scale linearly with the number of items:
|
||||
- 10 items: ~100+ queries (N+1 problem)
|
||||
- 50 items: ~500+ queries
|
||||
- 100 items: ~1000+ queries
|
||||
|
||||
### After Optimization
|
||||
- 10 items: 22 queries ✅
|
||||
- 50 items: 22 queries ✅
|
||||
- 100 items: 22 queries ✅
|
||||
|
||||
**Improvement**: ~95-98% reduction in query count for larger page sizes.
|
||||
|
||||
## Compliance with Requirements
|
||||
|
||||
### Requirement 8.1: Minimize SQL queries
|
||||
✅ **ACHIEVED**: Query count reduced to 22 constant queries
|
||||
|
||||
### Requirement 8.2: Use select_related() for ForeignKey/OneToOne
|
||||
✅ **ACHIEVED**: Applied to info, created_by, updated_by relationships
|
||||
|
||||
### Requirement 8.3: Use prefetch_related() for ManyToMany and reverse ForeignKey
|
||||
✅ **ACHIEVED**: Applied to all reverse relationships and ManyToMany (mirrors)
|
||||
|
||||
### Requirement 8.4: Use annotate() for aggregations
|
||||
✅ **ACHIEVED**: Used for objitem_count calculation
|
||||
|
||||
### Requirement 8.6: Reduce query count by at least 50%
|
||||
✅ **EXCEEDED**: Achieved 95-98% reduction for typical page sizes
|
||||
|
||||
## Testing Methodology
|
||||
|
||||
Three test scripts were created to verify the optimization:
|
||||
|
||||
1. **test_source_query_optimization.py**: Basic query count test
|
||||
2. **test_source_query_detailed.py**: Detailed query analysis
|
||||
3. **test_source_query_scale.py**: Scaling test with different page sizes
|
||||
|
||||
All tests confirm:
|
||||
- No N+1 query problems
|
||||
- Stable query count across different page sizes
|
||||
- Efficient use of Django ORM optimization techniques
|
||||
|
||||
## Recommendations
|
||||
|
||||
1. ✅ The optimization is complete and working correctly
|
||||
2. ✅ Query count is well within acceptable limits (≤50)
|
||||
3. ✅ No further optimization needed for SourceListView
|
||||
4. 📝 Apply similar patterns to other list views (ObjItemListView, TransponderListView, etc.)
|
||||
|
||||
## Bug Fix
|
||||
|
||||
### Issue
|
||||
Initial implementation had an incorrect prefetch path:
|
||||
- ❌ `'source_objitems__lyngsat_source__satellite'`
|
||||
|
||||
### Resolution
|
||||
Fixed to use the correct field name from LyngSat model:
|
||||
- ✅ `'source_objitems__lyngsat_source__id_satellite'`
|
||||
|
||||
The LyngSat model uses `id_satellite` as the ForeignKey field name, not `satellite`.
|
||||
|
||||
### Verification
|
||||
Tested with 1000 items per page - no errors, 24 queries total.
|
||||
|
||||
## Files Modified
|
||||
|
||||
- `dbapp/mainapp/views/source.py`: Updated SourceListView.get() method with optimized queryset
|
||||
|
||||
## Test Files Created
|
||||
|
||||
- `test_source_query_optimization.py`: Basic optimization test
|
||||
- `test_source_query_detailed.py`: Detailed query analysis
|
||||
- `test_source_query_scale.py`: Scaling verification test
|
||||
- `test_source_1000_items.py`: Large page size test (1000 items)
|
||||
- `OPTIMIZATION_REPORT_SourceListView.md`: This report
|
||||
|
||||
---
|
||||
|
||||
**Date**: 2025-11-18
|
||||
**Status**: ✅ COMPLETE (Bug Fixed)
|
||||
**Task**: 28. Оптимизировать запросы в SourceListView
|
||||
@@ -1,90 +0,0 @@
|
||||
# Отчет об оптимизации запросов в ObjItemListView
|
||||
|
||||
## Задача 29: Оптимизировать запросы в ObjItemListView
|
||||
|
||||
### Выполненные изменения
|
||||
|
||||
#### 1. Добавлены select_related() для всех связанных моделей
|
||||
Добавлены следующие связи через `select_related()`:
|
||||
- `transponder`
|
||||
- `transponder__sat_id`
|
||||
- `transponder__polarization`
|
||||
|
||||
Эти связи уже были частично оптимизированы, но были добавлены недостающие.
|
||||
|
||||
#### 2. Добавлены prefetch_related() для mirrors и marks
|
||||
Использованы оптимизированные `Prefetch` объекты:
|
||||
|
||||
```python
|
||||
# Оптимизированный prefetch для mirrors через geo_obj
|
||||
mirrors_prefetch = Prefetch(
|
||||
'geo_obj__mirrors',
|
||||
queryset=Satellite.objects.only('id', 'name').order_by('id')
|
||||
)
|
||||
|
||||
# Оптимизированный prefetch для marks через source
|
||||
marks_prefetch = Prefetch(
|
||||
'source__marks',
|
||||
queryset=ObjectMark.objects.select_related('created_by__user').order_by('-timestamp')
|
||||
)
|
||||
```
|
||||
|
||||
#### 3. Исправлен доступ к mirrors
|
||||
Изменен способ доступа к mirrors с `values_list()` на list comprehension:
|
||||
|
||||
**Было:**
|
||||
```python
|
||||
mirrors_list = list(obj.geo_obj.mirrors.values_list('name', flat=True))
|
||||
```
|
||||
|
||||
**Стало:**
|
||||
```python
|
||||
mirrors_list = [mirror.name for mirror in obj.geo_obj.mirrors.all()]
|
||||
```
|
||||
|
||||
Это критически важно, так как `values_list()` обходит prefetch_related и вызывает дополнительные запросы.
|
||||
|
||||
### Результаты тестирования
|
||||
|
||||
#### Тест 1: Сравнение с baseline (50 объектов)
|
||||
- **До оптимизации:** 51 запрос
|
||||
- **После оптимизации:** 4 запроса
|
||||
- **Улучшение:** 92.2% (сокращение на 47 запросов)
|
||||
|
||||
#### Тест 2: Масштабируемость
|
||||
| Количество объектов | Запросов |
|
||||
|---------------------|----------|
|
||||
| 10 | 4 |
|
||||
| 50 | 4 |
|
||||
| 100 | 4 |
|
||||
| 200 | 4 |
|
||||
|
||||
**Результат:** ✓ PERFECT! Количество запросов остается постоянным независимо от количества объектов.
|
||||
|
||||
### Структура запросов после оптимизации
|
||||
|
||||
1. **Основной запрос:** SELECT для ObjItem с JOIN для всех select_related связей
|
||||
2. **Prefetch mirrors:** SELECT для Satellite через geo_mirrors (ManyToMany)
|
||||
3. **Prefetch source:** SELECT для Source (если не покрыто select_related)
|
||||
4. **Prefetch marks:** SELECT для ObjectMark через source
|
||||
|
||||
### Требования
|
||||
Выполнены все требования задачи:
|
||||
- ✓ 8.1 - Добавлен select_related() для всех связанных моделей
|
||||
- ✓ 8.2 - Добавлен prefetch_related() для mirrors
|
||||
- ✓ 8.3 - Добавлен prefetch_related() для marks
|
||||
- ✓ 8.4 - Проверено количество запросов до и после оптимизации
|
||||
- ✓ 8.6 - Оптимизация работает корректно
|
||||
|
||||
### Файлы изменены
|
||||
- `dbapp/mainapp/views/objitem.py` - добавлены оптимизации запросов
|
||||
|
||||
### Тестовые файлы
|
||||
- `test_objitem_final.py` - тест сравнения с baseline
|
||||
- `test_objitem_scale.py` - тест масштабируемости
|
||||
- `test_objitem_query_optimization.py` - базовый тест
|
||||
- `test_objitem_detailed_queries.py` - детальный тест
|
||||
|
||||
## Заключение
|
||||
|
||||
Оптимизация успешно выполнена. Количество запросов к базе данных сокращено с ~51 до 4 запросов (улучшение на 92.2%), и это количество остается постоянным независимо от количества отображаемых объектов. Это значительно улучшит производительность страницы списка объектов, особенно при большом количестве записей.
|
||||
106
QUICKSTART.md
106
QUICKSTART.md
@@ -1,106 +0,0 @@
|
||||
# Быстрый старт с Docker
|
||||
|
||||
## Development (разработка)
|
||||
|
||||
```bash
|
||||
# 1. Скопировать переменные окружения
|
||||
cp .env.dev .env
|
||||
|
||||
# 2. Запустить контейнеры
|
||||
make dev-up
|
||||
# или
|
||||
docker-compose up -d --build
|
||||
|
||||
# 3. Создать суперпользователя
|
||||
make createsuperuser
|
||||
# или
|
||||
docker-compose exec web python manage.py createsuperuser
|
||||
|
||||
# 4. Открыть в браузере
|
||||
# Django: http://localhost:8000
|
||||
# Admin: http://localhost:8000/admin
|
||||
# TileServer: http://localhost:8080
|
||||
```
|
||||
|
||||
## Production (продакшн)
|
||||
|
||||
```bash
|
||||
# 1. Скопировать и настроить переменные
|
||||
cp .env.prod .env
|
||||
nano .env # Измените SECRET_KEY, пароли, ALLOWED_HOSTS
|
||||
|
||||
# 2. Запустить контейнеры
|
||||
make prod-up
|
||||
# или
|
||||
docker-compose -f docker-compose.prod.yaml up -d --build
|
||||
|
||||
# 3. Создать суперпользователя
|
||||
make prod-createsuperuser
|
||||
# или
|
||||
docker-compose -f docker-compose.prod.yaml exec web python manage.py createsuperuser
|
||||
|
||||
# 4. Открыть в браузере
|
||||
# Nginx: http://localhost
|
||||
# Django: http://localhost:8000
|
||||
# TileServer: http://localhost:8080
|
||||
```
|
||||
|
||||
## Полезные команды
|
||||
|
||||
```bash
|
||||
# Просмотр логов
|
||||
make dev-logs # development
|
||||
make prod-logs # production
|
||||
|
||||
# Остановка
|
||||
make dev-down # development
|
||||
make prod-down # production
|
||||
|
||||
# Перезапуск после изменений
|
||||
make dev-build # development
|
||||
make prod-build # production
|
||||
|
||||
# Django shell
|
||||
make shell # development
|
||||
make prod-shell # production
|
||||
|
||||
# Миграции
|
||||
make migrate # development
|
||||
make prod-migrate # production
|
||||
|
||||
# Backup БД
|
||||
make backup
|
||||
|
||||
# Статус контейнеров
|
||||
make status # development
|
||||
make prod-status # production
|
||||
```
|
||||
|
||||
## Структура проекта
|
||||
|
||||
```
|
||||
.
|
||||
├── dbapp/ # Django приложение
|
||||
│ ├── Dockerfile # Универсальный Dockerfile
|
||||
│ ├── entrypoint.sh # Скрипт запуска
|
||||
│ ├── manage.py
|
||||
│ └── ...
|
||||
├── nginx/ # Nginx (только prod)
|
||||
│ └── conf.d/
|
||||
│ └── default.conf
|
||||
├── tiles/ # Тайлы для TileServer GL
|
||||
│ ├── README.md
|
||||
│ └── config.json.example
|
||||
├── docker-compose.yaml # Development
|
||||
├── docker-compose.prod.yaml # Production
|
||||
├── .env.dev # Переменные dev
|
||||
├── .env.prod # Переменные prod
|
||||
├── Makefile # Команды для удобства
|
||||
└── DOCKER_README.md # Подробная документация
|
||||
```
|
||||
|
||||
## Что дальше?
|
||||
|
||||
1. Прочитайте [DOCKER_README.md](DOCKER_README.md) для подробной информации
|
||||
2. Настройте TileServer GL - см. [tiles/README.md](tiles/README.md)
|
||||
3. Для production настройте SSL сертификаты в `nginx/ssl/`
|
||||
@@ -1,117 +0,0 @@
|
||||
# Быстрый старт: Асинхронное заполнение данных Lyngsat
|
||||
|
||||
## Минимальная настройка (5 минут)
|
||||
|
||||
### 1. Установите зависимости
|
||||
```bash
|
||||
pip install -r dbapp/requirements.txt
|
||||
```
|
||||
|
||||
### 2. Примените миграции
|
||||
```bash
|
||||
cd dbapp
|
||||
python manage.py migrate
|
||||
```
|
||||
|
||||
### 3. Запустите необходимые сервисы
|
||||
|
||||
**Терминал 1 - Redis и FlareSolver:**
|
||||
```bash
|
||||
docker-compose up -d redis flaresolverr
|
||||
```
|
||||
|
||||
**Терминал 2 - Django:**
|
||||
```bash
|
||||
cd dbapp
|
||||
python manage.py runserver
|
||||
```
|
||||
|
||||
**Терминал 3 - Celery Worker:**
|
||||
```bash
|
||||
cd dbapp
|
||||
celery -A dbapp worker --loglevel=info
|
||||
```
|
||||
|
||||
### 4. Используйте систему
|
||||
|
||||
1. Откройте браузер: `http://localhost:8000/actions/`
|
||||
2. Нажмите "Заполнить данные Lyngsat"
|
||||
3. Выберите 1-2 спутника для теста
|
||||
4. Выберите регион (например, Europe)
|
||||
5. Нажмите "Заполнить данные"
|
||||
6. Наблюдайте за прогрессом в реальном времени!
|
||||
|
||||
## Проверка работоспособности
|
||||
|
||||
### Redis
|
||||
```bash
|
||||
redis-cli ping
|
||||
# Должно вернуть: PONG
|
||||
```
|
||||
|
||||
### FlareSolver
|
||||
```bash
|
||||
curl http://localhost:8191/v1
|
||||
# Должно вернуть JSON с информацией о сервисе
|
||||
```
|
||||
|
||||
### Celery Worker
|
||||
Проверьте вывод в терминале 3 - должны быть сообщения:
|
||||
```
|
||||
[2024-01-15 10:30:00,000: INFO/MainProcess] Connected to redis://localhost:6379/0
|
||||
[2024-01-15 10:30:00,000: INFO/MainProcess] celery@hostname ready.
|
||||
```
|
||||
|
||||
## Остановка сервисов
|
||||
|
||||
```bash
|
||||
# Остановить Docker контейнеры
|
||||
docker-compose down
|
||||
|
||||
# Остановить Django (Ctrl+C в терминале 2)
|
||||
|
||||
# Остановить Celery Worker (Ctrl+C в терминале 3)
|
||||
```
|
||||
|
||||
## Просмотр логов
|
||||
|
||||
```bash
|
||||
# Логи Celery Worker (если запущен с --logfile)
|
||||
tail -f dbapp/logs/celery_worker.log
|
||||
|
||||
# Логи Docker контейнеров
|
||||
docker-compose logs -f redis
|
||||
docker-compose logs -f flaresolverr
|
||||
```
|
||||
|
||||
## Что дальше?
|
||||
|
||||
- Прочитайте полную документацию: `ASYNC_LYNGSAT_GUIDE.md`
|
||||
- Настройте production окружение
|
||||
- Добавьте периодические задачи
|
||||
- Настройте email уведомления
|
||||
|
||||
## Решение проблем
|
||||
|
||||
**Worker не запускается:**
|
||||
```bash
|
||||
# Проверьте Redis
|
||||
redis-cli ping
|
||||
|
||||
# Проверьте переменные окружения
|
||||
echo $CELERY_BROKER_URL
|
||||
```
|
||||
|
||||
**Задача не выполняется:**
|
||||
```bash
|
||||
# Проверьте FlareSolver
|
||||
curl http://localhost:8191/v1
|
||||
|
||||
# Проверьте логи worker
|
||||
tail -f dbapp/logs/celery_worker.log
|
||||
```
|
||||
|
||||
**Прогресс не обновляется:**
|
||||
- Откройте консоль браузера (F12)
|
||||
- Проверьте Network tab на наличие ошибок
|
||||
- Обновите страницу
|
||||
@@ -1,135 +0,0 @@
|
||||
# Task 28 Completion Summary: Optimize SourceListView Queries
|
||||
|
||||
## ✅ Task Status: COMPLETED
|
||||
|
||||
## Objective
|
||||
Optimize SQL queries in SourceListView to eliminate N+1 query problems and improve performance by using Django ORM optimization techniques.
|
||||
|
||||
## What Was Done
|
||||
|
||||
### 1. Added select_related() for ForeignKey/OneToOne Relationships
|
||||
Enhanced the queryset to fetch related objects using SQL JOINs:
|
||||
- `info` (ForeignKey to ObjectInfo)
|
||||
- `created_by` and `created_by__user` (ForeignKey to CustomUser → User)
|
||||
- `updated_by` and `updated_by__user` (ForeignKey to CustomUser → User)
|
||||
|
||||
### 2. Added prefetch_related() for Reverse ForeignKey and ManyToMany
|
||||
Implemented comprehensive prefetching for all related collections:
|
||||
- All `source_objitems` with nested relationships:
|
||||
- `parameter_obj` and its related fields (satellite, polarization, modulation, standard)
|
||||
- `geo_obj` and its mirrors (ManyToMany)
|
||||
- `lyngsat_source` and its satellite
|
||||
- `transponder`
|
||||
- `created_by` and `updated_by` with their users
|
||||
- All `marks` with their `created_by` relationships
|
||||
|
||||
### 3. Used annotate() for Efficient Counting
|
||||
Implemented database-level counting using `Count()` aggregation:
|
||||
- Counts `objitem_count` in the database using GROUP BY
|
||||
- Supports filtered counting when filters are applied
|
||||
- Eliminates need for Python-level counting loops
|
||||
|
||||
## Results
|
||||
|
||||
### Query Performance
|
||||
- **Total queries**: 22 (constant)
|
||||
- **Scaling**: Perfect - query count remains at 22 regardless of page size
|
||||
- **Status**: ✅ EXCELLENT
|
||||
|
||||
### Test Results
|
||||
| Page Size | Query Count | Variation |
|
||||
|-----------|-------------|-----------|
|
||||
| 10 items | 22 queries | 0 |
|
||||
| 50 items | 22 queries | 0 |
|
||||
| 100 items | 22 queries | 0 |
|
||||
|
||||
### Performance Improvement
|
||||
- **Before**: ~100-1000+ queries (N+1 problem, scales with items)
|
||||
- **After**: 22 queries (constant, no scaling)
|
||||
- **Improvement**: 95-98% reduction in query count
|
||||
|
||||
## Requirements Compliance
|
||||
|
||||
✅ **Requirement 8.1**: Minimize SQL queries to database
|
||||
✅ **Requirement 8.2**: Use select_related() for ForeignKey/OneToOne
|
||||
✅ **Requirement 8.3**: Use prefetch_related() for ManyToMany and reverse ForeignKey
|
||||
✅ **Requirement 8.4**: Use annotate() instead of multiple queries in loops
|
||||
✅ **Requirement 8.6**: Reduce query count by at least 50% (achieved 95-98%)
|
||||
|
||||
## Files Modified
|
||||
|
||||
### Production Code
|
||||
- `dbapp/mainapp/views/source.py`: Updated SourceListView.get() method with optimized queryset
|
||||
|
||||
### Test Files Created
|
||||
- `test_source_query_optimization.py`: Basic query count verification
|
||||
- `test_source_query_detailed.py`: Detailed query analysis with SQL output
|
||||
- `test_source_query_scale.py`: Scaling test across different page sizes
|
||||
|
||||
### Documentation
|
||||
- `OPTIMIZATION_REPORT_SourceListView.md`: Comprehensive optimization report
|
||||
- `TASK_28_COMPLETION_SUMMARY.md`: This summary document
|
||||
|
||||
## Verification
|
||||
|
||||
All optimizations have been verified through automated testing:
|
||||
|
||||
1. ✅ Query count is stable at 22 regardless of page size
|
||||
2. ✅ No N+1 query problems detected
|
||||
3. ✅ All relationships properly optimized with select_related/prefetch_related
|
||||
4. ✅ Counting uses database-level aggregation
|
||||
|
||||
## Code Changes
|
||||
|
||||
The main optimization in `dbapp/mainapp/views/source.py`:
|
||||
|
||||
```python
|
||||
sources = Source.objects.select_related(
|
||||
'info',
|
||||
'created_by',
|
||||
'created_by__user',
|
||||
'updated_by',
|
||||
'updated_by__user',
|
||||
).prefetch_related(
|
||||
'source_objitems',
|
||||
'source_objitems__parameter_obj',
|
||||
'source_objitems__parameter_obj__id_satellite',
|
||||
'source_objitems__parameter_obj__polarization',
|
||||
'source_objitems__parameter_obj__modulation',
|
||||
'source_objitems__parameter_obj__standard',
|
||||
'source_objitems__geo_obj',
|
||||
'source_objitems__geo_obj__mirrors',
|
||||
'source_objitems__lyngsat_source',
|
||||
'source_objitems__lyngsat_source__satellite',
|
||||
'source_objitems__transponder',
|
||||
'source_objitems__created_by',
|
||||
'source_objitems__created_by__user',
|
||||
'source_objitems__updated_by',
|
||||
'source_objitems__updated_by__user',
|
||||
'marks',
|
||||
'marks__created_by',
|
||||
'marks__created_by__user'
|
||||
).annotate(
|
||||
objitem_count=Count('source_objitems', filter=objitem_filter_q, distinct=True)
|
||||
if has_objitem_filter
|
||||
else Count('source_objitems')
|
||||
)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
This optimization pattern should be applied to other list views:
|
||||
- Task 29: ObjItemListView
|
||||
- Task 30: TransponderListView
|
||||
- Task 31: LyngsatListView
|
||||
- Task 32: ObjectMarksListView
|
||||
|
||||
## Conclusion
|
||||
|
||||
Task 28 has been successfully completed with excellent results. The SourceListView now uses optimal Django ORM patterns to minimize database queries, resulting in a 95-98% reduction in query count and eliminating all N+1 query problems.
|
||||
|
||||
---
|
||||
|
||||
**Completed**: 2025-11-18
|
||||
**Developer**: Kiro AI Assistant
|
||||
**Status**: ✅ VERIFIED AND COMPLETE
|
||||
@@ -44,8 +44,8 @@ COPY --from=builder /app /app
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PATH="/usr/local/bin:$PATH"
|
||||
|
||||
# Делаем entrypoint.sh исполняемым
|
||||
RUN chmod +x /app/entrypoint.sh
|
||||
# Делаем entrypoint скрипты исполняемыми
|
||||
RUN chmod +x /app/entrypoint.sh /app/entrypoint-celery.sh
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
# Страница Кубсат
|
||||
|
||||
## Описание
|
||||
Страница "Кубсат" предназначена для фильтрации источников сигнала (Source) по различным критериям и экспорта результатов в Excel.
|
||||
|
||||
## Доступ
|
||||
Страница доступна по адресу: `/kubsat/`
|
||||
Также добавлена в навигационное меню между "Наличие сигнала" и "3D карта".
|
||||
|
||||
## Функциональность
|
||||
|
||||
### Фильтры
|
||||
|
||||
#### Реализованные фильтры:
|
||||
1. **Спутники** (мультивыбор) - фильтрация по спутникам из связанных ObjItem
|
||||
2. **Полоса спутника** (выбор) - выбор диапазона частот
|
||||
3. **Поляризация** (мультивыбор) - фильтрация по поляризации сигнала
|
||||
4. **Центральная частота** (диапазон) - фильтрация по частоте от/до в МГц
|
||||
5. **Полоса** (диапазон) - фильтрация по полосе частот от/до в МГц
|
||||
6. **Модуляция** (мультивыбор) - фильтрация по типу модуляции
|
||||
7. **Тип объекта** (мультивыбор) - фильтрация по типу объекта (ObjectInfo)
|
||||
8. **Количество привязанных ObjItem** (radio button):
|
||||
- Все
|
||||
- 1
|
||||
- 2 и более
|
||||
|
||||
#### Фиктивные фильтры (заглушки):
|
||||
9. **Принадлежность объекта** (мультивыбор) - пока не реализовано
|
||||
10. **Планы на** (radio да/нет) - фиктивный фильтр
|
||||
11. **Успех 1** (radio да/нет) - фиктивный фильтр
|
||||
12. **Успех 2** (radio да/нет) - фиктивный фильтр
|
||||
13. **Диапазон дат** (от/до) - фиктивный фильтр
|
||||
|
||||
### Таблица результатов
|
||||
|
||||
После применения фильтров отображается таблица на всю ширину страницы с колонками:
|
||||
- ID Source - идентификатор источника (объединяет несколько точек)
|
||||
- Тип объекта - тип источника
|
||||
- Кол-во точек - количество точек источника (автоматически пересчитывается при удалении)
|
||||
- Имя точки - название точки (ObjItem)
|
||||
- Спутник (имя и NORAD ID)
|
||||
- Частота (МГц)
|
||||
- Полоса (МГц)
|
||||
- Поляризация
|
||||
- Модуляция
|
||||
- Координаты ГЛ - координаты из geo_obj точки
|
||||
- Дата ГЛ - дата геолокации точки
|
||||
- Действия (кнопки удаления)
|
||||
|
||||
**Важно**:
|
||||
- Таблица показывает все точки (ObjItem) для каждого источника (Source)
|
||||
- Точки одного источника группируются вместе
|
||||
- Колонки ID Source, Тип объекта и Кол-во точек объединены для всех строк источника (rowspan)
|
||||
- Количество точек автоматически пересчитывается при удалении строк
|
||||
- Таблица имеет фиксированную высоту с прокруткой и sticky заголовок
|
||||
|
||||
### Двухэтапная фильтрация
|
||||
|
||||
Фильтрация происходит в два этапа:
|
||||
|
||||
**Этап 1: Фильтрация по дате ГЛ**
|
||||
- Если задан диапазон дат (от/до), отображаются только те точки, у которых дата ГЛ попадает в этот диапазон
|
||||
- Точки без даты ГЛ исключаются, если фильтр по дате задан
|
||||
- Если фильтр не задан, показываются все точки
|
||||
|
||||
**Этап 2: Фильтрация по количеству точек**
|
||||
- Применяется к уже отфильтрованным по дате точкам
|
||||
- Варианты:
|
||||
- "Все" - показываются источники с любым количеством точек
|
||||
- "1" - только источники с ровно 1 точкой (после фильтрации по дате)
|
||||
- "2 и более" - только источники с 2 и более точками (после фильтрации по дате)
|
||||
|
||||
**Важно**: Фильтр по количеству точек учитывает только те точки, которые прошли фильтрацию по дате!
|
||||
|
||||
### Управление данными в таблице
|
||||
|
||||
**Кнопки удаления:**
|
||||
- **Кнопка с иконкой корзины** (для каждой точки) - удаляет конкретную точку (ObjItem) из таблицы
|
||||
- **Кнопка с иконкой заполненной корзины** (для первой точки источника) - удаляет все точки источника (Source) из таблицы
|
||||
|
||||
|
||||
|
||||
**Важно**: Все удаления происходят только из таблицы, **БЕЗ удаления из базы данных**. Это позволяет пользователю исключить ненужные записи перед экспортом.
|
||||
|
||||
### Экспорт в Excel
|
||||
|
||||
Кнопка "Экспорт в Excel" создает файл со следующими колонками:
|
||||
1. **Дата** - текущая дата (без времени)
|
||||
2. **Широта, град** - рассчитывается как **инкрементальное среднее** из координат оставшихся в таблице точек
|
||||
3. **Долгота, град** - рассчитывается как **инкрементальное среднее** из координат оставшихся в таблице точек
|
||||
4. **Высота, м** - всегда 0
|
||||
5. **Местоположение** - из geo_obj.location первого ObjItem
|
||||
6. **ИСЗ** - имя спутника и NORAD ID в скобках
|
||||
7. **Прямой канал, МГц** - частота + перенос из транспондера
|
||||
8. **Обратный канал, МГц** - частота источника
|
||||
9. **Перенос** - из объекта Transponder
|
||||
10. **Получено координат, раз** - количество точек (ObjItem), оставшихся в таблице для данного источника
|
||||
11. **Период получения координат** - диапазон дат ГЛ в формате "5.11.2025-15.11.2025" (от самой ранней до самой поздней даты среди точек источника). Если все точки имеют одну дату, показывается только одна дата.
|
||||
12. **Зеркала** - все имена зеркал через перенос строки (из оставшихся точек)
|
||||
13. **СКО, км** - не заполняется
|
||||
14. **Примечание** - не заполняется
|
||||
15. **Оператор** - имя текущего пользователя
|
||||
|
||||
**Важно**:
|
||||
- Экспортируются только точки (ObjItem), оставшиеся в таблице после удалений
|
||||
- Координаты рассчитываются по алгоритму инкрементального среднего из функции `calculate_mean_coords` (аналогично `fill_data_from_df`)
|
||||
- Если пользователь удалил некоторые точки, координаты будут рассчитаны только по оставшимся
|
||||
|
||||
Файл сохраняется с именем `kubsat_YYYYMMDD_HHMMSS.xlsx`.
|
||||
|
||||
## Технические детали
|
||||
|
||||
### Файлы
|
||||
- **Форма**: `dbapp/mainapp/forms.py` - класс `KubsatFilterForm`
|
||||
- **Представления**: `dbapp/mainapp/views/kubsat.py` - классы `KubsatView` и `KubsatExportView`
|
||||
- **Шаблон**: `dbapp/mainapp/templates/mainapp/kubsat.html`
|
||||
- **URL**: `/kubsat/` и `/kubsat/export/`
|
||||
|
||||
### Зависимости
|
||||
- openpyxl - для создания Excel файлов
|
||||
- Django GIS - для работы с координатами
|
||||
|
||||
### Оптимизация запросов
|
||||
Используется `select_related` и `prefetch_related` для минимизации количества запросов к базе данных:
|
||||
```python
|
||||
queryset = Source.objects.select_related('info').prefetch_related(
|
||||
'source_objitems__parameter_obj__id_satellite',
|
||||
'source_objitems__parameter_obj__polarization',
|
||||
'source_objitems__parameter_obj__modulation',
|
||||
'source_objitems__transponder__sat_id'
|
||||
)
|
||||
```
|
||||
|
||||
## Использование
|
||||
|
||||
1. Откройте страницу "Кубсат" из навигационного меню
|
||||
2. Выберите нужные фильтры (спутники, поляризация, частота и т.д.)
|
||||
3. Опционально укажите диапазон дат для фильтрации точек по дате ГЛ (Этап 1)
|
||||
4. Опционально выберите количество точек (1 или 2+) - применяется к отфильтрованным по дате точкам (Этап 2)
|
||||
5. Нажмите "Применить фильтры"
|
||||
6. В таблице отобразятся точки (ObjItem) сгруппированные по источникам (Source)
|
||||
7. При необходимости удалите отдельные точки или целые объекты кнопками в колонке "Действия"
|
||||
8. Нажмите "Экспорт в Excel" для скачивания файла с оставшимися данными
|
||||
9. Форма не сбрасывается после экспорта - можно продолжить работу
|
||||
|
||||
## Примечания
|
||||
|
||||
- Форма не сбрасывается после экспорта
|
||||
- Удаление точек/объектов из таблицы не влияет на базу данных
|
||||
- Экспортируются только оставшиеся в таблице точки
|
||||
- Координаты в Excel рассчитываются как инкрементальное среднее из оставшихся точек
|
||||
- Фильтр по дате скрывает неподходящие точки (не показывает их в таблице)
|
||||
- Каждая строка таблицы = одна точка (ObjItem), строки группируются по источникам (Source)
|
||||
- Количество точек в колонке "Кол-во точек" автоматически пересчитывается при удалении строк
|
||||
96
dbapp/check_redis.py
Normal file
96
dbapp/check_redis.py
Normal file
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
Скрипт для проверки подключения к Redis.
|
||||
Запуск: python check_redis.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
import redis
|
||||
except ImportError:
|
||||
print("❌ Redis библиотека не установлена")
|
||||
print("Установите: pip install redis")
|
||||
sys.exit(1)
|
||||
|
||||
def check_redis():
|
||||
"""Проверка подключения к Redis"""
|
||||
print("=" * 60)
|
||||
print("ПРОВЕРКА REDIS")
|
||||
print("=" * 60)
|
||||
|
||||
# Получаем URL из переменных окружения
|
||||
broker_url = os.getenv("CELERY_BROKER_URL", "redis://localhost:6379/0")
|
||||
cache_url = os.getenv("REDIS_URL", "redis://localhost:6379/1")
|
||||
|
||||
print(f"\n1. Broker URL: {broker_url}")
|
||||
print(f"2. Cache URL: {cache_url}")
|
||||
|
||||
# Проверка broker (database 0)
|
||||
print("\n3. Проверка Celery Broker (db 0)...")
|
||||
try:
|
||||
r_broker = redis.from_url(broker_url)
|
||||
r_broker.ping()
|
||||
print(" ✓ Подключение успешно")
|
||||
|
||||
# Проверка ключей
|
||||
keys = r_broker.keys("*")
|
||||
print(f" ✓ Ключей в базе: {len(keys)}")
|
||||
|
||||
# Проверка очереди celery
|
||||
queue_length = r_broker.llen("celery")
|
||||
print(f" ✓ Задач в очереди 'celery': {queue_length}")
|
||||
|
||||
except redis.ConnectionError as e:
|
||||
print(f" ✗ Ошибка подключения: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f" ✗ Ошибка: {e}")
|
||||
return False
|
||||
|
||||
# Проверка cache (database 1)
|
||||
print("\n4. Проверка Django Cache (db 1)...")
|
||||
try:
|
||||
r_cache = redis.from_url(cache_url)
|
||||
r_cache.ping()
|
||||
print(" ✓ Подключение успешно")
|
||||
|
||||
# Проверка ключей
|
||||
keys = r_cache.keys("*")
|
||||
print(f" ✓ Ключей в базе: {len(keys)}")
|
||||
|
||||
except redis.ConnectionError as e:
|
||||
print(f" ✗ Ошибка подключения: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f" ✗ Ошибка: {e}")
|
||||
return False
|
||||
|
||||
# Тест записи/чтения
|
||||
print("\n5. Тест записи/чтения...")
|
||||
try:
|
||||
test_key = "test:celery:connection"
|
||||
test_value = "OK"
|
||||
|
||||
r_broker.set(test_key, test_value, ex=10) # TTL 10 секунд
|
||||
result = r_broker.get(test_key)
|
||||
|
||||
if result and result.decode() == test_value:
|
||||
print(f" ✓ Запись/чтение работает")
|
||||
r_broker.delete(test_key)
|
||||
else:
|
||||
print(f" ✗ Ошибка: ожидалось '{test_value}', получено '{result}'")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f" ✗ Ошибка: {e}")
|
||||
return False
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✓ ВСЕ ПРОВЕРКИ ПРОЙДЕНЫ")
|
||||
print("=" * 60)
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = check_redis()
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -4,18 +4,12 @@ Celery configuration for dbapp project.
|
||||
import os
|
||||
from celery import Celery
|
||||
|
||||
# Use the environment variable to determine the settings module
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', os.getenv('DJANGO_SETTINGS_MODULE', 'dbapp.settings.development'))
|
||||
|
||||
app = Celery('dbapp')
|
||||
|
||||
# Using a string here means the worker doesn't have to serialize
|
||||
# the configuration object to child processes.
|
||||
# - namespace='CELERY' means all celery-related configuration keys
|
||||
# should have a `CELERY_` prefix.
|
||||
app.config_from_object('django.conf:settings', namespace='CELERY')
|
||||
|
||||
# Load task modules from all registered Django apps.
|
||||
app.autodiscover_tasks()
|
||||
|
||||
|
||||
|
||||
@@ -197,6 +197,8 @@ STATICFILES_DIRS = [
|
||||
# Default primary key field type
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
|
||||
FLARESOLVERR_URL = os.getenv("FLARESOLVERR_URL", "http://flaresolverr:8191/v1")
|
||||
|
||||
# ============================================================================
|
||||
# THIRD-PARTY APP CONFIGURATION
|
||||
# ============================================================================
|
||||
|
||||
@@ -57,7 +57,7 @@ TEMPLATES = [
|
||||
"DIRS": [
|
||||
BASE_DIR / "templates",
|
||||
],
|
||||
"APP_DIRS": False, # Must be False when using custom loaders
|
||||
"APP_DIRS": False,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.debug",
|
||||
@@ -88,6 +88,13 @@ STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesSto
|
||||
# ============================================================================
|
||||
# LOGGING CONFIGURATION
|
||||
# ============================================================================
|
||||
LOGS_DIR = BASE_DIR.parent / "logs"
|
||||
LOGS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ============================================================================
|
||||
# CELERY LOGGING CONFIGURATION
|
||||
# ============================================================================
|
||||
CELERY_WORKER_HIJACK_ROOT_LOGGER = False
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
@@ -116,7 +123,13 @@ LOGGING = {
|
||||
"file": {
|
||||
"level": "ERROR",
|
||||
"class": "logging.FileHandler",
|
||||
"filename": BASE_DIR.parent / "logs" / "django_errors.log",
|
||||
"filename": LOGS_DIR / "django_errors.log",
|
||||
"formatter": "verbose",
|
||||
},
|
||||
"celery_file": {
|
||||
"level": "INFO",
|
||||
"class": "logging.FileHandler",
|
||||
"filename": LOGS_DIR / "celery.log",
|
||||
"formatter": "verbose",
|
||||
},
|
||||
"mail_admins": {
|
||||
@@ -137,5 +150,24 @@ LOGGING = {
|
||||
"level": "ERROR",
|
||||
"propagate": False,
|
||||
},
|
||||
"celery": {
|
||||
"handlers": ["console", "celery_file"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
},
|
||||
"celery.task": {
|
||||
"handlers": ["console", "celery_file"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
},
|
||||
"celery.worker": {
|
||||
"handlers": ["console", "celery_file"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
# Force Celery to log to stdout for Docker
|
||||
CELERY_WORKER_REDIRECT_STDOUTS = True
|
||||
CELERY_WORKER_REDIRECT_STDOUTS_LEVEL = "INFO"
|
||||
|
||||
26
dbapp/entrypoint-celery.sh
Normal file
26
dbapp/entrypoint-celery.sh
Normal file
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "Starting Celery Worker..."
|
||||
|
||||
# Ждем PostgreSQL
|
||||
echo "Waiting for PostgreSQL..."
|
||||
until PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -c '\q' 2>/dev/null; do
|
||||
echo "PostgreSQL is unavailable - sleeping"
|
||||
sleep 1
|
||||
done
|
||||
echo "PostgreSQL started"
|
||||
|
||||
# Ждем Redis (проверяем через Python, т.к. redis-cli не установлен)
|
||||
echo "Waiting for Redis..."
|
||||
until uv run python -c "import redis; r = redis.from_url('${CELERY_BROKER_URL}'); r.ping()" 2>/dev/null; do
|
||||
echo "Redis is unavailable - sleeping"
|
||||
sleep 1
|
||||
done
|
||||
echo "Redis started"
|
||||
|
||||
# Создаем директорию для логов
|
||||
mkdir -p /app/logs
|
||||
|
||||
# Запускаем команду (celery worker или beat)
|
||||
exec "$@"
|
||||
@@ -6,7 +6,13 @@ ENVIRONMENT=${ENVIRONMENT:-production}
|
||||
|
||||
echo "Starting in $ENVIRONMENT mode..."
|
||||
|
||||
# Ждем PostgreSQL
|
||||
if [ -d "logs" ]; then
|
||||
echo "Directory logs already exists."
|
||||
else
|
||||
echo "Creating logs directory..."
|
||||
mkdir -p logs
|
||||
fi
|
||||
|
||||
echo "Waiting for PostgreSQL..."
|
||||
until PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -c '\q' 2>/dev/null; do
|
||||
echo "PostgreSQL is unavailable - sleeping"
|
||||
@@ -14,17 +20,14 @@ until PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -c
|
||||
done
|
||||
echo "PostgreSQL started"
|
||||
|
||||
# Выполняем миграции
|
||||
echo "Running migrations..."
|
||||
uv run python manage.py migrate --noinput
|
||||
|
||||
# Собираем статику (только для production)
|
||||
if [ "$ENVIRONMENT" = "production" ]; then
|
||||
echo "Collecting static files..."
|
||||
uv run python manage.py collectstatic --noinput
|
||||
fi
|
||||
|
||||
# Запускаем сервер в зависимости от окружения
|
||||
if [ "$ENVIRONMENT" = "development" ]; then
|
||||
echo "Starting Django development server..."
|
||||
exec uv run python manage.py runserver 0.0.0.0:8000
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Callable, Optional
|
||||
from .async_parser import AsyncLyngSatParser
|
||||
from .models import LyngSat
|
||||
from mainapp.models import Polarization, Standard, Modulation, Satellite
|
||||
from dbapp.settings.base import FLARESOLVERR_URL
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -53,9 +54,13 @@ def process_single_satellite(
|
||||
|
||||
logger.info(f"Найдено {len(sources)} источников для {sat_name}")
|
||||
|
||||
# Находим спутник в базе
|
||||
# Находим спутник в базе по имени или альтернативному имени (lowercase)
|
||||
from django.db.models import Q
|
||||
sat_name_lower = sat_name.lower()
|
||||
try:
|
||||
sat_obj = Satellite.objects.get(name__icontains=sat_name)
|
||||
sat_obj = Satellite.objects.get(
|
||||
Q(name__icontains=sat_name_lower) | Q(alternative_name__icontains=sat_name_lower)
|
||||
)
|
||||
logger.debug(f"Спутник {sat_name} найден в базе (ID: {sat_obj.id})")
|
||||
except Satellite.DoesNotExist:
|
||||
error_msg = f"Спутник '{sat_name}' не найден в базе данных"
|
||||
@@ -185,7 +190,7 @@ def fill_lyngsat_data_async(
|
||||
try:
|
||||
# Создаем парсер
|
||||
parser = AsyncLyngSatParser(
|
||||
flaresolver_url="http://localhost:8191/v1",
|
||||
flaresolver_url=FLARESOLVERR_URL,
|
||||
target_sats=target_sats,
|
||||
regions=regions,
|
||||
use_cache=use_cache
|
||||
|
||||
@@ -2,6 +2,7 @@ import logging
|
||||
from .parser import LyngSatParser
|
||||
from .models import LyngSat
|
||||
from mainapp.models import Polarization, Standard, Modulation, Satellite
|
||||
from dbapp.settings.base import FLARESOLVERR_URL
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -50,7 +51,7 @@ def fill_lyngsat_data(
|
||||
|
||||
try:
|
||||
parser = LyngSatParser(
|
||||
flaresolver_url="http://localhost:8191/v1",
|
||||
flaresolver_url=FLARESOLVERR_URL,
|
||||
target_sats=target_sats,
|
||||
regions=regions
|
||||
)
|
||||
@@ -76,9 +77,13 @@ def fill_lyngsat_data(
|
||||
|
||||
logger.info(f"{log_prefix} Найдено {len(sources)} источников для {sat_name}")
|
||||
|
||||
# Находим спутник в базе
|
||||
# Находим спутник в базе по имени или альтернативному имени (lowercase)
|
||||
from django.db.models import Q
|
||||
sat_name_lower = sat_name.lower()
|
||||
try:
|
||||
sat_obj = Satellite.objects.get(name__icontains=sat_name)
|
||||
sat_obj = Satellite.objects.get(
|
||||
Q(name__icontains=sat_name_lower) | Q(alternative_name__icontains=sat_name_lower)
|
||||
)
|
||||
logger.debug(f"{log_prefix} Спутник {sat_name} найден в базе (ID: {sat_obj.id})")
|
||||
except Satellite.DoesNotExist:
|
||||
error_msg = f"Спутник '{sat_name}' не найден в базе данных"
|
||||
|
||||
@@ -23,19 +23,20 @@ from .models import (
|
||||
Polarization,
|
||||
Modulation,
|
||||
Standard,
|
||||
SigmaParMark,
|
||||
ObjectMark,
|
||||
ObjectInfo,
|
||||
ObjectOwnership,
|
||||
SigmaParameter,
|
||||
Parameter,
|
||||
Satellite,
|
||||
Mirror,
|
||||
Geo,
|
||||
ObjItem,
|
||||
CustomUser,
|
||||
Band,
|
||||
Source,
|
||||
TechAnalyze,
|
||||
SourceRequest,
|
||||
SourceRequestStatusHistory,
|
||||
)
|
||||
from .filters import (
|
||||
GeoKupDistanceFilter,
|
||||
@@ -346,27 +347,28 @@ class ParameterInline(admin.StackedInline):
|
||||
class ObjectMarkAdmin(BaseAdmin):
|
||||
"""Админ-панель для модели ObjectMark."""
|
||||
|
||||
list_display = ("source", "mark", "timestamp", "created_by")
|
||||
list_select_related = ("source", "created_by__user")
|
||||
search_fields = ("source__id",)
|
||||
list_display = ("id", "tech_analyze", "mark", "timestamp", "created_by")
|
||||
list_display_links = ("id",)
|
||||
list_select_related = ("tech_analyze", "tech_analyze__satellite", "created_by__user")
|
||||
list_editable = ("tech_analyze", "mark", "timestamp")
|
||||
search_fields = ("tech_analyze__name", "tech_analyze__id")
|
||||
ordering = ("-timestamp",)
|
||||
list_filter = (
|
||||
"mark",
|
||||
("timestamp", DateRangeQuickSelectListFilterBuilder()),
|
||||
("source", MultiSelectRelatedDropdownFilter),
|
||||
("tech_analyze__satellite", MultiSelectRelatedDropdownFilter),
|
||||
)
|
||||
readonly_fields = ("timestamp", "created_by")
|
||||
autocomplete_fields = ("source",)
|
||||
autocomplete_fields = ("tech_analyze",)
|
||||
|
||||
|
||||
@admin.register(SigmaParMark)
|
||||
class SigmaParMarkAdmin(BaseAdmin):
|
||||
"""Админ-панель для модели SigmaParMark."""
|
||||
# @admin.register(SigmaParMark)
|
||||
# class SigmaParMarkAdmin(BaseAdmin):
|
||||
# """Админ-панель для модели SigmaParMark."""
|
||||
|
||||
list_display = ("mark", "timestamp")
|
||||
search_fields = ("mark",)
|
||||
ordering = ("-timestamp",)
|
||||
list_filter = (("timestamp", DateRangeQuickSelectListFilterBuilder()),)
|
||||
# list_display = ("mark", "timestamp")
|
||||
# search_fields = ("mark",)
|
||||
# ordering = ("-timestamp",)
|
||||
# list_filter = (("timestamp", DateRangeQuickSelectListFilterBuilder()),)
|
||||
|
||||
|
||||
@admin.register(Polarization)
|
||||
@@ -417,7 +419,6 @@ class ObjectOwnershipAdmin(BaseAdmin):
|
||||
class SigmaParameterInline(admin.StackedInline):
|
||||
model = SigmaParameter
|
||||
extra = 0
|
||||
autocomplete_fields = ["mark"]
|
||||
readonly_fields = (
|
||||
"datetime_begin",
|
||||
"datetime_end",
|
||||
@@ -561,7 +562,6 @@ class SigmaParameterAdmin(ImportExportActionModelAdmin, BaseAdmin):
|
||||
"modulation__name",
|
||||
"standard__name",
|
||||
)
|
||||
autocomplete_fields = ("mark",)
|
||||
ordering = ("-frequency",)
|
||||
|
||||
def get_queryset(self, request):
|
||||
@@ -576,26 +576,28 @@ class SatelliteAdmin(BaseAdmin):
|
||||
|
||||
list_display = (
|
||||
"name",
|
||||
"alternative_name",
|
||||
"norad",
|
||||
"international_code",
|
||||
"undersat_point",
|
||||
"launch_date",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
)
|
||||
search_fields = ("name", "norad")
|
||||
search_fields = ("name", "alternative_name", "norad", "international_code")
|
||||
ordering = ("name",)
|
||||
filter_horizontal = ("band",)
|
||||
autocomplete_fields = ("band",)
|
||||
readonly_fields = ("created_at", "created_by", "updated_at", "updated_by")
|
||||
|
||||
|
||||
@admin.register(Mirror)
|
||||
class MirrorAdmin(ImportExportActionModelAdmin, BaseAdmin):
|
||||
"""Админ-панель для модели Mirror с поддержкой импорта/экспорта."""
|
||||
# @admin.register(Mirror)
|
||||
# class MirrorAdmin(ImportExportActionModelAdmin, BaseAdmin):
|
||||
# """Админ-панель для модели Mirror с поддержкой импорта/экспорта."""
|
||||
|
||||
list_display = ("name",)
|
||||
search_fields = ("name",)
|
||||
ordering = ("name",)
|
||||
# list_display = ("name",)
|
||||
# search_fields = ("name",)
|
||||
# ordering = ("name",)
|
||||
|
||||
|
||||
@admin.register(Geo)
|
||||
@@ -1087,3 +1089,197 @@ class SourceAdmin(ImportExportActionModelAdmin, LeafletGeoAdmin, BaseAdmin):
|
||||
)
|
||||
|
||||
autocomplete_fields = ("info",)
|
||||
|
||||
|
||||
@admin.register(TechAnalyze)
|
||||
class TechAnalyzeAdmin(ImportExportActionModelAdmin, BaseAdmin):
|
||||
"""Админ-панель для модели TechAnalyze."""
|
||||
|
||||
list_display = (
|
||||
"name",
|
||||
"satellite",
|
||||
"frequency",
|
||||
"freq_range",
|
||||
"polarization",
|
||||
"bod_velocity",
|
||||
"modulation",
|
||||
"standard",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
)
|
||||
list_display_links = ("name",)
|
||||
list_select_related = (
|
||||
"satellite",
|
||||
"polarization",
|
||||
"modulation",
|
||||
"standard",
|
||||
"created_by__user",
|
||||
"updated_by__user",
|
||||
)
|
||||
|
||||
list_filter = (
|
||||
("satellite", MultiSelectRelatedDropdownFilter),
|
||||
("polarization", MultiSelectRelatedDropdownFilter),
|
||||
("modulation", MultiSelectRelatedDropdownFilter),
|
||||
("standard", MultiSelectRelatedDropdownFilter),
|
||||
("frequency", NumericRangeFilterBuilder()),
|
||||
("freq_range", NumericRangeFilterBuilder()),
|
||||
("created_at", DateRangeQuickSelectListFilterBuilder()),
|
||||
("updated_at", DateRangeQuickSelectListFilterBuilder()),
|
||||
)
|
||||
|
||||
search_fields = (
|
||||
"name",
|
||||
"satellite__name",
|
||||
"frequency",
|
||||
"note",
|
||||
)
|
||||
|
||||
ordering = ("-created_at",)
|
||||
readonly_fields = ("created_at", "created_by", "updated_at", "updated_by")
|
||||
autocomplete_fields = ("satellite", "polarization", "modulation", "standard")
|
||||
|
||||
fieldsets = (
|
||||
(
|
||||
"Основная информация",
|
||||
{"fields": ("name", "satellite", "note")},
|
||||
),
|
||||
(
|
||||
"Технические параметры",
|
||||
{
|
||||
"fields": (
|
||||
"frequency",
|
||||
"freq_range",
|
||||
"polarization",
|
||||
"bod_velocity",
|
||||
"modulation",
|
||||
"standard",
|
||||
)
|
||||
},
|
||||
),
|
||||
(
|
||||
"Метаданные",
|
||||
{
|
||||
"fields": ("created_at", "created_by", "updated_at", "updated_by"),
|
||||
"classes": ("collapse",),
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class SourceRequestStatusHistoryInline(admin.TabularInline):
|
||||
"""Inline для отображения истории статусов заявки."""
|
||||
model = SourceRequestStatusHistory
|
||||
extra = 0
|
||||
readonly_fields = ('old_status', 'new_status', 'changed_at', 'changed_by')
|
||||
can_delete = False
|
||||
|
||||
def has_add_permission(self, request, obj=None):
|
||||
return False
|
||||
|
||||
|
||||
@admin.register(SourceRequest)
|
||||
class SourceRequestAdmin(BaseAdmin):
|
||||
"""Админ-панель для модели SourceRequest."""
|
||||
|
||||
list_display = (
|
||||
'id',
|
||||
'source',
|
||||
'status',
|
||||
'priority',
|
||||
'planned_at',
|
||||
'request_date',
|
||||
'gso_success',
|
||||
'kubsat_success',
|
||||
'points_count',
|
||||
'status_updated_at',
|
||||
'created_at',
|
||||
'created_by',
|
||||
)
|
||||
list_display_links = ('id', 'source')
|
||||
list_select_related = ('source', 'created_by__user', 'updated_by__user')
|
||||
|
||||
list_filter = (
|
||||
'status',
|
||||
'priority',
|
||||
'gso_success',
|
||||
'kubsat_success',
|
||||
('planned_at', DateRangeQuickSelectListFilterBuilder()),
|
||||
('request_date', DateRangeQuickSelectListFilterBuilder()),
|
||||
('created_at', DateRangeQuickSelectListFilterBuilder()),
|
||||
)
|
||||
|
||||
search_fields = (
|
||||
'source__id',
|
||||
'comment',
|
||||
)
|
||||
|
||||
ordering = ('-created_at',)
|
||||
readonly_fields = ('status_updated_at', 'created_at', 'created_by', 'updated_by', 'coords', 'points_count')
|
||||
autocomplete_fields = ('source',)
|
||||
inlines = [SourceRequestStatusHistoryInline]
|
||||
|
||||
fieldsets = (
|
||||
(
|
||||
'Основная информация',
|
||||
{'fields': ('source', 'status', 'priority')},
|
||||
),
|
||||
(
|
||||
'Даты',
|
||||
{'fields': ('planned_at', 'request_date', 'status_updated_at')},
|
||||
),
|
||||
(
|
||||
'Результаты',
|
||||
{'fields': ('gso_success', 'kubsat_success')},
|
||||
),
|
||||
(
|
||||
'Координаты',
|
||||
{'fields': ('coords', 'points_count')},
|
||||
),
|
||||
(
|
||||
'Комментарий',
|
||||
{'fields': ('comment',)},
|
||||
),
|
||||
(
|
||||
'Метаданные',
|
||||
{
|
||||
'fields': ('created_at', 'created_by', 'updated_by'),
|
||||
'classes': ('collapse',),
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@admin.register(SourceRequestStatusHistory)
|
||||
class SourceRequestStatusHistoryAdmin(BaseAdmin):
|
||||
"""Админ-панель для модели SourceRequestStatusHistory."""
|
||||
|
||||
list_display = (
|
||||
'id',
|
||||
'source_request',
|
||||
'old_status',
|
||||
'new_status',
|
||||
'changed_at',
|
||||
'changed_by',
|
||||
)
|
||||
list_display_links = ('id',)
|
||||
list_select_related = ('source_request', 'changed_by__user')
|
||||
|
||||
list_filter = (
|
||||
'old_status',
|
||||
'new_status',
|
||||
('changed_at', DateRangeQuickSelectListFilterBuilder()),
|
||||
)
|
||||
|
||||
search_fields = (
|
||||
'source_request__id',
|
||||
)
|
||||
|
||||
ordering = ('-changed_at',)
|
||||
readonly_fields = ('source_request', 'old_status', 'new_status', 'changed_at', 'changed_by')
|
||||
|
||||
def has_add_permission(self, request):
|
||||
return False
|
||||
|
||||
def has_change_permission(self, request, obj=None):
|
||||
return False
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# Third-party imports
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from sklearn.cluster import DBSCAN, HDBSCAN, KMeans
|
||||
|
||||
# Local imports
|
||||
from .models import ObjItem
|
||||
|
||||
def get_clusters(coords: list[tuple[float, float]]):
|
||||
coords = np.radians(coords)
|
||||
lat, lon = coords[:, 0], coords[:, 1]
|
||||
db = DBSCAN(eps=0.06, min_samples=5, algorithm='ball_tree', metric='haversine')
|
||||
# db = HDBSCAN()
|
||||
cluster_labels = db.fit_predict(coords)
|
||||
plt.figure(figsize=(10, 8))
|
||||
unique_labels = set(cluster_labels)
|
||||
colors = plt.cm.tab10(np.linspace(0, 1, len(unique_labels)))
|
||||
|
||||
for label, color in zip(unique_labels, colors):
|
||||
if label == -1:
|
||||
color = 'k'
|
||||
label_name = 'Шум'
|
||||
else:
|
||||
label_name = f'Кластер {label}'
|
||||
|
||||
mask = cluster_labels == label
|
||||
plt.scatter(lon[mask], lat[mask], c=[color], label=label_name, s=30)
|
||||
|
||||
plt.xlabel('Долгота')
|
||||
plt.ylabel('Широта')
|
||||
plt.title('Кластеризация геоданных с DBSCAN (метрика Хаверсина)')
|
||||
plt.legend()
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
@@ -40,6 +40,13 @@ class LoadExcelData(forms.Form):
|
||||
min_value=0,
|
||||
widget=forms.NumberInput(attrs={"class": "form-control"}),
|
||||
)
|
||||
is_automatic = forms.BooleanField(
|
||||
label="Автоматическая загрузка",
|
||||
required=False,
|
||||
initial=False,
|
||||
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
|
||||
help_text="Если отмечено, точки не будут добавляться к объектам",
|
||||
)
|
||||
|
||||
|
||||
class LoadCsvData(forms.Form):
|
||||
@@ -47,6 +54,13 @@ class LoadCsvData(forms.Form):
|
||||
label="Выберите CSV файл",
|
||||
widget=forms.FileInput(attrs={"class": "form-control", "accept": ".csv"}),
|
||||
)
|
||||
is_automatic = forms.BooleanField(
|
||||
label="Автоматическая загрузка",
|
||||
required=False,
|
||||
initial=False,
|
||||
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
|
||||
help_text="Если отмечено, точки не будут добавляться к объектам",
|
||||
)
|
||||
|
||||
|
||||
class UploadVchLoad(UploadFileForm):
|
||||
@@ -463,7 +477,7 @@ class SourceForm(forms.ModelForm):
|
||||
|
||||
class Meta:
|
||||
model = Source
|
||||
fields = ['info', 'ownership']
|
||||
fields = ['info', 'ownership', 'note']
|
||||
widgets = {
|
||||
'info': forms.Select(attrs={
|
||||
'class': 'form-select',
|
||||
@@ -473,10 +487,16 @@ class SourceForm(forms.ModelForm):
|
||||
'class': 'form-select',
|
||||
'id': 'id_ownership',
|
||||
}),
|
||||
'note': forms.Textarea(attrs={
|
||||
'class': 'form-control',
|
||||
'rows': "3",
|
||||
'id': 'id_note',
|
||||
})
|
||||
}
|
||||
labels = {
|
||||
'info': 'Тип объекта',
|
||||
'ownership': 'Принадлежность объекта',
|
||||
'note': 'Примечание'
|
||||
}
|
||||
help_texts = {
|
||||
'info': 'Стационарные: координата усредняется. Подвижные: координата = последняя точка. При изменении типа координата пересчитывается автоматически.',
|
||||
@@ -514,13 +534,8 @@ class SourceForm(forms.ModelForm):
|
||||
|
||||
instance = super().save(commit=False)
|
||||
|
||||
# Обработка coords_average
|
||||
avg_lat = self.cleaned_data.get("average_latitude")
|
||||
avg_lng = self.cleaned_data.get("average_longitude")
|
||||
if avg_lat is not None and avg_lng is not None:
|
||||
instance.coords_average = Point(avg_lng, avg_lat, srid=4326)
|
||||
else:
|
||||
instance.coords_average = None
|
||||
# coords_average НЕ обрабатываем здесь - это поле управляется только программно
|
||||
# (через _recalculate_average_coords в модели Source)
|
||||
|
||||
# Обработка coords_kupsat
|
||||
kup_lat = self.cleaned_data.get("kupsat_latitude")
|
||||
@@ -567,14 +582,14 @@ class KubsatFilterForm(forms.Form):
|
||||
queryset=None,
|
||||
label='Диапазоны работы спутника',
|
||||
required=False,
|
||||
widget=forms.SelectMultiple(attrs={'class': 'form-select', 'size': '4'})
|
||||
widget=forms.SelectMultiple(attrs={'class': 'form-select', 'size': '5'})
|
||||
)
|
||||
|
||||
polarization = forms.ModelMultipleChoiceField(
|
||||
queryset=Polarization.objects.all().order_by('name'),
|
||||
label='Поляризация',
|
||||
required=False,
|
||||
widget=forms.SelectMultiple(attrs={'class': 'form-select', 'size': '4'})
|
||||
widget=forms.SelectMultiple(attrs={'class': 'form-select', 'size': '5'})
|
||||
)
|
||||
|
||||
frequency_min = forms.FloatField(
|
||||
@@ -605,7 +620,7 @@ class KubsatFilterForm(forms.Form):
|
||||
queryset=Modulation.objects.all().order_by('name'),
|
||||
label='Модуляция',
|
||||
required=False,
|
||||
widget=forms.SelectMultiple(attrs={'class': 'form-select', 'size': '4'})
|
||||
widget=forms.SelectMultiple(attrs={'class': 'form-select', 'size': '5'})
|
||||
)
|
||||
|
||||
object_type = forms.ModelMultipleChoiceField(
|
||||
@@ -622,11 +637,18 @@ class KubsatFilterForm(forms.Form):
|
||||
widget=forms.SelectMultiple(attrs={'class': 'form-select', 'size': '3'})
|
||||
)
|
||||
|
||||
objitem_count = forms.ChoiceField(
|
||||
choices=[('', 'Все'), ('1', '1'), ('2+', '2 и более')],
|
||||
label='Количество привязанных точек ГЛ',
|
||||
objitem_count_min = forms.IntegerField(
|
||||
label='Количество привязанных точек ГЛ от',
|
||||
required=False,
|
||||
widget=forms.RadioSelect()
|
||||
min_value=0,
|
||||
widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'От'})
|
||||
)
|
||||
|
||||
objitem_count_max = forms.IntegerField(
|
||||
label='Количество привязанных точек ГЛ до',
|
||||
required=False,
|
||||
min_value=0,
|
||||
widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'До'})
|
||||
)
|
||||
|
||||
# Фиктивные фильтры
|
||||
@@ -795,7 +817,10 @@ class SatelliteForm(forms.ModelForm):
|
||||
model = Satellite
|
||||
fields = [
|
||||
'name',
|
||||
'alternative_name',
|
||||
'location_place',
|
||||
'norad',
|
||||
'international_code',
|
||||
'band',
|
||||
'undersat_point',
|
||||
'url',
|
||||
@@ -808,10 +833,21 @@ class SatelliteForm(forms.ModelForm):
|
||||
'placeholder': 'Введите название спутника',
|
||||
'required': True
|
||||
}),
|
||||
'alternative_name': forms.TextInput(attrs={
|
||||
'class': 'form-control',
|
||||
'placeholder': 'Введите альтернативное название (необязательно)'
|
||||
}),
|
||||
'location_place': forms.Select(attrs={
|
||||
'class': 'form-select'
|
||||
}),
|
||||
'norad': forms.NumberInput(attrs={
|
||||
'class': 'form-control',
|
||||
'placeholder': 'Введите NORAD ID'
|
||||
}),
|
||||
'international_code': forms.TextInput(attrs={
|
||||
'class': 'form-control',
|
||||
'placeholder': 'Например, 2011-074A'
|
||||
}),
|
||||
'band': forms.SelectMultiple(attrs={
|
||||
'class': 'form-select',
|
||||
'size': '5'
|
||||
@@ -837,7 +873,10 @@ class SatelliteForm(forms.ModelForm):
|
||||
}
|
||||
labels = {
|
||||
'name': 'Название спутника',
|
||||
'alternative_name': 'Альтернативное название',
|
||||
'location_place': 'Комплекс',
|
||||
'norad': 'NORAD ID',
|
||||
'international_code': 'Международный код',
|
||||
'band': 'Диапазоны работы',
|
||||
'undersat_point': 'Подспутниковая точка (градусы)',
|
||||
'url': 'Ссылка на источник',
|
||||
@@ -846,7 +885,10 @@ class SatelliteForm(forms.ModelForm):
|
||||
}
|
||||
help_texts = {
|
||||
'name': 'Уникальное название спутника',
|
||||
'alternative_name': 'Альтернативное название спутника (например, на другом языке)',
|
||||
'location_place': 'К какому комплексу принадлежит спутник',
|
||||
'norad': 'Идентификатор NORAD для отслеживания спутника',
|
||||
'international_code': 'Международный идентификатор спутника (например, 2011-074A)',
|
||||
'band': 'Выберите диапазоны работы спутника (удерживайте Ctrl для множественного выбора)',
|
||||
'undersat_point': 'Восточное полушарие с +, западное с -',
|
||||
'url': 'Ссылка на сайт, где можно проверить информацию',
|
||||
@@ -884,3 +926,269 @@ class SatelliteForm(forms.ModelForm):
|
||||
raise forms.ValidationError('Спутник с таким названием уже существует')
|
||||
|
||||
return name
|
||||
|
||||
|
||||
class SourceRequestForm(forms.ModelForm):
|
||||
"""
|
||||
Форма для создания и редактирования заявок на источники.
|
||||
"""
|
||||
|
||||
# Дополнительные поля для координат ГСО
|
||||
coords_lat = forms.FloatField(
|
||||
required=False,
|
||||
label='Широта ГСО',
|
||||
widget=forms.NumberInput(attrs={
|
||||
'class': 'form-control',
|
||||
'step': '0.000001',
|
||||
'placeholder': 'Например: 55.751244'
|
||||
})
|
||||
)
|
||||
coords_lon = forms.FloatField(
|
||||
required=False,
|
||||
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={
|
||||
'class': 'form-control',
|
||||
'step': '0.000001',
|
||||
'placeholder': 'Например: 37.618423'
|
||||
})
|
||||
)
|
||||
|
||||
# Дополнительные поля для координат объекта
|
||||
coords_object_lat = forms.FloatField(
|
||||
required=False,
|
||||
label='Широта объекта',
|
||||
widget=forms.NumberInput(attrs={
|
||||
'class': 'form-control',
|
||||
'step': '0.000001',
|
||||
'placeholder': 'Например: 55.751244'
|
||||
})
|
||||
)
|
||||
coords_object_lon = forms.FloatField(
|
||||
required=False,
|
||||
label='Долгота объекта',
|
||||
widget=forms.NumberInput(attrs={
|
||||
'class': 'form-control',
|
||||
'step': '0.000001',
|
||||
'placeholder': 'Например: 37.618423'
|
||||
})
|
||||
)
|
||||
|
||||
class Meta:
|
||||
from .models import SourceRequest
|
||||
model = SourceRequest
|
||||
fields = [
|
||||
'source',
|
||||
'satellite',
|
||||
'status',
|
||||
'priority',
|
||||
'planned_at',
|
||||
'request_date',
|
||||
'card_date',
|
||||
'downlink',
|
||||
'uplink',
|
||||
'transfer',
|
||||
'region',
|
||||
'gso_success',
|
||||
'kubsat_success',
|
||||
'comment',
|
||||
]
|
||||
widgets = {
|
||||
'source': forms.Select(attrs={
|
||||
'class': 'form-select',
|
||||
}),
|
||||
'satellite': forms.Select(attrs={
|
||||
'class': 'form-select',
|
||||
}),
|
||||
'status': forms.Select(attrs={
|
||||
'class': 'form-select'
|
||||
}),
|
||||
'priority': forms.Select(attrs={
|
||||
'class': 'form-select'
|
||||
}),
|
||||
'planned_at': forms.DateTimeInput(attrs={
|
||||
'class': 'form-control',
|
||||
'type': 'datetime-local'
|
||||
}),
|
||||
'request_date': forms.DateInput(attrs={
|
||||
'class': 'form-control',
|
||||
'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(
|
||||
choices=[(None, '-'), (True, 'Да'), (False, 'Нет')],
|
||||
attrs={'class': 'form-select'}
|
||||
),
|
||||
'kubsat_success': forms.Select(
|
||||
choices=[(None, '-'), (True, 'Да'), (False, 'Нет')],
|
||||
attrs={'class': 'form-select'}
|
||||
),
|
||||
'comment': forms.Textarea(attrs={
|
||||
'class': 'form-control',
|
||||
'rows': 3,
|
||||
'placeholder': 'Введите комментарий'
|
||||
}),
|
||||
}
|
||||
labels = {
|
||||
'source': 'Источник',
|
||||
'satellite': 'Спутник',
|
||||
'status': 'Статус',
|
||||
'priority': 'Приоритет',
|
||||
'planned_at': 'Дата и время планирования',
|
||||
'request_date': 'Дата заявки',
|
||||
'card_date': 'Дата формирования карточки',
|
||||
'downlink': 'Частота Downlink (МГц)',
|
||||
'uplink': 'Частота Uplink (МГц)',
|
||||
'transfer': 'Перенос (МГц)',
|
||||
'region': 'Район',
|
||||
'gso_success': 'ГСО успешно?',
|
||||
'kubsat_success': 'Кубсат успешно?',
|
||||
'comment': 'Комментарий',
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
# Извлекаем source_id если передан
|
||||
source_id = kwargs.pop('source_id', None)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# Загружаем queryset для источников и спутников
|
||||
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, устанавливаем его как начальное значение
|
||||
if source_id:
|
||||
self.fields['source'].initial = source_id
|
||||
# Можно сделать поле только для чтения
|
||||
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(
|
||||
choices=[(None, '-'), (True, 'Да'), (False, 'Нет')],
|
||||
attrs={'class': 'form-select'}
|
||||
)
|
||||
self.fields['kubsat_success'].widget = forms.Select(
|
||||
choices=[(None, '-'), (True, 'Да'), (False, 'Нет')],
|
||||
attrs={'class': 'form-select'}
|
||||
)
|
||||
|
||||
# Заполняем координаты из существующего объекта
|
||||
if self.instance and self.instance.pk:
|
||||
if self.instance.coords:
|
||||
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
|
||||
if self.instance.coords_object:
|
||||
self.fields['coords_object_lat'].initial = self.instance.coords_object.y
|
||||
self.fields['coords_object_lon'].initial = self.instance.coords_object.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):
|
||||
from django.contrib.gis.geos import Point
|
||||
|
||||
instance = super().save(commit=False)
|
||||
|
||||
# Обрабатываем координаты ГСО
|
||||
coords_lat = self.cleaned_data.get('coords_lat')
|
||||
coords_lon = self.cleaned_data.get('coords_lon')
|
||||
|
||||
if coords_lat is not None and coords_lon is not None:
|
||||
instance.coords = Point(coords_lon, coords_lat, srid=4326)
|
||||
elif coords_lat is None and coords_lon is 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
|
||||
|
||||
# Обрабатываем координаты объекта
|
||||
coords_object_lat = self.cleaned_data.get('coords_object_lat')
|
||||
coords_object_lon = self.cleaned_data.get('coords_object_lon')
|
||||
|
||||
if coords_object_lat is not None and coords_object_lon is not None:
|
||||
instance.coords_object = Point(coords_object_lon, coords_object_lat, srid=4326)
|
||||
elif coords_object_lat is None and coords_object_lon is None:
|
||||
instance.coords_object = None
|
||||
|
||||
if commit:
|
||||
instance.save()
|
||||
|
||||
return instance
|
||||
|
||||
1
dbapp/mainapp/management/__init__.py
Normal file
1
dbapp/mainapp/management/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# Management commands package
|
||||
1
dbapp/mainapp/management/commands/__init__.py
Normal file
1
dbapp/mainapp/management/commands/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# Commands package
|
||||
169
dbapp/mainapp/management/commands/generate_test_marks.py
Normal file
169
dbapp/mainapp/management/commands/generate_test_marks.py
Normal file
@@ -0,0 +1,169 @@
|
||||
"""
|
||||
Management command для генерации тестовых отметок сигналов.
|
||||
|
||||
Использование:
|
||||
python manage.py generate_test_marks --satellite_id=1 --user_id=1 --date_range=10.10.2025-15.10.2025
|
||||
|
||||
Параметры:
|
||||
--satellite_id: ID спутника (обязательный)
|
||||
--user_id: ID пользователя CustomUser (обязательный)
|
||||
--date_range: Диапазон дат в формате ДД.ММ.ГГГГ-ДД.ММ.ГГГГ (обязательный)
|
||||
--clear: Удалить существующие отметки перед генерацией
|
||||
|
||||
Особенности:
|
||||
- Генерирует отметки только в будние дни (пн-пт)
|
||||
- Время отметок: утро с 8:00 до 11:00
|
||||
- Одна отметка в день для всех сигналов спутника
|
||||
- Все отметки в один день имеют одинаковый timestamp (пакетное сохранение)
|
||||
- Все отметки имеют значение True (сигнал присутствует)
|
||||
"""
|
||||
|
||||
import random
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.utils import timezone
|
||||
|
||||
from mainapp.models import TechAnalyze, ObjectMark, Satellite, CustomUser
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Генерирует тестовые отметки сигналов для теханализов выбранного спутника'
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
'--satellite_id',
|
||||
type=int,
|
||||
required=True,
|
||||
help='ID спутника для генерации отметок'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--user_id',
|
||||
type=int,
|
||||
required=True,
|
||||
help='ID пользователя CustomUser - автор всех отметок'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--date_range',
|
||||
type=str,
|
||||
required=True,
|
||||
help='Диапазон дат в формате ДД.ММ.ГГГГ-ДД.ММ.ГГГГ (например: 10.10.2025-15.10.2025)'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--clear',
|
||||
action='store_true',
|
||||
help='Удалить существующие отметки перед генерацией'
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
satellite_id = options['satellite_id']
|
||||
user_id = options['user_id']
|
||||
date_range = options['date_range']
|
||||
clear = options['clear']
|
||||
|
||||
# Проверяем существование пользователя
|
||||
try:
|
||||
custom_user = CustomUser.objects.select_related('user').get(id=user_id)
|
||||
except CustomUser.DoesNotExist:
|
||||
raise CommandError(f'Пользователь CustomUser с ID {user_id} не найден')
|
||||
|
||||
# Парсим диапазон дат
|
||||
try:
|
||||
start_str, end_str = date_range.split('-')
|
||||
start_date = datetime.strptime(start_str.strip(), '%d.%m.%Y')
|
||||
end_date = datetime.strptime(end_str.strip(), '%d.%m.%Y')
|
||||
|
||||
# Делаем timezone-aware
|
||||
start_date = timezone.make_aware(start_date)
|
||||
end_date = timezone.make_aware(end_date)
|
||||
|
||||
if start_date > end_date:
|
||||
raise CommandError('Начальная дата должна быть раньше конечной')
|
||||
|
||||
except ValueError as e:
|
||||
raise CommandError(
|
||||
f'Неверный формат даты. Используйте ДД.ММ.ГГГГ-ДД.ММ.ГГГГ (например: 10.10.2025-15.10.2025). Ошибка: {e}'
|
||||
)
|
||||
|
||||
# Проверяем существование спутника
|
||||
try:
|
||||
satellite = Satellite.objects.get(id=satellite_id)
|
||||
except Satellite.DoesNotExist:
|
||||
raise CommandError(f'Спутник с ID {satellite_id} не найден')
|
||||
|
||||
# Получаем теханализы для спутника
|
||||
tech_analyzes = list(TechAnalyze.objects.filter(satellite=satellite))
|
||||
ta_count = len(tech_analyzes)
|
||||
|
||||
if ta_count == 0:
|
||||
raise CommandError(f'Нет теханализов для спутника "{satellite.name}"')
|
||||
|
||||
self.stdout.write(f'Спутник: {satellite.name}')
|
||||
self.stdout.write(f'Теханализов: {ta_count}')
|
||||
self.stdout.write(f'Пользователь: {custom_user}')
|
||||
self.stdout.write(f'Период: {start_str} - {end_str} (только будние дни)')
|
||||
self.stdout.write(f'Время: 8:00 - 11:00')
|
||||
|
||||
# Удаляем существующие отметки если указан флаг
|
||||
if clear:
|
||||
deleted_count = ObjectMark.objects.filter(
|
||||
tech_analyze__satellite=satellite
|
||||
).delete()[0]
|
||||
self.stdout.write(
|
||||
self.style.WARNING(f'Удалено существующих отметок: {deleted_count}')
|
||||
)
|
||||
|
||||
# Генерируем отметки
|
||||
total_marks = 0
|
||||
marks_to_create = []
|
||||
workdays_count = 0
|
||||
|
||||
current_date = start_date
|
||||
# Включаем конечную дату в диапазон
|
||||
end_date_inclusive = end_date + timedelta(days=1)
|
||||
|
||||
while current_date < end_date_inclusive:
|
||||
# Проверяем, что это будний день (0=пн, 4=пт)
|
||||
if current_date.weekday() < 5:
|
||||
workdays_count += 1
|
||||
|
||||
# Генерируем случайное время в диапазоне 8:00-11:00
|
||||
random_hour = random.randint(8, 10)
|
||||
random_minute = random.randint(0, 59)
|
||||
random_second = random.randint(0, 59)
|
||||
|
||||
mark_time = current_date.replace(
|
||||
hour=random_hour,
|
||||
minute=random_minute,
|
||||
second=random_second,
|
||||
microsecond=0
|
||||
)
|
||||
|
||||
# Создаём отметки для всех теханализов с одинаковым timestamp
|
||||
for ta in tech_analyzes:
|
||||
marks_to_create.append(ObjectMark(
|
||||
tech_analyze=ta,
|
||||
mark=True, # Всегда True
|
||||
timestamp=mark_time,
|
||||
created_by=custom_user,
|
||||
))
|
||||
total_marks += 1
|
||||
|
||||
current_date += timedelta(days=1)
|
||||
|
||||
# Bulk create для производительности
|
||||
self.stdout.write(f'Рабочих дней: {workdays_count}')
|
||||
self.stdout.write(f'Создание {total_marks} отметок...')
|
||||
|
||||
# Создаём партиями по 1000
|
||||
batch_size = 1000
|
||||
for i in range(0, len(marks_to_create), batch_size):
|
||||
batch = marks_to_create[i:i + batch_size]
|
||||
ObjectMark.objects.bulk_create(batch)
|
||||
self.stdout.write(f' Создано: {min(i + batch_size, len(marks_to_create))}/{total_marks}')
|
||||
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(
|
||||
f'Успешно создано {total_marks} отметок для {ta_count} теханализов за {workdays_count} рабочих дней'
|
||||
)
|
||||
)
|
||||
28
dbapp/mainapp/migrations/0013_add_is_automatic_to_objitem.py
Normal file
28
dbapp/mainapp/migrations/0013_add_is_automatic_to_objitem.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# Generated by Django 5.2.7 on 2025-11-24 19:11
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0012_source_confirm_at_source_last_signal_at'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.DeleteModel(
|
||||
name='Mirror',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='sigmaparameter',
|
||||
name='mark',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='objitem',
|
||||
name='is_automatic',
|
||||
field=models.BooleanField(db_index=True, default=False, help_text='Если True, точка не добавляется к объектам (Source), а хранится отдельно', verbose_name='Автоматическая'),
|
||||
),
|
||||
migrations.DeleteModel(
|
||||
name='SigmaParMark',
|
||||
),
|
||||
]
|
||||
18
dbapp/mainapp/migrations/0014_source_note.py
Normal file
18
dbapp/mainapp/migrations/0014_source_note.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.2.7 on 2025-11-25 12:46
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0013_add_is_automatic_to_objitem'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='source',
|
||||
name='note',
|
||||
field=models.TextField(blank=True, help_text='Дополнительное описание объекта', null=True, verbose_name='Примечание'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.2.7 on 2025-11-26 20:20
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0014_source_note'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='satellite',
|
||||
name='international_code',
|
||||
field=models.CharField(blank=True, help_text='Международный идентификатор спутника (например, 2011-074A)', max_length=20, null=True, verbose_name='Международный код'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,44 @@
|
||||
# Generated by Django 5.2.7 on 2025-11-27 07:10
|
||||
|
||||
import django.db.models.deletion
|
||||
import mainapp.models
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0015_add_international_code_to_satellite'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='satellite',
|
||||
name='international_code',
|
||||
field=models.CharField(blank=True, help_text='Международный идентификатор спутника (например, 2011-074A)', max_length=50, null=True, verbose_name='Международный код'),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TechAnalyze',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(db_index=True, help_text='Уникальное название для технического анализа', max_length=255, unique=True, verbose_name='Имя')),
|
||||
('frequency', models.FloatField(blank=True, db_index=True, default=0, help_text='Центральная частота сигнала', null=True, verbose_name='Частота, МГц')),
|
||||
('freq_range', models.FloatField(blank=True, default=0, help_text='Полоса частот сигнала', null=True, verbose_name='Полоса частот, МГц')),
|
||||
('bod_velocity', models.FloatField(blank=True, default=0, help_text='Символьная скорость', null=True, verbose_name='Символьная скорость, БОД')),
|
||||
('note', models.TextField(blank=True, help_text='Дополнительные примечания', null=True, verbose_name='Примечание')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True, help_text='Дата и время создания записи', verbose_name='Дата создания')),
|
||||
('updated_at', models.DateTimeField(auto_now=True, help_text='Дата и время последнего изменения', verbose_name='Дата последнего изменения')),
|
||||
('created_by', models.ForeignKey(blank=True, help_text='Пользователь, создавший запись', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='tech_analyze_created', to='mainapp.customuser', verbose_name='Создан пользователем')),
|
||||
('modulation', models.ForeignKey(blank=True, default=mainapp.models.get_default_modulation, null=True, on_delete=django.db.models.deletion.SET_DEFAULT, related_name='tech_analyze_modulations', to='mainapp.modulation', verbose_name='Модуляция')),
|
||||
('polarization', models.ForeignKey(blank=True, default=mainapp.models.get_default_polarization, null=True, on_delete=django.db.models.deletion.SET_DEFAULT, related_name='tech_analyze_polarizations', to='mainapp.polarization', verbose_name='Поляризация')),
|
||||
('satellite', models.ForeignKey(help_text='Спутник, к которому относится анализ', on_delete=django.db.models.deletion.PROTECT, related_name='tech_analyzes', to='mainapp.satellite', verbose_name='Спутник')),
|
||||
('standard', models.ForeignKey(blank=True, default=mainapp.models.get_default_standard, null=True, on_delete=django.db.models.deletion.SET_DEFAULT, related_name='tech_analyze_standards', to='mainapp.standard', verbose_name='Стандарт')),
|
||||
('updated_by', models.ForeignKey(blank=True, help_text='Пользователь, последним изменивший запись', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='tech_analyze_updated', to='mainapp.customuser', verbose_name='Изменен пользователем')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Тех. анализ',
|
||||
'verbose_name_plural': 'Тех. анализы',
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 5.2.7 on 2025-12-01 08:15
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0016_alter_satellite_international_code_techanalyze'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='satellite',
|
||||
name='alternative_name',
|
||||
field=models.CharField(blank=True, db_index=True, help_text='Альтернативное название спутника (например, из скобок)', max_length=100, null=True, verbose_name='Альтернативное имя'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='standard',
|
||||
name='name',
|
||||
field=models.CharField(db_index=True, help_text='Стандарт передачи данных (DVB-S, DVB-S2, DVB-S2X и т.д.)', max_length=80, unique=True, verbose_name='Стандарт'),
|
||||
),
|
||||
]
|
||||
87
dbapp/mainapp/migrations/0018_add_source_request_models.py
Normal file
87
dbapp/mainapp/migrations/0018_add_source_request_models.py
Normal file
@@ -0,0 +1,87 @@
|
||||
# Generated by Django 5.2.7 on 2025-12-08 08:45
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0017_add_satellite_alternative_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='objectownership',
|
||||
name='name',
|
||||
field=models.CharField(help_text='Принадлежность объекта', max_length=255, unique=True, verbose_name='Принадлежность'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='satellite',
|
||||
name='alternative_name',
|
||||
field=models.CharField(blank=True, db_index=True, help_text='Альтернативное название спутника', max_length=100, null=True, verbose_name='Альтернативное имя'),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SourceRequest',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('status', models.CharField(choices=[('planned', 'Запланировано'), ('conducted', 'Проведён'), ('successful', 'Успешно'), ('no_correlation', 'Нет корреляции'), ('no_signal', 'Нет сигнала в спектре'), ('unsuccessful', 'Неуспешно'), ('downloading', 'Скачивание'), ('processing', 'Обработка'), ('result_received', 'Результат получен')], db_index=True, default='planned', help_text='Текущий статус заявки', max_length=20, verbose_name='Статус')),
|
||||
('priority', models.CharField(choices=[('low', 'Низкий'), ('medium', 'Средний'), ('high', 'Высокий')], db_index=True, default='medium', help_text='Приоритет заявки', max_length=10, verbose_name='Приоритет')),
|
||||
('planned_at', models.DateTimeField(blank=True, help_text='Запланированная дата и время', null=True, verbose_name='Дата и время планирования')),
|
||||
('request_date', models.DateField(blank=True, help_text='Дата подачи заявки', null=True, verbose_name='Дата заявки')),
|
||||
('status_updated_at', models.DateTimeField(auto_now=True, help_text='Дата и время последнего обновления статуса', verbose_name='Дата обновления статуса')),
|
||||
('gso_success', models.BooleanField(blank=True, help_text='Успешность ГСО', null=True, verbose_name='ГСО успешно?')),
|
||||
('kubsat_success', models.BooleanField(blank=True, help_text='Успешность Кубсат', null=True, verbose_name='Кубсат успешно?')),
|
||||
('comment', models.TextField(blank=True, help_text='Дополнительные комментарии к заявке', null=True, verbose_name='Комментарий')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True, help_text='Дата и время создания записи', verbose_name='Дата создания')),
|
||||
('created_by', models.ForeignKey(blank=True, help_text='Пользователь, создавший запись', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='source_requests_created', to='mainapp.customuser', verbose_name='Создан пользователем')),
|
||||
('source', models.ForeignKey(help_text='Связанный источник', on_delete=django.db.models.deletion.CASCADE, related_name='source_requests', to='mainapp.source', verbose_name='Источник')),
|
||||
('updated_by', models.ForeignKey(blank=True, help_text='Пользователь, последним изменивший запись', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='source_requests_updated', to='mainapp.customuser', verbose_name='Изменен пользователем')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Заявка на источник',
|
||||
'verbose_name_plural': 'Заявки на источники',
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SourceRequestStatusHistory',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('old_status', models.CharField(choices=[('planned', 'Запланировано'), ('conducted', 'Проведён'), ('successful', 'Успешно'), ('no_correlation', 'Нет корреляции'), ('no_signal', 'Нет сигнала в спектре'), ('unsuccessful', 'Неуспешно'), ('downloading', 'Скачивание'), ('processing', 'Обработка'), ('result_received', 'Результат получен')], help_text='Статус до изменения', max_length=20, verbose_name='Старый статус')),
|
||||
('new_status', models.CharField(choices=[('planned', 'Запланировано'), ('conducted', 'Проведён'), ('successful', 'Успешно'), ('no_correlation', 'Нет корреляции'), ('no_signal', 'Нет сигнала в спектре'), ('unsuccessful', 'Неуспешно'), ('downloading', 'Скачивание'), ('processing', 'Обработка'), ('result_received', 'Результат получен')], help_text='Статус после изменения', max_length=20, verbose_name='Новый статус')),
|
||||
('changed_at', models.DateTimeField(auto_now_add=True, db_index=True, help_text='Дата и время изменения статуса', verbose_name='Дата изменения')),
|
||||
('changed_by', models.ForeignKey(blank=True, help_text='Пользователь, изменивший статус', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='status_changes', to='mainapp.customuser', verbose_name='Изменен пользователем')),
|
||||
('source_request', models.ForeignKey(help_text='Связанная заявка', on_delete=django.db.models.deletion.CASCADE, related_name='status_history', to='mainapp.sourcerequest', verbose_name='Заявка')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'История статуса заявки',
|
||||
'verbose_name_plural': 'История статусов заявок',
|
||||
'ordering': ['-changed_at'],
|
||||
},
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='sourcerequest',
|
||||
index=models.Index(fields=['-created_at'], name='mainapp_sou_created_61d8ae_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='sourcerequest',
|
||||
index=models.Index(fields=['status'], name='mainapp_sou_status_31dc99_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='sourcerequest',
|
||||
index=models.Index(fields=['priority'], name='mainapp_sou_priorit_5b5044_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='sourcerequest',
|
||||
index=models.Index(fields=['source', '-created_at'], name='mainapp_sou_source__6bb459_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='sourcerequeststatushistory',
|
||||
index=models.Index(fields=['-changed_at'], name='mainapp_sou_changed_9b876e_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='sourcerequeststatushistory',
|
||||
index=models.Index(fields=['source_request', '-changed_at'], name='mainapp_sou_source__957c28_idx'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
# Generated by Django 5.2.7 on 2025-12-08 09:24
|
||||
|
||||
import django.contrib.gis.db.models.fields
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0018_add_source_request_models'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
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.AddField(
|
||||
model_name='sourcerequest',
|
||||
name='points_count',
|
||||
field=models.PositiveIntegerField(default=0, help_text='Количество точек ГЛ, использованных для расчёта координат', verbose_name='Количество точек'),
|
||||
),
|
||||
]
|
||||
18
dbapp/mainapp/migrations/0020_satellite_location_place.py
Normal file
18
dbapp/mainapp/migrations/0020_satellite_location_place.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.2.7 on 2025-12-08 12:41
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0019_add_coords_to_source_request'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='satellite',
|
||||
name='location_place',
|
||||
field=models.CharField(choices=[('kr', 'КР'), ('dv', 'ДВ')], default='kr', help_text='К какому комплексу принадлежит спутник', max_length=30, null=True, verbose_name='Комплекс'),
|
||||
),
|
||||
]
|
||||
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='Источник'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
Миграция для изменения модели ObjectMark:
|
||||
- Удаление всех существующих отметок
|
||||
- Удаление поля source
|
||||
- Добавление поля tech_analyze
|
||||
"""
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
def delete_all_marks(apps, schema_editor):
|
||||
"""Удаляем все существующие отметки перед изменением структуры."""
|
||||
ObjectMark = apps.get_model('mainapp', 'ObjectMark')
|
||||
count = ObjectMark.objects.count()
|
||||
ObjectMark.objects.all().delete()
|
||||
print(f"Удалено {count} отметок ObjectMark")
|
||||
|
||||
|
||||
def noop(apps, schema_editor):
|
||||
"""Обратная операция - ничего не делаем."""
|
||||
pass
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0021_add_source_request_fields'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
# Сначала удаляем все отметки
|
||||
migrations.RunPython(delete_all_marks, noop),
|
||||
|
||||
# Удаляем старое поле source
|
||||
migrations.RemoveField(
|
||||
model_name='objectmark',
|
||||
name='source',
|
||||
),
|
||||
|
||||
# Добавляем новое поле tech_analyze
|
||||
migrations.AddField(
|
||||
model_name='objectmark',
|
||||
name='tech_analyze',
|
||||
field=models.ForeignKey(
|
||||
help_text='Связанный технический анализ',
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name='marks',
|
||||
to='mainapp.techanalyze',
|
||||
verbose_name='Тех. анализ',
|
||||
),
|
||||
preserve_default=False,
|
||||
),
|
||||
|
||||
# Обновляем метаданные модели
|
||||
migrations.AlterModelOptions(
|
||||
name='objectmark',
|
||||
options={
|
||||
'ordering': ['-timestamp'],
|
||||
'verbose_name': 'Отметка сигнала',
|
||||
'verbose_name_plural': 'Отметки сигналов'
|
||||
},
|
||||
),
|
||||
|
||||
# Добавляем индекс для оптимизации запросов
|
||||
migrations.AddIndex(
|
||||
model_name='objectmark',
|
||||
index=models.Index(
|
||||
fields=['tech_analyze', '-timestamp'],
|
||||
name='mainapp_obj_tech_an_idx'
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,29 @@
|
||||
# Generated by Django 5.2.7 on 2025-12-11 12:08
|
||||
|
||||
import django.contrib.gis.db.models.fields
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0022_change_objectmark_to_techanalyze'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RenameIndex(
|
||||
model_name='objectmark',
|
||||
new_name='mainapp_obj_tech_an_b0c804_idx',
|
||||
old_name='mainapp_obj_tech_an_idx',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='sourcerequest',
|
||||
name='coords_object',
|
||||
field=django.contrib.gis.db.models.fields.PointField(blank=True, help_text='Координаты объекта (WGS84)', null=True, srid=4326, verbose_name='Координаты объекта'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='objectmark',
|
||||
name='mark',
|
||||
field=models.BooleanField(blank=True, help_text='True - сигнал обнаружен, False - сигнал отсутствует', null=True, verbose_name='Наличие сигнала'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,33 @@
|
||||
# Generated by Django 5.2.7 on 2025-12-12 12:24
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mainapp', '0023_add_coords_object_to_sourcerequest'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='objectmark',
|
||||
name='timestamp',
|
||||
field=models.DateTimeField(blank=True, db_index=True, help_text='Время фиксации отметки', null=True, verbose_name='Время'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='sourcerequest',
|
||||
name='status',
|
||||
field=models.CharField(choices=[('planned', 'Запланировано'), ('canceled_gso', 'Отменено ГСО'), ('canceled_kub', 'Отменено МКА'), ('conducted', 'Проведён'), ('successful', 'Успешно'), ('no_correlation', 'Нет корреляции'), ('no_signal', 'Нет сигнала в спектре'), ('unsuccessful', 'Неуспешно'), ('downloading', 'Скачивание'), ('processing', 'Обработка'), ('result_received', 'Результат получен')], db_index=True, default='planned', help_text='Текущий статус заявки', max_length=20, verbose_name='Статус'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='sourcerequeststatushistory',
|
||||
name='new_status',
|
||||
field=models.CharField(choices=[('planned', 'Запланировано'), ('canceled_gso', 'Отменено ГСО'), ('canceled_kub', 'Отменено МКА'), ('conducted', 'Проведён'), ('successful', 'Успешно'), ('no_correlation', 'Нет корреляции'), ('no_signal', 'Нет сигнала в спектре'), ('unsuccessful', 'Неуспешно'), ('downloading', 'Скачивание'), ('processing', 'Обработка'), ('result_received', 'Результат получен')], help_text='Статус после изменения', max_length=20, verbose_name='Новый статус'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='sourcerequeststatushistory',
|
||||
name='old_status',
|
||||
field=models.CharField(choices=[('planned', 'Запланировано'), ('canceled_gso', 'Отменено ГСО'), ('canceled_kub', 'Отменено МКА'), ('conducted', 'Проведён'), ('successful', 'Успешно'), ('no_correlation', 'Нет корреляции'), ('no_signal', 'Нет сигнала в спектре'), ('unsuccessful', 'Неуспешно'), ('downloading', 'Скачивание'), ('processing', 'Обработка'), ('result_received', 'Результат получен')], help_text='Статус до изменения', max_length=20, verbose_name='Старый статус'),
|
||||
),
|
||||
]
|
||||
@@ -87,14 +87,12 @@ class ObjectInfo(models.Model):
|
||||
class ObjectOwnership(models.Model):
|
||||
"""
|
||||
Модель принадлежности объекта.
|
||||
|
||||
Определяет к какой организации/стране/группе принадлежит объект.
|
||||
"""
|
||||
name = models.CharField(
|
||||
max_length=255,
|
||||
unique=True,
|
||||
verbose_name="Принадлежность",
|
||||
help_text="Принадлежность объекта (страна, организация и т.д.)",
|
||||
help_text="Принадлежность объекта",
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
@@ -108,30 +106,32 @@ class ObjectOwnership(models.Model):
|
||||
|
||||
class ObjectMark(models.Model):
|
||||
"""
|
||||
Модель отметки о наличии объекта.
|
||||
Модель отметки о наличии сигнала.
|
||||
|
||||
Используется для фиксации моментов времени когда объект был обнаружен или отсутствовал.
|
||||
Используется для фиксации моментов времени когда сигнал был обнаружен или отсутствовал.
|
||||
Привязывается к записям технического анализа (TechAnalyze).
|
||||
"""
|
||||
|
||||
# Основные поля
|
||||
mark = models.BooleanField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Наличие объекта",
|
||||
help_text="True - объект обнаружен, False - объект отсутствует",
|
||||
verbose_name="Наличие сигнала",
|
||||
help_text="True - сигнал обнаружен, False - сигнал отсутствует",
|
||||
)
|
||||
timestamp = models.DateTimeField(
|
||||
auto_now_add=True,
|
||||
verbose_name="Время",
|
||||
db_index=True,
|
||||
help_text="Время фиксации отметки",
|
||||
null=True,
|
||||
blank=True,
|
||||
)
|
||||
source = models.ForeignKey(
|
||||
'Source',
|
||||
tech_analyze = models.ForeignKey(
|
||||
'TechAnalyze',
|
||||
on_delete=models.CASCADE,
|
||||
related_name="marks",
|
||||
verbose_name="Источник",
|
||||
help_text="Связанный источник",
|
||||
verbose_name="Тех. анализ",
|
||||
help_text="Связанный технический анализ",
|
||||
)
|
||||
created_by = models.ForeignKey(
|
||||
CustomUser,
|
||||
@@ -162,74 +162,53 @@ class ObjectMark(models.Model):
|
||||
def __str__(self):
|
||||
if self.timestamp:
|
||||
timestamp = self.timestamp.strftime("%d.%m.%Y %H:%M")
|
||||
return f"+ {timestamp}" if self.mark else f"- {timestamp}"
|
||||
return "Отметка без времени"
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Отметка источника"
|
||||
verbose_name_plural = "Отметки источников"
|
||||
ordering = ["-timestamp"]
|
||||
|
||||
|
||||
# Для обратной совместимости с SigmaParameter
|
||||
class SigmaParMark(models.Model):
|
||||
"""
|
||||
Модель отметки о наличии сигнала (для Sigma).
|
||||
|
||||
Используется для фиксации моментов времени когда сигнал был обнаружен или потерян.
|
||||
"""
|
||||
|
||||
# Основные поля
|
||||
mark = models.BooleanField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Наличие сигнала",
|
||||
help_text="True - сигнал обнаружен, False - сигнал отсутствует",
|
||||
)
|
||||
timestamp = models.DateTimeField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Время",
|
||||
db_index=True,
|
||||
help_text="Время фиксации отметки",
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
if self.timestamp:
|
||||
timestamp = self.timestamp.strftime("%d.%m.%Y %H:%M")
|
||||
return f"+ {timestamp}" if self.mark else f"- {timestamp}"
|
||||
tech_name = self.tech_analyze.name if self.tech_analyze else "?"
|
||||
mark_str = "+" if self.mark else "-"
|
||||
return f"{tech_name}: {mark_str} {timestamp}"
|
||||
return "Отметка без времени"
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Отметка сигнала"
|
||||
verbose_name_plural = "Отметки сигналов"
|
||||
ordering = ["-timestamp"]
|
||||
indexes = [
|
||||
models.Index(fields=["tech_analyze", "-timestamp"]),
|
||||
]
|
||||
|
||||
|
||||
class Mirror(models.Model):
|
||||
"""
|
||||
Модель зеркала антенны.
|
||||
# Для обратной совместимости с SigmaParameter
|
||||
# class SigmaParMark(models.Model):
|
||||
# """
|
||||
# Модель отметки о наличии сигнала (для Sigma).
|
||||
|
||||
Представляет физическое зеркало антенны для приема спутникового сигнала.
|
||||
"""
|
||||
# Используется для фиксации моментов времени когда сигнал был обнаружен или потерян.
|
||||
# """
|
||||
|
||||
# Основные поля
|
||||
name = models.CharField(
|
||||
max_length=30,
|
||||
unique=True,
|
||||
verbose_name="Имя зеркала",
|
||||
db_index=True,
|
||||
help_text="Уникальное название зеркала антенны",
|
||||
)
|
||||
# # Основные поля
|
||||
# mark = models.BooleanField(
|
||||
# null=True,
|
||||
# blank=True,
|
||||
# verbose_name="Наличие сигнала",
|
||||
# help_text="True - сигнал обнаружен, False - сигнал отсутствует",
|
||||
# )
|
||||
# timestamp = models.DateTimeField(
|
||||
# null=True,
|
||||
# blank=True,
|
||||
# verbose_name="Время",
|
||||
# db_index=True,
|
||||
# help_text="Время фиксации отметки",
|
||||
# )
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Зеркало"
|
||||
verbose_name_plural = "Зеркала"
|
||||
ordering = ["name"]
|
||||
# def __str__(self):
|
||||
# if self.timestamp:
|
||||
# timestamp = self.timestamp.strftime("%d.%m.%Y %H:%M")
|
||||
# return f"+ {timestamp}" if self.mark else f"- {timestamp}"
|
||||
# return "Отметка без времени"
|
||||
|
||||
# class Meta:
|
||||
# verbose_name = "Отметка сигнала"
|
||||
# verbose_name_plural = "Отметки сигналов"
|
||||
# ordering = ["-timestamp"]
|
||||
|
||||
class Polarization(models.Model):
|
||||
"""
|
||||
@@ -290,7 +269,7 @@ class Standard(models.Model):
|
||||
|
||||
# Основные поля
|
||||
name = models.CharField(
|
||||
max_length=20,
|
||||
max_length=80,
|
||||
unique=True,
|
||||
verbose_name="Стандарт",
|
||||
db_index=True,
|
||||
@@ -335,7 +314,10 @@ class Satellite(models.Model):
|
||||
|
||||
Представляет спутник связи с его основными характеристиками.
|
||||
"""
|
||||
|
||||
PLACES = [
|
||||
("kr", "КР"),
|
||||
("dv", "ДВ")
|
||||
]
|
||||
# Основные поля
|
||||
name = models.CharField(
|
||||
max_length=100,
|
||||
@@ -344,12 +326,35 @@ class Satellite(models.Model):
|
||||
db_index=True,
|
||||
help_text="Название спутника",
|
||||
)
|
||||
alternative_name = models.CharField(
|
||||
max_length=100,
|
||||
blank=True,
|
||||
null=True,
|
||||
verbose_name="Альтернативное имя",
|
||||
db_index=True,
|
||||
help_text="Альтернативное название спутника",
|
||||
)
|
||||
location_place = models.CharField(
|
||||
max_length=30,
|
||||
choices=PLACES,
|
||||
null=True,
|
||||
default="kr",
|
||||
verbose_name="Комплекс",
|
||||
help_text="К какому комплексу принадлежит спутник",
|
||||
)
|
||||
norad = models.IntegerField(
|
||||
blank=True,
|
||||
null=True,
|
||||
verbose_name="NORAD ID",
|
||||
help_text="Идентификатор NORAD для отслеживания спутника",
|
||||
)
|
||||
international_code = models.CharField(
|
||||
max_length=50,
|
||||
blank=True,
|
||||
null=True,
|
||||
verbose_name="Международный код",
|
||||
help_text="Международный идентификатор спутника (например, 2011-074A)",
|
||||
)
|
||||
band = models.ManyToManyField(
|
||||
Band,
|
||||
related_name="bands",
|
||||
@@ -468,6 +473,123 @@ class ObjItemManager(models.Manager):
|
||||
return self.get_queryset().by_user(user)
|
||||
|
||||
|
||||
class TechAnalyze(models.Model):
|
||||
"""
|
||||
Модель технического анализа сигнала.
|
||||
|
||||
Хранит информацию о технических параметрах сигнала для анализа.
|
||||
"""
|
||||
|
||||
# Основные поля
|
||||
name = models.CharField(
|
||||
max_length=255,
|
||||
unique=True,
|
||||
verbose_name="Имя",
|
||||
db_index=True,
|
||||
help_text="Уникальное название для технического анализа",
|
||||
)
|
||||
satellite = models.ForeignKey(
|
||||
Satellite,
|
||||
on_delete=models.PROTECT,
|
||||
related_name="tech_analyzes",
|
||||
verbose_name="Спутник",
|
||||
help_text="Спутник, к которому относится анализ",
|
||||
)
|
||||
polarization = models.ForeignKey(
|
||||
Polarization,
|
||||
default=get_default_polarization,
|
||||
on_delete=models.SET_DEFAULT,
|
||||
related_name="tech_analyze_polarizations",
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Поляризация",
|
||||
)
|
||||
frequency = models.FloatField(
|
||||
default=0,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Частота, МГц",
|
||||
db_index=True,
|
||||
help_text="Центральная частота сигнала",
|
||||
)
|
||||
freq_range = models.FloatField(
|
||||
default=0,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Полоса частот, МГц",
|
||||
help_text="Полоса частот сигнала",
|
||||
)
|
||||
bod_velocity = models.FloatField(
|
||||
default=0,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Символьная скорость, БОД",
|
||||
help_text="Символьная скорость",
|
||||
)
|
||||
modulation = models.ForeignKey(
|
||||
Modulation,
|
||||
default=get_default_modulation,
|
||||
on_delete=models.SET_DEFAULT,
|
||||
related_name="tech_analyze_modulations",
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Модуляция",
|
||||
)
|
||||
standard = models.ForeignKey(
|
||||
Standard,
|
||||
default=get_default_standard,
|
||||
on_delete=models.SET_DEFAULT,
|
||||
related_name="tech_analyze_standards",
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Стандарт",
|
||||
)
|
||||
note = models.TextField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Примечание",
|
||||
help_text="Дополнительные примечания",
|
||||
)
|
||||
|
||||
# Метаданные
|
||||
created_at = models.DateTimeField(
|
||||
auto_now_add=True,
|
||||
verbose_name="Дата создания",
|
||||
help_text="Дата и время создания записи",
|
||||
)
|
||||
created_by = models.ForeignKey(
|
||||
CustomUser,
|
||||
on_delete=models.SET_NULL,
|
||||
related_name="tech_analyze_created",
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Создан пользователем",
|
||||
help_text="Пользователь, создавший запись",
|
||||
)
|
||||
updated_at = models.DateTimeField(
|
||||
auto_now=True,
|
||||
verbose_name="Дата последнего изменения",
|
||||
help_text="Дата и время последнего изменения",
|
||||
)
|
||||
updated_by = models.ForeignKey(
|
||||
CustomUser,
|
||||
on_delete=models.SET_NULL,
|
||||
related_name="tech_analyze_updated",
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Изменен пользователем",
|
||||
help_text="Пользователь, последним изменивший запись",
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.name} ({self.satellite.name if self.satellite else '-'})"
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Тех. анализ"
|
||||
verbose_name_plural = "Тех. анализы"
|
||||
ordering = ["-created_at"]
|
||||
|
||||
|
||||
class Source(models.Model):
|
||||
"""
|
||||
Модель источника сигнала.
|
||||
@@ -491,6 +613,12 @@ class Source(models.Model):
|
||||
verbose_name="Принадлежность объекта",
|
||||
help_text="Принадлежность объекта (страна, организация и т.д.)",
|
||||
)
|
||||
note = models.TextField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name="Примечание",
|
||||
help_text="Дополнительное описание объекта",
|
||||
)
|
||||
confirm_at = models.DateTimeField(
|
||||
null=True,
|
||||
blank=True,
|
||||
@@ -616,16 +744,6 @@ class Source(models.Model):
|
||||
if last_objitem:
|
||||
self.confirm_at = last_objitem.created_at
|
||||
|
||||
def update_last_signal_at(self):
|
||||
"""
|
||||
Обновляет дату last_signal_at на дату последней отметки о наличии сигнала (mark=True).
|
||||
"""
|
||||
last_signal_mark = self.marks.filter(mark=True).order_by('-timestamp').first()
|
||||
if last_signal_mark:
|
||||
self.last_signal_at = last_signal_mark.timestamp
|
||||
else:
|
||||
self.last_signal_at = None
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
"""
|
||||
Переопределенный метод save для автоматического обновления coords_average
|
||||
@@ -728,6 +846,12 @@ class ObjItem(models.Model):
|
||||
verbose_name="Транспондер",
|
||||
help_text="Транспондер, с помощью которого была получена точка",
|
||||
)
|
||||
is_automatic = models.BooleanField(
|
||||
default=False,
|
||||
verbose_name="Автоматическая",
|
||||
db_index=True,
|
||||
help_text="Если True, точка не добавляется к объектам (Source), а хранится отдельно",
|
||||
)
|
||||
|
||||
# Метаданные
|
||||
created_at = models.DateTimeField(
|
||||
@@ -1027,7 +1151,7 @@ class SigmaParameter(models.Model):
|
||||
verbose_name="Время окончания измерения",
|
||||
help_text="Дата и время окончания измерения",
|
||||
)
|
||||
mark = models.ManyToManyField(SigmaParMark, verbose_name="Отметка", blank=True)
|
||||
# mark = models.ManyToManyField(SigmaParMark, verbose_name="Отметка", blank=True)
|
||||
parameter = models.ForeignKey(
|
||||
Parameter,
|
||||
on_delete=models.SET_NULL,
|
||||
@@ -1064,6 +1188,299 @@ class SigmaParameter(models.Model):
|
||||
verbose_name_plural = "ВЧ sigma"
|
||||
|
||||
|
||||
class SourceRequest(models.Model):
|
||||
"""
|
||||
Модель заявки на источник.
|
||||
|
||||
Хранит информацию о заявках на обработку источников с различными статусами.
|
||||
"""
|
||||
|
||||
STATUS_CHOICES = [
|
||||
('planned', 'Запланировано'),
|
||||
('canceled_gso', 'Отменено ГСО'),
|
||||
('canceled_kub', 'Отменено МКА'),
|
||||
('conducted', 'Проведён'),
|
||||
('successful', 'Успешно'),
|
||||
('no_correlation', 'Нет корреляции'),
|
||||
('no_signal', 'Нет сигнала в спектре'),
|
||||
('unsuccessful', 'Неуспешно'),
|
||||
('downloading', 'Скачивание'),
|
||||
('processing', 'Обработка'),
|
||||
('result_received', 'Результат получен'),
|
||||
]
|
||||
|
||||
PRIORITY_CHOICES = [
|
||||
('low', 'Низкий'),
|
||||
('medium', 'Средний'),
|
||||
('high', 'Высокий'),
|
||||
]
|
||||
|
||||
# Связь с источником (опционально для заявок без привязки)
|
||||
source = models.ForeignKey(
|
||||
Source,
|
||||
on_delete=models.CASCADE,
|
||||
related_name='source_requests',
|
||||
verbose_name='Источник',
|
||||
null=True,
|
||||
blank=True,
|
||||
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(
|
||||
max_length=20,
|
||||
choices=STATUS_CHOICES,
|
||||
default='planned',
|
||||
verbose_name='Статус',
|
||||
db_index=True,
|
||||
help_text='Текущий статус заявки',
|
||||
)
|
||||
priority = models.CharField(
|
||||
max_length=10,
|
||||
choices=PRIORITY_CHOICES,
|
||||
default='medium',
|
||||
verbose_name='Приоритет',
|
||||
db_index=True,
|
||||
help_text='Приоритет заявки',
|
||||
)
|
||||
|
||||
# Даты
|
||||
planned_at = models.DateTimeField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Дата и время планирования',
|
||||
help_text='Запланированная дата и время',
|
||||
)
|
||||
request_date = models.DateField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Дата заявки',
|
||||
help_text='Дата подачи заявки',
|
||||
)
|
||||
card_date = models.DateField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Дата формирования карточки',
|
||||
help_text='Дата формирования карточки',
|
||||
)
|
||||
status_updated_at = models.DateTimeField(
|
||||
auto_now=True,
|
||||
verbose_name='Дата обновления статуса',
|
||||
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(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='ГСО успешно?',
|
||||
help_text='Успешность ГСО',
|
||||
)
|
||||
kubsat_success = models.BooleanField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Кубсат успешно?',
|
||||
help_text='Успешность Кубсат',
|
||||
)
|
||||
|
||||
# Район
|
||||
region = models.CharField(
|
||||
max_length=255,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Район',
|
||||
help_text='Район/местоположение',
|
||||
)
|
||||
|
||||
# Комментарий
|
||||
comment = models.TextField(
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Комментарий',
|
||||
help_text='Дополнительные комментарии к заявке',
|
||||
)
|
||||
|
||||
# Координаты ГСО (усреднённые по выбранным точкам)
|
||||
coords = gis.PointField(
|
||||
srid=4326,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Координаты ГСО',
|
||||
help_text='Координаты ГСО (WGS84)',
|
||||
)
|
||||
|
||||
# Координаты источника
|
||||
coords_source = gis.PointField(
|
||||
srid=4326,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Координаты источника',
|
||||
help_text='Координаты источника (WGS84)',
|
||||
)
|
||||
|
||||
# Координаты объекта
|
||||
coords_object = gis.PointField(
|
||||
srid=4326,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Координаты объекта',
|
||||
help_text='Координаты объекта (WGS84)',
|
||||
)
|
||||
|
||||
# Количество точек, использованных для расчёта координат
|
||||
points_count = models.PositiveIntegerField(
|
||||
default=0,
|
||||
verbose_name='Количество точек',
|
||||
help_text='Количество точек ГЛ, использованных для расчёта координат',
|
||||
)
|
||||
|
||||
# Метаданные
|
||||
created_at = models.DateTimeField(
|
||||
auto_now_add=True,
|
||||
verbose_name='Дата создания',
|
||||
help_text='Дата и время создания записи',
|
||||
)
|
||||
created_by = models.ForeignKey(
|
||||
CustomUser,
|
||||
on_delete=models.SET_NULL,
|
||||
related_name='source_requests_created',
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Создан пользователем',
|
||||
help_text='Пользователь, создавший запись',
|
||||
)
|
||||
updated_by = models.ForeignKey(
|
||||
CustomUser,
|
||||
on_delete=models.SET_NULL,
|
||||
related_name='source_requests_updated',
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Изменен пользователем',
|
||||
help_text='Пользователь, последним изменивший запись',
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return f"Заявка #{self.pk} - {self.source_id} ({self.get_status_display()})"
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
# Определяем, изменился ли статус
|
||||
old_status = None
|
||||
if self.pk:
|
||||
try:
|
||||
old_instance = SourceRequest.objects.get(pk=self.pk)
|
||||
old_status = old_instance.status
|
||||
except SourceRequest.DoesNotExist:
|
||||
pass
|
||||
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
# Если статус изменился, создаем запись в истории
|
||||
if old_status is not None and old_status != self.status:
|
||||
SourceRequestStatusHistory.objects.create(
|
||||
source_request=self,
|
||||
old_status=old_status,
|
||||
new_status=self.status,
|
||||
changed_by=self.updated_by,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'Заявка на источник'
|
||||
verbose_name_plural = 'Заявки на источники'
|
||||
ordering = ['-created_at']
|
||||
indexes = [
|
||||
models.Index(fields=['-created_at']),
|
||||
models.Index(fields=['status']),
|
||||
models.Index(fields=['priority']),
|
||||
models.Index(fields=['source', '-created_at']),
|
||||
]
|
||||
|
||||
|
||||
class SourceRequestStatusHistory(models.Model):
|
||||
"""
|
||||
Модель истории изменений статусов заявок.
|
||||
|
||||
Хранит полную хронологию изменений статусов заявок.
|
||||
"""
|
||||
|
||||
source_request = models.ForeignKey(
|
||||
SourceRequest,
|
||||
on_delete=models.CASCADE,
|
||||
related_name='status_history',
|
||||
verbose_name='Заявка',
|
||||
help_text='Связанная заявка',
|
||||
)
|
||||
old_status = models.CharField(
|
||||
max_length=20,
|
||||
choices=SourceRequest.STATUS_CHOICES,
|
||||
verbose_name='Старый статус',
|
||||
help_text='Статус до изменения',
|
||||
)
|
||||
new_status = models.CharField(
|
||||
max_length=20,
|
||||
choices=SourceRequest.STATUS_CHOICES,
|
||||
verbose_name='Новый статус',
|
||||
help_text='Статус после изменения',
|
||||
)
|
||||
changed_at = models.DateTimeField(
|
||||
auto_now_add=True,
|
||||
verbose_name='Дата изменения',
|
||||
db_index=True,
|
||||
help_text='Дата и время изменения статуса',
|
||||
)
|
||||
changed_by = models.ForeignKey(
|
||||
CustomUser,
|
||||
on_delete=models.SET_NULL,
|
||||
related_name='status_changes',
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name='Изменен пользователем',
|
||||
help_text='Пользователь, изменивший статус',
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.source_request_id}: {self.get_old_status_display()} → {self.get_new_status_display()}"
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'История статуса заявки'
|
||||
verbose_name_plural = 'История статусов заявок'
|
||||
ordering = ['-changed_at']
|
||||
indexes = [
|
||||
models.Index(fields=['-changed_at']),
|
||||
models.Index(fields=['source_request', '-changed_at']),
|
||||
]
|
||||
|
||||
|
||||
class Geo(models.Model):
|
||||
"""
|
||||
Модель геолокационных данных.
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
# Django imports
|
||||
from django.contrib.auth.models import User
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
# from django.contrib.auth.models import User
|
||||
# from django.db.models.signals import post_save
|
||||
# from django.dispatch import receiver
|
||||
|
||||
# Local imports
|
||||
from .models import CustomUser
|
||||
# # Local imports
|
||||
# from .models import CustomUser
|
||||
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
def create_or_update_user_profile(sender, instance, created, **kwargs):
|
||||
if created:
|
||||
CustomUser.objects.create(user=instance)
|
||||
instance.customuser.save()
|
||||
# @receiver(post_save, sender=User)
|
||||
# def create_or_update_user_profile(sender, instance, created, **kwargs):
|
||||
# if created:
|
||||
# CustomUser.objects.get_or_create(user=instance)
|
||||
# else:
|
||||
# # Only save if customuser exists (avoid error if it doesn't)
|
||||
# if hasattr(instance, 'customuser'):
|
||||
# instance.customuser.save()
|
||||
@@ -6,7 +6,7 @@
|
||||
.multiselect-input-container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
min-height: 38px;
|
||||
border: 1px solid #ced4da;
|
||||
border-radius: 0.25rem;
|
||||
@@ -27,7 +27,8 @@
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
flex: 0 0 auto;
|
||||
flex: 1 1 auto;
|
||||
max-width: calc(100% - 150px);
|
||||
}
|
||||
|
||||
.multiselect-tag {
|
||||
|
||||
@@ -79,26 +79,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Transponders Card -->
|
||||
<div class="col-lg-6">
|
||||
<div class="card h-100 shadow-sm border-0">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="bg-warning bg-opacity-10 rounded-circle p-2 me-3">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-wifi text-warning" viewBox="0 0 16 16">
|
||||
<path d="M6.002 3.5a5.5 5.5 0 1 1 3.996 9.5H10A5.5 5.5 0 0 1 6.002 3.5M6.002 5.5a3.5 3.5 0 1 0 3.996 5.5H10A3.5 3.5 0 0 0 6.002 5.5"/>
|
||||
<path d="M10.5 12.5a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5.5.5 0 0 0-1 0 .5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5.5.5 0 0 0-1 0 .5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5 3.5 3.5 0 0 1 7 0"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 class="card-title mb-0">Добавление транспондеров</h3>
|
||||
</div>
|
||||
<p class="card-text">Добавьте список транспондеров в базу данных.</p>
|
||||
<a href="{% url 'mainapp:add_trans' %}" class="btn btn-warning">
|
||||
Добавить транспондеры
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- VCH Load Data Card -->
|
||||
<div class="col-lg-6">
|
||||
|
||||
@@ -19,6 +19,19 @@
|
||||
<!-- Form fields with Bootstrap styling -->
|
||||
{% include 'mainapp/components/_form_field.html' with field=form.file %}
|
||||
|
||||
<!-- Automatic checkbox -->
|
||||
<div class="mb-3">
|
||||
<div class="form-check">
|
||||
{{ form.is_automatic }}
|
||||
<label class="form-check-label" for="{{ form.is_automatic.id_for_label }}">
|
||||
{{ form.is_automatic.label }}
|
||||
</label>
|
||||
{% if form.is_automatic.help_text %}
|
||||
<div class="form-text">{{ form.is_automatic.help_text }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
|
||||
<a href="{% url 'mainapp:source_list' %}" class="btn btn-secondary me-md-2">Назад</a>
|
||||
<button type="submit" class="btn btn-success">Добавить в базу</button>
|
||||
|
||||
@@ -21,6 +21,19 @@
|
||||
{% include 'mainapp/components/_form_field.html' with field=form.sat_choice %}
|
||||
{% include 'mainapp/components/_form_field.html' with field=form.number_input %}
|
||||
|
||||
<!-- Automatic checkbox -->
|
||||
<div class="mb-3">
|
||||
<div class="form-check">
|
||||
{{ form.is_automatic }}
|
||||
<label class="form-check-label" for="{{ form.is_automatic.id_for_label }}">
|
||||
{{ form.is_automatic.label }}
|
||||
</label>
|
||||
{% if form.is_automatic.help_text %}
|
||||
<div class="form-text">{{ form.is_automatic.help_text }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
|
||||
<a href="{% url 'mainapp:source_list' %}" class="btn btn-secondary me-md-2">Назад</a>
|
||||
<button type="submit" class="btn btn-primary">Добавить в базу</button>
|
||||
|
||||
@@ -40,7 +40,6 @@
|
||||
{% include 'mainapp/components/_column_toggle_item.html' with column_index=18 column_label="Усреднённое" checked=False %}
|
||||
{% include 'mainapp/components/_column_toggle_item.html' with column_index=19 column_label="Стандарт" checked=False %}
|
||||
{% include 'mainapp/components/_column_toggle_item.html' with column_index=20 column_label="Тип источника" checked=True %}
|
||||
{% include 'mainapp/components/_column_toggle_item.html' with column_index=21 column_label="Sigma" checked=True %}
|
||||
{% include 'mainapp/components/_column_toggle_item.html' with column_index=22 column_label="Зеркала" checked=True %}
|
||||
{% include 'mainapp/components/_column_toggle_item.html' with column_index=21 column_label="Зеркала" checked=True %}
|
||||
</ul>
|
||||
</div>
|
||||
@@ -0,0 +1,71 @@
|
||||
<!-- Frequency Plan Modal -->
|
||||
<div class="modal fade" id="frequencyPlanModal" tabindex="-1" aria-labelledby="frequencyPlanModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-xl">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="frequencyPlanModalLabel">Частотный план</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="modalLoadingSpinner" class="text-center py-5">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Загрузка...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="modalFrequencyContent" style="display: none;">
|
||||
<p class="text-muted">Визуализация транспондеров спутника по частотам. <span style="color: #0d6efd;">■</span> Downlink (синий), <span style="color: #fd7e14;">■</span> Uplink (оранжевый). Используйте колесико мыши для масштабирования, наведите курсор на полосу для подробной информации и связи с парным каналом.</p>
|
||||
|
||||
<div class="frequency-plan">
|
||||
<div class="chart-controls">
|
||||
<button type="button" class="btn btn-sm btn-outline-primary" id="modalResetZoom">
|
||||
<i class="bi bi-arrow-clockwise"></i> Сбросить масштаб
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="frequency-chart-container">
|
||||
<canvas id="modalFrequencyChart"></canvas>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<p><strong>Всего транспондеров:</strong> <span id="modalTransponderCount">0</span></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="modalNoData" style="display: none;" class="text-center text-muted py-5">
|
||||
<p>Нет данных о транспондерах для этого спутника</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.frequency-plan {
|
||||
padding: 20px;
|
||||
background-color: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.frequency-chart-container {
|
||||
position: relative;
|
||||
background: white;
|
||||
border: 1px solid #dee2e6;
|
||||
border-radius: 4px;
|
||||
padding: 20px;
|
||||
height: 400px;
|
||||
}
|
||||
|
||||
.chart-controls {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 15px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.chart-controls button {
|
||||
padding: 5px 15px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,833 @@
|
||||
{% load l10n %}
|
||||
<!-- Вкладка фильтров и экспорта -->
|
||||
<form method="get" id="filterForm" class="mb-4">
|
||||
<input type="hidden" name="tab" value="filters">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0">Фильтры</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<!-- Спутники -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="{{ form.satellites.id_for_label }}" class="form-label">{{ form.satellites.label }}</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('satellites', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('satellites', false)">Снять</button>
|
||||
</div>
|
||||
{{ form.satellites }}
|
||||
<small class="form-text text-muted">Удерживайте Ctrl для выбора нескольких</small>
|
||||
</div>
|
||||
|
||||
<!-- Полоса спутника -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="{{ form.band.id_for_label }}" class="form-label">{{ form.band.label }}</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('band', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('band', false)">Снять</button>
|
||||
</div>
|
||||
{{ form.band }}
|
||||
<small class="form-text text-muted">Удерживайте Ctrl для выбора нескольких</small>
|
||||
</div>
|
||||
|
||||
<!-- Поляризация -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="{{ form.polarization.id_for_label }}" class="form-label">{{ form.polarization.label }}</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('polarization', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('polarization', false)">Снять</button>
|
||||
</div>
|
||||
{{ form.polarization }}
|
||||
<small class="form-text text-muted">Удерживайте Ctrl для выбора нескольких</small>
|
||||
</div>
|
||||
|
||||
<!-- Модуляция -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="{{ form.modulation.id_for_label }}" class="form-label">{{ form.modulation.label }}</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('modulation', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('modulation', false)">Снять</button>
|
||||
</div>
|
||||
{{ form.modulation }}
|
||||
<small class="form-text text-muted">Удерживайте Ctrl для выбора нескольких</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- Центральная частота -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label class="form-label">Центральная частота (МГц)</label>
|
||||
<div class="input-group">
|
||||
{{ form.frequency_min }}
|
||||
<span class="input-group-text">—</span>
|
||||
{{ form.frequency_max }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Полоса -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label class="form-label">Полоса (МГц)</label>
|
||||
<div class="input-group">
|
||||
{{ form.freq_range_min }}
|
||||
<span class="input-group-text">—</span>
|
||||
{{ form.freq_range_max }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Тип объекта -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="{{ form.object_type.id_for_label }}" class="form-label">{{ form.object_type.label }}</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('object_type', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('object_type', false)">Снять</button>
|
||||
</div>
|
||||
{{ form.object_type }}
|
||||
<small class="form-text text-muted">Удерживайте Ctrl для выбора нескольких</small>
|
||||
</div>
|
||||
|
||||
<!-- Принадлежность объекта -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="{{ form.object_ownership.id_for_label }}" class="form-label">{{ form.object_ownership.label }}</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('object_ownership', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('object_ownership', false)">Снять</button>
|
||||
</div>
|
||||
{{ form.object_ownership }}
|
||||
<small class="form-text text-muted">Удерживайте Ctrl для выбора нескольких</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- Количество ObjItem -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label class="form-label">Количество привязанных точек ГЛ</label>
|
||||
<div class="input-group mb-2">
|
||||
{{ form.objitem_count_min }}
|
||||
</div>
|
||||
<div class="input-group">
|
||||
{{ form.objitem_count_max }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Планы на Кубсат -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label class="form-label">{{ form.has_plans.label }}</label>
|
||||
<div>
|
||||
{% for radio in form.has_plans %}
|
||||
<div class="form-check">
|
||||
{{ radio.tag }}
|
||||
<label class="form-check-label" for="{{ radio.id_for_label }}">
|
||||
{{ radio.choice_label }}
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ГСО успешно -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label class="form-label">{{ form.success_1.label }}</label>
|
||||
<div>
|
||||
{% for radio in form.success_1 %}
|
||||
<div class="form-check">
|
||||
{{ radio.tag }}
|
||||
<label class="form-check-label" for="{{ radio.id_for_label }}">
|
||||
{{ radio.choice_label }}
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Кубсат успешно -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label class="form-label">{{ form.success_2.label }}</label>
|
||||
<div>
|
||||
{% for radio in form.success_2 %}
|
||||
<div class="form-check">
|
||||
{{ radio.tag }}
|
||||
<label class="form-check-label" for="{{ radio.id_for_label }}">
|
||||
{{ radio.choice_label }}
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- Диапазон дат -->
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Диапазон дат ГЛ:</label>
|
||||
<div class="input-group">
|
||||
{{ form.date_from }}
|
||||
<span class="input-group-text">—</span>
|
||||
{{ form.date_to }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<button type="submit" class="btn btn-primary">Применить фильтры</button>
|
||||
<a href="{% url 'mainapp:kubsat' %}" class="btn btn-secondary">Сбросить</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- Кнопка экспорта и статистика -->
|
||||
{% if sources_with_date_info %}
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="d-flex flex-wrap align-items-center gap-3">
|
||||
<!-- Поиск по имени точки -->
|
||||
<div class="input-group" style="max-width: 350px;">
|
||||
<input type="text" id="searchObjitemName" class="form-control"
|
||||
placeholder="Поиск по имени точки..."
|
||||
oninput="filterTableByName()">
|
||||
<button type="button" class="btn btn-outline-secondary" onclick="clearSearch()">
|
||||
<i class="bi bi-x-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" class="btn btn-success" onclick="exportToExcel()">
|
||||
<i class="bi bi-file-earmark-excel"></i> Экспорт в Excel
|
||||
</button>
|
||||
<button type="button" class="btn btn-primary" onclick="createRequestsFromTable()">
|
||||
<i class="bi bi-plus-circle"></i> Создать заявки
|
||||
</button>
|
||||
<span class="text-muted" id="statsCounter">
|
||||
Найдено объектов: {{ sources_with_date_info|length }},
|
||||
точек: {% for source_data in sources_with_date_info %}{{ source_data.objitems_data|length }}{% if not forloop.last %}+{% endif %}{% endfor %}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- Таблица результатов -->
|
||||
{% if sources_with_date_info %}
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body p-0">
|
||||
<div class="table-responsive" style="max-height: 60vh; overflow-y: auto;">
|
||||
<table class="table table-striped table-hover table-sm table-bordered" style="font-size: 0.85rem;" id="resultsTable">
|
||||
<thead class="table-dark sticky-top">
|
||||
<tr>
|
||||
<th style="min-width: 80px;">ID объекта</th>
|
||||
<th style="min-width: 120px;">Тип объекта</th>
|
||||
<th style="min-width: 150px;">Принадлежность объекта</th>
|
||||
<th class="text-center" style="min-width: 60px;" title="Всего заявок">Заявки</th>
|
||||
<th class="text-center" style="min-width: 80px;">ГСО</th>
|
||||
<th class="text-center" style="min-width: 80px;">Кубсат</th>
|
||||
<th class="text-center" style="min-width: 100px;">Статус заявки</th>
|
||||
<th class="text-center" style="min-width: 100px;">Кол-во точек</th>
|
||||
<th style="min-width: 150px;">Усреднённая координата</th>
|
||||
<th style="min-width: 120px;">Имя точки</th>
|
||||
<th style="min-width: 150px;">Спутник</th>
|
||||
<th style="min-width: 100px;">Частота (МГц)</th>
|
||||
<th style="min-width: 100px;">Полоса (МГц)</th>
|
||||
<th style="min-width: 100px;">Поляризация</th>
|
||||
<th style="min-width: 100px;">Модуляция</th>
|
||||
<th style="min-width: 150px;">Координаты ГЛ</th>
|
||||
<th style="min-width: 100px;">Дата ГЛ</th>
|
||||
<th style="min-width: 150px;">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for source_data in sources_with_date_info %}
|
||||
{% for objitem_data in source_data.objitems_data %}
|
||||
<tr data-source-id="{{ source_data.source.id }}"
|
||||
data-objitem-id="{{ objitem_data.objitem.id }}"
|
||||
data-objitem-name="{{ objitem_data.objitem.name|default:'' }}"
|
||||
data-matches-date="{{ objitem_data.matches_date|yesno:'true,false' }}"
|
||||
data-is-first-in-source="{% if forloop.first %}true{% else %}false{% endif %}"
|
||||
data-lat="{% if objitem_data.objitem.geo_obj and objitem_data.objitem.geo_obj.coords %}{{ objitem_data.objitem.geo_obj.coords.y }}{% endif %}"
|
||||
data-lon="{% if objitem_data.objitem.geo_obj and objitem_data.objitem.geo_obj.coords %}{{ objitem_data.objitem.geo_obj.coords.x }}{% endif %}">
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="source-id-cell">{{ source_data.source.id }}</td>
|
||||
{% endif %}
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="source-type-cell">{{ source_data.source.info.name|default:"-" }}</td>
|
||||
{% endif %}
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="source-ownership-cell">
|
||||
{% if source_data.source.ownership %}
|
||||
{% if source_data.source.ownership.name == "ТВ" and source_data.has_lyngsat %}
|
||||
<a href="#" class="text-primary text-decoration-none"
|
||||
onclick="showLyngsatModal({{ source_data.lyngsat_id }}); return false;">
|
||||
<i class="bi bi-tv"></i> {{ source_data.source.ownership.name }}
|
||||
</a>
|
||||
{% else %}
|
||||
{{ source_data.source.ownership.name }}
|
||||
{% endif %}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="text-center source-requests-count-cell">
|
||||
{% if source_data.requests_count > 0 %}
|
||||
<span class="badge bg-info">{{ source_data.requests_count }}</span>
|
||||
{% else %}
|
||||
<span class="text-muted">0</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="text-center source-gso-cell">
|
||||
{% if source_data.gso_success == True %}
|
||||
<span class="badge bg-success"><i class="bi bi-check-lg"></i></span>
|
||||
{% elif source_data.gso_success == False %}
|
||||
<span class="badge bg-danger"><i class="bi bi-x-lg"></i></span>
|
||||
{% else %}
|
||||
<span class="text-muted">-</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="text-center source-kubsat-cell">
|
||||
{% if source_data.kubsat_success == True %}
|
||||
<span class="badge bg-success"><i class="bi bi-check-lg"></i></span>
|
||||
{% elif source_data.kubsat_success == False %}
|
||||
<span class="badge bg-danger"><i class="bi bi-x-lg"></i></span>
|
||||
{% else %}
|
||||
<span class="text-muted">-</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="text-center source-status-cell">
|
||||
{% if source_data.request_status %}
|
||||
{% if source_data.request_status_raw == 'successful' or source_data.request_status_raw == 'result_received' %}
|
||||
<span class="badge bg-success">{{ source_data.request_status }}</span>
|
||||
{% elif source_data.request_status_raw == 'unsuccessful' or source_data.request_status_raw == 'no_correlation' or source_data.request_status_raw == 'no_signal' %}
|
||||
<span class="badge bg-danger">{{ source_data.request_status }}</span>
|
||||
{% elif source_data.request_status_raw == 'planned' %}
|
||||
<span class="badge bg-primary">{{ source_data.request_status }}</span>
|
||||
{% elif source_data.request_status_raw == 'downloading' or source_data.request_status_raw == 'processing' %}
|
||||
<span class="badge bg-warning text-dark">{{ source_data.request_status }}</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary">{{ source_data.request_status }}</span>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<span class="text-muted">-</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="text-center source-count-cell" data-initial-count="{{ source_data.objitems_data|length }}">{{ source_data.objitems_data|length }}</td>
|
||||
{% endif %}
|
||||
|
||||
{% if forloop.first %}
|
||||
<td rowspan="{{ source_data.objitems_data|length }}" class="source-avg-coords-cell"
|
||||
data-avg-lat="{{ source_data.avg_lat|default:''|unlocalize }}"
|
||||
data-avg-lon="{{ source_data.avg_lon|default:''|unlocalize }}">
|
||||
{% if source_data.avg_lat and source_data.avg_lon %}
|
||||
{{ source_data.avg_lat|floatformat:6|unlocalize }}, {{ source_data.avg_lon|floatformat:6|unlocalize }}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
|
||||
<td>{{ objitem_data.objitem.name|default:"-" }}</td>
|
||||
|
||||
<td>
|
||||
{% if objitem_data.objitem.parameter_obj and objitem_data.objitem.parameter_obj.id_satellite %}
|
||||
{{ objitem_data.objitem.parameter_obj.id_satellite.name }}
|
||||
{% if objitem_data.objitem.parameter_obj.id_satellite.norad %}
|
||||
({{ objitem_data.objitem.parameter_obj.id_satellite.norad }})
|
||||
{% endif %}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
{% if objitem_data.objitem.parameter_obj %}
|
||||
{{ objitem_data.objitem.parameter_obj.frequency|default:"-"|floatformat:3 }}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
{% if objitem_data.objitem.parameter_obj %}
|
||||
{{ objitem_data.objitem.parameter_obj.freq_range|default:"-"|floatformat:3 }}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
{% if objitem_data.objitem.parameter_obj and objitem_data.objitem.parameter_obj.polarization %}
|
||||
{{ objitem_data.objitem.parameter_obj.polarization.name }}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
{% if objitem_data.objitem.parameter_obj and objitem_data.objitem.parameter_obj.modulation %}
|
||||
{{ objitem_data.objitem.parameter_obj.modulation.name }}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
{% if objitem_data.objitem.geo_obj and objitem_data.objitem.geo_obj.coords %}
|
||||
{{ objitem_data.objitem.geo_obj.coords.y|floatformat:6|unlocalize }}, {{ objitem_data.objitem.geo_obj.coords.x|floatformat:6|unlocalize }}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
{% if objitem_data.geo_date %}
|
||||
{{ objitem_data.geo_date|date:"d.m.Y" }}
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<div class="btn-group" role="group">
|
||||
<button type="button" class="btn btn-sm btn-danger" onclick="removeObjItem(this)" title="Удалить точку">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
{% if forloop.first %}
|
||||
<button type="button" class="btn btn-sm btn-warning" onclick="removeSource(this)" title="Удалить весь объект">
|
||||
<i class="bi bi-trash-fill"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% elif request.GET %}
|
||||
<div class="alert alert-info">
|
||||
По заданным критериям ничего не найдено.
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<script>
|
||||
// Функция для пересчёта усреднённых координат источника через Python API
|
||||
// Координаты рассчитываются на сервере с сортировкой по дате ГЛ
|
||||
function recalculateAverageCoords(sourceId) {
|
||||
const sourceRows = Array.from(document.querySelectorAll(`tr[data-source-id="${sourceId}"]`));
|
||||
if (sourceRows.length === 0) return;
|
||||
|
||||
// Собираем ID всех оставшихся точек для этого источника
|
||||
const objitemIds = sourceRows.map(row => row.dataset.objitemId).filter(id => id);
|
||||
|
||||
if (objitemIds.length === 0) {
|
||||
// Нет точек - очищаем координаты
|
||||
updateAvgCoordsCell(sourceId, null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Вызываем Python API для пересчёта координат
|
||||
const formData = new FormData();
|
||||
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
|
||||
if (csrfToken) {
|
||||
formData.append('csrfmiddlewaretoken', csrfToken.value);
|
||||
}
|
||||
objitemIds.forEach(id => formData.append('objitem_ids', id));
|
||||
|
||||
fetch('{% url "mainapp:kubsat_recalculate_coords" %}', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken ? csrfToken.value : ''
|
||||
},
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(result => {
|
||||
if (result.success && result.results[sourceId]) {
|
||||
const coords = result.results[sourceId];
|
||||
updateAvgCoordsCell(sourceId, coords.avg_lat, coords.avg_lon);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error recalculating coords:', error);
|
||||
});
|
||||
}
|
||||
|
||||
// Обновляет ячейку с усреднёнными координатами
|
||||
function updateAvgCoordsCell(sourceId, avgLat, avgLon) {
|
||||
const sourceRows = Array.from(document.querySelectorAll(`tr[data-source-id="${sourceId}"]`));
|
||||
if (sourceRows.length === 0) return;
|
||||
|
||||
const firstRow = sourceRows[0];
|
||||
const avgCoordsCell = firstRow.querySelector('.source-avg-coords-cell');
|
||||
if (avgCoordsCell) {
|
||||
if (avgLat !== null && avgLon !== null) {
|
||||
avgCoordsCell.textContent = `${avgLat.toFixed(6)}, ${avgLon.toFixed(6)}`;
|
||||
avgCoordsCell.dataset.avgLat = avgLat;
|
||||
avgCoordsCell.dataset.avgLon = avgLon;
|
||||
} else {
|
||||
avgCoordsCell.textContent = '-';
|
||||
avgCoordsCell.dataset.avgLat = '';
|
||||
avgCoordsCell.dataset.avgLon = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeObjItem(button) {
|
||||
const row = button.closest('tr');
|
||||
const sourceId = row.dataset.sourceId;
|
||||
const isFirstInSource = row.dataset.isFirstInSource === 'true';
|
||||
const sourceRows = Array.from(document.querySelectorAll(`tr[data-source-id="${sourceId}"]`));
|
||||
|
||||
// All rowspan cells that need to be handled
|
||||
const rowspanCellClasses = [
|
||||
'.source-id-cell', '.source-type-cell', '.source-ownership-cell', '.source-requests-count-cell',
|
||||
'.source-gso-cell', '.source-kubsat-cell', '.source-status-cell', '.source-count-cell', '.source-avg-coords-cell'
|
||||
];
|
||||
|
||||
if (sourceRows.length === 1) {
|
||||
row.remove();
|
||||
} else if (isFirstInSource) {
|
||||
const nextRow = sourceRows[1];
|
||||
const cells = rowspanCellClasses.map(cls => row.querySelector(cls)).filter(c => c);
|
||||
|
||||
if (cells.length > 0) {
|
||||
const currentRowspan = parseInt(cells[0].getAttribute('rowspan'));
|
||||
const newRowspan = currentRowspan - 1;
|
||||
|
||||
// Clone and update all rowspan cells
|
||||
const newCells = cells.map(cell => {
|
||||
const newCell = cell.cloneNode(true);
|
||||
newCell.setAttribute('rowspan', newRowspan);
|
||||
if (newCell.classList.contains('source-count-cell')) {
|
||||
newCell.textContent = newRowspan;
|
||||
}
|
||||
return newCell;
|
||||
});
|
||||
|
||||
// Insert cells in reverse order to maintain correct order
|
||||
newCells.reverse().forEach(cell => {
|
||||
nextRow.insertBefore(cell, nextRow.firstChild);
|
||||
});
|
||||
|
||||
const actionsCell = nextRow.querySelector('td:last-child');
|
||||
if (actionsCell) {
|
||||
const btnGroup = actionsCell.querySelector('.btn-group');
|
||||
if (btnGroup && btnGroup.children.length === 1) {
|
||||
const deleteSourceBtn = document.createElement('button');
|
||||
deleteSourceBtn.type = 'button';
|
||||
deleteSourceBtn.className = 'btn btn-sm btn-warning';
|
||||
deleteSourceBtn.onclick = function() { removeSource(this); };
|
||||
deleteSourceBtn.title = 'Удалить весь объект';
|
||||
deleteSourceBtn.innerHTML = '<i class="bi bi-trash-fill"></i>';
|
||||
btnGroup.appendChild(deleteSourceBtn);
|
||||
}
|
||||
}
|
||||
}
|
||||
nextRow.dataset.isFirstInSource = 'true';
|
||||
row.remove();
|
||||
// Пересчитываем усреднённые координаты после удаления точки
|
||||
recalculateAverageCoords(sourceId);
|
||||
} else {
|
||||
const firstRow = sourceRows[0];
|
||||
const cells = rowspanCellClasses.map(cls => firstRow.querySelector(cls)).filter(c => c);
|
||||
|
||||
if (cells.length > 0) {
|
||||
const currentRowspan = parseInt(cells[0].getAttribute('rowspan'));
|
||||
const newRowspan = currentRowspan - 1;
|
||||
|
||||
cells.forEach(cell => {
|
||||
cell.setAttribute('rowspan', newRowspan);
|
||||
if (cell.classList.contains('source-count-cell')) {
|
||||
cell.textContent = newRowspan;
|
||||
}
|
||||
});
|
||||
}
|
||||
row.remove();
|
||||
// Пересчитываем усреднённые координаты после удаления точки
|
||||
recalculateAverageCoords(sourceId);
|
||||
}
|
||||
updateCounter();
|
||||
}
|
||||
|
||||
function removeSource(button) {
|
||||
const row = button.closest('tr');
|
||||
const sourceId = row.dataset.sourceId;
|
||||
const rows = document.querySelectorAll(`tr[data-source-id="${sourceId}"]`);
|
||||
rows.forEach(r => r.remove());
|
||||
updateCounter();
|
||||
}
|
||||
|
||||
function updateCounter() {
|
||||
const rows = document.querySelectorAll('#resultsTable tbody tr');
|
||||
const counter = document.getElementById('statsCounter');
|
||||
if (counter) {
|
||||
// Подсчитываем уникальные источники и точки (только видимые)
|
||||
const uniqueSources = new Set();
|
||||
let visibleRowsCount = 0;
|
||||
rows.forEach(row => {
|
||||
if (row.style.display !== 'none') {
|
||||
uniqueSources.add(row.dataset.sourceId);
|
||||
visibleRowsCount++;
|
||||
}
|
||||
});
|
||||
counter.textContent = `Найдено объектов: ${uniqueSources.size}, точек: ${visibleRowsCount}`;
|
||||
}
|
||||
}
|
||||
|
||||
function exportToExcel() {
|
||||
const rows = document.querySelectorAll('#resultsTable tbody tr');
|
||||
const objitemIds = Array.from(rows).map(row => row.dataset.objitemId);
|
||||
|
||||
if (objitemIds.length === 0) {
|
||||
alert('Нет данных для экспорта');
|
||||
return;
|
||||
}
|
||||
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = '{% url "mainapp:kubsat_export" %}';
|
||||
|
||||
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
|
||||
if (csrfToken) {
|
||||
const csrfInput = document.createElement('input');
|
||||
csrfInput.type = 'hidden';
|
||||
csrfInput.name = 'csrfmiddlewaretoken';
|
||||
csrfInput.value = csrfToken.value;
|
||||
form.appendChild(csrfInput);
|
||||
}
|
||||
|
||||
objitemIds.forEach(id => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'hidden';
|
||||
input.name = 'objitem_ids';
|
||||
input.value = id;
|
||||
form.appendChild(input);
|
||||
});
|
||||
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
document.body.removeChild(form);
|
||||
}
|
||||
|
||||
function selectAllOptions(selectName, selectAll) {
|
||||
const selectElement = document.querySelector(`select[name="${selectName}"]`);
|
||||
if (selectElement) {
|
||||
for (let i = 0; i < selectElement.options.length; i++) {
|
||||
selectElement.options[i].selected = selectAll;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createRequestsFromTable() {
|
||||
const rows = document.querySelectorAll('#resultsTable tbody tr');
|
||||
const objitemIds = Array.from(rows).map(row => row.dataset.objitemId);
|
||||
|
||||
if (objitemIds.length === 0) {
|
||||
alert('Нет данных для создания заявок');
|
||||
return;
|
||||
}
|
||||
|
||||
// Подсчитываем уникальные источники
|
||||
const uniqueSources = new Set();
|
||||
rows.forEach(row => uniqueSources.add(row.dataset.sourceId));
|
||||
|
||||
if (!confirm(`Будет создано ${uniqueSources.size} заявок (по одной на каждый источник) со статусом "Запланировано".\n\nКоординаты будут рассчитаны как среднее по выбранным точкам.\n\nПродолжить?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Показываем индикатор загрузки
|
||||
const btn = event.target.closest('button');
|
||||
const originalText = btn.innerHTML;
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Создание...';
|
||||
|
||||
const formData = new FormData();
|
||||
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
|
||||
if (csrfToken) {
|
||||
formData.append('csrfmiddlewaretoken', csrfToken.value);
|
||||
}
|
||||
|
||||
objitemIds.forEach(id => {
|
||||
formData.append('objitem_ids', id);
|
||||
});
|
||||
|
||||
fetch('{% url "mainapp:kubsat_create_requests" %}', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken ? csrfToken.value : ''
|
||||
},
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(result => {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = originalText;
|
||||
|
||||
if (result.success) {
|
||||
let message = `Создано заявок: ${result.created_count} из ${result.total_sources}`;
|
||||
if (result.errors && result.errors.length > 0) {
|
||||
message += `\n\nОшибки:\n${result.errors.join('\n')}`;
|
||||
}
|
||||
alert(message);
|
||||
// Перезагружаем страницу для обновления данных
|
||||
location.reload();
|
||||
} else {
|
||||
alert('Ошибка: ' + result.error);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = originalText;
|
||||
console.error('Error creating requests:', error);
|
||||
alert('Ошибка создания заявок');
|
||||
});
|
||||
}
|
||||
|
||||
// Фильтрация таблицы по имени точки
|
||||
function filterTableByName() {
|
||||
const searchValue = document.getElementById('searchObjitemName').value.toLowerCase().trim();
|
||||
const rows = document.querySelectorAll('#resultsTable tbody tr');
|
||||
|
||||
if (!searchValue) {
|
||||
// Показываем все строки
|
||||
rows.forEach(row => {
|
||||
row.style.display = '';
|
||||
});
|
||||
// Восстанавливаем rowspan
|
||||
recalculateRowspans();
|
||||
updateCounter();
|
||||
return;
|
||||
}
|
||||
|
||||
// Группируем строки по source_id
|
||||
const sourceGroups = {};
|
||||
rows.forEach(row => {
|
||||
const sourceId = row.dataset.sourceId;
|
||||
if (!sourceGroups[sourceId]) {
|
||||
sourceGroups[sourceId] = [];
|
||||
}
|
||||
sourceGroups[sourceId].push(row);
|
||||
});
|
||||
|
||||
// Фильтруем по имени точки используя data-атрибут
|
||||
Object.keys(sourceGroups).forEach(sourceId => {
|
||||
const sourceRows = sourceGroups[sourceId];
|
||||
let hasVisibleRows = false;
|
||||
|
||||
sourceRows.forEach(row => {
|
||||
// Используем data-атрибут для получения имени точки
|
||||
const name = (row.dataset.objitemName || '').toLowerCase();
|
||||
|
||||
if (name.includes(searchValue)) {
|
||||
row.style.display = '';
|
||||
hasVisibleRows = true;
|
||||
} else {
|
||||
row.style.display = 'none';
|
||||
}
|
||||
});
|
||||
|
||||
// Если нет видимых строк в группе, скрываем все (включая ячейки с rowspan)
|
||||
if (!hasVisibleRows) {
|
||||
sourceRows.forEach(row => {
|
||||
row.style.display = 'none';
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Пересчитываем rowspan для видимых строк
|
||||
recalculateRowspans();
|
||||
updateCounter();
|
||||
}
|
||||
|
||||
// Пересчет rowspan для видимых строк
|
||||
function recalculateRowspans() {
|
||||
const rows = document.querySelectorAll('#resultsTable tbody tr');
|
||||
|
||||
// Группируем видимые строки по source_id
|
||||
const sourceGroups = {};
|
||||
rows.forEach(row => {
|
||||
if (row.style.display !== 'none') {
|
||||
const sourceId = row.dataset.sourceId;
|
||||
if (!sourceGroups[sourceId]) {
|
||||
sourceGroups[sourceId] = [];
|
||||
}
|
||||
sourceGroups[sourceId].push(row);
|
||||
}
|
||||
});
|
||||
|
||||
// All rowspan cell classes
|
||||
const rowspanCellClasses = [
|
||||
'.source-id-cell', '.source-type-cell', '.source-ownership-cell', '.source-requests-count-cell',
|
||||
'.source-gso-cell', '.source-kubsat-cell', '.source-status-cell', '.source-count-cell', '.source-avg-coords-cell'
|
||||
];
|
||||
|
||||
// Обновляем rowspan для каждой группы
|
||||
Object.keys(sourceGroups).forEach(sourceId => {
|
||||
const visibleRows = sourceGroups[sourceId];
|
||||
const newRowspan = visibleRows.length;
|
||||
|
||||
if (visibleRows.length > 0) {
|
||||
const firstRow = visibleRows[0];
|
||||
|
||||
rowspanCellClasses.forEach(cls => {
|
||||
const cell = firstRow.querySelector(cls);
|
||||
if (cell) {
|
||||
cell.setAttribute('rowspan', newRowspan);
|
||||
// Обновляем отображаемое количество точек
|
||||
if (cell.classList.contains('source-count-cell')) {
|
||||
cell.textContent = newRowspan;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Очистка поиска
|
||||
function clearSearch() {
|
||||
document.getElementById('searchObjitemName').value = '';
|
||||
filterTableByName();
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
updateCounter();
|
||||
});
|
||||
</script>
|
||||
@@ -2,29 +2,32 @@
|
||||
Переиспользуемый компонент для отображения сообщений Django
|
||||
Использование:
|
||||
{% include 'mainapp/components/_messages.html' %}
|
||||
|
||||
Для отключения автоскрытия добавьте extra_tags='persistent':
|
||||
messages.success(request, "Сообщение", extra_tags='persistent')
|
||||
{% endcomment %}
|
||||
|
||||
{% if messages %}
|
||||
<div class="messages-container">
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-{{ message.tags }} alert-dismissible fade show auto-dismiss" role="alert">
|
||||
{% if message.tags == 'error' %}
|
||||
<div class="alert alert-{% if 'error' in message.tags %}danger{% elif 'success' in message.tags %}success{% elif 'warning' in message.tags %}warning{% else %}info{% endif %} alert-dismissible fade show {% if 'persistent' not in message.tags %}auto-dismiss{% endif %}" role="alert">
|
||||
{% if 'error' in message.tags %}
|
||||
<i class="bi bi-exclamation-triangle-fill me-2"></i>
|
||||
{% elif message.tags == 'success' %}
|
||||
{% elif 'success' in message.tags %}
|
||||
<i class="bi bi-check-circle-fill me-2"></i>
|
||||
{% elif message.tags == 'warning' %}
|
||||
{% elif 'warning' in message.tags %}
|
||||
<i class="bi bi-exclamation-circle-fill me-2"></i>
|
||||
{% elif message.tags == 'info' %}
|
||||
{% elif 'info' in message.tags %}
|
||||
<i class="bi bi-info-circle-fill me-2"></i>
|
||||
{% endif %}
|
||||
{{ message }}
|
||||
{{ message|safe }}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Автоматическое скрытие уведомлений через 5 секунд
|
||||
// Автоматическое скрытие уведомлений через 5 секунд (кроме persistent)
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const alerts = document.querySelectorAll('.alert.auto-dismiss');
|
||||
alerts.forEach(function(alert) {
|
||||
|
||||
@@ -31,11 +31,11 @@
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{% url 'lyngsatapp:lyngsat_list' %}">Справочные данные</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<!-- <li class="nav-item">
|
||||
<a class="nav-link" href="{% url 'mainapp:actions' %}">Действия</a>
|
||||
</li>
|
||||
</li> -->
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{% url 'mainapp:object_marks' %}">Наличие сигнала</a>
|
||||
<a class="nav-link" href="{% url 'mainapp:signal_marks' %}">Отметки сигналов</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="{% url 'mainapp:kubsat' %}">Кубсат</a>
|
||||
|
||||
@@ -43,11 +43,26 @@ function showSatelliteModal(satelliteId) {
|
||||
'<div class="col-md-6"><div class="card h-100">' +
|
||||
'<div class="card-header bg-light"><strong><i class="bi bi-info-circle"></i> Основная информация</strong></div>' +
|
||||
'<div class="card-body"><table class="table table-sm table-borderless mb-0"><tbody>' +
|
||||
'<tr><td class="text-muted" style="width: 40%;">Название:</td><td><strong>' + data.name + '</strong></td></tr>' +
|
||||
'<tr><td class="text-muted">NORAD ID:</td><td>' + data.norad + '</td></tr>' +
|
||||
'<tr><td class="text-muted">Подспутниковая точка:</td><td><strong>' + data.undersat_point + '</strong></td></tr>' +
|
||||
'<tr><td class="text-muted">Диапазоны:</td><td>' + data.bands + '</td></tr>' +
|
||||
'</tbody></table></div></div></div>' +
|
||||
'<tr><td class="text-muted" style="width: 40%;">Название:</td><td><strong>' + data.name + '</strong></td></tr>';
|
||||
|
||||
if (data.alternative_name && data.alternative_name !== '-') {
|
||||
html += '<tr><td class="text-muted">Альтернативное название:</td><td><strong>' + data.alternative_name + '</strong></td></tr>';
|
||||
}
|
||||
|
||||
html += '<tr><td class="text-muted">NORAD ID:</td><td>' + (data.norad || '-') + '</td></tr>';
|
||||
|
||||
if (data.international_code && data.international_code !== '-') {
|
||||
html += '<tr><td class="text-muted">Международный код:</td><td>' + data.international_code + '</td></tr>';
|
||||
}
|
||||
|
||||
html += '<tr><td class="text-muted">Подспутниковая точка:</td><td><strong>' + (data.undersat_point !== null ? data.undersat_point + '°' : '-') + '</strong></td></tr>' +
|
||||
'<tr><td class="text-muted">Диапазоны:</td><td>' + data.bands + '</td></tr>';
|
||||
|
||||
if (data.location_place && data.location_place !== '-') {
|
||||
html += '<tr><td class="text-muted">Комплекс:</td><td><span class="badge bg-secondary">' + data.location_place + '</span></td></tr>';
|
||||
}
|
||||
|
||||
html += '</tbody></table></div></div></div>' +
|
||||
'<div class="col-md-6"><div class="card h-100">' +
|
||||
'<div class="card-header bg-light"><strong><i class="bi bi-calendar"></i> Дополнительная информация</strong></div>' +
|
||||
'<div class="card-body"><table class="table table-sm table-borderless mb-0"><tbody>' +
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!-- Selected Items Offcanvas Component -->
|
||||
<div class="offcanvas offcanvas-end" tabindex="-1" id="selectedItemsOffcanvas" aria-labelledby="selectedItemsOffcanvasLabel" style="width: 100vw;">
|
||||
<div class="offcanvas offcanvas-end" tabindex="-1" id="selectedItemsOffcanvas" aria-labelledby="selectedItemsOffcanvasLabel" style="width: 66vw;">
|
||||
<div class="offcanvas-header">
|
||||
<h5 class="offcanvas-title" id="selectedItemsOffcanvasLabel">Выбранные элементы</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Закрыть"></button>
|
||||
@@ -12,8 +12,8 @@
|
||||
<button type="button" class="btn btn-danger btn-sm" onclick="removeSelectedItems()">
|
||||
<i class="bi bi-trash"></i> Убрать из списка
|
||||
</button>
|
||||
<button type="button" class="btn btn-primary btn-sm" onclick="sendSelectedItems()">
|
||||
<i class="bi bi-send"></i> Отправить
|
||||
<button type="button" class="btn btn-primary btn-sm" onclick="showSelectedItemsOnMap()">
|
||||
<i class="bi bi-map"></i> Карта
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary btn-sm ms-auto" data-bs-dismiss="offcanvas">
|
||||
Закрыть
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
{% 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-header d-flex justify-content-between align-items-center">
|
||||
<h5 class="mb-0"><i class="bi bi-list-task"></i> Заявки на источники</h5>
|
||||
<div>
|
||||
<button type="button" class="btn btn-outline-danger btn-sm me-2" id="bulkDeleteBtn" onclick="bulkDeleteRequests()">
|
||||
<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 class="card-body">
|
||||
<!-- Фильтры заявок -->
|
||||
<form method="get" class="row g-2 mb-3" id="requestsFilterForm">
|
||||
<div class="col-md-2">
|
||||
<select name="status" class="form-select form-select-sm" onchange="this.form.submit()">
|
||||
<option value="">Все статусы</option>
|
||||
{% for value, label in status_choices %}
|
||||
<option value="{{ value }}" {% if current_status == value %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<select name="priority" class="form-select form-select-sm" onchange="this.form.submit()">
|
||||
<option value="">Все приоритеты</option>
|
||||
{% for value, label in priority_choices %}
|
||||
<option value="{{ value }}" {% if current_priority == value %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<select name="gso_success" class="form-select form-select-sm" onchange="this.form.submit()">
|
||||
<option value="">ГСО: все</option>
|
||||
<option value="true" {% if request.GET.gso_success == 'true' %}selected{% endif %}>ГСО: Да</option>
|
||||
<option value="false" {% if request.GET.gso_success == 'false' %}selected{% endif %}>ГСО: Нет</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<select name="kubsat_success" class="form-select form-select-sm" onchange="this.form.submit()">
|
||||
<option value="">Кубсат: все</option>
|
||||
<option value="true" {% if request.GET.kubsat_success == 'true' %}selected{% endif %}>Кубсат: Да</option>
|
||||
<option value="false" {% if request.GET.kubsat_success == 'false' %}selected{% endif %}>Кубсат: Нет</option>
|
||||
</select>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- Клиентский поиск -->
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-4">
|
||||
<div class="input-group input-group-sm">
|
||||
<input type="text" id="searchRequestInput" class="form-control"
|
||||
placeholder="Поиск по спутнику, частоте...">
|
||||
<button type="button" class="btn btn-outline-secondary" onclick="clearRequestSearch()">
|
||||
<i class="bi bi-x-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Таблица заявок (Tabulator с встроенной пагинацией) -->
|
||||
<div id="requestsTable"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
|
||||
<script>
|
||||
// Данные заявок из Django (через JSON)
|
||||
const requestsData = JSON.parse('{{ requests_json|escapejs }}');
|
||||
|
||||
// Форматтер для статуса
|
||||
function statusFormatter(cell) {
|
||||
const status = cell.getValue();
|
||||
const display = cell.getData().status_display;
|
||||
let badgeClass = 'bg-secondary';
|
||||
|
||||
if (status === 'successful' || status === 'result_received') {
|
||||
badgeClass = 'bg-success';
|
||||
} else if (status === 'unsuccessful' || status === 'no_correlation' || status === 'no_signal') {
|
||||
badgeClass = 'bg-danger';
|
||||
} else if (status === 'planned') {
|
||||
badgeClass = 'bg-primary';
|
||||
} else if (status === 'downloading' || status === 'processing') {
|
||||
badgeClass = 'bg-warning text-dark';
|
||||
}
|
||||
|
||||
return `<span class="badge ${badgeClass}">${display}</span>`;
|
||||
}
|
||||
|
||||
// Форматтер для булевых значений (ГСО/Кубсат)
|
||||
function boolFormatter(cell) {
|
||||
const val = cell.getValue();
|
||||
if (val === true) {
|
||||
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 if (field === 'coords_source_lat') {
|
||||
lat = data.coords_source_lat;
|
||||
lon = data.coords_source_lon;
|
||||
} else if (field === 'coords_object_lat') {
|
||||
lat = data.coords_object_lat;
|
||||
lon = data.coords_object_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: true,
|
||||
paginationSizeSelector: [50, 200, 500],
|
||||
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: 105, formatter: priorityFormatter},
|
||||
{title: "Заявка", field: "request_date_display", width: 105,
|
||||
sorter: function(a, b, aRow, bRow) {
|
||||
const dateA = aRow.getData().request_date;
|
||||
const dateB = bRow.getData().request_date;
|
||||
if (!dateA && !dateB) return 0;
|
||||
if (!dateA) return 1;
|
||||
if (!dateB) return -1;
|
||||
return new Date(dateA) - new Date(dateB);
|
||||
}
|
||||
},
|
||||
{title: "Карточка", field: "card_date_display", width: 120,
|
||||
sorter: function(a, b, aRow, bRow) {
|
||||
const dateA = aRow.getData().card_date;
|
||||
const dateB = bRow.getData().card_date;
|
||||
if (!dateA && !dateB) return 0;
|
||||
if (!dateA) return 1;
|
||||
if (!dateB) return -1;
|
||||
return new Date(dateA) - new Date(dateB);
|
||||
}
|
||||
},
|
||||
{title: "Планирование", field: "planned_at_display", width: 150,
|
||||
sorter: function(a, b, aRow, bRow) {
|
||||
const dateA = aRow.getData().planned_at;
|
||||
const dateB = bRow.getData().planned_at;
|
||||
if (!dateA && !dateB) return 0;
|
||||
if (!dateA) return 1;
|
||||
if (!dateB) return -1;
|
||||
return new Date(dateA) - new Date(dateB);
|
||||
}
|
||||
},
|
||||
{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: 130, formatter: coordsFormatter},
|
||||
{title: "Район", field: "region", width: 100, 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: 140, formatter: coordsFormatter},
|
||||
{title: "Коорд. об.", field: "coords_object_lat", width: 140, 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() {
|
||||
document.getElementById('searchRequestInput').value = '';
|
||||
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() {
|
||||
updateRequestsCounter();
|
||||
});
|
||||
</script>
|
||||
312
dbapp/mainapp/templates/mainapp/data_entry.html
Normal file
312
dbapp/mainapp/templates/mainapp/data_entry.html
Normal file
@@ -0,0 +1,312 @@
|
||||
{% extends "mainapp/base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Ввод данных{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link href="{% static 'tabulator/css/tabulator_bootstrap5.min.css' %}" rel="stylesheet">
|
||||
<style>
|
||||
.data-entry-container {
|
||||
padding: 20px;
|
||||
}
|
||||
.form-section {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.table-section {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
#data-table {
|
||||
margin-top: 20px;
|
||||
font-size: 12px;
|
||||
}
|
||||
#data-table .tabulator-header {
|
||||
font-size: 12px;
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
#data-table .tabulator-header .tabulator-col {
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
height: auto;
|
||||
min-height: 40px;
|
||||
}
|
||||
#data-table .tabulator-header .tabulator-col-content {
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
padding: 6px 4px;
|
||||
}
|
||||
#data-table .tabulator-cell {
|
||||
font-size: 12px;
|
||||
padding: 6px 4px;
|
||||
}
|
||||
.btn-group-custom {
|
||||
margin-top: 15px;
|
||||
}
|
||||
.input-field {
|
||||
font-family: monospace;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="data-entry-container">
|
||||
<h2>Ввод данных точек спутников</h2>
|
||||
|
||||
<div class="form-section">
|
||||
<div class="row">
|
||||
<div class="col-md-4 mb-3">
|
||||
<label for="satellite-select" class="form-label">Спутник</label>
|
||||
<select id="satellite-select" class="form-select">
|
||||
<option value="">Выберите спутник</option>
|
||||
{% for satellite in satellites %}
|
||||
<option value="{{ satellite.id }}">{{ satellite.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-8 mb-3">
|
||||
<label for="data-input" class="form-label">Данные</label>
|
||||
<input type="text" id="data-input" class="form-control input-field"
|
||||
placeholder="Вставьте строку данных и нажмите Enter">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-section">
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<div>
|
||||
<h5>Таблица данных <span id="row-count" class="badge bg-primary">0</span></h5>
|
||||
</div>
|
||||
<div class="btn-group-custom">
|
||||
<button id="export-xlsx" class="btn btn-success">
|
||||
<i class="bi bi-file-earmark-excel"></i> Сохранить в Excel
|
||||
</button>
|
||||
<button id="clear-table" class="btn btn-danger ms-2">
|
||||
<i class="bi bi-trash"></i> Очистить таблицу
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="data-table"></div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
|
||||
<script src="{% static 'sheetjs/xlsx.full.min.js' %}"></script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Initialize Tabulator
|
||||
const table = new Tabulator("#data-table", {
|
||||
layout: "fitDataStretch",
|
||||
height: "500px",
|
||||
placeholder: "Нет данных. Введите данные в поле выше и нажмите Enter.",
|
||||
headerWordWrap: true,
|
||||
columns: [
|
||||
{title: "Объект наблюдения", field: "object_name", minWidth: 180, widthGrow: 2, editor: "input"},
|
||||
{title: "Частота, МГц", field: "frequency", minWidth: 100, widthGrow: 1, editor: "input"},
|
||||
{title: "Полоса, МГц", field: "freq_range", minWidth: 100, widthGrow: 1, editor: "input"},
|
||||
{title: "Символьная скорость, БОД", field: "bod_velocity", minWidth: 120, widthGrow: 1.5, editor: "input"},
|
||||
{title: "Модуляция", field: "modulation", minWidth: 100, widthGrow: 1, editor: "input"},
|
||||
{title: "ОСШ", field: "snr", minWidth: 70, widthGrow: 0.8, editor: "input"},
|
||||
{title: "Дата", field: "date", minWidth: 100, widthGrow: 1, editor: "input"},
|
||||
{title: "Время", field: "time", minWidth: 90, widthGrow: 1, editor: "input"},
|
||||
{title: "Зеркала", field: "mirrors", minWidth: 130, widthGrow: 1.5, editor: "input"},
|
||||
{title: "Местоопределение", field: "location", minWidth: 130, widthGrow: 1.5, editor: "input"},
|
||||
{title: "Координаты", field: "coordinates", minWidth: 150, widthGrow: 2, editor: "input"},
|
||||
],
|
||||
data: [],
|
||||
});
|
||||
|
||||
// Update row count
|
||||
function updateRowCount() {
|
||||
const count = table.getDataCount();
|
||||
document.getElementById('row-count').textContent = count;
|
||||
}
|
||||
|
||||
// Listen to table events
|
||||
table.on("rowAdded", updateRowCount);
|
||||
table.on("dataChanged", updateRowCount);
|
||||
|
||||
// Parse input string
|
||||
function parseInputString(inputStr) {
|
||||
const parts = inputStr.split(';');
|
||||
|
||||
if (parts.length < 5) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Parse date and time (first part)
|
||||
const dateTimePart = parts[0].trim();
|
||||
const dateTimeMatch = dateTimePart.match(/(\d{2}\.\d{2}\.\d{4})\s+(\d{2}:\d{2}:\d{2})/);
|
||||
|
||||
if (!dateTimeMatch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const date = dateTimeMatch[1];
|
||||
const time = dateTimeMatch[2];
|
||||
|
||||
// Parse object name (second part)
|
||||
const objectName = parts[1].trim();
|
||||
|
||||
// Parse location (fourth part - "Позиция")
|
||||
// const location = parts[3].trim() || '-';
|
||||
const location = '-';
|
||||
|
||||
// Parse coordinates (fifth part)
|
||||
const coordsPart = parts[4].trim();
|
||||
const coordsMatch = coordsPart.match(/([-\d,]+)\s+([-\d,]+)/);
|
||||
|
||||
let coordinates = '-';
|
||||
if (coordsMatch) {
|
||||
const lat = coordsMatch[1].replace(',', '.');
|
||||
const lon = coordsMatch[2].replace(',', '.');
|
||||
coordinates = `${lat}, ${lon}`;
|
||||
}
|
||||
|
||||
return {
|
||||
date: date,
|
||||
time: time,
|
||||
object_name: objectName,
|
||||
location: location,
|
||||
coordinates: coordinates,
|
||||
};
|
||||
}
|
||||
|
||||
// Search for ObjItem data
|
||||
async function searchObjItemData(objectName, satelliteId, latitude, longitude) {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
name: objectName,
|
||||
});
|
||||
|
||||
if (satelliteId) {
|
||||
params.append('satellite_id', satelliteId);
|
||||
}
|
||||
|
||||
if (latitude && longitude) {
|
||||
params.append('latitude', latitude);
|
||||
params.append('longitude', longitude);
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/search-objitem/?${params.toString()}`);
|
||||
const data = await response.json();
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error searching ObjItem:', error);
|
||||
return { found: false };
|
||||
}
|
||||
}
|
||||
|
||||
// Handle input
|
||||
const dataInput = document.getElementById('data-input');
|
||||
const satelliteSelect = document.getElementById('satellite-select');
|
||||
|
||||
dataInput.addEventListener('keypress', async function(e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
|
||||
const inputValue = this.value.trim();
|
||||
|
||||
if (!inputValue) {
|
||||
alert('Введите данные');
|
||||
return;
|
||||
}
|
||||
|
||||
// Disable input while processing
|
||||
this.disabled = true;
|
||||
|
||||
try {
|
||||
// Parse input
|
||||
const parsedData = parseInputString(inputValue);
|
||||
|
||||
if (!parsedData) {
|
||||
alert('Неверный формат данных. Проверьте формат строки.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Search for ObjItem data
|
||||
const satelliteId = satelliteSelect.value;
|
||||
|
||||
// Extract latitude and longitude from coordinates
|
||||
let latitude = null;
|
||||
let longitude = null;
|
||||
if (parsedData.coordinates && parsedData.coordinates !== '-') {
|
||||
const coordParts = parsedData.coordinates.split(',').map(c => c.trim());
|
||||
if (coordParts.length === 2) {
|
||||
latitude = coordParts[0];
|
||||
longitude = coordParts[1];
|
||||
}
|
||||
}
|
||||
|
||||
const objItemData = await searchObjItemData(
|
||||
parsedData.object_name,
|
||||
satelliteId,
|
||||
latitude,
|
||||
longitude
|
||||
);
|
||||
|
||||
// Show warning if object not found
|
||||
if (!objItemData.found) {
|
||||
console.warn('Объект не найден в базе данных:', parsedData.object_name);
|
||||
}
|
||||
|
||||
// Prepare row data
|
||||
const rowData = {
|
||||
object_name: parsedData.object_name || '-',
|
||||
date: parsedData.date || '-',
|
||||
time: parsedData.time || '-',
|
||||
location: parsedData.location || '-',
|
||||
coordinates: parsedData.coordinates || '-',
|
||||
frequency: objItemData.found && objItemData.frequency !== null ? objItemData.frequency : '-',
|
||||
freq_range: objItemData.found && objItemData.freq_range !== null ? objItemData.freq_range : '-',
|
||||
bod_velocity: objItemData.found && objItemData.bod_velocity !== null ? objItemData.bod_velocity : '-',
|
||||
modulation: objItemData.found && objItemData.modulation !== null ? objItemData.modulation : '-',
|
||||
snr: objItemData.found && objItemData.snr !== null ? objItemData.snr : '-',
|
||||
mirrors: objItemData.found && objItemData.mirrors !== null ? objItemData.mirrors : '-',
|
||||
};
|
||||
|
||||
// Add row to table
|
||||
table.addRow(rowData);
|
||||
|
||||
// Clear input
|
||||
this.value = '';
|
||||
} catch (error) {
|
||||
console.error('Ошибка при обработке данных:', error);
|
||||
alert('Произошла ошибка при обработке данных. Проверьте консоль для деталей.');
|
||||
} finally {
|
||||
// Re-enable input
|
||||
this.disabled = false;
|
||||
this.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Export to Excel
|
||||
document.getElementById('export-xlsx').addEventListener('click', function() {
|
||||
table.download("xlsx", "data_export.xlsx", {sheetName: "Данные"});
|
||||
});
|
||||
|
||||
// Clear table
|
||||
document.getElementById('clear-table').addEventListener('click', function() {
|
||||
if (confirm('Вы уверены, что хотите очистить таблицу?')) {
|
||||
table.clearData();
|
||||
updateRowCount();
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize row count
|
||||
updateRowCount();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -13,7 +13,6 @@
|
||||
|
||||
<!-- Форма фильтров -->
|
||||
<form method="get" id="filterForm" class="mb-4">
|
||||
{% csrf_token %}
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0">Фильтры</h5>
|
||||
@@ -124,16 +123,12 @@
|
||||
<div class="row">
|
||||
<!-- Количество ObjItem -->
|
||||
<div class="col-md-3 mb-3">
|
||||
<label class="form-label">{{ form.objitem_count.label }}</label>
|
||||
<div>
|
||||
{% for radio in form.objitem_count %}
|
||||
<div class="form-check">
|
||||
{{ radio.tag }}
|
||||
<label class="form-check-label" for="{{ radio.id_for_label }}">
|
||||
{{ radio.choice_label }}
|
||||
</label>
|
||||
<label class="form-label">Количество привязанных точек ГЛ</label>
|
||||
<div class="input-group mb-2">
|
||||
{{ form.objitem_count_min }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div class="input-group">
|
||||
{{ form.objitem_count_max }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -212,6 +207,16 @@
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="d-flex flex-wrap align-items-center gap-3">
|
||||
<!-- Поиск по имени точки -->
|
||||
<div class="input-group" style="max-width: 350px;">
|
||||
<input type="text" id="searchObjitemName" class="form-control"
|
||||
placeholder="Поиск по имени точки..."
|
||||
oninput="filterTableByName()">
|
||||
<button type="button" class="btn btn-outline-secondary" onclick="clearSearch()">
|
||||
<i class="bi bi-x-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button type="button" class="btn btn-success" onclick="exportToExcel()">
|
||||
<i class="bi bi-file-earmark-excel"></i> Экспорт в Excel
|
||||
</button>
|
||||
@@ -256,6 +261,7 @@
|
||||
{% for objitem_data in source_data.objitems_data %}
|
||||
<tr data-source-id="{{ source_data.source.id }}"
|
||||
data-objitem-id="{{ objitem_data.objitem.id }}"
|
||||
data-objitem-name="{{ objitem_data.objitem.name|default:'' }}"
|
||||
data-matches-date="{{ objitem_data.matches_date|yesno:'true,false' }}"
|
||||
data-is-first-in-source="{% if forloop.first %}true{% else %}false{% endif %}">
|
||||
|
||||
@@ -500,12 +506,16 @@ function updateCounter() {
|
||||
const rows = document.querySelectorAll('#resultsTable tbody tr');
|
||||
const counter = document.getElementById('statsCounter');
|
||||
if (counter) {
|
||||
// Подсчитываем уникальные источники
|
||||
// Подсчитываем уникальные источники и точки (только видимые)
|
||||
const uniqueSources = new Set();
|
||||
let visibleRowsCount = 0;
|
||||
rows.forEach(row => {
|
||||
if (row.style.display !== 'none') {
|
||||
uniqueSources.add(row.dataset.sourceId);
|
||||
visibleRowsCount++;
|
||||
}
|
||||
});
|
||||
counter.textContent = `Найдено объектов: ${uniqueSources.size}, точек: ${rows.length}`;
|
||||
counter.textContent = `Найдено объектов: ${uniqueSources.size}, точек: ${visibleRowsCount}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -561,6 +571,108 @@ function selectAllOptions(selectName, selectAll) {
|
||||
}
|
||||
}
|
||||
|
||||
// Фильтрация таблицы по имени точки
|
||||
function filterTableByName() {
|
||||
const searchValue = document.getElementById('searchObjitemName').value.toLowerCase().trim();
|
||||
const rows = document.querySelectorAll('#resultsTable tbody tr');
|
||||
|
||||
if (!searchValue) {
|
||||
// Показываем все строки
|
||||
rows.forEach(row => {
|
||||
row.style.display = '';
|
||||
});
|
||||
// Восстанавливаем rowspan
|
||||
recalculateRowspans();
|
||||
updateCounter();
|
||||
return;
|
||||
}
|
||||
|
||||
// Группируем строки по source_id
|
||||
const sourceGroups = {};
|
||||
rows.forEach(row => {
|
||||
const sourceId = row.dataset.sourceId;
|
||||
if (!sourceGroups[sourceId]) {
|
||||
sourceGroups[sourceId] = [];
|
||||
}
|
||||
sourceGroups[sourceId].push(row);
|
||||
});
|
||||
|
||||
// Фильтруем по имени точки используя data-атрибут
|
||||
Object.keys(sourceGroups).forEach(sourceId => {
|
||||
const sourceRows = sourceGroups[sourceId];
|
||||
let hasVisibleRows = false;
|
||||
|
||||
sourceRows.forEach(row => {
|
||||
// Используем data-атрибут для получения имени точки
|
||||
const name = (row.dataset.objitemName || '').toLowerCase();
|
||||
|
||||
if (name.includes(searchValue)) {
|
||||
row.style.display = '';
|
||||
hasVisibleRows = true;
|
||||
} else {
|
||||
row.style.display = 'none';
|
||||
}
|
||||
});
|
||||
|
||||
// Если нет видимых строк в группе, скрываем все (включая ячейки с rowspan)
|
||||
if (!hasVisibleRows) {
|
||||
sourceRows.forEach(row => {
|
||||
row.style.display = 'none';
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Пересчитываем rowspan для видимых строк
|
||||
recalculateRowspans();
|
||||
updateCounter();
|
||||
}
|
||||
|
||||
// Пересчет rowspan для видимых строк
|
||||
function recalculateRowspans() {
|
||||
const rows = document.querySelectorAll('#resultsTable tbody tr');
|
||||
|
||||
// Группируем видимые строки по source_id
|
||||
const sourceGroups = {};
|
||||
rows.forEach(row => {
|
||||
if (row.style.display !== 'none') {
|
||||
const sourceId = row.dataset.sourceId;
|
||||
if (!sourceGroups[sourceId]) {
|
||||
sourceGroups[sourceId] = [];
|
||||
}
|
||||
sourceGroups[sourceId].push(row);
|
||||
}
|
||||
});
|
||||
|
||||
// Обновляем rowspan для каждой группы
|
||||
Object.keys(sourceGroups).forEach(sourceId => {
|
||||
const visibleRows = sourceGroups[sourceId];
|
||||
const newRowspan = visibleRows.length;
|
||||
|
||||
if (visibleRows.length > 0) {
|
||||
const firstRow = visibleRows[0];
|
||||
const sourceIdCell = firstRow.querySelector('.source-id-cell');
|
||||
const sourceTypeCell = firstRow.querySelector('.source-type-cell');
|
||||
const sourceOwnershipCell = firstRow.querySelector('.source-ownership-cell');
|
||||
const sourceCountCell = firstRow.querySelector('.source-count-cell');
|
||||
|
||||
if (sourceIdCell) sourceIdCell.setAttribute('rowspan', newRowspan);
|
||||
if (sourceTypeCell) sourceTypeCell.setAttribute('rowspan', newRowspan);
|
||||
if (sourceOwnershipCell) sourceOwnershipCell.setAttribute('rowspan', newRowspan);
|
||||
if (sourceCountCell) {
|
||||
sourceCountCell.setAttribute('rowspan', newRowspan);
|
||||
// Обновляем отображаемое количество точек
|
||||
sourceCountCell.textContent = newRowspan;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Очистка поиска
|
||||
function clearSearch() {
|
||||
document.getElementById('searchObjitemName').value = '';
|
||||
filterTableByName();
|
||||
}
|
||||
|
||||
// Обновляем счетчик при загрузке страницы
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
updateCounter();
|
||||
|
||||
639
dbapp/mainapp/templates/mainapp/kubsat_tabs.html
Normal file
639
dbapp/mainapp/templates/mainapp/kubsat_tabs.html
Normal file
@@ -0,0 +1,639 @@
|
||||
{% extends 'mainapp/base.html' %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Кубсат{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container-fluid px-3">
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<h2>Кубсат</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Вкладки -->
|
||||
<ul class="nav nav-tabs mb-3" id="kubsatTabs" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link active" id="requests-tab" data-bs-toggle="tab" data-bs-target="#requests"
|
||||
type="button" role="tab" aria-controls="requests" aria-selected="true">
|
||||
<i class="bi bi-list-task"></i> Заявки
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="filters-tab" data-bs-toggle="tab" data-bs-target="#filters"
|
||||
type="button" role="tab" aria-controls="filters" aria-selected="false">
|
||||
<i class="bi bi-funnel"></i> Фильтры и экспорт
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content" id="kubsatTabsContent">
|
||||
<!-- Вкладка заявок -->
|
||||
<div class="tab-pane fade show active" id="requests" role="tabpanel" aria-labelledby="requests-tab">
|
||||
{% include 'mainapp/components/_source_requests_tab.html' %}
|
||||
</div>
|
||||
|
||||
<!-- Вкладка фильтров -->
|
||||
<div class="tab-pane fade" id="filters" role="tabpanel" aria-labelledby="filters-tab">
|
||||
{% include 'mainapp/components/_kubsat_filters_tab.html' %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Модальное окно создания/редактирования заявки -->
|
||||
<div class="modal fade" id="requestModal" tabindex="-1" aria-labelledby="requestModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-xl">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header bg-primary text-white">
|
||||
<h5 class="modal-title" id="requestModalLabel">
|
||||
<i class="bi bi-plus-circle"></i> <span id="requestModalTitle">Создать заявку</span>
|
||||
</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="requestForm">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" id="requestId" name="request_id" value="">
|
||||
|
||||
<!-- Источник и статус -->
|
||||
<div class="row">
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="requestSource" class="form-label">Источник (ID)</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">#</span>
|
||||
<input type="number" class="form-control" id="requestSourceId" name="source"
|
||||
placeholder="ID источника" min="1" onchange="loadSourceData()">
|
||||
<button type="button" class="btn btn-outline-secondary" onclick="loadSourceData()">
|
||||
<i class="bi bi-search"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div id="sourceCheckResult" class="form-text"></div>
|
||||
</div>
|
||||
<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>
|
||||
<select class="form-select" id="requestStatus" name="status">
|
||||
<option value="planned">Запланировано</option>
|
||||
<option value="conducted">Проведён</option>
|
||||
<option value="successful">Успешно</option>
|
||||
<option value="no_correlation">Нет корреляции</option>
|
||||
<option value="no_signal">Нет сигнала в спектре</option>
|
||||
<option value="unsuccessful">Неуспешно</option>
|
||||
<option value="downloading">Скачивание</option>
|
||||
<option value="processing">Обработка</option>
|
||||
<option value="result_received">Результат получен</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="requestPriority" class="form-label">Приоритет</label>
|
||||
<select class="form-select" id="requestPriority" name="priority">
|
||||
<option value="low">Низкий</option>
|
||||
<option value="medium" selected>Средний</option>
|
||||
<option value="high">Высокий</option>
|
||||
</select>
|
||||
</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-header py-2">
|
||||
<small class="text-muted"><i class="bi bi-info-circle"></i> Данные источника</small>
|
||||
</div>
|
||||
<div class="card-body py-2">
|
||||
<div class="row">
|
||||
<div class="col-md-4 mb-2">
|
||||
<label class="form-label small text-muted mb-0">Имя точки</label>
|
||||
<input type="text" class="form-control form-control-sm" id="requestObjitemName" readonly>
|
||||
</div>
|
||||
<div class="col-md-4 mb-2">
|
||||
<label class="form-label small text-muted mb-0">Модуляция</label>
|
||||
<input type="text" class="form-control form-control-sm" id="requestModulation" readonly>
|
||||
</div>
|
||||
<div class="col-md-4 mb-2">
|
||||
<label class="form-label small text-muted mb-0">Символьная скорость</label>
|
||||
<input type="text" class="form-control form-control-sm" id="requestSymbolRate" readonly>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Координаты ГСО -->
|
||||
<div class="row">
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="requestCoordsLat" class="form-label">Широта ГСО</label>
|
||||
<input type="number" step="0.000001" class="form-control" id="requestCoordsLat" name="coords_lat"
|
||||
placeholder="Например: 55.751244">
|
||||
</div>
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="requestCoordsLon" class="form-label">Долгота ГСО</label>
|
||||
<input type="number" step="0.000001" class="form-control" id="requestCoordsLon" name="coords_lon"
|
||||
placeholder="Например: 37.618423">
|
||||
</div>
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="requestCoordsSourceLat" class="form-label">Широта источника</label>
|
||||
<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 class="row">
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="requestCoordsObjectLat" class="form-label">Широта объекта</label>
|
||||
<input type="number" step="0.000001" class="form-control" id="requestCoordsObjectLat" name="coords_object_lat"
|
||||
placeholder="Например: 55.751244">
|
||||
</div>
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="requestCoordsObjectLon" class="form-label">Долгота объекта</label>
|
||||
<input type="number" step="0.000001" class="form-control" id="requestCoordsObjectLon" name="coords_object_lon"
|
||||
placeholder="Например: 37.618423">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Даты -->
|
||||
<div class="row">
|
||||
<div class="col-md-4 mb-3">
|
||||
<label for="requestPlannedAt" class="form-label">Дата и время планирования</label>
|
||||
<input type="datetime-local" class="form-control" id="requestPlannedAt" name="planned_at">
|
||||
</div>
|
||||
<div class="col-md-4 mb-3">
|
||||
<label for="requestDate" class="form-label">Дата заявки</label>
|
||||
<input type="date" class="form-control" id="requestDate" name="request_date">
|
||||
</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 class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="requestGsoSuccess" class="form-label">ГСО успешно?</label>
|
||||
<select class="form-select" id="requestGsoSuccess" name="gso_success">
|
||||
<option value="">-</option>
|
||||
<option value="true">Да</option>
|
||||
<option value="false">Нет</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="requestKubsatSuccess" class="form-label">Кубсат успешно?</label>
|
||||
<select class="form-select" id="requestKubsatSuccess" name="kubsat_success">
|
||||
<option value="">-</option>
|
||||
<option value="true">Да</option>
|
||||
<option value="false">Нет</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Комментарий -->
|
||||
<div class="mb-3">
|
||||
<label for="requestComment" class="form-label">Комментарий</label>
|
||||
<textarea class="form-control" id="requestComment" name="comment" rows="2"></textarea>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
||||
<button type="button" class="btn btn-primary" onclick="saveRequest()">
|
||||
<i class="bi bi-check-lg"></i> Сохранить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Модальное окно истории статусов -->
|
||||
<div class="modal fade" id="historyModal" tabindex="-1" aria-labelledby="historyModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header bg-info text-white">
|
||||
<h5 class="modal-title" id="historyModalLabel">
|
||||
<i class="bi bi-clock-history"></i> История изменений статуса
|
||||
</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="modal-body" id="historyModalBody">
|
||||
<div class="text-center py-4">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Загрузка...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Загрузка данных источника по ID
|
||||
function loadSourceData() {
|
||||
const sourceId = document.getElementById('requestSourceId').value;
|
||||
const resultDiv = document.getElementById('sourceCheckResult');
|
||||
const sourceDataCard = document.getElementById('sourceDataCard');
|
||||
|
||||
if (!sourceId) {
|
||||
resultDiv.innerHTML = '<span class="text-warning">Введите ID источника</span>';
|
||||
sourceDataCard.style.display = 'none';
|
||||
clearSourceData();
|
||||
return;
|
||||
}
|
||||
|
||||
resultDiv.innerHTML = '<span class="text-muted">Загрузка...</span>';
|
||||
|
||||
fetch(`{% url 'mainapp:source_data_api' source_id=0 %}`.replace('0', sourceId))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.found) {
|
||||
resultDiv.innerHTML = `<span class="text-success"><i class="bi bi-check-circle"></i> Источник #${sourceId} найден</span>`;
|
||||
|
||||
// Заполняем данные источника (только для чтения)
|
||||
document.getElementById('requestObjitemName').value = data.objitem_name || '-';
|
||||
document.getElementById('requestModulation').value = data.modulation || '-';
|
||||
document.getElementById('requestSymbolRate').value = data.symbol_rate || '-';
|
||||
|
||||
// Заполняем координаты ГСО (редактируемые)
|
||||
// if (data.coords_lat !== null) {
|
||||
// document.getElementById('requestCoordsLat').value = data.coords_lat.toFixed(6);
|
||||
// }
|
||||
// if (data.coords_lon !== null) {
|
||||
// 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';
|
||||
} else {
|
||||
resultDiv.innerHTML = `<span class="text-danger"><i class="bi bi-x-circle"></i> Источник #${sourceId} не найден</span>`;
|
||||
sourceDataCard.style.display = 'none';
|
||||
clearSourceData();
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
resultDiv.innerHTML = `<span class="text-danger"><i class="bi bi-x-circle"></i> Источник #${sourceId} не найден</span>`;
|
||||
sourceDataCard.style.display = 'none';
|
||||
clearSourceData();
|
||||
});
|
||||
}
|
||||
|
||||
// Очистка данных источника
|
||||
function clearSourceData() {
|
||||
document.getElementById('requestObjitemName').value = '';
|
||||
document.getElementById('requestModulation').value = '';
|
||||
document.getElementById('requestSymbolRate').value = '';
|
||||
document.getElementById('requestCoordsLat').value = '';
|
||||
document.getElementById('requestCoordsLon').value = '';
|
||||
document.getElementById('requestCoordsSourceLat').value = '';
|
||||
document.getElementById('requestCoordsSourceLon').value = '';
|
||||
document.getElementById('requestCoordsObjectLat').value = '';
|
||||
document.getElementById('requestCoordsObjectLon').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 = '';
|
||||
}
|
||||
|
||||
// Открытие модального окна создания заявки
|
||||
function openCreateRequestModal(sourceId = null) {
|
||||
document.getElementById('requestModalTitle').textContent = 'Создать заявку';
|
||||
document.getElementById('requestForm').reset();
|
||||
document.getElementById('requestId').value = '';
|
||||
document.getElementById('sourceCheckResult').innerHTML = '';
|
||||
document.getElementById('sourceDataCard').style.display = 'none';
|
||||
clearSourceData();
|
||||
|
||||
if (sourceId) {
|
||||
document.getElementById('requestSourceId').value = sourceId;
|
||||
loadSourceData();
|
||||
}
|
||||
|
||||
const modal = new bootstrap.Modal(document.getElementById('requestModal'));
|
||||
modal.show();
|
||||
}
|
||||
|
||||
// Открытие модального окна редактирования заявки
|
||||
function openEditRequestModal(requestId) {
|
||||
document.getElementById('requestModalTitle').textContent = 'Редактировать заявку';
|
||||
document.getElementById('sourceCheckResult').innerHTML = '';
|
||||
|
||||
fetch(`/api/source-request/${requestId}/`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.getElementById('requestId').value = data.id;
|
||||
document.getElementById('requestSourceId').value = data.source_id || '';
|
||||
document.getElementById('requestSatellite').value = data.satellite_id || '';
|
||||
document.getElementById('requestStatus').value = data.status;
|
||||
document.getElementById('requestPriority').value = data.priority;
|
||||
document.getElementById('requestPlannedAt').value = data.planned_at || '';
|
||||
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('requestKubsatSuccess').value = data.kubsat_success === null ? '' : data.kubsat_success.toString();
|
||||
document.getElementById('requestComment').value = data.comment || '';
|
||||
|
||||
// Заполняем данные источника
|
||||
document.getElementById('requestObjitemName').value = data.objitem_name || '-';
|
||||
document.getElementById('requestModulation').value = data.modulation || '-';
|
||||
document.getElementById('requestSymbolRate').value = data.symbol_rate || '-';
|
||||
|
||||
// Заполняем частоты
|
||||
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) {
|
||||
document.getElementById('requestCoordsLat').value = data.coords_lat.toFixed(6);
|
||||
} else {
|
||||
document.getElementById('requestCoordsLat').value = '';
|
||||
}
|
||||
if (data.coords_lon !== null) {
|
||||
document.getElementById('requestCoordsLon').value = data.coords_lon.toFixed(6);
|
||||
} else {
|
||||
document.getElementById('requestCoordsLon').value = '';
|
||||
}
|
||||
|
||||
// Заполняем координаты источника
|
||||
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 = '';
|
||||
}
|
||||
|
||||
// Заполняем координаты объекта
|
||||
if (data.coords_object_lat !== null) {
|
||||
document.getElementById('requestCoordsObjectLat').value = data.coords_object_lat.toFixed(6);
|
||||
} else {
|
||||
document.getElementById('requestCoordsObjectLat').value = '';
|
||||
}
|
||||
if (data.coords_object_lon !== null) {
|
||||
document.getElementById('requestCoordsObjectLon').value = data.coords_object_lon.toFixed(6);
|
||||
} else {
|
||||
document.getElementById('requestCoordsObjectLon').value = '';
|
||||
}
|
||||
|
||||
document.getElementById('sourceDataCard').style.display = data.source_id ? 'block' : 'none';
|
||||
|
||||
const modal = new bootstrap.Modal(document.getElementById('requestModal'));
|
||||
modal.show();
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error loading request:', error);
|
||||
alert('Ошибка загрузки данных заявки');
|
||||
});
|
||||
}
|
||||
|
||||
// Сохранение заявки
|
||||
function saveRequest() {
|
||||
const form = document.getElementById('requestForm');
|
||||
const formData = new FormData(form);
|
||||
const requestId = document.getElementById('requestId').value;
|
||||
|
||||
const url = requestId
|
||||
? `/source-requests/${requestId}/edit/`
|
||||
: '{% url "mainapp:source_request_create" %}';
|
||||
|
||||
fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-CSRFToken': formData.get('csrfmiddlewaretoken'),
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
},
|
||||
body: new URLSearchParams(formData)
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(result => {
|
||||
if (result.success) {
|
||||
// Properly close modal and remove backdrop
|
||||
const modalEl = document.getElementById('requestModal');
|
||||
const modalInstance = bootstrap.Modal.getInstance(modalEl);
|
||||
if (modalInstance) {
|
||||
modalInstance.hide();
|
||||
}
|
||||
// Remove any remaining backdrops
|
||||
document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
|
||||
document.body.classList.remove('modal-open');
|
||||
document.body.style.removeProperty('overflow');
|
||||
document.body.style.removeProperty('padding-right');
|
||||
|
||||
location.reload();
|
||||
} else {
|
||||
alert('Ошибка: ' + JSON.stringify(result.errors));
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error saving request:', error);
|
||||
alert('Ошибка сохранения заявки');
|
||||
});
|
||||
}
|
||||
|
||||
// Удаление заявки
|
||||
function deleteRequest(requestId) {
|
||||
if (!confirm('Вы уверены, что хотите удалить эту заявку?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`/source-requests/${requestId}/delete/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(result => {
|
||||
if (result.success) {
|
||||
location.reload();
|
||||
} else {
|
||||
alert('Ошибка: ' + result.error);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error deleting request:', error);
|
||||
alert('Ошибка удаления заявки');
|
||||
});
|
||||
}
|
||||
|
||||
// Показать историю статусов
|
||||
function showHistory(requestId) {
|
||||
const modal = new bootstrap.Modal(document.getElementById('historyModal'));
|
||||
modal.show();
|
||||
|
||||
const modalBody = document.getElementById('historyModalBody');
|
||||
modalBody.innerHTML = '<div class="text-center py-4"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Загрузка...</span></div></div>';
|
||||
|
||||
fetch(`/api/source-request/${requestId}/`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.history && data.history.length > 0) {
|
||||
let html = '<table class="table table-sm table-striped"><thead><tr><th>Старый статус</th><th>Новый статус</th><th>Дата изменения</th><th>Пользователь</th></tr></thead><tbody>';
|
||||
data.history.forEach(h => {
|
||||
html += `<tr><td>${h.old_status}</td><td>${h.new_status}</td><td>${h.changed_at}</td><td>${h.changed_by}</td></tr>`;
|
||||
});
|
||||
html += '</tbody></table>';
|
||||
modalBody.innerHTML = html;
|
||||
} else {
|
||||
modalBody.innerHTML = '<div class="alert alert-info">История изменений пуста</div>';
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
modalBody.innerHTML = '<div class="alert alert-danger">Ошибка загрузки истории</div>';
|
||||
});
|
||||
}
|
||||
|
||||
// Функция для показа модального окна LyngSat
|
||||
function showLyngsatModal(lyngsatId) {
|
||||
const modal = new bootstrap.Modal(document.getElementById('lyngsatModal'));
|
||||
modal.show();
|
||||
|
||||
const modalBody = document.getElementById('lyngsatModalBody');
|
||||
modalBody.innerHTML = '<div class="text-center py-4"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Загрузка...</span></div></div>';
|
||||
|
||||
fetch('/api/lyngsat/' + lyngsatId + '/')
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка загрузки данных');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
let html = '<div class="container-fluid"><div class="row g-3">' +
|
||||
'<div class="col-md-6"><div class="card h-100">' +
|
||||
'<div class="card-header bg-light"><strong><i class="bi bi-info-circle"></i> Основная информация</strong></div>' +
|
||||
'<div class="card-body"><table class="table table-sm table-borderless mb-0"><tbody>' +
|
||||
'<tr><td class="text-muted" style="width: 40%;">Спутник:</td><td><strong>' + data.satellite + '</strong></td></tr>' +
|
||||
'<tr><td class="text-muted">Частота:</td><td><strong>' + data.frequency + ' МГц</strong></td></tr>' +
|
||||
'<tr><td class="text-muted">Поляризация:</td><td><span class="badge bg-info">' + data.polarization + '</span></td></tr>' +
|
||||
'<tr><td class="text-muted">Канал:</td><td>' + data.channel_info + '</td></tr>' +
|
||||
'</tbody></table></div></div></div>' +
|
||||
'<div class="col-md-6"><div class="card h-100">' +
|
||||
'<div class="card-header bg-light"><strong><i class="bi bi-gear"></i> Технические параметры</strong></div>' +
|
||||
'<div class="card-body"><table class="table table-sm table-borderless mb-0"><tbody>' +
|
||||
'<tr><td class="text-muted" style="width: 40%;">Модуляция:</td><td><span class="badge bg-secondary">' + data.modulation + '</span></td></tr>' +
|
||||
'<tr><td class="text-muted">Стандарт:</td><td><span class="badge bg-secondary">' + data.standard + '</span></td></tr>' +
|
||||
'<tr><td class="text-muted">Сим. скорость:</td><td><strong>' + data.sym_velocity + ' БОД</strong></td></tr>' +
|
||||
'<tr><td class="text-muted">FEC:</td><td>' + data.fec + '</td></tr>' +
|
||||
'</tbody></table></div></div></div>' +
|
||||
'<div class="col-12"><div class="card">' +
|
||||
'<div class="card-header bg-light"><strong><i class="bi bi-clock-history"></i> Дополнительная информация</strong></div>' +
|
||||
'<div class="card-body"><div class="row">' +
|
||||
'<div class="col-md-6"><p class="mb-2"><span class="text-muted">Последнее обновление:</span><br><strong>' + data.last_update + '</strong></p></div>' +
|
||||
'<div class="col-md-6">' + (data.url ? '<p class="mb-2"><span class="text-muted">Ссылка на объект:</span><br>' +
|
||||
'<a href="' + data.url + '" target="_blank" class="btn btn-sm btn-outline-primary">' +
|
||||
'<i class="bi bi-link-45deg"></i> Открыть на LyngSat</a></p>' : '') +
|
||||
'</div></div></div></div></div></div></div>';
|
||||
modalBody.innerHTML = html;
|
||||
})
|
||||
.catch(error => {
|
||||
modalBody.innerHTML = '<div class="alert alert-danger" role="alert">' +
|
||||
'<i class="bi bi-exclamation-triangle"></i> ' + error.message + '</div>';
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Restore active tab from URL parameter
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const activeTab = urlParams.get('tab');
|
||||
if (activeTab === 'filters') {
|
||||
const filtersTab = document.getElementById('filters-tab');
|
||||
const requestsTab = document.getElementById('requests-tab');
|
||||
const filtersPane = document.getElementById('filters');
|
||||
const requestsPane = document.getElementById('requests');
|
||||
|
||||
if (filtersTab && requestsTab) {
|
||||
requestsTab.classList.remove('active');
|
||||
requestsTab.setAttribute('aria-selected', 'false');
|
||||
filtersTab.classList.add('active');
|
||||
filtersTab.setAttribute('aria-selected', 'true');
|
||||
|
||||
requestsPane.classList.remove('show', 'active');
|
||||
filtersPane.classList.add('show', 'active');
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- LyngSat Data Modal -->
|
||||
<div class="modal fade" id="lyngsatModal" tabindex="-1" aria-labelledby="lyngsatModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header bg-primary text-white">
|
||||
<h5 class="modal-title" id="lyngsatModalLabel">
|
||||
<i class="bi bi-tv"></i> Данные объекта LyngSat
|
||||
</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
|
||||
aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="modal-body" id="lyngsatModalBody">
|
||||
<div class="text-center py-4">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Загрузка...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
1475
dbapp/mainapp/templates/mainapp/multi_sources_playback_map.html
Normal file
1475
dbapp/mainapp/templates/mainapp/multi_sources_playback_map.html
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,516 +0,0 @@
|
||||
{% extends "mainapp/base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Наличие сигнала объектов{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
.sticky-top {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.source-info-cell {
|
||||
min-width: 200px;
|
||||
background-color: #f8f9fa;
|
||||
}
|
||||
|
||||
.param-cell {
|
||||
min-width: 120px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.marks-cell {
|
||||
min-width: 150px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.actions-cell {
|
||||
min-width: 180px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.mark-status {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.mark-present {
|
||||
color: #28a745;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.mark-absent {
|
||||
color: #dc3545;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.btn-mark {
|
||||
padding: 6px 16px;
|
||||
font-size: 0.875rem;
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.btn-edit-mark {
|
||||
padding: 2px 8px;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.no-marks {
|
||||
color: #6c757d;
|
||||
font-style: italic;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.btn-mark:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-edit-mark:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.mark-status {
|
||||
transition: color 0.3s ease;
|
||||
}
|
||||
|
||||
.btn-edit-mark:hover:not(:disabled) {
|
||||
background-color: #6c757d;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.satellite-selector {
|
||||
background-color: #f8f9fa;
|
||||
border: 1px solid #dee2e6;
|
||||
border-radius: 0.375rem;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.satellite-selector h5 {
|
||||
margin-bottom: 1rem;
|
||||
color: #495057;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="{% if full_width_page %}container-fluid{% else %}container{% endif %} px-3">
|
||||
<!-- Page Header -->
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<h2>Наличие сигнала объектов</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Satellite Selector -->
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<div class="satellite-selector">
|
||||
<h5>Выберите спутник:</h5>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<select id="satellite-select" class="form-select" onchange="selectSatellite()">
|
||||
<option value="">-- Выберите спутник --</option>
|
||||
{% for satellite in satellites %}
|
||||
<option value="{{ satellite.id }}" {% if satellite.id == selected_satellite_id %}selected{% endif %}>
|
||||
{{ satellite.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if selected_satellite_id %}
|
||||
<!-- Toolbar with search, pagination, and filters -->
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
{% include 'mainapp/components/_toolbar.html' with show_search=True show_filters=True show_actions=False search_placeholder='Поиск по ID или имени объекта...' %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Table -->
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body p-0">
|
||||
<div class="table-responsive" style="max-height: 75vh; overflow-y: auto;">
|
||||
<table class="table table-striped table-hover table-sm table-bordered mb-0">
|
||||
<thead class="table-dark sticky-top">
|
||||
<tr>
|
||||
<th class="source-info-cell">
|
||||
{% include 'mainapp/components/_sort_header.html' with field='id' label='ID / Имя' current_sort=sort %}
|
||||
</th>
|
||||
<th class="param-cell">
|
||||
{% include 'mainapp/components/_sort_header.html' with field='frequency' label='Частота, МГц' current_sort=sort %}
|
||||
</th>
|
||||
<th class="param-cell">
|
||||
{% include 'mainapp/components/_sort_header.html' with field='freq_range' label='Полоса, МГц' current_sort=sort %}
|
||||
</th>
|
||||
<th class="param-cell">Поляризация</th>
|
||||
<th class="param-cell">Модуляция</th>
|
||||
<th class="param-cell">
|
||||
{% include 'mainapp/components/_sort_header.html' with field='bod_velocity' label='Бодовая скорость' current_sort=sort %}
|
||||
</th>
|
||||
<th class="marks-cell">Наличие</th>
|
||||
<th class="marks-cell">
|
||||
{% include 'mainapp/components/_sort_header.html' with field='last_mark_date' label='Дата и время' current_sort=sort %}
|
||||
</th>
|
||||
<th class="actions-cell">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for source in sources %}
|
||||
{% with marks=source.marks.all %}
|
||||
{% if marks %}
|
||||
<!-- Первая строка с информацией об объекте и первой отметкой -->
|
||||
<tr data-source-id="{{ source.id }}">
|
||||
<td class="source-info-cell" rowspan="{{ marks.count }}">
|
||||
<div><strong>ID:</strong> {{ source.id }}</div>
|
||||
<div><strong>Имя:</strong> {{ source.objitem_name }}</div>
|
||||
</td>
|
||||
<td class="param-cell" rowspan="{{ marks.count }}">{{ source.frequency }}</td>
|
||||
<td class="param-cell" rowspan="{{ marks.count }}">{{ source.freq_range }}</td>
|
||||
<td class="param-cell" rowspan="{{ marks.count }}">{{ source.polarization }}</td>
|
||||
<td class="param-cell" rowspan="{{ marks.count }}">{{ source.modulation }}</td>
|
||||
<td class="param-cell" rowspan="{{ marks.count }}">{{ source.bod_velocity }}</td>
|
||||
{% with first_mark=marks.0 %}
|
||||
<td class="marks-cell" data-mark-id="{{ first_mark.id }}">
|
||||
<span class="mark-status {% if first_mark.mark %}mark-present{% else %}mark-absent{% endif %}">
|
||||
{% if first_mark.mark %}✓ Есть{% else %}✗ Нет{% endif %}
|
||||
</span>
|
||||
{% if first_mark.can_edit %}
|
||||
<button class="btn btn-sm btn-outline-secondary btn-edit-mark ms-2"
|
||||
onclick="toggleMark({{ first_mark.id }}, {{ first_mark.mark|yesno:'true,false' }})">
|
||||
✎
|
||||
</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="marks-cell">
|
||||
<div>{{ first_mark.timestamp|date:"d.m.Y H:i" }}</div>
|
||||
<small class="text-muted">{{ first_mark.created_by|default:"—" }}</small>
|
||||
</td>
|
||||
<td class="actions-cell" rowspan="{{ marks.count }}">
|
||||
<div class="action-buttons" id="actions-{{ source.id }}">
|
||||
<button class="btn btn-success btn-mark btn-sm"
|
||||
onclick="addMark({{ source.id }}, true)">
|
||||
✓ Есть
|
||||
</button>
|
||||
<button class="btn btn-danger btn-mark btn-sm"
|
||||
onclick="addMark({{ source.id }}, false)">
|
||||
✗ Нет
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
{% endwith %}
|
||||
</tr>
|
||||
|
||||
<!-- Остальные отметки -->
|
||||
{% for mark in marks|slice:"1:" %}
|
||||
<tr data-source-id="{{ source.id }}">
|
||||
<td class="marks-cell" data-mark-id="{{ mark.id }}">
|
||||
<span class="mark-status {% if mark.mark %}mark-present{% else %}mark-absent{% endif %}">
|
||||
{% if mark.mark %}✓ Есть{% else %}✗ Нет{% endif %}
|
||||
</span>
|
||||
{% if mark.can_edit %}
|
||||
<button class="btn btn-sm btn-outline-secondary btn-edit-mark ms-2"
|
||||
onclick="toggleMark({{ mark.id }}, {{ mark.mark|yesno:'true,false' }})">
|
||||
✎
|
||||
</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="marks-cell">
|
||||
<div>{{ mark.timestamp|date:"d.m.Y H:i" }}</div>
|
||||
<small class="text-muted">{{ mark.created_by|default:"—" }}</small>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<!-- Объект без отметок -->
|
||||
<tr data-source-id="{{ source.id }}">
|
||||
<td class="source-info-cell">
|
||||
<div><strong>ID:</strong> {{ source.id }}</div>
|
||||
<div><strong>Имя:</strong> {{ source.objitem_name }}</div>
|
||||
</td>
|
||||
<td class="param-cell">{{ source.frequency }}</td>
|
||||
<td class="param-cell">{{ source.freq_range }}</td>
|
||||
<td class="param-cell">{{ source.polarization }}</td>
|
||||
<td class="param-cell">{{ source.modulation }}</td>
|
||||
<td class="param-cell">{{ source.bod_velocity }}</td>
|
||||
<td colspan="2" class="no-marks">Отметок нет</td>
|
||||
<td class="actions-cell">
|
||||
<div class="action-buttons" id="actions-{{ source.id }}">
|
||||
<button class="btn btn-success btn-mark btn-sm"
|
||||
onclick="addMark({{ source.id }}, true)">
|
||||
✓ Есть
|
||||
</button>
|
||||
<button class="btn btn-danger btn-mark btn-sm"
|
||||
onclick="addMark({{ source.id }}, false)">
|
||||
✗ Нет
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td colspan="9" class="text-center py-4">
|
||||
<p class="text-muted mb-0">Объекты не найдены для выбранного спутника</p>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<!-- No satellite selected message -->
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="alert alert-info text-center">
|
||||
<h5>Пожалуйста, выберите спутник для просмотра объектов</h5>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Offcanvas Filter Panel -->
|
||||
<div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasFilters" aria-labelledby="offcanvasFiltersLabel">
|
||||
<div class="offcanvas-header">
|
||||
<h5 class="offcanvas-title" id="offcanvasFiltersLabel">Фильтры</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="offcanvas-body">
|
||||
<form method="get" id="filter-form">
|
||||
<!-- Mark Status Filter -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Статус отметок:</label>
|
||||
<select name="mark_status" class="form-select form-select-sm">
|
||||
<option value="">Все</option>
|
||||
<option value="with_marks" {% if filter_mark_status == 'with_marks' %}selected{% endif %}>С отметками</option>
|
||||
<option value="without_marks" {% if filter_mark_status == 'without_marks' %}selected{% endif %}>Без отметок</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Date Range Filters -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Дата отметки от:</label>
|
||||
<input type="date" class="form-control form-control-sm" name="date_from" value="{{ filter_date_from }}">
|
||||
</div>
|
||||
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Дата отметки до:</label>
|
||||
<input type="date" class="form-control form-control-sm" name="date_to" value="{{ filter_date_to }}">
|
||||
</div>
|
||||
|
||||
<!-- User Selection - Multi-select -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Пользователь:</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('user_id', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('user_id', false)">Снять</button>
|
||||
</div>
|
||||
<select name="user_id" class="form-select form-select-sm mb-2" multiple size="6">
|
||||
{% for user in users %}
|
||||
<option value="{{ user.id }}" {% if user.id in selected_users %}selected{% endif %}>
|
||||
{{ user.user.username }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{# Сохраняем параметры сортировки, поиска и спутника при применении фильтров #}
|
||||
{% if selected_satellite_id %}
|
||||
<input type="hidden" name="satellite_id" value="{{ selected_satellite_id }}">
|
||||
{% endif %}
|
||||
{% if request.GET.sort %}
|
||||
<input type="hidden" name="sort" value="{{ request.GET.sort }}">
|
||||
{% endif %}
|
||||
{% if request.GET.search %}
|
||||
<input type="hidden" name="search" value="{{ request.GET.search }}">
|
||||
{% endif %}
|
||||
{% if request.GET.items_per_page %}
|
||||
<input type="hidden" name="items_per_page" value="{{ request.GET.items_per_page }}">
|
||||
{% endif %}
|
||||
|
||||
<div class="d-grid gap-2 mt-3">
|
||||
<button type="submit" class="btn btn-primary btn-sm">
|
||||
Применить
|
||||
</button>
|
||||
<a href="?{% if selected_satellite_id %}satellite_id={{ selected_satellite_id }}{% endif %}" class="btn btn-secondary btn-sm">
|
||||
Сбросить
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Satellite selection
|
||||
function selectSatellite() {
|
||||
const select = document.getElementById('satellite-select');
|
||||
const satelliteId = select.value;
|
||||
|
||||
if (satelliteId) {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
urlParams.set('satellite_id', satelliteId);
|
||||
|
||||
// Reset page when changing satellite
|
||||
urlParams.delete('page');
|
||||
|
||||
window.location.search = urlParams.toString();
|
||||
} else {
|
||||
// Clear all params if no satellite selected
|
||||
window.location.search = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Multi-select helper function
|
||||
function selectAllOptions(selectName, select) {
|
||||
const selectElement = document.querySelector(`select[name="${selectName}"]`);
|
||||
if (selectElement) {
|
||||
for (let option of selectElement.options) {
|
||||
option.selected = select;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update filter counter badge when filters are active
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const filterCounter = document.getElementById('filterCounter');
|
||||
|
||||
if (filterCounter) {
|
||||
// Count active filters (excluding pagination, sort, search, items_per_page, and satellite_id)
|
||||
const excludedParams = ['page', 'sort', 'search', 'items_per_page', 'satellite_id'];
|
||||
let activeFilters = 0;
|
||||
|
||||
for (const [key, value] of urlParams.entries()) {
|
||||
if (!excludedParams.includes(key) && value) {
|
||||
activeFilters++;
|
||||
}
|
||||
}
|
||||
|
||||
if (activeFilters > 0) {
|
||||
filterCounter.textContent = activeFilters;
|
||||
filterCounter.style.display = 'inline-block';
|
||||
} else {
|
||||
filterCounter.style.display = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
function addMark(sourceId, mark) {
|
||||
// Отключить кнопки для этого объекта
|
||||
const buttons = document.querySelectorAll(`#actions-${sourceId} button`);
|
||||
buttons.forEach(btn => btn.disabled = true);
|
||||
|
||||
fetch("{% url 'mainapp:add_object_mark' %}", {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-CSRFToken': '{{ csrf_token }}'
|
||||
},
|
||||
body: `source_id=${sourceId}&mark=${mark}`
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
// Перезагрузить страницу для обновления таблицы
|
||||
location.reload();
|
||||
} else {
|
||||
// Включить кнопки обратно
|
||||
buttons.forEach(btn => btn.disabled = false);
|
||||
alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
buttons.forEach(btn => btn.disabled = false);
|
||||
alert('Ошибка при добавлении наличие сигнала');
|
||||
});
|
||||
}
|
||||
|
||||
function toggleMark(markId, currentValue) {
|
||||
const newValue = !currentValue;
|
||||
const cell = document.querySelector(`td[data-mark-id="${markId}"]`);
|
||||
const editBtn = cell.querySelector('.btn-edit-mark');
|
||||
|
||||
// Отключить кнопку редактирования на время запроса
|
||||
if (editBtn) {
|
||||
editBtn.disabled = true;
|
||||
}
|
||||
|
||||
fetch("{% url 'mainapp:update_object_mark' %}", {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-CSRFToken': '{{ csrf_token }}'
|
||||
},
|
||||
body: `mark_id=${markId}&mark=${newValue}`
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
// Обновить отображение наличие сигнала без перезагрузки страницы
|
||||
const statusSpan = cell.querySelector('.mark-status');
|
||||
|
||||
if (data.mark.mark) {
|
||||
statusSpan.textContent = '✓ Есть';
|
||||
statusSpan.className = 'mark-status mark-present';
|
||||
} else {
|
||||
statusSpan.textContent = '✗ Нет';
|
||||
statusSpan.className = 'mark-status mark-absent';
|
||||
}
|
||||
|
||||
// Обновить значение в onclick для следующего переключения
|
||||
if (editBtn) {
|
||||
editBtn.setAttribute('onclick', `toggleMark(${markId}, ${data.mark.mark})`);
|
||||
editBtn.disabled = false;
|
||||
}
|
||||
|
||||
// Если больше нельзя редактировать, убрать кнопку
|
||||
if (!data.mark.can_edit && editBtn) {
|
||||
editBtn.remove();
|
||||
}
|
||||
} else {
|
||||
// Включить кнопку обратно при ошибке
|
||||
if (editBtn) {
|
||||
editBtn.disabled = false;
|
||||
}
|
||||
alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
if (editBtn) {
|
||||
editBtn.disabled = false;
|
||||
}
|
||||
alert('Ошибка при изменении наличие сигнала');
|
||||
});
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -3,7 +3,7 @@
|
||||
{% load static leaflet_tags %}
|
||||
{% load l10n %}
|
||||
|
||||
{% block title %}{% if object %}Редактировать объект: {{ object.name }}{% else %}Создать объект{% endif %}{% endblock %}
|
||||
{% block title %}{% if object %}Редактировать объект: {{ object.name }}{% else %}Создать новый объект{% endif %}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link rel="stylesheet" href="{% static 'css/checkbox-select-multiple.css' %}">
|
||||
@@ -144,7 +144,7 @@
|
||||
<div class="container-fluid px-3">
|
||||
<div class="row mb-3">
|
||||
<div class="col-12 d-flex justify-content-between align-items-center">
|
||||
<h2>{% if object %}Редактировать объект: {{ object.name }}{% else %}Создать объект{% endif %}</h2>
|
||||
<h2>{% if object %}Редактировать объект: {{ object.name }}{% else %}Создать новый объект{% endif %}</h2>
|
||||
<div>
|
||||
{% if user.customuser.role == 'admin' or user.customuser.role == 'moderator' %}
|
||||
<button type="submit" form="objitem-form" class="btn btn-primary btn-action">Сохранить</button>
|
||||
@@ -248,6 +248,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if object %}
|
||||
<!-- Транспондер -->
|
||||
<div class="form-section">
|
||||
<div class="form-section-header">
|
||||
@@ -339,6 +340,7 @@
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- Блок с картой -->
|
||||
<div class="form-section">
|
||||
|
||||
@@ -3,14 +3,21 @@
|
||||
|
||||
{% block title %}Список объектов{% endblock %}
|
||||
{% block extra_css %}
|
||||
<link href="{% static 'leaflet/leaflet.css' %}" rel="stylesheet">
|
||||
<link href="{% static 'leaflet-draw/leaflet.draw.css' %}" rel="stylesheet">
|
||||
<style>
|
||||
.table-responsive tr.selected {
|
||||
background-color: #d4edff;
|
||||
}
|
||||
#polygonFilterMap {
|
||||
z-index: 1;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'js/sorting.js' %}"></script>
|
||||
<script src="{% static 'leaflet/leaflet.js' %}"></script>
|
||||
<script src="{% static 'leaflet-draw/leaflet.draw.js' %}"></script>
|
||||
{% endblock %}
|
||||
{% block content %}
|
||||
<div class="container-fluid px-3">
|
||||
@@ -40,22 +47,22 @@
|
||||
|
||||
<!-- Action buttons bar -->
|
||||
<div class="d-flex gap-2">
|
||||
{% comment %} <button type="button" class="btn btn-success btn-sm" title="Добавить">
|
||||
<i class="bi bi-plus-circle"></i> Добавить
|
||||
</button>
|
||||
<button type="button" class="btn btn-info btn-sm" title="Изменить">
|
||||
<i class="bi bi-pencil"></i> Изменить
|
||||
</button> {% endcomment %}
|
||||
{% if user.customuser.role == 'admin' or user.customuser.role == 'moderator' %}
|
||||
<a href="{% url 'mainapp:objitem_create' %}" class="btn btn-success btn-sm" title="Создать новый объект">
|
||||
<i class="bi bi-plus-circle"></i> Создать
|
||||
</a>
|
||||
<button type="button" class="btn btn-danger btn-sm" title="Удалить"
|
||||
onclick="deleteSelectedObjects()">
|
||||
<i class="bi bi-trash"></i> Удалить
|
||||
</button>
|
||||
{% endif %}
|
||||
<button type="button" class="btn btn-outline-primary btn-sm" title="Показать на карте"
|
||||
<button type="button" class="btn btn-primary btn-sm" title="Показать на карте"
|
||||
onclick="showSelectedOnMap()">
|
||||
<i class="bi bi-map"></i> Карта
|
||||
</button>
|
||||
<!-- <a href="{% url 'mainapp:tech_analyze_entry' %}" class="btn btn-info btn-sm" title="Тех. анализ">
|
||||
<i class="bi bi-clipboard-data"></i> Тех. анализ
|
||||
</a> -->
|
||||
</div>
|
||||
|
||||
<!-- Items per page select moved here -->
|
||||
@@ -118,19 +125,66 @@
|
||||
</div>
|
||||
<div class="offcanvas-body">
|
||||
<form method="get" id="filter-form">
|
||||
<!-- Satellite Selection - Multi-select -->
|
||||
<!-- Hidden field to preserve polygon filter -->
|
||||
{% if polygon_coords %}
|
||||
<input type="hidden" name="polygon" value="{{ polygon_coords }}">
|
||||
{% endif %}
|
||||
|
||||
<!-- Polygon Filter Section -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label fw-bold">
|
||||
<i class="bi bi-pentagon"></i> Фильтр по полигону
|
||||
</label>
|
||||
<div class="d-grid gap-2">
|
||||
<button type="button" class="btn btn-outline-success btn-sm"
|
||||
onclick="openPolygonFilterMap()">
|
||||
<i class="bi bi-pentagon"></i> Нарисовать полигон
|
||||
{% if polygon_coords %}
|
||||
<span class="badge bg-success ms-1">✓ Активен</span>
|
||||
{% endif %}
|
||||
</button>
|
||||
{% if polygon_coords %}
|
||||
<button type="button" class="btn btn-outline-danger btn-sm"
|
||||
onclick="clearPolygonFilter()" title="Очистить фильтр по полигону">
|
||||
<i class="bi bi-x-circle"></i> Очистить полигон
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr class="my-3">
|
||||
|
||||
<!-- Satellite Filter -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Спутник:</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('satellite_id', true)">Выбрать</button>
|
||||
onclick="selectAllOptions('satellite', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('satellite_id', false)">Снять</button>
|
||||
onclick="selectAllOptions('satellite', false)">Снять</button>
|
||||
</div>
|
||||
<select name="satellite_id" class="form-select form-select-sm mb-2" multiple size="6">
|
||||
{% for satellite in satellites %}
|
||||
<option value="{{ satellite.id }}" {% if satellite.id in selected_satellites %}selected{% endif %}>
|
||||
{{ satellite.name }}
|
||||
<select name="satellite" class="form-select form-select-sm mb-2" multiple size="6">
|
||||
{% for sat in satellites %}
|
||||
<option value="{{ sat.id }}" {% if sat.id in selected_satellites %}selected{% endif %}>
|
||||
{{ sat.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Complex Filter -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Комплекс:</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('complex', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('complex', false)">Снять</button>
|
||||
</div>
|
||||
<select name="complex" class="form-select form-select-sm mb-2" multiple size="2">
|
||||
{% for complex_code, complex_name in complexes %}
|
||||
<option value="{{ complex_code }}" {% if complex_code in selected_complexes %}selected{% endif %}>
|
||||
{{ complex_name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
@@ -208,37 +262,37 @@
|
||||
</select>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Source Type Filter -->
|
||||
<!-- Standard Filter -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Тип точки:</label>
|
||||
<div>
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" name="has_source_type"
|
||||
id="has_source_type_1" value="1" {% if has_source_type == '1' %}checked{% endif %}>
|
||||
<label class="form-check-label" for="has_source_type_1">Есть (ТВ)</label>
|
||||
</div>
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" name="has_source_type"
|
||||
id="has_source_type_0" value="0" {% if has_source_type == '0' %}checked{% endif %}>
|
||||
<label class="form-check-label" for="has_source_type_0">Нет</label>
|
||||
</div>
|
||||
<label class="form-label">Стандарт:</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('standard', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('standard', false)">Снять</button>
|
||||
</div>
|
||||
<select name="standard" class="form-select form-select-sm mb-2" multiple size="4">
|
||||
{% for std in standards %}
|
||||
<option value="{{ std.id }}" {% if std.id in selected_standards %}selected{% endif %}>
|
||||
{{ std.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Sigma Filter -->
|
||||
<!-- Automatic Filter -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Sigma:</label>
|
||||
<label class="form-label">Автоматическая:</label>
|
||||
<div>
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" name="has_sigma" id="has_sigma_1" value="1"
|
||||
{% if has_sigma == '1' %}checked{% endif %}>
|
||||
<label class="form-check-label" for="has_sigma_1">Есть</label>
|
||||
<input class="form-check-input" type="checkbox" name="is_automatic" id="is_automatic_1" value="1"
|
||||
{% if is_automatic == '1' %}checked{% endif %}>
|
||||
<label class="form-check-label" for="is_automatic_1">Да</label>
|
||||
</div>
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" name="has_sigma" id="has_sigma_0" value="0"
|
||||
{% if has_sigma == '0' %}checked{% endif %}>
|
||||
<label class="form-check-label" for="has_sigma_0">Нет</label>
|
||||
<input class="form-check-input" type="checkbox" name="is_automatic" id="is_automatic_0" value="0"
|
||||
{% if is_automatic == '0' %}checked{% endif %}>
|
||||
<label class="form-check-label" for="is_automatic_0">Нет</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -266,6 +320,24 @@
|
||||
value="{{ date_to|default:'' }}">
|
||||
</div>
|
||||
|
||||
<!-- Mirrors Filter -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Зеркала:</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('mirror', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary"
|
||||
onclick="selectAllOptions('mirror', false)">Снять</button>
|
||||
</div>
|
||||
<select name="mirror" class="form-select form-select-sm mb-2" multiple size="6">
|
||||
{% for mir in mirrors %}
|
||||
<option value="{{ mir.id }}" {% if mir.id in selected_mirrors %}selected{% endif %}>
|
||||
{{ mir.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Apply Filters and Reset Buttons -->
|
||||
<div class="d-grid gap-2 mt-2">
|
||||
<button type="submit" class="btn btn-primary btn-sm">Применить</button>
|
||||
@@ -293,7 +365,7 @@
|
||||
{% include 'mainapp/components/_table_header.html' with label="Част, МГц" field="frequency" sort=sort %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Полоса, МГц" field="freq_range" sort=sort %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Поляризация" field="polarization" sort=sort %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Сим. V" field="bod_velocity" sort=sort %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Сим. скор." field="bod_velocity" sort=sort %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Модул" field="modulation" sort=sort %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="ОСШ" field="snr" sort=sort %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Время ГЛ" field="geo_timestamp" sort=sort %}
|
||||
@@ -307,8 +379,8 @@
|
||||
{% include 'mainapp/components/_table_header.html' with label="Усреднённое" field="" sortable=False %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Стандарт" field="standard" sort=sort %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Тип точки" field="" sortable=False %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Sigma" field="" sortable=False %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Зеркала" field="" sortable=False %}
|
||||
{% include 'mainapp/components/_table_header.html' with label="Автоматическая?" field="is_automatic" sort=sort %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -366,18 +438,8 @@
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if item.has_sigma %}
|
||||
<a href="#" class="text-info text-decoration-none"
|
||||
onclick="showSigmaParameterModal({{ item.obj.parameter_obj.id }}); return false;"
|
||||
title="{{ item.sigma_info }}">
|
||||
<i class="bi bi-graph-up"></i> {{ item.sigma_info }}
|
||||
</a>
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ item.mirrors }}</td>
|
||||
<td>{{ item.mirrors_display|safe }}</td>
|
||||
<td>{{ item.is_automatic }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
@@ -538,7 +600,29 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Остальной ваш JavaScript код остается без изменений
|
||||
// Column visibility functions with localStorage support
|
||||
function getColumnVisibilityKey() {
|
||||
return 'objitemListColumnVisibility';
|
||||
}
|
||||
|
||||
function saveColumnVisibility() {
|
||||
const columnCheckboxes = document.querySelectorAll('.column-toggle');
|
||||
const visibility = {};
|
||||
columnCheckboxes.forEach(checkbox => {
|
||||
const columnIndex = checkbox.getAttribute('data-column');
|
||||
visibility[columnIndex] = checkbox.checked;
|
||||
});
|
||||
localStorage.setItem(getColumnVisibilityKey(), JSON.stringify(visibility));
|
||||
}
|
||||
|
||||
function loadColumnVisibility() {
|
||||
const saved = localStorage.getItem(getColumnVisibilityKey());
|
||||
if (saved) {
|
||||
return JSON.parse(saved);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toggleColumn(checkbox) {
|
||||
const columnIndex = parseInt(checkbox.getAttribute('data-column'));
|
||||
const table = document.querySelector('.table');
|
||||
@@ -553,7 +637,27 @@
|
||||
cell.style.display = 'none';
|
||||
});
|
||||
}
|
||||
|
||||
// Save state after toggle
|
||||
saveColumnVisibility();
|
||||
}
|
||||
|
||||
function toggleColumnWithoutSave(checkbox) {
|
||||
const columnIndex = parseInt(checkbox.getAttribute('data-column'));
|
||||
const table = document.querySelector('.table');
|
||||
const cells = table.querySelectorAll(`td:nth-child(${columnIndex + 1}), th:nth-child(${columnIndex + 1})`);
|
||||
|
||||
if (checkbox.checked) {
|
||||
cells.forEach(cell => {
|
||||
cell.style.display = '';
|
||||
});
|
||||
} else {
|
||||
cells.forEach(cell => {
|
||||
cell.style.display = 'none';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function toggleAllColumns(selectAllCheckbox) {
|
||||
const columnCheckboxes = document.querySelectorAll('.column-toggle');
|
||||
columnCheckboxes.forEach(checkbox => {
|
||||
@@ -612,6 +716,7 @@
|
||||
setupRadioLikeCheckboxes('has_valid');
|
||||
setupRadioLikeCheckboxes('has_source_type');
|
||||
setupRadioLikeCheckboxes('has_sigma');
|
||||
setupRadioLikeCheckboxes('is_automatic');
|
||||
|
||||
// Date range quick selection functions
|
||||
window.setDateRange = function (period) {
|
||||
@@ -717,36 +822,32 @@
|
||||
|
||||
// Initialize column visibility - hide creation columns by default
|
||||
function initColumnVisibility() {
|
||||
const creationDateCheckbox = document.querySelector('input[data-column="15"]');
|
||||
const creationUserCheckbox = document.querySelector('input[data-column="16"]');
|
||||
if (creationDateCheckbox) {
|
||||
creationDateCheckbox.checked = false;
|
||||
toggleColumn(creationDateCheckbox);
|
||||
const savedVisibility = loadColumnVisibility();
|
||||
|
||||
if (savedVisibility) {
|
||||
// Restore saved state
|
||||
const columnCheckboxes = document.querySelectorAll('.column-toggle');
|
||||
columnCheckboxes.forEach(checkbox => {
|
||||
const columnIndex = checkbox.getAttribute('data-column');
|
||||
if (savedVisibility.hasOwnProperty(columnIndex)) {
|
||||
checkbox.checked = savedVisibility[columnIndex];
|
||||
toggleColumnWithoutSave(checkbox);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Default state: hide specific columns
|
||||
const columnsToHide = [15, 16, 17, 18, 19]; // Создано, Кем(созд), Комментарий, Усреднённое, Стандарт
|
||||
|
||||
if (creationUserCheckbox) {
|
||||
creationUserCheckbox.checked = false;
|
||||
toggleColumn(creationUserCheckbox);
|
||||
columnsToHide.forEach(columnIndex => {
|
||||
const checkbox = document.querySelector(`input[data-column="${columnIndex}"]`);
|
||||
if (checkbox) {
|
||||
checkbox.checked = false;
|
||||
toggleColumnWithoutSave(checkbox);
|
||||
}
|
||||
});
|
||||
|
||||
// Hide comment, is_average, and standard columns by default
|
||||
const commentCheckbox = document.querySelector('input[data-column="17"]');
|
||||
const isAverageCheckbox = document.querySelector('input[data-column="18"]');
|
||||
const standardCheckbox = document.querySelector('input[data-column="19"]');
|
||||
|
||||
if (commentCheckbox) {
|
||||
commentCheckbox.checked = false;
|
||||
toggleColumn(commentCheckbox);
|
||||
}
|
||||
|
||||
if (isAverageCheckbox) {
|
||||
isAverageCheckbox.checked = false;
|
||||
toggleColumn(isAverageCheckbox);
|
||||
}
|
||||
|
||||
if (standardCheckbox) {
|
||||
standardCheckbox.checked = false;
|
||||
toggleColumn(standardCheckbox);
|
||||
// Save initial state
|
||||
saveColumnVisibility();
|
||||
}
|
||||
}
|
||||
// Filter counter functionality
|
||||
@@ -756,19 +857,24 @@
|
||||
let filterCount = 0;
|
||||
|
||||
// Count non-empty form fields
|
||||
const multiSelectFieldNames = ['modulation', 'polarization', 'standard', 'satellite', 'mirror', 'complex'];
|
||||
for (const [key, value] of formData.entries()) {
|
||||
if (value && value.trim() !== '') {
|
||||
// For multi-select fields, we need to handle them separately
|
||||
if (key === 'satellite_id' || key === 'modulation' || key === 'polarization') {
|
||||
if (multiSelectFieldNames.includes(key)) {
|
||||
// Skip counting individual selections - they'll be counted as one filter
|
||||
continue;
|
||||
}
|
||||
// Skip polygon hidden field - counted separately
|
||||
if (key === 'polygon') {
|
||||
continue;
|
||||
}
|
||||
filterCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// Count selected options in multi-select fields
|
||||
const multiSelectFields = ['satellite_id', 'modulation', 'polarization'];
|
||||
const multiSelectFields = ['modulation', 'polarization', 'standard', 'satellite', 'mirror', 'complex'];
|
||||
for (const field of multiSelectFields) {
|
||||
const selectElement = document.querySelector(`select[name="${field}"]`);
|
||||
if (selectElement) {
|
||||
@@ -779,14 +885,9 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Count checkbox filters
|
||||
const hasKupsatCheckboxes = document.querySelectorAll('input[name="has_kupsat"]:checked');
|
||||
const hasValidCheckboxes = document.querySelectorAll('input[name="has_valid"]:checked');
|
||||
|
||||
if (hasKupsatCheckboxes.length > 0) {
|
||||
filterCount++;
|
||||
}
|
||||
if (hasValidCheckboxes.length > 0) {
|
||||
// Check if polygon filter is active
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
if (urlParams.has('polygon')) {
|
||||
filterCount++;
|
||||
}
|
||||
|
||||
@@ -915,7 +1016,7 @@
|
||||
updated_by: row.cells[14].textContent,
|
||||
created_at: row.cells[15].textContent,
|
||||
created_by: row.cells[16].textContent,
|
||||
mirrors: row.cells[22].textContent
|
||||
mirrors: row.cells[21].textContent
|
||||
};
|
||||
|
||||
window.selectedItems.push(rowData);
|
||||
@@ -1006,16 +1107,19 @@
|
||||
populateSelectedItemsTable();
|
||||
}
|
||||
|
||||
// Function to send selected items (placeholder)
|
||||
function sendSelectedItems() {
|
||||
const selectedCount = document.querySelectorAll('#selected-items-table-body .selected-item-checkbox:checked').length;
|
||||
if (selectedCount === 0) {
|
||||
alert('Пожалуйста, выберите хотя бы один элемент для отправки');
|
||||
// Function to show selected items on map
|
||||
function showSelectedItemsOnMap() {
|
||||
if (!window.selectedItems || window.selectedItems.length === 0) {
|
||||
alert('Список точек пуст');
|
||||
return;
|
||||
}
|
||||
|
||||
alert(`Отправка ${selectedCount} элементов... (функция в разработке)`);
|
||||
// Placeholder for actual send functionality
|
||||
// Extract IDs from selected items
|
||||
const selectedIds = window.selectedItems.map(item => item.id);
|
||||
|
||||
// Redirect to the map view with selected IDs as query parameter
|
||||
const url = '{% url "mainapp:show_selected_objects_map" %}' + '?ids=' + selectedIds.join(',');
|
||||
window.open(url, '_blank'); // Open in a new tab
|
||||
}
|
||||
|
||||
// Function to toggle all checkboxes in the selected items table
|
||||
@@ -1353,4 +1457,190 @@
|
||||
<!-- Include the satellite modal component -->
|
||||
{% include 'mainapp/components/_satellite_modal.html' %}
|
||||
|
||||
<!-- Polygon Filter Modal -->
|
||||
<div class="modal fade" id="polygonFilterModal" tabindex="-1" aria-labelledby="polygonFilterModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-xl">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header bg-success text-white">
|
||||
<h5 class="modal-title" id="polygonFilterModalLabel">
|
||||
<i class="bi bi-pentagon"></i> Фильтр по полигону
|
||||
</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="modal-body p-0">
|
||||
<div id="polygonFilterMap" style="height: 500px; width: 100%;"></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-outline-danger" onclick="clearPolygonOnMap()">
|
||||
<i class="bi bi-trash"></i> Очистить
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
||||
<button type="button" class="btn btn-success" onclick="applyPolygonFilter()">
|
||||
<i class="bi bi-check-lg"></i> Применить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Polygon filter map variables
|
||||
let polygonFilterMapInstance = null;
|
||||
let drawnItems = null;
|
||||
let drawControl = null;
|
||||
let currentPolygon = null;
|
||||
|
||||
// Initialize polygon filter map
|
||||
function initPolygonFilterMap() {
|
||||
if (polygonFilterMapInstance) {
|
||||
return; // Already initialized
|
||||
}
|
||||
|
||||
// Create map centered on Russia
|
||||
polygonFilterMapInstance = L.map('polygonFilterMap').setView([55.7558, 37.6173], 4);
|
||||
|
||||
// Add OpenStreetMap tile layer
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
maxZoom: 19
|
||||
}).addTo(polygonFilterMapInstance);
|
||||
|
||||
// Initialize FeatureGroup to store drawn items
|
||||
drawnItems = new L.FeatureGroup();
|
||||
polygonFilterMapInstance.addLayer(drawnItems);
|
||||
|
||||
// Initialize draw control
|
||||
drawControl = new L.Control.Draw({
|
||||
position: 'topright',
|
||||
draw: {
|
||||
polygon: {
|
||||
allowIntersection: false,
|
||||
showArea: true,
|
||||
drawError: {
|
||||
color: '#e1e100',
|
||||
message: '<strong>Ошибка:</strong> полигон не должен пересекать сам себя!'
|
||||
},
|
||||
shapeOptions: {
|
||||
color: '#3388ff',
|
||||
fillOpacity: 0.2
|
||||
}
|
||||
},
|
||||
polyline: false,
|
||||
rectangle: {
|
||||
shapeOptions: {
|
||||
color: '#3388ff',
|
||||
fillOpacity: 0.2
|
||||
}
|
||||
},
|
||||
circle: false,
|
||||
circlemarker: false,
|
||||
marker: false
|
||||
},
|
||||
edit: {
|
||||
featureGroup: drawnItems,
|
||||
remove: true
|
||||
}
|
||||
});
|
||||
polygonFilterMapInstance.addControl(drawControl);
|
||||
|
||||
// Handle polygon creation
|
||||
polygonFilterMapInstance.on(L.Draw.Event.CREATED, function (event) {
|
||||
const layer = event.layer;
|
||||
|
||||
// Remove existing polygon
|
||||
drawnItems.clearLayers();
|
||||
|
||||
// Add new polygon
|
||||
drawnItems.addLayer(layer);
|
||||
currentPolygon = layer;
|
||||
});
|
||||
|
||||
// Handle polygon edit
|
||||
polygonFilterMapInstance.on(L.Draw.Event.EDITED, function (event) {
|
||||
const layers = event.layers;
|
||||
layers.eachLayer(function (layer) {
|
||||
currentPolygon = layer;
|
||||
});
|
||||
});
|
||||
|
||||
// Handle polygon deletion
|
||||
polygonFilterMapInstance.on(L.Draw.Event.DELETED, function () {
|
||||
currentPolygon = null;
|
||||
});
|
||||
|
||||
// Load existing polygon if present
|
||||
{% if polygon_coords %}
|
||||
try {
|
||||
const coords = {{ polygon_coords|safe }};
|
||||
if (coords && coords.length > 0) {
|
||||
const latLngs = coords.map(coord => [coord[1], coord[0]]); // [lng, lat] -> [lat, lng]
|
||||
const polygon = L.polygon(latLngs, {
|
||||
color: '#3388ff',
|
||||
fillOpacity: 0.2
|
||||
});
|
||||
drawnItems.addLayer(polygon);
|
||||
currentPolygon = polygon;
|
||||
|
||||
// Fit map to polygon bounds
|
||||
polygonFilterMapInstance.fitBounds(polygon.getBounds());
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error loading existing polygon:', e);
|
||||
}
|
||||
{% endif %}
|
||||
}
|
||||
|
||||
// Open polygon filter map modal
|
||||
function openPolygonFilterMap() {
|
||||
const modal = new bootstrap.Modal(document.getElementById('polygonFilterModal'));
|
||||
modal.show();
|
||||
|
||||
// Initialize map after modal is shown (to ensure proper rendering)
|
||||
setTimeout(() => {
|
||||
initPolygonFilterMap();
|
||||
if (polygonFilterMapInstance) {
|
||||
polygonFilterMapInstance.invalidateSize();
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// Clear polygon on map
|
||||
function clearPolygonOnMap() {
|
||||
if (drawnItems) {
|
||||
drawnItems.clearLayers();
|
||||
currentPolygon = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply polygon filter
|
||||
function applyPolygonFilter() {
|
||||
if (!currentPolygon) {
|
||||
alert('Пожалуйста, нарисуйте полигон на карте');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get polygon coordinates
|
||||
const latLngs = currentPolygon.getLatLngs()[0]; // Get first ring for polygon
|
||||
const coords = latLngs.map(latLng => [latLng.lng, latLng.lat]); // [lat, lng] -> [lng, lat]
|
||||
|
||||
// Close the polygon by adding first point at the end
|
||||
coords.push(coords[0]);
|
||||
|
||||
// Add polygon coordinates to URL and reload
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
urlParams.set('polygon', JSON.stringify(coords));
|
||||
urlParams.delete('page'); // Reset to first page
|
||||
|
||||
window.location.search = urlParams.toString();
|
||||
}
|
||||
|
||||
// Clear polygon filter
|
||||
function clearPolygonFilter() {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
urlParams.delete('polygon');
|
||||
urlParams.delete('page');
|
||||
window.location.search = urlParams.toString();
|
||||
}
|
||||
</script>
|
||||
|
||||
{% endblock %}
|
||||
@@ -52,7 +52,7 @@
|
||||
attribution: 'Tiles © Esri'
|
||||
});
|
||||
|
||||
const street_local = L.tileLayer('http://127.0.0.1:8080/styles/basic-preview/{z}/{x}/{y}.png', {
|
||||
const street_local = L.tileLayer('/tiles/styles/basic-preview/512/{z}/{x}/{y}.png', {
|
||||
maxZoom: 19,
|
||||
attribution: 'Local Tiles'
|
||||
});
|
||||
|
||||
810
dbapp/mainapp/templates/mainapp/points_averaging.html
Normal file
810
dbapp/mainapp/templates/mainapp/points_averaging.html
Normal file
@@ -0,0 +1,810 @@
|
||||
{% extends "mainapp/base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Усреднение точек{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link href="{% static 'tabulator/css/tabulator_bootstrap5.min.css' %}" rel="stylesheet">
|
||||
<style>
|
||||
.averaging-container {
|
||||
padding: 20px;
|
||||
}
|
||||
.form-section {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.table-section {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
#sources-table {
|
||||
margin-top: 15px;
|
||||
font-size: 12px;
|
||||
}
|
||||
#sources-table .tabulator-header {
|
||||
font-size: 12px;
|
||||
}
|
||||
#sources-table .tabulator-cell {
|
||||
font-size: 12px;
|
||||
padding: 6px 4px;
|
||||
}
|
||||
.btn-group-custom {
|
||||
margin-top: 15px;
|
||||
}
|
||||
.loading-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(255,255,255,0.8);
|
||||
display: none;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
.loading-overlay.active {
|
||||
display: flex;
|
||||
}
|
||||
.modal-xl {
|
||||
max-width: 95%;
|
||||
}
|
||||
.group-card {
|
||||
border: 1px solid #e9ecef;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 10px;
|
||||
background: #fff;
|
||||
}
|
||||
.group-header {
|
||||
background: #f8f9fa;
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid #e9ecef;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
.group-header.has-outliers {
|
||||
background: #fff3cd;
|
||||
}
|
||||
.group-info {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 15px;
|
||||
align-items: center;
|
||||
}
|
||||
.group-info-item {
|
||||
font-size: 13px;
|
||||
}
|
||||
.group-info-item strong {
|
||||
color: #495057;
|
||||
}
|
||||
.group-actions {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
}
|
||||
.group-body {
|
||||
padding: 10px;
|
||||
}
|
||||
.points-table {
|
||||
font-size: 11px;
|
||||
width: 100%;
|
||||
}
|
||||
.points-table th, .points-table td {
|
||||
padding: 5px 6px;
|
||||
border: 1px solid #dee2e6;
|
||||
}
|
||||
.points-table th {
|
||||
background: #f8f9fa;
|
||||
font-weight: 600;
|
||||
}
|
||||
.points-table tr.outlier {
|
||||
background-color: #ffcccc !important;
|
||||
}
|
||||
.points-table tr.valid {
|
||||
background-color: #d4edda !important;
|
||||
}
|
||||
.source-has-outliers {
|
||||
background-color: #fff3cd !important;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="loading-overlay" id="loading-overlay">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Загрузка...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="averaging-container">
|
||||
<h2>Усреднение точек по объектам</h2>
|
||||
|
||||
<div class="form-section">
|
||||
<div class="row">
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="satellite-select" class="form-label">Спутник</label>
|
||||
<select id="satellite-select" class="form-select">
|
||||
<option value="">Выберите спутник</option>
|
||||
{% for satellite in satellites %}
|
||||
<option value="{{ satellite.id }}">{{ satellite.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="date-from" class="form-label">Дата с</label>
|
||||
<input type="date" id="date-from" class="form-control">
|
||||
</div>
|
||||
<div class="col-md-3 mb-3">
|
||||
<label for="date-to" class="form-label">Дата по</label>
|
||||
<input type="date" id="date-to" class="form-control">
|
||||
</div>
|
||||
<div class="col-md-3 mb-3 d-flex align-items-end">
|
||||
<button id="btn-process" class="btn btn-primary w-100">
|
||||
<i class="bi bi-play-fill"></i> Загрузить данные
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-section">
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<div>
|
||||
<h5>Объекты <span id="source-count" class="badge bg-primary">0</span></h5>
|
||||
</div>
|
||||
<div class="btn-group-custom">
|
||||
<button id="export-xlsx" class="btn btn-success" disabled>
|
||||
<i class="bi bi-file-earmark-excel"></i> Сохранить в Excel
|
||||
</button>
|
||||
<button id="export-json" class="btn btn-info ms-2" disabled>
|
||||
<i class="bi bi-filetype-json"></i> Сохранить в JSON
|
||||
</button>
|
||||
<button id="clear-all" class="btn btn-danger ms-2">
|
||||
<i class="bi bi-trash"></i> Очистить всё
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="sources-table"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal for source details -->
|
||||
<div class="modal fade" id="sourceDetailsModal" tabindex="-1" aria-labelledby="sourceDetailsModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-xl">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="sourceDetailsModalLabel">Детали объекта</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body" id="modal-body-content">
|
||||
<!-- Groups will be rendered here -->
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
|
||||
<script src="{% static 'sheetjs/xlsx.full.min.js' %}"></script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
let allSourcesData = [];
|
||||
let currentSourceIdx = null;
|
||||
let sourcesTable = null;
|
||||
|
||||
function showLoading() {
|
||||
document.getElementById('loading-overlay').classList.add('active');
|
||||
}
|
||||
function hideLoading() {
|
||||
document.getElementById('loading-overlay').classList.remove('active');
|
||||
}
|
||||
|
||||
function getCookie(name) {
|
||||
let cookieValue = null;
|
||||
if (document.cookie && document.cookie !== '') {
|
||||
const cookies = document.cookie.split(';');
|
||||
for (let i = 0; i < cookies.length; i++) {
|
||||
const cookie = cookies[i].trim();
|
||||
if (cookie.substring(0, name.length + 1) === (name + '=')) {
|
||||
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cookieValue;
|
||||
}
|
||||
|
||||
function generateUUID() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
||||
const r = Math.random() * 16 | 0;
|
||||
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
function updateCounts() {
|
||||
document.getElementById('source-count').textContent = allSourcesData.length;
|
||||
const hasData = allSourcesData.length > 0;
|
||||
document.getElementById('export-xlsx').disabled = !hasData;
|
||||
document.getElementById('export-json').disabled = !hasData;
|
||||
}
|
||||
|
||||
// Prepare table data from sources
|
||||
function getTableData() {
|
||||
const data = [];
|
||||
allSourcesData.forEach((source, sourceIdx) => {
|
||||
const totalPoints = source.groups.reduce((sum, g) => sum + g.valid_points_count, 0);
|
||||
const hasOutliers = source.groups.some(g => g.has_outliers);
|
||||
|
||||
// Get first group's params as representative
|
||||
const firstGroup = source.groups[0] || {};
|
||||
|
||||
data.push({
|
||||
_sourceIdx: sourceIdx,
|
||||
source_name: source.source_name,
|
||||
source_id: source.source_id,
|
||||
groups_count: source.groups.length,
|
||||
total_points: totalPoints,
|
||||
has_outliers: hasOutliers,
|
||||
frequency: firstGroup.frequency || '-',
|
||||
modulation: firstGroup.modulation || '-',
|
||||
mirrors: firstGroup.mirrors || '-',
|
||||
});
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
// Initialize or update sources table
|
||||
function updateSourcesTable() {
|
||||
const data = getTableData();
|
||||
|
||||
if (!sourcesTable) {
|
||||
sourcesTable = new Tabulator("#sources-table", {
|
||||
layout: "fitDataStretch",
|
||||
height: "500px",
|
||||
placeholder: "Нет данных. Выберите спутник и диапазон дат, затем нажмите 'Загрузить данные'.",
|
||||
initialSort: [
|
||||
{column: "frequency", dir: "asc"}
|
||||
],
|
||||
columns: [
|
||||
{title: "Объект", field: "source_name", minWidth: 180, widthGrow: 2},
|
||||
{title: "Групп", field: "groups_count", minWidth: 70, hozAlign: "center"},
|
||||
{title: "Точек", field: "total_points", minWidth: 70, hozAlign: "center"},
|
||||
{title: "Частота", field: "frequency", minWidth: 100, sorter: "number"},
|
||||
{title: "Модуляция", field: "modulation", minWidth: 90},
|
||||
{title: "Зеркала", field: "mirrors", minWidth: 130},
|
||||
{
|
||||
title: "Действия",
|
||||
field: "actions",
|
||||
minWidth: 150,
|
||||
hozAlign: "center",
|
||||
formatter: function(cell) {
|
||||
const data = cell.getRow().getData();
|
||||
const outlierBadge = data.has_outliers ? '<span class="badge bg-warning me-1">!</span>' : '';
|
||||
return `${outlierBadge}
|
||||
<button class="btn btn-sm btn-primary btn-view-source" title="Открыть детали">
|
||||
<i class="bi bi-eye"></i>
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger btn-delete-source ms-1" title="Удалить">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>`;
|
||||
},
|
||||
cellClick: function(e, cell) {
|
||||
const data = cell.getRow().getData();
|
||||
if (e.target.closest('.btn-view-source')) {
|
||||
openSourceModal(data._sourceIdx);
|
||||
} else if (e.target.closest('.btn-delete-source')) {
|
||||
deleteSource(data._sourceIdx);
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
data: data,
|
||||
rowFormatter: function(row) {
|
||||
if (row.getData().has_outliers) {
|
||||
row.getElement().classList.add('source-has-outliers');
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
sourcesTable.setData(data);
|
||||
}
|
||||
|
||||
updateCounts();
|
||||
}
|
||||
|
||||
// Delete source
|
||||
function deleteSource(sourceIdx) {
|
||||
//if (!confirm('Удалить этот объект со всеми группами?')) return;
|
||||
allSourcesData.splice(sourceIdx, 1);
|
||||
updateSourcesTable();
|
||||
}
|
||||
|
||||
// Open source modal
|
||||
function openSourceModal(sourceIdx) {
|
||||
currentSourceIdx = sourceIdx;
|
||||
const source = allSourcesData[sourceIdx];
|
||||
if (!source) return;
|
||||
|
||||
document.getElementById('sourceDetailsModalLabel').textContent = `Объект: ${source.source_name}`;
|
||||
renderModalContent();
|
||||
|
||||
const modal = new bootstrap.Modal(document.getElementById('sourceDetailsModal'));
|
||||
modal.show();
|
||||
}
|
||||
|
||||
// Render modal content
|
||||
function renderModalContent() {
|
||||
const source = allSourcesData[currentSourceIdx];
|
||||
if (!source) return;
|
||||
|
||||
let html = '';
|
||||
source.groups.forEach((group, groupIdx) => {
|
||||
html += renderGroupCard(group, groupIdx);
|
||||
});
|
||||
|
||||
if (source.groups.length === 0) {
|
||||
html = '<div class="alert alert-info">Нет групп для отображения</div>';
|
||||
}
|
||||
|
||||
document.getElementById('modal-body-content').innerHTML = html;
|
||||
addModalEventListeners();
|
||||
}
|
||||
|
||||
// Render group card
|
||||
function renderGroupCard(group, groupIdx) {
|
||||
const headerClass = group.has_outliers ? 'has-outliers' : '';
|
||||
|
||||
let pointsHtml = '';
|
||||
group.points.forEach((point, pointIdx) => {
|
||||
const rowClass = point.is_outlier ? 'outlier' : 'valid';
|
||||
pointsHtml += `
|
||||
<tr class="${rowClass}">
|
||||
<td>${point.id}</td>
|
||||
<td>${point.name}</td>
|
||||
<td>${point.frequency}</td>
|
||||
<td>${point.freq_range}</td>
|
||||
<td>${point.bod_velocity}</td>
|
||||
<td>${point.modulation}</td>
|
||||
<td>${point.snr}</td>
|
||||
<td>${point.timestamp}</td>
|
||||
<td>${point.mirrors}</td>
|
||||
<td>${point.coordinates}</td>
|
||||
<td>${point.distance_from_avg}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-outline-danger btn-delete-point"
|
||||
data-group-idx="${groupIdx}"
|
||||
data-point-idx="${pointIdx}"
|
||||
title="Удалить точку">
|
||||
<i class="bi bi-x"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
});
|
||||
|
||||
return `
|
||||
<div class="group-card" data-group-idx="${groupIdx}">
|
||||
<div class="group-header ${headerClass}">
|
||||
<div class="group-info">
|
||||
<span class="group-info-item"><strong>Интервал:</strong> ${group.interval_label}</span>
|
||||
<span class="group-info-item"><strong>Усреднённые координаты:</strong> ${group.avg_coordinates} <span class="badge bg-secondary">${group.avg_type || 'ГК'}</span></span>
|
||||
<span class="group-info-item"><strong>Медианное время:</strong> ${group.avg_time}</span>
|
||||
<span class="group-info-item"><strong>Точек:</strong> ${group.valid_points_count}/${group.total_points}</span>
|
||||
${group.has_outliers ? `<span class="badge bg-warning">Выбросов: ${group.outliers_count}</span>` : ''}
|
||||
</div>
|
||||
<div class="group-actions">
|
||||
<button class="btn btn-sm btn-primary btn-average-group" data-group-idx="${groupIdx}" title="Пересчитать усреднение">
|
||||
<i class="bi bi-calculator"></i> Усреднить
|
||||
</button>
|
||||
${group.has_outliers ? `
|
||||
<button class="btn btn-sm btn-warning btn-average-all" data-group-idx="${groupIdx}" title="Усреднить все точки">
|
||||
<i class="bi bi-arrow-repeat"></i> Все точки
|
||||
</button>
|
||||
` : ''}
|
||||
<button class="btn btn-sm btn-danger btn-delete-group" data-group-idx="${groupIdx}" title="Удалить группу">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="group-body">
|
||||
<table class="points-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Имя</th>
|
||||
<th>Частота</th>
|
||||
<th>Полоса</th>
|
||||
<th>Симв. скорость</th>
|
||||
<th>Модуляция</th>
|
||||
<th>ОСШ</th>
|
||||
<th>Дата/Время</th>
|
||||
<th>Зеркала</th>
|
||||
<th>Координаты</th>
|
||||
<th>Расст., км</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${pointsHtml}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Add event listeners for modal
|
||||
function addModalEventListeners() {
|
||||
document.querySelectorAll('.btn-delete-group').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const groupIdx = parseInt(this.dataset.groupIdx);
|
||||
deleteGroup(groupIdx);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('.btn-delete-point').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const groupIdx = parseInt(this.dataset.groupIdx);
|
||||
const pointIdx = parseInt(this.dataset.pointIdx);
|
||||
deletePoint(groupIdx, pointIdx);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('.btn-average-group').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const groupIdx = parseInt(this.dataset.groupIdx);
|
||||
recalculateGroup(groupIdx, false);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('.btn-average-all').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const groupIdx = parseInt(this.dataset.groupIdx);
|
||||
recalculateGroup(groupIdx, true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Delete group
|
||||
function deleteGroup(groupIdx) {
|
||||
if (!confirm('Удалить эту группу точек?')) return;
|
||||
|
||||
const source = allSourcesData[currentSourceIdx];
|
||||
source.groups.splice(groupIdx, 1);
|
||||
|
||||
if (source.groups.length === 0) {
|
||||
allSourcesData.splice(currentSourceIdx, 1);
|
||||
bootstrap.Modal.getInstance(document.getElementById('sourceDetailsModal')).hide();
|
||||
updateSourcesTable();
|
||||
} else {
|
||||
renderModalContent();
|
||||
updateSourcesTable();
|
||||
}
|
||||
}
|
||||
|
||||
// Delete point
|
||||
function deletePoint(groupIdx, pointIdx) {
|
||||
const source = allSourcesData[currentSourceIdx];
|
||||
const group = source.groups[groupIdx];
|
||||
|
||||
if (group.points.length <= 1) {
|
||||
alert('Нельзя удалить последнюю точку. Удалите группу целиком.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm('Удалить эту точку и пересчитать усреднение?')) return;
|
||||
|
||||
group.points.splice(pointIdx, 1);
|
||||
group.total_points = group.points.length;
|
||||
recalculateGroup(groupIdx, true);
|
||||
}
|
||||
|
||||
// Recalculate group
|
||||
async function recalculateGroup(groupIdx, includeAll) {
|
||||
const source = allSourcesData[currentSourceIdx];
|
||||
const group = source.groups[groupIdx];
|
||||
|
||||
showLoading();
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/points-averaging/recalculate/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': getCookie('csrftoken')
|
||||
},
|
||||
body: JSON.stringify({
|
||||
points: group.points,
|
||||
include_all: includeAll
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Ошибка при пересчёте');
|
||||
return;
|
||||
}
|
||||
|
||||
// Update group data
|
||||
Object.assign(group, {
|
||||
avg_coordinates: data.avg_coordinates,
|
||||
avg_coord_tuple: data.avg_coord_tuple,
|
||||
avg_type: data.avg_type,
|
||||
total_points: data.total_points,
|
||||
valid_points_count: data.valid_points_count,
|
||||
outliers_count: data.outliers_count,
|
||||
has_outliers: data.has_outliers,
|
||||
mirrors: data.mirrors || group.mirrors,
|
||||
avg_time: data.avg_time || group.avg_time,
|
||||
points: data.points,
|
||||
});
|
||||
|
||||
renderModalContent();
|
||||
updateSourcesTable();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
alert('Произошла ошибка при пересчёте');
|
||||
} finally {
|
||||
hideLoading();
|
||||
}
|
||||
}
|
||||
|
||||
// Process button click
|
||||
document.getElementById('btn-process').addEventListener('click', async function() {
|
||||
const satelliteId = document.getElementById('satellite-select').value;
|
||||
const dateFrom = document.getElementById('date-from').value;
|
||||
const dateTo = document.getElementById('date-to').value;
|
||||
|
||||
if (!satelliteId) { alert('Выберите спутник'); return; }
|
||||
if (!dateFrom || !dateTo) { alert('Укажите диапазон дат'); return; }
|
||||
|
||||
showLoading();
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({ satellite_id: satelliteId, date_from: dateFrom, date_to: dateTo });
|
||||
const response = await fetch(`/api/points-averaging/?${params.toString()}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) { alert(data.error || 'Ошибка при обработке данных'); return; }
|
||||
|
||||
data.sources.forEach(source => {
|
||||
const existingIdx = allSourcesData.findIndex(s => s.source_id === source.source_id);
|
||||
if (existingIdx >= 0) {
|
||||
source.groups.forEach(newGroup => {
|
||||
const existingGroupIdx = allSourcesData[existingIdx].groups.findIndex(g => g.interval_key === newGroup.interval_key);
|
||||
if (existingGroupIdx < 0) {
|
||||
allSourcesData[existingIdx].groups.push(newGroup);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
allSourcesData.push(source);
|
||||
}
|
||||
});
|
||||
|
||||
updateSourcesTable();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
alert('Произошла ошибка при обработке данных');
|
||||
} finally {
|
||||
hideLoading();
|
||||
}
|
||||
});
|
||||
|
||||
// Clear all
|
||||
document.getElementById('clear-all').addEventListener('click', function() {
|
||||
if (!confirm('Очистить все данные?')) return;
|
||||
allSourcesData = [];
|
||||
updateSourcesTable();
|
||||
});
|
||||
|
||||
// Export to Excel
|
||||
document.getElementById('export-xlsx').addEventListener('click', function() {
|
||||
if (allSourcesData.length === 0) { alert('Нет данных для экспорта'); return; }
|
||||
|
||||
const summaryData = [];
|
||||
allSourcesData.forEach(source => {
|
||||
source.groups.forEach(group => {
|
||||
summaryData.push({
|
||||
'Объект': source.source_name,
|
||||
'Частота, МГц': group.frequency,
|
||||
'Полоса, МГц': group.freq_range,
|
||||
'Символьная скорость, БОД': group.bod_velocity,
|
||||
'Модуляция': group.modulation,
|
||||
'ОСШ': group.snr,
|
||||
'Зеркала': group.mirrors,
|
||||
'Усреднённые координаты': group.avg_coordinates,
|
||||
// 'Тип усреднения': group.avg_type || 'ГК',
|
||||
'Время': group.avg_time || '-',
|
||||
'Кол-во точек': group.valid_points_count
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Sort by frequency
|
||||
summaryData.sort((a, b) => {
|
||||
const freqA = parseFloat(a['Частота, МГц']) || 0;
|
||||
const freqB = parseFloat(b['Частота, МГц']) || 0;
|
||||
return freqA - freqB;
|
||||
});
|
||||
|
||||
const allPointsData = [];
|
||||
allSourcesData.forEach(source => {
|
||||
source.groups.forEach(group => {
|
||||
group.points.forEach(point => {
|
||||
allPointsData.push({
|
||||
'Объект': source.source_name,
|
||||
'ID точки': point.id,
|
||||
'Имя точки': point.name,
|
||||
'Частота, МГц': point.frequency,
|
||||
'Полоса, МГц': point.freq_range,
|
||||
'Символьная скорость, БОД': point.bod_velocity,
|
||||
'Модуляция': point.modulation,
|
||||
'ОСШ': point.snr,
|
||||
'Дата/Время': point.timestamp,
|
||||
'Зеркала': point.mirrors,
|
||||
'Местоположение': point.location,
|
||||
'Координаты точки': point.coordinates,
|
||||
'Усреднённые координаты': group.avg_coordinates,
|
||||
'Расстояние от среднего, км': point.distance_from_avg,
|
||||
'Статус': point.is_outlier ? 'Выброс' : 'OK'
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Sort by frequency
|
||||
allPointsData.sort((a, b) => {
|
||||
const freqA = parseFloat(a['Частота, МГц']) || 0;
|
||||
const freqB = parseFloat(b['Частота, МГц']) || 0;
|
||||
return freqA - freqB;
|
||||
});
|
||||
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(summaryData), "Усреднение");
|
||||
XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(allPointsData), "Все точки");
|
||||
|
||||
const dateStr = new Date().toISOString().slice(0, 10);
|
||||
XLSX.writeFile(wb, `averaging_${dateStr}.xlsx`);
|
||||
});
|
||||
|
||||
|
||||
// Export to JSON
|
||||
document.getElementById('export-json').addEventListener('click', function() {
|
||||
if (allSourcesData.length === 0) { alert('Нет данных для экспорта'); return; }
|
||||
|
||||
const CREATOR_ID = '6fd12c90-7f17-43d9-a03e-ee14e880f757';
|
||||
|
||||
const pathObject = {
|
||||
"tacticObjectType": "path",
|
||||
"captionPosition": "right",
|
||||
"points": [
|
||||
{"id": "b92b9cbb-dd27-49aa-bcb6-e89a147bc02c", "latitude": 57, "longitude": -13, "altitude": 0, "customActions": [], "tags": {"creator": CREATOR_ID}, "tacticObjectType": "point"},
|
||||
{"id": "8e3666d4-4990-4cb9-9594-63ad06333489", "latitude": 57, "longitude": 64, "altitude": 0, "customActions": [], "tags": {"creator": CREATOR_ID}, "tacticObjectType": "point"},
|
||||
{"id": "5f137485-d2fc-443d-8507-c936f02f3569", "latitude": 11, "longitude": 64, "altitude": 0, "customActions": [], "tags": {"creator": CREATOR_ID}, "tacticObjectType": "point"},
|
||||
{"id": "0fb90df7-8eb0-49fa-9d00-336389171bf5", "latitude": 11, "longitude": -13, "altitude": 0, "customActions": [], "tags": {"creator": CREATOR_ID}, "tacticObjectType": "point"},
|
||||
{"id": "3ef12637-585e-40a4-b0ee-8f1786c89ce6", "latitude": 57, "longitude": -13, "altitude": 0, "customActions": [], "tags": {"creator": CREATOR_ID}, "tacticObjectType": "point"}
|
||||
],
|
||||
"isCycle": false,
|
||||
"id": "2f604051-4984-4c2f-8c4c-c0cb64008f5f",
|
||||
"draggable": false, "selectable": false, "editable": false,
|
||||
"caption": "Ограничение для работы с поверхностями",
|
||||
"line": {"color": "rgb(148,0,211)", "thickness": 1, "dash": "solid", "border": null},
|
||||
"customActions": [],
|
||||
"tags": {"creator": CREATOR_ID}
|
||||
};
|
||||
|
||||
const result = [pathObject];
|
||||
|
||||
const jsonSourceColors = [
|
||||
"rgb(0,128,0)", "rgb(0,0,255)", "rgb(255,0,0)", "rgb(255,165,0)", "rgb(128,0,128)",
|
||||
"rgb(0,128,128)", "rgb(255,20,147)", "rgb(139,69,19)", "rgb(0,100,0)", "rgb(70,130,180)"
|
||||
];
|
||||
|
||||
allSourcesData.forEach((source, sourceIdx) => {
|
||||
const sourceColor = jsonSourceColors[sourceIdx % jsonSourceColors.length];
|
||||
|
||||
source.groups.forEach(group => {
|
||||
const avgCoord = group.avg_coord_tuple;
|
||||
const avgLat = avgCoord[1];
|
||||
const avgLon = avgCoord[0];
|
||||
const avgCaption = `${source.source_name} (усредн) - ${group.avg_time || '-'}`;
|
||||
const avgSourceId = generateUUID();
|
||||
|
||||
result.push({
|
||||
"tacticObjectType": "source",
|
||||
"captionPosition": "right",
|
||||
"id": avgSourceId,
|
||||
"icon": {"type": "triangle", "color": sourceColor},
|
||||
"caption": avgCaption,
|
||||
"name": avgCaption,
|
||||
"customActions": [],
|
||||
"trackBehavior": {},
|
||||
"bearingStyle": {"color": sourceColor, "thickness": 2, "dash": "solid", "border": null},
|
||||
"bearingBehavior": {},
|
||||
"tags": {"creator": CREATOR_ID}
|
||||
});
|
||||
|
||||
result.push({
|
||||
"tacticObjectType": "position",
|
||||
"id": generateUUID(),
|
||||
"parentId": avgSourceId,
|
||||
"timeStamp": Date.now() / 1000,
|
||||
"latitude": avgLat,
|
||||
"altitude": 0,
|
||||
"longitude": avgLon,
|
||||
"caption": "",
|
||||
"tooltip": "",
|
||||
"customActions": [],
|
||||
"tags": {"layers": [], "creator": CREATOR_ID}
|
||||
});
|
||||
|
||||
// group.points.forEach(point => {
|
||||
// if (point.is_outlier) return;
|
||||
|
||||
// const pointCoord = point.coord_tuple;
|
||||
// const pointCaption = `${point.name || '-'} - ${point.timestamp || '-'}`;
|
||||
// const pointSourceId = generateUUID();
|
||||
|
||||
// result.push({
|
||||
// "tacticObjectType": "source",
|
||||
// "captionPosition": "right",
|
||||
// "id": pointSourceId,
|
||||
// "icon": {"type": "circle", "color": sourceColor},
|
||||
// "caption": pointCaption,
|
||||
// "name": pointCaption,
|
||||
// "customActions": [],
|
||||
// "trackBehavior": {},
|
||||
// "bearingStyle": {"color": sourceColor, "thickness": 2, "dash": "solid", "border": null},
|
||||
// "bearingBehavior": {},
|
||||
// "tags": {"creator": CREATOR_ID}
|
||||
// });
|
||||
|
||||
// result.push({
|
||||
// "tacticObjectType": "position",
|
||||
// "id": generateUUID(),
|
||||
// "parentId": pointSourceId,
|
||||
// "timeStamp": point.timestamp_unix || (Date.now() / 1000),
|
||||
// "latitude": pointCoord[1],
|
||||
// "altitude": 0,
|
||||
// "longitude": pointCoord[0],
|
||||
// "caption": "",
|
||||
// "tooltip": "",
|
||||
// "customActions": [],
|
||||
// "tags": {"layers": [], "creator": CREATOR_ID}
|
||||
// });
|
||||
// });
|
||||
});
|
||||
});
|
||||
|
||||
const jsonString = JSON.stringify(result, null, 2);
|
||||
const blob = new Blob(['\uFEFF' + jsonString], {type: 'application/json;charset=utf-8'});
|
||||
const dateStr = new Date().toISOString().slice(0, 10);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = `averaging_${dateStr}.json`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(a.href);
|
||||
});
|
||||
|
||||
// Initialize
|
||||
updateSourcesTable();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -69,7 +69,7 @@
|
||||
{% csrf_token %}
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="col-md-4">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.name.id_for_label }}" class="form-label">
|
||||
{{ form.name.label }} <span class="text-danger">*</span>
|
||||
@@ -86,6 +86,42 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-4">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.alternative_name.id_for_label }}" class="form-label">
|
||||
{{ form.alternative_name.label }}
|
||||
</label>
|
||||
{{ form.alternative_name }}
|
||||
{% if form.alternative_name.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{{ form.alternative_name.errors.0 }}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if form.alternative_name.help_text %}
|
||||
<div class="form-text">{{ form.alternative_name.help_text }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-4">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.location_place.id_for_label }}" class="form-label">
|
||||
{{ form.location_place.label }}
|
||||
</label>
|
||||
{{ form.location_place }}
|
||||
{% if form.location_place.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{{ form.location_place.errors.0 }}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if form.location_place.help_text %}
|
||||
<div class="form-text">{{ form.location_place.help_text }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.norad.id_for_label }}" class="form-label">
|
||||
@@ -102,26 +138,26 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.international_code.id_for_label }}" class="form-label">
|
||||
{{ form.international_code.label }}
|
||||
</label>
|
||||
{{ form.international_code }}
|
||||
{% if form.international_code.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{{ form.international_code.errors.0 }}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if form.international_code.help_text %}
|
||||
<div class="form-text">{{ form.international_code.help_text }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.band.id_for_label }}" class="form-label">
|
||||
{{ form.band.label }}
|
||||
</label>
|
||||
{{ form.band }}
|
||||
{% if form.band.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{{ form.band.errors.0 }}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if form.band.help_text %}
|
||||
<div class="form-text">{{ form.band.help_text }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.undersat_point.id_for_label }}" class="form-label">
|
||||
@@ -138,9 +174,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.launch_date.id_for_label }}" class="form-label">
|
||||
@@ -157,8 +191,29 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.band.id_for_label }}" class="form-label">
|
||||
{{ form.band.label }}
|
||||
</label>
|
||||
{{ form.band }}
|
||||
{% if form.band.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{{ form.band.errors.0 }}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if form.band.help_text %}
|
||||
<div class="form-text">{{ form.band.help_text }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="mb-3">
|
||||
<label for="{{ form.url.id_for_label }}" class="form-label">
|
||||
{{ form.url.label }}
|
||||
@@ -212,26 +267,26 @@
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h4>Частотный план</h4>
|
||||
<p class="text-muted">Визуализация транспондеров спутника по частотам (Downlink). Используйте колесико мыши для масштабирования, наведите курсор на полосу для подробной информации.</p>
|
||||
<p class="text-muted">Визуализация транспондеров спутника по частотам. <span style="color: #0d6efd;">■</span> Downlink (синий), <span style="color: #fd7e14;">■</span> Uplink (оранжевый). Используйте колесико мыши для масштабирования, наведите курсор на полосу для подробной информации и связи с парным каналом.</p>
|
||||
|
||||
<div class="frequency-plan">
|
||||
<div class="chart-controls">
|
||||
<button type="button" class="btn btn-sm btn-outline-primary" id="resetZoom">
|
||||
<i class="bi bi-arrow-clockwise"></i> Сбросить масштаб
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="zoomIn">
|
||||
<!-- <button type="button" class="btn btn-sm btn-outline-secondary" id="zoomIn">
|
||||
<i class="bi bi-zoom-in"></i> Увеличить
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="zoomOut">
|
||||
<i class="bi bi-zoom-out"></i> Уменьшить
|
||||
</button>
|
||||
</button> -->
|
||||
</div>
|
||||
|
||||
<div class="frequency-chart-container">
|
||||
<canvas id="frequencyChart"></canvas>
|
||||
</div>
|
||||
|
||||
<div class="legend">
|
||||
<!-- <div class="legend">
|
||||
<div class="legend-item">
|
||||
<div class="legend-color" style="background-color: #0d6efd;"></div>
|
||||
<span>H - Горизонтальная</span>
|
||||
@@ -252,7 +307,7 @@
|
||||
<div class="legend-color" style="background-color: #6c757d;"></div>
|
||||
<span>Другая</span>
|
||||
</div>
|
||||
</div>
|
||||
</div> -->
|
||||
|
||||
<div class="mt-3">
|
||||
<p><strong>Всего транспондеров:</strong> {{ transponder_count }}</p>
|
||||
@@ -272,32 +327,28 @@
|
||||
// Transponder data from Django
|
||||
const transpondersData = {{ transponders|safe }};
|
||||
|
||||
// Color mapping for polarizations
|
||||
const polarizationColors = {
|
||||
'H': '#0d6efd',
|
||||
'V': '#198754',
|
||||
'L': '#dc3545',
|
||||
'R': '#ffc107',
|
||||
'default': '#6c757d'
|
||||
};
|
||||
|
||||
function getColor(polarization) {
|
||||
return polarizationColors[polarization] || polarizationColors['default'];
|
||||
}
|
||||
|
||||
// Chart state
|
||||
let canvas, ctx, container;
|
||||
let zoomLevel = 1;
|
||||
let panOffset = 0;
|
||||
let zoomLevelUL = 1;
|
||||
let zoomLevelDL = 1;
|
||||
let panOffsetUL = 0;
|
||||
let panOffsetDL = 0;
|
||||
let isDragging = false;
|
||||
let dragStartX = 0;
|
||||
let dragStartOffset = 0;
|
||||
let dragStartOffsetUL = 0;
|
||||
let dragStartOffsetDL = 0;
|
||||
let dragArea = null; // 'uplink' or 'downlink'
|
||||
let hoveredTransponder = null;
|
||||
let transponderRects = [];
|
||||
|
||||
// Frequency range
|
||||
let minFreq, maxFreq, freqRange;
|
||||
let originalMinFreq, originalMaxFreq, originalFreqRange;
|
||||
// Frequency ranges for uplink and downlink
|
||||
let minFreqUL, maxFreqUL, freqRangeUL;
|
||||
let minFreqDL, maxFreqDL, freqRangeDL;
|
||||
let originalMinFreqUL, originalMaxFreqUL, originalFreqRangeUL;
|
||||
let originalMinFreqDL, originalMaxFreqDL, originalFreqRangeDL;
|
||||
|
||||
// Layout variables (need to be global for event handlers)
|
||||
let uplinkStartY, uplinkHeight, downlinkStartY, downlinkHeight;
|
||||
|
||||
function initializeFrequencyChart() {
|
||||
if (!transpondersData || transpondersData.length === 0) {
|
||||
@@ -310,27 +361,50 @@ function initializeFrequencyChart() {
|
||||
container = canvas.parentElement;
|
||||
ctx = canvas.getContext('2d');
|
||||
|
||||
// Calculate frequency range
|
||||
minFreq = Infinity;
|
||||
maxFreq = -Infinity;
|
||||
// Calculate frequency ranges separately for uplink and downlink
|
||||
minFreqUL = Infinity;
|
||||
maxFreqUL = -Infinity;
|
||||
minFreqDL = Infinity;
|
||||
maxFreqDL = -Infinity;
|
||||
|
||||
transpondersData.forEach(t => {
|
||||
const startFreq = t.downlink - (t.frequency_range / 2);
|
||||
const endFreq = t.downlink + (t.frequency_range / 2);
|
||||
minFreq = Math.min(minFreq, startFreq);
|
||||
maxFreq = Math.max(maxFreq, endFreq);
|
||||
// Downlink
|
||||
const dlStartFreq = t.downlink - (t.frequency_range / 2);
|
||||
const dlEndFreq = t.downlink + (t.frequency_range / 2);
|
||||
minFreqDL = Math.min(minFreqDL, dlStartFreq);
|
||||
maxFreqDL = Math.max(maxFreqDL, dlEndFreq);
|
||||
|
||||
// Uplink (if exists)
|
||||
if (t.uplink) {
|
||||
const ulStartFreq = t.uplink - (t.frequency_range / 2);
|
||||
const ulEndFreq = t.uplink + (t.frequency_range / 2);
|
||||
minFreqUL = Math.min(minFreqUL, ulStartFreq);
|
||||
maxFreqUL = Math.max(maxFreqUL, ulEndFreq);
|
||||
}
|
||||
});
|
||||
|
||||
// Add 2% padding
|
||||
const padding = (maxFreq - minFreq) * 0.02;
|
||||
minFreq -= padding;
|
||||
maxFreq += padding;
|
||||
// Add 2% padding for downlink
|
||||
const paddingDL = (maxFreqDL - minFreqDL) * 0.04;
|
||||
minFreqDL -= paddingDL;
|
||||
maxFreqDL += paddingDL;
|
||||
|
||||
// Add 2% padding for uplink (if exists)
|
||||
if (maxFreqUL !== -Infinity) {
|
||||
const paddingUL = (maxFreqUL - minFreqUL) * 0.04;
|
||||
minFreqUL -= paddingUL;
|
||||
maxFreqUL += paddingUL;
|
||||
}
|
||||
|
||||
// Store original values
|
||||
originalMinFreq = minFreq;
|
||||
originalMaxFreq = maxFreq;
|
||||
originalFreqRange = maxFreq - minFreq;
|
||||
freqRange = originalFreqRange;
|
||||
originalMinFreqDL = minFreqDL;
|
||||
originalMaxFreqDL = maxFreqDL;
|
||||
originalFreqRangeDL = maxFreqDL - minFreqDL;
|
||||
freqRangeDL = originalFreqRangeDL;
|
||||
|
||||
originalMinFreqUL = minFreqUL;
|
||||
originalMaxFreqUL = maxFreqUL;
|
||||
originalFreqRangeUL = maxFreqUL - minFreqUL;
|
||||
freqRangeUL = originalFreqRangeUL;
|
||||
|
||||
// Setup event listeners
|
||||
canvas.addEventListener('wheel', handleWheel, { passive: false });
|
||||
@@ -363,15 +437,22 @@ function renderChart() {
|
||||
// Layout constants
|
||||
const leftMargin = 60;
|
||||
const rightMargin = 20;
|
||||
const topMargin = 40;
|
||||
const topMargin = 60;
|
||||
const middleMargin = 60; // Space between UL and DL sections
|
||||
const bottomMargin = 40;
|
||||
const chartWidth = width - leftMargin - rightMargin;
|
||||
const chartHeight = height - topMargin - bottomMargin;
|
||||
const availableHeight = height - topMargin - middleMargin - bottomMargin;
|
||||
|
||||
// Group transponders by polarization
|
||||
// Split available height between UL and DL
|
||||
uplinkHeight = availableHeight * 0.48;
|
||||
downlinkHeight = availableHeight * 0.48;
|
||||
|
||||
// Group transponders by polarization (use first letter only)
|
||||
const polarizationGroups = {};
|
||||
transpondersData.forEach(t => {
|
||||
const pol = t.polarization || 'Другая';
|
||||
let pol = t.polarization || '-';
|
||||
// Take only first letter for abbreviation
|
||||
pol = pol.charAt(0).toUpperCase();
|
||||
if (!polarizationGroups[pol]) {
|
||||
polarizationGroups[pol] = [];
|
||||
}
|
||||
@@ -379,55 +460,106 @@ function renderChart() {
|
||||
});
|
||||
|
||||
const polarizations = Object.keys(polarizationGroups);
|
||||
const rowHeight = chartHeight / polarizations.length;
|
||||
const rowHeightUL = uplinkHeight / polarizations.length;
|
||||
const rowHeightDL = downlinkHeight / polarizations.length;
|
||||
|
||||
// Calculate visible frequency range with zoom and pan
|
||||
const visibleFreqRange = freqRange / zoomLevel;
|
||||
const centerFreq = (minFreq + maxFreq) / 2;
|
||||
const visibleMinFreq = centerFreq - visibleFreqRange / 2 + panOffset;
|
||||
const visibleMaxFreq = centerFreq + visibleFreqRange / 2 + panOffset;
|
||||
// Calculate visible frequency ranges with zoom and pan for UL
|
||||
const visibleFreqRangeUL = freqRangeUL / zoomLevelUL;
|
||||
const centerFreqUL = (minFreqUL + maxFreqUL) / 2;
|
||||
const visibleMinFreqUL = centerFreqUL - visibleFreqRangeUL / 2 + panOffsetUL;
|
||||
const visibleMaxFreqUL = centerFreqUL + visibleFreqRangeUL / 2 + panOffsetUL;
|
||||
|
||||
// Draw frequency axis
|
||||
// Calculate visible frequency ranges with zoom and pan for DL
|
||||
const visibleFreqRangeDL = freqRangeDL / zoomLevelDL;
|
||||
const centerFreqDL = (minFreqDL + maxFreqDL) / 2;
|
||||
const visibleMinFreqDL = centerFreqDL - visibleFreqRangeDL / 2 + panOffsetDL;
|
||||
const visibleMaxFreqDL = centerFreqDL + visibleFreqRangeDL / 2 + panOffsetDL;
|
||||
|
||||
uplinkStartY = topMargin;
|
||||
downlinkStartY = topMargin + uplinkHeight + middleMargin;
|
||||
|
||||
// Draw UPLINK frequency axis
|
||||
ctx.strokeStyle = '#dee2e6';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(leftMargin, topMargin);
|
||||
ctx.lineTo(width - rightMargin, topMargin);
|
||||
ctx.moveTo(leftMargin, uplinkStartY);
|
||||
ctx.lineTo(width - rightMargin, uplinkStartY);
|
||||
ctx.stroke();
|
||||
|
||||
// Draw frequency labels and grid
|
||||
// Draw UPLINK frequency labels and grid
|
||||
ctx.fillStyle = '#6c757d';
|
||||
ctx.font = '11px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
|
||||
const numTicks = 10;
|
||||
for (let i = 0; i <= numTicks; i++) {
|
||||
const freq = visibleMinFreq + (visibleMaxFreq - visibleMinFreq) * i / numTicks;
|
||||
const freq = visibleMinFreqUL + (visibleMaxFreqUL - visibleMinFreqUL) * i / numTicks;
|
||||
const x = leftMargin + chartWidth * i / numTicks;
|
||||
|
||||
// Draw tick
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, topMargin);
|
||||
ctx.lineTo(x, topMargin - 5);
|
||||
ctx.moveTo(x, uplinkStartY);
|
||||
ctx.lineTo(x, uplinkStartY - 5);
|
||||
ctx.stroke();
|
||||
|
||||
// Draw grid line
|
||||
ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, topMargin);
|
||||
ctx.lineTo(x, height - bottomMargin);
|
||||
ctx.moveTo(x, uplinkStartY);
|
||||
ctx.lineTo(x, uplinkStartY + uplinkHeight);
|
||||
ctx.stroke();
|
||||
ctx.strokeStyle = '#dee2e6';
|
||||
|
||||
// Draw label
|
||||
ctx.fillText(freq.toFixed(1), x, topMargin - 10);
|
||||
ctx.fillText(freq.toFixed(1), x, uplinkStartY - 10);
|
||||
}
|
||||
|
||||
// Draw axis title
|
||||
// Draw UPLINK axis title
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.font = 'bold 12px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText('Частота (МГц)', width / 2, topMargin - 25);
|
||||
ctx.fillText('Uplink Частота (МГц)', width / 2, uplinkStartY - 25);
|
||||
|
||||
// Draw DOWNLINK frequency axis
|
||||
ctx.strokeStyle = '#dee2e6';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(leftMargin, downlinkStartY);
|
||||
ctx.lineTo(width - rightMargin, downlinkStartY);
|
||||
ctx.stroke();
|
||||
|
||||
// Draw DOWNLINK frequency labels and grid
|
||||
ctx.fillStyle = '#6c757d';
|
||||
ctx.font = '11px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
|
||||
for (let i = 0; i <= numTicks; i++) {
|
||||
const freq = visibleMinFreqDL + (visibleMaxFreqDL - visibleMinFreqDL) * i / numTicks;
|
||||
const x = leftMargin + chartWidth * i / numTicks;
|
||||
|
||||
// Draw tick
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, downlinkStartY);
|
||||
ctx.lineTo(x, downlinkStartY - 5);
|
||||
ctx.stroke();
|
||||
|
||||
// Draw grid line
|
||||
ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, downlinkStartY);
|
||||
ctx.lineTo(x, downlinkStartY + downlinkHeight);
|
||||
ctx.stroke();
|
||||
ctx.strokeStyle = '#dee2e6';
|
||||
|
||||
// Draw label
|
||||
ctx.fillText(freq.toFixed(1), x, downlinkStartY - 10);
|
||||
}
|
||||
|
||||
// Draw DOWNLINK axis title
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.font = 'bold 12px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText('Downlink Частота (МГц)', width / 2, downlinkStartY - 25);
|
||||
|
||||
// Draw polarization label
|
||||
ctx.save();
|
||||
@@ -443,82 +575,203 @@ function renderChart() {
|
||||
// Draw transponders
|
||||
polarizations.forEach((pol, index) => {
|
||||
const group = polarizationGroups[pol];
|
||||
const color = getColor(pol);
|
||||
const y = topMargin + index * rowHeight;
|
||||
const barHeight = rowHeight * 0.7;
|
||||
const barY = y + (rowHeight - barHeight) / 2;
|
||||
const downlinkColor = '#0000ff';
|
||||
const uplinkColor = '#fd7e14';
|
||||
|
||||
// Draw polarization label
|
||||
// Uplink row (now on top)
|
||||
const uplinkY = uplinkStartY + index * rowHeightUL;
|
||||
const uplinkBarHeight = rowHeightUL * 0.8;
|
||||
const uplinkBarY = uplinkY + (rowHeightUL - uplinkBarHeight) / 2;
|
||||
|
||||
// Downlink row (now on bottom)
|
||||
const downlinkY = downlinkStartY + index * rowHeightDL;
|
||||
const downlinkBarHeight = rowHeightDL * 0.8;
|
||||
const downlinkBarY = downlinkY + (rowHeightDL - downlinkBarHeight) / 2;
|
||||
|
||||
// Draw polarization label for UL section
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.font = 'bold 12px sans-serif';
|
||||
ctx.textAlign = 'right';
|
||||
ctx.fillText(pol, leftMargin - 10, barY + barHeight / 2 + 4);
|
||||
ctx.font = 'bold 14px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(pol, leftMargin - 25, uplinkBarY + uplinkBarHeight / 2 + 4);
|
||||
|
||||
// Draw transponders
|
||||
// Draw polarization label for DL section
|
||||
ctx.fillText(pol, leftMargin - 25, downlinkBarY + downlinkBarHeight / 2 + 4);
|
||||
|
||||
// Draw separator lines between polarization groups
|
||||
if (index < polarizations.length - 1) {
|
||||
ctx.strokeStyle = '#adb5bd';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(leftMargin, uplinkY + rowHeightUL);
|
||||
ctx.lineTo(width - rightMargin, uplinkY + rowHeightUL);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(leftMargin, downlinkY + rowHeightDL);
|
||||
ctx.lineTo(width - rightMargin, downlinkY + rowHeightDL);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// Draw uplink transponders (now first, on top)
|
||||
group.forEach(t => {
|
||||
const startFreq = t.downlink - (t.frequency_range / 2);
|
||||
const endFreq = t.downlink + (t.frequency_range / 2);
|
||||
if (!t.uplink) return; // Skip if no uplink data
|
||||
|
||||
// Check if transponder is visible
|
||||
if (endFreq < visibleMinFreq || startFreq > visibleMaxFreq) {
|
||||
const startFreq = t.uplink - (t.frequency_range / 2);
|
||||
const endFreq = t.uplink + (t.frequency_range / 2);
|
||||
|
||||
// Check if transponder is visible in UL range
|
||||
if (endFreq < visibleMinFreqUL || startFreq > visibleMaxFreqUL) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate position
|
||||
const x1 = leftMargin + ((startFreq - visibleMinFreq) / (visibleMaxFreq - visibleMinFreq)) * chartWidth;
|
||||
const x2 = leftMargin + ((endFreq - visibleMinFreq) / (visibleMaxFreq - visibleMinFreq)) * chartWidth;
|
||||
// Calculate position using UL axis
|
||||
const x1 = leftMargin + ((startFreq - visibleMinFreqUL) / (visibleMaxFreqUL - visibleMinFreqUL)) * chartWidth;
|
||||
const x2 = leftMargin + ((endFreq - visibleMinFreqUL) / (visibleMaxFreqUL - visibleMinFreqUL)) * chartWidth;
|
||||
const barWidth = x2 - x1;
|
||||
|
||||
// Skip if too small
|
||||
if (barWidth < 1) return;
|
||||
|
||||
// Draw bar
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(x1, barY, barWidth, barHeight);
|
||||
const isHovered = hoveredTransponder && hoveredTransponder.transponder.name === t.name;
|
||||
|
||||
// Draw border
|
||||
ctx.strokeStyle = '#fff';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeRect(x1, barY, barWidth, barHeight);
|
||||
// Draw uplink bar
|
||||
ctx.fillStyle = uplinkColor;
|
||||
ctx.fillRect(x1, uplinkBarY, barWidth, uplinkBarHeight);
|
||||
|
||||
// Draw border (thicker if hovered)
|
||||
ctx.strokeStyle = isHovered ? '#000' : '#fff';
|
||||
ctx.lineWidth = isHovered ? 3 : 1;
|
||||
ctx.strokeRect(x1, uplinkBarY, barWidth, uplinkBarHeight);
|
||||
|
||||
// Draw name if there's space
|
||||
if (barWidth > 40) {
|
||||
ctx.fillStyle = (pol === 'R') ? '#000' : '#fff';
|
||||
ctx.font = '10px sans-serif';
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.font = isHovered ? 'bold 10px sans-serif' : '9px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(t.name, x1 + barWidth / 2, barY + barHeight / 2 + 3);
|
||||
ctx.fillText(t.name, x1 + barWidth / 2, uplinkBarY + uplinkBarHeight / 2 + 3);
|
||||
}
|
||||
|
||||
// Store for hover detection
|
||||
transponderRects.push({
|
||||
x: x1,
|
||||
y: barY,
|
||||
y: uplinkBarY,
|
||||
width: barWidth,
|
||||
height: barHeight,
|
||||
transponder: t
|
||||
height: uplinkBarHeight,
|
||||
transponder: t,
|
||||
type: 'uplink',
|
||||
centerX: x1 + barWidth / 2
|
||||
});
|
||||
});
|
||||
|
||||
// Draw downlink transponders (now second, on bottom)
|
||||
group.forEach(t => {
|
||||
const startFreq = t.downlink - (t.frequency_range / 2);
|
||||
const endFreq = t.downlink + (t.frequency_range / 2);
|
||||
|
||||
// Check if transponder is visible in DL range
|
||||
if (endFreq < visibleMinFreqDL || startFreq > visibleMaxFreqDL) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate position using DL axis
|
||||
const x1 = leftMargin + ((startFreq - visibleMinFreqDL) / (visibleMaxFreqDL - visibleMinFreqDL)) * chartWidth;
|
||||
const x2 = leftMargin + ((endFreq - visibleMinFreqDL) / (visibleMaxFreqDL - visibleMinFreqDL)) * chartWidth;
|
||||
const barWidth = x2 - x1;
|
||||
|
||||
if (barWidth < 1) return;
|
||||
|
||||
const isHovered = hoveredTransponder && hoveredTransponder.transponder.name === t.name;
|
||||
|
||||
// Draw downlink bar
|
||||
ctx.fillStyle = downlinkColor;
|
||||
ctx.fillRect(x1, downlinkBarY, barWidth, downlinkBarHeight);
|
||||
|
||||
// Draw border (thicker if hovered)
|
||||
ctx.strokeStyle = isHovered ? '#000' : '#fff';
|
||||
ctx.lineWidth = isHovered ? 3 : 1;
|
||||
ctx.strokeRect(x1, downlinkBarY, barWidth, downlinkBarHeight);
|
||||
|
||||
// Draw name if there's space
|
||||
if (barWidth > 40) {
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.font = isHovered ? 'bold 10px sans-serif' : '9px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(t.name, x1 + barWidth / 2, downlinkBarY + downlinkBarHeight / 2 + 3);
|
||||
}
|
||||
|
||||
// Store for hover detection
|
||||
transponderRects.push({
|
||||
x: x1,
|
||||
y: downlinkBarY,
|
||||
width: barWidth,
|
||||
height: downlinkBarHeight,
|
||||
transponder: t,
|
||||
type: 'downlink',
|
||||
centerX: x1 + barWidth / 2
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Draw hover tooltip
|
||||
// Draw connection line between downlink and uplink when hovering
|
||||
if (hoveredTransponder) {
|
||||
drawConnectionLine(hoveredTransponder);
|
||||
drawTooltip(hoveredTransponder);
|
||||
}
|
||||
}
|
||||
|
||||
function drawTooltip(t) {
|
||||
const startFreq = t.downlink - (t.frequency_range / 2);
|
||||
const endFreq = t.downlink + (t.frequency_range / 2);
|
||||
function drawConnectionLine(rectInfo) {
|
||||
const t = rectInfo.transponder;
|
||||
if (!t.uplink) return; // No uplink to connect
|
||||
|
||||
// Find both downlink and uplink rects for this transponder
|
||||
const downlinkRect = transponderRects.find(r => r.transponder.name === t.name && r.type === 'downlink');
|
||||
const uplinkRect = transponderRects.find(r => r.transponder.name === t.name && r.type === 'uplink');
|
||||
|
||||
if (!downlinkRect || !uplinkRect) return;
|
||||
|
||||
// Draw connecting line
|
||||
const x1 = downlinkRect.centerX;
|
||||
const y1 = downlinkRect.y + downlinkRect.height;
|
||||
const x2 = uplinkRect.centerX;
|
||||
const y2 = uplinkRect.y;
|
||||
|
||||
ctx.save();
|
||||
ctx.strokeStyle = '#ffc107';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.setLineDash([5, 3]);
|
||||
ctx.globalAlpha = 0.8;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x1, y1);
|
||||
ctx.lineTo(x2, y2);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawTooltip(rectInfo) {
|
||||
const t = rectInfo.transponder;
|
||||
const isUplink = rectInfo.type === 'uplink';
|
||||
const freq = isUplink ? t.uplink : t.downlink;
|
||||
const startFreq = freq - (t.frequency_range / 2);
|
||||
const endFreq = freq + (t.frequency_range / 2);
|
||||
|
||||
const lines = [
|
||||
t.name,
|
||||
'Тип: ' + (isUplink ? 'Uplink' : 'Downlink'),
|
||||
'Диапазон: ' + startFreq.toFixed(3) + ' - ' + endFreq.toFixed(3) + ' МГц',
|
||||
'Downlink: ' + t.downlink.toFixed(3) + ' МГц',
|
||||
'Центр: ' + freq.toFixed(3) + ' МГц',
|
||||
'Полоса: ' + t.frequency_range.toFixed(3) + ' МГц',
|
||||
'Поляризация: ' + t.polarization,
|
||||
'Зона: ' + t.zone_name
|
||||
];
|
||||
|
||||
// Add frequency conversion info for uplink
|
||||
if (isUplink && t.downlink && t.uplink) {
|
||||
const conversion = t.downlink - t.uplink;
|
||||
lines.push('Перенос: ' + conversion.toFixed(3) + ' МГц');
|
||||
}
|
||||
|
||||
// Calculate tooltip size
|
||||
ctx.font = '12px sans-serif';
|
||||
const padding = 10;
|
||||
@@ -533,17 +786,19 @@ function drawTooltip(t) {
|
||||
const tooltipHeight = lines.length * lineHeight + padding * 2;
|
||||
|
||||
// Position tooltip
|
||||
const mouseX = hoveredTransponder._mouseX || canvas.width / 2;
|
||||
const mouseY = hoveredTransponder._mouseY || canvas.height / 2;
|
||||
const mouseX = rectInfo._mouseX || canvas.width / 2;
|
||||
const mouseY = rectInfo._mouseY || canvas.height / 2;
|
||||
let tooltipX = mouseX + 15;
|
||||
let tooltipY = mouseY + 15;
|
||||
let tooltipY = mouseY - tooltipHeight - 15; // Always show above cursor
|
||||
|
||||
// Keep tooltip in bounds
|
||||
// Keep tooltip in bounds horizontally
|
||||
if (tooltipX + tooltipWidth > canvas.width) {
|
||||
tooltipX = mouseX - tooltipWidth - 15;
|
||||
}
|
||||
if (tooltipY + tooltipHeight > canvas.height) {
|
||||
tooltipY = mouseY - tooltipHeight - 15;
|
||||
|
||||
// If tooltip goes above canvas, show below cursor instead
|
||||
if (tooltipY < 0) {
|
||||
tooltipY = mouseY + 15;
|
||||
}
|
||||
|
||||
// Draw tooltip background
|
||||
@@ -565,24 +820,50 @@ function drawTooltip(t) {
|
||||
function handleWheel(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const delta = e.deltaY > 0 ? 0.9 : 1.1;
|
||||
const newZoom = Math.max(1, Math.min(20, zoomLevel * delta));
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const mouseY = e.clientY - rect.top;
|
||||
|
||||
if (newZoom !== zoomLevel) {
|
||||
zoomLevel = newZoom;
|
||||
// Determine which area we're zooming
|
||||
const isUplinkArea = mouseY < (uplinkStartY + uplinkHeight);
|
||||
|
||||
const delta = e.deltaY > 0 ? 0.9 : 1.1;
|
||||
|
||||
if (isUplinkArea) {
|
||||
const newZoom = Math.max(1, Math.min(20, zoomLevelUL * delta));
|
||||
if (newZoom !== zoomLevelUL) {
|
||||
zoomLevelUL = newZoom;
|
||||
|
||||
// Adjust pan to keep center
|
||||
const maxPan = (originalFreqRange * (zoomLevel - 1)) / (2 * zoomLevel);
|
||||
panOffset = Math.max(-maxPan, Math.min(maxPan, panOffset));
|
||||
const maxPan = (originalFreqRangeUL * (zoomLevelUL - 1)) / (2 * zoomLevelUL);
|
||||
panOffsetUL = Math.max(-maxPan, Math.min(maxPan, panOffsetUL));
|
||||
|
||||
renderChart();
|
||||
}
|
||||
} else {
|
||||
const newZoom = Math.max(1, Math.min(20, zoomLevelDL * delta));
|
||||
if (newZoom !== zoomLevelDL) {
|
||||
zoomLevelDL = newZoom;
|
||||
|
||||
// Adjust pan to keep center
|
||||
const maxPan = (originalFreqRangeDL * (zoomLevelDL - 1)) / (2 * zoomLevelDL);
|
||||
panOffsetDL = Math.max(-maxPan, Math.min(maxPan, panOffsetDL));
|
||||
|
||||
renderChart();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleMouseDown(e) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const mouseY = e.clientY - rect.top;
|
||||
|
||||
// Determine which area we're dragging
|
||||
dragArea = mouseY < (uplinkStartY + uplinkHeight) ? 'uplink' : 'downlink';
|
||||
|
||||
isDragging = true;
|
||||
dragStartX = e.clientX;
|
||||
dragStartOffset = panOffset;
|
||||
dragStartOffsetUL = panOffsetUL;
|
||||
dragStartOffsetDL = panOffsetDL;
|
||||
canvas.style.cursor = 'grabbing';
|
||||
}
|
||||
|
||||
@@ -593,12 +874,22 @@ function handleMouseMove(e) {
|
||||
|
||||
if (isDragging) {
|
||||
const dx = e.clientX - dragStartX;
|
||||
const freqPerPixel = (freqRange / zoomLevel) / (rect.width - 80);
|
||||
panOffset = dragStartOffset - dx * freqPerPixel;
|
||||
|
||||
if (dragArea === 'uplink') {
|
||||
const freqPerPixel = (freqRangeUL / zoomLevelUL) / (rect.width - 80);
|
||||
panOffsetUL = dragStartOffsetUL - dx * freqPerPixel;
|
||||
|
||||
// Limit pan
|
||||
const maxPan = (originalFreqRange * (zoomLevel - 1)) / (2 * zoomLevel);
|
||||
panOffset = Math.max(-maxPan, Math.min(maxPan, panOffset));
|
||||
const maxPan = (originalFreqRangeUL * (zoomLevelUL - 1)) / (2 * zoomLevelUL);
|
||||
panOffsetUL = Math.max(-maxPan, Math.min(maxPan, panOffsetUL));
|
||||
} else {
|
||||
const freqPerPixel = (freqRangeDL / zoomLevelDL) / (rect.width - 80);
|
||||
panOffsetDL = dragStartOffsetDL - dx * freqPerPixel;
|
||||
|
||||
// Limit pan
|
||||
const maxPan = (originalFreqRangeDL * (zoomLevelDL - 1)) / (2 * zoomLevelDL);
|
||||
panOffsetDL = Math.max(-maxPan, Math.min(maxPan, panOffsetDL));
|
||||
}
|
||||
|
||||
renderChart();
|
||||
} else {
|
||||
@@ -607,7 +898,7 @@ function handleMouseMove(e) {
|
||||
for (const tr of transponderRects) {
|
||||
if (mouseX >= tr.x && mouseX <= tr.x + tr.width &&
|
||||
mouseY >= tr.y && mouseY <= tr.y + tr.height) {
|
||||
found = tr.transponder;
|
||||
found = tr;
|
||||
found._mouseX = mouseX;
|
||||
found._mouseY = mouseY;
|
||||
break;
|
||||
@@ -638,20 +929,27 @@ function handleMouseLeave() {
|
||||
}
|
||||
|
||||
function resetZoom() {
|
||||
zoomLevel = 1;
|
||||
panOffset = 0;
|
||||
zoomLevelUL = 1;
|
||||
zoomLevelDL = 1;
|
||||
panOffsetUL = 0;
|
||||
panOffsetDL = 0;
|
||||
renderChart();
|
||||
}
|
||||
|
||||
function zoomIn() {
|
||||
zoomLevel = Math.min(20, zoomLevel * 1.2);
|
||||
zoomLevelUL = Math.min(20, zoomLevelUL * 1.2);
|
||||
zoomLevelDL = Math.min(20, zoomLevelDL * 1.2);
|
||||
renderChart();
|
||||
}
|
||||
|
||||
function zoomOut() {
|
||||
zoomLevel = Math.max(1, zoomLevel / 1.2);
|
||||
if (zoomLevel === 1) {
|
||||
panOffset = 0;
|
||||
zoomLevelUL = Math.max(1, zoomLevelUL / 1.2);
|
||||
zoomLevelDL = Math.max(1, zoomLevelDL / 1.2);
|
||||
if (zoomLevelUL === 1) {
|
||||
panOffsetUL = 0;
|
||||
}
|
||||
if (zoomLevelDL === 1) {
|
||||
panOffsetDL = 0;
|
||||
}
|
||||
renderChart();
|
||||
}
|
||||
@@ -662,8 +960,8 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
|
||||
// Control buttons
|
||||
document.getElementById('resetZoom').addEventListener('click', resetZoom);
|
||||
document.getElementById('zoomIn').addEventListener('click', zoomIn);
|
||||
document.getElementById('zoomOut').addEventListener('click', zoomOut);
|
||||
// document.getElementById('zoomIn').addEventListener('click', zoomIn);
|
||||
// document.getElementById('zoomOut').addEventListener('click', zoomOut);
|
||||
});
|
||||
|
||||
// Re-render on window resize
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
971
dbapp/mainapp/templates/mainapp/secret_stats.html
Normal file
971
dbapp/mainapp/templates/mainapp/secret_stats.html
Normal file
@@ -0,0 +1,971 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🎉 Итоги {{ year }} года</title>
|
||||
<link href="{% static 'bootstrap/bootstrap.min.css' %}" rel="stylesheet">
|
||||
<link href="{% static 'bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700;900&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root {
|
||||
--gradient-1: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
--gradient-2: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
|
||||
--gradient-3: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
|
||||
--gradient-4: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
|
||||
--gradient-5: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
|
||||
--gradient-6: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
|
||||
--dark-bg: #0d1117;
|
||||
--card-bg: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
font-family: 'Montserrat', sans-serif;
|
||||
background: var(--dark-bg);
|
||||
color: #fff;
|
||||
overflow-x: hidden;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.particles {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.particle {
|
||||
position: absolute;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 50%;
|
||||
animation: float 15s infinite ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translateY(100vh) rotate(0deg); opacity: 0; }
|
||||
10% { opacity: 1; }
|
||||
90% { opacity: 1; }
|
||||
100% { transform: translateY(-100vh) rotate(720deg); opacity: 0; }
|
||||
}
|
||||
|
||||
.slide {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 40px 20px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.slide-intro { background: var(--gradient-1); }
|
||||
.slide-points { background: var(--gradient-2); }
|
||||
.slide-new { background: var(--gradient-3); }
|
||||
.slide-satellites { background: var(--gradient-4); }
|
||||
.slide-time { background: var(--gradient-5); }
|
||||
.slide-summary { background: var(--gradient-1); }
|
||||
|
||||
.big-number {
|
||||
font-size: clamp(4rem, 15vw, 12rem);
|
||||
font-weight: 900;
|
||||
line-height: 1;
|
||||
text-shadow: 0 10px 30px rgba(0,0,0,0.3);
|
||||
opacity: 0;
|
||||
transform: scale(0.5);
|
||||
animation: popIn 0.8s ease-out forwards;
|
||||
}
|
||||
|
||||
.big-text {
|
||||
font-size: clamp(1.5rem, 4vw, 3rem);
|
||||
font-weight: 700;
|
||||
text-shadow: 0 5px 15px rgba(0,0,0,0.2);
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
animation: slideUp 0.6s ease-out 0.3s forwards;
|
||||
}
|
||||
|
||||
.sub-text {
|
||||
font-size: clamp(1rem, 2vw, 1.5rem);
|
||||
font-weight: 400;
|
||||
opacity: 0.9;
|
||||
margin-top: 10px;
|
||||
opacity: 0;
|
||||
animation: fadeIn 0.6s ease-out 0.5s forwards;
|
||||
}
|
||||
|
||||
@keyframes popIn {
|
||||
0% { opacity: 0; transform: scale(0.5); }
|
||||
70% { transform: scale(1.1); }
|
||||
100% { opacity: 1; transform: scale(1); }
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
to { opacity: 0.9; }
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% { transform: scale(1); }
|
||||
50% { transform: scale(1.05); }
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 24px;
|
||||
padding: 30px;
|
||||
margin: 15px;
|
||||
text-align: center;
|
||||
transition: all 0.3s ease;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
opacity: 0;
|
||||
transform: translateY(50px);
|
||||
animation: cardSlideUp 0.6s ease-out forwards;
|
||||
}
|
||||
|
||||
.stat-card:hover {
|
||||
transform: translateY(-10px) scale(1.02);
|
||||
box-shadow: 0 20px 40px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
@keyframes cardSlideUp {
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.stat-card:nth-child(1) { animation-delay: 0.2s; }
|
||||
.stat-card:nth-child(2) { animation-delay: 0.4s; }
|
||||
.stat-card:nth-child(3) { animation-delay: 0.6s; }
|
||||
.stat-card:nth-child(4) { animation-delay: 0.8s; }
|
||||
|
||||
.stat-value {
|
||||
font-size: 3rem;
|
||||
font-weight: 900;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 1rem;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.satellite-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 15px;
|
||||
max-width: 1200px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.satellite-item {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 16px;
|
||||
padding: 20px 30px;
|
||||
text-align: center;
|
||||
transition: all 0.3s ease;
|
||||
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||
opacity: 0;
|
||||
transform: scale(0.8);
|
||||
animation: satelliteIn 0.5s ease-out forwards;
|
||||
}
|
||||
|
||||
.satellite-item:hover {
|
||||
transform: scale(1.1);
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
@keyframes satelliteIn {
|
||||
to { opacity: 1; transform: scale(1); }
|
||||
}
|
||||
|
||||
.satellite-item:nth-child(1) { animation-delay: 0.1s; }
|
||||
.satellite-item:nth-child(2) { animation-delay: 0.2s; }
|
||||
.satellite-item:nth-child(3) { animation-delay: 0.3s; }
|
||||
.satellite-item:nth-child(4) { animation-delay: 0.4s; }
|
||||
.satellite-item:nth-child(5) { animation-delay: 0.5s; }
|
||||
.satellite-item:nth-child(6) { animation-delay: 0.6s; }
|
||||
.satellite-item:nth-child(7) { animation-delay: 0.7s; }
|
||||
.satellite-item:nth-child(8) { animation-delay: 0.8s; }
|
||||
.satellite-item:nth-child(9) { animation-delay: 0.9s; }
|
||||
.satellite-item:nth-child(10) { animation-delay: 1.0s; }
|
||||
|
||||
.satellite-name {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.satellite-stats {
|
||||
font-size: 0.9rem;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.chart-container {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 24px;
|
||||
padding: 30px;
|
||||
margin: 20px;
|
||||
max-width: 800px;
|
||||
width: 100%;
|
||||
opacity: 0;
|
||||
animation: fadeIn 0.8s ease-out 0.5s forwards;
|
||||
}
|
||||
|
||||
.chart-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.year-selector {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 1000;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 12px;
|
||||
padding: 10px 20px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
.year-selector select {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: #fff;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.year-selector select option {
|
||||
background: #333;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.scroll-indicator {
|
||||
position: fixed;
|
||||
bottom: 30px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
animation: bounce 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
0%, 20%, 50%, 80%, 100% { transform: translateX(-50%) translateY(0); }
|
||||
40% { transform: translateX(-50%) translateY(-20px); }
|
||||
60% { transform: translateX(-50%) translateY(-10px); }
|
||||
}
|
||||
|
||||
.scroll-indicator i {
|
||||
font-size: 2rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
.emoji-rain {
|
||||
position: fixed;
|
||||
top: -50px;
|
||||
font-size: 2rem;
|
||||
animation: rain 3s linear forwards;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
@keyframes rain {
|
||||
to { transform: translateY(110vh) rotate(360deg); }
|
||||
}
|
||||
|
||||
.glow-text {
|
||||
text-shadow: 0 0 10px currentColor, 0 0 20px currentColor, 0 0 30px currentColor;
|
||||
}
|
||||
|
||||
.counter {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.progress-bar-custom {
|
||||
height: 30px;
|
||||
border-radius: 15px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
overflow: hidden;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(90deg, #fff 0%, rgba(255,255,255,0.7) 100%);
|
||||
transition: width 1.5s ease-out;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding-right: 15px;
|
||||
font-weight: 700;
|
||||
font-size: 0.9rem;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.new-emissions-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 15px;
|
||||
max-width: 1200px;
|
||||
margin-top: 30px;
|
||||
width: 100%;
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
.emission-card {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 12px;
|
||||
padding: 15px 20px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
opacity: 0;
|
||||
transform: translateX(-30px);
|
||||
animation: slideRight 0.5s ease-out forwards;
|
||||
}
|
||||
|
||||
@keyframes slideRight {
|
||||
to { opacity: 1; transform: translateX(0); }
|
||||
}
|
||||
|
||||
.emission-name {
|
||||
font-weight: 700;
|
||||
font-size: 1.1rem;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.emission-info {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.confetti {
|
||||
position: fixed;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
top: -10px;
|
||||
z-index: 1000;
|
||||
animation: confetti-fall 3s linear forwards;
|
||||
}
|
||||
|
||||
@keyframes confetti-fall {
|
||||
0% { transform: translateY(0) rotate(0deg); opacity: 1; }
|
||||
100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
|
||||
}
|
||||
|
||||
.heatmap-container {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
justify-content: center;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.heatmap-cell {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 700;
|
||||
font-size: 0.8rem;
|
||||
transition: all 0.3s ease;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.heatmap-cell:hover {
|
||||
transform: scale(1.2);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.nav-dots {
|
||||
position: fixed;
|
||||
right: 20px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.nav-dot {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.nav-dot:hover, .nav-dot.active {
|
||||
background: #fff;
|
||||
transform: scale(1.3);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.big-number { font-size: 4rem; }
|
||||
.big-text { font-size: 1.5rem; }
|
||||
.stat-card { padding: 20px; margin: 10px; }
|
||||
.stat-value { font-size: 2rem; }
|
||||
.nav-dots { display: none; }
|
||||
.year-selector { top: 10px; right: 10px; padding: 8px 15px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Particles Background -->
|
||||
<div class="particles" id="particles"></div>
|
||||
|
||||
<!-- Year Selector -->
|
||||
<div class="year-selector">
|
||||
<select id="yearSelect" onchange="changeYear(this.value)">
|
||||
{% for y in available_years %}
|
||||
<option value="{{ y }}" {% if y == year %}selected{% endif %}>{{ y }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Navigation Dots -->
|
||||
<div class="nav-dots">
|
||||
<div class="nav-dot active" data-slide="0" title="Начало"></div>
|
||||
<div class="nav-dot" data-slide="1" title="Точки ГЛ"></div>
|
||||
<div class="nav-dot" data-slide="2" title="Новые излучения"></div>
|
||||
<div class="nav-dot" data-slide="3" title="Спутники"></div>
|
||||
<div class="nav-dot" data-slide="4" title="Время"></div>
|
||||
<div class="nav-dot" data-slide="5" title="Итоги"></div>
|
||||
</div>
|
||||
|
||||
<!-- Scroll Indicator -->
|
||||
<div class="scroll-indicator" id="scrollIndicator">
|
||||
<i class="bi bi-chevron-double-down"></i>
|
||||
</div>
|
||||
|
||||
<!-- Slide 1: Intro -->
|
||||
<section class="slide slide-intro" data-slide="0">
|
||||
<div class="text-center">
|
||||
<div class="big-text" style="animation-delay: 0s;">🎉 Ваш {{ year }} год</div>
|
||||
<div class="big-number" style="animation-delay: 0.3s;">в цифрах</div>
|
||||
<div class="sub-text" style="animation-delay: 0.6s;">Итоги работы системы геолокации</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Slide 2: Total Points -->
|
||||
<section class="slide slide-points" data-slide="1">
|
||||
<div class="text-center">
|
||||
<div class="sub-text">За {{ year }} год вы получили</div>
|
||||
<div class="big-number counter" data-target="{{ total_points }}">0</div>
|
||||
<div class="big-text">точек геолокации</div>
|
||||
<div class="sub-text">по <span class="counter" data-target="{{ total_sources }}">0</span> объектам</div>
|
||||
|
||||
{% if busiest_day %}
|
||||
<div class="stat-card mt-5" style="display: inline-block;">
|
||||
<div class="stat-label">🔥 Самый активный день</div>
|
||||
<div class="stat-value">{{ busiest_day.date|date:"d.m.Y" }}</div>
|
||||
<div class="stat-label">{{ busiest_day.points }} точек</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Slide 3: New Emissions -->
|
||||
<section class="slide slide-new" data-slide="2">
|
||||
<div class="text-center">
|
||||
<div class="sub-text">✨ Новые открытия</div>
|
||||
<div class="big-number counter" data-target="{{ new_emissions_count }}">0</div>
|
||||
<div class="big-text">новых излучений</div>
|
||||
<div class="sub-text">впервые обнаруженных в {{ year }} году</div>
|
||||
<div class="sub-text">по <span class="counter" data-target="{{ new_emissions_sources }}">0</span> объектам</div>
|
||||
|
||||
{% if new_emission_objects %}
|
||||
<div class="new-emissions-grid">
|
||||
{% for obj in new_emission_objects %}
|
||||
<div class="emission-card" style="animation-delay: {{ forloop.counter0|divisibleby:10 }}s;">
|
||||
<div class="emission-name">{{ obj.name }}</div>
|
||||
<div class="emission-info">{{ obj.info }} • {{ obj.ownership }}</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Slide 4: Satellites -->
|
||||
<section class="slide slide-satellites" data-slide="3">
|
||||
<div class="text-center">
|
||||
<div class="sub-text">📡 Спутники</div>
|
||||
<div class="big-number counter" data-target="{{ satellite_count }}">0</div>
|
||||
<div class="big-text">спутников с данными</div>
|
||||
|
||||
<div class="satellite-list">
|
||||
{% for sat in satellite_stats %}
|
||||
<div class="satellite-item">
|
||||
<div class="satellite-name">{{ sat.parameter_obj__id_satellite__name }}</div>
|
||||
<div class="satellite-stats">
|
||||
<strong>{{ sat.points_count }}</strong> точек •
|
||||
<strong>{{ sat.sources_count }}</strong> объектов
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<div class="chart-container mt-4">
|
||||
<div class="chart-title">Распределение точек по спутникам</div>
|
||||
<canvas id="satelliteChart" height="300"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Slide 5: Time Analysis -->
|
||||
<section class="slide slide-time" data-slide="4">
|
||||
<div class="text-center">
|
||||
<div class="sub-text">⏰ Когда вы работали</div>
|
||||
<div class="big-text">Анализ по времени</div>
|
||||
|
||||
<div class="row justify-content-center mt-4">
|
||||
<div class="col-md-5">
|
||||
<div class="chart-container">
|
||||
<div class="chart-title">По месяцам</div>
|
||||
<canvas id="monthlyChart" height="250"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<div class="chart-container">
|
||||
<div class="chart-title">По дням недели</div>
|
||||
<canvas id="weekdayChart" height="250"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chart-container" style="max-width: 600px;">
|
||||
<div class="chart-title">По часам</div>
|
||||
<canvas id="hourlyChart" height="200"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Slide 6: Summary -->
|
||||
<section class="slide slide-summary" data-slide="5">
|
||||
<div class="text-center">
|
||||
<div class="big-text">🏆 Итоги {{ year }}</div>
|
||||
|
||||
<div class="row justify-content-center mt-4">
|
||||
<div class="col-auto">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value glow-text">{{ total_points }}</div>
|
||||
<div class="stat-label">Точек ГЛ</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value glow-text">{{ total_sources }}</div>
|
||||
<div class="stat-label">Объектов</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value glow-text">{{ new_emissions_count }}</div>
|
||||
<div class="stat-label">Новых излучений</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value glow-text">{{ satellite_count }}</div>
|
||||
<div class="stat-label">Спутников</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chart-container mt-4" style="max-width: 700px;">
|
||||
<div class="chart-title">🌟 Топ-10 объектов по количеству точек</div>
|
||||
<canvas id="topObjectsChart" height="300"></canvas>
|
||||
</div>
|
||||
|
||||
<div class="mt-5">
|
||||
<div class="big-text">До встречи в {{ year|add:1 }}! 🚀</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script src="{% static 'chartjs/chart.js' %}"></script>
|
||||
<script src="{% static 'chartjs/chart-datalabels.js' %}"></script>
|
||||
<script>
|
||||
// Data from Django
|
||||
const monthlyData = {{ monthly_data_json|safe }};
|
||||
const satelliteStats = {{ satellite_stats_json|safe }};
|
||||
const weekdayData = {{ weekday_data_json|safe }};
|
||||
const hourlyData = {{ hourly_data_json|safe }};
|
||||
const topObjects = {{ top_objects_json|safe }};
|
||||
|
||||
// Create particles
|
||||
function createParticles() {
|
||||
const container = document.getElementById('particles');
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const particle = document.createElement('div');
|
||||
particle.className = 'particle';
|
||||
particle.style.left = Math.random() * 100 + '%';
|
||||
particle.style.animationDelay = Math.random() * 15 + 's';
|
||||
particle.style.animationDuration = (10 + Math.random() * 10) + 's';
|
||||
particle.style.width = (5 + Math.random() * 10) + 'px';
|
||||
particle.style.height = particle.style.width;
|
||||
container.appendChild(particle);
|
||||
}
|
||||
}
|
||||
createParticles();
|
||||
|
||||
// Counter animation
|
||||
function animateCounters() {
|
||||
const counters = document.querySelectorAll('.counter');
|
||||
counters.forEach(counter => {
|
||||
const target = parseInt(counter.dataset.target) || 0;
|
||||
const duration = 2000;
|
||||
const step = target / (duration / 16);
|
||||
let current = 0;
|
||||
|
||||
const updateCounter = () => {
|
||||
current += step;
|
||||
if (current < target) {
|
||||
counter.textContent = Math.floor(current).toLocaleString('ru-RU');
|
||||
requestAnimationFrame(updateCounter);
|
||||
} else {
|
||||
counter.textContent = target.toLocaleString('ru-RU');
|
||||
}
|
||||
};
|
||||
updateCounter();
|
||||
});
|
||||
}
|
||||
|
||||
// Intersection Observer for animations
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
const slideIndex = entry.target.dataset.slide;
|
||||
document.querySelectorAll('.nav-dot').forEach((dot, i) => {
|
||||
dot.classList.toggle('active', i == slideIndex);
|
||||
});
|
||||
|
||||
// Trigger counter animation when slide is visible
|
||||
if (slideIndex == 1 || slideIndex == 2 || slideIndex == 3 || slideIndex == 5) {
|
||||
entry.target.querySelectorAll('.counter').forEach(counter => {
|
||||
if (!counter.dataset.animated) {
|
||||
counter.dataset.animated = 'true';
|
||||
const target = parseInt(counter.dataset.target) || 0;
|
||||
animateCounter(counter, target);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Create confetti on summary slide
|
||||
if (slideIndex == 5 && !window.confettiCreated) {
|
||||
window.confettiCreated = true;
|
||||
createConfetti();
|
||||
}
|
||||
}
|
||||
});
|
||||
}, { threshold: 0.5 });
|
||||
|
||||
document.querySelectorAll('.slide').forEach(slide => observer.observe(slide));
|
||||
|
||||
function animateCounter(element, target) {
|
||||
const duration = 2000;
|
||||
const step = target / (duration / 16);
|
||||
let current = 0;
|
||||
|
||||
const update = () => {
|
||||
current += step;
|
||||
if (current < target) {
|
||||
element.textContent = Math.floor(current).toLocaleString('ru-RU');
|
||||
requestAnimationFrame(update);
|
||||
} else {
|
||||
element.textContent = target.toLocaleString('ru-RU');
|
||||
}
|
||||
};
|
||||
update();
|
||||
}
|
||||
|
||||
// Confetti effect
|
||||
function createConfetti() {
|
||||
const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7', '#dfe6e9', '#fd79a8', '#a29bfe'];
|
||||
for (let i = 0; i < 100; i++) {
|
||||
setTimeout(() => {
|
||||
const confetti = document.createElement('div');
|
||||
confetti.className = 'confetti';
|
||||
confetti.style.left = Math.random() * 100 + '%';
|
||||
confetti.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
|
||||
confetti.style.animationDuration = (2 + Math.random() * 2) + 's';
|
||||
confetti.style.borderRadius = Math.random() > 0.5 ? '50%' : '0';
|
||||
document.body.appendChild(confetti);
|
||||
setTimeout(() => confetti.remove(), 4000);
|
||||
}, i * 30);
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation dots click
|
||||
document.querySelectorAll('.nav-dot').forEach(dot => {
|
||||
dot.addEventListener('click', () => {
|
||||
const slideIndex = dot.dataset.slide;
|
||||
document.querySelector(`[data-slide="${slideIndex}"]`).scrollIntoView({ behavior: 'smooth' });
|
||||
});
|
||||
});
|
||||
|
||||
// Hide scroll indicator on scroll
|
||||
window.addEventListener('scroll', () => {
|
||||
const indicator = document.getElementById('scrollIndicator');
|
||||
if (window.scrollY > 100) {
|
||||
indicator.style.opacity = '0';
|
||||
} else {
|
||||
indicator.style.opacity = '1';
|
||||
}
|
||||
});
|
||||
|
||||
// Year change
|
||||
function changeYear(year) {
|
||||
window.location.href = '?year=' + year;
|
||||
}
|
||||
|
||||
// Chart.js configuration
|
||||
Chart.defaults.color = '#fff';
|
||||
Chart.defaults.borderColor = 'rgba(255, 255, 255, 0.1)';
|
||||
|
||||
// Monthly Chart
|
||||
if (monthlyData.length > 0) {
|
||||
const monthNames = ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'];
|
||||
new Chart(document.getElementById('monthlyChart'), {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: monthlyData.map(d => {
|
||||
if (d.month) {
|
||||
const [year, month] = d.month.split('-');
|
||||
return monthNames[parseInt(month) - 1];
|
||||
}
|
||||
return '';
|
||||
}),
|
||||
datasets: [{
|
||||
label: 'Точки',
|
||||
data: monthlyData.map(d => d.points),
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.7)',
|
||||
borderRadius: 8,
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
datalabels: { display: false }
|
||||
},
|
||||
scales: {
|
||||
y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.1)' } },
|
||||
x: { grid: { display: false } }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Weekday Chart
|
||||
if (weekdayData.length > 0) {
|
||||
const weekdayNames = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
|
||||
const sortedWeekday = [...weekdayData].sort((a, b) => {
|
||||
// Convert Sunday (1) to 7 for proper sorting (Mon-Sun)
|
||||
const aDay = a.weekday === 1 ? 8 : a.weekday;
|
||||
const bDay = b.weekday === 1 ? 8 : b.weekday;
|
||||
return aDay - bDay;
|
||||
});
|
||||
|
||||
new Chart(document.getElementById('weekdayChart'), {
|
||||
type: 'polarArea',
|
||||
data: {
|
||||
labels: sortedWeekday.map(d => weekdayNames[d.weekday - 1]),
|
||||
datasets: [{
|
||||
data: sortedWeekday.map(d => d.points),
|
||||
backgroundColor: [
|
||||
'rgba(255, 99, 132, 0.7)',
|
||||
'rgba(54, 162, 235, 0.7)',
|
||||
'rgba(255, 206, 86, 0.7)',
|
||||
'rgba(75, 192, 192, 0.7)',
|
||||
'rgba(153, 102, 255, 0.7)',
|
||||
'rgba(255, 159, 64, 0.7)',
|
||||
'rgba(199, 199, 199, 0.7)'
|
||||
],
|
||||
borderWidth: 2,
|
||||
borderColor: '#fff'
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: { position: 'right' },
|
||||
datalabels: { display: false }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Hourly Chart
|
||||
if (hourlyData.length > 0) {
|
||||
// Fill missing hours with 0
|
||||
const fullHourlyData = Array.from({length: 24}, (_, i) => {
|
||||
const found = hourlyData.find(d => d.hour === i);
|
||||
return found ? found.points : 0;
|
||||
});
|
||||
|
||||
new Chart(document.getElementById('hourlyChart'), {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: Array.from({length: 24}, (_, i) => i + ':00'),
|
||||
datasets: [{
|
||||
label: 'Точки',
|
||||
data: fullHourlyData,
|
||||
borderColor: 'rgba(255, 255, 255, 0.9)',
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.2)',
|
||||
fill: true,
|
||||
tension: 0.4,
|
||||
pointRadius: 4,
|
||||
pointBackgroundColor: '#fff'
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
datalabels: { display: false }
|
||||
},
|
||||
scales: {
|
||||
y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.1)' } },
|
||||
x: { grid: { display: false } }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Satellite Pie Chart
|
||||
if (satelliteStats.length > 0) {
|
||||
const top10 = satelliteStats.slice(0, 10);
|
||||
const otherPoints = satelliteStats.slice(10).reduce((sum, s) => sum + s.points_count, 0);
|
||||
|
||||
const labels = top10.map(s => s.parameter_obj__id_satellite__name);
|
||||
const data = top10.map(s => s.points_count);
|
||||
|
||||
if (otherPoints > 0) {
|
||||
labels.push('Другие');
|
||||
data.push(otherPoints);
|
||||
}
|
||||
|
||||
const colors = [
|
||||
'#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7',
|
||||
'#dfe6e9', '#fd79a8', '#a29bfe', '#00b894', '#e17055', '#636e72'
|
||||
];
|
||||
|
||||
new Chart(document.getElementById('satelliteChart'), {
|
||||
type: 'doughnut',
|
||||
data: {
|
||||
labels: labels,
|
||||
datasets: [{
|
||||
data: data,
|
||||
backgroundColor: colors.slice(0, data.length),
|
||||
borderWidth: 3,
|
||||
borderColor: 'rgba(255,255,255,0.3)'
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
cutout: '60%',
|
||||
plugins: {
|
||||
legend: { position: 'right', labels: { padding: 15 } },
|
||||
datalabels: {
|
||||
color: '#fff',
|
||||
font: { weight: 'bold', size: 11 },
|
||||
formatter: (value, ctx) => {
|
||||
const total = ctx.dataset.data.reduce((a, b) => a + b, 0);
|
||||
const pct = ((value / total) * 100).toFixed(1);
|
||||
return pct > 5 ? pct + '%' : '';
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: [ChartDataLabels]
|
||||
});
|
||||
}
|
||||
|
||||
// Top Objects Chart
|
||||
if (topObjects.length > 0) {
|
||||
const colors = [
|
||||
'#ffd700', '#c0c0c0', '#cd7f32', '#4ecdc4', '#45b7d1',
|
||||
'#96ceb4', '#ffeaa7', '#fd79a8', '#a29bfe', '#00b894'
|
||||
];
|
||||
|
||||
new Chart(document.getElementById('topObjectsChart'), {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: topObjects.map(o => o.name.length > 20 ? o.name.substring(0, 20) + '...' : o.name),
|
||||
datasets: [{
|
||||
label: 'Точки',
|
||||
data: topObjects.map(o => o.points),
|
||||
backgroundColor: colors,
|
||||
borderRadius: 8,
|
||||
borderSkipped: false
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
indexAxis: 'y',
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
datalabels: {
|
||||
anchor: 'end',
|
||||
align: 'end',
|
||||
color: '#fff',
|
||||
font: { weight: 'bold' },
|
||||
formatter: (value) => value.toLocaleString('ru-RU')
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
grid: { color: 'rgba(255,255,255,0.1)' },
|
||||
grace: '15%'
|
||||
},
|
||||
y: { grid: { display: false } }
|
||||
}
|
||||
},
|
||||
plugins: [ChartDataLabels]
|
||||
});
|
||||
}
|
||||
|
||||
// Emoji rain on intro
|
||||
setTimeout(() => {
|
||||
const emojis = ['🛰️', '📡', '🌍', '✨', '🎯', '📍', '🔭', '⭐'];
|
||||
for (let i = 0; i < 20; i++) {
|
||||
setTimeout(() => {
|
||||
const emoji = document.createElement('div');
|
||||
emoji.className = 'emoji-rain';
|
||||
emoji.textContent = emojis[Math.floor(Math.random() * emojis.length)];
|
||||
emoji.style.left = Math.random() * 100 + '%';
|
||||
emoji.style.animationDuration = (2 + Math.random() * 2) + 's';
|
||||
document.body.appendChild(emoji);
|
||||
setTimeout(() => emoji.remove(), 4000);
|
||||
}, i * 200);
|
||||
}
|
||||
}, 1000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
642
dbapp/mainapp/templates/mainapp/signal_marks.html
Normal file
642
dbapp/mainapp/templates/mainapp/signal_marks.html
Normal file
@@ -0,0 +1,642 @@
|
||||
{% extends "mainapp/base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Отметки сигналов{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link href="{% static 'tabulator/css/tabulator_bootstrap5.min.css' %}" rel="stylesheet">
|
||||
<style>
|
||||
.satellite-selector {
|
||||
background-color: #f8f9fa;
|
||||
border: 1px solid #dee2e6;
|
||||
border-radius: 0.375rem;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link.active {
|
||||
background-color: #0d6efd;
|
||||
color: white;
|
||||
border-color: #0d6efd;
|
||||
}
|
||||
|
||||
/* Стили для ячеек истории */
|
||||
.mark-cell {
|
||||
text-align: center;
|
||||
padding: 4px 6px;
|
||||
font-size: 0.8rem;
|
||||
min-width: 70px;
|
||||
}
|
||||
|
||||
.mark-present {
|
||||
background-color: #d4edda !important;
|
||||
color: #155724;
|
||||
}
|
||||
|
||||
.mark-absent {
|
||||
background-color: #f8d7da !important;
|
||||
color: #721c24;
|
||||
}
|
||||
|
||||
.mark-empty {
|
||||
background-color: #f8f9fa;
|
||||
color: #adb5bd;
|
||||
}
|
||||
|
||||
.mark-user {
|
||||
font-size: 0.7rem;
|
||||
color: #6c757d;
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Стили для кнопок отметок */
|
||||
.mark-btn-group {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.mark-btn {
|
||||
padding: 2px 10px;
|
||||
font-size: 0.8rem;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
border: 2px solid transparent;
|
||||
}
|
||||
|
||||
.mark-btn-yes {
|
||||
background-color: #e8f5e9;
|
||||
color: #2e7d32;
|
||||
border-color: #a5d6a7;
|
||||
}
|
||||
|
||||
.mark-btn-yes.selected {
|
||||
background-color: #4caf50;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.mark-btn-no {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border-color: #ef9a9a;
|
||||
}
|
||||
|
||||
.mark-btn-no.selected {
|
||||
background-color: #f44336;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.filter-panel {
|
||||
background-color: #f8f9fa;
|
||||
border: 1px solid #dee2e6;
|
||||
border-radius: 0.375rem;
|
||||
padding: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
/* Таблица истории */
|
||||
.history-table {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.history-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: #343a40;
|
||||
color: white;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
padding: 6px 8px;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.history-table td {
|
||||
padding: 4px 6px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.history-table .name-col {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
background: #f8f9fa;
|
||||
min-width: 250px;
|
||||
white-space: normal;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.history-table thead .name-col {
|
||||
background: #343a40;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.history-wrapper {
|
||||
max-height: 65vh;
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="{% if full_width_page %}container-fluid{% else %}container{% endif %} px-3">
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<h2>Отметки сигналов</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Satellite Selector -->
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<div class="satellite-selector">
|
||||
<h5> Выберите спутник:</h5>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<select id="satellite-select" class="form-select" onchange="selectSatellite()">
|
||||
<option value="">-- Выберите спутник --</option>
|
||||
{% for satellite in satellites %}
|
||||
<option value="{{ satellite.id }}" {% if satellite.id == selected_satellite_id %}selected{% endif %}>
|
||||
{{ satellite.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if selected_satellite %}
|
||||
<!-- Tabs -->
|
||||
<ul class="nav nav-tabs" id="marksTabs" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link active" id="entry-tab" data-bs-toggle="tab" data-bs-target="#entry-pane"
|
||||
type="button" role="tab">
|
||||
<i class="bi bi-pencil-square"></i> Проставить отметки
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history-pane"
|
||||
type="button" role="tab">
|
||||
<i class="bi bi-clock-history"></i> История отметок
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content" id="marksTabsContent">
|
||||
<!-- Entry Tab -->
|
||||
<div class="tab-pane fade show active" id="entry-pane" role="tabpanel">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
|
||||
<div>
|
||||
<input type="text" id="entry-search" class="form-control form-control-sm"
|
||||
placeholder="Поиск по имени..." style="width: 200px;">
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
<button class="btn btn-outline-primary btn-sm" onclick="openCreateModal()">
|
||||
<i class="bi bi-plus-lg"></i> Создать теханализ
|
||||
</button>
|
||||
<button class="btn btn-success" id="save-marks-btn" onclick="saveMarks()" disabled>
|
||||
<i class="bi bi-check-lg"></i> Сохранить
|
||||
<span class="badge bg-light text-dark" id="marks-count">0</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body p-0">
|
||||
<div id="entry-table"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- History Tab -->
|
||||
<div class="tab-pane fade" id="history-pane" role="tabpanel">
|
||||
<div class="filter-panel">
|
||||
<div class="row align-items-end">
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Дата от:</label>
|
||||
<input type="date" id="history-date-from" class="form-control form-control-sm">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Дата до:</label>
|
||||
<input type="date" id="history-date-to" class="form-control form-control-sm">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Показывать:</label>
|
||||
<select id="history-page-size" class="form-select form-select-sm">
|
||||
<option value="0" selected>Все</option>
|
||||
<option value="50">50</option>
|
||||
<option value="100">100</option>
|
||||
<option value="200">200</option>
|
||||
<option value="500">500</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label">Поиск по имени:</label>
|
||||
<input type="text" id="history-search" class="form-control form-control-sm"
|
||||
placeholder="Введите имя..." oninput="filterHistoryTable()">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary btn-sm" onclick="loadHistory()">
|
||||
Показать
|
||||
</button>
|
||||
<button class="btn btn-secondary btn-sm" onclick="resetHistoryFilters()">
|
||||
Сбросить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-body p-0">
|
||||
<div class="history-wrapper" id="history-container">
|
||||
<div class="text-center p-4 text-muted">
|
||||
Нажмите "Показать" для загрузки данных
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info text-center">
|
||||
<h5> Пожалуйста, выберите спутник</h5>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Modal for creating TechAnalyze -->
|
||||
<div class="modal fade" id="createTechAnalyzeModal" tabindex="-1">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title"><i class="bi bi-plus-circle"></i> Создать теханализ</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="create-tech-analyze-form">
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Имя <span class="text-danger">*</span></label>
|
||||
<input type="text" class="form-control" id="ta-name" required>
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Частота, МГц</label>
|
||||
<input type="number" step="0.001" class="form-control" id="ta-frequency">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-4 mb-3">
|
||||
<label class="form-label">Полоса, МГц</label>
|
||||
<input type="number" step="0.001" class="form-control" id="ta-freq-range">
|
||||
</div>
|
||||
<div class="col-md-4 mb-3">
|
||||
<label class="form-label">Сим. скорость</label>
|
||||
<input type="number" class="form-control" id="ta-bod-velocity">
|
||||
</div>
|
||||
<div class="col-md-4 mb-3">
|
||||
<label class="form-label">Поляризация</label>
|
||||
<select class="form-select" id="ta-polarization">
|
||||
<option value="">-- Выберите --</option>
|
||||
{% for p in polarizations %}
|
||||
<option value="{{ p.name }}">{{ p.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Модуляция</label>
|
||||
<select class="form-select" id="ta-modulation">
|
||||
<option value="">-- Выберите --</option>
|
||||
{% for m in modulations %}
|
||||
<option value="{{ m.name }}">{{ m.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Стандарт</label>
|
||||
<select class="form-select" id="ta-standard">
|
||||
<option value="">-- Выберите --</option>
|
||||
{% for s in standards %}
|
||||
<option value="{{ s.name }}">{{ s.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input" type="checkbox" id="ta-add-mark" checked>
|
||||
<label class="form-check-label" for="ta-add-mark">
|
||||
Сразу добавить отметку "Есть сигнал"
|
||||
</label>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
||||
<button type="button" class="btn btn-primary" onclick="createTechAnalyze()">Создать</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
|
||||
<script>
|
||||
const SATELLITE_ID = {% if selected_satellite_id %}{{ selected_satellite_id }}{% else %}null{% endif %};
|
||||
const CSRF_TOKEN = '{{ csrf_token }}';
|
||||
|
||||
let entryTable = null;
|
||||
let pendingMarks = {};
|
||||
|
||||
function selectSatellite() {
|
||||
const select = document.getElementById('satellite-select');
|
||||
if (select.value) {
|
||||
window.location.search = `satellite_id=${select.value}`;
|
||||
} else {
|
||||
window.location.search = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Entry table
|
||||
function initEntryTable() {
|
||||
if (!SATELLITE_ID) return;
|
||||
|
||||
entryTable = new Tabulator("#entry-table", {
|
||||
ajaxURL: "{% url 'mainapp:signal_marks_entry_api' %}",
|
||||
ajaxParams: { satellite_id: SATELLITE_ID },
|
||||
pagination: true,
|
||||
paginationMode: "remote",
|
||||
paginationSize: 100,
|
||||
paginationSizeSelector: [50, 100, 200, 500, true],
|
||||
layout: "fitColumns",
|
||||
height: "65vh",
|
||||
placeholder: "Нет данных",
|
||||
columns: [
|
||||
{title: "ID", field: "id", width: 60},
|
||||
{title: "Имя", field: "name", width: 500},
|
||||
{title: "Частота", field: "frequency", width: 120, hozAlign: "right",
|
||||
formatter: c => c.getValue() ? c.getValue().toFixed(3) : '-'},
|
||||
{title: "Полоса", field: "freq_range", width: 120, hozAlign: "right",
|
||||
formatter: c => c.getValue() ? c.getValue().toFixed(3) : '-'},
|
||||
{title: "Сим.v", field: "bod_velocity", width: 120, hozAlign: "right",
|
||||
formatter: c => c.getValue() ? Math.round(c.getValue()) : '-'},
|
||||
{title: "Пол.", field: "polarization", width: 105, hozAlign: "center"},
|
||||
{title: "Мод.", field: "modulation", width: 95, hozAlign: "center"},
|
||||
{title: "Станд.", field: "standard", width: 125},
|
||||
{title: "Посл. отметка", field: "last_mark", width: 190,
|
||||
formatter: function(c) {
|
||||
const d = c.getValue();
|
||||
if (!d) return '<span class="text-muted">—</span>';
|
||||
const icon = d.mark ? '✓' : '✗';
|
||||
const cls = d.mark ? 'text-success' : 'text-danger';
|
||||
return `<span class="${cls}">${icon}</span> ${d.timestamp}`;
|
||||
}
|
||||
},
|
||||
{title: "Отметка", field: "id", width: 100, hozAlign: "center", headerSort: false,
|
||||
formatter: function(c) {
|
||||
const row = c.getRow().getData();
|
||||
const id = row.id;
|
||||
if (!row.can_add_mark) return '<span class="text-muted small">5 мин</span>';
|
||||
const yesS = pendingMarks[id] === true ? 'selected' : '';
|
||||
const noS = pendingMarks[id] === false ? 'selected' : '';
|
||||
return `<div class="mark-btn-group">
|
||||
<button type="button" class="mark-btn mark-btn-yes ${yesS}" data-id="${id}" data-val="true">✓</button>
|
||||
<button type="button" class="mark-btn mark-btn-no ${noS}" data-id="${id}" data-val="false">✗</button>
|
||||
</div>`;
|
||||
}
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Делегирование событий для кнопок отметок - без перерисовки таблицы
|
||||
document.getElementById('entry-table').addEventListener('click', function(e) {
|
||||
const btn = e.target.closest('.mark-btn');
|
||||
if (!btn) return;
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const id = parseInt(btn.dataset.id);
|
||||
const val = btn.dataset.val === 'true';
|
||||
|
||||
// Переключаем отметку
|
||||
if (pendingMarks[id] === val) {
|
||||
delete pendingMarks[id];
|
||||
} else {
|
||||
pendingMarks[id] = val;
|
||||
}
|
||||
|
||||
// Обновляем только кнопки в этой строке
|
||||
const container = btn.closest('.mark-btn-group');
|
||||
if (container) {
|
||||
const yesBtn = container.querySelector('.mark-btn-yes');
|
||||
const noBtn = container.querySelector('.mark-btn-no');
|
||||
|
||||
yesBtn.classList.toggle('selected', pendingMarks[id] === true);
|
||||
noBtn.classList.toggle('selected', pendingMarks[id] === false);
|
||||
}
|
||||
|
||||
updateMarksCount();
|
||||
});
|
||||
}
|
||||
|
||||
function updateMarksCount() {
|
||||
const count = Object.keys(pendingMarks).length;
|
||||
document.getElementById('marks-count').textContent = count;
|
||||
document.getElementById('save-marks-btn').disabled = count === 0;
|
||||
}
|
||||
|
||||
function saveMarks() {
|
||||
const marks = Object.entries(pendingMarks).map(([id, mark]) => ({
|
||||
tech_analyze_id: parseInt(id), mark: mark
|
||||
}));
|
||||
if (!marks.length) return;
|
||||
|
||||
const btn = document.getElementById('save-marks-btn');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Сохранение...';
|
||||
|
||||
fetch("{% url 'mainapp:save_signal_marks' %}", {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json', 'X-CSRFToken': CSRF_TOKEN},
|
||||
body: JSON.stringify({ marks })
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
// Восстанавливаем кнопку сначала
|
||||
btn.innerHTML = '<i class="bi bi-check-lg"></i> Сохранить <span class="badge bg-light text-dark" id="marks-count">0</span>';
|
||||
|
||||
if (data.success) {
|
||||
pendingMarks = {};
|
||||
updateMarksCount();
|
||||
// Перезагружаем данные таблицы
|
||||
if (entryTable) {
|
||||
entryTable.setData("{% url 'mainapp:signal_marks_entry_api' %}", { satellite_id: SATELLITE_ID });
|
||||
}
|
||||
alert(`Сохранено: ${data.created}` + (data.skipped ? `, пропущено: ${data.skipped}` : ''));
|
||||
} else {
|
||||
updateMarksCount();
|
||||
alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
|
||||
}
|
||||
})
|
||||
.catch(e => {
|
||||
console.error('Save error:', e);
|
||||
btn.innerHTML = '<i class="bi bi-check-lg"></i> Сохранить <span class="badge bg-light text-dark" id="marks-count">0</span>';
|
||||
updateMarksCount();
|
||||
alert('Ошибка сохранения: ' + e.message);
|
||||
});
|
||||
}
|
||||
|
||||
// History
|
||||
function loadHistory() {
|
||||
const dateFrom = document.getElementById('history-date-from').value;
|
||||
const dateTo = document.getElementById('history-date-to').value;
|
||||
const pageSize = document.getElementById('history-page-size').value;
|
||||
const container = document.getElementById('history-container');
|
||||
|
||||
container.innerHTML = '<div class="text-center p-4"><span class="spinner-border"></span></div>';
|
||||
|
||||
let url = `{% url 'mainapp:signal_marks_history_api' %}?satellite_id=${SATELLITE_ID}`;
|
||||
if (dateFrom) url += `&date_from=${dateFrom}`;
|
||||
if (dateTo) url += `&date_to=${dateTo}`;
|
||||
// size=0 означает "все записи"
|
||||
url += `&size=${pageSize || 0}`;
|
||||
|
||||
fetch(url)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.error) {
|
||||
container.innerHTML = `<div class="alert alert-danger m-3">${data.error}</div>`;
|
||||
return;
|
||||
}
|
||||
if (data.message) {
|
||||
container.innerHTML = `<div class="alert alert-info m-3">${data.message}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Build HTML table
|
||||
let html = '<table class="table table-bordered table-sm history-table mb-0">';
|
||||
html += '<thead><tr>';
|
||||
html += '<th class="name-col">Имя</th>';
|
||||
|
||||
for (const period of data.periods) {
|
||||
html += `<th class="mark-cell">${period}</th>`;
|
||||
}
|
||||
html += '</tr></thead><tbody>';
|
||||
|
||||
for (const row of data.data) {
|
||||
html += '<tr>';
|
||||
html += `<td class="name-col">${row.name}</td>`;
|
||||
|
||||
for (const mark of row.marks) {
|
||||
if (mark) {
|
||||
const cls = mark.mark ? 'mark-present' : 'mark-absent';
|
||||
const icon = mark.mark ? '✓' : '✗';
|
||||
html += `<td class="mark-cell ${cls}">
|
||||
<strong>${icon}</strong>
|
||||
<span class="mark-user">${mark.user}</span>
|
||||
<span class="mark-user">${mark.time}</span>
|
||||
</td>`;
|
||||
} else {
|
||||
html += '<td class="mark-cell mark-empty">—</td>';
|
||||
}
|
||||
}
|
||||
html += '</tr>';
|
||||
}
|
||||
|
||||
html += '</tbody></table>';
|
||||
container.innerHTML = html;
|
||||
})
|
||||
.catch(e => {
|
||||
container.innerHTML = '<div class="alert alert-danger m-3">Ошибка загрузки</div>';
|
||||
});
|
||||
}
|
||||
|
||||
function resetHistoryFilters() {
|
||||
document.getElementById('history-date-from').value = '';
|
||||
document.getElementById('history-date-to').value = '';
|
||||
document.getElementById('history-page-size').value = '0';
|
||||
document.getElementById('history-search').value = '';
|
||||
loadHistory();
|
||||
}
|
||||
|
||||
function filterHistoryTable() {
|
||||
const searchValue = document.getElementById('history-search').value.toLowerCase().trim();
|
||||
const table = document.querySelector('.history-table');
|
||||
if (!table) return;
|
||||
|
||||
const rows = table.querySelectorAll('tbody tr');
|
||||
rows.forEach(row => {
|
||||
const nameCell = row.querySelector('.name-col');
|
||||
if (nameCell) {
|
||||
const name = nameCell.textContent.toLowerCase();
|
||||
row.style.display = name.includes(searchValue) ? '' : 'none';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Init
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const searchInput = document.getElementById('entry-search');
|
||||
if (searchInput) {
|
||||
let timeout;
|
||||
searchInput.addEventListener('input', function() {
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => {
|
||||
if (entryTable) {
|
||||
entryTable.setData("{% url 'mainapp:signal_marks_entry_api' %}", {
|
||||
satellite_id: SATELLITE_ID, search: this.value
|
||||
});
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
}
|
||||
|
||||
initEntryTable();
|
||||
|
||||
document.getElementById('history-tab').addEventListener('shown.bs.tab', function() {
|
||||
loadHistory();
|
||||
});
|
||||
});
|
||||
|
||||
// Modal
|
||||
function openCreateModal() {
|
||||
document.getElementById('create-tech-analyze-form').reset();
|
||||
document.getElementById('ta-add-mark').checked = true;
|
||||
new bootstrap.Modal(document.getElementById('createTechAnalyzeModal')).show();
|
||||
}
|
||||
|
||||
function createTechAnalyze() {
|
||||
const name = document.getElementById('ta-name').value.trim();
|
||||
if (!name) { alert('Укажите имя'); return; }
|
||||
|
||||
fetch("{% url 'mainapp:create_tech_analyze_for_marks' %}", {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json', 'X-CSRFToken': CSRF_TOKEN},
|
||||
body: JSON.stringify({
|
||||
satellite_id: SATELLITE_ID,
|
||||
name: name,
|
||||
frequency: document.getElementById('ta-frequency').value,
|
||||
freq_range: document.getElementById('ta-freq-range').value,
|
||||
bod_velocity: document.getElementById('ta-bod-velocity').value,
|
||||
polarization: document.getElementById('ta-polarization').value,
|
||||
modulation: document.getElementById('ta-modulation').value,
|
||||
standard: document.getElementById('ta-standard').value,
|
||||
})
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(result => {
|
||||
if (result.success) {
|
||||
bootstrap.Modal.getInstance(document.getElementById('createTechAnalyzeModal')).hide();
|
||||
if (document.getElementById('ta-add-mark').checked) {
|
||||
pendingMarks[result.tech_analyze.id] = true;
|
||||
updateMarksCount();
|
||||
}
|
||||
entryTable.setData();
|
||||
} else {
|
||||
alert('Ошибка: ' + (result.error || 'Неизвестная ошибка'));
|
||||
}
|
||||
})
|
||||
.catch(e => alert('Ошибка создания'));
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -86,7 +86,7 @@
|
||||
attribution: 'Tiles © Esri'
|
||||
});
|
||||
|
||||
const street_local = L.tileLayer('http://127.0.0.1:8080/styles/basic-preview/{z}/{x}/{y}.png', {
|
||||
const street_local = L.tileLayer('/tiles/styles/basic-preview/512/{z}/{x}/{y}.png', {
|
||||
maxZoom: 19,
|
||||
attribution: 'Local Tiles'
|
||||
});
|
||||
|
||||
@@ -129,13 +129,15 @@
|
||||
<div class="container-fluid px-3">
|
||||
<div class="row mb-3">
|
||||
<div class="col-12 d-flex justify-content-between align-items-center">
|
||||
<h2>Редактировать объект #{{ object.id }}</h2>
|
||||
<h2>{% if object %}Редактировать объект #{{ object.id }}{% else %}Создать новый источник{% endif %}</h2>
|
||||
<div>
|
||||
{% if user.customuser.role == 'admin' or user.customuser.role == 'moderator' %}
|
||||
<button type="submit" form="source-form" class="btn btn-primary btn-action">Сохранить</button>
|
||||
{% if object %}
|
||||
<a href="{% url 'mainapp:source_delete' object.id %}{% if request.GET.urlencode %}?{{ request.GET.urlencode }}{% endif %}"
|
||||
class="btn btn-danger btn-action">Удалить</a>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
<a href="{% url 'mainapp:source_list' %}{% if request.GET.urlencode %}?{{ request.GET.urlencode }}{% endif %}"
|
||||
class="btn btn-secondary btn-action">Назад</a>
|
||||
</div>
|
||||
@@ -236,6 +238,17 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="mb-3">
|
||||
<label for="id_ownership" class="form-label">{{ form.note.label }}:</label>
|
||||
{{ form.note }}
|
||||
{% if form.note.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{{ form.note.errors }}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Блок с картой -->
|
||||
@@ -331,6 +344,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if object %}
|
||||
<!-- Привязанные объекты -->
|
||||
<div class="form-section">
|
||||
<div class="form-section-header">
|
||||
@@ -416,6 +430,7 @@
|
||||
<p class="text-muted">Нет привязанных объектов</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</form>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,169 +3,46 @@
|
||||
{% block title %}Карта объектов{% endblock title %}
|
||||
|
||||
{% block extra_css %}
|
||||
<!-- MapLibre GL CSS -->
|
||||
<link href="{% static 'maplibre/maplibre-gl.css' %}" rel="stylesheet">
|
||||
<!-- Leaflet CSS -->
|
||||
<link href="{% static 'leaflet/leaflet.css' %}" rel="stylesheet">
|
||||
<link href="{% static 'leaflet-measure/leaflet-measure.css' %}" rel="stylesheet">
|
||||
<link href="{% static 'leaflet-tree/L.Control.Layers.Tree.css' %}" rel="stylesheet">
|
||||
<style>
|
||||
body {
|
||||
overflow: hidden;
|
||||
}
|
||||
#map {
|
||||
position: fixed;
|
||||
top: 56px;
|
||||
top: 56px; /* Высота navbar */
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 0;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* Легенда */
|
||||
.maplibregl-ctrl-legend {
|
||||
.legend {
|
||||
background: white;
|
||||
padding: 10px;
|
||||
padding: 8px;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 0 0 2px rgba(0,0,0,.1);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
box-shadow: 0 0 10px rgba(0,0,0,0.2);
|
||||
font-size: 11px;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.maplibregl-ctrl-legend h6 {
|
||||
.legend h6 {
|
||||
font-size: 12px;
|
||||
margin: 0 0 8px 0;
|
||||
font-weight: bold;
|
||||
margin: 0 0 6px 0;
|
||||
}
|
||||
|
||||
.legend-item {
|
||||
margin: 4px 0;
|
||||
margin: 3px 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.legend-marker {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
margin-right: 8px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid white;
|
||||
box-shadow: 0 0 3px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
.legend-section {
|
||||
margin-bottom: 8px;
|
||||
padding-bottom: 6px;
|
||||
border-bottom: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.legend-section:last-child {
|
||||
border-bottom: none;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* Слои контрол */
|
||||
.maplibregl-ctrl-layers {
|
||||
background: white;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 0 0 2px rgba(0,0,0,.1);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
max-width: 250px;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.maplibregl-ctrl-layers h6 {
|
||||
margin: 0 0 10px 0;
|
||||
font-size: 13px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.layer-item {
|
||||
margin: 5px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.layer-item label {
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.layer-item input[type="checkbox"] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Кастомные кнопки контролов */
|
||||
.maplibregl-ctrl-projection .maplibregl-ctrl-icon,
|
||||
.maplibregl-ctrl-3d .maplibregl-ctrl-icon,
|
||||
.maplibregl-ctrl-style .maplibregl-ctrl-icon {
|
||||
background-size: 20px 20px;
|
||||
background-position: center;
|
||||
width: 18px;
|
||||
height: 30px;
|
||||
margin-right: 6px;
|
||||
background-size: contain;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
.maplibregl-ctrl-projection .maplibregl-ctrl-icon {
|
||||
background-image: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><circle cx="10" cy="10" r="6" fill="none" stroke="%23333" stroke-width="1.5"/><ellipse cx="10" cy="10" rx="3" ry="6" fill="none" stroke="%23333" stroke-width="1.5"/><line x1="4" y1="10" x2="16" y2="10" stroke="%23333" stroke-width="1.5"/></svg>');
|
||||
}
|
||||
|
||||
.maplibregl-ctrl-3d .maplibregl-ctrl-icon {
|
||||
background-image: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M 5 13 L 5 8 L 10 5 L 15 8 L 15 13 L 10 16 Z M 5 8 L 10 10.5 M 10 10.5 L 15 8 M 10 10.5 L 10 16" fill="none" stroke="%23333" stroke-width="1.5" stroke-linejoin="round"/></svg>');
|
||||
}
|
||||
|
||||
.maplibregl-ctrl-style .maplibregl-ctrl-icon {
|
||||
background-image: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><rect x="3" y="3" width="6" height="6" fill="none" stroke="%23333" stroke-width="1.5"/><rect x="11" y="3" width="6" height="6" fill="none" stroke="%23333" stroke-width="1.5"/><rect x="3" y="11" width="6" height="6" fill="none" stroke="%23333" stroke-width="1.5"/><rect x="11" y="11" width="6" height="6" fill="none" stroke="%23333" stroke-width="1.5"/></svg>');
|
||||
}
|
||||
|
||||
/* Popup стили */
|
||||
.maplibregl-popup-content {
|
||||
padding: 10px 15px;
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
.popup-title {
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.popup-info {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
/* Стили меню */
|
||||
.style-menu {
|
||||
background: white;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 0 0 2px rgba(0,0,0,.1);
|
||||
padding: 5px;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.style-menu button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 6px 10px;
|
||||
border: none;
|
||||
background: none;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.style-menu button:hover {
|
||||
background-color: #f0f0f0;
|
||||
}
|
||||
|
||||
.style-menu button.active {
|
||||
background-color: #e3f2fd;
|
||||
color: #1976d2;
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
@@ -174,508 +51,181 @@
|
||||
{% endblock content %}
|
||||
|
||||
{% block extra_js %}
|
||||
<!-- MapLibre GL JavaScript -->
|
||||
<script src="{% static 'maplibre/maplibre-gl.js' %}"></script>
|
||||
<!-- Leaflet JavaScript -->
|
||||
<script src="{% static 'leaflet/leaflet.js' %}"></script>
|
||||
<script src="{% static 'leaflet-measure/leaflet-measure.ru.js' %}"></script>
|
||||
<script src="{% static 'leaflet-tree/L.Control.Layers.Tree.js' %}"></script>
|
||||
|
||||
<script>
|
||||
// Цвета для маркеров
|
||||
const markerColors = {
|
||||
'blue': '#3388ff',
|
||||
'orange': '#ff8c00',
|
||||
'green': '#28a745',
|
||||
'violet': '#9c27b0'
|
||||
};
|
||||
|
||||
// Данные групп из Django
|
||||
const groups = [
|
||||
{% for group in groups %}
|
||||
{
|
||||
name: '{{ group.name|escapejs }}',
|
||||
color: '{{ group.color }}',
|
||||
points: [
|
||||
{% for point_data in group.points %}
|
||||
{
|
||||
id: '{{ point_data.source_id|escapejs }}',
|
||||
coordinates: [{{ point_data.point.0|safe }}, {{ point_data.point.1|safe }}]
|
||||
}{% if not forloop.last %},{% endif %}
|
||||
{% endfor %}
|
||||
]
|
||||
}{% if not forloop.last %},{% endif %}
|
||||
{% endfor %}
|
||||
];
|
||||
|
||||
// Полигон фильтра
|
||||
const polygonCoords = {% if polygon_coords %}{{ polygon_coords|safe }}{% else %}null{% endif %};
|
||||
|
||||
// Стили карт
|
||||
const mapStyles = {
|
||||
streets: {
|
||||
version: 8,
|
||||
sources: {
|
||||
'osm': {
|
||||
type: 'raster',
|
||||
tiles: ['https://a.tile.openstreetmap.org/{z}/{x}/{y}.png'],
|
||||
tileSize: 256,
|
||||
attribution: '© OpenStreetMap'
|
||||
}
|
||||
},
|
||||
layers: [{
|
||||
id: 'osm',
|
||||
type: 'raster',
|
||||
source: 'osm'
|
||||
}]
|
||||
},
|
||||
satellite: {
|
||||
version: 8,
|
||||
sources: {
|
||||
'satellite': {
|
||||
type: 'raster',
|
||||
tiles: ['https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'],
|
||||
tileSize: 256,
|
||||
attribution: '© Esri'
|
||||
}
|
||||
},
|
||||
layers: [{
|
||||
id: 'satellite',
|
||||
type: 'raster',
|
||||
source: 'satellite'
|
||||
}]
|
||||
},
|
||||
local: {
|
||||
version: 8,
|
||||
sources: {
|
||||
'local': {
|
||||
type: 'raster',
|
||||
tiles: ['http://127.0.0.1:8080/styles/basic-preview/{z}/{x}/{y}.png'],
|
||||
tileSize: 256,
|
||||
attribution: 'Local'
|
||||
}
|
||||
},
|
||||
layers: [{
|
||||
id: 'local',
|
||||
type: 'raster',
|
||||
source: 'local'
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
// Инициализация карты
|
||||
const map = new maplibregl.Map({
|
||||
container: 'map',
|
||||
style: mapStyles.streets,
|
||||
center: [37.62, 55.75],
|
||||
zoom: 10,
|
||||
maxZoom: 18,
|
||||
minZoom: 0
|
||||
let map = L.map('map').setView([55.75, 37.62], 10);
|
||||
L.control.scale({
|
||||
imperial: false,
|
||||
metric: true
|
||||
}).addTo(map);
|
||||
map.attributionControl.setPrefix(false);
|
||||
|
||||
const street = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
maxZoom: 19,
|
||||
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
|
||||
});
|
||||
street.addTo(map);
|
||||
|
||||
const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
|
||||
attribution: 'Tiles © Esri'
|
||||
});
|
||||
|
||||
let currentStyle = 'streets';
|
||||
let is3DEnabled = false;
|
||||
let isGlobeProjection = false;
|
||||
const allMarkers = [];
|
||||
|
||||
// Добавляем стандартные контролы
|
||||
map.addControl(new maplibregl.NavigationControl(), 'top-right');
|
||||
map.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), 'bottom-right');
|
||||
map.addControl(new maplibregl.FullscreenControl(), 'top-right');
|
||||
|
||||
// Кастомный контрол для переключения проекции
|
||||
class ProjectionControl {
|
||||
onAdd(map) {
|
||||
this._map = map;
|
||||
this._container = document.createElement('div');
|
||||
this._container.className = 'maplibregl-ctrl maplibregl-ctrl-group maplibregl-ctrl-projection';
|
||||
this._container.innerHTML = '<button type="button" title="Переключить проекцию"><span class="maplibregl-ctrl-icon"></span></button>';
|
||||
this._container.onclick = () => {
|
||||
if (isGlobeProjection) {
|
||||
map.setProjection({ type: 'mercator' });
|
||||
isGlobeProjection = false;
|
||||
} else {
|
||||
map.setProjection({ type: 'globe' });
|
||||
isGlobeProjection = true;
|
||||
}
|
||||
};
|
||||
return this._container;
|
||||
}
|
||||
onRemove() {
|
||||
this._container.parentNode.removeChild(this._container);
|
||||
this._map = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Кастомный контрол для переключения стилей
|
||||
class StyleControl {
|
||||
onAdd(map) {
|
||||
this._map = map;
|
||||
this._container = document.createElement('div');
|
||||
this._container.className = 'maplibregl-ctrl maplibregl-ctrl-group maplibregl-ctrl-style';
|
||||
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.title = 'Стиль карты';
|
||||
button.innerHTML = '<span class="maplibregl-ctrl-icon"></span>';
|
||||
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'style-menu';
|
||||
menu.style.display = 'none';
|
||||
menu.style.position = 'absolute';
|
||||
menu.style.top = '100%';
|
||||
menu.style.right = '0';
|
||||
menu.style.marginTop = '5px';
|
||||
|
||||
const styles = [
|
||||
{ id: 'streets', name: 'Улицы' },
|
||||
{ id: 'satellite', name: 'Спутник' },
|
||||
{ id: 'local', name: 'Локально' }
|
||||
];
|
||||
|
||||
styles.forEach(style => {
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = style.name;
|
||||
btn.className = style.id === currentStyle ? 'active' : '';
|
||||
btn.onclick = () => {
|
||||
this.switchStyle(style.id);
|
||||
menu.querySelectorAll('button').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
menu.style.display = 'none';
|
||||
};
|
||||
menu.appendChild(btn);
|
||||
const street_local = L.tileLayer('/tiles/styles/basic-preview/512/{z}/{x}/{y}.png', {
|
||||
maxZoom: 19,
|
||||
attribution: 'Local Tiles'
|
||||
});
|
||||
|
||||
button.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
|
||||
const baseLayers = {
|
||||
"Улицы": street,
|
||||
"Спутник": satellite,
|
||||
"Локально": street_local
|
||||
};
|
||||
|
||||
document.addEventListener('click', () => {
|
||||
menu.style.display = 'none';
|
||||
});
|
||||
L.control.layers(baseLayers).addTo(map);
|
||||
map.setMaxZoom(18);
|
||||
map.setMinZoom(0);
|
||||
L.control.measure({ primaryLengthUnit: 'kilometers' }).addTo(map);
|
||||
|
||||
this._container.appendChild(button);
|
||||
this._container.appendChild(menu);
|
||||
this._container.style.position = 'relative';
|
||||
|
||||
return this._container;
|
||||
}
|
||||
|
||||
switchStyle(styleName) {
|
||||
const center = this._map.getCenter();
|
||||
const zoom = this._map.getZoom();
|
||||
const bearing = this._map.getBearing();
|
||||
const pitch = this._map.getPitch();
|
||||
|
||||
this._map.setStyle(mapStyles[styleName]);
|
||||
currentStyle = styleName;
|
||||
|
||||
this._map.once('styledata', () => {
|
||||
this._map.setCenter(center);
|
||||
this._map.setZoom(zoom);
|
||||
this._map.setBearing(bearing);
|
||||
this._map.setPitch(pitch);
|
||||
|
||||
addMarkersToMap();
|
||||
addFilterPolygon();
|
||||
});
|
||||
}
|
||||
|
||||
onRemove() {
|
||||
this._container.parentNode.removeChild(this._container);
|
||||
this._map = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Кастомный контрол для слоев
|
||||
class LayersControl {
|
||||
onAdd(map) {
|
||||
this._map = map;
|
||||
this._container = document.createElement('div');
|
||||
this._container.className = 'maplibregl-ctrl maplibregl-ctrl-layers';
|
||||
|
||||
const title = document.createElement('h6');
|
||||
title.textContent = 'Слои точек';
|
||||
this._container.appendChild(title);
|
||||
|
||||
groups.forEach((group, groupIndex) => {
|
||||
const layerId = `points-layer-${groupIndex}`;
|
||||
|
||||
const layerItem = document.createElement('div');
|
||||
layerItem.className = 'layer-item';
|
||||
|
||||
const label = document.createElement('label');
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.checked = true;
|
||||
checkbox.addEventListener('change', (e) => {
|
||||
const visibility = e.target.checked ? 'visible' : 'none';
|
||||
if (map.getLayer(layerId)) {
|
||||
map.setLayoutProperty(layerId, 'visibility', visibility);
|
||||
}
|
||||
// Также скрываем/показываем внутренний круг
|
||||
const innerLayerId = `${layerId}-inner`;
|
||||
if (map.getLayer(innerLayerId)) {
|
||||
map.setLayoutProperty(innerLayerId, 'visibility', visibility);
|
||||
}
|
||||
});
|
||||
|
||||
const colorSpan = document.createElement('span');
|
||||
colorSpan.className = 'legend-marker';
|
||||
colorSpan.style.backgroundColor = markerColors[group.color];
|
||||
|
||||
const nameSpan = document.createElement('span');
|
||||
nameSpan.textContent = `${group.name} (${group.points.length})`;
|
||||
|
||||
label.appendChild(checkbox);
|
||||
label.appendChild(colorSpan);
|
||||
label.appendChild(nameSpan);
|
||||
layerItem.appendChild(label);
|
||||
this._container.appendChild(layerItem);
|
||||
});
|
||||
|
||||
return this._container;
|
||||
}
|
||||
onRemove() {
|
||||
this._container.parentNode.removeChild(this._container);
|
||||
this._map = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Кастомный контрол для легенды
|
||||
class LegendControl {
|
||||
onAdd(map) {
|
||||
this._map = map;
|
||||
this._container = document.createElement('div');
|
||||
this._container.className = 'maplibregl-ctrl maplibregl-ctrl-legend';
|
||||
|
||||
const title = document.createElement('h6');
|
||||
title.textContent = 'Легенда';
|
||||
this._container.appendChild(title);
|
||||
|
||||
groups.forEach(group => {
|
||||
const section = document.createElement('div');
|
||||
section.className = 'legend-section';
|
||||
|
||||
const item = document.createElement('div');
|
||||
item.className = 'legend-item';
|
||||
|
||||
const marker = document.createElement('div');
|
||||
marker.className = 'legend-marker';
|
||||
marker.style.backgroundColor = markerColors[group.color];
|
||||
|
||||
const text = document.createElement('span');
|
||||
text.textContent = `${group.name} (${group.points.length})`;
|
||||
|
||||
item.appendChild(marker);
|
||||
item.appendChild(text);
|
||||
section.appendChild(item);
|
||||
this._container.appendChild(section);
|
||||
});
|
||||
|
||||
if (polygonCoords && polygonCoords.length > 0) {
|
||||
const section = document.createElement('div');
|
||||
section.className = 'legend-section';
|
||||
|
||||
const item = document.createElement('div');
|
||||
item.className = 'legend-item';
|
||||
|
||||
const marker = document.createElement('div');
|
||||
marker.style.width = '18px';
|
||||
marker.style.height = '18px';
|
||||
marker.style.marginRight = '8px';
|
||||
marker.style.backgroundColor = 'rgba(51, 136, 255, 0.2)';
|
||||
marker.style.border = '2px solid #3388ff';
|
||||
marker.style.borderRadius = '2px';
|
||||
|
||||
const text = document.createElement('span');
|
||||
text.textContent = 'Область фильтра';
|
||||
|
||||
item.appendChild(marker);
|
||||
item.appendChild(text);
|
||||
section.appendChild(item);
|
||||
this._container.appendChild(section);
|
||||
}
|
||||
|
||||
return this._container;
|
||||
}
|
||||
onRemove() {
|
||||
this._container.parentNode.removeChild(this._container);
|
||||
this._map = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Добавляем кастомные контролы
|
||||
map.addControl(new ProjectionControl(), 'top-right');
|
||||
map.addControl(new StyleControl(), 'top-right');
|
||||
map.addControl(new LayersControl(), 'top-left');
|
||||
map.addControl(new LegendControl(), 'bottom-left');
|
||||
|
||||
// Добавление маркеров на карту
|
||||
function addMarkersToMap() {
|
||||
groups.forEach((group, groupIndex) => {
|
||||
const sourceId = `points-${groupIndex}`;
|
||||
const layerId = `points-layer-${groupIndex}`;
|
||||
|
||||
// Создаем GeoJSON для группы
|
||||
const geojson = {
|
||||
type: 'FeatureCollection',
|
||||
features: group.points.map(point => ({
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'Point',
|
||||
coordinates: point.coordinates
|
||||
},
|
||||
properties: {
|
||||
id: point.id,
|
||||
groupName: group.name,
|
||||
color: markerColors[group.color]
|
||||
}
|
||||
}))
|
||||
// Цвета для маркеров
|
||||
var markerColors = {
|
||||
'blue': 'blue',
|
||||
'orange': 'orange',
|
||||
'green': 'green',
|
||||
'violet': 'violet'
|
||||
};
|
||||
|
||||
// Добавляем источник данных
|
||||
if (!map.getSource(sourceId)) {
|
||||
map.addSource(sourceId, {
|
||||
type: 'geojson',
|
||||
data: geojson
|
||||
var getColorIcon = function(color) {
|
||||
return L.icon({
|
||||
iconUrl: '{% static "leaflet-markers/img/marker-icon-" %}' + color + '.png',
|
||||
shadowUrl: '{% static "leaflet-markers/img/marker-shadow.png" %}',
|
||||
iconSize: [25, 41],
|
||||
iconAnchor: [12, 41],
|
||||
popupAnchor: [1, -34],
|
||||
shadowSize: [41, 41]
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Добавляем слой с кругами (основной маркер)
|
||||
if (!map.getLayer(layerId)) {
|
||||
map.addLayer({
|
||||
id: layerId,
|
||||
type: 'circle',
|
||||
source: sourceId,
|
||||
paint: {
|
||||
'circle-radius': 10,
|
||||
'circle-color': ['get', 'color'],
|
||||
'circle-stroke-width': 3,
|
||||
'circle-stroke-color': '#ffffff',
|
||||
'circle-opacity': 1
|
||||
}
|
||||
var overlays = [];
|
||||
|
||||
// Создаём слои для каждого типа координат
|
||||
{% for group in groups %}
|
||||
var groupName = '{{ group.name|escapejs }}';
|
||||
var colorName = '{{ group.color }}';
|
||||
var groupIcon = getColorIcon(colorName);
|
||||
var groupLayer = L.layerGroup();
|
||||
|
||||
var subgroup = [];
|
||||
{% for point_data in group.points %}
|
||||
var pointName = "{{ point_data.source_id|escapejs }}";
|
||||
var marker = L.marker([{{ point_data.point.1|safe }}, {{ point_data.point.0|safe }}], {
|
||||
icon: groupIcon
|
||||
}).bindPopup(pointName);
|
||||
groupLayer.addLayer(marker);
|
||||
|
||||
subgroup.push({
|
||||
label: "{{ forloop.counter }} - {{ point_data.source_id|escapejs }}",
|
||||
layer: marker
|
||||
});
|
||||
{% endfor %}
|
||||
|
||||
// Добавляем внутренний круг
|
||||
map.addLayer({
|
||||
id: `${layerId}-inner`,
|
||||
type: 'circle',
|
||||
source: sourceId,
|
||||
paint: {
|
||||
'circle-radius': 4,
|
||||
'circle-color': '#ffffff',
|
||||
'circle-opacity': 1
|
||||
}
|
||||
overlays.push({
|
||||
label: groupName,
|
||||
selectAllCheckbox: true,
|
||||
children: subgroup,
|
||||
layer: groupLayer
|
||||
});
|
||||
{% endfor %}
|
||||
|
||||
// Добавляем popup при клике
|
||||
map.on('click', layerId, (e) => {
|
||||
const coordinates = e.features[0].geometry.coordinates.slice();
|
||||
const { id, groupName } = e.features[0].properties;
|
||||
// Корневая группа
|
||||
const rootGroup = {
|
||||
label: "Все точки",
|
||||
selectAllCheckbox: true,
|
||||
children: overlays,
|
||||
layer: L.layerGroup()
|
||||
};
|
||||
|
||||
new maplibregl.Popup()
|
||||
.setLngLat(coordinates)
|
||||
.setHTML(`<div class="popup-title">${id}</div><div class="popup-info">Группа: ${groupName}</div>`)
|
||||
.addTo(map);
|
||||
// Создаём tree control
|
||||
const layerControl = L.control.layers.tree(baseLayers, [rootGroup], {
|
||||
collapsed: false,
|
||||
autoZIndex: true
|
||||
});
|
||||
layerControl.addTo(map);
|
||||
|
||||
// Меняем курсор при наведении
|
||||
map.on('mouseenter', layerId, () => {
|
||||
map.getCanvas().style.cursor = 'pointer';
|
||||
});
|
||||
// Подгоняем карту под все маркеры
|
||||
{% if groups %}
|
||||
var groupBounds = L.featureGroup([]);
|
||||
{% for group in groups %}
|
||||
{% for point_data in group.points %}
|
||||
groupBounds.addLayer(L.marker([{{ point_data.point.1|safe }}, {{ point_data.point.0|safe }}]));
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
map.fitBounds(groupBounds.getBounds().pad(0.1));
|
||||
{% endif %}
|
||||
|
||||
map.on('mouseleave', layerId, () => {
|
||||
map.getCanvas().style.cursor = '';
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
// Добавляем легенду в левый нижний угол
|
||||
var legend = L.control({ position: 'bottomleft' });
|
||||
legend.onAdd = function(map) {
|
||||
var div = L.DomUtil.create('div', 'legend');
|
||||
div.innerHTML = '<h6><strong>Легенда</strong></h6>';
|
||||
|
||||
// Добавление полигона фильтра
|
||||
function addFilterPolygon() {
|
||||
if (!polygonCoords || polygonCoords.length === 0) return;
|
||||
{% for group in groups %}
|
||||
div.innerHTML += `
|
||||
<div class="legend-item">
|
||||
<div class="legend-marker" style="background-image: url('{% static "leaflet-markers/img/marker-icon-" %}{{ group.color }}.png');"></div>
|
||||
<span>{{ group.name|escapejs }}</span>
|
||||
</div>
|
||||
`;
|
||||
{% endfor %}
|
||||
|
||||
{% if polygon_coords %}
|
||||
div.innerHTML += `
|
||||
<div class="legend-item" style="margin-top: 8px; padding-top: 8px; border-top: 1px solid #ddd;">
|
||||
<div style="width: 18px; height: 18px; margin-right: 6px; background-color: rgba(51, 136, 255, 0.2); border: 2px solid #3388ff;"></div>
|
||||
<span>Область фильтра</span>
|
||||
</div>
|
||||
`;
|
||||
{% endif %}
|
||||
|
||||
return div;
|
||||
};
|
||||
legend.addTo(map);
|
||||
|
||||
// Добавляем полигон фильтра на карту, если он есть
|
||||
{% if polygon_coords %}
|
||||
try {
|
||||
const polygonGeoJSON = {
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'Polygon',
|
||||
coordinates: [polygonCoords]
|
||||
}
|
||||
};
|
||||
const polygonCoords = {{ polygon_coords|safe }};
|
||||
if (polygonCoords && polygonCoords.length > 0) {
|
||||
// Преобразуем координаты из [lng, lat] в [lat, lng] для Leaflet
|
||||
const latLngs = polygonCoords.map(coord => [coord[1], coord[0]]);
|
||||
|
||||
if (!map.getSource('filter-polygon')) {
|
||||
map.addSource('filter-polygon', {
|
||||
type: 'geojson',
|
||||
data: polygonGeoJSON
|
||||
// Создаем полигон
|
||||
const filterPolygon = L.polygon(latLngs, {
|
||||
color: '#3388ff',
|
||||
fillColor: '#3388ff',
|
||||
fillOpacity: 0.2,
|
||||
weight: 2,
|
||||
dashArray: '5, 5'
|
||||
});
|
||||
}
|
||||
|
||||
if (!map.getLayer('filter-polygon-fill')) {
|
||||
map.addLayer({
|
||||
id: 'filter-polygon-fill',
|
||||
type: 'fill',
|
||||
source: 'filter-polygon',
|
||||
paint: {
|
||||
'fill-color': '#3388ff',
|
||||
'fill-opacity': 0.2
|
||||
}
|
||||
});
|
||||
}
|
||||
// Добавляем полигон на карту
|
||||
filterPolygon.addTo(map);
|
||||
|
||||
if (!map.getLayer('filter-polygon-outline')) {
|
||||
map.addLayer({
|
||||
id: 'filter-polygon-outline',
|
||||
type: 'line',
|
||||
source: 'filter-polygon',
|
||||
paint: {
|
||||
'line-color': '#3388ff',
|
||||
'line-width': 2,
|
||||
'line-dasharray': [2, 2]
|
||||
}
|
||||
});
|
||||
}
|
||||
// Добавляем popup с информацией
|
||||
filterPolygon.bindPopup('<strong>Область фильтра</strong><br>Отображаются только объекты с точками в этой области');
|
||||
|
||||
map.on('click', 'filter-polygon-fill', (e) => {
|
||||
new maplibregl.Popup()
|
||||
.setLngLat(e.lngLat)
|
||||
.setHTML('<div class="popup-title">Область фильтра</div><div class="popup-info">Отображаются только источники с точками в этой области</div>')
|
||||
.addTo(map);
|
||||
});
|
||||
// Если нет других точек, центрируем карту на полигоне
|
||||
{% if not groups %}
|
||||
map.fitBounds(filterPolygon.getBounds());
|
||||
{% endif %}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Ошибка при отображении полигона фильтра:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Подгонка карты под все маркеры
|
||||
function fitMapToBounds() {
|
||||
const allCoordinates = [];
|
||||
|
||||
groups.forEach(group => {
|
||||
group.points.forEach(point => {
|
||||
allCoordinates.push(point.coordinates);
|
||||
});
|
||||
});
|
||||
|
||||
if (polygonCoords && polygonCoords.length > 0) {
|
||||
polygonCoords.forEach(coord => {
|
||||
allCoordinates.push(coord);
|
||||
});
|
||||
}
|
||||
|
||||
if (allCoordinates.length > 0) {
|
||||
const bounds = allCoordinates.reduce((bounds, coord) => {
|
||||
return bounds.extend(coord);
|
||||
}, new maplibregl.LngLatBounds(allCoordinates[0], allCoordinates[0]));
|
||||
|
||||
map.fitBounds(bounds, { padding: 50 });
|
||||
}
|
||||
}
|
||||
|
||||
// Инициализация после загрузки карты
|
||||
map.on('load', () => {
|
||||
addMarkersToMap();
|
||||
addFilterPolygon();
|
||||
fitMapToBounds();
|
||||
});
|
||||
{% endif %}
|
||||
</script>
|
||||
{% endblock extra_js %}
|
||||
159
dbapp/mainapp/templates/mainapp/source_request_import.html
Normal file
159
dbapp/mainapp/templates/mainapp/source_request_import.html
Normal file
@@ -0,0 +1,159 @@
|
||||
{% 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>
|
||||
<li><strong>Координаты объекта</strong> → Координаты объекта (формат: "26.223, 33.969" или пусто)</li>
|
||||
</ul>
|
||||
<hr>
|
||||
<h6>Проверка дубликатов:</h6>
|
||||
<p class="mb-0 small">Строки пропускаются, если уже существует заявка с такой же комбинацией: спутник + downlink + uplink + перенос + координаты ГСО + дата проведения</p>
|
||||
<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.skipped_rows && data.skipped_rows.length > 0) {
|
||||
html += `
|
||||
<div class="alert alert-info">
|
||||
<strong>Пропущенные строки (дубликаты):</strong>
|
||||
<ul class="mb-0 small">
|
||||
${data.skipped_rows.map(e => `<li>${e}</li>`).join('')}
|
||||
</ul>
|
||||
${data.skipped > 20 ? '<p class="mb-0 mt-2"><em>Показаны первые 20 пропущенных</em></p>' : ''}
|
||||
</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 %}
|
||||
@@ -7,6 +7,7 @@
|
||||
<link href="{% static 'leaflet/leaflet.css' %}" rel="stylesheet">
|
||||
<link href="{% static 'leaflet-measure/leaflet-measure.css' %}" rel="stylesheet">
|
||||
<link href="{% static 'leaflet-tree/L.Control.Layers.Tree.css' %}" rel="stylesheet">
|
||||
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet-playback@1.0.2/dist/LeafletPlayback.css" /> -->
|
||||
<style>
|
||||
body {
|
||||
overflow: hidden;
|
||||
@@ -57,11 +58,112 @@
|
||||
font-size: 11px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.playback-control {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
background: white;
|
||||
padding: 15px 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 15px;
|
||||
}
|
||||
.playback-control button {
|
||||
padding: 6px 12px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background: #007bff;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
min-width: auto;
|
||||
}
|
||||
.playback-control button:hover {
|
||||
background: #0056b3;
|
||||
}
|
||||
.playback-control button:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.playback-control .time-display {
|
||||
font-size: 13px;
|
||||
font-weight: bold;
|
||||
min-width: 160px;
|
||||
text-align: center;
|
||||
}
|
||||
.playback-control input[type="range"] {
|
||||
width: 250px;
|
||||
}
|
||||
.playback-control .speed-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.playback-control .speed-control label {
|
||||
font-size: 11px;
|
||||
margin: 0;
|
||||
}
|
||||
.playback-control .speed-control select {
|
||||
padding: 3px 6px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #ccc;
|
||||
font-size: 12px;
|
||||
}
|
||||
.playback-control .visibility-controls {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
border-left: 1px solid #ddd;
|
||||
padding-left: 15px;
|
||||
margin-left: 10px;
|
||||
}
|
||||
.playback-control .visibility-controls label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 11px;
|
||||
margin: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
.playback-control .visibility-controls input[type="checkbox"] {
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div id="map"></div>
|
||||
<div class="playback-control" id="playbackControl" style="display: none;">
|
||||
<button id="playBtn">▶</button>
|
||||
<button id="pauseBtn" disabled>⏸</button>
|
||||
<button id="resetBtn">⏮</button>
|
||||
<input type="range" id="timeSlider" min="0" max="100" value="0" step="1">
|
||||
<div class="time-display" id="timeDisplay">--</div>
|
||||
<div class="speed-control">
|
||||
<label for="speedSelect">Скорость:</label>
|
||||
<select id="speedSelect">
|
||||
<option value="0.5">0.5x</option>
|
||||
<option value="1" selected>1x</option>
|
||||
<option value="2">2x</option>
|
||||
<option value="5">5x</option>
|
||||
<option value="10">10x</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="visibility-controls">
|
||||
<label>
|
||||
<input type="checkbox" id="showPointsCheckbox" checked>
|
||||
Точки
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" id="showTrackCheckbox" checked>
|
||||
Трек
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock content %}
|
||||
|
||||
{% block extra_js %}
|
||||
@@ -69,6 +171,8 @@
|
||||
<script src="{% static 'leaflet/leaflet.js' %}"></script>
|
||||
<script src="{% static 'leaflet-measure/leaflet-measure.ru.js' %}"></script>
|
||||
<script src="{% static 'leaflet-tree/L.Control.Layers.Tree.js' %}"></script>
|
||||
<script src="{% static 'leaflet-polylineDecorator/leaflet.polylineDecorator.js' %}"></script>
|
||||
<script src="{% static 'leaflet-playback/leaflet-playback.js' %}"></script>
|
||||
|
||||
<script>
|
||||
// Инициализация карты
|
||||
@@ -89,7 +193,7 @@
|
||||
attribution: 'Tiles © Esri'
|
||||
});
|
||||
|
||||
const street_local = L.tileLayer('http://127.0.0.1:8080/styles/basic-preview/{z}/{x}/{y}.png', {
|
||||
const street_local = L.tileLayer('/tiles/styles/basic-preview/512/{z}/{x}/{y}.png', {
|
||||
maxZoom: 19,
|
||||
attribution: 'Local Tiles'
|
||||
});
|
||||
@@ -119,6 +223,28 @@
|
||||
|
||||
var sourceOverlays = [];
|
||||
var glPointLayers = [];
|
||||
var glPointCoordinates = [];
|
||||
var glPointsData = [];
|
||||
var trackLayer = L.layerGroup(); // Layer group for track and related elements
|
||||
var glPointsGroupLayer = L.layerGroup(); // Layer group specifically for GL points
|
||||
|
||||
// Сначала собираем все данные о точках ГЛ с временными метками
|
||||
{% for group in groups %}
|
||||
{% for point_data in group.points %}
|
||||
{% if not point_data.source_id %}
|
||||
glPointsData.push({
|
||||
name: "{{ point_data.name|escapejs }}",
|
||||
frequency: "{{ point_data.frequency|escapejs }}",
|
||||
coords: [{{ point_data.point.1|safe }}, {{ point_data.point.0|safe }}],
|
||||
timestamp: {% if point_data.timestamp %}"{{ point_data.timestamp|escapejs }}"{% else %}null{% endif %}
|
||||
});
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
|
||||
// Фильтруем точки с временными метками и сортируем
|
||||
var glPointsWithTime = glPointsData.filter(p => p.timestamp !== null);
|
||||
glPointsWithTime.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
|
||||
|
||||
// Создаём слои для координат объекта и точек ГЛ
|
||||
{% for group in groups %}
|
||||
@@ -138,14 +264,31 @@
|
||||
{% else %}
|
||||
// Это точка ГЛ
|
||||
var pointName = "{{ point_data.name|escapejs }}";
|
||||
var marker = L.marker([{{ point_data.point.1|safe }}, {{ point_data.point.0|safe }}], {
|
||||
icon: groupIcon
|
||||
}).bindPopup(pointName + '<br>' + "{{ point_data.frequency|escapejs }}");
|
||||
var pointCoords = [{{ point_data.point.1|safe }}, {{ point_data.point.0|safe }}];
|
||||
var pointNumber = {{ forloop.counter }};
|
||||
|
||||
// Определяем цвет маркера: первый - зеленый, последний - оранжевый, остальные - обычный
|
||||
var markerIcon;
|
||||
if (pointNumber === 1) {
|
||||
markerIcon = getColorIcon('green');
|
||||
} else if (pointNumber === glPointsData.length) {
|
||||
markerIcon = getColorIcon('orange');
|
||||
} else {
|
||||
markerIcon = groupIcon;
|
||||
}
|
||||
|
||||
var marker = L.marker(pointCoords, {
|
||||
icon: markerIcon
|
||||
}).bindPopup(pointNumber + '. ' + pointName + '<br>' + "{{ point_data.frequency|escapejs }}");
|
||||
groupLayer.addLayer(marker);
|
||||
glPointsGroupLayer.addLayer(marker); // Also add to GL points group layer
|
||||
|
||||
// Сохраняем координаты для построения трека
|
||||
glPointCoordinates.push(pointCoords);
|
||||
|
||||
// Добавляем каждую точку ГЛ отдельно в список
|
||||
glPointLayers.push({
|
||||
label: "{{ forloop.counter }} - {{ point_data.name|escapejs }} ({{ point_data.frequency|escapejs }})",
|
||||
label: pointNumber + " - {{ point_data.name|escapejs }} ({{ point_data.frequency|escapejs }})",
|
||||
layer: marker
|
||||
});
|
||||
{% endif %}
|
||||
@@ -158,8 +301,76 @@
|
||||
layer: groupLayer
|
||||
});
|
||||
{% endif %}
|
||||
|
||||
// НЕ добавляем слой группы на карту при загрузке - будет управляться через layer control
|
||||
{% if group.color in 'blue,orange,green,violet' %}
|
||||
// groupLayer.addTo(map); // Закомментировано - слои скрыты по умолчанию
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
// Создаём трек между точками ГЛ с номерами на сегментах
|
||||
if (glPointCoordinates.length > 1) {
|
||||
// Создаём отдельные сегменты линий между точками
|
||||
for (var i = 0; i < glPointCoordinates.length - 1; i++) {
|
||||
var segmentNumber = i + 1;
|
||||
|
||||
// Создаем линию с стрелкой
|
||||
var segment = L.polyline([glPointCoordinates[i], glPointCoordinates[i + 1]], {
|
||||
color: 'blue',
|
||||
weight: 3,
|
||||
opacity: 0.7
|
||||
});
|
||||
trackLayer.addLayer(segment);
|
||||
|
||||
// Добавляем стрелку через декоратор
|
||||
setTimeout(function(seg, segLayer, num) {
|
||||
return function() {
|
||||
var decorator = L.polylineDecorator(seg, {
|
||||
patterns: [
|
||||
{
|
||||
offset: '65%',
|
||||
repeat: 0,
|
||||
symbol: L.Symbol.arrowHead({
|
||||
pixelSize: 15,
|
||||
polygon: false,
|
||||
pathOptions: {
|
||||
stroke: true,
|
||||
color: 'blue',
|
||||
weight: 3,
|
||||
opacity: 0.7
|
||||
}
|
||||
})
|
||||
}
|
||||
]
|
||||
});
|
||||
segLayer.addLayer(decorator);
|
||||
};
|
||||
}(segment, trackLayer, segmentNumber), 100);
|
||||
|
||||
// Вычисляем центр сегмента для размещения номера
|
||||
var midLat = (glPointCoordinates[i][0] + glPointCoordinates[i + 1][0]) / 2;
|
||||
var midLng = (glPointCoordinates[i][1] + glPointCoordinates[i + 1][1]) / 2;
|
||||
|
||||
// Добавляем номер сегмента
|
||||
var segmentIcon = L.divIcon({
|
||||
className: 'segment-label',
|
||||
html: '<div style="background: rgba(0, 0, 255, 0.9); color: white; border: 2px solid white; border-radius: 50%; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 14px; box-shadow: 0 2px 4px rgba(0,0,0,0.4);">' + segmentNumber + '</div>',
|
||||
iconSize: [28, 28],
|
||||
iconAnchor: [14, 14]
|
||||
});
|
||||
var segmentMarker = L.marker([midLat, midLng], { icon: segmentIcon });
|
||||
trackLayer.addLayer(segmentMarker);
|
||||
}
|
||||
|
||||
// НЕ добавляем слой трека на карту при загрузке - будет управляться через playback
|
||||
// trackLayer.addTo(map);
|
||||
}
|
||||
|
||||
// НЕ добавляем GL точки на карту при загрузке - будет управляться через playback
|
||||
// if (glPointLayers.length > 0) {
|
||||
// glPointsGroupLayer.addTo(map);
|
||||
// }
|
||||
|
||||
// Создаём иерархию
|
||||
var treeOverlays = [];
|
||||
|
||||
@@ -177,7 +388,15 @@
|
||||
label: "Точки ГЛ",
|
||||
selectAllCheckbox: true,
|
||||
children: glPointLayers,
|
||||
layer: L.layerGroup()
|
||||
layer: glPointsGroupLayer
|
||||
});
|
||||
}
|
||||
|
||||
// Добавляем слой трека в контрол
|
||||
if (glPointCoordinates.length > 1) {
|
||||
treeOverlays.push({
|
||||
label: "Трек между точками ГЛ",
|
||||
layer: trackLayer
|
||||
});
|
||||
}
|
||||
|
||||
@@ -224,7 +443,7 @@
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
// Точки ГЛ (все одним цветом)
|
||||
// Точки ГЛ
|
||||
{% for group in groups %}
|
||||
{% if group.color not in 'blue,orange,green,violet' %}
|
||||
div.innerHTML += '<div class="legend-section"><div class="legend-section-title">Точки ГЛ:</div></div>';
|
||||
@@ -237,8 +456,272 @@
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
// Добавляем информацию о треке
|
||||
if (glPointCoordinates.length > 1) {
|
||||
div.innerHTML += '<div class="legend-section"><div class="legend-section-title">Трек между точками:</div></div>';
|
||||
div.innerHTML += `
|
||||
<div class="legend-item">
|
||||
<div style="width: 18px; height: 3px; background: blue; margin-right: 6px;"></div>
|
||||
<span>Соединительная линия</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Добавляем информацию о специальных точках
|
||||
if (glPointCoordinates.length > 1) {
|
||||
div.innerHTML += '<div class="legend-section"><div class="legend-section-title">Специальные точки:</div></div>';
|
||||
div.innerHTML += `
|
||||
<div class="legend-item">
|
||||
<div class="legend-marker" style="background-image: url('{% static "leaflet-markers/img/marker-icon-green.png" %}');"></div>
|
||||
<span>Первая точка</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-marker" style="background-image: url('{% static "leaflet-markers/img/marker-icon-orange.png" %}');"></div>
|
||||
<span>Последняя точка</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Добавляем информацию о playback (если доступен)
|
||||
if (glPointsWithTime && glPointsWithTime.length > 1) {
|
||||
div.innerHTML += '<div class="legend-section"><div class="legend-section-title">Режим воспроизведения:</div></div>';
|
||||
div.innerHTML += `
|
||||
<div class="legend-item">
|
||||
<div class="legend-marker" style="background-image: url('{% static "leaflet-markers/img/marker-icon-grey.png" %}');"></div>
|
||||
<span>Пройденные точки</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div style="width: 24px; height: 24px; margin-right: 6px; background: rgba(0, 0, 255, 0.9); color: white; border: 2px solid white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 11px;">1</div>
|
||||
<span>Номер сегмента трека</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div style="width: 18px; height: 18px; margin-right: 6px; background: #007bff; border-radius: 3px; display: flex; align-items: center; justify-content: center; color: white; font-size: 10px;">▶</div>
|
||||
<span>Используйте панель внизу</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return div;
|
||||
};
|
||||
legend.addTo(map);
|
||||
|
||||
// ============ PLAYBACK FUNCTIONALITY ============
|
||||
var playbackData = null;
|
||||
var currentPlaybackIndex = 0;
|
||||
var playbackInterval = null;
|
||||
var playbackMarkers = [];
|
||||
var playbackPolyline = null;
|
||||
var playbackSpeed = 1000; // milliseconds per step
|
||||
|
||||
// Показываем контроллер только если есть точки с временными метками
|
||||
if (glPointsWithTime.length > 1) {
|
||||
document.getElementById('playbackControl').style.display = 'flex';
|
||||
|
||||
// Инициализация слайдера
|
||||
var timeSlider = document.getElementById('timeSlider');
|
||||
timeSlider.max = glPointsWithTime.length - 1;
|
||||
|
||||
// Функция для форматирования даты
|
||||
function formatDate(isoString) {
|
||||
var date = new Date(isoString);
|
||||
return date.toLocaleString('ru-RU', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
// Функция для обновления отображения времени
|
||||
function updateTimeDisplay(index) {
|
||||
var timeDisplay = document.getElementById('timeDisplay');
|
||||
if (index >= 0 && index < glPointsWithTime.length) {
|
||||
timeDisplay.textContent = formatDate(glPointsWithTime[index].timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
// Функция для отрисовки точек до указанного индекса
|
||||
function renderPlaybackState(index) {
|
||||
// Очищаем предыдущие маркеры
|
||||
playbackMarkers.forEach(m => map.removeLayer(m));
|
||||
playbackMarkers = [];
|
||||
|
||||
if (playbackPolyline) {
|
||||
map.removeLayer(playbackPolyline);
|
||||
}
|
||||
|
||||
// Проверяем состояние чекбоксов
|
||||
var showPoints = document.getElementById('showPointsCheckbox').checked;
|
||||
var showTrack = document.getElementById('showTrackCheckbox').checked;
|
||||
|
||||
// Рисуем все точки до текущего индекса
|
||||
var coords = [];
|
||||
for (var i = 0; i <= index; i++) {
|
||||
var point = glPointsWithTime[i];
|
||||
coords.push(point.coords);
|
||||
|
||||
if (showPoints) {
|
||||
var markerIcon;
|
||||
|
||||
// Первая точка - зеленая, текущая - оранжевая, остальные - серые
|
||||
if (i === 0) {
|
||||
markerIcon = getColorIcon('green');
|
||||
} else if (i === index) {
|
||||
markerIcon = getColorIcon('orange');
|
||||
} else {
|
||||
markerIcon = getColorIcon('grey');
|
||||
}
|
||||
|
||||
var marker = L.marker(point.coords, { icon: markerIcon })
|
||||
.bindPopup((i + 1) + '. ' + point.name + '<br>' + point.frequency + '<br>' + formatDate(point.timestamp));
|
||||
marker.addTo(map);
|
||||
playbackMarkers.push(marker);
|
||||
}
|
||||
}
|
||||
|
||||
// Рисуем линию трека с номерами сегментов
|
||||
if (showTrack && coords.length > 1) {
|
||||
// Рисуем отдельные сегменты с номерами
|
||||
for (var i = 0; i < coords.length - 1; i++) {
|
||||
var segmentNumber = i + 1;
|
||||
|
||||
// Создаем линию сегмента
|
||||
var segment = L.polyline([coords[i], coords[i + 1]], {
|
||||
color: 'blue',
|
||||
weight: 3,
|
||||
opacity: 0.7
|
||||
}).addTo(map);
|
||||
playbackMarkers.push(segment);
|
||||
|
||||
// Добавляем стрелку на последний сегмент
|
||||
if (i === coords.length - 2) {
|
||||
var decorator = L.polylineDecorator(segment, {
|
||||
patterns: [{
|
||||
offset: '65%',
|
||||
repeat: 0,
|
||||
symbol: L.Symbol.arrowHead({
|
||||
pixelSize: 15,
|
||||
polygon: false,
|
||||
pathOptions: {
|
||||
stroke: true,
|
||||
color: 'blue',
|
||||
weight: 3,
|
||||
opacity: 0.7
|
||||
}
|
||||
})
|
||||
}]
|
||||
}).addTo(map);
|
||||
playbackMarkers.push(decorator);
|
||||
}
|
||||
|
||||
// Вычисляем центр сегмента для размещения номера
|
||||
var midLat = (coords[i][0] + coords[i + 1][0]) / 2;
|
||||
var midLng = (coords[i][1] + coords[i + 1][1]) / 2;
|
||||
|
||||
// Добавляем номер сегмента
|
||||
var segmentIcon = L.divIcon({
|
||||
className: 'segment-label',
|
||||
html: '<div style="background: rgba(0, 0, 255, 0.9); color: white; border: 2px solid white; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.4);">' + segmentNumber + '</div>',
|
||||
iconSize: [24, 24],
|
||||
iconAnchor: [12, 12]
|
||||
});
|
||||
var segmentMarker = L.marker([midLat, midLng], { icon: segmentIcon });
|
||||
segmentMarker.addTo(map);
|
||||
playbackMarkers.push(segmentMarker);
|
||||
}
|
||||
}
|
||||
|
||||
updateTimeDisplay(index);
|
||||
timeSlider.value = index;
|
||||
}
|
||||
|
||||
// Кнопка воспроизведения
|
||||
document.getElementById('playBtn').addEventListener('click', function() {
|
||||
if (playbackInterval) return;
|
||||
|
||||
this.disabled = true;
|
||||
document.getElementById('pauseBtn').disabled = false;
|
||||
|
||||
playbackInterval = setInterval(function() {
|
||||
currentPlaybackIndex++;
|
||||
|
||||
if (currentPlaybackIndex >= glPointsWithTime.length) {
|
||||
// Достигли конца
|
||||
clearInterval(playbackInterval);
|
||||
playbackInterval = null;
|
||||
document.getElementById('playBtn').disabled = false;
|
||||
document.getElementById('pauseBtn').disabled = true;
|
||||
currentPlaybackIndex = glPointsWithTime.length - 1;
|
||||
} else {
|
||||
renderPlaybackState(currentPlaybackIndex);
|
||||
}
|
||||
}, playbackSpeed);
|
||||
});
|
||||
|
||||
// Кнопка паузы
|
||||
document.getElementById('pauseBtn').addEventListener('click', function() {
|
||||
if (playbackInterval) {
|
||||
clearInterval(playbackInterval);
|
||||
playbackInterval = null;
|
||||
document.getElementById('playBtn').disabled = false;
|
||||
this.disabled = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Кнопка сброса
|
||||
document.getElementById('resetBtn').addEventListener('click', function() {
|
||||
if (playbackInterval) {
|
||||
clearInterval(playbackInterval);
|
||||
playbackInterval = null;
|
||||
}
|
||||
|
||||
currentPlaybackIndex = 0;
|
||||
renderPlaybackState(0);
|
||||
|
||||
document.getElementById('playBtn').disabled = false;
|
||||
document.getElementById('pauseBtn').disabled = true;
|
||||
});
|
||||
|
||||
// Слайдер времени
|
||||
timeSlider.addEventListener('input', function() {
|
||||
if (playbackInterval) {
|
||||
clearInterval(playbackInterval);
|
||||
playbackInterval = null;
|
||||
document.getElementById('playBtn').disabled = false;
|
||||
document.getElementById('pauseBtn').disabled = true;
|
||||
}
|
||||
|
||||
currentPlaybackIndex = parseInt(this.value);
|
||||
renderPlaybackState(currentPlaybackIndex);
|
||||
});
|
||||
|
||||
// Выбор скорости
|
||||
document.getElementById('speedSelect').addEventListener('change', function() {
|
||||
var speedMultiplier = parseFloat(this.value);
|
||||
playbackSpeed = 1000 / speedMultiplier;
|
||||
|
||||
// Если воспроизведение активно, перезапускаем с новой скоростью
|
||||
if (playbackInterval) {
|
||||
clearInterval(playbackInterval);
|
||||
document.getElementById('pauseBtn').click();
|
||||
setTimeout(function() {
|
||||
document.getElementById('playBtn').click();
|
||||
}, 100);
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчики для чекбоксов видимости
|
||||
document.getElementById('showPointsCheckbox').addEventListener('change', function() {
|
||||
renderPlaybackState(currentPlaybackIndex);
|
||||
});
|
||||
|
||||
document.getElementById('showTrackCheckbox').addEventListener('change', function() {
|
||||
renderPlaybackState(currentPlaybackIndex);
|
||||
});
|
||||
|
||||
// Инициализация - показываем первую точку
|
||||
renderPlaybackState(0);
|
||||
}
|
||||
</script>
|
||||
{% endblock extra_js %}
|
||||
|
||||
1724
dbapp/mainapp/templates/mainapp/statistics.html
Normal file
1724
dbapp/mainapp/templates/mainapp/statistics.html
Normal file
File diff suppressed because it is too large
Load Diff
387
dbapp/mainapp/templates/mainapp/tech_analyze_entry.html
Normal file
387
dbapp/mainapp/templates/mainapp/tech_analyze_entry.html
Normal file
@@ -0,0 +1,387 @@
|
||||
{% extends "mainapp/base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Тех. анализ - Ввод данных{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link href="{% static 'tabulator/css/tabulator_bootstrap5.min.css' %}" rel="stylesheet">
|
||||
<style>
|
||||
.data-entry-container {
|
||||
padding: 20px;
|
||||
}
|
||||
.form-section {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.table-section {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
#tech-analyze-table {
|
||||
margin-top: 20px;
|
||||
font-size: 12px;
|
||||
}
|
||||
#tech-analyze-table .tabulator-header {
|
||||
font-size: 12px;
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
#tech-analyze-table .tabulator-header .tabulator-col {
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
height: auto;
|
||||
min-height: 40px;
|
||||
}
|
||||
#tech-analyze-table .tabulator-header .tabulator-col-content {
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
padding: 6px 4px;
|
||||
}
|
||||
#tech-analyze-table .tabulator-cell {
|
||||
font-size: 12px;
|
||||
padding: 6px 4px;
|
||||
}
|
||||
.btn-group-custom {
|
||||
margin-top: 15px;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<!-- Toast Container -->
|
||||
<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999;">
|
||||
<div id="saveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="toast-header">
|
||||
<strong class="me-auto" id="toastTitle">Уведомление</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="toast-body" id="toastBody">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="data-entry-container">
|
||||
<h2>Тех. анализ - Ввод данных</h2>
|
||||
|
||||
<div class="form-section">
|
||||
<div class="row">
|
||||
<div class="col-md-4 mb-3">
|
||||
<label for="satellite-select" class="form-label">Спутник <span class="text-danger">*</span></label>
|
||||
<select id="satellite-select" class="form-select">
|
||||
<option value="">Выберите спутник</option>
|
||||
{% for satellite in satellites %}
|
||||
<option value="{{ satellite.id }}">{{ satellite.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-8 mb-3 d-flex align-items-end gap-2">
|
||||
<a href="{% url 'mainapp:tech_analyze_list' %}" class="btn btn-primary">
|
||||
<i class="bi bi-list"></i> Список данных
|
||||
</a>
|
||||
</div>
|
||||
<!-- <div class="col-md-8 mb-3">
|
||||
<div class="alert alert-info mb-0">
|
||||
<i class="bi bi-info-circle"></i>
|
||||
<strong>Инструкция:</strong>
|
||||
<ul class="mb-0 mt-2" style="font-size: 0.9em;">
|
||||
<li><strong>Порядок столбцов в Excel:</strong> Имя, Частота МГц, Полоса МГц, Сим. скорость БОД, Модуляция, Стандарт, Примечание</li>
|
||||
<li><strong>Поляризация извлекается автоматически</strong> из имени (например: "Сигнал 11500 МГц L" → "Левая")</li>
|
||||
<li>Поддерживаемые буквы: L=Левая, R=Правая, H=Горизонтальная, V=Вертикальная</li>
|
||||
<li>Скопируйте данные из Excel и вставьте в таблицу (Ctrl+V)</li>
|
||||
<li>Используйте стрелки, Tab, Enter для навигации и редактирования</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div> -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-section">
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<div>
|
||||
<h5>Таблица данных <span id="row-count" class="badge bg-primary">0</span></h5>
|
||||
</div>
|
||||
<div class="btn-group-custom">
|
||||
<button id="add-row" class="btn btn-primary">
|
||||
<i class="bi bi-plus-circle"></i> Добавить строку
|
||||
</button>
|
||||
<button id="delete-selected" class="btn btn-warning ms-2">
|
||||
<i class="bi bi-trash"></i> Удалить выбранные
|
||||
</button>
|
||||
<button id="save-data" class="btn btn-success ms-2">
|
||||
<i class="bi bi-save"></i> Сохранить
|
||||
</button>
|
||||
<button id="clear-table" class="btn btn-danger ms-2">
|
||||
<i class="bi bi-x-circle"></i> Очистить таблицу
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="tech-analyze-table"></div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Initialize Tabulator
|
||||
const table = new Tabulator("#tech-analyze-table", {
|
||||
layout: "fitDataStretch",
|
||||
height: "500px",
|
||||
placeholder: "Нет данных. Скопируйте данные из Excel и вставьте в таблицу (Ctrl+V).",
|
||||
headerWordWrap: true,
|
||||
clipboard: true,
|
||||
clipboardPasteAction: "replace",
|
||||
clipboardPasteParser: function(clipboard) {
|
||||
// Парсим данные из буфера обмена
|
||||
const rows = clipboard.split('\n').filter(row => row.trim() !== '');
|
||||
const data = [];
|
||||
|
||||
// Функция для извлечения поляризации из имени
|
||||
function extractPolarization(name) {
|
||||
if (!name) return '';
|
||||
|
||||
// Маппинг букв на полные названия
|
||||
const polarizationMap = {
|
||||
'L': 'Левая',
|
||||
'R': 'Правая',
|
||||
'H': 'Горизонтальная',
|
||||
'V': 'Вертикальная'
|
||||
};
|
||||
|
||||
// Ищем паттерн "МГц X" где X - буква поляризации
|
||||
const match = name.match(/МГц\s+([LRHV])/i);
|
||||
if (match) {
|
||||
const letter = match[1].toUpperCase();
|
||||
return polarizationMap[letter] || '';
|
||||
}
|
||||
|
||||
// Альтернативный паттерн: просто последняя буква L/R/H/V
|
||||
const lastChar = name.trim().slice(-1).toUpperCase();
|
||||
if (polarizationMap[lastChar]) {
|
||||
return polarizationMap[lastChar];
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
rows.forEach(row => {
|
||||
// Разделяем по табуляции (стандартный разделитель Excel)
|
||||
const cells = row.split('\t');
|
||||
|
||||
const name = cells[0] || '';
|
||||
const polarization = extractPolarization(name);
|
||||
|
||||
// Создаем объект с правильными полями (новый порядок без поляризации в начале)
|
||||
const rowData = {
|
||||
name: name,
|
||||
frequency: cells[1] || '',
|
||||
freq_range: cells[2] || '',
|
||||
bod_velocity: cells[3] || '',
|
||||
modulation: cells[4] || '',
|
||||
standard: cells[5] || '',
|
||||
note: cells[6] || '',
|
||||
polarization: polarization // Автоматически извлеченная поляризация
|
||||
};
|
||||
|
||||
data.push(rowData);
|
||||
});
|
||||
|
||||
return data;
|
||||
},
|
||||
columns: [
|
||||
{
|
||||
formatter: "rowSelection",
|
||||
titleFormatter: "rowSelection",
|
||||
hozAlign: "center",
|
||||
headerSort: false,
|
||||
width: 40,
|
||||
clipboard: false,
|
||||
cellClick: function(e, cell) {
|
||||
cell.getRow().toggleSelect();
|
||||
}
|
||||
},
|
||||
{title: "Имя", field: "name", minWidth: 150, widthGrow: 2, editor: "input"},
|
||||
{title: "Частота, МГц", field: "frequency", minWidth: 100, widthGrow: 1, editor: "input"},
|
||||
{title: "Полоса, МГц", field: "freq_range", minWidth: 100, widthGrow: 1, editor: "input"},
|
||||
{title: "Символьная скорость, БОД", field: "bod_velocity", minWidth: 150, widthGrow: 1.5, editor: "input"},
|
||||
{title: "Вид модуляции", field: "modulation", minWidth: 120, widthGrow: 1.2, editor: "input"},
|
||||
{title: "Стандарт", field: "standard", minWidth: 100, widthGrow: 1, editor: "input"},
|
||||
{title: "Примечание", field: "note", minWidth: 150, widthGrow: 2, editor: "input"},
|
||||
{title: "Поляризация", field: "polarization", minWidth: 100, widthGrow: 1, editor: "input"},
|
||||
],
|
||||
data: [],
|
||||
});
|
||||
|
||||
// Update row count
|
||||
function updateRowCount() {
|
||||
const count = table.getDataCount();
|
||||
document.getElementById('row-count').textContent = count;
|
||||
}
|
||||
|
||||
// Listen to table events
|
||||
table.on("rowAdded", updateRowCount);
|
||||
table.on("dataChanged", updateRowCount);
|
||||
table.on("rowDeleted", updateRowCount);
|
||||
|
||||
// Add row button
|
||||
document.getElementById('add-row').addEventListener('click', function() {
|
||||
table.addRow({
|
||||
name: '',
|
||||
frequency: '',
|
||||
freq_range: '',
|
||||
bod_velocity: '',
|
||||
modulation: '',
|
||||
standard: '',
|
||||
note: '',
|
||||
polarization: ''
|
||||
});
|
||||
});
|
||||
|
||||
// Helper function to show toast
|
||||
function showToast(title, message, type = 'info') {
|
||||
const toastEl = document.getElementById('saveToast');
|
||||
const toastTitle = document.getElementById('toastTitle');
|
||||
const toastBody = document.getElementById('toastBody');
|
||||
const toastHeader = toastEl.querySelector('.toast-header');
|
||||
|
||||
// Remove previous background classes
|
||||
toastHeader.classList.remove('bg-success', 'bg-danger', 'bg-warning', 'text-white');
|
||||
|
||||
// Add appropriate background class
|
||||
if (type === 'success') {
|
||||
toastHeader.classList.add('bg-success', 'text-white');
|
||||
} else if (type === 'error') {
|
||||
toastHeader.classList.add('bg-danger', 'text-white');
|
||||
} else if (type === 'warning') {
|
||||
toastHeader.classList.add('bg-warning');
|
||||
}
|
||||
|
||||
toastTitle.textContent = title;
|
||||
toastBody.innerHTML = message;
|
||||
|
||||
const toast = new bootstrap.Toast(toastEl, { delay: 5000 });
|
||||
toast.show();
|
||||
}
|
||||
|
||||
// Delete selected rows
|
||||
document.getElementById('delete-selected').addEventListener('click', function() {
|
||||
const selectedRows = table.getSelectedRows();
|
||||
if (selectedRows.length === 0) {
|
||||
showToast('Внимание', 'Выберите строки для удаления', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
if (confirm(`Удалить ${selectedRows.length} строк(и)?`)) {
|
||||
selectedRows.forEach(row => row.delete());
|
||||
showToast('Успешно', `Удалено строк: ${selectedRows.length}`, 'success');
|
||||
}
|
||||
});
|
||||
|
||||
// Save data
|
||||
document.getElementById('save-data').addEventListener('click', async function() {
|
||||
const satelliteId = document.getElementById('satellite-select').value;
|
||||
|
||||
if (!satelliteId) {
|
||||
showToast('Внимание', 'Пожалуйста, выберите спутник', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const data = table.getData();
|
||||
|
||||
if (data.length === 0) {
|
||||
showToast('Внимание', 'Нет данных для сохранения', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate that all rows have names
|
||||
const emptyNames = data.filter(row => !row.name || row.name.trim() === '');
|
||||
if (emptyNames.length > 0) {
|
||||
showToast('Внимание', 'Все строки должны иметь имя', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
// Disable button while saving
|
||||
this.disabled = true;
|
||||
this.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Сохранение...';
|
||||
|
||||
try {
|
||||
const response = await fetch('/tech-analyze/save/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': getCookie('csrftoken')
|
||||
},
|
||||
body: JSON.stringify({
|
||||
satellite_id: satelliteId,
|
||||
rows: data
|
||||
})
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
let message = `<strong>Успешно сохранено!</strong><br>`;
|
||||
message += `Создано: ${result.created}<br>`;
|
||||
message += `Обновлено: ${result.updated}<br>`;
|
||||
message += `Всего: ${result.total}`;
|
||||
|
||||
if (result.errors && result.errors.length > 0) {
|
||||
message += `<br><br><strong>Ошибки:</strong><br>${result.errors.join('<br>')}`;
|
||||
}
|
||||
|
||||
showToast('Сохранение завершено', message, 'success');
|
||||
|
||||
// Clear table after successful save
|
||||
if (!result.errors || result.errors.length === 0) {
|
||||
table.clearData();
|
||||
}
|
||||
} else {
|
||||
showToast('Ошибка', result.error || 'Неизвестная ошибка', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
showToast('Ошибка', 'Произошла ошибка при сохранении данных', 'error');
|
||||
} finally {
|
||||
// Re-enable button
|
||||
this.disabled = false;
|
||||
this.innerHTML = '<i class="bi bi-save"></i> Сохранить';
|
||||
}
|
||||
});
|
||||
|
||||
// Clear table
|
||||
document.getElementById('clear-table').addEventListener('click', function() {
|
||||
if (confirm('Вы уверены, что хотите очистить таблицу?')) {
|
||||
table.clearData();
|
||||
updateRowCount();
|
||||
}
|
||||
});
|
||||
|
||||
// Helper function to get CSRF token
|
||||
function getCookie(name) {
|
||||
let cookieValue = null;
|
||||
if (document.cookie && document.cookie !== '') {
|
||||
const cookies = document.cookie.split(';');
|
||||
for (let i = 0; i < cookies.length; i++) {
|
||||
const cookie = cookies[i].trim();
|
||||
if (cookie.substring(0, name.length + 1) === (name + '=')) {
|
||||
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cookieValue;
|
||||
}
|
||||
|
||||
// Initialize row count
|
||||
updateRowCount();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
528
dbapp/mainapp/templates/mainapp/tech_analyze_list.html
Normal file
528
dbapp/mainapp/templates/mainapp/tech_analyze_list.html
Normal file
@@ -0,0 +1,528 @@
|
||||
{% extends 'mainapp/base.html' %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}Тех. анализ - Список{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link href="{% static 'tabulator/css/tabulator_bootstrap5.min.css' %}" rel="stylesheet">
|
||||
<style>
|
||||
.sticky-top {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
#tech-analyze-table {
|
||||
font-size: 12px;
|
||||
}
|
||||
#tech-analyze-table .tabulator-header {
|
||||
font-size: 12px;
|
||||
}
|
||||
#tech-analyze-table .tabulator-cell {
|
||||
font-size: 12px;
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
#tech-analyze-table .tabulator-row {
|
||||
min-height: 40px;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container-fluid px-3">
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<h2>Тех. анализ - Список данных</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toolbar -->
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="d-flex flex-wrap align-items-center gap-3">
|
||||
<!-- Search bar -->
|
||||
<div style="min-width: 200px; flex-grow: 1; max-width: 400px;">
|
||||
<div class="input-group">
|
||||
<input type="text" id="toolbar-search" class="form-control" placeholder="Поиск по ID или имени...">
|
||||
<button type="button" class="btn btn-outline-primary" onclick="performSearch()">Найти</button>
|
||||
<button type="button" class="btn btn-outline-secondary" onclick="clearSearch()">Очистить</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Action buttons -->
|
||||
<div class="d-flex gap-2">
|
||||
<a href="{% url 'mainapp:tech_analyze_entry' %}" class="btn btn-success btn-sm" title="Ввод данных">
|
||||
<i class="bi bi-plus-circle"></i> Ввод данных
|
||||
</a>
|
||||
{% if user.customuser.role == 'admin' or user.customuser.role == 'moderator' %}
|
||||
<button type="button" class="btn btn-danger btn-sm" title="Удалить выбранные" onclick="deleteSelected()">
|
||||
<i class="bi bi-trash"></i> Удалить
|
||||
</button>
|
||||
{% endif %}
|
||||
<button type="button" class="btn btn-info btn-sm" title="Привязать к существующим точкам" onclick="showLinkModal()">
|
||||
<i class="bi bi-link-45deg"></i> Привязать к точкам
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Filter Toggle Button -->
|
||||
<div>
|
||||
<button class="btn btn-outline-primary btn-sm" type="button" data-bs-toggle="offcanvas"
|
||||
data-bs-target="#offcanvasFilters" aria-controls="offcanvasFilters">
|
||||
<i class="bi bi-funnel"></i> Фильтры
|
||||
<span id="filterCounter" class="badge bg-danger" style="display: none;">0</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Offcanvas Filter Panel -->
|
||||
<div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasFilters" aria-labelledby="offcanvasFiltersLabel">
|
||||
<div class="offcanvas-header">
|
||||
<h5 class="offcanvas-title" id="offcanvasFiltersLabel">Фильтры</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="offcanvas-body">
|
||||
<form method="get" id="filter-form">
|
||||
<!-- Satellite Selection - Multi-select -->
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Спутник:</label>
|
||||
<div class="d-flex justify-content-between mb-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllOptions('satellite_id', true)">Выбрать</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllOptions('satellite_id', false)">Снять</button>
|
||||
</div>
|
||||
<select name="satellite_id" class="form-select form-select-sm mb-2" multiple size="6">
|
||||
{% for satellite in satellites %}
|
||||
<option value="{{ satellite.id }}" {% if satellite.id in selected_satellites %}selected{% endif %}>
|
||||
{{ satellite.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Apply Filters and Reset Buttons -->
|
||||
<div class="d-grid gap-2 mt-2">
|
||||
<button type="submit" class="btn btn-primary btn-sm">Применить</button>
|
||||
<a href="?" class="btn btn-secondary btn-sm">Сбросить</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Table -->
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div id="tech-analyze-table"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Link to Points Modal -->
|
||||
<div class="modal fade" id="linkToPointsModal" tabindex="-1" aria-labelledby="linkToPointsModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="linkToPointsModalLabel">
|
||||
<i class="bi bi-link-45deg"></i> Привязать к существующим точкам
|
||||
</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="alert alert-info">
|
||||
<i class="bi bi-info-circle"></i>
|
||||
<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 class="mb-3">
|
||||
<label for="linkSatelliteSelect" class="form-label">Выберите спутник <span class="text-danger">*</span></label>
|
||||
<select class="form-select" id="linkSatelliteSelect" required>
|
||||
<option value="">Выберите спутник</option>
|
||||
{% for satellite in satellites %}
|
||||
<option value="{{ satellite.id }}">{{ satellite.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div id="linkResultMessage" class="alert" style="display: none;"></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="button" class="btn btn-primary" id="confirmLinkBtn" onclick="confirmLink(event)">
|
||||
<i class="bi bi-check-circle"></i> Привязать
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Include the satellite modal component -->
|
||||
{% include 'mainapp/components/_satellite_modal.html' %}
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
|
||||
<script>
|
||||
// Helper function to get CSRF token
|
||||
function getCookie(name) {
|
||||
let cookieValue = null;
|
||||
if (document.cookie && document.cookie !== '') {
|
||||
const cookies = document.cookie.split(';');
|
||||
for (let i = 0; i < cookies.length; i++) {
|
||||
const cookie = cookies[i].trim();
|
||||
if (cookie.substring(0, name.length + 1) === (name + '=')) {
|
||||
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cookieValue;
|
||||
}
|
||||
|
||||
// Initialize Tabulator
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const ajaxParams = {};
|
||||
for (const [key, value] of urlParams.entries()) {
|
||||
if (ajaxParams[key]) {
|
||||
if (!Array.isArray(ajaxParams[key])) {
|
||||
ajaxParams[key] = [ajaxParams[key]];
|
||||
}
|
||||
ajaxParams[key].push(value);
|
||||
} else {
|
||||
ajaxParams[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const table = new Tabulator("#tech-analyze-table", {
|
||||
ajaxURL: "{% url 'mainapp:tech_analyze_api' %}",
|
||||
ajaxParams: ajaxParams,
|
||||
pagination: true,
|
||||
paginationMode: "remote",
|
||||
paginationSize: {{ items_per_page }},
|
||||
paginationSizeSelector: [25, 50, 100, 200, 500],
|
||||
layout: "fitDataStretch",
|
||||
height: "70vh",
|
||||
placeholder: "Нет данных для отображения",
|
||||
rowHeight: null, // Автоматическая высота строк
|
||||
columns: [
|
||||
{
|
||||
formatter: "rowSelection",
|
||||
titleFormatter: "rowSelection",
|
||||
hozAlign: "center",
|
||||
headerSort: false,
|
||||
width: 40,
|
||||
cellClick: function(e, cell) {
|
||||
cell.getRow().toggleSelect();
|
||||
}
|
||||
},
|
||||
{title: "ID", field: "id", width: 80, hozAlign: "center"},
|
||||
{
|
||||
title: "Имя",
|
||||
field: "name",
|
||||
minWidth: 250,
|
||||
widthGrow: 3,
|
||||
formatter: function(cell) {
|
||||
return '<div style="white-space: normal; word-wrap: break-word; padding: 4px 0;">' +
|
||||
(cell.getValue() || '-') + '</div>';
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "Спутник",
|
||||
field: "satellite_name",
|
||||
minWidth: 120,
|
||||
widthGrow: 1,
|
||||
formatter: function(cell) {
|
||||
const data = cell.getData();
|
||||
if (data.satellite_id) {
|
||||
return '<a href="#" class="text-decoration-underline" onclick="showSatelliteModal(' + data.satellite_id + '); return false;">' +
|
||||
(data.satellite_name || '-') + '</a>';
|
||||
}
|
||||
return data.satellite_name || '-';
|
||||
}
|
||||
},
|
||||
{title: "Частота, МГц", field: "frequency", width: 120, hozAlign: "right", formatter: function(cell) {
|
||||
const val = cell.getValue();
|
||||
return val && val !== 0 ? val.toFixed(3) : '-';
|
||||
}},
|
||||
{title: "Полоса, МГц", field: "freq_range", width: 120, hozAlign: "right", formatter: function(cell) {
|
||||
const val = cell.getValue();
|
||||
return val && val !== 0 ? val.toFixed(3) : '-';
|
||||
}},
|
||||
{title: "Сим. скорость, БОД", field: "bod_velocity", width: 150, hozAlign: "right", formatter: function(cell) {
|
||||
const val = cell.getValue();
|
||||
return val && val !== 0 ? val.toFixed(0) : '-';
|
||||
}},
|
||||
{title: "Поляризация", field: "polarization_name", width: 120},
|
||||
{title: "Модуляция", field: "modulation_name", width: 120},
|
||||
{title: "Стандарт", field: "standard_name", width: 120},
|
||||
{
|
||||
title: "Примечание",
|
||||
field: "note",
|
||||
minWidth: 150,
|
||||
widthGrow: 2,
|
||||
formatter: function(cell) {
|
||||
return '<div style="white-space: normal; word-wrap: break-word; padding: 4px 0;">' +
|
||||
(cell.getValue() || '-') + '</div>';
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "Создано",
|
||||
field: "created_at",
|
||||
width: 140,
|
||||
formatter: function(cell) {
|
||||
const val = cell.getValue();
|
||||
if (!val) return '-';
|
||||
try {
|
||||
const date = new Date(val);
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
return day + '.' + month + '.' + year + ' ' + hours + ':' + minutes;
|
||||
} catch (e) {
|
||||
return '-';
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "Обновлено",
|
||||
field: "updated_at",
|
||||
width: 140,
|
||||
formatter: function(cell) {
|
||||
const val = cell.getValue();
|
||||
if (!val) return '-';
|
||||
try {
|
||||
const date = new Date(val);
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const year = date.getFullYear();
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
return day + '.' + month + '.' + year + ' ' + hours + ':' + minutes;
|
||||
} catch (e) {
|
||||
return '-';
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Search functionality
|
||||
function performSearch() {
|
||||
const searchValue = document.getElementById('toolbar-search').value.trim();
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
|
||||
if (searchValue) {
|
||||
urlParams.set('search', searchValue);
|
||||
} else {
|
||||
urlParams.delete('search');
|
||||
}
|
||||
|
||||
urlParams.delete('page');
|
||||
window.location.search = urlParams.toString();
|
||||
}
|
||||
|
||||
function clearSearch() {
|
||||
document.getElementById('toolbar-search').value = '';
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
urlParams.delete('search');
|
||||
urlParams.delete('page');
|
||||
window.location.search = urlParams.toString();
|
||||
}
|
||||
|
||||
// Handle Enter key in search input
|
||||
document.getElementById('toolbar-search').addEventListener('keypress', function(e) {
|
||||
if (e.key === 'Enter') {
|
||||
performSearch();
|
||||
}
|
||||
});
|
||||
|
||||
// Function to select/deselect all options in a select element
|
||||
function selectAllOptions(selectName, selectAll) {
|
||||
const selectElement = document.querySelector('select[name="' + selectName + '"]');
|
||||
if (selectElement) {
|
||||
for (let i = 0; i < selectElement.options.length; i++) {
|
||||
selectElement.options[i].selected = selectAll;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Filter counter functionality
|
||||
function updateFilterCounter() {
|
||||
const form = document.getElementById('filter-form');
|
||||
let filterCount = 0;
|
||||
|
||||
// Count selected satellites
|
||||
const satelliteSelect = document.querySelector('select[name="satellite_id"]');
|
||||
if (satelliteSelect) {
|
||||
const selectedOptions = Array.from(satelliteSelect.selectedOptions).filter(function(opt) { return opt.selected; });
|
||||
if (selectedOptions.length > 0) {
|
||||
filterCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// Display the filter counter
|
||||
const counterElement = document.getElementById('filterCounter');
|
||||
if (counterElement) {
|
||||
if (filterCount > 0) {
|
||||
counterElement.textContent = filterCount;
|
||||
counterElement.style.display = 'inline';
|
||||
} else {
|
||||
counterElement.style.display = 'none';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete selected items
|
||||
function deleteSelected() {
|
||||
const selectedRows = table.getSelectedRows();
|
||||
|
||||
if (selectedRows.length === 0) {
|
||||
alert('Пожалуйста, выберите хотя бы одну запись для удаления');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm('Удалить ' + selectedRows.length + ' записей?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedIds = selectedRows.map(function(row) { return row.getData().id; });
|
||||
|
||||
fetch('{% url "mainapp:tech_analyze_delete" %}', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': getCookie('csrftoken')
|
||||
},
|
||||
body: JSON.stringify({
|
||||
ids: selectedIds
|
||||
})
|
||||
})
|
||||
.then(function(response) { return response.json(); })
|
||||
.then(function(data) {
|
||||
if (data.success) {
|
||||
table.replaceData();
|
||||
} else {
|
||||
alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
|
||||
}
|
||||
})
|
||||
.catch(function(error) {
|
||||
console.error('Error:', error);
|
||||
alert('Произошла ошибка при удалении записей');
|
||||
});
|
||||
}
|
||||
|
||||
// Show link modal
|
||||
function showLinkModal() {
|
||||
const modal = new bootstrap.Modal(document.getElementById('linkToPointsModal'));
|
||||
document.getElementById('linkResultMessage').style.display = 'none';
|
||||
modal.show();
|
||||
}
|
||||
|
||||
// Confirm link
|
||||
function confirmLink(event) {
|
||||
const satelliteId = document.getElementById('linkSatelliteSelect').value;
|
||||
const resultDiv = document.getElementById('linkResultMessage');
|
||||
|
||||
if (!satelliteId) {
|
||||
resultDiv.className = 'alert alert-warning';
|
||||
resultDiv.textContent = 'Пожалуйста, выберите спутник';
|
||||
resultDiv.style.display = 'block';
|
||||
return;
|
||||
}
|
||||
|
||||
// Show loading state
|
||||
const btn = document.getElementById('confirmLinkBtn');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Обработка...';
|
||||
resultDiv.style.display = 'none';
|
||||
|
||||
fetch('{% url "mainapp:tech_analyze_link_existing" %}', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': getCookie('csrftoken')
|
||||
},
|
||||
body: JSON.stringify({
|
||||
satellite_id: satelliteId
|
||||
})
|
||||
})
|
||||
.then(function(response) { return response.json(); })
|
||||
.then(function(data) {
|
||||
if (data.success) {
|
||||
resultDiv.className = 'alert alert-success';
|
||||
resultDiv.innerHTML = '<strong>Привязка завершена!</strong><br>' +
|
||||
'Обновлено точек: ' + data.updated + '<br>' +
|
||||
'Пропущено: ' + data.skipped + '<br>' +
|
||||
'Всего обработано: ' + data.total;
|
||||
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
resultDiv.innerHTML += '<br><br><strong>Ошибки:</strong><br>' + data.errors.join('<br>');
|
||||
}
|
||||
} else {
|
||||
resultDiv.className = 'alert alert-danger';
|
||||
resultDiv.textContent = 'Ошибка: ' + (data.error || 'Неизвестная ошибка');
|
||||
}
|
||||
resultDiv.style.display = 'block';
|
||||
})
|
||||
.catch(function(error) {
|
||||
console.error('Error:', error);
|
||||
resultDiv.className = 'alert alert-danger';
|
||||
resultDiv.textContent = 'Произошла ошибка при привязке точек';
|
||||
resultDiv.style.display = 'block';
|
||||
})
|
||||
.finally(function() {
|
||||
// Re-enable button
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="bi bi-check-circle"></i> Привязать';
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize on page load
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Update filter counter on page load
|
||||
updateFilterCounter();
|
||||
|
||||
// Add event listeners to form elements to update counter when filters change
|
||||
const form = document.getElementById('filter-form');
|
||||
if (form) {
|
||||
const selectFields = form.querySelectorAll('select');
|
||||
selectFields.forEach(function(select) {
|
||||
select.addEventListener('change', updateFilterCounter);
|
||||
});
|
||||
}
|
||||
|
||||
// Update counter when offcanvas is shown
|
||||
const offcanvasElement = document.getElementById('offcanvasFilters');
|
||||
if (offcanvasElement) {
|
||||
offcanvasElement.addEventListener('show.bs.offcanvas', updateFilterCounter);
|
||||
}
|
||||
|
||||
// Set search value from URL
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const searchQuery = urlParams.get('search');
|
||||
if (searchQuery) {
|
||||
document.getElementById('toolbar-search').value = searchQuery;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -61,6 +61,9 @@
|
||||
<a href="{% url 'mainapp:transponder_create' %}" class="btn btn-success btn-sm" title="Создать">
|
||||
<i class="bi bi-plus-circle"></i> Создать
|
||||
</a>
|
||||
<a href="{% url 'mainapp:add_trans' %}" class="btn btn-warning btn-sm" title="Загрузить из XML">
|
||||
<i class="bi bi-upload"></i> Загрузить XML
|
||||
</a>
|
||||
<button type="button" class="btn btn-danger btn-sm" title="Удалить"
|
||||
onclick="deleteSelectedTransponders()">
|
||||
<i class="bi bi-trash"></i> Удалить
|
||||
|
||||
@@ -214,12 +214,15 @@ class CSVImportTestCase(TestCase):
|
||||
3;Signal3 V;56.8389;60.6057;0;01.01.2024 12:10:00;Test Satellite;12345;11540.7;36.0;1;good;Mirror1;Mirror2;"""
|
||||
|
||||
# Выполняем импорт
|
||||
sources_created = get_points_from_csv(csv_content, self.custom_user)
|
||||
result = get_points_from_csv(csv_content, self.custom_user)
|
||||
|
||||
# Проверяем результаты
|
||||
# Первые две точки близко (Москва), третья далеко (Екатеринбург)
|
||||
# Должно быть создано 2 источника
|
||||
self.assertEqual(sources_created, 2)
|
||||
self.assertEqual(result['new_sources'], 2)
|
||||
self.assertEqual(result['added'], 3)
|
||||
self.assertEqual(result['skipped'], 0)
|
||||
self.assertEqual(len(result['errors']), 0)
|
||||
self.assertEqual(Source.objects.count(), 2)
|
||||
self.assertEqual(ObjItem.objects.count(), 3)
|
||||
|
||||
@@ -237,8 +240,8 @@ class CSVImportTestCase(TestCase):
|
||||
csv_content_1 = """1;Signal1 V;55.7558;37.6173;0;01.01.2024 12:00:00;Test Satellite;12345;11500.5;36.0;1;good;Mirror1;Mirror2;
|
||||
2;Signal2 H;55.7560;37.6175;0;01.01.2024 12:05:00;Test Satellite;12345;11520.3;36.0;1;good;Mirror1;Mirror2;"""
|
||||
|
||||
sources_created_1 = get_points_from_csv(csv_content_1, self.custom_user)
|
||||
self.assertEqual(sources_created_1, 1)
|
||||
result_1 = get_points_from_csv(csv_content_1, self.custom_user)
|
||||
self.assertEqual(result_1['new_sources'], 1)
|
||||
initial_sources_count = Source.objects.count()
|
||||
initial_objitems_count = ObjItem.objects.count()
|
||||
|
||||
@@ -248,11 +251,12 @@ class CSVImportTestCase(TestCase):
|
||||
csv_content_2 = """3;Signal3 V;55.7562;37.6177;0;01.01.2024 12:10:00;Test Satellite;12345;11540.7;36.0;1;good;Mirror1;Mirror2;
|
||||
4;Signal4 H;56.8389;60.6057;0;01.01.2024 12:15:00;Test Satellite;12345;11560.2;36.0;1;good;Mirror1;Mirror2;"""
|
||||
|
||||
sources_created_2 = get_points_from_csv(csv_content_2, self.custom_user)
|
||||
result_2 = get_points_from_csv(csv_content_2, self.custom_user)
|
||||
|
||||
# Проверяем результаты
|
||||
# Должен быть создан 1 новый источник (для точки 4)
|
||||
self.assertEqual(sources_created_2, 1)
|
||||
self.assertEqual(result_2['new_sources'], 1)
|
||||
self.assertEqual(result_2['added'], 2)
|
||||
self.assertEqual(Source.objects.count(), initial_sources_count + 1)
|
||||
self.assertEqual(ObjItem.objects.count(), initial_objitems_count + 2)
|
||||
|
||||
@@ -276,10 +280,12 @@ class CSVImportTestCase(TestCase):
|
||||
# Второй импорт - та же точка (дубликат)
|
||||
csv_content_2 = """1;Signal1 V;55.7558;37.6173;0;01.01.2024 12:00:00;Test Satellite;12345;11500.5;36.0;1;good;Mirror1;Mirror2;"""
|
||||
|
||||
sources_created = get_points_from_csv(csv_content_2, self.custom_user)
|
||||
result = get_points_from_csv(csv_content_2, self.custom_user)
|
||||
|
||||
# Проверяем, что дубликат пропущен
|
||||
self.assertEqual(sources_created, 0)
|
||||
self.assertEqual(result['new_sources'], 0)
|
||||
self.assertEqual(result['added'], 0)
|
||||
self.assertEqual(result['skipped'], 1)
|
||||
self.assertEqual(Source.objects.count(), initial_sources_count)
|
||||
self.assertEqual(ObjItem.objects.count(), initial_objitems_count)
|
||||
|
||||
@@ -304,10 +310,12 @@ class CSVImportTestCase(TestCase):
|
||||
4;Signal4 H;56.8389;60.6057;0;01.01.2024 12:15:00;Test Satellite;12345;11560.2;36.0;1;good;Mirror1;Mirror2;
|
||||
5;Signal5 V;56.8391;60.6059;0;01.01.2024 12:20:00;Test Satellite;12345;11580.8;36.0;1;good;Mirror1;Mirror2;"""
|
||||
|
||||
sources_created = get_points_from_csv(csv_content_2, self.custom_user)
|
||||
result = get_points_from_csv(csv_content_2, self.custom_user)
|
||||
|
||||
# Проверяем результаты
|
||||
self.assertEqual(sources_created, 1) # Только для Екатеринбурга
|
||||
self.assertEqual(result['new_sources'], 1) # Только для Екатеринбурга
|
||||
self.assertEqual(result['added'], 3) # Точки 3, 4, 5
|
||||
self.assertEqual(result['skipped'], 1) # Точка 1 (дубликат)
|
||||
self.assertEqual(Source.objects.count(), 2) # Москва + Екатеринбург
|
||||
self.assertEqual(ObjItem.objects.count(), 5) # 2 начальных + 3 новых (дубликат пропущен)
|
||||
|
||||
|
||||
@@ -6,8 +6,9 @@ from .views import (
|
||||
ActionsPageView,
|
||||
AddSatellitesView,
|
||||
AddTranspondersView,
|
||||
ClusterTestView,
|
||||
# ClusterTestView,
|
||||
ClearLyngsatCacheView,
|
||||
DataEntryView,
|
||||
DeleteSelectedObjectsView,
|
||||
DeleteSelectedSourcesView,
|
||||
DeleteSelectedTranspondersView,
|
||||
@@ -18,6 +19,8 @@ from .views import (
|
||||
HomeView,
|
||||
KubsatView,
|
||||
KubsatExportView,
|
||||
KubsatCreateRequestsView,
|
||||
KubsatRecalculateCoordsView,
|
||||
LinkLyngsatSourcesView,
|
||||
LinkVchSigmaView,
|
||||
LoadCsvDataView,
|
||||
@@ -25,6 +28,9 @@ from .views import (
|
||||
LyngsatDataAPIView,
|
||||
LyngsatTaskStatusAPIView,
|
||||
LyngsatTaskStatusView,
|
||||
MergeSourcesView,
|
||||
MultiSourcesPlaybackDataAPIView,
|
||||
MultiSourcesPlaybackMapView,
|
||||
ObjItemCreateView,
|
||||
ObjItemDeleteView,
|
||||
ObjItemDetailView,
|
||||
@@ -32,15 +38,18 @@ from .views import (
|
||||
ObjItemUpdateView,
|
||||
ProcessKubsatView,
|
||||
SatelliteDataAPIView,
|
||||
SatelliteTranspondersAPIView,
|
||||
SatelliteListView,
|
||||
SatelliteCreateView,
|
||||
SatelliteUpdateView,
|
||||
SearchObjItemAPIView,
|
||||
ShowMapView,
|
||||
ShowSelectedObjectsMapView,
|
||||
ShowSourcesMapView,
|
||||
ShowSourceWithPointsMapView,
|
||||
ShowSourceAveragingStepsMapView,
|
||||
SourceListView,
|
||||
SourceCreateView,
|
||||
SourceUpdateView,
|
||||
SourceDeleteView,
|
||||
SourceObjItemsAPIView,
|
||||
@@ -53,7 +62,39 @@ from .views import (
|
||||
UploadVchLoadView,
|
||||
custom_logout,
|
||||
)
|
||||
from .views.marks import ObjectMarksListView, AddObjectMarkView, UpdateObjectMarkView
|
||||
from .views.marks import (
|
||||
SignalMarksView,
|
||||
SignalMarksHistoryAPIView,
|
||||
SignalMarksEntryAPIView,
|
||||
SaveSignalMarksView,
|
||||
CreateTechAnalyzeView,
|
||||
ObjectMarksListView,
|
||||
AddObjectMarkView,
|
||||
UpdateObjectMarkView,
|
||||
)
|
||||
from .views.source_requests import (
|
||||
SourceRequestListView,
|
||||
SourceRequestCreateView,
|
||||
SourceRequestUpdateView,
|
||||
SourceRequestDeleteView,
|
||||
SourceRequestBulkDeleteView,
|
||||
SourceRequestExportView,
|
||||
SourceRequestAPIView,
|
||||
SourceRequestDetailAPIView,
|
||||
SourceDataAPIView,
|
||||
SourceRequestImportView,
|
||||
)
|
||||
from .views.tech_analyze import (
|
||||
TechAnalyzeEntryView,
|
||||
TechAnalyzeSaveView,
|
||||
LinkExistingPointsView,
|
||||
TechAnalyzeListView,
|
||||
TechAnalyzeDeleteView,
|
||||
TechAnalyzeAPIView,
|
||||
)
|
||||
from .views.points_averaging import PointsAveragingView, PointsAveragingAPIView, RecalculateGroupAPIView
|
||||
from .views.statistics import StatisticsView, StatisticsAPIView, ExtendedStatisticsAPIView
|
||||
from .views.secret_stats import SecretStatsView
|
||||
|
||||
app_name = 'mainapp'
|
||||
|
||||
@@ -64,9 +105,11 @@ urlpatterns = [
|
||||
path('home/', RedirectView.as_view(pattern_name='mainapp:source_list', permanent=True), name='home_redirect'),
|
||||
# Keep /sources/ as an alias (Requirement 1.2)
|
||||
path('sources/', SourceListView.as_view(), name='source_list'),
|
||||
path('source/create/', SourceCreateView.as_view(), name='source_create'),
|
||||
path('source/<int:pk>/edit/', SourceUpdateView.as_view(), name='source_update'),
|
||||
path('source/<int:pk>/delete/', SourceDeleteView.as_view(), name='source_delete'),
|
||||
path('delete-selected-sources/', DeleteSelectedSourcesView.as_view(), name='delete_selected_sources'),
|
||||
path('merge-sources/', MergeSourcesView.as_view(), name='merge_sources'),
|
||||
path('objitems/', ObjItemListView.as_view(), name='objitem_list'),
|
||||
path('transponders/', TransponderListView.as_view(), name='transponder_list'),
|
||||
path('transponder/create/', TransponderCreateView.as_view(), name='transponder_create'),
|
||||
@@ -87,8 +130,9 @@ urlpatterns = [
|
||||
path('show-sources-map/', ShowSourcesMapView.as_view(), name='show_sources_map'),
|
||||
path('show-source-with-points-map/<int:source_id>/', ShowSourceWithPointsMapView.as_view(), name='show_source_with_points_map'),
|
||||
path('show-source-averaging-map/<int:source_id>/', ShowSourceAveragingStepsMapView.as_view(), name='show_source_averaging_map'),
|
||||
path('multi-sources-playback-map/', MultiSourcesPlaybackMapView.as_view(), name='multi_sources_playback_map'),
|
||||
path('delete-selected-objects/', DeleteSelectedObjectsView.as_view(), name='delete_selected_objects'),
|
||||
path('cluster/', ClusterTestView.as_view(), name='cluster'),
|
||||
# path('cluster/', ClusterTestView.as_view(), name='cluster'),
|
||||
path('vch-upload/', UploadVchLoadView.as_view(), name='vch_load'),
|
||||
path('vch-link/', LinkVchSigmaView.as_view(), name='link_vch_sigma'),
|
||||
path('link-lyngsat/', LinkLyngsatSourcesView.as_view(), name='link_lyngsat'),
|
||||
@@ -97,7 +141,9 @@ urlpatterns = [
|
||||
path('api/source/<int:source_id>/objitems/', SourceObjItemsAPIView.as_view(), name='source_objitems_api'),
|
||||
path('api/transponder/<int:transponder_id>/', TransponderDataAPIView.as_view(), name='transponder_data_api'),
|
||||
path('api/satellite/<int:satellite_id>/', SatelliteDataAPIView.as_view(), name='satellite_data_api'),
|
||||
path('api/satellite/<int:satellite_id>/transponders/', SatelliteTranspondersAPIView.as_view(), name='satellite_transponders_api'),
|
||||
path('api/geo-points/', GeoPointsAPIView.as_view(), name='geo_points_api'),
|
||||
path('api/multi-sources-playback/', MultiSourcesPlaybackDataAPIView.as_view(), name='multi_sources_playback_api'),
|
||||
path('kubsat-excel/', ProcessKubsatView.as_view(), name='kubsat_excel'),
|
||||
path('object/create/', ObjItemCreateView.as_view(), name='objitem_create'),
|
||||
path('object/<int:pk>/edit/', ObjItemUpdateView.as_view(), name='objitem_update'),
|
||||
@@ -109,10 +155,45 @@ urlpatterns = [
|
||||
path('api/lyngsat-task-status/<str:task_id>/', LyngsatTaskStatusAPIView.as_view(), name='lyngsat_task_status_api'),
|
||||
path('clear-lyngsat-cache/', ClearLyngsatCacheView.as_view(), name='clear_lyngsat_cache'),
|
||||
path('unlink-all-lyngsat/', UnlinkAllLyngsatSourcesView.as_view(), name='unlink_all_lyngsat'),
|
||||
# Signal Marks (новая система отметок)
|
||||
path('signal-marks/', SignalMarksView.as_view(), name='signal_marks'),
|
||||
path('api/signal-marks/history/', SignalMarksHistoryAPIView.as_view(), name='signal_marks_history_api'),
|
||||
path('api/signal-marks/entry/', SignalMarksEntryAPIView.as_view(), name='signal_marks_entry_api'),
|
||||
path('api/signal-marks/save/', SaveSignalMarksView.as_view(), name='save_signal_marks'),
|
||||
path('api/signal-marks/create-tech-analyze/', CreateTechAnalyzeView.as_view(), name='create_tech_analyze_for_marks'),
|
||||
# Старые URL для обратной совместимости (редирект)
|
||||
path('object-marks/', ObjectMarksListView.as_view(), name='object_marks'),
|
||||
path('api/add-object-mark/', AddObjectMarkView.as_view(), name='add_object_mark'),
|
||||
path('api/update-object-mark/', UpdateObjectMarkView.as_view(), name='update_object_mark'),
|
||||
path('kubsat/', KubsatView.as_view(), name='kubsat'),
|
||||
path('kubsat/export/', KubsatExportView.as_view(), name='kubsat_export'),
|
||||
path('kubsat/create-requests/', KubsatCreateRequestsView.as_view(), name='kubsat_create_requests'),
|
||||
path('kubsat/recalculate-coords/', KubsatRecalculateCoordsView.as_view(), name='kubsat_recalculate_coords'),
|
||||
# Source Requests
|
||||
path('source-requests/', SourceRequestListView.as_view(), name='source_request_list'),
|
||||
path('source-requests/create/', SourceRequestCreateView.as_view(), name='source_request_create'),
|
||||
path('source-requests/<int:pk>/edit/', SourceRequestUpdateView.as_view(), name='source_request_update'),
|
||||
path('source-requests/<int:pk>/delete/', SourceRequestDeleteView.as_view(), name='source_request_delete'),
|
||||
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/<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('api/search-objitem/', SearchObjItemAPIView.as_view(), name='search_objitem_api'),
|
||||
path('tech-analyze/', TechAnalyzeEntryView.as_view(), name='tech_analyze_entry'),
|
||||
path('tech-analyze/list/', TechAnalyzeListView.as_view(), name='tech_analyze_list'),
|
||||
path('tech-analyze/save/', TechAnalyzeSaveView.as_view(), name='tech_analyze_save'),
|
||||
path('tech-analyze/delete/', TechAnalyzeDeleteView.as_view(), name='tech_analyze_delete'),
|
||||
path('tech-analyze/link-existing/', LinkExistingPointsView.as_view(), name='tech_analyze_link_existing'),
|
||||
path('api/tech-analyze/', TechAnalyzeAPIView.as_view(), name='tech_analyze_api'),
|
||||
path('points-averaging/', PointsAveragingView.as_view(), name='points_averaging'),
|
||||
path('api/points-averaging/', PointsAveragingAPIView.as_view(), name='points_averaging_api'),
|
||||
path('api/points-averaging/recalculate/', RecalculateGroupAPIView.as_view(), name='points_averaging_recalculate'),
|
||||
path('statistics/', StatisticsView.as_view(), name='statistics'),
|
||||
path('api/statistics/', StatisticsAPIView.as_view(), name='statistics_api'),
|
||||
path('api/statistics/extended/', ExtendedStatisticsAPIView.as_view(), name='extended_statistics_api'),
|
||||
path('secret-stat/', SecretStatsView.as_view(), name='secret_stats'),
|
||||
path('logout/', custom_logout, name='logout'),
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -22,10 +22,12 @@ from .api import (
|
||||
GetLocationsView,
|
||||
LyngsatDataAPIView,
|
||||
SatelliteDataAPIView,
|
||||
SatelliteTranspondersAPIView,
|
||||
SigmaParameterDataAPIView,
|
||||
SourceObjItemsAPIView,
|
||||
LyngsatTaskStatusAPIView,
|
||||
TransponderDataAPIView,
|
||||
MultiSourcesPlaybackDataAPIView,
|
||||
)
|
||||
from .lyngsat import (
|
||||
LinkLyngsatSourcesView,
|
||||
@@ -34,7 +36,7 @@ from .lyngsat import (
|
||||
ClearLyngsatCacheView,
|
||||
UnlinkAllLyngsatSourcesView,
|
||||
)
|
||||
from .source import SourceListView, SourceUpdateView, SourceDeleteView, DeleteSelectedSourcesView
|
||||
from .source import SourceListView, SourceCreateView, SourceUpdateView, SourceDeleteView, DeleteSelectedSourcesView, MergeSourcesView
|
||||
from .transponder import (
|
||||
TransponderListView,
|
||||
TransponderCreateView,
|
||||
@@ -53,11 +55,35 @@ from .map import (
|
||||
ShowSourcesMapView,
|
||||
ShowSourceWithPointsMapView,
|
||||
ShowSourceAveragingStepsMapView,
|
||||
ClusterTestView,
|
||||
MultiSourcesPlaybackMapView,
|
||||
# ClusterTestView,
|
||||
)
|
||||
from .kubsat import (
|
||||
KubsatView,
|
||||
KubsatExportView,
|
||||
KubsatCreateRequestsView,
|
||||
KubsatRecalculateCoordsView,
|
||||
)
|
||||
from .data_entry import (
|
||||
DataEntryView,
|
||||
SearchObjItemAPIView,
|
||||
)
|
||||
from .points_averaging import (
|
||||
PointsAveragingView,
|
||||
PointsAveragingAPIView,
|
||||
RecalculateGroupAPIView,
|
||||
)
|
||||
from .statistics import (
|
||||
StatisticsView,
|
||||
StatisticsAPIView,
|
||||
)
|
||||
from .source_requests import (
|
||||
SourceRequestListView,
|
||||
SourceRequestCreateView,
|
||||
SourceRequestUpdateView,
|
||||
SourceRequestDeleteView,
|
||||
SourceRequestAPIView,
|
||||
SourceRequestDetailAPIView,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@@ -85,10 +111,12 @@ __all__ = [
|
||||
'GetLocationsView',
|
||||
'LyngsatDataAPIView',
|
||||
'SatelliteDataAPIView',
|
||||
'SatelliteTranspondersAPIView',
|
||||
'SigmaParameterDataAPIView',
|
||||
'SourceObjItemsAPIView',
|
||||
'LyngsatTaskStatusAPIView',
|
||||
'TransponderDataAPIView',
|
||||
'MultiSourcesPlaybackDataAPIView',
|
||||
# LyngSat
|
||||
'LinkLyngsatSourcesView',
|
||||
'FillLyngsatDataView',
|
||||
@@ -97,9 +125,11 @@ __all__ = [
|
||||
'UnlinkAllLyngsatSourcesView',
|
||||
# Source
|
||||
'SourceListView',
|
||||
'SourceCreateView',
|
||||
'SourceUpdateView',
|
||||
'SourceDeleteView',
|
||||
'DeleteSelectedSourcesView',
|
||||
'MergeSourcesView',
|
||||
# Transponder
|
||||
'TransponderListView',
|
||||
'TransponderCreateView',
|
||||
@@ -116,8 +146,28 @@ __all__ = [
|
||||
'ShowSourcesMapView',
|
||||
'ShowSourceWithPointsMapView',
|
||||
'ShowSourceAveragingStepsMapView',
|
||||
'ClusterTestView',
|
||||
'MultiSourcesPlaybackMapView',
|
||||
# 'ClusterTestView',
|
||||
# Kubsat
|
||||
'KubsatView',
|
||||
'KubsatExportView',
|
||||
'KubsatCreateRequestsView',
|
||||
'KubsatRecalculateCoordsView',
|
||||
# Data Entry
|
||||
'DataEntryView',
|
||||
'SearchObjItemAPIView',
|
||||
# Points Averaging
|
||||
'PointsAveragingView',
|
||||
'PointsAveragingAPIView',
|
||||
'RecalculateGroupAPIView',
|
||||
# Statistics
|
||||
'StatisticsView',
|
||||
'StatisticsAPIView',
|
||||
# Source Requests
|
||||
'SourceRequestListView',
|
||||
'SourceRequestCreateView',
|
||||
'SourceRequestUpdateView',
|
||||
'SourceRequestDeleteView',
|
||||
'SourceRequestAPIView',
|
||||
'SourceRequestDetailAPIView',
|
||||
]
|
||||
|
||||
@@ -199,8 +199,8 @@ class SourceObjItemsAPIView(LoginRequiredMixin, View):
|
||||
'source_objitems__transponder',
|
||||
'source_objitems__created_by__user',
|
||||
'source_objitems__updated_by__user',
|
||||
'marks',
|
||||
'marks__created_by__user'
|
||||
# 'marks',
|
||||
# 'marks__created_by__user'
|
||||
).get(id=source_id)
|
||||
|
||||
# Get all related ObjItems, sorted by created_at
|
||||
@@ -359,20 +359,9 @@ class SourceObjItemsAPIView(LoginRequiredMixin, View):
|
||||
'mirrors': mirrors,
|
||||
})
|
||||
|
||||
# Get marks for the source
|
||||
# Отметки теперь привязаны к TechAnalyze, а не к Source
|
||||
# marks_data оставляем пустым для обратной совместимости
|
||||
marks_data = []
|
||||
for mark in source.marks.all().order_by('-timestamp'):
|
||||
mark_timestamp = '-'
|
||||
if mark.timestamp:
|
||||
local_time = timezone.localtime(mark.timestamp)
|
||||
mark_timestamp = local_time.strftime("%d.%m.%Y %H:%M")
|
||||
|
||||
marks_data.append({
|
||||
'id': mark.id,
|
||||
'mark': mark.mark,
|
||||
'timestamp': mark_timestamp,
|
||||
'created_by': str(mark.created_by) if mark.created_by else '-',
|
||||
})
|
||||
|
||||
return JsonResponse({
|
||||
'source_id': source_id,
|
||||
@@ -602,10 +591,19 @@ class SatelliteDataAPIView(LoginRequiredMixin, View):
|
||||
bands = list(satellite.band.values_list('name', flat=True))
|
||||
bands_str = ', '.join(bands) if bands else '-'
|
||||
|
||||
# Get location place display
|
||||
location_place_display = '-'
|
||||
if satellite.location_place:
|
||||
location_place_choices = dict(Satellite.PLACES)
|
||||
location_place_display = location_place_choices.get(satellite.location_place, satellite.location_place)
|
||||
|
||||
data = {
|
||||
'id': satellite.id,
|
||||
'name': satellite.name,
|
||||
'alternative_name': satellite.alternative_name or '-',
|
||||
'norad': satellite.norad if satellite.norad else None,
|
||||
'international_code': satellite.international_code or '-',
|
||||
'location_place': location_place_display,
|
||||
'bands': bands_str,
|
||||
'undersat_point': satellite.undersat_point if satellite.undersat_point is not None else None,
|
||||
'url': satellite.url or None,
|
||||
@@ -622,3 +620,143 @@ class SatelliteDataAPIView(LoginRequiredMixin, View):
|
||||
return JsonResponse({'error': 'Спутник не найден'}, status=404)
|
||||
except Exception as e:
|
||||
return JsonResponse({'error': str(e)}, status=500)
|
||||
|
||||
|
||||
class MultiSourcesPlaybackDataAPIView(LoginRequiredMixin, View):
|
||||
"""API endpoint for getting playback data for multiple sources."""
|
||||
|
||||
def get(self, request):
|
||||
from ..models import Source
|
||||
|
||||
ids = request.GET.get('ids', '')
|
||||
if not ids:
|
||||
return JsonResponse({'error': 'Не указаны ID источников'}, status=400)
|
||||
|
||||
try:
|
||||
id_list = [int(x) for x in ids.split(',') if x.isdigit()]
|
||||
if not id_list:
|
||||
return JsonResponse({'error': 'Некорректные ID источников'}, status=400)
|
||||
|
||||
sources = Source.objects.filter(id__in=id_list).prefetch_related(
|
||||
'source_objitems',
|
||||
'source_objitems__parameter_obj',
|
||||
'source_objitems__geo_obj',
|
||||
)
|
||||
|
||||
# Collect data for each source
|
||||
sources_data = []
|
||||
global_min_time = None
|
||||
global_max_time = None
|
||||
|
||||
# Define colors for different sources
|
||||
colors = ['red', 'blue', 'green', 'purple', 'orange', 'cyan', 'magenta', 'yellow', 'lime', 'pink']
|
||||
|
||||
for idx, source in enumerate(sources):
|
||||
# Get all ObjItems with geo data and timestamp
|
||||
objitems = source.source_objitems.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__coords__isnull=False,
|
||||
geo_obj__timestamp__isnull=False
|
||||
).select_related('geo_obj', 'parameter_obj').order_by('geo_obj__timestamp')
|
||||
|
||||
points = []
|
||||
for objitem in objitems:
|
||||
geo = objitem.geo_obj
|
||||
param = getattr(objitem, 'parameter_obj', None)
|
||||
|
||||
timestamp = geo.timestamp
|
||||
|
||||
# Update global min/max time
|
||||
if global_min_time is None or timestamp < global_min_time:
|
||||
global_min_time = timestamp
|
||||
if global_max_time is None or timestamp > global_max_time:
|
||||
global_max_time = timestamp
|
||||
|
||||
freq_str = '-'
|
||||
if param and param.frequency:
|
||||
freq_str = f"{param.frequency} МГц"
|
||||
|
||||
points.append({
|
||||
'lat': geo.coords.y,
|
||||
'lng': geo.coords.x,
|
||||
'timestamp': timestamp.isoformat(),
|
||||
'timestamp_ms': int(timestamp.timestamp() * 1000),
|
||||
'name': objitem.name or f'Точка #{objitem.id}',
|
||||
'frequency': freq_str,
|
||||
'location': geo.location or '-',
|
||||
})
|
||||
|
||||
if points:
|
||||
# Get source name from first objitem or use ID
|
||||
source_name = f"Объект #{source.id}"
|
||||
if source.source_objitems.exists():
|
||||
first_objitem = source.source_objitems.first()
|
||||
if first_objitem and first_objitem.name:
|
||||
# Extract base name (without frequency info)
|
||||
source_name = first_objitem.name.split(' ')[0] if first_objitem.name else source_name
|
||||
|
||||
sources_data.append({
|
||||
'source_id': source.id,
|
||||
'source_name': source_name,
|
||||
'color': colors[idx % len(colors)],
|
||||
'points': points,
|
||||
'points_count': len(points),
|
||||
})
|
||||
|
||||
# Format global time range
|
||||
time_range = None
|
||||
if global_min_time and global_max_time:
|
||||
time_range = {
|
||||
'min': global_min_time.isoformat(),
|
||||
'max': global_max_time.isoformat(),
|
||||
'min_ms': int(global_min_time.timestamp() * 1000),
|
||||
'max_ms': int(global_max_time.timestamp() * 1000),
|
||||
}
|
||||
|
||||
return JsonResponse({
|
||||
'sources': sources_data,
|
||||
'time_range': time_range,
|
||||
'total_sources': len(sources_data),
|
||||
})
|
||||
except Exception as e:
|
||||
return JsonResponse({'error': str(e)}, status=500)
|
||||
|
||||
|
||||
|
||||
class SatelliteTranspondersAPIView(LoginRequiredMixin, View):
|
||||
"""API endpoint for getting transponders for a satellite."""
|
||||
|
||||
def get(self, request, satellite_id):
|
||||
from mapsapp.models import Transponders
|
||||
|
||||
try:
|
||||
transponders = Transponders.objects.filter(
|
||||
sat_id=satellite_id
|
||||
).select_related('polarization').order_by('downlink')
|
||||
|
||||
if not transponders.exists():
|
||||
return JsonResponse({
|
||||
'satellite_id': satellite_id,
|
||||
'transponders': [],
|
||||
'count': 0
|
||||
})
|
||||
|
||||
transponders_data = []
|
||||
for t in transponders:
|
||||
transponders_data.append({
|
||||
'id': t.id,
|
||||
'name': t.name or '-',
|
||||
'downlink': float(t.downlink) if t.downlink else 0,
|
||||
'uplink': float(t.uplink) if t.uplink else None,
|
||||
'frequency_range': float(t.frequency_range) if t.frequency_range else 0,
|
||||
'polarization': t.polarization.name if t.polarization else '-',
|
||||
'zone_name': t.zone_name or '-',
|
||||
})
|
||||
|
||||
return JsonResponse({
|
||||
'satellite_id': satellite_id,
|
||||
'transponders': transponders_data,
|
||||
'count': len(transponders_data)
|
||||
})
|
||||
except Exception as e:
|
||||
return JsonResponse({'error': str(e)}, status=500)
|
||||
|
||||
@@ -339,49 +339,9 @@ class HomeView(LoginRequiredMixin, View):
|
||||
return f"{lat_str} {lon_str}"
|
||||
return "-"
|
||||
|
||||
# Get marks if requested
|
||||
# Отметки теперь привязаны к TechAnalyze, а не к Source
|
||||
# marks_data оставляем пустым для обратной совместимости
|
||||
marks_data = []
|
||||
if show_marks == "1":
|
||||
marks_qs = source.marks.select_related('created_by__user').all()
|
||||
|
||||
# Filter marks by date
|
||||
if marks_date_from:
|
||||
try:
|
||||
date_from_obj = datetime.strptime(marks_date_from, "%Y-%m-%dT%H:%M")
|
||||
marks_qs = marks_qs.filter(timestamp__gte=date_from_obj)
|
||||
except (ValueError, TypeError):
|
||||
try:
|
||||
date_from_obj = datetime.strptime(marks_date_from, "%Y-%m-%d")
|
||||
marks_qs = marks_qs.filter(timestamp__gte=date_from_obj)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if marks_date_to:
|
||||
try:
|
||||
date_to_obj = datetime.strptime(marks_date_to, "%Y-%m-%dT%H:%M")
|
||||
marks_qs = marks_qs.filter(timestamp__lte=date_to_obj)
|
||||
except (ValueError, TypeError):
|
||||
try:
|
||||
date_to_obj = datetime.strptime(marks_date_to, "%Y-%m-%d") + timedelta(days=1)
|
||||
marks_qs = marks_qs.filter(timestamp__lt=date_to_obj)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Filter marks by status
|
||||
if marks_status == "present":
|
||||
marks_qs = marks_qs.filter(mark=True)
|
||||
elif marks_status == "absent":
|
||||
marks_qs = marks_qs.filter(mark=False)
|
||||
|
||||
# Process marks
|
||||
for mark in marks_qs:
|
||||
marks_data.append({
|
||||
'id': mark.id,
|
||||
'mark': mark.mark,
|
||||
'timestamp': mark.timestamp,
|
||||
'created_by': str(mark.created_by) if mark.created_by else "-",
|
||||
'can_edit': mark.can_edit(),
|
||||
})
|
||||
|
||||
processed.append({
|
||||
'id': source.id,
|
||||
@@ -429,41 +389,8 @@ class HomeView(LoginRequiredMixin, View):
|
||||
kupsat_coords = format_coords(source.coords_kupsat) if source else "-"
|
||||
valid_coords = format_coords(source.coords_valid) if source else "-"
|
||||
|
||||
# Get marks if requested
|
||||
# Отметки теперь привязаны к TechAnalyze, а не к ObjItem
|
||||
marks_data = []
|
||||
if show_marks == "1":
|
||||
marks_qs = objitem.marks.select_related('created_by__user').all()
|
||||
|
||||
# Filter marks by date
|
||||
if marks_date_from:
|
||||
try:
|
||||
date_from_obj = datetime.strptime(marks_date_from, "%Y-%m-%d")
|
||||
marks_qs = marks_qs.filter(timestamp__gte=date_from_obj)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if marks_date_to:
|
||||
try:
|
||||
date_to_obj = datetime.strptime(marks_date_to, "%Y-%m-%d") + timedelta(days=1)
|
||||
marks_qs = marks_qs.filter(timestamp__lt=date_to_obj)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Filter marks by status
|
||||
if marks_status == "present":
|
||||
marks_qs = marks_qs.filter(mark=True)
|
||||
elif marks_status == "absent":
|
||||
marks_qs = marks_qs.filter(mark=False)
|
||||
|
||||
# Process marks
|
||||
for mark in marks_qs:
|
||||
marks_data.append({
|
||||
'id': mark.id,
|
||||
'mark': mark.mark,
|
||||
'timestamp': mark.timestamp,
|
||||
'created_by': str(mark.created_by) if mark.created_by else "-",
|
||||
'can_edit': mark.can_edit(),
|
||||
})
|
||||
|
||||
processed.append({
|
||||
'id': objitem.id,
|
||||
|
||||
127
dbapp/mainapp/views/data_entry.py
Normal file
127
dbapp/mainapp/views/data_entry.py
Normal file
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
Data entry view for satellite points.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.db.models import Q
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.views import View
|
||||
|
||||
from ..models import ObjItem, Satellite
|
||||
|
||||
|
||||
class DataEntryView(LoginRequiredMixin, View):
|
||||
"""
|
||||
View for data entry form with Tabulator table.
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
# Get satellites that have points
|
||||
satellites = Satellite.objects.filter(
|
||||
parameters__objitem__isnull=False
|
||||
).distinct().order_by('name')
|
||||
|
||||
context = {
|
||||
'satellites': satellites,
|
||||
"full_width_page": True
|
||||
}
|
||||
|
||||
return render(request, 'mainapp/data_entry.html', context)
|
||||
|
||||
|
||||
class SearchObjItemAPIView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API endpoint for searching ObjItem by name and coordinates.
|
||||
Returns closest matching ObjItem with all required data.
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
from django.contrib.gis.geos import Point
|
||||
from django.contrib.gis.db.models.functions import Distance
|
||||
|
||||
name = request.GET.get('name', '').strip()
|
||||
satellite_id = request.GET.get('satellite_id', '').strip()
|
||||
latitude = request.GET.get('latitude', '').strip()
|
||||
longitude = request.GET.get('longitude', '').strip()
|
||||
|
||||
if not name:
|
||||
return JsonResponse({'error': 'Name parameter is required'}, status=400)
|
||||
|
||||
# Build query
|
||||
query = Q(name__iexact=name)
|
||||
|
||||
# Add satellite filter if provided
|
||||
if satellite_id:
|
||||
try:
|
||||
sat_id = int(satellite_id)
|
||||
query &= Q(parameter_obj__id_satellite_id=sat_id)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Filter ObjItems with geo data
|
||||
query &= Q(geo_obj__coords__isnull=False)
|
||||
|
||||
# Get queryset
|
||||
objitems = ObjItem.objects.filter(query).select_related(
|
||||
'parameter_obj',
|
||||
'parameter_obj__id_satellite',
|
||||
'parameter_obj__polarization',
|
||||
'parameter_obj__modulation',
|
||||
'parameter_obj__standard',
|
||||
'geo_obj'
|
||||
).prefetch_related(
|
||||
'geo_obj__mirrors'
|
||||
)
|
||||
|
||||
# If coordinates provided, find closest point
|
||||
if latitude and longitude:
|
||||
try:
|
||||
lat = float(latitude.replace(',', '.'))
|
||||
lon = float(longitude.replace(',', '.'))
|
||||
point = Point(lon, lat, srid=4326)
|
||||
|
||||
# Order by distance and get closest
|
||||
objitem = objitems.annotate(
|
||||
distance=Distance('geo_obj__coords', point)
|
||||
).order_by('distance').first()
|
||||
except (ValueError, TypeError):
|
||||
# If coordinate parsing fails, just get first match
|
||||
objitem = objitems.first()
|
||||
else:
|
||||
# No coordinates provided, get first match
|
||||
objitem = objitems.first()
|
||||
|
||||
if not objitem:
|
||||
return JsonResponse({'found': False})
|
||||
|
||||
# Prepare response data
|
||||
data = {
|
||||
'found': True,
|
||||
'frequency': None,
|
||||
'freq_range': None,
|
||||
'bod_velocity': None,
|
||||
'modulation': None,
|
||||
'snr': None,
|
||||
'mirrors': None,
|
||||
}
|
||||
|
||||
# Get parameter data
|
||||
if hasattr(objitem, 'parameter_obj') and objitem.parameter_obj:
|
||||
param = objitem.parameter_obj
|
||||
data['frequency'] = param.frequency if param.frequency else None
|
||||
data['freq_range'] = param.freq_range if param.freq_range else None
|
||||
data['bod_velocity'] = param.bod_velocity if param.bod_velocity else None
|
||||
data['modulation'] = param.modulation.name if param.modulation else None
|
||||
data['snr'] = param.snr if param.snr else None
|
||||
|
||||
# Get mirrors data
|
||||
if hasattr(objitem, 'geo_obj') and objitem.geo_obj:
|
||||
mirrors = objitem.geo_obj.mirrors.all()
|
||||
if mirrors:
|
||||
data['mirrors'] = ', '.join([m.name for m in mirrors])
|
||||
|
||||
return JsonResponse(data)
|
||||
@@ -54,7 +54,25 @@ class AddTranspondersView(LoginRequiredMixin, FormMessageMixin, FormView):
|
||||
try:
|
||||
content = uploaded_file.read()
|
||||
# Передаем текущего пользователя в функцию парсинга
|
||||
parse_transponders_from_xml(BytesIO(content), self.request.user.customuser)
|
||||
stats = parse_transponders_from_xml(BytesIO(content), self.request.user.customuser)
|
||||
|
||||
# Формируем сообщение со статистикой
|
||||
stats_message = (
|
||||
f"<strong>Импорт завершён</strong><br>"
|
||||
f"Спутники: создано {stats['satellites_created']}, "
|
||||
f"обновлено {stats['satellites_updated']}, "
|
||||
f"пропущено {stats['satellites_skipped']}, "
|
||||
f"игнорировано {stats['satellites_ignored']}<br>"
|
||||
f"Транспондеры: создано {stats['transponders_created']}, "
|
||||
f"существующих {stats['transponders_existing']}"
|
||||
)
|
||||
|
||||
if stats['errors']:
|
||||
stats_message += f"<br><strong>Ошибок: {len(stats['errors'])}</strong>"
|
||||
messages.warning(self.request, stats_message, extra_tags='persistent')
|
||||
else:
|
||||
messages.success(self.request, stats_message, extra_tags='persistent')
|
||||
|
||||
except ValueError as e:
|
||||
messages.error(self.request, f"Ошибка при чтении таблиц: {e}")
|
||||
return redirect("mainapp:add_trans")
|
||||
@@ -78,6 +96,7 @@ class LoadExcelDataView(LoginRequiredMixin, FormMessageMixin, FormView):
|
||||
uploaded_file = self.request.FILES["file"]
|
||||
selected_sat = form.cleaned_data["sat_choice"]
|
||||
number = form.cleaned_data["number_input"]
|
||||
is_automatic = form.cleaned_data.get("is_automatic", False)
|
||||
|
||||
try:
|
||||
import io
|
||||
@@ -85,11 +104,27 @@ class LoadExcelDataView(LoginRequiredMixin, FormMessageMixin, FormView):
|
||||
df = pd.read_excel(io.BytesIO(uploaded_file.read()))
|
||||
if number > 0:
|
||||
df = df.head(number)
|
||||
result = fill_data_from_df(df, selected_sat, self.request.user.customuser)
|
||||
result = fill_data_from_df(df, selected_sat, self.request.user.customuser, is_automatic)
|
||||
|
||||
messages.success(
|
||||
self.request, f"Данные успешно загружены! Обработано строк: {result}"
|
||||
# Формируем сообщение об успехе
|
||||
if is_automatic:
|
||||
success_msg = f"Данные успешно загружены как автоматические! Добавлено точек: {result['added']}"
|
||||
else:
|
||||
success_msg = f"Данные успешно загружены! Создано источников: {result['new_sources']}, добавлено точек: {result['added']}"
|
||||
|
||||
if result['skipped'] > 0:
|
||||
success_msg += f", пропущено дубликатов: {result['skipped']}"
|
||||
|
||||
messages.success(self.request, success_msg)
|
||||
|
||||
# Показываем ошибки, если они есть
|
||||
if result['errors']:
|
||||
error_count = len(result['errors'])
|
||||
messages.warning(
|
||||
self.request,
|
||||
f"Обнаружено ошибок: {error_count}. Первые ошибки: " + "; ".join(result['errors'][:5])
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
messages.error(self.request, f"Ошибка при обработке файла: {str(e)}")
|
||||
|
||||
@@ -109,12 +144,34 @@ class LoadCsvDataView(LoginRequiredMixin, FormMessageMixin, FormView):
|
||||
|
||||
def form_valid(self, form):
|
||||
uploaded_file = self.request.FILES["file"]
|
||||
is_automatic = form.cleaned_data.get("is_automatic", False)
|
||||
|
||||
try:
|
||||
content = uploaded_file.read()
|
||||
if isinstance(content, bytes):
|
||||
content = content.decode("utf-8")
|
||||
|
||||
get_points_from_csv(content, self.request.user.customuser)
|
||||
result = get_points_from_csv(content, self.request.user.customuser, is_automatic)
|
||||
|
||||
# Формируем сообщение об успехе
|
||||
if is_automatic:
|
||||
success_msg = f"Данные успешно загружены как автоматические! Добавлено точек: {result['added']}"
|
||||
else:
|
||||
success_msg = f"Данные успешно загружены! Создано источников: {result['new_sources']}, добавлено точек: {result['added']}"
|
||||
|
||||
if result['skipped'] > 0:
|
||||
success_msg += f", пропущено дубликатов: {result['skipped']}"
|
||||
|
||||
messages.success(self.request, success_msg)
|
||||
|
||||
# Показываем ошибки, если они есть
|
||||
if result['errors']:
|
||||
error_count = len(result['errors'])
|
||||
messages.warning(
|
||||
self.request,
|
||||
f"Обнаружено ошибок: {error_count}. Первые ошибки: " + "; ".join(result['errors'][:5])
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
messages.error(self.request, f"Ошибка при обработке файла: {str(e)}")
|
||||
return redirect("mainapp:load_csv_data")
|
||||
|
||||
@@ -19,13 +19,120 @@ from mainapp.utils import calculate_mean_coords
|
||||
|
||||
class KubsatView(LoginRequiredMixin, FormView):
|
||||
"""Страница Кубсат с фильтрами и таблицей источников"""
|
||||
template_name = 'mainapp/kubsat.html'
|
||||
template_name = 'mainapp/kubsat_tabs.html'
|
||||
form_class = KubsatFilterForm
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['full_width_page'] = True
|
||||
|
||||
# Добавляем данные для вкладки заявок
|
||||
from mainapp.models import SourceRequest, Satellite
|
||||
|
||||
# Список спутников для формы создания заявки
|
||||
context['satellites'] = Satellite.objects.all().order_by('name')
|
||||
|
||||
requests_qs = SourceRequest.objects.select_related(
|
||||
'source', 'source__info', 'source__ownership',
|
||||
'satellite',
|
||||
'created_by__user', 'updated_by__user'
|
||||
).prefetch_related(
|
||||
'source__source_objitems__parameter_obj__modulation'
|
||||
).order_by('-created_at')
|
||||
|
||||
# Фильтры для заявок
|
||||
status = self.request.GET.get('status')
|
||||
if status:
|
||||
requests_qs = requests_qs.filter(status=status)
|
||||
|
||||
priority = self.request.GET.get('priority')
|
||||
if priority:
|
||||
requests_qs = requests_qs.filter(priority=priority)
|
||||
|
||||
# Добавляем данные источника к каждой заявке
|
||||
requests_list = []
|
||||
for req in requests_qs[:100]:
|
||||
# Получаем данные из первой точки источника
|
||||
objitem_name = '-'
|
||||
modulation = '-'
|
||||
symbol_rate = '-'
|
||||
|
||||
if req.source:
|
||||
first_objitem = req.source.source_objitems.select_related(
|
||||
'parameter_obj__modulation'
|
||||
).order_by('geo_obj__timestamp').first()
|
||||
|
||||
if first_objitem:
|
||||
objitem_name = first_objitem.name or '-'
|
||||
if first_objitem.parameter_obj:
|
||||
if first_objitem.parameter_obj.modulation:
|
||||
modulation = first_objitem.parameter_obj.modulation.name
|
||||
if first_objitem.parameter_obj.bod_velocity and first_objitem.parameter_obj.bod_velocity > 0:
|
||||
symbol_rate = str(int(first_objitem.parameter_obj.bod_velocity))
|
||||
|
||||
# Добавляем атрибуты к объекту заявки
|
||||
req.objitem_name = objitem_name
|
||||
req.modulation = modulation
|
||||
req.symbol_rate = symbol_rate
|
||||
requests_list.append(req)
|
||||
|
||||
context['requests'] = requests_list
|
||||
|
||||
# Сериализуем заявки в JSON для Tabulator
|
||||
import json
|
||||
from django.utils import timezone
|
||||
|
||||
requests_json_data = []
|
||||
for req in requests_list:
|
||||
# Конвертируем даты в локальный часовой пояс для отображения
|
||||
planned_at_local = None
|
||||
planned_at_iso = None
|
||||
if req.planned_at:
|
||||
planned_at_local = timezone.localtime(req.planned_at)
|
||||
planned_at_iso = planned_at_local.isoformat()
|
||||
|
||||
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(),
|
||||
# Даты в ISO формате для правильной сортировки
|
||||
'request_date': req.request_date.isoformat() if req.request_date else None,
|
||||
'card_date': req.card_date.isoformat() if req.card_date else None,
|
||||
'planned_at': planned_at_iso,
|
||||
# Отформатированные даты для отображения
|
||||
'request_date_display': req.request_date.strftime('%d.%m.%Y') if req.request_date else '-',
|
||||
'card_date_display': req.card_date.strftime('%d.%m.%Y') if req.card_date else '-',
|
||||
'planned_at_display': (
|
||||
planned_at_local.strftime('%d.%m.%Y') if planned_at_local and planned_at_local.hour == 0 and planned_at_local.minute == 0
|
||||
else planned_at_local.strftime('%d.%m.%Y %H:%M') if planned_at_local
|
||||
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,
|
||||
'coords_object_lat': float(req.coords_object.y) if req.coords_object else None,
|
||||
'coords_object_lon': float(req.coords_object.x) if req.coords_object else None,
|
||||
'comment': req.comment or '',
|
||||
})
|
||||
context['requests_json'] = json.dumps(requests_json_data, ensure_ascii=False)
|
||||
|
||||
context['status_choices'] = SourceRequest.STATUS_CHOICES
|
||||
context['priority_choices'] = SourceRequest.PRIORITY_CHOICES
|
||||
context['current_status'] = status or ''
|
||||
context['current_priority'] = priority or ''
|
||||
context['search_query'] = self.request.GET.get('search', '')
|
||||
|
||||
# Если форма была отправлена, применяем фильтры
|
||||
if self.request.GET:
|
||||
form = self.form_class(self.request.GET)
|
||||
@@ -35,14 +142,27 @@ class KubsatView(LoginRequiredMixin, FormView):
|
||||
date_to = form.cleaned_data.get('date_to')
|
||||
has_date_filter = bool(date_from or date_to)
|
||||
|
||||
objitem_count = form.cleaned_data.get('objitem_count')
|
||||
objitem_count_min = form.cleaned_data.get('objitem_count_min')
|
||||
objitem_count_max = form.cleaned_data.get('objitem_count_max')
|
||||
sources_with_date_info = []
|
||||
for source in sources:
|
||||
# Get latest request info for this source
|
||||
latest_request = source.source_requests.order_by('-created_at').first()
|
||||
requests_count = source.source_requests.count()
|
||||
|
||||
source_data = {
|
||||
'source': source,
|
||||
'objitems_data': [],
|
||||
'has_lyngsat': False,
|
||||
'lyngsat_id': None
|
||||
'lyngsat_id': None,
|
||||
'has_request': latest_request is not None,
|
||||
'request_status': latest_request.get_status_display() if latest_request else None,
|
||||
'request_status_raw': latest_request.status if latest_request else None,
|
||||
'gso_success': latest_request.gso_success if latest_request else None,
|
||||
'kubsat_success': latest_request.kubsat_success if latest_request else None,
|
||||
'planned_at': latest_request.planned_at if latest_request else None,
|
||||
'requests_count': requests_count,
|
||||
'average_coords': None, # Будет рассчитано после сбора точек
|
||||
}
|
||||
|
||||
for objitem in source.source_objitems.all():
|
||||
@@ -83,11 +203,31 @@ class KubsatView(LoginRequiredMixin, FormView):
|
||||
|
||||
# Применяем фильтр по количеству точек (если задан)
|
||||
include_source = True
|
||||
if objitem_count:
|
||||
if objitem_count == '1':
|
||||
include_source = (filtered_count == 1)
|
||||
elif objitem_count == '2+':
|
||||
include_source = (filtered_count >= 2)
|
||||
if objitem_count_min is not None and filtered_count < objitem_count_min:
|
||||
include_source = False
|
||||
if objitem_count_max is not None and filtered_count > objitem_count_max:
|
||||
include_source = False
|
||||
|
||||
# Сортируем точки по дате ГЛ перед расчётом усреднённых координат
|
||||
source_data['objitems_data'].sort(
|
||||
key=lambda x: x['geo_date'] if x['geo_date'] else datetime.min.date()
|
||||
)
|
||||
|
||||
# Рассчитываем усреднённые координаты из отфильтрованных точек
|
||||
if source_data['objitems_data']:
|
||||
avg_coords = None
|
||||
for objitem_info in source_data['objitems_data']:
|
||||
objitem = objitem_info['objitem']
|
||||
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))
|
||||
if avg_coords is None:
|
||||
avg_coords = coord
|
||||
else:
|
||||
avg_coords, _ = calculate_mean_coords(avg_coords, coord)
|
||||
if avg_coords:
|
||||
source_data['average_coords'] = avg_coords
|
||||
source_data['avg_lat'] = avg_coords[1]
|
||||
source_data['avg_lon'] = avg_coords[0]
|
||||
|
||||
if source_data['objitems_data'] and include_source:
|
||||
sources_with_date_info.append(source_data)
|
||||
@@ -99,12 +239,17 @@ class KubsatView(LoginRequiredMixin, FormView):
|
||||
|
||||
def apply_filters(self, filters):
|
||||
"""Применяет фильтры к queryset Source"""
|
||||
from mainapp.models import SourceRequest
|
||||
from django.db.models import Subquery, OuterRef, Exists
|
||||
|
||||
queryset = Source.objects.select_related('info', 'ownership').prefetch_related(
|
||||
'source_objitems__parameter_obj__id_satellite',
|
||||
'source_objitems__parameter_obj__polarization',
|
||||
'source_objitems__parameter_obj__modulation',
|
||||
'source_objitems__transponder__sat_id',
|
||||
'source_objitems__lyngsat_source'
|
||||
'source_objitems__lyngsat_source',
|
||||
'source_objitems__geo_obj',
|
||||
'source_requests'
|
||||
).annotate(objitem_count=Count('source_objitems'))
|
||||
|
||||
# Фильтр по спутникам
|
||||
@@ -159,15 +304,47 @@ class KubsatView(LoginRequiredMixin, FormView):
|
||||
if filters.get('object_ownership'):
|
||||
queryset = queryset.filter(ownership__in=filters['object_ownership'])
|
||||
|
||||
# Фильтр по количеству ObjItem
|
||||
objitem_count = filters.get('objitem_count')
|
||||
if objitem_count == '1':
|
||||
queryset = queryset.filter(objitem_count=1)
|
||||
elif objitem_count == '2+':
|
||||
queryset = queryset.filter(objitem_count__gte=2)
|
||||
# Фильтр по количеству ObjItem (диапазон)
|
||||
objitem_count_min = filters.get('objitem_count_min')
|
||||
objitem_count_max = filters.get('objitem_count_max')
|
||||
|
||||
# Фиктивные фильтры (пока не применяются)
|
||||
# has_plans, success_1, success_2, date_from, date_to
|
||||
if objitem_count_min is not None:
|
||||
queryset = queryset.filter(objitem_count__gte=objitem_count_min)
|
||||
if objitem_count_max is not None:
|
||||
queryset = queryset.filter(objitem_count__lte=objitem_count_max)
|
||||
|
||||
# Фильтр по наличию планов (заявок со статусом 'planned')
|
||||
has_plans = filters.get('has_plans')
|
||||
if has_plans == 'yes':
|
||||
queryset = queryset.filter(
|
||||
source_requests__status='planned'
|
||||
).distinct()
|
||||
elif has_plans == 'no':
|
||||
queryset = queryset.exclude(
|
||||
source_requests__status='planned'
|
||||
).distinct()
|
||||
|
||||
# Фильтр по ГСО успешно
|
||||
success_1 = filters.get('success_1')
|
||||
if success_1 == 'yes':
|
||||
queryset = queryset.filter(
|
||||
source_requests__gso_success=True
|
||||
).distinct()
|
||||
elif success_1 == 'no':
|
||||
queryset = queryset.filter(
|
||||
source_requests__gso_success=False
|
||||
).distinct()
|
||||
|
||||
# Фильтр по Кубсат успешно
|
||||
success_2 = filters.get('success_2')
|
||||
if success_2 == 'yes':
|
||||
queryset = queryset.filter(
|
||||
source_requests__kubsat_success=True
|
||||
).distinct()
|
||||
elif success_2 == 'no':
|
||||
queryset = queryset.filter(
|
||||
source_requests__kubsat_success=False
|
||||
).distinct()
|
||||
|
||||
return queryset.distinct()
|
||||
|
||||
@@ -268,6 +445,11 @@ class KubsatExportView(LoginRequiredMixin, FormView):
|
||||
source = data['source']
|
||||
objitems_list = data['objitems']
|
||||
|
||||
# Сортируем точки по дате ГЛ перед расчётом
|
||||
objitems_list.sort(
|
||||
key=lambda x: x.geo_obj.timestamp if x.geo_obj and x.geo_obj.timestamp else datetime.min
|
||||
)
|
||||
|
||||
# Рассчитываем инкрементальное среднее координат из оставшихся точек
|
||||
average_coords = None
|
||||
for objitem in objitems_list:
|
||||
@@ -411,3 +593,162 @@ class KubsatExportView(LoginRequiredMixin, FormView):
|
||||
response['Content-Disposition'] = f'attachment; filename="kubsat_{datetime.now().strftime("%Y%m%d")}.xlsx"'
|
||||
|
||||
return response
|
||||
|
||||
|
||||
class KubsatCreateRequestsView(LoginRequiredMixin, FormView):
|
||||
"""Массовое создание заявок из отфильтрованных данных"""
|
||||
form_class = KubsatFilterForm
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
import json
|
||||
from django.http import JsonResponse
|
||||
from mainapp.models import SourceRequest, CustomUser
|
||||
|
||||
# Получаем список ID точек (ObjItem) из POST
|
||||
objitem_ids = request.POST.getlist('objitem_ids')
|
||||
|
||||
if not objitem_ids:
|
||||
return JsonResponse({'success': False, 'error': 'Нет данных для создания заявок'}, status=400)
|
||||
|
||||
# Получаем ObjItem с их источниками
|
||||
objitems = ObjItem.objects.filter(id__in=objitem_ids).select_related(
|
||||
'source',
|
||||
'geo_obj'
|
||||
)
|
||||
|
||||
# Группируем ObjItem по Source
|
||||
sources_objitems = {}
|
||||
for objitem in objitems:
|
||||
if objitem.source:
|
||||
if objitem.source.id not in sources_objitems:
|
||||
sources_objitems[objitem.source.id] = {
|
||||
'source': objitem.source,
|
||||
'objitems': []
|
||||
}
|
||||
sources_objitems[objitem.source.id]['objitems'].append(objitem)
|
||||
|
||||
# Получаем CustomUser для текущего пользователя
|
||||
try:
|
||||
custom_user = CustomUser.objects.get(user=request.user)
|
||||
except CustomUser.DoesNotExist:
|
||||
custom_user = None
|
||||
|
||||
created_count = 0
|
||||
errors = []
|
||||
|
||||
for source_id, data in sources_objitems.items():
|
||||
source = data['source']
|
||||
objitems_list = data['objitems']
|
||||
|
||||
# Сортируем точки по дате ГЛ перед расчётом
|
||||
objitems_list.sort(
|
||||
key=lambda x: x.geo_obj.timestamp if x.geo_obj and x.geo_obj.timestamp else datetime.min
|
||||
)
|
||||
|
||||
# Рассчитываем усреднённые координаты из выбранных точек
|
||||
average_coords = None
|
||||
points_with_coords = 0
|
||||
|
||||
for objitem in objitems_list:
|
||||
if hasattr(objitem, 'geo_obj') and objitem.geo_obj and objitem.geo_obj.coords:
|
||||
coord = (objitem.geo_obj.coords.x, objitem.geo_obj.coords.y)
|
||||
points_with_coords += 1
|
||||
|
||||
if average_coords is None:
|
||||
average_coords = coord
|
||||
else:
|
||||
average_coords, _ = calculate_mean_coords(average_coords, coord)
|
||||
|
||||
# Создаём Point объект если есть координаты
|
||||
coords_point = None
|
||||
if average_coords:
|
||||
coords_point = Point(average_coords[0], average_coords[1], srid=4326)
|
||||
|
||||
try:
|
||||
# Создаём новую заявку со статусом "planned"
|
||||
source_request = SourceRequest.objects.create(
|
||||
source=source,
|
||||
status='planned',
|
||||
priority='medium',
|
||||
coords=coords_point,
|
||||
points_count=points_with_coords,
|
||||
created_by=custom_user,
|
||||
updated_by=custom_user,
|
||||
comment=f'Создано из Кубсат. Точек: {len(objitems_list)}'
|
||||
)
|
||||
created_count += 1
|
||||
except Exception as e:
|
||||
errors.append(f'Источник #{source_id}: {str(e)}')
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'created_count': created_count,
|
||||
'total_sources': len(sources_objitems),
|
||||
'errors': errors
|
||||
})
|
||||
|
||||
|
||||
class KubsatRecalculateCoordsView(LoginRequiredMixin, FormView):
|
||||
"""API для пересчёта усреднённых координат по списку ObjItem ID"""
|
||||
form_class = KubsatFilterForm
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
import json
|
||||
from django.http import JsonResponse
|
||||
|
||||
# Получаем список ID точек (ObjItem) из POST
|
||||
objitem_ids = request.POST.getlist('objitem_ids')
|
||||
|
||||
if not objitem_ids:
|
||||
return JsonResponse({'success': False, 'error': 'Нет данных для расчёта'}, status=400)
|
||||
|
||||
# Получаем ObjItem с их источниками, сортируем по дате ГЛ
|
||||
objitems = ObjItem.objects.filter(id__in=objitem_ids).select_related(
|
||||
'source',
|
||||
'geo_obj'
|
||||
).order_by('geo_obj__timestamp') # Сортировка по дате ГЛ
|
||||
|
||||
# Группируем ObjItem по Source
|
||||
sources_objitems = {}
|
||||
for objitem in objitems:
|
||||
if objitem.source:
|
||||
if objitem.source.id not in sources_objitems:
|
||||
sources_objitems[objitem.source.id] = []
|
||||
sources_objitems[objitem.source.id].append(objitem)
|
||||
|
||||
# Рассчитываем усреднённые координаты для каждого источника
|
||||
results = {}
|
||||
for source_id, objitems_list in sources_objitems.items():
|
||||
# Сортируем по дате ГЛ (на случай если порядок сбился)
|
||||
objitems_list.sort(key=lambda x: x.geo_obj.timestamp if x.geo_obj and x.geo_obj.timestamp else datetime.min)
|
||||
|
||||
average_coords = None
|
||||
points_count = 0
|
||||
|
||||
for objitem in objitems_list:
|
||||
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))
|
||||
points_count += 1
|
||||
|
||||
if average_coords is None:
|
||||
average_coords = coord
|
||||
else:
|
||||
average_coords, _ = calculate_mean_coords(average_coords, coord)
|
||||
|
||||
if average_coords:
|
||||
results[str(source_id)] = {
|
||||
'avg_lon': average_coords[0],
|
||||
'avg_lat': average_coords[1],
|
||||
'points_count': points_count
|
||||
}
|
||||
else:
|
||||
results[str(source_id)] = {
|
||||
'avg_lon': None,
|
||||
'avg_lat': None,
|
||||
'points_count': 0
|
||||
}
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'results': results
|
||||
})
|
||||
|
||||
@@ -11,7 +11,7 @@ from django.shortcuts import redirect, render
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views import View
|
||||
|
||||
from ..clusters import get_clusters
|
||||
# from ..clusters import get_clusters
|
||||
from ..mixins import RoleRequiredMixin
|
||||
from ..models import ObjItem
|
||||
|
||||
@@ -154,7 +154,7 @@ class ShowSourcesMapView(LoginRequiredMixin, View):
|
||||
points.append(
|
||||
{
|
||||
"point": (coords.x, coords.y), # (lon, lat)
|
||||
"source_id": f"Источник #{source.id}",
|
||||
"source_id": f"Объект #{source.id}",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -232,7 +232,7 @@ class ShowSourceWithPointsMapView(LoginRequiredMixin, View):
|
||||
"parameter_obj", "geo_obj"
|
||||
).all()
|
||||
|
||||
# Собираем все точки ГЛ в одну группу
|
||||
# Собираем все точки ГЛ в одну группу с сортировкой по времени
|
||||
all_gl_points = []
|
||||
for obj in gl_points:
|
||||
if (
|
||||
@@ -250,9 +250,13 @@ class ShowSourceWithPointsMapView(LoginRequiredMixin, View):
|
||||
"point": (obj.geo_obj.coords.x, obj.geo_obj.coords.y),
|
||||
"name": obj.name,
|
||||
"frequency": f"{param.frequency} [{param.freq_range}] МГц",
|
||||
"timestamp": obj.geo_obj.timestamp.isoformat() if obj.geo_obj.timestamp else None,
|
||||
}
|
||||
)
|
||||
|
||||
# Сортируем точки по времени (от старой к новой)
|
||||
all_gl_points.sort(key=lambda x: x["timestamp"] if x["timestamp"] else "")
|
||||
|
||||
# Добавляем все точки ГЛ одним цветом (красный)
|
||||
if all_gl_points:
|
||||
groups.append(
|
||||
@@ -418,19 +422,41 @@ class ShowSourceAveragingStepsMapView(LoginRequiredMixin, View):
|
||||
return render(request, "mainapp/source_averaging_map.html", context)
|
||||
|
||||
|
||||
class ClusterTestView(LoginRequiredMixin, View):
|
||||
"""Test view for clustering functionality."""
|
||||
class MultiSourcesPlaybackMapView(LoginRequiredMixin, View):
|
||||
"""View for displaying animated playback of multiple sources on map."""
|
||||
|
||||
def get(self, request):
|
||||
objs = ObjItem.objects.filter(
|
||||
name__icontains="! Astra 4A 12654,040 [1,962] МГц H"
|
||||
)
|
||||
coords = []
|
||||
for obj in objs:
|
||||
if hasattr(obj, "geo_obj") and obj.geo_obj and obj.geo_obj.coords:
|
||||
coords.append(
|
||||
(obj.geo_obj.coords.coords[1], obj.geo_obj.coords.coords[0])
|
||||
)
|
||||
get_clusters(coords)
|
||||
from ..models import Source
|
||||
|
||||
return JsonResponse({"success": "ок"})
|
||||
ids = request.GET.get("ids", "")
|
||||
|
||||
if not ids:
|
||||
return redirect("mainapp:source_list")
|
||||
|
||||
id_list = [int(x) for x in ids.split(",") if x.isdigit()]
|
||||
if not id_list:
|
||||
return redirect("mainapp:source_list")
|
||||
|
||||
context = {
|
||||
"source_ids": ",".join(str(x) for x in id_list),
|
||||
"source_count": len(id_list),
|
||||
}
|
||||
return render(request, "mainapp/multi_sources_playback_map.html", context)
|
||||
|
||||
|
||||
# class ClusterTestView(LoginRequiredMixin, View):
|
||||
# """Test view for clustering functionality."""
|
||||
|
||||
# def get(self, request):
|
||||
# objs = ObjItem.objects.filter(
|
||||
# name__icontains="! Astra 4A 12654,040 [1,962] МГц H"
|
||||
# )
|
||||
# coords = []
|
||||
# for obj in objs:
|
||||
# if hasattr(obj, "geo_obj") and obj.geo_obj and obj.geo_obj.coords:
|
||||
# coords.append(
|
||||
# (obj.geo_obj.coords.coords[1], obj.geo_obj.coords.coords[0])
|
||||
# )
|
||||
# get_clusters(coords)
|
||||
|
||||
# return JsonResponse({"success": "ок"})
|
||||
|
||||
@@ -1,312 +1,536 @@
|
||||
"""
|
||||
Views для управления отметками объектов.
|
||||
Views для управления отметками сигналов (привязаны к TechAnalyze).
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import timedelta
|
||||
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.db.models import Prefetch
|
||||
from django.core.paginator import Paginator
|
||||
from django.db import transaction
|
||||
from django.db.models import Count, Max, Min, Prefetch, Q
|
||||
from django.http import JsonResponse
|
||||
from django.views.generic import ListView, View
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.shortcuts import render, get_object_or_404
|
||||
from django.utils import timezone
|
||||
from django.views import View
|
||||
|
||||
from mainapp.models import Source, ObjectMark, CustomUser, Satellite
|
||||
from mainapp.models import (
|
||||
TechAnalyze,
|
||||
ObjectMark,
|
||||
CustomUser,
|
||||
Satellite,
|
||||
Polarization,
|
||||
Modulation,
|
||||
Standard,
|
||||
)
|
||||
|
||||
|
||||
class ObjectMarksListView(LoginRequiredMixin, ListView):
|
||||
class SignalMarksView(LoginRequiredMixin, View):
|
||||
"""
|
||||
Представление списка источников с отметками.
|
||||
Главное представление для работы с отметками сигналов.
|
||||
Содержит две вкладки: история отметок и проставление новых.
|
||||
"""
|
||||
model = Source
|
||||
template_name = "mainapp/object_marks.html"
|
||||
context_object_name = "sources"
|
||||
|
||||
def get_paginate_by(self, queryset):
|
||||
"""Получить количество элементов на странице из параметров запроса"""
|
||||
from mainapp.utils import parse_pagination_params
|
||||
_, items_per_page = parse_pagination_params(self.request, default_per_page=50)
|
||||
return items_per_page
|
||||
def get(self, request):
|
||||
satellites = Satellite.objects.filter(
|
||||
tech_analyzes__isnull=False
|
||||
).distinct().order_by('name')
|
||||
|
||||
def get_queryset(self):
|
||||
"""Получить queryset с предзагруженными связанными данными"""
|
||||
from django.db.models import Count, Max, Min
|
||||
satellite_id = request.GET.get('satellite_id')
|
||||
selected_satellite = None
|
||||
|
||||
if satellite_id:
|
||||
try:
|
||||
selected_satellite = Satellite.objects.get(id=satellite_id)
|
||||
except Satellite.DoesNotExist:
|
||||
pass
|
||||
|
||||
# Справочники для модального окна создания теханализа
|
||||
polarizations = Polarization.objects.all().order_by('name')
|
||||
modulations = Modulation.objects.all().order_by('name')
|
||||
standards = Standard.objects.all().order_by('name')
|
||||
|
||||
context = {
|
||||
'satellites': satellites,
|
||||
'selected_satellite': selected_satellite,
|
||||
'selected_satellite_id': int(satellite_id) if satellite_id and satellite_id.isdigit() else None,
|
||||
'full_width_page': True,
|
||||
'polarizations': polarizations,
|
||||
'modulations': modulations,
|
||||
'standards': standards,
|
||||
}
|
||||
|
||||
return render(request, 'mainapp/signal_marks.html', context)
|
||||
|
||||
|
||||
class SignalMarksHistoryAPIView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API для получения истории отметок с фиксированными 15 колонками.
|
||||
Делит выбранный временной диапазон на 15 равных периодов.
|
||||
"""
|
||||
|
||||
NUM_COLUMNS = 15 # Фиксированное количество колонок
|
||||
|
||||
def get(self, request):
|
||||
from datetime import datetime
|
||||
from django.utils.dateparse import parse_date
|
||||
|
||||
satellite_id = request.GET.get('satellite_id')
|
||||
date_from = request.GET.get('date_from')
|
||||
date_to = request.GET.get('date_to')
|
||||
page = int(request.GET.get('page', 1))
|
||||
size = int(request.GET.get('size', 50))
|
||||
|
||||
# Проверяем, выбран ли спутник
|
||||
satellite_id = self.request.GET.get('satellite_id')
|
||||
if not satellite_id:
|
||||
# Если спутник не выбран, возвращаем пустой queryset
|
||||
return Source.objects.none()
|
||||
return JsonResponse({'error': 'Не выбран спутник'}, status=400)
|
||||
|
||||
queryset = Source.objects.prefetch_related(
|
||||
'source_objitems',
|
||||
'source_objitems__parameter_obj',
|
||||
'source_objitems__parameter_obj__id_satellite',
|
||||
'source_objitems__parameter_obj__polarization',
|
||||
'source_objitems__parameter_obj__modulation',
|
||||
# Базовый queryset теханализов для спутника
|
||||
tech_analyzes = TechAnalyze.objects.filter(
|
||||
satellite_id=satellite_id
|
||||
).select_related(
|
||||
'polarization', 'modulation', 'standard'
|
||||
).order_by('frequency', 'name')
|
||||
|
||||
# Базовый фильтр отметок по спутнику
|
||||
marks_base_qs = ObjectMark.objects.filter(
|
||||
tech_analyze__satellite_id=satellite_id
|
||||
).select_related('created_by__user', 'tech_analyze')
|
||||
|
||||
# Определяем диапазон дат
|
||||
parsed_date_from = None
|
||||
parsed_date_to = None
|
||||
|
||||
if date_from:
|
||||
parsed_date_from = parse_date(date_from)
|
||||
if parsed_date_from:
|
||||
marks_base_qs = marks_base_qs.filter(timestamp__date__gte=parsed_date_from)
|
||||
|
||||
if date_to:
|
||||
parsed_date_to = parse_date(date_to)
|
||||
if parsed_date_to:
|
||||
marks_base_qs = marks_base_qs.filter(timestamp__date__lte=parsed_date_to)
|
||||
|
||||
# Если даты не указаны, берём из данных
|
||||
date_range = marks_base_qs.aggregate(
|
||||
min_date=Min('timestamp'),
|
||||
max_date=Max('timestamp')
|
||||
)
|
||||
|
||||
min_date = date_range['min_date']
|
||||
max_date = date_range['max_date']
|
||||
|
||||
if not min_date or not max_date:
|
||||
return JsonResponse({
|
||||
'periods': [],
|
||||
'data': [],
|
||||
'last_page': 1,
|
||||
'total': 0,
|
||||
'message': 'Нет отметок в выбранном диапазоне',
|
||||
})
|
||||
|
||||
# Используем указанные даты или данные из БД
|
||||
start_dt = datetime.combine(parsed_date_from, datetime.min.time()) if parsed_date_from else min_date
|
||||
end_dt = datetime.combine(parsed_date_to, datetime.max.time()) if parsed_date_to else max_date
|
||||
|
||||
# Делаем timezone-aware если нужно
|
||||
if timezone.is_naive(start_dt):
|
||||
start_dt = timezone.make_aware(start_dt)
|
||||
if timezone.is_naive(end_dt):
|
||||
end_dt = timezone.make_aware(end_dt)
|
||||
|
||||
# Вычисляем длительность периода
|
||||
total_duration = end_dt - start_dt
|
||||
period_duration = total_duration / self.NUM_COLUMNS
|
||||
|
||||
# Генерируем границы периодов
|
||||
periods = []
|
||||
for i in range(self.NUM_COLUMNS):
|
||||
period_start = start_dt + (period_duration * i)
|
||||
period_end = start_dt + (period_duration * (i + 1))
|
||||
periods.append({
|
||||
'start': period_start,
|
||||
'end': period_end,
|
||||
'label': self._format_period_label(period_start, period_end, total_duration),
|
||||
})
|
||||
|
||||
# Пагинация теханализов (size=0 означает "все записи")
|
||||
if size == 0:
|
||||
# Все записи без пагинации
|
||||
page_obj = tech_analyzes
|
||||
num_pages = 1
|
||||
total_count = tech_analyzes.count()
|
||||
else:
|
||||
paginator = Paginator(tech_analyzes, size)
|
||||
page_obj = paginator.get_page(page)
|
||||
num_pages = paginator.num_pages
|
||||
total_count = paginator.count
|
||||
|
||||
# Формируем данные
|
||||
data = []
|
||||
for ta in page_obj:
|
||||
row = {
|
||||
'id': ta.id,
|
||||
'name': ta.name,
|
||||
'marks': [],
|
||||
}
|
||||
|
||||
# Получаем все отметки для этого теханализа
|
||||
ta_marks = list(marks_base_qs.filter(tech_analyze=ta).order_by('-timestamp'))
|
||||
|
||||
# Для каждого периода находим последнюю отметку
|
||||
for period in periods:
|
||||
mark_in_period = None
|
||||
for mark in ta_marks:
|
||||
if period['start'] <= mark.timestamp < period['end']:
|
||||
mark_in_period = mark
|
||||
break # Берём первую (последнюю по времени, т.к. сортировка -timestamp)
|
||||
|
||||
if mark_in_period:
|
||||
# Конвертируем в локальное время (Europe/Moscow)
|
||||
local_time = timezone.localtime(mark_in_period.timestamp)
|
||||
row['marks'].append({
|
||||
'mark': mark_in_period.mark,
|
||||
'user': str(mark_in_period.created_by) if mark_in_period.created_by else '-',
|
||||
'time': local_time.strftime('%d.%m %H:%M'),
|
||||
})
|
||||
else:
|
||||
row['marks'].append(None)
|
||||
|
||||
data.append(row)
|
||||
|
||||
return JsonResponse({
|
||||
'periods': [p['label'] for p in periods],
|
||||
'data': data,
|
||||
'last_page': num_pages,
|
||||
'total': total_count,
|
||||
})
|
||||
|
||||
def _format_period_label(self, start, end, total_duration):
|
||||
"""Форматирует метку периода (диапазон) в зависимости от общей длительности."""
|
||||
# Конвертируем в локальное время
|
||||
local_start = timezone.localtime(start)
|
||||
local_end = timezone.localtime(end)
|
||||
total_days = total_duration.days
|
||||
|
||||
if total_days <= 1:
|
||||
# Показываем часы: "10:00<br>12:00"
|
||||
return f"{local_start.strftime('%H:%M')}<br>{local_end.strftime('%H:%M')}"
|
||||
elif total_days <= 7:
|
||||
# Показываем день и время с переносом
|
||||
if local_start.date() == local_end.date():
|
||||
# Один день: "01.12<br>10:00-14:00"
|
||||
return f"{local_start.strftime('%d.%m')}<br>{local_start.strftime('%H:%M')}-{local_end.strftime('%H:%M')}"
|
||||
else:
|
||||
# Разные дни: "01.12 10:00<br>02.12 10:00"
|
||||
return f"{local_start.strftime('%d.%m %H:%M')}<br>{local_end.strftime('%d.%m %H:%M')}"
|
||||
elif total_days <= 60:
|
||||
# Показываем дату: "01.12-05.12"
|
||||
return f"{local_start.strftime('%d.%m')}-{local_end.strftime('%d.%m')}"
|
||||
else:
|
||||
# Показываем месяц: "01.12.24-15.12.24"
|
||||
return f"{local_start.strftime('%d.%m.%y')}-{local_end.strftime('%d.%m.%y')}"
|
||||
|
||||
|
||||
class SignalMarksEntryAPIView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API для получения данных теханализов для проставления отметок.
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
satellite_id = request.GET.get('satellite_id')
|
||||
page = int(request.GET.get('page', 1))
|
||||
size_param = request.GET.get('size', '100')
|
||||
search = request.GET.get('search', '').strip()
|
||||
|
||||
# Обработка size: "true" означает "все записи", иначе число
|
||||
if size_param == 'true' or size_param == '0':
|
||||
size = 0 # Все записи
|
||||
else:
|
||||
try:
|
||||
size = int(size_param)
|
||||
except (ValueError, TypeError):
|
||||
size = 100
|
||||
|
||||
if not satellite_id:
|
||||
return JsonResponse({'error': 'Не выбран спутник'}, status=400)
|
||||
|
||||
# Базовый queryset
|
||||
tech_analyzes = TechAnalyze.objects.filter(
|
||||
satellite_id=satellite_id
|
||||
).select_related(
|
||||
'polarization', 'modulation', 'standard'
|
||||
).prefetch_related(
|
||||
Prefetch(
|
||||
'marks',
|
||||
queryset=ObjectMark.objects.select_related('created_by__user').order_by('-timestamp')
|
||||
queryset=ObjectMark.objects.select_related('created_by__user').order_by('-timestamp')[:1],
|
||||
to_attr='last_marks'
|
||||
)
|
||||
).annotate(
|
||||
mark_count=Count('marks'),
|
||||
last_mark_date=Max('marks__timestamp'),
|
||||
# Аннотации для сортировки по параметрам (берем минимальное значение из связанных объектов)
|
||||
min_frequency=Min('source_objitems__parameter_obj__frequency'),
|
||||
min_freq_range=Min('source_objitems__parameter_obj__freq_range'),
|
||||
min_bod_velocity=Min('source_objitems__parameter_obj__bod_velocity')
|
||||
).order_by('frequency', 'name')
|
||||
|
||||
# Поиск
|
||||
if search:
|
||||
tech_analyzes = tech_analyzes.filter(
|
||||
Q(name__icontains=search) |
|
||||
Q(id__icontains=search)
|
||||
)
|
||||
|
||||
# Фильтрация по выбранному спутнику (обязательно)
|
||||
queryset = queryset.filter(source_objitems__parameter_obj__id_satellite_id=satellite_id).distinct()
|
||||
# Пагинация (size=0 означает "все записи")
|
||||
if size == 0:
|
||||
page_obj = tech_analyzes
|
||||
num_pages = 1
|
||||
total_count = tech_analyzes.count()
|
||||
else:
|
||||
paginator = Paginator(tech_analyzes, size)
|
||||
page_obj = paginator.get_page(page)
|
||||
num_pages = paginator.num_pages
|
||||
total_count = paginator.count
|
||||
|
||||
# Фильтрация по статусу (есть/нет отметок)
|
||||
mark_status = self.request.GET.get('mark_status')
|
||||
if mark_status == 'with_marks':
|
||||
queryset = queryset.filter(mark_count__gt=0)
|
||||
elif mark_status == 'without_marks':
|
||||
queryset = queryset.filter(mark_count=0)
|
||||
# Формируем данные
|
||||
data = []
|
||||
for ta in page_obj:
|
||||
last_mark = ta.last_marks[0] if ta.last_marks else None
|
||||
|
||||
# Фильтрация по дате отметки
|
||||
date_from = self.request.GET.get('date_from')
|
||||
date_to = self.request.GET.get('date_to')
|
||||
if date_from:
|
||||
from django.utils.dateparse import parse_date
|
||||
parsed_date = parse_date(date_from)
|
||||
if parsed_date:
|
||||
queryset = queryset.filter(marks__timestamp__date__gte=parsed_date).distinct()
|
||||
if date_to:
|
||||
from django.utils.dateparse import parse_date
|
||||
parsed_date = parse_date(date_to)
|
||||
if parsed_date:
|
||||
queryset = queryset.filter(marks__timestamp__date__lte=parsed_date).distinct()
|
||||
# Проверяем, можно ли добавить новую отметку (прошло 5 минут)
|
||||
can_add_mark = True
|
||||
if last_mark and last_mark.timestamp:
|
||||
time_diff = timezone.now() - last_mark.timestamp
|
||||
can_add_mark = time_diff >= timedelta(minutes=5)
|
||||
|
||||
# Фильтрация по пользователям (мультивыбор)
|
||||
user_ids = self.request.GET.getlist('user_id')
|
||||
if user_ids:
|
||||
queryset = queryset.filter(marks__created_by_id__in=user_ids).distinct()
|
||||
data.append({
|
||||
'id': ta.id,
|
||||
'name': ta.name,
|
||||
'frequency': float(ta.frequency) if ta.frequency else 0,
|
||||
'freq_range': float(ta.freq_range) if ta.freq_range else 0,
|
||||
'polarization': ta.polarization.name if ta.polarization else '-',
|
||||
'bod_velocity': float(ta.bod_velocity) if ta.bod_velocity else 0,
|
||||
'modulation': ta.modulation.name if ta.modulation else '-',
|
||||
'standard': ta.standard.name if ta.standard else '-',
|
||||
'mark_count': ta.mark_count,
|
||||
'last_mark': {
|
||||
'mark': last_mark.mark,
|
||||
'timestamp': last_mark.timestamp.strftime('%d.%m.%Y %H:%M'),
|
||||
'user': str(last_mark.created_by) if last_mark.created_by else '-',
|
||||
} if last_mark else None,
|
||||
'can_add_mark': can_add_mark,
|
||||
})
|
||||
|
||||
# Поиск по имени объекта или ID
|
||||
search_query = self.request.GET.get('search', '').strip()
|
||||
if search_query:
|
||||
from django.db.models import Q
|
||||
return JsonResponse({
|
||||
'data': data,
|
||||
'last_page': num_pages,
|
||||
'total': total_count,
|
||||
})
|
||||
|
||||
|
||||
class SaveSignalMarksView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API для сохранения отметок сигналов.
|
||||
Принимает массив отметок и сохраняет их в базу.
|
||||
"""
|
||||
|
||||
def post(self, request):
|
||||
try:
|
||||
# Попытка поиска по ID
|
||||
source_id = int(search_query)
|
||||
queryset = queryset.filter(Q(id=source_id) | Q(source_objitems__name__icontains=search_query)).distinct()
|
||||
except ValueError:
|
||||
# Поиск только по имени
|
||||
queryset = queryset.filter(source_objitems__name__icontains=search_query).distinct()
|
||||
data = json.loads(request.body)
|
||||
marks = data.get('marks', [])
|
||||
|
||||
# Сортировка
|
||||
sort = self.request.GET.get('sort', '-id')
|
||||
allowed_sorts = [
|
||||
'id', '-id',
|
||||
'created_at', '-created_at',
|
||||
'last_mark_date', '-last_mark_date',
|
||||
'mark_count', '-mark_count',
|
||||
'frequency', '-frequency',
|
||||
'freq_range', '-freq_range',
|
||||
'bod_velocity', '-bod_velocity'
|
||||
]
|
||||
if not marks:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Нет данных для сохранения'
|
||||
}, status=400)
|
||||
|
||||
if sort in allowed_sorts:
|
||||
# Для сортировки по last_mark_date нужно обработать NULL значения
|
||||
if 'last_mark_date' in sort:
|
||||
from django.db.models import F
|
||||
from django.db.models.functions import Coalesce
|
||||
queryset = queryset.order_by(
|
||||
Coalesce(F('last_mark_date'), F('created_at')).desc() if sort.startswith('-') else Coalesce(F('last_mark_date'), F('created_at')).asc()
|
||||
# Получаем CustomUser
|
||||
custom_user = None
|
||||
if hasattr(request.user, 'customuser'):
|
||||
custom_user = request.user.customuser
|
||||
else:
|
||||
custom_user, _ = CustomUser.objects.get_or_create(user=request.user)
|
||||
|
||||
created_count = 0
|
||||
skipped_count = 0
|
||||
errors = []
|
||||
|
||||
with transaction.atomic():
|
||||
for item in marks:
|
||||
tech_analyze_id = item.get('tech_analyze_id')
|
||||
mark_value = item.get('mark')
|
||||
|
||||
if tech_analyze_id is None or mark_value is None:
|
||||
continue
|
||||
|
||||
try:
|
||||
tech_analyze = TechAnalyze.objects.get(id=tech_analyze_id)
|
||||
|
||||
# Проверяем, можно ли добавить отметку
|
||||
last_mark = tech_analyze.marks.order_by('-timestamp').first()
|
||||
if last_mark and last_mark.timestamp:
|
||||
time_diff = timezone.now() - last_mark.timestamp
|
||||
if time_diff < timedelta(minutes=5):
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
# Создаём отметку с текущим временем
|
||||
ObjectMark.objects.create(
|
||||
tech_analyze=tech_analyze,
|
||||
mark=mark_value,
|
||||
timestamp=timezone.now(),
|
||||
created_by=custom_user,
|
||||
)
|
||||
# Сортировка по частоте
|
||||
elif sort == 'frequency':
|
||||
queryset = queryset.order_by('min_frequency')
|
||||
elif sort == '-frequency':
|
||||
queryset = queryset.order_by('-min_frequency')
|
||||
# Сортировка по полосе
|
||||
elif sort == 'freq_range':
|
||||
queryset = queryset.order_by('min_freq_range')
|
||||
elif sort == '-freq_range':
|
||||
queryset = queryset.order_by('-min_freq_range')
|
||||
# Сортировка по бодовой скорости
|
||||
elif sort == 'bod_velocity':
|
||||
queryset = queryset.order_by('min_bod_velocity')
|
||||
elif sort == '-bod_velocity':
|
||||
queryset = queryset.order_by('-min_bod_velocity')
|
||||
else:
|
||||
queryset = queryset.order_by(sort)
|
||||
else:
|
||||
queryset = queryset.order_by('-id')
|
||||
created_count += 1
|
||||
|
||||
return queryset
|
||||
except TechAnalyze.DoesNotExist:
|
||||
errors.append(f'Теханализ {tech_analyze_id} не найден')
|
||||
except Exception as e:
|
||||
errors.append(f'Ошибка для {tech_analyze_id}: {str(e)}')
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Добавить дополнительные данные в контекст"""
|
||||
context = super().get_context_data(**kwargs)
|
||||
from mainapp.utils import parse_pagination_params
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'created': created_count,
|
||||
'skipped': skipped_count,
|
||||
'errors': errors if errors else None,
|
||||
})
|
||||
|
||||
# Все спутники для выбора
|
||||
context['satellites'] = Satellite.objects.filter(
|
||||
parameters__objitem__source__isnull=False
|
||||
).distinct().order_by('name')
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Неверный формат данных'
|
||||
}, status=400)
|
||||
except Exception as e:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}, status=500)
|
||||
|
||||
# Выбранный спутник
|
||||
satellite_id = self.request.GET.get('satellite_id')
|
||||
context['selected_satellite_id'] = int(satellite_id) if satellite_id and satellite_id.isdigit() else None
|
||||
|
||||
context['users'] = CustomUser.objects.select_related('user').filter(
|
||||
marks_created__isnull=False
|
||||
).distinct().order_by('user__username')
|
||||
class CreateTechAnalyzeView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API для создания нового теханализа из модального окна.
|
||||
"""
|
||||
|
||||
# Параметры пагинации
|
||||
page_number, items_per_page = parse_pagination_params(self.request, default_per_page=50)
|
||||
context['items_per_page'] = items_per_page
|
||||
context['available_items_per_page'] = [25, 50, 100, 200, 500]
|
||||
def post(self, request):
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
|
||||
# Параметры поиска и сортировки
|
||||
context['search_query'] = self.request.GET.get('search', '')
|
||||
context['sort'] = self.request.GET.get('sort', '-id')
|
||||
satellite_id = data.get('satellite_id')
|
||||
name = data.get('name', '').strip()
|
||||
|
||||
# Параметры фильтров для отображения в UI
|
||||
context['selected_users'] = [int(x) for x in self.request.GET.getlist('user_id') if x.isdigit()]
|
||||
context['filter_mark_status'] = self.request.GET.get('mark_status', '')
|
||||
context['filter_date_from'] = self.request.GET.get('date_from', '')
|
||||
context['filter_date_to'] = self.request.GET.get('date_to', '')
|
||||
if not satellite_id:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Не указан спутник'
|
||||
}, status=400)
|
||||
|
||||
# Полноэкранный режим
|
||||
context['full_width_page'] = True
|
||||
if not name:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Не указано имя'
|
||||
}, status=400)
|
||||
|
||||
# Добавить информацию о параметрах для каждого источника
|
||||
for source in context['sources']:
|
||||
# Получить первый объект для параметров (они должны быть одинаковыми)
|
||||
first_objitem = source.source_objitems.select_related(
|
||||
'parameter_obj',
|
||||
'parameter_obj__polarization',
|
||||
'parameter_obj__modulation'
|
||||
).first()
|
||||
# Проверяем уникальность имени
|
||||
if TechAnalyze.objects.filter(name=name).exists():
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': f'Теханализ с именем "{name}" уже существует'
|
||||
}, status=400)
|
||||
|
||||
if first_objitem:
|
||||
source.objitem_name = first_objitem.name if first_objitem.name else '-'
|
||||
try:
|
||||
satellite = Satellite.objects.get(id=satellite_id)
|
||||
except Satellite.DoesNotExist:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Спутник не найден'
|
||||
}, status=404)
|
||||
|
||||
# Получить параметры
|
||||
if first_objitem.parameter_obj:
|
||||
param = first_objitem.parameter_obj
|
||||
source.frequency = param.frequency if param.frequency else '-'
|
||||
source.freq_range = param.freq_range if param.freq_range else '-'
|
||||
source.polarization = param.polarization.name if param.polarization else '-'
|
||||
source.modulation = param.modulation.name if param.modulation else '-'
|
||||
source.bod_velocity = param.bod_velocity if param.bod_velocity else '-'
|
||||
else:
|
||||
source.frequency = '-'
|
||||
source.freq_range = '-'
|
||||
source.polarization = '-'
|
||||
source.modulation = '-'
|
||||
source.bod_velocity = '-'
|
||||
else:
|
||||
source.objitem_name = '-'
|
||||
source.frequency = '-'
|
||||
source.freq_range = '-'
|
||||
source.polarization = '-'
|
||||
source.modulation = '-'
|
||||
source.bod_velocity = '-'
|
||||
# Получаем или создаём справочные данные
|
||||
polarization_name = data.get('polarization', '').strip() or '-'
|
||||
polarization, _ = Polarization.objects.get_or_create(name=polarization_name)
|
||||
|
||||
# Проверка возможности редактирования отметок
|
||||
for mark in source.marks.all():
|
||||
mark.editable = mark.can_edit()
|
||||
modulation_name = data.get('modulation', '').strip() or '-'
|
||||
modulation, _ = Modulation.objects.get_or_create(name=modulation_name)
|
||||
|
||||
return context
|
||||
standard_name = data.get('standard', '').strip() or '-'
|
||||
standard, _ = Standard.objects.get_or_create(name=standard_name)
|
||||
|
||||
# Обработка числовых полей
|
||||
def parse_float(val):
|
||||
if val:
|
||||
try:
|
||||
return float(str(val).replace(',', '.'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return 0
|
||||
|
||||
# Получаем CustomUser
|
||||
custom_user = None
|
||||
if hasattr(request.user, 'customuser'):
|
||||
custom_user = request.user.customuser
|
||||
|
||||
# Создаём теханализ
|
||||
tech_analyze = TechAnalyze.objects.create(
|
||||
name=name,
|
||||
satellite=satellite,
|
||||
frequency=parse_float(data.get('frequency')),
|
||||
freq_range=parse_float(data.get('freq_range')),
|
||||
bod_velocity=parse_float(data.get('bod_velocity')),
|
||||
polarization=polarization,
|
||||
modulation=modulation,
|
||||
standard=standard,
|
||||
note=data.get('note', '').strip(),
|
||||
created_by=custom_user,
|
||||
)
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'tech_analyze': {
|
||||
'id': tech_analyze.id,
|
||||
'name': tech_analyze.name,
|
||||
'frequency': float(tech_analyze.frequency) if tech_analyze.frequency else 0,
|
||||
'freq_range': float(tech_analyze.freq_range) if tech_analyze.freq_range else 0,
|
||||
'polarization': polarization.name,
|
||||
'bod_velocity': float(tech_analyze.bod_velocity) if tech_analyze.bod_velocity else 0,
|
||||
'modulation': modulation.name,
|
||||
'standard': standard.name,
|
||||
}
|
||||
})
|
||||
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Неверный формат данных'
|
||||
}, status=400)
|
||||
except Exception as e:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}, status=500)
|
||||
|
||||
|
||||
# Оставляем старые views для обратной совместимости (редирект на новую страницу)
|
||||
class ObjectMarksListView(LoginRequiredMixin, View):
|
||||
"""Редирект на новую страницу отметок."""
|
||||
|
||||
def get(self, request):
|
||||
from django.shortcuts import redirect
|
||||
return redirect('mainapp:signal_marks')
|
||||
|
||||
|
||||
class AddObjectMarkView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API endpoint для добавления отметки источника.
|
||||
"""
|
||||
"""Устаревший endpoint - теперь используется SaveSignalMarksView."""
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
"""Создать новую отметку"""
|
||||
from datetime import timedelta
|
||||
from django.utils import timezone
|
||||
|
||||
source_id = request.POST.get('source_id')
|
||||
mark = request.POST.get('mark') == 'true'
|
||||
|
||||
if not source_id:
|
||||
return JsonResponse({'success': False, 'error': 'Не указан ID источника'}, status=400)
|
||||
|
||||
source = get_object_or_404(Source, pk=source_id)
|
||||
|
||||
# Проверить последнюю отметку источника
|
||||
last_mark = source.marks.first()
|
||||
if last_mark:
|
||||
time_diff = timezone.now() - last_mark.timestamp
|
||||
if time_diff < timedelta(minutes=5):
|
||||
minutes_left = 5 - int(time_diff.total_seconds() / 60)
|
||||
def post(self, request):
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': f'Нельзя добавить отметку. Подождите ещё {minutes_left} мин.'
|
||||
}, status=400)
|
||||
|
||||
# Получить или создать CustomUser для текущего пользователя
|
||||
custom_user, _ = CustomUser.objects.get_or_create(user=request.user)
|
||||
|
||||
# Создать отметку
|
||||
object_mark = ObjectMark.objects.create(
|
||||
source=source,
|
||||
mark=mark,
|
||||
created_by=custom_user
|
||||
)
|
||||
|
||||
# Обновляем дату последнего сигнала источника
|
||||
source.update_last_signal_at()
|
||||
source.save()
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'mark': {
|
||||
'id': object_mark.id,
|
||||
'mark': object_mark.mark,
|
||||
'timestamp': object_mark.timestamp.strftime('%d.%m.%Y %H:%M'),
|
||||
'created_by': str(object_mark.created_by) if object_mark.created_by else 'Неизвестно',
|
||||
'can_edit': object_mark.can_edit()
|
||||
}
|
||||
})
|
||||
'error': 'Этот endpoint устарел. Используйте /api/save-signal-marks/'
|
||||
}, status=410)
|
||||
|
||||
|
||||
class UpdateObjectMarkView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API endpoint для обновления отметки объекта (в течение 5 минут).
|
||||
"""
|
||||
"""Устаревший endpoint."""
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
"""Обновить существующую отметку"""
|
||||
mark_id = request.POST.get('mark_id')
|
||||
new_mark_value = request.POST.get('mark') == 'true'
|
||||
|
||||
if not mark_id:
|
||||
return JsonResponse({'success': False, 'error': 'Не указан ID отметки'}, status=400)
|
||||
|
||||
object_mark = get_object_or_404(ObjectMark, pk=mark_id)
|
||||
|
||||
# Проверить возможность редактирования
|
||||
if not object_mark.can_edit():
|
||||
def post(self, request):
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Время редактирования истекло (более 5 минут)'
|
||||
}, status=400)
|
||||
|
||||
# Обновить отметку
|
||||
object_mark.mark = new_mark_value
|
||||
object_mark.save()
|
||||
|
||||
# Обновляем дату последнего сигнала источника
|
||||
object_mark.source.update_last_signal_at()
|
||||
object_mark.source.save()
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'mark': {
|
||||
'id': object_mark.id,
|
||||
'mark': object_mark.mark,
|
||||
'timestamp': object_mark.timestamp.strftime('%d.%m.%Y %H:%M'),
|
||||
'created_by': str(object_mark.created_by) if object_mark.created_by else 'Неизвестно',
|
||||
'can_edit': object_mark.can_edit()
|
||||
}
|
||||
})
|
||||
'error': 'Этот endpoint устарел.'
|
||||
}, status=410)
|
||||
|
||||
@@ -14,7 +14,7 @@ from django.views.generic import CreateView, DeleteView, UpdateView
|
||||
|
||||
from ..forms import GeoForm, ObjItemForm, ParameterForm
|
||||
from ..mixins import CoordinateProcessingMixin, FormMessageMixin, RoleRequiredMixin
|
||||
from ..models import Geo, Modulation, ObjItem, ObjectMark, Polarization, Satellite
|
||||
from ..models import Geo, Modulation, ObjItem, Polarization, Satellite
|
||||
from ..utils import (
|
||||
format_coordinate,
|
||||
format_coords_display,
|
||||
@@ -53,20 +53,10 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
"""View for displaying a list of ObjItems with filtering and pagination."""
|
||||
|
||||
def get(self, request):
|
||||
satellites = (
|
||||
Satellite.objects.filter(parameters__objitem__isnull=False)
|
||||
.distinct()
|
||||
.only("id", "name")
|
||||
.order_by("name")
|
||||
)
|
||||
|
||||
selected_sat_id = request.GET.get("satellite_id")
|
||||
|
||||
# If no satellite is selected and no filters are applied, select the first satellite
|
||||
if not selected_sat_id and not request.GET.getlist("satellite_id"):
|
||||
first_satellite = satellites.first()
|
||||
if first_satellite:
|
||||
selected_sat_id = str(first_satellite.id)
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from django.contrib.gis.geos import Polygon
|
||||
from ..models import Standard
|
||||
|
||||
page_number, items_per_page = parse_pagination_params(request)
|
||||
sort_param = request.GET.get("sort", "-id")
|
||||
@@ -82,72 +72,21 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
search_query = request.GET.get("search")
|
||||
selected_modulations = request.GET.getlist("modulation")
|
||||
selected_polarizations = request.GET.getlist("polarization")
|
||||
selected_satellites = request.GET.getlist("satellite_id")
|
||||
has_kupsat = request.GET.get("has_kupsat")
|
||||
has_valid = request.GET.get("has_valid")
|
||||
selected_standards = request.GET.getlist("standard")
|
||||
selected_satellites = request.GET.getlist("satellite")
|
||||
selected_mirrors = request.GET.getlist("mirror")
|
||||
selected_complexes = request.GET.getlist("complex")
|
||||
date_from = request.GET.get("date_from")
|
||||
date_to = request.GET.get("date_to")
|
||||
polygon_coords = request.GET.get("polygon")
|
||||
|
||||
objects = ObjItem.objects.none()
|
||||
|
||||
if selected_satellites or selected_sat_id:
|
||||
if selected_sat_id and not selected_satellites:
|
||||
try:
|
||||
selected_sat_id_single = int(selected_sat_id)
|
||||
selected_satellites = [selected_sat_id_single]
|
||||
except ValueError:
|
||||
selected_satellites = []
|
||||
|
||||
if selected_satellites:
|
||||
# Create optimized prefetch for mirrors through geo_obj
|
||||
mirrors_prefetch = Prefetch(
|
||||
'geo_obj__mirrors',
|
||||
queryset=Satellite.objects.only('id', 'name').order_by('id')
|
||||
)
|
||||
|
||||
# Create optimized prefetch for marks (through source)
|
||||
marks_prefetch = Prefetch(
|
||||
'source__marks',
|
||||
queryset=ObjectMark.objects.select_related('created_by__user').order_by('-timestamp')
|
||||
)
|
||||
|
||||
objects = (
|
||||
ObjItem.objects.select_related(
|
||||
"geo_obj",
|
||||
"source",
|
||||
"updated_by__user",
|
||||
"created_by__user",
|
||||
"lyngsat_source",
|
||||
"parameter_obj",
|
||||
"parameter_obj__id_satellite",
|
||||
"parameter_obj__polarization",
|
||||
"parameter_obj__modulation",
|
||||
"parameter_obj__standard",
|
||||
"transponder",
|
||||
"transponder__sat_id",
|
||||
"transponder__polarization",
|
||||
)
|
||||
.prefetch_related(
|
||||
"parameter_obj__sigma_parameter",
|
||||
"parameter_obj__sigma_parameter__polarization",
|
||||
mirrors_prefetch,
|
||||
marks_prefetch,
|
||||
)
|
||||
.filter(parameter_obj__id_satellite_id__in=selected_satellites)
|
||||
)
|
||||
else:
|
||||
# Create optimized prefetch for mirrors through geo_obj
|
||||
mirrors_prefetch = Prefetch(
|
||||
'geo_obj__mirrors',
|
||||
queryset=Satellite.objects.only('id', 'name').order_by('id')
|
||||
)
|
||||
|
||||
# Create optimized prefetch for marks (through source)
|
||||
marks_prefetch = Prefetch(
|
||||
'source__marks',
|
||||
queryset=ObjectMark.objects.select_related('created_by__user').order_by('-timestamp')
|
||||
)
|
||||
|
||||
# Load all objects without satellite filter
|
||||
objects = ObjItem.objects.select_related(
|
||||
"geo_obj",
|
||||
"source",
|
||||
@@ -163,12 +102,10 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
"transponder__sat_id",
|
||||
"transponder__polarization",
|
||||
).prefetch_related(
|
||||
"parameter_obj__sigma_parameter",
|
||||
"parameter_obj__sigma_parameter__polarization",
|
||||
mirrors_prefetch,
|
||||
marks_prefetch,
|
||||
)
|
||||
|
||||
# Apply frequency filters
|
||||
if freq_min is not None and freq_min.strip() != "":
|
||||
try:
|
||||
freq_min_val = float(freq_min)
|
||||
@@ -186,6 +123,7 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Apply range filters
|
||||
if range_min is not None and range_min.strip() != "":
|
||||
try:
|
||||
range_min_val = float(range_min)
|
||||
@@ -203,6 +141,7 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Apply SNR filters
|
||||
if snr_min is not None and snr_min.strip() != "":
|
||||
try:
|
||||
snr_min_val = float(snr_min)
|
||||
@@ -216,6 +155,7 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Apply symbol rate filters
|
||||
if bod_min is not None and bod_min.strip() != "":
|
||||
try:
|
||||
bod_min_val = float(bod_min)
|
||||
@@ -233,30 +173,45 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Apply modulation filter
|
||||
if selected_modulations:
|
||||
objects = objects.filter(
|
||||
parameter_obj__modulation__id__in=selected_modulations
|
||||
)
|
||||
|
||||
# Apply polarization filter
|
||||
if selected_polarizations:
|
||||
objects = objects.filter(
|
||||
parameter_obj__polarization__id__in=selected_polarizations
|
||||
)
|
||||
|
||||
if has_kupsat == "1":
|
||||
objects = objects.filter(source__coords_kupsat__isnull=False)
|
||||
elif has_kupsat == "0":
|
||||
objects = objects.filter(source__coords_kupsat__isnull=True)
|
||||
# Apply standard filter
|
||||
if selected_standards:
|
||||
objects = objects.filter(
|
||||
parameter_obj__standard__id__in=selected_standards
|
||||
)
|
||||
|
||||
if has_valid == "1":
|
||||
objects = objects.filter(source__coords_valid__isnull=False)
|
||||
elif has_valid == "0":
|
||||
objects = objects.filter(source__coords_valid__isnull=True)
|
||||
# Apply satellite filter
|
||||
if selected_satellites:
|
||||
objects = objects.filter(
|
||||
parameter_obj__id_satellite__id__in=selected_satellites
|
||||
)
|
||||
|
||||
# Apply mirrors filter
|
||||
if selected_mirrors:
|
||||
objects = objects.filter(
|
||||
geo_obj__mirrors__id__in=selected_mirrors
|
||||
).distinct()
|
||||
|
||||
# Apply complex filter (location_place)
|
||||
if selected_complexes:
|
||||
objects = objects.filter(
|
||||
parameter_obj__id_satellite__location_place__in=selected_complexes
|
||||
)
|
||||
|
||||
# Date filter for geo_obj timestamp
|
||||
if date_from and date_from.strip():
|
||||
try:
|
||||
from datetime import datetime
|
||||
date_from_obj = datetime.strptime(date_from, "%Y-%m-%d")
|
||||
objects = objects.filter(geo_obj__timestamp__gte=date_from_obj)
|
||||
except (ValueError, TypeError):
|
||||
@@ -264,7 +219,6 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
|
||||
if date_to and date_to.strip():
|
||||
try:
|
||||
from datetime import datetime, timedelta
|
||||
date_to_obj = datetime.strptime(date_to, "%Y-%m-%d")
|
||||
# Add one day to include the entire end date
|
||||
date_to_obj = date_to_obj + timedelta(days=1)
|
||||
@@ -272,20 +226,27 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Filter by source type (lyngsat_source)
|
||||
has_source_type = request.GET.get("has_source_type")
|
||||
if has_source_type == "1":
|
||||
objects = objects.filter(lyngsat_source__isnull=False)
|
||||
elif has_source_type == "0":
|
||||
objects = objects.filter(lyngsat_source__isnull=True)
|
||||
# Filter by is_automatic
|
||||
is_automatic_filter = request.GET.get("is_automatic")
|
||||
if is_automatic_filter == "1":
|
||||
objects = objects.filter(is_automatic=True)
|
||||
elif is_automatic_filter == "0":
|
||||
objects = objects.filter(is_automatic=False)
|
||||
|
||||
# Filter by sigma (sigma parameters)
|
||||
has_sigma = request.GET.get("has_sigma")
|
||||
if has_sigma == "1":
|
||||
objects = objects.filter(parameter_obj__sigma_parameter__isnull=False)
|
||||
elif has_sigma == "0":
|
||||
objects = objects.filter(parameter_obj__sigma_parameter__isnull=True)
|
||||
# Apply polygon filter
|
||||
if polygon_coords:
|
||||
try:
|
||||
coords = json.loads(polygon_coords)
|
||||
if coords and len(coords) >= 3:
|
||||
# Ensure polygon is closed
|
||||
if coords[0] != coords[-1]:
|
||||
coords.append(coords[0])
|
||||
polygon = Polygon(coords, srid=4326)
|
||||
objects = objects.filter(geo_obj__coords__within=polygon)
|
||||
except (json.JSONDecodeError, ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Apply search filter
|
||||
if search_query:
|
||||
search_query = search_query.strip()
|
||||
if search_query:
|
||||
@@ -293,8 +254,6 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
models.Q(name__icontains=search_query)
|
||||
| models.Q(geo_obj__location__icontains=search_query)
|
||||
)
|
||||
else:
|
||||
selected_sat_id = None
|
||||
|
||||
objects = objects.annotate(
|
||||
first_param_freq=F("parameter_obj__frequency"),
|
||||
@@ -336,6 +295,8 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
"-polarization": "-first_param_pol_name",
|
||||
"modulation": "first_param_mod_name",
|
||||
"-modulation": "-first_param_mod_name",
|
||||
"is_automatic": "is_automatic",
|
||||
"-is_automatic": "-is_automatic",
|
||||
}
|
||||
|
||||
# Apply sorting if valid, otherwise use default
|
||||
@@ -425,19 +386,16 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
|
||||
source_type = "ТВ" if obj.lyngsat_source else "-"
|
||||
|
||||
has_sigma = False
|
||||
sigma_info = "-"
|
||||
if param:
|
||||
sigma_count = param.sigma_parameter.count()
|
||||
if sigma_count > 0:
|
||||
has_sigma = True
|
||||
first_sigma = param.sigma_parameter.first()
|
||||
if first_sigma:
|
||||
sigma_freq = format_frequency(first_sigma.transfer_frequency)
|
||||
sigma_range = format_frequency(first_sigma.freq_range)
|
||||
sigma_pol = first_sigma.polarization.name if first_sigma.polarization else "-"
|
||||
sigma_pol_short = sigma_pol[0] if sigma_pol and sigma_pol != "-" else "-"
|
||||
sigma_info = f"{sigma_freq}/{sigma_range}/{sigma_pol_short}"
|
||||
# Build mirrors display with clickable links
|
||||
mirrors_display = "-"
|
||||
if mirrors_list:
|
||||
mirrors_links = []
|
||||
for mirror in obj.geo_obj.mirrors.all():
|
||||
mirrors_links.append(
|
||||
f'<a href="#" class="text-decoration-underline" '
|
||||
f'onclick="showSatelliteModal({mirror.id}); return false;">{mirror.name}</a>'
|
||||
)
|
||||
mirrors_display = ", ".join(mirrors_links) if mirrors_links else "-"
|
||||
|
||||
processed_objects.append(
|
||||
{
|
||||
@@ -464,23 +422,40 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
"is_average": is_average,
|
||||
"source_type": source_type,
|
||||
"standard": standard_name,
|
||||
"has_sigma": has_sigma,
|
||||
"sigma_info": sigma_info,
|
||||
"mirrors": ", ".join(mirrors_list) if mirrors_list else "-",
|
||||
"mirrors_display": mirrors_display,
|
||||
"is_automatic": "Да" if obj.is_automatic else "Нет",
|
||||
"obj": obj,
|
||||
}
|
||||
)
|
||||
|
||||
modulations = Modulation.objects.all()
|
||||
polarizations = Polarization.objects.all()
|
||||
standards = Standard.objects.all()
|
||||
|
||||
# Get the new filter values
|
||||
has_source_type = request.GET.get("has_source_type")
|
||||
has_sigma = request.GET.get("has_sigma")
|
||||
# Get satellites for filter (only those used in parameters)
|
||||
satellites = (
|
||||
Satellite.objects.filter(parameters__isnull=False)
|
||||
.distinct()
|
||||
.only("id", "name")
|
||||
.order_by("name")
|
||||
)
|
||||
|
||||
# Get mirrors for filter (only those used in geo objects)
|
||||
mirrors = (
|
||||
Satellite.objects.filter(geo_mirrors__isnull=False)
|
||||
.distinct()
|
||||
.only("id", "name")
|
||||
.order_by("name")
|
||||
)
|
||||
|
||||
# Get complexes for filter
|
||||
complexes = [
|
||||
("kr", "КР"),
|
||||
("dv", "ДВ")
|
||||
]
|
||||
|
||||
context = {
|
||||
"satellites": satellites,
|
||||
"selected_satellite_id": selected_sat_id,
|
||||
"page_obj": page_obj,
|
||||
"processed_objects": processed_objects,
|
||||
"items_per_page": items_per_page,
|
||||
@@ -500,17 +475,26 @@ class ObjItemListView(LoginRequiredMixin, View):
|
||||
"selected_polarizations": [
|
||||
int(x) if isinstance(x, str) else x for x in selected_polarizations if (isinstance(x, int) or (isinstance(x, str) and x.isdigit()))
|
||||
],
|
||||
"selected_standards": [
|
||||
int(x) if isinstance(x, str) else x for x in selected_standards if (isinstance(x, int) or (isinstance(x, str) and x.isdigit()))
|
||||
],
|
||||
"selected_satellites": [
|
||||
int(x) if isinstance(x, str) else x for x in selected_satellites if (isinstance(x, int) or (isinstance(x, str) and x.isdigit()))
|
||||
],
|
||||
"has_kupsat": has_kupsat,
|
||||
"has_valid": has_valid,
|
||||
"selected_mirrors": [
|
||||
int(x) if isinstance(x, str) else x for x in selected_mirrors if (isinstance(x, int) or (isinstance(x, str) and x.isdigit()))
|
||||
],
|
||||
"selected_complexes": selected_complexes,
|
||||
"date_from": date_from,
|
||||
"date_to": date_to,
|
||||
"has_source_type": has_source_type,
|
||||
"has_sigma": has_sigma,
|
||||
"is_automatic": is_automatic_filter,
|
||||
"modulations": modulations,
|
||||
"polarizations": polarizations,
|
||||
"standards": standards,
|
||||
"satellites": satellites,
|
||||
"mirrors": mirrors,
|
||||
"complexes": complexes,
|
||||
"polygon_coords": polygon_coords,
|
||||
"full_width_page": True,
|
||||
"sort": sort_param,
|
||||
}
|
||||
@@ -679,6 +663,10 @@ class ObjItemCreateView(ObjItemFormView, CreateView):
|
||||
|
||||
success_message = "Объект успешно создан!"
|
||||
|
||||
def get_object(self, queryset=None):
|
||||
"""Return None for create view."""
|
||||
return None
|
||||
|
||||
def set_user_fields(self):
|
||||
self.object.created_by = self.request.user.customuser
|
||||
self.object.updated_by = self.request.user.customuser
|
||||
|
||||
623
dbapp/mainapp/views/points_averaging.py
Normal file
623
dbapp/mainapp/views/points_averaging.py
Normal file
@@ -0,0 +1,623 @@
|
||||
"""
|
||||
Points averaging view for satellite data grouping by day/night intervals.
|
||||
Groups points by Source, then by time intervals within each Source.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.views import View
|
||||
from django.utils import timezone
|
||||
|
||||
from ..models import ObjItem, Satellite, Source
|
||||
from ..utils import (
|
||||
calculate_mean_coords,
|
||||
calculate_distance_wgs84,
|
||||
format_frequency,
|
||||
format_symbol_rate,
|
||||
format_coords_display,
|
||||
RANGE_DISTANCE,
|
||||
get_gauss_kruger_zone,
|
||||
transform_wgs84_to_gk,
|
||||
transform_gk_to_wgs84,
|
||||
average_coords_in_gk,
|
||||
)
|
||||
|
||||
|
||||
class PointsAveragingView(LoginRequiredMixin, View):
|
||||
"""
|
||||
View for points averaging form with date range selection and grouping.
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
# Get satellites that have sources with points with geo data
|
||||
satellites = Satellite.objects.filter(
|
||||
parameters__objitem__source__isnull=False,
|
||||
parameters__objitem__geo_obj__coords__isnull=False
|
||||
).distinct().order_by('name')
|
||||
|
||||
context = {
|
||||
'satellites': satellites,
|
||||
'full_width_page': True,
|
||||
}
|
||||
|
||||
return render(request, 'mainapp/points_averaging.html', context)
|
||||
|
||||
|
||||
class PointsAveragingAPIView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API endpoint for grouping and averaging points by Source and day/night intervals.
|
||||
|
||||
Groups points into:
|
||||
- Day: 08:00 - 19:00
|
||||
- Night: 19:00 - 08:00 (next day)
|
||||
- Weekend: Friday 19:00 - Monday 08:00
|
||||
|
||||
For each group within each Source, calculates average coordinates and checks for outliers (>56 km).
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
satellite_id = request.GET.get('satellite_id', '').strip()
|
||||
date_from = request.GET.get('date_from', '').strip()
|
||||
date_to = request.GET.get('date_to', '').strip()
|
||||
|
||||
if not satellite_id:
|
||||
return JsonResponse({'error': 'Выберите спутник'}, status=400)
|
||||
|
||||
if not date_from or not date_to:
|
||||
return JsonResponse({'error': 'Укажите диапазон дат'}, status=400)
|
||||
|
||||
try:
|
||||
satellite = Satellite.objects.get(id=int(satellite_id))
|
||||
except (Satellite.DoesNotExist, ValueError):
|
||||
return JsonResponse({'error': 'Спутник не найден'}, status=404)
|
||||
|
||||
# Parse dates
|
||||
try:
|
||||
date_from_obj = datetime.strptime(date_from, "%Y-%m-%d")
|
||||
date_to_obj = datetime.strptime(date_to, "%Y-%m-%d") + timedelta(days=1)
|
||||
except ValueError:
|
||||
return JsonResponse({'error': 'Неверный формат даты'}, status=400)
|
||||
|
||||
# Get all Sources for the satellite that have points in the date range
|
||||
sources = Source.objects.filter(
|
||||
source_objitems__parameter_obj__id_satellite=satellite,
|
||||
source_objitems__geo_obj__coords__isnull=False,
|
||||
source_objitems__geo_obj__timestamp__gte=date_from_obj,
|
||||
source_objitems__geo_obj__timestamp__lt=date_to_obj,
|
||||
).distinct().prefetch_related(
|
||||
'source_objitems',
|
||||
'source_objitems__geo_obj',
|
||||
'source_objitems__geo_obj__mirrors',
|
||||
'source_objitems__parameter_obj',
|
||||
'source_objitems__parameter_obj__polarization',
|
||||
'source_objitems__parameter_obj__modulation',
|
||||
'source_objitems__parameter_obj__standard',
|
||||
)
|
||||
|
||||
if not sources.exists():
|
||||
return JsonResponse({'error': 'Источники не найдены в указанном диапазоне'}, status=404)
|
||||
|
||||
# Process each source
|
||||
result_sources = []
|
||||
for source in sources:
|
||||
source_data = self._process_source(source, date_from_obj, date_to_obj)
|
||||
if source_data['groups']: # Only add if has groups with points
|
||||
result_sources.append(source_data)
|
||||
|
||||
if not result_sources:
|
||||
return JsonResponse({'error': 'Точки не найдены в указанном диапазоне'}, status=404)
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'satellite': satellite.name,
|
||||
'date_from': date_from,
|
||||
'date_to': date_to,
|
||||
'sources': result_sources,
|
||||
'total_sources': len(result_sources),
|
||||
})
|
||||
|
||||
def _process_source(self, source, date_from_obj, date_to_obj):
|
||||
"""
|
||||
Process a single Source: get its points and group them by time intervals.
|
||||
"""
|
||||
# Get all points for this source in the date range
|
||||
objitems = source.source_objitems.filter(
|
||||
geo_obj__coords__isnull=False,
|
||||
geo_obj__timestamp__gte=date_from_obj,
|
||||
geo_obj__timestamp__lt=date_to_obj,
|
||||
).select_related(
|
||||
'parameter_obj',
|
||||
'parameter_obj__id_satellite',
|
||||
'parameter_obj__polarization',
|
||||
'parameter_obj__modulation',
|
||||
'parameter_obj__standard',
|
||||
'geo_obj',
|
||||
).prefetch_related(
|
||||
'geo_obj__mirrors'
|
||||
).order_by('geo_obj__timestamp')
|
||||
|
||||
# Group points by day/night intervals
|
||||
groups = self._group_points_by_intervals(list(objitems))
|
||||
|
||||
# Process each group: calculate average and check for outliers
|
||||
result_groups = []
|
||||
for group_key, points in groups.items():
|
||||
group_result = self._process_group(group_key, points)
|
||||
result_groups.append(group_result)
|
||||
|
||||
# Get source name from first point or use ID
|
||||
source_name = f"Источник #{source.id}"
|
||||
if objitems.exists():
|
||||
first_point = objitems.first()
|
||||
if first_point.name:
|
||||
source_name = first_point.name
|
||||
|
||||
return {
|
||||
'source_id': source.id,
|
||||
'source_name': source_name,
|
||||
'total_points': sum(len(g['points']) for g in result_groups),
|
||||
'groups': result_groups,
|
||||
}
|
||||
|
||||
def _group_points_by_intervals(self, objitems):
|
||||
"""
|
||||
Group points by day/night intervals.
|
||||
|
||||
Day: 08:00 - 19:00
|
||||
Night: 19:00 - 08:00 (next day)
|
||||
Weekend: Friday 19:00 - Monday 08:00
|
||||
"""
|
||||
groups = {}
|
||||
|
||||
for objitem in objitems:
|
||||
if not objitem.geo_obj or not objitem.geo_obj.timestamp:
|
||||
continue
|
||||
|
||||
timestamp = timezone.localtime(objitem.geo_obj.timestamp)
|
||||
|
||||
# Determine interval
|
||||
interval_key = self._get_interval_key(timestamp)
|
||||
|
||||
if interval_key not in groups:
|
||||
groups[interval_key] = []
|
||||
|
||||
groups[interval_key].append(objitem)
|
||||
|
||||
return groups
|
||||
|
||||
def _get_interval_key(self, timestamp):
|
||||
"""
|
||||
Get interval key for a timestamp.
|
||||
|
||||
Weekend: Friday 19:00 - Monday 08:00 -> "YYYY-MM-DD_weekend" (date of Friday)
|
||||
Day (weekdays): 08:00 - 19:00 -> "YYYY-MM-DD_day"
|
||||
Night (weekdays): 19:00 - 08:00 -> "YYYY-MM-DD_night" (date of the start of night)
|
||||
"""
|
||||
hour = timestamp.hour
|
||||
date = timestamp.date()
|
||||
weekday = date.weekday() # 0=Monday, 4=Friday, 5=Saturday, 6=Sunday
|
||||
|
||||
# Check if timestamp falls into weekend interval (Fri 19:00 - Mon 08:00)
|
||||
if self._is_weekend_interval(date, hour, weekday):
|
||||
# Find the Friday date for this weekend
|
||||
friday_date = self._get_friday_for_weekend(date, hour, weekday)
|
||||
return f"{friday_date.strftime('%Y-%m-%d')}_weekend"
|
||||
|
||||
# Weekday intervals
|
||||
if 8 <= hour < 19:
|
||||
# Day interval
|
||||
return f"{date.strftime('%Y-%m-%d')}_day"
|
||||
elif hour >= 19:
|
||||
# Night interval starting this day
|
||||
return f"{date.strftime('%Y-%m-%d')}_night"
|
||||
else:
|
||||
# Night interval (00:00 - 08:00), belongs to previous day's night
|
||||
prev_date = date - timedelta(days=1)
|
||||
return f"{prev_date.strftime('%Y-%m-%d')}_night"
|
||||
|
||||
def _is_weekend_interval(self, date, hour, weekday):
|
||||
"""
|
||||
Check if the given timestamp falls into weekend interval.
|
||||
Weekend: Friday 19:00 - Monday 08:00
|
||||
"""
|
||||
# Friday after 19:00
|
||||
if weekday == 4 and hour >= 19:
|
||||
return True
|
||||
# Saturday (all day)
|
||||
if weekday == 5:
|
||||
return True
|
||||
# Sunday (all day)
|
||||
if weekday == 6:
|
||||
return True
|
||||
# Monday before 08:00
|
||||
if weekday == 0 and hour < 8:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _get_friday_for_weekend(self, date, hour, weekday):
|
||||
"""
|
||||
Get the Friday date for the weekend interval that contains this timestamp.
|
||||
"""
|
||||
if weekday == 4: # Friday
|
||||
return date
|
||||
elif weekday == 5: # Saturday
|
||||
return date - timedelta(days=1)
|
||||
elif weekday == 6: # Sunday
|
||||
return date - timedelta(days=2)
|
||||
elif weekday == 0 and hour < 8: # Monday before 08:00
|
||||
return date - timedelta(days=3)
|
||||
return date
|
||||
|
||||
def _process_group(self, interval_key, points):
|
||||
"""
|
||||
Process a group of points: calculate average and check for outliers.
|
||||
|
||||
Algorithm:
|
||||
1. Find first pair of points within 56 km of each other
|
||||
2. Calculate their average as initial center
|
||||
3. Iteratively add points within 56 km of current average
|
||||
4. Points not within 56 km of final average are outliers
|
||||
"""
|
||||
# Parse interval info
|
||||
date_str, interval_type = interval_key.rsplit('_', 1)
|
||||
interval_date = datetime.strptime(date_str, '%Y-%m-%d').date()
|
||||
|
||||
if interval_type == 'day':
|
||||
interval_label = f"{interval_date.strftime('%d.%m.%Y')} День (08:00-19:00)"
|
||||
elif interval_type == 'weekend':
|
||||
# Weekend starts Friday 19:00, ends Monday 08:00
|
||||
monday_date = interval_date + timedelta(days=3)
|
||||
interval_label = f"{interval_date.strftime('%d.%m.%Y')} Выходные (Пт 19:00 - Пн 08:00, {monday_date.strftime('%d.%m.%Y')})"
|
||||
else:
|
||||
interval_label = f"{interval_date.strftime('%d.%m.%Y')} Ночь (19:00-08:00)"
|
||||
|
||||
# Collect coordinates and build points_data
|
||||
points_data = []
|
||||
timestamp_objects = [] # Store datetime objects separately
|
||||
|
||||
for objitem in points:
|
||||
geo = objitem.geo_obj
|
||||
param = getattr(objitem, 'parameter_obj', None)
|
||||
|
||||
coord = (geo.coords.x, geo.coords.y)
|
||||
|
||||
# Get mirrors
|
||||
mirrors = '-'
|
||||
if geo.mirrors.exists():
|
||||
mirrors = ', '.join([m.name for m in geo.mirrors.all()])
|
||||
|
||||
# Format timestamp
|
||||
timestamp_str = '-'
|
||||
timestamp_unix = None
|
||||
if geo.timestamp:
|
||||
local_time = timezone.localtime(geo.timestamp)
|
||||
timestamp_str = local_time.strftime("%d.%m.%Y %H:%M")
|
||||
timestamp_unix = geo.timestamp.timestamp()
|
||||
timestamp_objects.append(geo.timestamp)
|
||||
else:
|
||||
timestamp_objects.append(None)
|
||||
|
||||
points_data.append({
|
||||
'id': objitem.id,
|
||||
'name': objitem.name or '-',
|
||||
'frequency': format_frequency(param.frequency) if param else '-',
|
||||
'freq_range': format_frequency(param.freq_range) if param else '-',
|
||||
'bod_velocity': format_symbol_rate(param.bod_velocity) if param else '-',
|
||||
'modulation': param.modulation.name if param and param.modulation else '-',
|
||||
'snr': f"{param.snr:.0f}" if param and param.snr else '-',
|
||||
'timestamp': timestamp_str,
|
||||
'timestamp_unix': timestamp_unix,
|
||||
'mirrors': mirrors,
|
||||
'location': geo.location or '-',
|
||||
'coordinates': format_coords_display(geo.coords),
|
||||
'coord_tuple': coord,
|
||||
'is_outlier': False,
|
||||
'distance_from_avg': 0,
|
||||
})
|
||||
|
||||
# Apply clustering algorithm
|
||||
avg_coord, valid_indices, avg_type = self._find_cluster_center(points_data)
|
||||
|
||||
# Mark outliers and calculate distances
|
||||
outliers = []
|
||||
valid_points = []
|
||||
|
||||
for i, point_data in enumerate(points_data):
|
||||
coord = point_data['coord_tuple']
|
||||
distance = calculate_distance_wgs84(avg_coord, coord)
|
||||
point_data['distance_from_avg'] = round(distance, 2)
|
||||
|
||||
if i in valid_indices:
|
||||
point_data['is_outlier'] = False
|
||||
valid_points.append(point_data)
|
||||
else:
|
||||
point_data['is_outlier'] = True
|
||||
outliers.append(point_data)
|
||||
|
||||
# Format average coordinates
|
||||
avg_lat = avg_coord[1]
|
||||
avg_lon = avg_coord[0]
|
||||
lat_str = f"{abs(avg_lat):.4f}N" if avg_lat >= 0 else f"{abs(avg_lat):.4f}S"
|
||||
lon_str = f"{abs(avg_lon):.4f}E" if avg_lon >= 0 else f"{abs(avg_lon):.4f}W"
|
||||
avg_coords_str = f"{lat_str} {lon_str}"
|
||||
|
||||
# Get common parameters from first valid point (or first point if no valid)
|
||||
first_point = valid_points[0] if valid_points else (points_data[0] if points_data else {})
|
||||
|
||||
# Collect all unique mirrors from valid points
|
||||
all_mirrors = set()
|
||||
for point in valid_points:
|
||||
mirrors_str = point.get('mirrors', '-')
|
||||
if mirrors_str and mirrors_str != '-':
|
||||
# Split by comma and add each mirror
|
||||
for mirror in mirrors_str.split(','):
|
||||
mirror = mirror.strip()
|
||||
if mirror and mirror != '-':
|
||||
all_mirrors.add(mirror)
|
||||
|
||||
combined_mirrors = ', '.join(sorted(all_mirrors)) if all_mirrors else '-'
|
||||
|
||||
# Calculate median time from valid points using timestamp_objects array
|
||||
valid_timestamps = []
|
||||
for i in valid_indices:
|
||||
if i < len(timestamp_objects) and timestamp_objects[i]:
|
||||
valid_timestamps.append(timestamp_objects[i])
|
||||
|
||||
median_time_str = '-'
|
||||
if valid_timestamps:
|
||||
# Sort timestamps and get median
|
||||
sorted_timestamps = sorted(valid_timestamps, key=lambda ts: ts.timestamp())
|
||||
n = len(sorted_timestamps)
|
||||
|
||||
if n % 2 == 1:
|
||||
# Odd number of timestamps - take middle one
|
||||
median_datetime = sorted_timestamps[n // 2]
|
||||
else:
|
||||
# Even number of timestamps - take average of two middle ones
|
||||
mid1 = sorted_timestamps[n // 2 - 1]
|
||||
mid2 = sorted_timestamps[n // 2]
|
||||
avg_seconds = (mid1.timestamp() + mid2.timestamp()) / 2
|
||||
median_datetime = datetime.fromtimestamp(avg_seconds, tz=mid1.tzinfo)
|
||||
|
||||
median_time_str = timezone.localtime(median_datetime).strftime("%d.%m.%Y %H:%M")
|
||||
|
||||
return {
|
||||
'interval_key': interval_key,
|
||||
'interval_label': interval_label,
|
||||
'total_points': len(points_data),
|
||||
'valid_points_count': len(valid_points),
|
||||
'outliers_count': len(outliers),
|
||||
'has_outliers': len(outliers) > 0,
|
||||
'avg_coordinates': avg_coords_str,
|
||||
'avg_coord_tuple': avg_coord,
|
||||
'avg_type': avg_type,
|
||||
'avg_time': median_time_str,
|
||||
'frequency': first_point.get('frequency', '-'),
|
||||
'freq_range': first_point.get('freq_range', '-'),
|
||||
'bod_velocity': first_point.get('bod_velocity', '-'),
|
||||
'modulation': first_point.get('modulation', '-'),
|
||||
'snr': first_point.get('snr', '-'),
|
||||
'mirrors': combined_mirrors,
|
||||
'points': points_data,
|
||||
'outliers': outliers,
|
||||
'valid_points': valid_points,
|
||||
}
|
||||
|
||||
def _find_cluster_center(self, points_data):
|
||||
"""
|
||||
Find cluster center using the following algorithm:
|
||||
1. Take the first point as reference
|
||||
2. Find all points within 56 km of the first point
|
||||
3. Calculate average of all found points using Gauss-Kruger projection
|
||||
4. Return final average and indices of valid points
|
||||
|
||||
If only 1 point, return it as center.
|
||||
|
||||
Returns:
|
||||
tuple: (avg_coord, set of valid point indices, avg_type)
|
||||
"""
|
||||
if len(points_data) == 0:
|
||||
return (0, 0), set(), "ГК"
|
||||
|
||||
if len(points_data) == 1:
|
||||
return points_data[0]['coord_tuple'], {0}, "ГК"
|
||||
|
||||
# Step 1: Take first point as reference
|
||||
first_coord = points_data[0]['coord_tuple']
|
||||
valid_indices = {0}
|
||||
|
||||
# Step 2: Find all points within 56 km of the first point
|
||||
for i in range(1, len(points_data)):
|
||||
coord_i = points_data[i]['coord_tuple']
|
||||
distance = calculate_distance_wgs84(first_coord, coord_i)
|
||||
|
||||
if distance <= RANGE_DISTANCE:
|
||||
valid_indices.add(i)
|
||||
|
||||
# Step 3: Calculate average of all valid points using Gauss-Kruger projection
|
||||
avg_coord, avg_type = self._calculate_average_from_indices(points_data, valid_indices)
|
||||
|
||||
return avg_coord, valid_indices, avg_type
|
||||
|
||||
def _calculate_average_from_indices(self, points_data, indices):
|
||||
"""
|
||||
Calculate average coordinate from points at given indices.
|
||||
Uses arithmetic averaging in Gauss-Kruger or UTM projection.
|
||||
|
||||
Returns:
|
||||
tuple: (avg_coord, avg_type) where avg_type is "ГК", "UTM" or "Геод"
|
||||
"""
|
||||
indices_list = sorted(indices)
|
||||
if not indices_list:
|
||||
return (0, 0), "ГК"
|
||||
|
||||
if len(indices_list) == 1:
|
||||
return points_data[indices_list[0]]['coord_tuple'], "ГК"
|
||||
|
||||
# Collect coordinates for averaging
|
||||
coords = [points_data[idx]['coord_tuple'] for idx in indices_list]
|
||||
|
||||
# Use Gauss-Kruger/UTM projection for averaging
|
||||
avg_coord, avg_type = average_coords_in_gk(coords)
|
||||
|
||||
return avg_coord, avg_type
|
||||
|
||||
|
||||
class RecalculateGroupAPIView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API endpoint for recalculating a group after removing outliers or including all points.
|
||||
"""
|
||||
|
||||
def post(self, request):
|
||||
import json
|
||||
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({'error': 'Invalid JSON'}, status=400)
|
||||
|
||||
points = data.get('points', [])
|
||||
include_all = data.get('include_all', False)
|
||||
|
||||
if not points:
|
||||
return JsonResponse({'error': 'No points provided'}, status=400)
|
||||
|
||||
# If include_all is True, average ALL points without clustering (no outliers)
|
||||
# If include_all is False, use only non-outlier points and apply clustering
|
||||
if include_all:
|
||||
# Average all points - no outliers, all points are valid
|
||||
avg_coord, avg_type = self._calculate_average_from_indices(points, set(range(len(points))))
|
||||
valid_indices = set(range(len(points)))
|
||||
else:
|
||||
# Filter out outliers first
|
||||
points = [p for p in points if not p.get('is_outlier', False)]
|
||||
|
||||
if not points:
|
||||
return JsonResponse({'error': 'No valid points after filtering'}, status=400)
|
||||
|
||||
# Apply clustering algorithm
|
||||
avg_coord, valid_indices, avg_type = self._find_cluster_center(points)
|
||||
|
||||
# Mark outliers and calculate distances
|
||||
for i, point in enumerate(points):
|
||||
coord = tuple(point['coord_tuple'])
|
||||
distance = calculate_distance_wgs84(avg_coord, coord)
|
||||
point['distance_from_avg'] = round(distance, 2)
|
||||
point['is_outlier'] = i not in valid_indices
|
||||
|
||||
# Format average coordinates
|
||||
avg_lat = avg_coord[1]
|
||||
avg_lon = avg_coord[0]
|
||||
lat_str = f"{abs(avg_lat):.4f}N" if avg_lat >= 0 else f"{abs(avg_lat):.4f}S"
|
||||
lon_str = f"{abs(avg_lon):.4f}E" if avg_lon >= 0 else f"{abs(avg_lon):.4f}W"
|
||||
avg_coords_str = f"{lat_str} {lon_str}"
|
||||
|
||||
outliers = [p for p in points if p.get('is_outlier', False)]
|
||||
valid_points = [p for p in points if not p.get('is_outlier', False)]
|
||||
|
||||
# Collect all unique mirrors from valid points
|
||||
all_mirrors = set()
|
||||
for point in valid_points:
|
||||
mirrors_str = point.get('mirrors', '-')
|
||||
if mirrors_str and mirrors_str != '-':
|
||||
for mirror in mirrors_str.split(','):
|
||||
mirror = mirror.strip()
|
||||
if mirror and mirror != '-':
|
||||
all_mirrors.add(mirror)
|
||||
|
||||
combined_mirrors = ', '.join(sorted(all_mirrors)) if all_mirrors else '-'
|
||||
|
||||
# Calculate median time from valid points using timestamp_unix
|
||||
valid_timestamps_unix = []
|
||||
for point in valid_points:
|
||||
if point.get('timestamp_unix'):
|
||||
valid_timestamps_unix.append(point['timestamp_unix'])
|
||||
|
||||
median_time_str = '-'
|
||||
if valid_timestamps_unix:
|
||||
from datetime import datetime
|
||||
# Sort timestamps and get median
|
||||
sorted_timestamps = sorted(valid_timestamps_unix)
|
||||
n = len(sorted_timestamps)
|
||||
|
||||
if n % 2 == 1:
|
||||
# Odd number of timestamps - take middle one
|
||||
median_unix = sorted_timestamps[n // 2]
|
||||
else:
|
||||
# Even number of timestamps - take average of two middle ones
|
||||
mid1 = sorted_timestamps[n // 2 - 1]
|
||||
mid2 = sorted_timestamps[n // 2]
|
||||
median_unix = (mid1 + mid2) / 2
|
||||
|
||||
# Convert Unix timestamp to datetime
|
||||
median_datetime = datetime.fromtimestamp(median_unix, tz=timezone.get_current_timezone())
|
||||
median_time_str = timezone.localtime(median_datetime).strftime("%d.%m.%Y %H:%M")
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'avg_coordinates': avg_coords_str,
|
||||
'avg_coord_tuple': avg_coord,
|
||||
'avg_type': avg_type,
|
||||
'total_points': len(points),
|
||||
'valid_points_count': len(valid_points),
|
||||
'outliers_count': len(outliers),
|
||||
'has_outliers': len(outliers) > 0,
|
||||
'mirrors': combined_mirrors,
|
||||
'avg_time': median_time_str,
|
||||
'points': points,
|
||||
})
|
||||
|
||||
def _find_cluster_center(self, points):
|
||||
"""
|
||||
Find cluster center using the following algorithm:
|
||||
1. Take the first point as reference
|
||||
2. Find all points within 56 km of the first point
|
||||
3. Calculate average of all found points using Gauss-Kruger projection
|
||||
4. Return final average, indices of valid points, and averaging type
|
||||
"""
|
||||
if len(points) == 0:
|
||||
return (0, 0), set(), "ГК"
|
||||
|
||||
if len(points) == 1:
|
||||
return tuple(points[0]['coord_tuple']), {0}, "ГК"
|
||||
|
||||
# Step 1: Take first point as reference
|
||||
first_coord = tuple(points[0]['coord_tuple'])
|
||||
valid_indices = {0}
|
||||
|
||||
# Step 2: Find all points within 56 km of the first point
|
||||
for i in range(1, len(points)):
|
||||
coord_i = tuple(points[i]['coord_tuple'])
|
||||
distance = calculate_distance_wgs84(first_coord, coord_i)
|
||||
|
||||
if distance <= RANGE_DISTANCE:
|
||||
valid_indices.add(i)
|
||||
|
||||
# Step 3: Calculate average of all valid points
|
||||
avg_coord, avg_type = self._calculate_average_from_indices(points, valid_indices)
|
||||
|
||||
return avg_coord, valid_indices, avg_type
|
||||
|
||||
def _calculate_average_from_indices(self, points, indices):
|
||||
"""
|
||||
Calculate average coordinate from points at given indices.
|
||||
Uses arithmetic averaging in Gauss-Kruger or UTM projection.
|
||||
|
||||
Returns:
|
||||
tuple: (avg_coord, avg_type)
|
||||
"""
|
||||
indices_list = sorted(indices)
|
||||
if not indices_list:
|
||||
return (0, 0), "ГК"
|
||||
|
||||
if len(indices_list) == 1:
|
||||
return tuple(points[indices_list[0]]['coord_tuple']), "ГК"
|
||||
|
||||
# Collect coordinates for averaging
|
||||
coords = [tuple(points[idx]['coord_tuple']) for idx in indices_list]
|
||||
|
||||
# Use Gauss-Kruger/UTM projection for averaging
|
||||
avg_coord, avg_type = average_coords_in_gk(coords)
|
||||
|
||||
return avg_coord, avg_type
|
||||
@@ -23,7 +23,13 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
"""View for displaying a list of satellites with filtering and pagination."""
|
||||
|
||||
def get(self, request):
|
||||
# Get pagination parameters
|
||||
# Get pagination parameters - default to "Все" (all items) for satellites
|
||||
# If no items_per_page is specified, use MAX_ITEMS_PER_PAGE
|
||||
from ..utils import MAX_ITEMS_PER_PAGE
|
||||
default_per_page = MAX_ITEMS_PER_PAGE if not request.GET.get("items_per_page") else None
|
||||
if default_per_page:
|
||||
page_number, items_per_page = parse_pagination_params(request, default_per_page=default_per_page)
|
||||
else:
|
||||
page_number, items_per_page = parse_pagination_params(request)
|
||||
|
||||
# Get sorting parameters (default to name)
|
||||
@@ -32,6 +38,7 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
# Get filter parameters
|
||||
search_query = request.GET.get("search", "").strip()
|
||||
selected_bands = request.GET.getlist("band_id")
|
||||
selected_location_places = request.GET.getlist("location_place")
|
||||
norad_min = request.GET.get("norad_min", "").strip()
|
||||
norad_max = request.GET.get("norad_max", "").strip()
|
||||
undersat_point_min = request.GET.get("undersat_point_min", "").strip()
|
||||
@@ -40,6 +47,8 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
launch_date_to = request.GET.get("launch_date_to", "").strip()
|
||||
date_from = request.GET.get("date_from", "").strip()
|
||||
date_to = request.GET.get("date_to", "").strip()
|
||||
transponder_count_min = request.GET.get("transponder_count_min", "").strip()
|
||||
transponder_count_max = request.GET.get("transponder_count_max", "").strip()
|
||||
|
||||
# Get all bands for filters
|
||||
bands = Band.objects.all().order_by("name")
|
||||
@@ -58,6 +67,10 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
if selected_bands:
|
||||
satellites = satellites.filter(band__id__in=selected_bands).distinct()
|
||||
|
||||
# Filter by location_place
|
||||
if selected_location_places:
|
||||
satellites = satellites.filter(location_place__in=selected_location_places)
|
||||
|
||||
# Filter by NORAD ID
|
||||
if norad_min:
|
||||
try:
|
||||
@@ -124,21 +137,41 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Search by name
|
||||
# Search by name, alternative_name, or comment
|
||||
if search_query:
|
||||
satellites = satellites.filter(
|
||||
Q(name__icontains=search_query) |
|
||||
Q(alternative_name__icontains=search_query) |
|
||||
Q(comment__icontains=search_query)
|
||||
)
|
||||
|
||||
# Filter by transponder count
|
||||
if transponder_count_min:
|
||||
try:
|
||||
min_val = int(transponder_count_min)
|
||||
satellites = satellites.filter(transponder_count__gte=min_val)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if transponder_count_max:
|
||||
try:
|
||||
max_val = int(transponder_count_max)
|
||||
satellites = satellites.filter(transponder_count__lte=max_val)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Apply sorting
|
||||
valid_sort_fields = {
|
||||
"id": "id",
|
||||
"-id": "-id",
|
||||
"name": "name",
|
||||
"-name": "-name",
|
||||
"alternative_name": "alternative_name",
|
||||
"-alternative_name": "-alternative_name",
|
||||
"norad": "norad",
|
||||
"-norad": "-norad",
|
||||
"international_code": "international_code",
|
||||
"-international_code": "-international_code",
|
||||
"undersat_point": "undersat_point",
|
||||
"-undersat_point": "-undersat_point",
|
||||
"launch_date": "launch_date",
|
||||
@@ -149,6 +182,8 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
"-updated_at": "-updated_at",
|
||||
"transponder_count": "transponder_count",
|
||||
"-transponder_count": "-transponder_count",
|
||||
"location_place": "location_place",
|
||||
"-location_place": "-location_place",
|
||||
}
|
||||
|
||||
if sort_param in valid_sort_fields:
|
||||
@@ -164,10 +199,16 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
# Get band names
|
||||
band_names = [band.name for band in satellite.band.all()]
|
||||
|
||||
# Get location_place display value
|
||||
location_place_display = dict(Satellite.PLACES).get(satellite.location_place, "-") if satellite.location_place else "-"
|
||||
|
||||
processed_satellites.append({
|
||||
'id': satellite.id,
|
||||
'name': satellite.name or "-",
|
||||
'alternative_name': satellite.alternative_name or "-",
|
||||
'location_place': location_place_display,
|
||||
'norad': satellite.norad if satellite.norad else "-",
|
||||
'international_code': satellite.international_code or "-",
|
||||
'bands': ", ".join(band_names) if band_names else "-",
|
||||
'undersat_point': f"{satellite.undersat_point:.2f}" if satellite.undersat_point is not None else "-",
|
||||
'launch_date': satellite.launch_date.strftime("%d.%m.%Y") if satellite.launch_date else "-",
|
||||
@@ -185,7 +226,7 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
'page_obj': page_obj,
|
||||
'processed_satellites': processed_satellites,
|
||||
'items_per_page': items_per_page,
|
||||
'available_items_per_page': [50, 100, 500, 1000],
|
||||
'available_items_per_page': [50, 100, 500, 1000, 'Все'],
|
||||
'sort': sort_param,
|
||||
'search_query': search_query,
|
||||
'bands': bands,
|
||||
@@ -193,6 +234,8 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
int(x) if isinstance(x, str) else x for x in selected_bands
|
||||
if (isinstance(x, int) or (isinstance(x, str) and x.isdigit()))
|
||||
],
|
||||
'location_places': Satellite.PLACES,
|
||||
'selected_location_places': selected_location_places,
|
||||
'norad_min': norad_min,
|
||||
'norad_max': norad_max,
|
||||
'undersat_point_min': undersat_point_min,
|
||||
@@ -201,6 +244,8 @@ class SatelliteListView(LoginRequiredMixin, View):
|
||||
'launch_date_to': launch_date_to,
|
||||
'date_from': date_from,
|
||||
'date_to': date_to,
|
||||
'transponder_count_min': transponder_count_min,
|
||||
'transponder_count_max': transponder_count_max,
|
||||
'full_width_page': True,
|
||||
}
|
||||
|
||||
@@ -259,6 +304,7 @@ class SatelliteUpdateView(RoleRequiredMixin, FormMessageMixin, UpdateView):
|
||||
'id': t.id,
|
||||
'name': t.name or f"TP-{t.id}",
|
||||
'downlink': float(t.downlink),
|
||||
'uplink': float(t.uplink) if t.uplink else None,
|
||||
'frequency_range': float(t.frequency_range),
|
||||
'polarization': t.polarization.name if t.polarization else '-',
|
||||
'zone_name': t.zone_name or '-',
|
||||
|
||||
305
dbapp/mainapp/views/secret_stats.py
Normal file
305
dbapp/mainapp/views/secret_stats.py
Normal file
@@ -0,0 +1,305 @@
|
||||
"""
|
||||
Секретная страница статистики в стиле Spotify Wrapped / Яндекс.Музыка.
|
||||
Красивые анимации, диаграммы и визуализации.
|
||||
"""
|
||||
import json
|
||||
from datetime import timedelta, datetime
|
||||
from collections import defaultdict
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
|
||||
from django.db.models import Count, Q, Min, Max, Avg, Sum
|
||||
from django.db.models.functions import TruncDate, TruncMonth, ExtractWeekDay, ExtractHour
|
||||
from django.utils import timezone
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
from ..models import ObjItem, Source, Satellite, Geo, Parameter
|
||||
|
||||
|
||||
class AdminOnlyMixin(UserPassesTestMixin):
|
||||
"""Mixin to restrict access to admin role only."""
|
||||
|
||||
def test_func(self):
|
||||
return (
|
||||
self.request.user.is_authenticated and
|
||||
hasattr(self.request.user, 'customuser') and
|
||||
self.request.user.customuser.role == 'admin'
|
||||
)
|
||||
|
||||
def handle_no_permission(self):
|
||||
from django.contrib import messages
|
||||
from django.shortcuts import redirect
|
||||
messages.error(self.request, 'Доступ запрещён. Требуется роль администратора.')
|
||||
return redirect('mainapp:home')
|
||||
|
||||
|
||||
class SecretStatsView(LoginRequiredMixin, AdminOnlyMixin, TemplateView):
|
||||
"""Секретная страница статистики - итоги года в стиле Spotify Wrapped."""
|
||||
|
||||
template_name = 'mainapp/secret_stats.html'
|
||||
|
||||
def get_year_range(self):
|
||||
"""Получает диапазон дат для текущего года."""
|
||||
now = timezone.now()
|
||||
year = self.request.GET.get('year', now.year)
|
||||
try:
|
||||
year = int(year)
|
||||
except (ValueError, TypeError):
|
||||
year = now.year
|
||||
|
||||
date_from = datetime(year, 1, 1).date()
|
||||
date_to = datetime(year, 12, 31).date()
|
||||
|
||||
return date_from, date_to, year
|
||||
|
||||
def get_base_queryset(self, date_from, date_to):
|
||||
"""Возвращает базовый queryset ObjItem с фильтрами по дате ГЛ."""
|
||||
qs = ObjItem.objects.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__timestamp__isnull=False,
|
||||
geo_obj__timestamp__date__gte=date_from,
|
||||
geo_obj__timestamp__date__lte=date_to
|
||||
)
|
||||
return qs
|
||||
|
||||
def get_main_stats(self, date_from, date_to):
|
||||
"""Основная статистика: точки и объекты."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to)
|
||||
|
||||
total_points = base_qs.count()
|
||||
total_sources = base_qs.filter(source__isnull=False).values('source').distinct().count()
|
||||
|
||||
return {
|
||||
'total_points': total_points,
|
||||
'total_sources': total_sources,
|
||||
}
|
||||
|
||||
def get_new_emissions(self, date_from, date_to):
|
||||
"""
|
||||
Новые излучения - объекты, у которых имя появилось впервые в выбранном периоде.
|
||||
"""
|
||||
# Получаем все имена объектов, которые появились ДО выбранного периода
|
||||
existing_names = set(
|
||||
ObjItem.objects.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__timestamp__isnull=False,
|
||||
geo_obj__timestamp__date__lt=date_from,
|
||||
name__isnull=False
|
||||
).exclude(name='').values_list('name', flat=True).distinct()
|
||||
)
|
||||
|
||||
# Базовый queryset для выбранного периода
|
||||
period_qs = self.get_base_queryset(date_from, date_to).filter(
|
||||
name__isnull=False
|
||||
).exclude(name='')
|
||||
|
||||
# Получаем уникальные имена в выбранном периоде
|
||||
period_names = set(period_qs.values_list('name', flat=True).distinct())
|
||||
|
||||
# Новые имена = имена в периоде, которых не было раньше
|
||||
new_names = period_names - existing_names
|
||||
|
||||
if not new_names:
|
||||
return {'count': 0, 'objects': [], 'sources_count': 0}
|
||||
|
||||
# Получаем данные о новых объектах
|
||||
objitems_data = period_qs.filter(
|
||||
name__in=new_names
|
||||
).select_related(
|
||||
'source__info', 'source__ownership'
|
||||
).values(
|
||||
'name',
|
||||
'source__info__name',
|
||||
'source__ownership__name'
|
||||
).distinct()
|
||||
|
||||
seen_names = set()
|
||||
new_objects = []
|
||||
|
||||
for item in objitems_data:
|
||||
name = item['name']
|
||||
if name not in seen_names:
|
||||
seen_names.add(name)
|
||||
new_objects.append({
|
||||
'name': name,
|
||||
'info': item['source__info__name'] or '-',
|
||||
'ownership': item['source__ownership__name'] or '-',
|
||||
})
|
||||
|
||||
new_objects.sort(key=lambda x: x['name'])
|
||||
|
||||
# Количество источников для новых излучений
|
||||
new_sources_count = period_qs.filter(
|
||||
name__in=new_names, source__isnull=False
|
||||
).values('source').distinct().count()
|
||||
|
||||
return {
|
||||
'count': len(new_names),
|
||||
'objects': new_objects[:20], # Топ-20 для отображения
|
||||
'sources_count': new_sources_count
|
||||
}
|
||||
|
||||
def get_satellite_stats(self, date_from, date_to):
|
||||
"""Статистика по спутникам."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to)
|
||||
|
||||
stats = base_qs.filter(
|
||||
parameter_obj__id_satellite__isnull=False
|
||||
).values(
|
||||
'parameter_obj__id_satellite__id',
|
||||
'parameter_obj__id_satellite__name'
|
||||
).annotate(
|
||||
points_count=Count('id'),
|
||||
sources_count=Count('source', distinct=True),
|
||||
unique_names=Count('name', distinct=True)
|
||||
).order_by('-points_count')
|
||||
|
||||
return list(stats)
|
||||
|
||||
def get_monthly_stats(self, date_from, date_to):
|
||||
"""Статистика по месяцам."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to)
|
||||
|
||||
monthly = base_qs.annotate(
|
||||
month=TruncMonth('geo_obj__timestamp')
|
||||
).values('month').annotate(
|
||||
points=Count('id'),
|
||||
sources=Count('source', distinct=True)
|
||||
).order_by('month')
|
||||
|
||||
return list(monthly)
|
||||
|
||||
def get_weekday_stats(self, date_from, date_to):
|
||||
"""Статистика по дням недели."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to)
|
||||
|
||||
weekday = base_qs.annotate(
|
||||
weekday=ExtractWeekDay('geo_obj__timestamp')
|
||||
).values('weekday').annotate(
|
||||
points=Count('id')
|
||||
).order_by('weekday')
|
||||
|
||||
return list(weekday)
|
||||
|
||||
def get_hourly_stats(self, date_from, date_to):
|
||||
"""Статистика по часам."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to)
|
||||
|
||||
hourly = base_qs.annotate(
|
||||
hour=ExtractHour('geo_obj__timestamp')
|
||||
).values('hour').annotate(
|
||||
points=Count('id')
|
||||
).order_by('hour')
|
||||
|
||||
return list(hourly)
|
||||
|
||||
def get_top_objects(self, date_from, date_to):
|
||||
"""Топ объектов по количеству точек."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to)
|
||||
|
||||
top = base_qs.filter(
|
||||
name__isnull=False
|
||||
).exclude(name='').values('name').annotate(
|
||||
points=Count('id')
|
||||
).order_by('-points')[:10]
|
||||
|
||||
return list(top)
|
||||
|
||||
def get_busiest_day(self, date_from, date_to):
|
||||
"""Самый активный день."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to)
|
||||
|
||||
daily = base_qs.annotate(
|
||||
date=TruncDate('geo_obj__timestamp')
|
||||
).values('date').annotate(
|
||||
points=Count('id')
|
||||
).order_by('-points').first()
|
||||
|
||||
return daily
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
|
||||
date_from, date_to, year = self.get_year_range()
|
||||
|
||||
# Основная статистика
|
||||
main_stats = self.get_main_stats(date_from, date_to)
|
||||
|
||||
# Новые излучения
|
||||
new_emissions = self.get_new_emissions(date_from, date_to)
|
||||
|
||||
# Статистика по спутникам
|
||||
satellite_stats = self.get_satellite_stats(date_from, date_to)
|
||||
|
||||
# Статистика по месяцам
|
||||
monthly_stats = self.get_monthly_stats(date_from, date_to)
|
||||
|
||||
# Статистика по дням недели
|
||||
weekday_stats = self.get_weekday_stats(date_from, date_to)
|
||||
|
||||
# Статистика по часам
|
||||
hourly_stats = self.get_hourly_stats(date_from, date_to)
|
||||
|
||||
# Топ объектов
|
||||
top_objects = self.get_top_objects(date_from, date_to)
|
||||
|
||||
# Самый активный день
|
||||
busiest_day = self.get_busiest_day(date_from, date_to)
|
||||
|
||||
# Доступные годы для выбора
|
||||
years_with_data = ObjItem.objects.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__timestamp__isnull=False
|
||||
).dates('geo_obj__timestamp', 'year')
|
||||
available_years = sorted([d.year for d in years_with_data], reverse=True)
|
||||
|
||||
# JSON данные для графиков
|
||||
monthly_data_json = json.dumps([
|
||||
{
|
||||
'month': item['month'].strftime('%Y-%m') if item['month'] else None,
|
||||
'month_name': item['month'].strftime('%B') if item['month'] else None,
|
||||
'points': item['points'],
|
||||
'sources': item['sources'],
|
||||
}
|
||||
for item in monthly_stats
|
||||
])
|
||||
|
||||
satellite_stats_json = json.dumps(satellite_stats)
|
||||
|
||||
weekday_names = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб']
|
||||
weekday_data_json = json.dumps([
|
||||
{
|
||||
'weekday': item['weekday'],
|
||||
'weekday_name': weekday_names[item['weekday'] - 1] if item['weekday'] else '',
|
||||
'points': item['points'],
|
||||
}
|
||||
for item in weekday_stats
|
||||
])
|
||||
|
||||
hourly_data_json = json.dumps([
|
||||
{
|
||||
'hour': item['hour'],
|
||||
'points': item['points'],
|
||||
}
|
||||
for item in hourly_stats
|
||||
])
|
||||
|
||||
top_objects_json = json.dumps(top_objects)
|
||||
|
||||
context.update({
|
||||
'year': year,
|
||||
'available_years': available_years,
|
||||
'total_points': main_stats['total_points'],
|
||||
'total_sources': main_stats['total_sources'],
|
||||
'new_emissions_count': new_emissions['count'],
|
||||
'new_emissions_sources': new_emissions['sources_count'],
|
||||
'new_emission_objects': new_emissions['objects'],
|
||||
'satellite_stats': satellite_stats[:10], # Топ-10
|
||||
'satellite_count': len(satellite_stats),
|
||||
'busiest_day': busiest_day,
|
||||
'monthly_data_json': monthly_data_json,
|
||||
'satellite_stats_json': satellite_stats_json,
|
||||
'weekday_data_json': weekday_data_json,
|
||||
'hourly_data_json': hourly_data_json,
|
||||
'top_objects_json': top_objects_json,
|
||||
})
|
||||
|
||||
return context
|
||||
@@ -43,10 +43,17 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
objitem_count_max = request.GET.get("objitem_count_max", "").strip()
|
||||
date_from = request.GET.get("date_from", "").strip()
|
||||
date_to = request.GET.get("date_to", "").strip()
|
||||
# Signal mark filters
|
||||
has_signal_mark = request.GET.get("has_signal_mark")
|
||||
mark_date_from = request.GET.get("mark_date_from", "").strip()
|
||||
mark_date_to = request.GET.get("mark_date_to", "").strip()
|
||||
|
||||
# Source request filters
|
||||
has_requests = request.GET.get("has_requests")
|
||||
selected_request_statuses = request.GET.getlist("request_status")
|
||||
selected_request_priorities = request.GET.getlist("request_priority")
|
||||
request_gso_success = request.GET.get("request_gso_success")
|
||||
request_kubsat_success = request.GET.get("request_kubsat_success")
|
||||
request_planned_from = request.GET.get("request_planned_from", "").strip()
|
||||
request_planned_to = request.GET.get("request_planned_to", "").strip()
|
||||
request_date_from = request.GET.get("request_date_from", "").strip()
|
||||
request_date_to = request.GET.get("request_date_to", "").strip()
|
||||
|
||||
# Get filter parameters - ObjItem level (параметры точек)
|
||||
geo_date_from = request.GET.get("geo_date_from", "").strip()
|
||||
@@ -54,7 +61,9 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
selected_satellites = request.GET.getlist("satellite_id")
|
||||
selected_polarizations = request.GET.getlist("polarization_id")
|
||||
selected_modulations = request.GET.getlist("modulation_id")
|
||||
selected_standards = request.GET.getlist("standard_id")
|
||||
selected_mirrors = request.GET.getlist("mirror_id")
|
||||
selected_complexes = request.GET.getlist("complex_id")
|
||||
freq_min = request.GET.get("freq_min", "").strip()
|
||||
freq_max = request.GET.get("freq_max", "").strip()
|
||||
freq_range_min = request.GET.get("freq_range_min", "").strip()
|
||||
@@ -89,10 +98,11 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
.order_by("name")
|
||||
)
|
||||
|
||||
# Get all polarizations, modulations for filters
|
||||
from ..models import Polarization, Modulation, ObjectInfo
|
||||
# Get all polarizations, modulations, standards for filters
|
||||
from ..models import Polarization, Modulation, ObjectInfo, Standard
|
||||
polarizations = Polarization.objects.all().order_by("name")
|
||||
modulations = Modulation.objects.all().order_by("name")
|
||||
standards = Standard.objects.all().order_by("name")
|
||||
|
||||
# Get all ObjectInfo for filter
|
||||
object_infos = ObjectInfo.objects.all().order_by("name")
|
||||
@@ -160,6 +170,11 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
objitem_filter_q &= Q(source_objitems__parameter_obj__modulation_id__in=selected_modulations)
|
||||
has_objitem_filter = True
|
||||
|
||||
# Add standard filter
|
||||
if selected_standards:
|
||||
objitem_filter_q &= Q(source_objitems__parameter_obj__standard_id__in=selected_standards)
|
||||
has_objitem_filter = True
|
||||
|
||||
# Add frequency filter
|
||||
if freq_min:
|
||||
try:
|
||||
@@ -233,6 +248,11 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
objitem_filter_q &= Q(source_objitems__geo_obj__mirrors__id__in=selected_mirrors)
|
||||
has_objitem_filter = True
|
||||
|
||||
# Add complex filter
|
||||
if selected_complexes:
|
||||
objitem_filter_q &= Q(source_objitems__parameter_obj__id_satellite__location_place__in=selected_complexes)
|
||||
has_objitem_filter = True
|
||||
|
||||
# Add polygon filter
|
||||
if polygon_geom:
|
||||
objitem_filter_q &= Q(source_objitems__geo_obj__coords__within=polygon_geom)
|
||||
@@ -284,6 +304,8 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
filtered_objitems_qs = filtered_objitems_qs.filter(parameter_obj__polarization_id__in=selected_polarizations)
|
||||
if selected_modulations:
|
||||
filtered_objitems_qs = filtered_objitems_qs.filter(parameter_obj__modulation_id__in=selected_modulations)
|
||||
if selected_standards:
|
||||
filtered_objitems_qs = filtered_objitems_qs.filter(parameter_obj__standard_id__in=selected_standards)
|
||||
if freq_min:
|
||||
try:
|
||||
freq_min_val = float(freq_min)
|
||||
@@ -334,6 +356,8 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
pass
|
||||
if selected_mirrors:
|
||||
filtered_objitems_qs = filtered_objitems_qs.filter(geo_obj__mirrors__id__in=selected_mirrors)
|
||||
if selected_complexes:
|
||||
filtered_objitems_qs = filtered_objitems_qs.filter(parameter_obj__id_satellite__location_place__in=selected_complexes)
|
||||
if polygon_geom:
|
||||
filtered_objitems_qs = filtered_objitems_qs.filter(geo_obj__coords__within=polygon_geom)
|
||||
|
||||
@@ -350,10 +374,6 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
).prefetch_related(
|
||||
# Use Prefetch with filtered queryset
|
||||
Prefetch('source_objitems', queryset=filtered_objitems_qs, to_attr='filtered_objitems'),
|
||||
# Prefetch marks with their relationships
|
||||
'marks',
|
||||
'marks__created_by',
|
||||
'marks__created_by__user'
|
||||
).annotate(
|
||||
# Use annotate for efficient counting in a single query
|
||||
objitem_count=Count('source_objitems', filter=objitem_filter_q, distinct=True) if has_objitem_filter else Count('source_objitems')
|
||||
@@ -392,36 +412,75 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
if selected_ownership:
|
||||
sources = sources.filter(ownership_id__in=selected_ownership)
|
||||
|
||||
# Filter by signal marks
|
||||
if has_signal_mark or mark_date_from or mark_date_to:
|
||||
mark_filter_q = Q()
|
||||
# NOTE: Фильтры по отметкам сигналов удалены, т.к. ObjectMark теперь связан с TechAnalyze, а не с Source
|
||||
# Для фильтрации по отметкам используйте страницу "Отметки сигналов"
|
||||
|
||||
# Filter by mark value (signal presence)
|
||||
if has_signal_mark == "1":
|
||||
mark_filter_q &= Q(marks__mark=True)
|
||||
elif has_signal_mark == "0":
|
||||
mark_filter_q &= Q(marks__mark=False)
|
||||
# Filter by source requests
|
||||
if has_requests == "1":
|
||||
# Has requests - apply subfilters
|
||||
from ..models import SourceRequest
|
||||
from django.db.models import Exists, OuterRef
|
||||
|
||||
# Filter by mark date range
|
||||
if mark_date_from:
|
||||
# Build subquery for filtering requests
|
||||
request_subquery = SourceRequest.objects.filter(source=OuterRef('pk'))
|
||||
|
||||
# Filter by request status
|
||||
if selected_request_statuses:
|
||||
request_subquery = request_subquery.filter(status__in=selected_request_statuses)
|
||||
|
||||
# Filter by request priority
|
||||
if selected_request_priorities:
|
||||
request_subquery = request_subquery.filter(priority__in=selected_request_priorities)
|
||||
|
||||
# Filter by GSO success
|
||||
if request_gso_success == "true":
|
||||
request_subquery = request_subquery.filter(gso_success=True)
|
||||
elif request_gso_success == "false":
|
||||
request_subquery = request_subquery.filter(gso_success=False)
|
||||
|
||||
# Filter by Kubsat success
|
||||
if request_kubsat_success == "true":
|
||||
request_subquery = request_subquery.filter(kubsat_success=True)
|
||||
elif request_kubsat_success == "false":
|
||||
request_subquery = request_subquery.filter(kubsat_success=False)
|
||||
|
||||
# Filter by planned date range
|
||||
if request_planned_from:
|
||||
try:
|
||||
mark_date_from_obj = datetime.strptime(mark_date_from, "%Y-%m-%d")
|
||||
mark_filter_q &= Q(marks__timestamp__gte=mark_date_from_obj)
|
||||
planned_from_obj = datetime.strptime(request_planned_from, "%Y-%m-%d")
|
||||
request_subquery = request_subquery.filter(planned_at__gte=planned_from_obj)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if mark_date_to:
|
||||
if request_planned_to:
|
||||
try:
|
||||
from datetime import timedelta
|
||||
mark_date_to_obj = datetime.strptime(mark_date_to, "%Y-%m-%d")
|
||||
# Add one day to include entire end date
|
||||
mark_date_to_obj = mark_date_to_obj + timedelta(days=1)
|
||||
mark_filter_q &= Q(marks__timestamp__lt=mark_date_to_obj)
|
||||
planned_to_obj = datetime.strptime(request_planned_to, "%Y-%m-%d")
|
||||
planned_to_obj = planned_to_obj + timedelta(days=1)
|
||||
request_subquery = request_subquery.filter(planned_at__lt=planned_to_obj)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if mark_filter_q:
|
||||
sources = sources.filter(mark_filter_q).distinct()
|
||||
# Filter by request date range
|
||||
if request_date_from:
|
||||
try:
|
||||
req_date_from_obj = datetime.strptime(request_date_from, "%Y-%m-%d")
|
||||
request_subquery = request_subquery.filter(request_date__gte=req_date_from_obj)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if request_date_to:
|
||||
try:
|
||||
req_date_to_obj = datetime.strptime(request_date_to, "%Y-%m-%d")
|
||||
request_subquery = request_subquery.filter(request_date__lte=req_date_to_obj)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Apply the subquery filter using Exists
|
||||
sources = sources.filter(Exists(request_subquery))
|
||||
elif has_requests == "0":
|
||||
# No requests
|
||||
sources = sources.filter(source_requests__isnull=True)
|
||||
|
||||
# Filter by ObjItem count
|
||||
if objitem_count_min:
|
||||
@@ -506,6 +565,12 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
source_objitems__parameter_obj__modulation_id__in=selected_modulations
|
||||
).distinct()
|
||||
|
||||
# Filter by standards
|
||||
if selected_standards:
|
||||
sources = sources.filter(
|
||||
source_objitems__parameter_obj__standard_id__in=selected_standards
|
||||
).distinct()
|
||||
|
||||
# Filter by frequency range
|
||||
if freq_min:
|
||||
try:
|
||||
@@ -572,6 +637,12 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
source_objitems__geo_obj__mirrors__id__in=selected_mirrors
|
||||
).distinct()
|
||||
|
||||
# Filter by complex
|
||||
if selected_complexes:
|
||||
sources = sources.filter(
|
||||
source_objitems__parameter_obj__id_satellite__location_place__in=selected_complexes
|
||||
).distinct()
|
||||
|
||||
# Filter by polygon
|
||||
if polygon_geom:
|
||||
sources = sources.filter(
|
||||
@@ -639,14 +710,8 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
# Get first satellite ID for modal link (if multiple satellites, use first one)
|
||||
first_satellite_id = min(satellite_ids) if satellite_ids else None
|
||||
|
||||
# Get all marks (presence/absence)
|
||||
# Отметки теперь привязаны к TechAnalyze, а не к Source
|
||||
marks_data = []
|
||||
for mark in source.marks.all():
|
||||
marks_data.append({
|
||||
'mark': mark.mark,
|
||||
'timestamp': mark.timestamp,
|
||||
'created_by': str(mark.created_by) if mark.created_by else '-',
|
||||
})
|
||||
|
||||
# Get info name and ownership
|
||||
info_name = source.info.name if source.info else '-'
|
||||
@@ -671,6 +736,7 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
'has_lyngsat': has_lyngsat,
|
||||
'lyngsat_id': lyngsat_id,
|
||||
'marks': marks_data,
|
||||
'note': source.note if source.note else '-'
|
||||
})
|
||||
|
||||
# Prepare context for template
|
||||
@@ -696,9 +762,16 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
'objitem_count_max': objitem_count_max,
|
||||
'date_from': date_from,
|
||||
'date_to': date_to,
|
||||
'has_signal_mark': has_signal_mark,
|
||||
'mark_date_from': mark_date_from,
|
||||
'mark_date_to': mark_date_to,
|
||||
# Source request filters
|
||||
'has_requests': has_requests,
|
||||
'selected_request_statuses': selected_request_statuses,
|
||||
'selected_request_priorities': selected_request_priorities,
|
||||
'request_gso_success': request_gso_success,
|
||||
'request_kubsat_success': request_kubsat_success,
|
||||
'request_planned_from': request_planned_from,
|
||||
'request_planned_to': request_planned_to,
|
||||
'request_date_from': request_date_from,
|
||||
'request_date_to': request_date_to,
|
||||
# ObjItem-level filters
|
||||
'geo_date_from': geo_date_from,
|
||||
'geo_date_to': geo_date_to,
|
||||
@@ -716,6 +789,10 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
'selected_modulations': [
|
||||
int(x) if isinstance(x, str) else x for x in selected_modulations if (isinstance(x, int) or (isinstance(x, str) and x.isdigit()))
|
||||
],
|
||||
'standards': standards,
|
||||
'selected_standards': [
|
||||
int(x) if isinstance(x, str) else x for x in selected_standards if (isinstance(x, int) or (isinstance(x, str) and x.isdigit()))
|
||||
],
|
||||
'freq_min': freq_min,
|
||||
'freq_max': freq_max,
|
||||
'freq_range_min': freq_range_min,
|
||||
@@ -728,6 +805,9 @@ class SourceListView(LoginRequiredMixin, View):
|
||||
'selected_mirrors': [
|
||||
int(x) if isinstance(x, str) else x for x in selected_mirrors if (isinstance(x, int) or (isinstance(x, str) and x.isdigit()))
|
||||
],
|
||||
# Complex filter choices
|
||||
'complexes': [('kr', 'КР'), ('dv', 'ДВ')],
|
||||
'selected_complexes': selected_complexes,
|
||||
'object_infos': object_infos,
|
||||
'polygon_coords': json.dumps(polygon_coords) if polygon_coords else None,
|
||||
'full_width_page': True,
|
||||
@@ -752,6 +832,48 @@ class AdminModeratorMixin(UserPassesTestMixin):
|
||||
return redirect('mainapp:source_list')
|
||||
|
||||
|
||||
class SourceCreateView(LoginRequiredMixin, AdminModeratorMixin, View):
|
||||
"""View for creating new Source."""
|
||||
|
||||
def get(self, request):
|
||||
form = SourceForm()
|
||||
|
||||
context = {
|
||||
'object': None,
|
||||
'form': form,
|
||||
'objitems': [],
|
||||
'full_width_page': True,
|
||||
}
|
||||
|
||||
return render(request, 'mainapp/source_form.html', context)
|
||||
|
||||
def post(self, request):
|
||||
form = SourceForm(request.POST)
|
||||
|
||||
if form.is_valid():
|
||||
source = form.save(commit=False)
|
||||
# Set created_by and updated_by to current user
|
||||
if hasattr(request.user, 'customuser'):
|
||||
source.created_by = request.user.customuser
|
||||
source.updated_by = request.user.customuser
|
||||
source.save()
|
||||
|
||||
messages.success(request, f'Источник #{source.id} успешно создан.')
|
||||
|
||||
# Redirect to edit page
|
||||
return redirect('mainapp:source_update', pk=source.id)
|
||||
|
||||
# If form is invalid, re-render with errors
|
||||
context = {
|
||||
'object': None,
|
||||
'form': form,
|
||||
'objitems': [],
|
||||
'full_width_page': True,
|
||||
}
|
||||
|
||||
return render(request, 'mainapp/source_form.html', context)
|
||||
|
||||
|
||||
class SourceUpdateView(LoginRequiredMixin, AdminModeratorMixin, View):
|
||||
"""View for editing Source with 4 coordinate fields and related ObjItems."""
|
||||
|
||||
@@ -937,3 +1059,115 @@ class DeleteSelectedSourcesView(LoginRequiredMixin, AdminModeratorMixin, View):
|
||||
|
||||
except Exception as e:
|
||||
return JsonResponse({"error": f"Ошибка при удалении: {str(e)}"}, status=500)
|
||||
|
||||
|
||||
|
||||
class MergeSourcesView(LoginRequiredMixin, AdminModeratorMixin, View):
|
||||
"""View for merging multiple sources into one."""
|
||||
|
||||
def post(self, request):
|
||||
"""Merge selected sources into the first one."""
|
||||
try:
|
||||
# Parse JSON body
|
||||
import json
|
||||
data = json.loads(request.body)
|
||||
|
||||
source_ids = data.get('source_ids', [])
|
||||
info_id = data.get('info_id')
|
||||
ownership_id = data.get('ownership_id')
|
||||
note = data.get('note', '')
|
||||
|
||||
# Validate input
|
||||
if not source_ids or len(source_ids) < 2:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Необходимо выбрать минимум 2 источника для объединения'
|
||||
}, status=400)
|
||||
|
||||
if not info_id:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Необходимо выбрать тип объекта'
|
||||
}, status=400)
|
||||
|
||||
if not ownership_id:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Необходимо выбрать принадлежность объекта'
|
||||
}, status=400)
|
||||
|
||||
# Get all sources
|
||||
sources = Source.objects.filter(id__in=source_ids).order_by('id')
|
||||
|
||||
if sources.count() != len(source_ids):
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Некоторые источники не найдены'
|
||||
}, status=404)
|
||||
|
||||
# First source is the target
|
||||
target_source = sources.first()
|
||||
sources_to_merge = sources.exclude(id=target_source.id)
|
||||
|
||||
# Get ObjectInfo and ObjectOwnership
|
||||
from ..models import ObjectInfo, ObjectOwnership
|
||||
try:
|
||||
info = ObjectInfo.objects.get(id=info_id)
|
||||
ownership = ObjectOwnership.objects.get(id=ownership_id)
|
||||
except (ObjectInfo.DoesNotExist, ObjectOwnership.DoesNotExist):
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Тип объекта или принадлежность не найдены'
|
||||
}, status=404)
|
||||
|
||||
# Start transaction
|
||||
from django.db import transaction
|
||||
|
||||
with transaction.atomic():
|
||||
# Update target source
|
||||
target_source.info = info
|
||||
target_source.ownership = ownership
|
||||
target_source.note = note
|
||||
if hasattr(request.user, 'customuser'):
|
||||
target_source.updated_by = request.user.customuser
|
||||
target_source.save()
|
||||
|
||||
# Move all ObjItems from sources_to_merge to target_source
|
||||
total_moved = 0
|
||||
for source in sources_to_merge:
|
||||
# Get all objitems for this source
|
||||
objitems = source.source_objitems.all()
|
||||
objitem_count = objitems.count()
|
||||
|
||||
# Update source field for all objitems
|
||||
objitems.update(source=target_source)
|
||||
|
||||
total_moved += objitem_count
|
||||
|
||||
# Recalculate coords_average for target source
|
||||
target_source._recalculate_average_coords()
|
||||
target_source.update_confirm_at()
|
||||
target_source.save()
|
||||
|
||||
# Delete sources_to_merge (objitems already moved to target)
|
||||
deleted_count = sources_to_merge.count()
|
||||
sources_to_merge.delete()
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'message': f'Успешно объединено {deleted_count + 1} источников. Перемещено {total_moved} точек в источник #{target_source.id}',
|
||||
'target_source_id': target_source.id,
|
||||
'moved_objitems': total_moved,
|
||||
'deleted_sources': deleted_count
|
||||
})
|
||||
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Неверный формат данных'
|
||||
}, status=400)
|
||||
except Exception as e:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': f'Ошибка при объединении источников: {str(e)}'
|
||||
}, status=500)
|
||||
|
||||
1121
dbapp/mainapp/views/source_requests.py
Normal file
1121
dbapp/mainapp/views/source_requests.py
Normal file
File diff suppressed because it is too large
Load Diff
498
dbapp/mainapp/views/statistics.py
Normal file
498
dbapp/mainapp/views/statistics.py
Normal file
@@ -0,0 +1,498 @@
|
||||
"""
|
||||
Представление для страницы статистики.
|
||||
"""
|
||||
import json
|
||||
from datetime import timedelta
|
||||
from django.db.models import Count, Q, Min, Sum, F, Subquery, OuterRef
|
||||
from django.db.models.functions import TruncDate, Abs
|
||||
from django.utils import timezone
|
||||
from django.views.generic import TemplateView
|
||||
from django.http import JsonResponse
|
||||
|
||||
from ..models import ObjItem, Source, Satellite, Geo, SourceRequest, SourceRequestStatusHistory
|
||||
from mapsapp.models import Transponders
|
||||
|
||||
|
||||
class StatisticsView(TemplateView):
|
||||
"""Страница статистики по данным геолокации."""
|
||||
|
||||
template_name = 'mainapp/statistics.html'
|
||||
|
||||
def get_date_range(self):
|
||||
"""Получает диапазон дат из параметров запроса."""
|
||||
date_from = self.request.GET.get('date_from')
|
||||
date_to = self.request.GET.get('date_to')
|
||||
preset = self.request.GET.get('preset')
|
||||
|
||||
now = timezone.now()
|
||||
|
||||
# Обработка пресетов
|
||||
if preset == 'week':
|
||||
date_from = (now - timedelta(days=7)).date()
|
||||
date_to = now.date()
|
||||
elif preset == 'month':
|
||||
date_from = (now - timedelta(days=30)).date()
|
||||
date_to = now.date()
|
||||
elif preset == '3months':
|
||||
date_from = (now - timedelta(days=90)).date()
|
||||
date_to = now.date()
|
||||
elif preset == '6months':
|
||||
date_from = (now - timedelta(days=180)).date()
|
||||
date_to = now.date()
|
||||
elif preset == 'all':
|
||||
date_from = None
|
||||
date_to = None
|
||||
else:
|
||||
# Парсинг дат из параметров
|
||||
from datetime import datetime
|
||||
if date_from:
|
||||
try:
|
||||
date_from = datetime.strptime(date_from, '%Y-%m-%d').date()
|
||||
except ValueError:
|
||||
date_from = None
|
||||
if date_to:
|
||||
try:
|
||||
date_to = datetime.strptime(date_to, '%Y-%m-%d').date()
|
||||
except ValueError:
|
||||
date_to = None
|
||||
|
||||
return date_from, date_to, preset
|
||||
|
||||
def get_selected_satellites(self):
|
||||
"""Получает выбранные спутники из параметров запроса."""
|
||||
satellite_ids = self.request.GET.getlist('satellite_id')
|
||||
return [int(sid) for sid in satellite_ids if sid.isdigit()]
|
||||
|
||||
def get_selected_location_places(self):
|
||||
"""Получает выбранные комплексы из параметров запроса."""
|
||||
return self.request.GET.getlist('location_place')
|
||||
|
||||
def get_base_queryset(self, date_from, date_to, satellite_ids, location_places=None):
|
||||
"""Возвращает базовый queryset ObjItem с фильтрами."""
|
||||
qs = ObjItem.objects.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__timestamp__isnull=False
|
||||
)
|
||||
|
||||
if date_from:
|
||||
qs = qs.filter(geo_obj__timestamp__date__gte=date_from)
|
||||
if date_to:
|
||||
qs = qs.filter(geo_obj__timestamp__date__lte=date_to)
|
||||
if satellite_ids:
|
||||
qs = qs.filter(parameter_obj__id_satellite__id__in=satellite_ids)
|
||||
if location_places:
|
||||
qs = qs.filter(parameter_obj__id_satellite__location_place__in=location_places)
|
||||
|
||||
return qs
|
||||
|
||||
def get_statistics(self, date_from, date_to, satellite_ids, location_places=None):
|
||||
"""Вычисляет основную статистику."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to, satellite_ids, location_places)
|
||||
|
||||
# Общее количество точек
|
||||
total_points = base_qs.count()
|
||||
|
||||
# Количество уникальных объектов (Source)
|
||||
total_sources = base_qs.filter(source__isnull=False).values('source').distinct().count()
|
||||
|
||||
# Новые излучения - объекты, у которых имя появилось впервые в выбранном периоде
|
||||
new_emissions_data = self._calculate_new_emissions(date_from, date_to, satellite_ids, location_places)
|
||||
|
||||
# Статистика по спутникам
|
||||
satellite_stats = self._get_satellite_statistics(date_from, date_to, satellite_ids, location_places)
|
||||
|
||||
# Данные для графика по дням
|
||||
daily_data = self._get_daily_statistics(date_from, date_to, satellite_ids, location_places)
|
||||
|
||||
return {
|
||||
'total_points': total_points,
|
||||
'total_sources': total_sources,
|
||||
'new_emissions_count': new_emissions_data['count'],
|
||||
'new_emission_objects': new_emissions_data['objects'],
|
||||
'satellite_stats': satellite_stats,
|
||||
'daily_data': daily_data,
|
||||
}
|
||||
|
||||
def _calculate_new_emissions(self, date_from, date_to, satellite_ids, location_places=None):
|
||||
"""
|
||||
Вычисляет новые излучения - уникальные имена объектов,
|
||||
которые появились впервые в выбранном периоде.
|
||||
|
||||
Возвращает количество уникальных новых имён и данные об объектах.
|
||||
Оптимизировано для минимизации SQL запросов.
|
||||
"""
|
||||
if not date_from:
|
||||
# Если нет начальной даты, берём все данные - новых излучений нет
|
||||
return {'count': 0, 'objects': []}
|
||||
|
||||
# Получаем все имена объектов, которые появились ДО выбранного периода
|
||||
existing_names = set(
|
||||
ObjItem.objects.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__timestamp__isnull=False,
|
||||
geo_obj__timestamp__date__lt=date_from,
|
||||
name__isnull=False
|
||||
).exclude(name='').values_list('name', flat=True).distinct()
|
||||
)
|
||||
|
||||
# Базовый queryset для выбранного периода
|
||||
period_qs = self.get_base_queryset(date_from, date_to, satellite_ids, location_places).filter(
|
||||
name__isnull=False
|
||||
).exclude(name='')
|
||||
|
||||
# Получаем уникальные имена в выбранном периоде
|
||||
period_names = set(period_qs.values_list('name', flat=True).distinct())
|
||||
|
||||
# Новые имена = имена в периоде, которых не было раньше
|
||||
new_names = period_names - existing_names
|
||||
|
||||
if not new_names:
|
||||
return {'count': 0, 'objects': []}
|
||||
|
||||
# Оптимизация: получаем все данные одним запросом с группировкой по имени
|
||||
# Используем values() для получения уникальных комбинаций name + info + ownership
|
||||
objitems_data = period_qs.filter(
|
||||
name__in=new_names
|
||||
).select_related(
|
||||
'source__info', 'source__ownership'
|
||||
).values(
|
||||
'name',
|
||||
'source__info__name',
|
||||
'source__ownership__name'
|
||||
).distinct()
|
||||
|
||||
# Собираем данные, оставляя только первую запись для каждого имени
|
||||
seen_names = set()
|
||||
new_objects = []
|
||||
|
||||
for item in objitems_data:
|
||||
name = item['name']
|
||||
if name not in seen_names:
|
||||
seen_names.add(name)
|
||||
new_objects.append({
|
||||
'name': name,
|
||||
'info': item['source__info__name'] or '-',
|
||||
'ownership': item['source__ownership__name'] or '-',
|
||||
})
|
||||
|
||||
# Сортируем по имени
|
||||
new_objects.sort(key=lambda x: x['name'])
|
||||
|
||||
return {'count': len(new_names), 'objects': new_objects}
|
||||
|
||||
def _get_satellite_statistics(self, date_from, date_to, satellite_ids, location_places=None):
|
||||
"""Получает статистику по каждому спутнику."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to, satellite_ids, location_places)
|
||||
|
||||
# Группируем по спутникам
|
||||
stats = base_qs.filter(
|
||||
parameter_obj__id_satellite__isnull=False
|
||||
).values(
|
||||
'parameter_obj__id_satellite__id',
|
||||
'parameter_obj__id_satellite__name'
|
||||
).annotate(
|
||||
points_count=Count('id'),
|
||||
sources_count=Count('source', distinct=True)
|
||||
).order_by('-points_count')
|
||||
|
||||
return list(stats)
|
||||
|
||||
def _get_daily_statistics(self, date_from, date_to, satellite_ids, location_places=None):
|
||||
"""Получает статистику по дням для графика."""
|
||||
base_qs = self.get_base_queryset(date_from, date_to, satellite_ids, location_places)
|
||||
|
||||
daily = base_qs.annotate(
|
||||
date=TruncDate('geo_obj__timestamp')
|
||||
).values('date').annotate(
|
||||
points=Count('id'),
|
||||
sources=Count('source', distinct=True)
|
||||
).order_by('date')
|
||||
|
||||
return list(daily)
|
||||
|
||||
def _get_zone_statistics(self, date_from, date_to, location_place):
|
||||
"""
|
||||
Получает статистику по зоне (КР или ДВ).
|
||||
|
||||
Возвращает:
|
||||
- total_coords: общее количество координат ГЛ
|
||||
- new_coords: количество новых координат ГЛ (уникальные имена, появившиеся впервые)
|
||||
- transfer_delta: сумма дельт переносов по новым транспондерам
|
||||
"""
|
||||
# Базовый queryset для зоны
|
||||
zone_qs = ObjItem.objects.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__timestamp__isnull=False,
|
||||
parameter_obj__id_satellite__location_place=location_place
|
||||
)
|
||||
|
||||
if date_from:
|
||||
zone_qs = zone_qs.filter(geo_obj__timestamp__date__gte=date_from)
|
||||
if date_to:
|
||||
zone_qs = zone_qs.filter(geo_obj__timestamp__date__lte=date_to)
|
||||
|
||||
# Общее количество координат ГЛ
|
||||
total_coords = zone_qs.count()
|
||||
|
||||
# Новые координаты ГЛ (уникальные имена, появившиеся впервые в периоде)
|
||||
new_coords = 0
|
||||
if date_from:
|
||||
# Имена, которые были ДО периода
|
||||
existing_names = set(
|
||||
ObjItem.objects.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__timestamp__isnull=False,
|
||||
geo_obj__timestamp__date__lt=date_from,
|
||||
parameter_obj__id_satellite__location_place=location_place,
|
||||
name__isnull=False
|
||||
).exclude(name='').values_list('name', flat=True).distinct()
|
||||
)
|
||||
|
||||
# Имена в периоде
|
||||
period_names = set(
|
||||
zone_qs.filter(name__isnull=False).exclude(name='').values_list('name', flat=True).distinct()
|
||||
)
|
||||
|
||||
new_coords = len(period_names - existing_names)
|
||||
|
||||
# Расчёт дельты переносов по новым транспондерам
|
||||
transfer_delta = self._calculate_transfer_delta(date_from, date_to, location_place)
|
||||
|
||||
return {
|
||||
'total_coords': total_coords,
|
||||
'new_coords': new_coords,
|
||||
'transfer_delta': transfer_delta,
|
||||
}
|
||||
|
||||
def _calculate_transfer_delta(self, date_from, date_to, location_place):
|
||||
"""
|
||||
Вычисляет сумму дельт по downlink для новых транспондеров.
|
||||
|
||||
Логика:
|
||||
1. Берём все новые транспондеры за период (по created_at)
|
||||
2. Для каждого ищем предыдущий транспондер с таким же именем, спутником и зоной
|
||||
3. Вычисляем дельту по downlink
|
||||
4. Суммируем все дельты
|
||||
"""
|
||||
if not date_from:
|
||||
return 0.0
|
||||
|
||||
# Новые транспондеры за период для данной зоны
|
||||
new_transponders_qs = Transponders.objects.filter(
|
||||
sat_id__location_place=location_place,
|
||||
created_at__date__gte=date_from
|
||||
)
|
||||
if date_to:
|
||||
new_transponders_qs = new_transponders_qs.filter(created_at__date__lte=date_to)
|
||||
|
||||
total_delta = 0.0
|
||||
|
||||
for transponder in new_transponders_qs:
|
||||
if not transponder.name or not transponder.sat_id or transponder.downlink is None:
|
||||
continue
|
||||
|
||||
# Ищем предыдущий транспондер с таким же именем, спутником и зоной
|
||||
previous = Transponders.objects.filter(
|
||||
name=transponder.name,
|
||||
sat_id=transponder.sat_id,
|
||||
zone_name=transponder.zone_name,
|
||||
created_at__lt=transponder.created_at,
|
||||
downlink__isnull=False
|
||||
).order_by('-created_at').first()
|
||||
|
||||
if previous and previous.downlink is not None:
|
||||
delta = abs(transponder.downlink - previous.downlink)
|
||||
total_delta += delta
|
||||
|
||||
return round(total_delta, 2)
|
||||
|
||||
def _get_kubsat_statistics(self, date_from, date_to):
|
||||
"""
|
||||
Получает статистику по Кубсатам из SourceRequest.
|
||||
|
||||
Возвращает:
|
||||
- planned_count: количество запланированных сеансов
|
||||
- conducted_count: количество проведённых
|
||||
- canceled_gso_count: количество отменённых ГСО
|
||||
- canceled_kub_count: количество отменённых МКА
|
||||
"""
|
||||
# Базовый queryset для заявок
|
||||
requests_qs = SourceRequest.objects.all()
|
||||
|
||||
# Фильтруем по дате создания или planned_at
|
||||
if date_from:
|
||||
requests_qs = requests_qs.filter(
|
||||
Q(created_at__date__gte=date_from) | Q(planned_at__date__gte=date_from)
|
||||
)
|
||||
if date_to:
|
||||
requests_qs = requests_qs.filter(
|
||||
Q(created_at__date__lte=date_to) | Q(planned_at__date__lte=date_to)
|
||||
)
|
||||
|
||||
# Получаем ID заявок, у которых в истории был статус 'planned'
|
||||
# Это заявки, которые были запланированы в выбранном периоде
|
||||
history_qs = SourceRequestStatusHistory.objects.filter(
|
||||
new_status='planned'
|
||||
)
|
||||
if date_from:
|
||||
history_qs = history_qs.filter(changed_at__date__gte=date_from)
|
||||
if date_to:
|
||||
history_qs = history_qs.filter(changed_at__date__lte=date_to)
|
||||
|
||||
planned_request_ids = set(history_qs.values_list('source_request_id', flat=True))
|
||||
|
||||
# Также добавляем заявки, которые были созданы со статусом 'planned' в периоде
|
||||
created_planned_qs = SourceRequest.objects.filter(status='planned')
|
||||
if date_from:
|
||||
created_planned_qs = created_planned_qs.filter(created_at__date__gte=date_from)
|
||||
if date_to:
|
||||
created_planned_qs = created_planned_qs.filter(created_at__date__lte=date_to)
|
||||
|
||||
planned_request_ids.update(created_planned_qs.values_list('id', flat=True))
|
||||
|
||||
planned_count = len(planned_request_ids)
|
||||
|
||||
# Считаем статусы из истории для запланированных заявок
|
||||
conducted_count = 0
|
||||
canceled_gso_count = 0
|
||||
canceled_kub_count = 0
|
||||
|
||||
if planned_request_ids:
|
||||
# Получаем историю статусов для запланированных заявок
|
||||
status_history = SourceRequestStatusHistory.objects.filter(
|
||||
source_request_id__in=planned_request_ids
|
||||
)
|
||||
if date_from:
|
||||
status_history = status_history.filter(changed_at__date__gte=date_from)
|
||||
if date_to:
|
||||
status_history = status_history.filter(changed_at__date__lte=date_to)
|
||||
|
||||
# Считаем уникальные заявки по каждому статусу
|
||||
conducted_ids = set(status_history.filter(new_status='conducted').values_list('source_request_id', flat=True))
|
||||
canceled_gso_ids = set(status_history.filter(new_status='canceled_gso').values_list('source_request_id', flat=True))
|
||||
canceled_kub_ids = set(status_history.filter(new_status='canceled_kub').values_list('source_request_id', flat=True))
|
||||
|
||||
conducted_count = len(conducted_ids)
|
||||
canceled_gso_count = len(canceled_gso_ids)
|
||||
canceled_kub_count = len(canceled_kub_ids)
|
||||
|
||||
return {
|
||||
'planned_count': planned_count,
|
||||
'conducted_count': conducted_count,
|
||||
'canceled_gso_count': canceled_gso_count,
|
||||
'canceled_kub_count': canceled_kub_count,
|
||||
}
|
||||
|
||||
def get_extended_statistics(self, date_from, date_to):
|
||||
"""Получает расширенную статистику по зонам и Кубсатам."""
|
||||
kr_stats = self._get_zone_statistics(date_from, date_to, 'kr')
|
||||
dv_stats = self._get_zone_statistics(date_from, date_to, 'dv')
|
||||
kubsat_stats = self._get_kubsat_statistics(date_from, date_to)
|
||||
|
||||
return {
|
||||
'kr': kr_stats,
|
||||
'dv': dv_stats,
|
||||
'kubsat': kubsat_stats,
|
||||
}
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
|
||||
date_from, date_to, preset = self.get_date_range()
|
||||
satellite_ids = self.get_selected_satellites()
|
||||
location_places = self.get_selected_location_places()
|
||||
|
||||
# Получаем только спутники, у которых есть точки ГЛ
|
||||
satellites_with_points = ObjItem.objects.filter(
|
||||
geo_obj__isnull=False,
|
||||
geo_obj__timestamp__isnull=False,
|
||||
parameter_obj__id_satellite__isnull=False
|
||||
).values_list('parameter_obj__id_satellite__id', flat=True).distinct()
|
||||
|
||||
satellites = Satellite.objects.filter(
|
||||
id__in=satellites_with_points
|
||||
).order_by('name')
|
||||
|
||||
# Получаем статистику
|
||||
stats = self.get_statistics(date_from, date_to, satellite_ids, location_places)
|
||||
|
||||
# Получаем расширенную статистику
|
||||
extended_stats = self.get_extended_statistics(date_from, date_to)
|
||||
|
||||
# Сериализуем данные для JavaScript
|
||||
daily_data_json = json.dumps([
|
||||
{
|
||||
'date': item['date'].isoformat() if item['date'] else None,
|
||||
'points': item['points'],
|
||||
'sources': item['sources'],
|
||||
}
|
||||
for item in stats['daily_data']
|
||||
])
|
||||
|
||||
satellite_stats_json = json.dumps(stats['satellite_stats'])
|
||||
extended_stats_json = json.dumps(extended_stats)
|
||||
|
||||
context.update({
|
||||
'satellites': satellites,
|
||||
'selected_satellites': satellite_ids,
|
||||
'location_places': Satellite.PLACES,
|
||||
'selected_location_places': location_places,
|
||||
'date_from': date_from.isoformat() if date_from else '',
|
||||
'date_to': date_to.isoformat() if date_to else '',
|
||||
'preset': preset or '',
|
||||
'total_points': stats['total_points'],
|
||||
'total_sources': stats['total_sources'],
|
||||
'new_emissions_count': stats['new_emissions_count'],
|
||||
'new_emission_objects': stats['new_emission_objects'],
|
||||
'satellite_stats': stats['satellite_stats'],
|
||||
'daily_data': daily_data_json,
|
||||
'satellite_stats_json': satellite_stats_json,
|
||||
'extended_stats': extended_stats,
|
||||
'extended_stats_json': extended_stats_json,
|
||||
})
|
||||
|
||||
return context
|
||||
|
||||
|
||||
class StatisticsAPIView(StatisticsView):
|
||||
"""API endpoint для получения статистики в JSON формате."""
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
date_from, date_to, preset = self.get_date_range()
|
||||
satellite_ids = self.get_selected_satellites()
|
||||
location_places = self.get_selected_location_places()
|
||||
stats = self.get_statistics(date_from, date_to, satellite_ids, location_places)
|
||||
extended_stats = self.get_extended_statistics(date_from, date_to)
|
||||
|
||||
# Преобразуем даты в строки для JSON
|
||||
daily_data = []
|
||||
for item in stats['daily_data']:
|
||||
daily_data.append({
|
||||
'date': item['date'].isoformat() if item['date'] else None,
|
||||
'points': item['points'],
|
||||
'sources': item['sources'],
|
||||
})
|
||||
|
||||
return JsonResponse({
|
||||
'total_points': stats['total_points'],
|
||||
'total_sources': stats['total_sources'],
|
||||
'new_emissions_count': stats['new_emissions_count'],
|
||||
'new_emission_objects': stats['new_emission_objects'],
|
||||
'satellite_stats': stats['satellite_stats'],
|
||||
'daily_data': daily_data,
|
||||
'extended_stats': extended_stats,
|
||||
})
|
||||
|
||||
|
||||
class ExtendedStatisticsAPIView(StatisticsView):
|
||||
"""API endpoint для получения расширенной статистики в JSON формате."""
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
date_from, date_to, preset = self.get_date_range()
|
||||
extended_stats = self.get_extended_statistics(date_from, date_to)
|
||||
|
||||
return JsonResponse({
|
||||
'extended_stats': extended_stats,
|
||||
'date_from': date_from.isoformat() if date_from else None,
|
||||
'date_to': date_to.isoformat() if date_to else None,
|
||||
})
|
||||
485
dbapp/mainapp/views/tech_analyze.py
Normal file
485
dbapp/mainapp/views/tech_analyze.py
Normal file
@@ -0,0 +1,485 @@
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.core.paginator import Paginator
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.views import View
|
||||
from django.views.decorators.http import require_http_methods
|
||||
import json
|
||||
|
||||
from ..models import (
|
||||
TechAnalyze,
|
||||
Satellite,
|
||||
Polarization,
|
||||
Modulation,
|
||||
Standard,
|
||||
ObjItem,
|
||||
Parameter,
|
||||
)
|
||||
from ..mixins import RoleRequiredMixin
|
||||
from ..utils import parse_pagination_params, find_matching_transponder, find_matching_lyngsat
|
||||
|
||||
|
||||
class TechAnalyzeEntryView(LoginRequiredMixin, View):
|
||||
"""
|
||||
Представление для ввода данных технического анализа.
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
satellites = Satellite.objects.all().order_by('name')
|
||||
|
||||
context = {
|
||||
'satellites': satellites,
|
||||
}
|
||||
|
||||
return render(request, 'mainapp/tech_analyze_entry.html', context)
|
||||
|
||||
|
||||
class TechAnalyzeSaveView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API endpoint для сохранения данных технического анализа.
|
||||
"""
|
||||
|
||||
def post(self, request):
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
satellite_id = data.get('satellite_id')
|
||||
rows = data.get('rows', [])
|
||||
|
||||
if not satellite_id:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Не выбран спутник'
|
||||
}, status=400)
|
||||
|
||||
if not rows:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Нет данных для сохранения'
|
||||
}, status=400)
|
||||
|
||||
try:
|
||||
satellite = Satellite.objects.get(id=satellite_id)
|
||||
except Satellite.DoesNotExist:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Спутник не найден'
|
||||
}, status=404)
|
||||
|
||||
created_count = 0
|
||||
updated_count = 0
|
||||
errors = []
|
||||
|
||||
with transaction.atomic():
|
||||
for idx, row in enumerate(rows, start=1):
|
||||
try:
|
||||
name = row.get('name', '').strip()
|
||||
if not name:
|
||||
errors.append(f"Строка {idx}: отсутствует имя")
|
||||
continue
|
||||
|
||||
# Обработка поляризации
|
||||
polarization_name = row.get('polarization', '').strip() or '-'
|
||||
polarization, _ = Polarization.objects.get_or_create(name=polarization_name)
|
||||
|
||||
# Обработка модуляции
|
||||
modulation_name = row.get('modulation', '').strip() or '-'
|
||||
modulation, _ = Modulation.objects.get_or_create(name=modulation_name)
|
||||
|
||||
# Обработка стандарта
|
||||
standard_name = row.get('standard', '').strip()
|
||||
if standard_name.lower() == 'unknown':
|
||||
standard_name = '-'
|
||||
if not standard_name:
|
||||
standard_name = '-'
|
||||
standard, _ = Standard.objects.get_or_create(name=standard_name)
|
||||
|
||||
# Обработка числовых полей
|
||||
frequency = row.get('frequency')
|
||||
if frequency:
|
||||
try:
|
||||
frequency = float(str(frequency).replace(',', '.'))
|
||||
except (ValueError, TypeError):
|
||||
frequency = 0
|
||||
else:
|
||||
frequency = 0
|
||||
|
||||
freq_range = row.get('freq_range')
|
||||
if freq_range:
|
||||
try:
|
||||
freq_range = float(str(freq_range).replace(',', '.'))
|
||||
except (ValueError, TypeError):
|
||||
freq_range = 0
|
||||
else:
|
||||
freq_range = 0
|
||||
|
||||
bod_velocity = row.get('bod_velocity')
|
||||
if bod_velocity:
|
||||
try:
|
||||
bod_velocity = float(str(bod_velocity).replace(',', '.'))
|
||||
except (ValueError, TypeError):
|
||||
bod_velocity = 0
|
||||
else:
|
||||
bod_velocity = 0
|
||||
|
||||
note = row.get('note', '').strip()
|
||||
|
||||
# Создание или обновление записи
|
||||
tech_analyze, created = TechAnalyze.objects.update_or_create(
|
||||
name=name,
|
||||
defaults={
|
||||
'satellite': satellite,
|
||||
'polarization': polarization,
|
||||
'frequency': frequency,
|
||||
'freq_range': freq_range,
|
||||
'bod_velocity': bod_velocity,
|
||||
'modulation': modulation,
|
||||
'standard': standard,
|
||||
'note': note,
|
||||
'updated_by': request.user.customuser if hasattr(request.user, 'customuser') else None,
|
||||
}
|
||||
)
|
||||
|
||||
if created:
|
||||
tech_analyze.created_by = request.user.customuser if hasattr(request.user, 'customuser') else None
|
||||
tech_analyze.save()
|
||||
created_count += 1
|
||||
else:
|
||||
updated_count += 1
|
||||
|
||||
except Exception as e:
|
||||
errors.append(f"Строка {idx}: {str(e)}")
|
||||
|
||||
response_data = {
|
||||
'success': True,
|
||||
'created': created_count,
|
||||
'updated': updated_count,
|
||||
'total': created_count + updated_count,
|
||||
}
|
||||
|
||||
if errors:
|
||||
response_data['errors'] = errors
|
||||
|
||||
return JsonResponse(response_data)
|
||||
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Неверный формат данных'
|
||||
}, status=400)
|
||||
except Exception as e:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}, status=500)
|
||||
|
||||
|
||||
|
||||
class LinkExistingPointsView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API endpoint для привязки существующих точек к данным теханализа.
|
||||
|
||||
Алгоритм:
|
||||
1. Получить все ObjItem для выбранного спутника
|
||||
2. Для каждого ObjItem:
|
||||
- Извлечь имя источника
|
||||
- Найти соответствующую запись TechAnalyze по имени и спутнику
|
||||
- Если найдена и данные отсутствуют в Parameter:
|
||||
* Обновить модуляцию (если "-")
|
||||
* Обновить символьную скорость (если -1.0 или None)
|
||||
* Обновить стандарт (если "-")
|
||||
* Обновить частоту (если 0 или None)
|
||||
* Обновить полосу частот (если 0 или None)
|
||||
* Подобрать подходящий транспондер
|
||||
"""
|
||||
|
||||
def post(self, request):
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
satellite_id = data.get('satellite_id')
|
||||
|
||||
if not satellite_id:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Не выбран спутник'
|
||||
}, status=400)
|
||||
|
||||
try:
|
||||
satellite = Satellite.objects.get(id=satellite_id)
|
||||
except Satellite.DoesNotExist:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Спутник не найден'
|
||||
}, status=404)
|
||||
|
||||
# Получаем все ObjItem для данного спутника
|
||||
objitems = ObjItem.objects.filter(
|
||||
parameter_obj__id_satellite=satellite
|
||||
).select_related('parameter_obj', 'parameter_obj__modulation', 'parameter_obj__standard', 'parameter_obj__polarization')
|
||||
|
||||
updated_count = 0
|
||||
skipped_count = 0
|
||||
errors = []
|
||||
|
||||
with transaction.atomic():
|
||||
for objitem in objitems:
|
||||
try:
|
||||
if not objitem.parameter_obj:
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
parameter = objitem.parameter_obj
|
||||
source_name = objitem.name
|
||||
|
||||
# Проверяем, нужно ли обновлять данные
|
||||
needs_update = (
|
||||
(parameter.modulation and parameter.modulation.name == "-") or
|
||||
parameter.bod_velocity is None or
|
||||
parameter.bod_velocity == -1.0 or
|
||||
parameter.bod_velocity == 0 or
|
||||
(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:
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
# Ищем данные в TechAnalyze по имени и спутнику
|
||||
tech_analyze = TechAnalyze.objects.filter(
|
||||
name=source_name,
|
||||
satellite=satellite
|
||||
).select_related('modulation', 'standard', 'polarization').first()
|
||||
|
||||
if not tech_analyze:
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
# Обновляем данные
|
||||
updated = False
|
||||
|
||||
# Обновляем модуляцию
|
||||
if parameter.modulation and parameter.modulation.name == "-" and tech_analyze.modulation:
|
||||
parameter.modulation = tech_analyze.modulation
|
||||
updated = True
|
||||
|
||||
# Обновляем символьную скорость
|
||||
if (parameter.bod_velocity is None or parameter.bod_velocity == -1.0 or parameter.bod_velocity == 0) and \
|
||||
tech_analyze.bod_velocity and tech_analyze.bod_velocity > 0:
|
||||
parameter.bod_velocity = tech_analyze.bod_velocity
|
||||
updated = True
|
||||
|
||||
# Обновляем стандарт
|
||||
if parameter.standard and parameter.standard.name == "-" and tech_analyze.standard:
|
||||
parameter.standard = tech_analyze.standard
|
||||
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:
|
||||
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
|
||||
else:
|
||||
skipped_count += 1
|
||||
|
||||
except Exception as e:
|
||||
errors.append(f"ObjItem {objitem.id}: {str(e)}")
|
||||
|
||||
response_data = {
|
||||
'success': True,
|
||||
'updated': updated_count,
|
||||
'skipped': skipped_count,
|
||||
'total': objitems.count(),
|
||||
}
|
||||
|
||||
if errors:
|
||||
response_data['errors'] = errors
|
||||
|
||||
return JsonResponse(response_data)
|
||||
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Неверный формат данных'
|
||||
}, status=400)
|
||||
except Exception as e:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}, status=500)
|
||||
|
||||
|
||||
class TechAnalyzeListView(LoginRequiredMixin, View):
|
||||
"""
|
||||
Представление для отображения списка данных технического анализа.
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
# Получаем список спутников для фильтра
|
||||
satellites = Satellite.objects.all().order_by('name')
|
||||
|
||||
# Получаем параметры из URL для передачи в шаблон
|
||||
search_query = request.GET.get('search', '').strip()
|
||||
satellite_ids = request.GET.getlist('satellite_id')
|
||||
items_per_page = int(request.GET.get('items_per_page', 50))
|
||||
|
||||
context = {
|
||||
'satellites': satellites,
|
||||
'selected_satellites': [int(sid) for sid in satellite_ids if sid],
|
||||
'search_query': search_query,
|
||||
'items_per_page': items_per_page,
|
||||
'available_items_per_page': [25, 50, 100, 200, 500],
|
||||
'full_width_page': True,
|
||||
}
|
||||
|
||||
return render(request, 'mainapp/tech_analyze_list.html', context)
|
||||
|
||||
|
||||
class TechAnalyzeDeleteView(LoginRequiredMixin, RoleRequiredMixin, View):
|
||||
"""
|
||||
API endpoint для удаления выбранных записей теханализа.
|
||||
"""
|
||||
allowed_roles = ['admin', 'moderator']
|
||||
|
||||
def post(self, request):
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
ids = data.get('ids', [])
|
||||
|
||||
if not ids:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Не выбраны записи для удаления'
|
||||
}, status=400)
|
||||
|
||||
# Удаляем записи
|
||||
deleted_count, _ = TechAnalyze.objects.filter(id__in=ids).delete()
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'deleted': deleted_count,
|
||||
'message': f'Удалено записей: {deleted_count}'
|
||||
})
|
||||
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': 'Неверный формат данных'
|
||||
}, status=400)
|
||||
except Exception as e:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}, status=500)
|
||||
|
||||
|
||||
|
||||
class TechAnalyzeAPIView(LoginRequiredMixin, View):
|
||||
"""
|
||||
API endpoint для получения данных теханализа в формате для Tabulator.
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
# Получаем параметры фильтрации
|
||||
search_query = request.GET.get('search', '').strip()
|
||||
satellite_ids = request.GET.getlist('satellite_id')
|
||||
|
||||
# Получаем параметры пагинации от Tabulator
|
||||
page = int(request.GET.get('page', 1))
|
||||
size = int(request.GET.get('size', 50))
|
||||
|
||||
# Базовый queryset
|
||||
tech_analyzes = TechAnalyze.objects.select_related(
|
||||
'satellite', 'polarization', 'modulation', 'standard', 'created_by', 'updated_by'
|
||||
).order_by('-created_at')
|
||||
|
||||
# Применяем фильтры
|
||||
if search_query:
|
||||
tech_analyzes = tech_analyzes.filter(
|
||||
Q(name__icontains=search_query) |
|
||||
Q(id__icontains=search_query)
|
||||
)
|
||||
|
||||
if satellite_ids:
|
||||
tech_analyzes = tech_analyzes.filter(satellite_id__in=satellite_ids)
|
||||
|
||||
# Пагинация
|
||||
paginator = Paginator(tech_analyzes, size)
|
||||
page_obj = paginator.get_page(page)
|
||||
|
||||
# Формируем данные для Tabulator
|
||||
results = []
|
||||
for item in page_obj:
|
||||
results.append({
|
||||
'id': item.id,
|
||||
'name': item.name or '',
|
||||
'satellite_id': item.satellite.id if item.satellite else None,
|
||||
'satellite_name': item.satellite.name if item.satellite else '-',
|
||||
'frequency': float(item.frequency) if item.frequency else 0,
|
||||
'freq_range': float(item.freq_range) if item.freq_range else 0,
|
||||
'bod_velocity': float(item.bod_velocity) if item.bod_velocity else 0,
|
||||
'polarization_name': item.polarization.name if item.polarization else '-',
|
||||
'modulation_name': item.modulation.name if item.modulation else '-',
|
||||
'standard_name': item.standard.name if item.standard else '-',
|
||||
'note': item.note or '',
|
||||
'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
'updated_at': item.updated_at.isoformat() if item.updated_at else None,
|
||||
})
|
||||
|
||||
return JsonResponse({
|
||||
'last_page': paginator.num_pages,
|
||||
'data': results,
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user