Compare commits

...

172 Commits
v0.6.2 ... main

Author SHA1 Message Date
zakhy
d8316cfb6c fix id 2025-04-25 11:01:59 +07:00
zakhy
c4ae1011cd ver 2025-04-24 16:30:22 +07:00
zakhy
924aaf2785 Доработки по метео и финансам 2025-04-24 16:29:00 +07:00
zakhy
00ecd848b6 formData 2025-04-24 13:01:04 +07:00
zakhy
2c1fc9a1a0 formData 2025-04-24 12:58:05 +07:00
zakhy
72cb6f9672 formData 2025-04-24 12:51:59 +07:00
zakhy
b39eed1b3b formData 2025-04-24 12:49:11 +07:00
zakhy
9372b9bb75 formData 2025-04-24 12:47:58 +07:00
zakhy
1e7bce1d78 Контекст 2025-04-24 12:43:36 +07:00
zakhy
a5450a8d22 Контекст 2025-04-24 12:40:25 +07:00
zakhy
0aea3820c8 Шихтовщик логин 2025-04-24 12:33:40 +07:00
zakhy
e6d43a15c9 Шихтовщик логин 2025-04-24 12:30:22 +07:00
zakhy
4e8b8fa154 Шихтовщик 2025-04-24 11:31:05 +07:00
zakhy
b2e593feee Фикс 2025-04-24 08:31:59 +07:00
zakhy
ca9332a814 Фикс 2025-04-23 17:57:41 +07:00
zakhy
eac67e5f89 Закрыл пожелания 2025-04-23 17:41:53 +07:00
zakhy
89c7577624 Переработал фронт под новый бек 2025-04-23 16:52:16 +07:00
zakhy
caa2793250 Переработал бек под новое апи 2025-04-23 14:22:18 +07:00
zakhy
61cc64bde8 Убрал url 2025-04-18 18:07:25 +07:00
zakhy
9c9b096f0f black 2025-04-18 17:21:21 +07:00
zakhy
b4dcb5f012 Сортировка 2025-04-11 16:23:30 +07:00
zakhy
856cd20ad2 Исправил багу 2025-04-11 15:58:42 +07:00
zakhy
ce0ed2aaba Поправил миграцию 2025-04-11 15:46:13 +07:00
zakhy
e7f10940d9 Убрал заглушки 2025-04-11 15:27:06 +07:00
zakhy
19e5c42cce Дашборды на заглушках 2025-04-11 14:57:11 +07:00
zakhy
8c16af2d47 Отображение остатков 2025-04-11 10:20:56 +07:00
zakhy
c074f25796 Отдельное приложение под финансы. API 2025-04-10 10:29:29 +07:00
zakhy
54e7da200d Миграция на создание групп, мелкие правки 2025-04-10 09:20:00 +07:00
zakhy
1169ec67aa Обновил фикстуру 2025-04-10 08:29:41 +07:00
zakhy
6fb812600a Миграции 2025-04-10 08:29:31 +07:00
zakhy
f779589fdd Обновил зависимости 2025-04-10 08:21:28 +07:00
zakhy
4efe69d5d1 Посадочная страница для интеграции с 1С 2025-04-09 17:09:16 +07:00
zakhy
f79ee5e1ee Разграничение по правам 2025-04-09 15:52:25 +07:00
zakhy
e3d6c3e8b7 Разрулил проблему с настройками 2025-04-09 10:00:12 +07:00
zakhy
4fe93a5280 fix 2025-02-03 08:49:10 +07:00
zakhy
bd34b85e4d ком 2025-01-31 10:10:38 +07:00
zakhy
bb186215a7 Исправления алгоритма подсчета времени 2025-01-31 09:52:27 +07:00
zakhy
658678818c Регулярные запросы 2025-01-28 08:37:51 +07:00
zakhy
297eff9b0c fix 2025-01-27 18:03:19 +07:00
zakhy
44461573e3 Две стрелочки 2025-01-27 17:51:46 +07:00
zakhy
4186215daa Стрелочка 2025-01-27 17:47:19 +07:00
zakhy
9937ec04c7 Стрелочка 2025-01-27 17:46:42 +07:00
zakhy
d6a23a4443 Стрелочка 2025-01-27 17:46:33 +07:00
zakhy
3c9208a822 Направление ветра 2025-01-27 17:36:45 +07:00
zakhy
8a4f5f4f82 Направление ветра 2025-01-27 17:29:40 +07:00
zakhy
6776296c17 ui fix 2025-01-27 17:23:10 +07:00
zakhy
ca45966260 conver 2025-01-27 16:57:16 +07:00
zakhy
357ed5b047 ver 2025-01-27 16:55:51 +07:00
zakhy
760c84a408 Метеостанция 2025-01-27 16:55:26 +07:00
zakhy
7f35fe0a35 Добавил таймаут 2025-01-27 15:46:52 +07:00
zakhy
899d70df32 Библиотека по версированию 2025-01-27 14:26:08 +07:00
zakhy
f5fd49271c Библиотека по версированию 2025-01-27 11:33:05 +07:00
zakhy
199cea7230 Библиотека по версированию 2025-01-27 11:32:29 +07:00
zakhy
c8793c7ed0 Зависимости 2025-01-27 11:08:41 +07:00
zakhy
6b99b16892 Merge remote-tracking branch 'origin/main' 2025-01-27 11:06:41 +07:00
zakhy
b9c335ecf8 Статическое отображение + апи 2025-01-27 11:06:28 +07:00
19b8c9c579 Обновить README.md 2025-01-24 09:17:34 +00:00
zakhy
ce543c6d2f Добавил кнопку 2025-01-23 16:04:27 +07:00
zakhy
9600c9912f Логирования входов пользователей 2025-01-22 10:36:05 +07:00
2a686089f3 compose 2025-01-22 09:52:22 +07:00
zakhy
5fcf775cb7 rm 2025-01-22 09:25:48 +07:00
zakhy
2b68ad62d4 merge 2025-01-22 08:53:21 +07:00
zakhy
e4fbff3e29 Новый экран скада 2025-01-22 08:51:54 +07:00
zakhy
ff38fc13d6 Новый экран скада 2025-01-21 10:01:30 +07:00
zakhy
8e99a18916 исправление 2025-01-14 17:44:15 +07:00
zakhy
dd85bc231f убрал либу 2025-01-14 17:32:22 +07:00
zakhy
2c7fd17a5a убрал либу 2025-01-14 17:32:11 +07:00
zakhy
b9dbc4d2dd зафиксил багу 2025-01-14 17:31:54 +07:00
zakhy
23b207f052 remove task 2024-11-26 16:10:32 +07:00
zakhy
dbfdfd538d remove task 2024-11-26 16:08:13 +07:00
52f24c14ee rename_field 2024-11-26 14:52:22 +07:00
55a749c0ae upgrade gunicorn version 2024-11-26 14:26:25 +07:00
be04ac30d0 remove uptime 2024-11-26 14:19:40 +07:00
306b07d513 remove model 2024-11-26 13:53:41 +07:00
f2edd2e762 app uptime 2024-10-25 17:04:44 +07:00
715e9d9c76 worktime history 2024-10-25 16:21:31 +07:00
58b8687e2f task datetime change 2024-10-25 16:08:58 +07:00
1d3e435051 datetime calc 2024-10-25 14:24:23 +07:00
199694e5ec comment create scale control 2024-10-25 13:13:02 +07:00
33b234af48 scales db auth from settings 2024-10-25 12:51:30 +07:00
d2183aae1f upd compose 2024-10-25 12:11:03 +07:00
bdc3b3948a to default DF 2024-10-21 13:43:59 +07:00
9c0a24efe8 fixes 2024-10-21 13:05:55 +07:00
fc3de59d5a fixes 2024-10-21 13:01:37 +07:00
f26b1f419a fixes 2024-10-21 12:50:02 +07:00
f5d8ea6a89 fixes 2024-10-21 11:47:43 +07:00
a299ced40f old time calc 2024-10-19 09:20:17 +07:00
1ae7f63cb3 add log volume 2024-10-18 19:03:33 +07:00
fed47907c2 change charset 2024-10-18 17:09:01 +07:00
9df295ccdd change charset 2024-10-18 17:07:09 +07:00
49aef787c6 worktime history, uptime lib 2024-10-18 17:03:13 +07:00
106a66fad3 new time calculation 2024-10-15 10:42:43 +07:00
331900310a new time calculation 2024-10-15 10:40:06 +07:00
ded144966c fix ver 2024-10-15 10:34:52 +07:00
2f05cd62e9 restart always 2024-10-14 11:04:44 +07:00
dacf95b63f db settings from db 2024-10-14 10:42:16 +07:00
5669091ab0 db settings from db 2024-10-14 10:32:08 +07:00
8f8dd1ff70 add dep 2024-10-14 09:47:16 +07:00
c0df30da18 авторестарт при падении 2024-10-14 09:12:50 +07:00
b80c7ec47b пофиксил подсчет времени 2024-09-20 09:45:19 +07:00
46b71f7d8f добавил сборку 2024-09-18 13:05:06 +07:00
dd8c9cd0bb общий рефакторинг 2024-09-18 13:04:42 +07:00
1a74ef2a8d Обработка ошибок Density 2024-09-16 17:19:17 +07:00
6c1957bdce Обработка ошибок Aspiration 2024-09-16 16:51:48 +07:00
28fdd04fbe WorkStatus service 2024-09-16 15:31:47 +07:00
de2111be1e DensitySensors service 2024-09-16 15:09:17 +07:00
9021ed4710 Aspiration service 2024-09-16 14:43:32 +07:00
6d93b824a8 AccidentStops service 2024-09-16 11:12:22 +07:00
7216929715 обновил описание 2024-09-16 11:11:29 +07:00
ed32dd7d49 Merge pull request 'Версия 0.9.1' (#19) from dev into main
Reviewed-on: http://git.hronos.su:8080/sabron/repcofkk/pulls/19
2024-09-10 03:31:44 +00:00
c22844faf2 Merge pull request 'aspiration_units' (#18) from aspiration_units into dev
Reviewed-on: http://git.hronos.su:8080/sabron/repcofkk/pulls/18
2024-09-10 03:30:11 +00:00
15ab057a21 обновил версию 2024-09-10 10:29:31 +07:00
2731bd3337 фронтенд 2024-09-10 10:27:00 +07:00
91587c7df3 маршрут + представление + сервис 2024-09-10 10:26:38 +07:00
cf440be6af aspiration unit model + admin 2024-09-10 10:19:29 +07:00
79fe627829 поменял модель 2024-09-10 10:02:03 +07:00
febff28ba4 коммент 2024-09-10 10:00:47 +07:00
7ed96c8202 фикс 2024-09-09 15:08:12 +07:00
df1bfa981b удалил файловый кэш 2024-09-09 14:29:50 +07:00
a6f6952b1a фикс табуляции 2024-09-09 13:58:39 +07:00
7329842d90 фикс табуляции 2024-09-09 13:53:08 +07:00
228adf07eb Merge pull request 'Версия 0.9' (#17) from dev into main
Reviewed-on: http://git.hronos.su:8080/sabron/repcofkk/pulls/17
2024-09-09 06:35:10 +00:00
45c4067f70 Оптимизация развертывания
- Переопределил volumes
    - code, static volume теперь имеют относительный путь, а не хранятся в папке docker
- Контейнеры: web, celery, celerybeat - теперь поднимаются из одного образа.
2024-09-09 13:24:41 +07:00
5bec96aad8 рефакторинг фронта 2024-09-04 15:47:35 +07:00
dd947f48cf append / 2024-09-02 10:21:54 +07:00
0c853fbbfb убрал более не нужную задачу 2024-09-02 09:16:25 +07:00
fca46b23a2 фикс бага. Данные брались не те, что необходимы 2024-08-30 14:32:21 +07:00
bfcf2ea77b Merge pull request 'dev' (#16) from dev into main
Reviewed-on: http://git.hronos.su:8080/sabron/repcofkk/pulls/16
2024-08-29 10:15:10 +00:00
2e945ce541 Слияние обновления времени работы фабрики и обновления фронта 2024-08-29 13:48:53 +07:00
b4c43530b5 Удалил миграции 2024-08-29 13:43:52 +07:00
8ff936564f Исправил алгоритм подсчета времени работы фабрики 2024-08-29 12:42:19 +07:00
b79233ff26 Правки по фронту, адаптация 2024-08-28 15:51:48 +07:00
bac3abc1f4 Страница администрирования 2024-08-28 15:50:05 +07:00
5d3c3d414f tooltips 2024-08-28 15:49:12 +07:00
e1e0aca250 update readme md 2024-08-28 09:41:11 +07:00
d777ee0aec Преобразование объекта в строку. Flower не может преобразовать 2024-08-28 09:40:46 +07:00
de57248725 Быстрый фикс. Импорт другой функции 2024-08-28 08:51:56 +07:00
6ed4c0d3fb Merge pull request 'Обновление, фиксы, оптимизация' (#15) from dev into main
Reviewed-on: http://git.hronos.su:8080/sabron/repcofkk/pulls/15
2024-08-28 01:37:43 +00:00
e6de49a511 Обновил версию 2024-08-28 08:33:13 +07:00
b57a27204e Удалил комментарии 2024-08-28 08:26:13 +07:00
5698b1e0b4 Merge pull request 'fix-tasks' (#14) from fix-tasks into dev
Reviewed-on: http://git.hronos.su:8080/sabron/repcofkk/pulls/14
2024-08-27 10:16:28 +00:00
b73c351b22 Фикс: поправил задачи
Добавил функцию на создание объектов времени работы фабрики
2024-08-27 17:14:01 +07:00
c5578a8888 Фикс: исправил работу с redis 2024-08-27 15:48:33 +07:00
06bece6f43 фикс: исправил метод определения времени начала смены. 2024-08-27 11:02:00 +07:00
b5458efd51 фикс: замена .seconds на .total_seconds() 2024-08-26 16:13:09 +07:00
b11c8b1e1f миграции 2024-08-26 15:54:10 +07:00
d4f168b734 Убрал аутентификацию в flower 2024-08-26 12:48:44 +07:00
feb423a01b Добавление регулярной задачи на создание записи времени работы фабрики в начале смены 2024-08-26 12:47:43 +07:00
f344ccaf4a Обработка на случай локальной работы 2024-08-26 12:44:57 +07:00
b52cc4db29 Рефакторинг задач 2024-08-26 12:43:48 +07:00
227a54cc79 Адаптация виджетов аспирации 2024-08-26 12:24:02 +07:00
7c5840a811 admin для shiftreport 2024-08-26 12:23:40 +07:00
b71ce2bfcc Доработка внешнего вида 2024-08-22 16:45:38 +07:00
664d509e8a регулярная задача на создание отчета 2024-08-22 13:41:42 +07:00
cc12241148 модель отчета 2024-08-22 13:41:00 +07:00
60f5490e32 стиль к аспирации 2024-08-22 13:38:55 +07:00
21d3cb6f74 новая задача на создание отчета по весам, комментарии к задаче на создание времени работы 2024-08-22 13:33:02 +07:00
f8a79e308e фикс 2024-08-22 13:31:05 +07:00
65d5cb0d82 Страница с аспирационными установками 2024-08-22 13:24:06 +07:00
3aee192b4f Переименовал виджеты 2024-08-22 13:20:21 +07:00
6d04306e3b рефактор апи redis 2024-08-21 16:22:40 +07:00
6440eb1088 обновил стиль 2024-08-21 16:17:52 +07:00
c7e907f538 pre commit 2024-08-21 16:16:16 +07:00
0454d5c0db Виджет "Выход отсева и концентрата" + pre commit 2024-08-21 16:13:17 +07:00
7dd81d03dc Установил pre-commit
Запускает тесты и форматирует код перед коммитом
2024-08-21 15:01:19 +07:00
69313187d8 Убрал чистку бд 2024-08-20 10:59:21 +07:00
aec98de94b Переработка регулярной задачи на создание объектов времени работы фабрики.
Запись создается в момент начала смены, дублируя последний статус
2024-08-20 10:58:36 +07:00
d81acdd675 фикс парсинга времени 2024-08-20 10:53:15 +07:00
6c7423c041 Исправление расчета времени работы 2024-08-16 18:03:38 +07:00
0c101c48e3 Переработка логики определения текущего статуса. Упрощение 2024-08-16 18:03:17 +07:00
1c2d861545 Новая задача по созданию записей времени работы фабрики.
Использует Redis как источник данных
2024-08-16 16:22:26 +07:00
abc7ee07b5 Закоментрировал два сервиса 2024-08-16 16:21:36 +07:00
123 changed files with 5533 additions and 2231 deletions

60
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,60 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace # убирает лишние пробелы
- id: check-added-large-files # проверяет тяжелые файлы на изменения
- id: check-yaml # проверяет синтаксис .yaml файлов
- id: check-json # проверяет синтаксис .json файлов
exclude: launch.json
- id: check-case-conflict # проверяет файлы, которые могут конфликтовать в файловых системах без учета регистра.
- id: check-merge-conflict # проверяет файлы, содержащие конфликтные строки слияния.
- id: double-quote-string-fixer # заменяет " на '
- id: end-of-file-fixer # добавляет пустую строку в конце файла
- repo: https://github.com/adamchainz/django-upgrade
rev: "" # replace with latest tag on GitHub
hooks:
- id: django-upgrade
args: [--target-version, "4.2"]
# Отсортировывает импорты в проекте
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
exclude: __init__.py
args: [ --profile, black, --filter-files ]
# Обновляет синтаксис Python кода в соответствии с последними версиями
- repo: https://github.com/asottile/pyupgrade
rev: v3.17.0
hooks:
- id: pyupgrade
args: [ --py310-plus ]
# Форматирует код под PEP8
- repo: https://github.com/pre-commit/mirrors-autopep8
rev: v2.0.4
hooks:
- id: autopep8
args: [ --max-line-length=120, --in-place ]
# Сканер стилистических ошибок, нарушающие договоренности PEP8
- repo: https://github.com/PyCQA/flake8
rev: 7.1.1
hooks:
- id: flake8
exclude: "app/repcofkk/settings.py"
args: [ "--ignore=E501,F821", "--max-line-length=120" ]
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.4
hooks:
- id: gitleaks
- repo: https://github.com/adamchainz/django-upgrade
rev: "1.22.1" # replace with latest tag on GitHub
hooks:
- id: django-upgrade
args: [ --target-version, "4.2" ] # Replace with Django version

View File

@ -5,7 +5,7 @@
1. Клонировать репозиторий
```bash
git clone http://git.hronos.su:8080/sabron/repcofkk.git
git clone https://git.cybercode.pro/sabron/repcofkk.git
```
2. Запустить compose
@ -20,9 +20,12 @@ docker-compose up -d
docker compose exec web python manage.py createsuperuser
```
4. Заполнить переменные в админке
5. Перезапустить сервис `celery` и `gunicorn`
4. По *Документации пользователя* загрузить или установить вручную настройки
```bash
docker compose exec web python manage.py loaddata positions.json
docker compose exec web python manage.py loaddata settings.json
```
6. При возникновении ошибок смотреть логи контейнеров
```bash
sudo docker compose logs
```
```

View File

@ -1,56 +1,30 @@
###########
# BUILDER #
###########
# pull official base image
FROM python:3.10 as builder
# set work directory
WORKDIR /usr/src/app
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install system dependencies
RUN apt-get update && \
apt-get install -y --no-install-recommends gcc
# install python dependencies
COPY ./requirements.txt .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt
#########
# FINAL #
#########
# pull official base image
# pull official base image
FROM python:3.10
# create directory for the app user
RUN mkdir -p /home/app
# create the app user
RUN addgroup --system app && adduser --system --group app
# create the appropriate directories
ENV HOME=/home/app
ENV APP_HOME=/home/app/web
RUN mkdir $APP_HOME
RUN mkdir $APP_HOME/static
WORKDIR $APP_HOME
# install dependencies
RUN apt-get update && apt-get install -y --no-install-recommends
COPY --from=builder /usr/src/app/wheels /wheels
COPY --from=builder /usr/src/app/requirements.txt .
RUN pip install --upgrade pip
RUN pip install --no-cache /wheels/*
# copy project
COPY . $APP_HOME
RUN chown -R app:app $APP_HOME
USER app
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc
# create the appropriate directories
ENV HOME=/home/app
ENV APP_HOME=/home/app/web
RUN mkdir -p $APP_HOME/static
WORKDIR $APP_HOME
# install python dependencies
COPY ./requirements.txt .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /wheels -r requirements.txt
RUN pip install --no-cache /wheels/* && rm -rf /wheels
# copy project
COPY . $APP_HOME
# create the app user
RUN addgroup --system app && adduser --system --group app && \
chown -R app:app $APP_HOME
USER app

View File

6
app/apps/finance/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class FinanceConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.finance'

View File

View File

@ -0,0 +1,34 @@
import decimal
from dataclasses import dataclass
@dataclass
class DebtorDebt:
"""
Модель элемента дебиторской задолженности.
counter_party: Контрагент;
debt: Долг;
advance: Аванс.
"""
counter_party: str
debt: decimal.Decimal
advance: decimal.Decimal
@dataclass
class Balance:
"""
Модель элемента Остатков по расчетным счетам.
money type: Вид денежных средств;
place: Размещение;
amount_balance: Сумма остаток.
"""
money_type: str
place: str
amount_balance: decimal.Decimal
currency: str
percent: float
account_number: str | None = None
bank_name: str | None = None

View File

@ -0,0 +1,133 @@
import datetime
import decimal
import traceback
import requests
from apps.finance.models import Balance, DebtorDebt
from requests.auth import HTTPBasicAuth
from sabron.util import logging
from sabron.util.sabronmodule import get_settings
class Finance1CAPI:
def __init__(self):
self.fin_1c_api_login = get_settings('1c_api_login')
self.fin_1c_api_password = get_settings('1c_api_password')
self.fin_1c_api_host = get_settings('1c_api_host')
def get_balance(self) -> (list[Balance], dict):
try:
headers = {
'Accept': 'application/json',
}
basic = HTTPBasicAuth(self.fin_1c_api_login,
self.fin_1c_api_password)
url = f'{self.fin_1c_api_host}/hs/saphire-api/balance'
response = requests.get(url, headers=headers, auth=basic)
if response.status_code != 200:
return [], decimal.Decimal(0)
response_data = response.json()
balance_data = []
for balance_item in response_data['data']:
balance_place = balance_item['Размещение'].strip()
amount_balance = balance_item['СуммаОстаток']
money_type = balance_item['ВидДенежныхСредств'].strip()
currency_code = balance_item['Валюта']
summary_for_obj = response_data['summary'][money_type][currency_code]
percent = amount_balance * 100 / summary_for_obj
balance_object = Balance(
money_type=money_type,
place=balance_place,
amount_balance=amount_balance,
currency=currency_code,
percent=percent
)
if ',' in balance_place:
mas = balance_place.split(',', maxsplit=1)
balance_object.account_number = mas[0].strip()
balance_object.bank_name = mas[1].strip()
balance_data.append(balance_object)
return balance_data, response_data['summary']
except Exception:
logging.error(traceback.format_exc())
return [], {}
def get_debts(self) -> dict[str, decimal.Decimal]:
try:
headers = {
'Accept': 'application/json',
}
basic = HTTPBasicAuth(self.fin_1c_api_login,
self.fin_1c_api_password)
date_today = datetime.datetime.now()
formatted_date = date_today.strftime('%Y%m%d')
url = f'{self.fin_1c_api_host}/hs/saphire-api/debts/{formatted_date}'
response = requests.get(url, headers=headers, auth=basic)
response_template = {
'buyers': {
'debts': [],
'summary': {
'debt': 0,
'advance': 0,
},
},
'providers': {
'debts': [],
'summary': {
'debt': 0,
'advance': 0,
},
},
}
if response.status_code != 200:
return response_template
response_data = response.json()
buyers_mas = []
providers_mas = []
for databuyer in response_data['databuyers']:
buyers_mas.append(
DebtorDebt(
counter_party=databuyer['Контрагент'],
debt=databuyer['Долг'],
advance=databuyer['Аванс'],
)
)
for dataprovider in response_data['dataproviders']:
providers_mas.append(
DebtorDebt(
counter_party=dataprovider['Контрагент'],
debt=dataprovider['Долг'],
advance=dataprovider['Аванс'],
)
)
buyers = {
'debts': buyers_mas,
'summary': {
'debt': response_data['summarybuyers']['Долг'],
'advance': response_data['summarybuyers']['Аванс'],
},
}
providers = {
'debts': providers_mas,
'summary': {
'debt': response_data['summaryproviders']['Долг'],
'advance': response_data['summaryproviders']['Аванс'],
},
}
debts_data = {'buyers': buyers, 'providers': providers}
return debts_data
except Exception:
logging.error(traceback.format_exc())
return response_template

View File

@ -0,0 +1,153 @@
from dataclasses import asdict
from apps.finance.models import Balance
from apps.finance.services.integration_1c.api import Finance1CAPI
from apps.main.services.base_service import DashboardBaseService
class Finance1CService(DashboardBaseService):
cash_money_type = 'Деньги в кассе'
bank_money_type = 'Деньги на расчетных счетах'
@staticmethod
def get_balance() -> dict:
api = Finance1CAPI()
data, summary = api.get_balance()
result = {
'error': '',
'status': 0,
'total': len(data),
'items': [asdict(item) for item in data],
'summary': summary,
}
return result
@staticmethod
def get_debtor_debts() -> dict:
api = Finance1CAPI()
data, summary = api.get_debts()
result = {
'error': '',
'status': 0,
'total': len(data),
'items': [asdict(item) for item in data],
'summary': summary,
}
return result
@staticmethod
def get_balance_raw() -> (list[Balance], dict):
api = Finance1CAPI()
return api.get_balance()
@staticmethod
def get_debts_raw() -> dict:
api = Finance1CAPI()
return api.get_debts()
# @classmethod
# def get_balance_grouped_by_currency(cls) -> dict[str, dict]:
# data, summary = cls.get_balance_raw()
# for key, value in summary:
# pass
# res = {
#
# }
@classmethod
def get_balance_grouped_by_money_type(cls) -> (dict, dict):
data, summary = cls.get_balance_raw()
result = {'bank': {}, 'cash': {}}
for balance_object in data:
cls.create_currency_object(
result, asdict(balance_object), balance_object.money_type, summary
)
for outer_key, outer_value in summary.items():
for inner_key, inner_value in outer_value.items():
if outer_key == cls.cash_money_type:
result['cash'][inner_key]['summary'] = inner_value
elif outer_key == cls.bank_money_type:
result['bank'][inner_key]['summary'] = inner_value
result['bank']['643']['data']['main'].sort(key=lambda x: x['amount_balance'], reverse=True)
result['bank']['643']['data']['other'].sort(key=lambda x: x['amount_balance'], reverse=True)
return result
@classmethod
def create_currency_object(cls, result, balance_object, object_money_type, summary):
money_type = 'cash' if object_money_type == cls.cash_money_type else 'bank'
if not result.get(money_type):
result[money_type] = {}
if not result[money_type].get(balance_object['currency']):
result[money_type][balance_object['currency']] = {}
if not result[money_type][balance_object['currency']].get('data'):
result[money_type][balance_object['currency']]['data'] = {}
summary_for_type = summary[object_money_type][balance_object['currency']]
percent = balance_object['amount_balance'] * 100 / summary_for_type
if not result[money_type][balance_object['currency']]['data'].get('main'):
result[money_type][balance_object['currency']]['data']['main'] = []
result[money_type][balance_object['currency']]['data']['other'] = []
if percent > 2:
result[money_type][balance_object['currency']]['data']['main'].append(balance_object)
else:
result[money_type][balance_object['currency']]['data']['other'].append(balance_object)
@classmethod
def get_balance_grouped_by_percent(cls) -> tuple[dict[str, list], float]:
data, summary = cls.get_balance_raw()
main_group = []
other_group = []
for item in data:
percent = item.amount_balance * 100 / summary
if percent > 3:
main_group.append(asdict(item))
else:
other_group.append(asdict(item))
main_group.sort(key=lambda x: x['amount_balance'], reverse=True)
other_group.sort(key=lambda x: x['amount_balance'], reverse=True)
return (
{
'main_group': main_group,
'other_group': other_group,
},
summary,
)
@classmethod
def get_debts_grouped_by_percent(cls):
data = cls.get_debts_raw()
buyers_main_group, buyers_other_group = cls.sort_object_by_percent(
data['buyers']
)
providers_main_group, providers_other_group = cls.sort_object_by_percent(
data['providers']
)
return {
'buyers': {
'main_group': buyers_main_group,
'other_group': buyers_other_group,
'summary': data['buyers']['summary'],
},
'providers': {
'main_group': providers_main_group,
'other_group': providers_other_group,
'summary': data['providers']['summary'],
},
}
@classmethod
def sort_object_by_percent(cls, obj):
main_group = []
other_group = []
for item in obj['debts']:
percent = item.debt * 100 / obj['summary']['debt']
if percent > 1:
main_group.append(asdict(item))
else:
other_group.append(asdict(item))
main_group.sort(key=lambda x: x['debt'], reverse=True)
other_group.sort(key=lambda x: x['debt'], reverse=True)
return main_group, other_group

View File

@ -0,0 +1,15 @@
from apps.finance.services.integration_1c.service import Finance1CService
from apps.util.base_view import base_view
from django.http import JsonResponse
@base_view
def get_balance(request):
data = Finance1CService.get_balance()
return JsonResponse(data)
@base_view
def get_debtor_debts(request):
data = Finance1CService.get_debtor_debts()
return JsonResponse(data)

View File

@ -0,0 +1,487 @@
{% extends 'default.html' %}
{% load humanize %}
{% block content %}
<div class="m-content" style="padding-top: 10px; padding-bottom: 10px;">
<div class="row">
<div class="col-md-6 col-sm-12">
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<b>Остатки по счетам</b>
</h3>
</div>
</div>
</div>
<div class="m-portlet__body p-3">
<div class="d-flex mb-3 p-2" style="gap: 50px; border-bottom: 1px solid #ebedf2 ">
<span style="color: #6f727d; font-size: 15px">
Банк
<br>
<span style="font-size: 16px; font-weight: bold">{{ balances.bank.643.summary|intcomma }} ₽</span> <br>
<span style="font-size: 16px; font-weight: bold">{{ balances.bank.156.summary|intcomma }} ¥</span>
</span>
<span style="color: #6f727d; font-size: 15px">
Касса
<br>
<span style="font-size: 16px; font-weight: bold;">{{ balances.cash.643.summary|intcomma }} ₽</span>
</span>
</div>
<div class="row divider-vertical">
<div class="col-md-6 col-sm-12">
<h4 style="font-size: 18px">Более 2% от общего баланса</h4>
<div id="amountChart" style="min-height: 300px;">
</div>
</div>
<div class="col-md-6 col-sm-12">
<h4 style="font-size: 18px">До 2% от общего баланса</h4>
<div id="amountChart2"></div>
</div>
</div>
<div class="row">
<div class="col-12">
<h4 style="font-size: 18px">Все счета</h4>
<div class="position-sticky" style="top: -5px">
<div class="d-flex">
<span class=""></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.25fr 0.25fr">
<span style="display: flex; align-items: center">
</span>
<div class="d-flex flex-column justify-content-end">
<span class="pr-2 text-align-end"><b>Процент от баланса</b></span>
</div>
<div class="d-flex flex-column">
<span class="pr-2 text-align-end"><b>Остаток</b></span>
</div>
</div>
</div>
</div>
<div class="m-list-timeline" style="max-height: 380px; overflow-x: hidden;">
<div class="m-list-timeline__items">
{% for balance in balances.bank.643.data.main %}
<div class="m-list-timeline__item">
<div class="d-flex">
<span class="m-list-timeline__badge m-list-timeline__badge--success"></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.25fr 0.25fr">
<span>
{% if balance.bank_name and balance.account_number %}
{{ balance.bank_name }}: {{ balance.account_number }}
{% else %}
{% if balance.place %}
{{ balance.place }}
{% else %}
Безымянный счет
{% endif %}
{% endif %}
</span>
<span class="pr-2 text-align-end"><b>{{ balance.percent|floatformat:1 }} %</b></span>
<span class="pr-2 text-align-end"><b>{{ balance.amount_balance|intcomma }} ₽</b></span>
</div>
</div>
</div>
{% endfor %}
{% for balance in balances.bank.643.data.other %}
<div class="m-list-timeline__item">
<div class="d-flex">
<span class="m-list-timeline__badge m-list-timeline__badge--primary"></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.25fr 0.25fr">
<span>
{% if balance.bank_name and balance.account_number %}
{{ balance.bank_name }}: {{ balance.account_number }}
{% else %}
{% if balance.place %}
{{ balance.place }}
{% else %}
Безымянный счет
{% endif %}
{% endif %}
</span>
<span class="pr-2 text-align-end"><b>{{ balance.percent|floatformat:3 }} %</b></span>
<span class="pr-2 text-align-end"><b>{{ balance.amount_balance|intcomma }} ₽</b></span>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-12">
<div class="m-portlet m-portlet--tabs">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<b>Задолженности</b>
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="nav nav-tabs m-tabs m-tabs-line m-tabs-line--right m-tabs-line-danger"
role="tablist">
<li class="nav-item m-tabs__item">
<a class="nav-link m-tabs__link active show" data-toggle="tab"
href="#buyers-tab" role="tab" aria-selected="true">
Покупатели
</a>
</li>
<li class="nav-item m-tabs__item">
<a class="nav-link m-tabs__link" data-toggle="tab" href="#providers-tab"
role="tab" aria-selected="false">
Поставщики
</a>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body">
<div class="tab-content">
<div class="tab-pane active show" id="buyers-tab">
<div class="row">
<div class="col-12">
<div class="d-flex justify-content-between">
<h4 style="font-size: 18px">Более 1% от общего долга</h4>
<span class="m-widget12__text1" style="color: #6f727d; font-size: 15px">
Общая задолженность по покупателям
<br>
<span>Долг: </span><span
style="font-size: 16px; font-weight: bold;">{{ debts.buyers.summary.debt|intcomma }} ₽</span>
<br>
<span>Аванс: </span><span
style="font-size: 16px; font-weight: bold;">{{ debts.buyers.summary.advance|intcomma }} ₽</span>
</div>
<div id="debtsBuyersChart"></div>
</div>
<div class="col-12">
<h4 style="font-size: 18px">Все задолженности по покупателям</h4>
<div class="position-sticky" style="top: -5px">
<div class="d-flex">
<span class=""></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.5fr 0.5fr">
<span style="display: flex; align-items: center">
</span>
<div class="d-flex flex-column justify-content-end">
<span class="pr-2 text-align-end"><b>Долг</b></span>
</div>
<div class="d-flex flex-column">
<span class="pr-2 text-align-end"><b>Аванс</b></span>
</div>
</div>
</div>
</div>
<div class="m-list-timeline" style="max-height: 250px; overflow-x: hidden;">
<div class="m-list-timeline__items">
{% for debtor in debts.buyers.main_group %}
<div class="m-list-timeline__item">
<div class="d-flex">
<span class="m-list-timeline__badge m-list-timeline__badge--success"></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.5fr 0.5fr">
<span style="display: flex; align-items: center">
{{ debtor.counter_party }}
</span>
<div class="d-flex flex-column justify-content-end">
<span class="pr-2 text-align-end"><b>{{ debtor.debt|intcomma }} ₽</b></span>
</div>
<div class="d-flex flex-column">
<span class="pr-2 text-align-end"><b>{{ debtor.advance|intcomma }} ₽</b></span>
</div>
</div>
</div>
</div>
{% endfor %}
{% for debtor in debts.buyers.other_group %}
<div class="m-list-timeline__item">
<div class="d-flex">
<span class="m-list-timeline__badge m-list-timeline__badge--primary"></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.5fr 0.5fr">
<span style="display: flex; align-items: center">
{{ debtor.counter_party }}
</span>
<div class="d-flex flex-column justify-content-end">
<span class="pr-2 text-align-end"><b>{{ debtor.debt|intcomma }} ₽</b></span>
</div>
<div class="d-flex flex-column">
<span class="pr-2 text-align-end"><b>{{ debtor.advance|intcomma }} ₽</b></span>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="providers-tab">
<div class="row">
<div class="col-12">
<div class="d-flex justify-content-between">
<h4 style="font-size: 18px">Более 1% от общего долга</h4>
<span class="m-widget12__text1" style="color: #6f727d; font-size: 15px">
Общая дебиторская задолженность по поставщикам
<br>
<span>Долг: </span><span
style="font-size: 16px; font-weight: bold;">{{ debts.providers.summary.debt|intcomma }} ₽</span>
<br>
<span>Аванс: </span><span
style="font-size: 16px; font-weight: bold;">{{ debts.providers.summary.advance|intcomma }} ₽</span>
</div>
<div id="debtsProvidersChart"></div>
</div>
<div class="col-12">
<h4 style="font-size: 18px">Все задолженности по поставщикам</h4>
<div class="position-sticky" style="top: -5px">
<div class="d-flex">
<span class=""></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.5fr 0.5fr">
<span style="display: flex; align-items: center">
</span>
<div class="d-flex flex-column justify-content-end">
<span class="pr-2 text-align-end"><b>Долг</b></span>
</div>
<div class="d-flex flex-column">
<span class="pr-2 text-align-end"><b>Аванс</b></span>
</div>
</div>
</div>
</div>
<div class="m-list-timeline" style="max-height: 250px; overflow-x: hidden;">
<div class="m-list-timeline__items">
{% for debtor in debts.providers.main_group %}
<div class="m-list-timeline__item">
<div class="d-flex">
<span class="m-list-timeline__badge m-list-timeline__badge--success"></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.5fr 0.5fr">
<span style="display: flex; align-items: center">
{{ debtor.counter_party }}
</span>
<div class="d-flex flex-column justify-content-end">
<span class="pr-2 text-align-end"><b>{{ debtor.debt|intcomma }} ₽</b></span>
</div>
<div class="d-flex flex-column">
<span class="pr-2 text-align-end"><b>{{ debtor.advance|intcomma }} ₽</b></span>
</div>
</div>
</div>
</div>
{% endfor %}
{% for debtor in debts.providers.other_group %}
<div class="m-list-timeline__item">
<div class="d-flex">
<span class="m-list-timeline__badge m-list-timeline__badge--primary"></span>
<div class="w-100"
style="display: grid; grid-template-columns: 1fr 0.5fr 0.5fr">
<span style="display: flex; align-items: center">
{{ debtor.counter_party }}
</span>
<div class="d-flex flex-column justify-content-end">
<span class="pr-2 text-align-end"><b>{{ debtor.debt|intcomma }} ₽</b></span>
</div>
<div class="d-flex flex-column">
<span class="pr-2 text-align-end"><b>{{ debtor.advance|intcomma }} ₽</b></span>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block script_footer %}
<script>
const prettify = (num, separator = ' ') => {
const n = num.toString();
return n.replace(/(\d{1,3}(?=(?:\d\d\d)+(?!\d)))/g, "$1" + separator);
}
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const amountChart = document.getElementById('amountChart');
const amountChart2 = document.getElementById('amountChart2');
const balanceList = {{ balances_json|safe }};
console.log(balanceList)
const mainSeriesData = balanceList.bank["643"].data.main.map(item => item.amount_balance);
const mainLabelsData = balanceList.bank["643"].data.main.map(item => item.account_number ? item.account_number : item.place);
const otherSeriesData = balanceList.bank["643"].data.other.map(item => item.amount_balance);
const otherLabelsData = balanceList.bank["643"].data.other.map(item => item.account_number ? item.account_number : item.place);
const baseOptions = {
chart: {
type: 'donut',
height: 200
},
tooltip: {
y: {
formatter: function (value) {
return prettify(value) + ' ₽'; // или любой формат, например с пробелами
},
title: {
formatter: function (seriesName) {
return "Счет: " + seriesName + " -"; // по умолчанию — просто имя серии
}
}
}
},
dataLabels: {
enabled: false
},
legend: {
show: false
}
};
const options = {
...baseOptions,
series: mainSeriesData,
labels: mainLabelsData,
};
const options2 = {
...baseOptions,
series: otherSeriesData,
labels: otherLabelsData
}
const chart = new ApexCharts(amountChart, options);
chart.render();
const chart2 = new ApexCharts(amountChart2, options2)
chart2.render();
});
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const debtsBuyersChart = document.getElementById('debtsBuyersChart')
const debtsProvidersChart = document.getElementById('debtsProvidersChart')
const debts = {{ debts_json|safe }};
const buyersMainCategories = debts.buyers.main_group.map(item => item.counter_party);
const buyersMainAdvances = debts.buyers.main_group.map(item => item.advance);
const buyersMainDebts = debts.buyers.main_group.map(item => item.debt);
const providersMainCategories = debts.providers.main_group.map(item => item.counter_party);
const providersMainAdvances = debts.providers.main_group.map(item => item.advance);
const providersMainDebts = debts.providers.main_group.map(item => item.debt);
const baseOptions = {
chart: {
type: 'bar',
height: 300
},
plotOptions: {
bar: {
horizontal: true,
dataLabels: {
position: 'top',
},
}
},
dataLabels: {
enabled: false,
offsetX: -6,
style: {
fontSize: '12px',
colors: ['#fff']
}
},
stroke: {
show: true,
width: 1,
colors: ['#fff']
},
tooltip: {
shared: true,
intersect: false,
y: {
formatter: function (value) {
return prettify(value) + ' ₽'; // или любой формат, например с пробелами
},
title: {
formatter: function (seriesName) {
return seriesName + " -"; // по умолчанию — просто имя серии
}
}
}
},
}
var mainBuyersDebtsOptions = {
...baseOptions,
series: [{
name: "Долг",
data: buyersMainDebts
}, {
name: "Аванс",
data: buyersMainAdvances
}],
xaxis: {
categories: buyersMainCategories,
},
};
var mainProvidersDebtsOptions = {
...baseOptions,
series: [{
name: "Долг",
data: providersMainDebts
}, {
name: "Аванс",
data: providersMainAdvances
}],
xaxis: {
categories: providersMainCategories,
},
};
var buyersMainChart = new ApexCharts(debtsBuyersChart, mainBuyersDebtsOptions);
buyersMainChart.render();
var providersMainChart = new ApexCharts(debtsProvidersChart, mainProvidersDebtsOptions);
providersMainChart.render();
})
</script>
{% endblock %}

11
app/apps/finance/urls.py Normal file
View File

@ -0,0 +1,11 @@
from apps.finance.services.integration_1c.views import get_balance, get_debtor_debts
from apps.finance.views_money import fin_index
from django.urls import path
app_name = 'finance'
urlpatterns = [
path('', fin_index, name='fin_index'),
path('balance/', get_balance, name='get_balance'),
path('debts/', get_debtor_debts, name='get_debtor_debts-'),
]

22
app/apps/finance/utils.py Normal file
View File

@ -0,0 +1,22 @@
def get_currency_symbol_by_numeric_code(code: str) -> str:
currency_map = {
'840': '$', # USD — Доллар США
'978': '€', # EUR — Евро
'643': '₽', # RUB — Российский рубль
'826': '£', # GBP — Британский фунт
'392': '¥', # JPY — Японская иена
'124': 'C$', # CAD — Канадский доллар
'036': 'A$', # AUD — Австралийский доллар
'756': 'CHF', # CHF — Швейцарский франк
'156': '¥', # CNY — Китайский юань
'410': '₩', # KRW — Южнокорейская вона
'784': 'د.إ', # AED — Дирхам ОАЭ
'356': '₹', # INR — Индийская рупия
'949': '₺', # TRY — Турецкая лира
'702': 'S$', # SGD — Сингапурский доллар
'554': 'NZ$', # NZD — Новозеландский доллар
'986': 'R$', # BRL — Бразильский реал
'710': 'R', # ZAR — Южноафриканский рэнд
}
return currency_map.get(code, '?')

View File

@ -0,0 +1,45 @@
import json
import traceback
from apps.finance.services.integration_1c.service import Finance1CService
from apps.util.base_view import group_required
from apps.util.generalmodule import get_context_template
from django.contrib.auth.decorators import login_required
from django.core.serializers.json import DjangoJSONEncoder
from django.shortcuts import render
from django.utils.safestring import mark_safe
from django.views.decorators.cache import never_cache
from sabron.util import logging
@login_required(login_url='/accounts/login/?next=')
@group_required('Финансы')
@never_cache
def fin_index(request):
try:
if request.method == 'GET':
context = get_context_template(request)
user_groups = [group.name for group in request.user.groups.all()]
user_have_fin_group = 'Финансы' in user_groups
user_have_coal_group = 'Уголь' in user_groups
context['user_have_fin_group'] = user_have_fin_group
context['user_have_coal_group'] = user_have_coal_group
service = Finance1CService()
debts = service.get_debts_grouped_by_percent()
balances = service.get_balance_grouped_by_money_type()
return render(
request,
'finance/fin_index.html',
{
**context,
'balances': balances,
'balances_json': mark_safe(
json.dumps(balances, cls=DjangoJSONEncoder)),
'debts': debts,
'debts_json': mark_safe(json.dumps(debts, cls=DjangoJSONEncoder)),
},
)
except Exception:
logging.error(traceback.format_exc())

View File

@ -1,41 +1,34 @@
from django.contrib import admin
from apps.main.models.accident_stops import AccidentStop
from apps.main.models.scales_control import ScalesControl, Position
from apps.main.models.aspiration_unit import AspirationUnit
from apps.main.models.scales_control import Position
from apps.main.models.worktime import FabricWorkTime
from django.contrib import admin
@admin.register(FabricWorkTime)
class FabricWorkTimeAdmin(admin.ModelAdmin):
list_display = ["time", "status"]
list_filter = ["time", "status"]
list_display = ['time', 'status']
list_filter = ['time', 'status']
ordering = [
"-time",
'-time',
]
list_editable = [
"status",
'status',
]
@admin.register(ScalesControl)
class ScalesControlAdmin(admin.ModelAdmin):
list_display = ["date_created", "name", "value"]
list_filter = ["time", "name"]
ordering = [
"-time",
]
def date_created(self, obj):
return obj.time.strftime("%x - %X")
@admin.register(AccidentStop)
class AccidentStopAdmin(admin.ModelAdmin):
list_display = ["time"]
list_filter = ["time"]
ordering = ["-time"]
list_display = ['time']
list_filter = ['time']
ordering = ['-time']
@admin.register(Position)
class PositionAdmin(admin.ModelAdmin):
list_display = ["title"]
list_display = ['title']
@admin.register(AspirationUnit)
class AspirationUnitAdmin(admin.ModelAdmin):
pass

View File

@ -1,7 +1,7 @@
# Generated by Django 3.2.23 on 2024-05-30 09:30
# Generated by Django 3.2.25 on 2024-08-29 13:13
import django.utils.timezone
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
@ -12,81 +12,154 @@ class Migration(migrations.Migration):
operations = [
migrations.CreateModel(
name="AccidentStop",
name='AccidentStop',
fields=[
(
"id",
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
verbose_name='ID',
),
),
("time", models.DateTimeField(auto_now=True)),
('time', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'verbose_name': 'Аварийная остановка',
'verbose_name_plural': 'Аварийные остановки',
},
),
migrations.CreateModel(
name="FabricWorkTime",
name='FabricWorkTime',
fields=[
(
"id",
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
verbose_name='ID',
),
),
("time", models.DateTimeField(auto_now=True)),
('time', models.DateTimeField(default=django.utils.timezone.now)),
(
"status",
'status',
models.CharField(
choices=[
("WO", "Работает под нагрузкой"),
("WA", "Работает без нагрузки"),
("NW", "Не работает"),
('WO', 'Работает под нагрузкой'),
('WA', 'Работает без нагрузки'),
('NW', 'Не работает'),
],
max_length=10,
),
),
],
options={
'verbose_name': 'Время работы фабрики',
'verbose_name_plural': 'Отрезки времени работы фабрики',
},
),
migrations.CreateModel(
name="Position",
name='Position',
fields=[
(
"id",
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
verbose_name='ID',
),
),
("title", models.CharField(max_length=100)),
('title', models.CharField(blank=True, max_length=100)),
('tag', models.CharField(blank=True, max_length=80)),
('aver_smena_tag', models.CharField(blank=True, max_length=80)),
('aver_pred_smena_tag', models.CharField(blank=True, max_length=80)),
('smena_tag', models.CharField(blank=True, max_length=80)),
('pred_smena_tag', models.CharField(blank=True, max_length=80)),
('month_tag', models.CharField(blank=True, max_length=80)),
('sutki_tag', models.CharField(blank=True, max_length=80)),
],
options={
'verbose_name': 'Позиция',
'verbose_name_plural': 'Позиции',
},
),
migrations.CreateModel(
name="ScalesControl",
name='ScalesControl',
fields=[
(
"id",
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
verbose_name='ID',
),
),
("time", models.DateTimeField(auto_now=True)),
("value", models.PositiveIntegerField(default=0)),
(
"position",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="main.position"
'name',
models.CharField(
blank=True, db_column='Name', max_length=150, null=True
),
),
(
'value',
models.DecimalField(
blank=True,
db_column='Values',
decimal_places=6,
max_digits=50,
null=True,
),
),
('time', models.DateTimeField(blank=True, db_column='Date', null=True)),
('check', models.BooleanField(db_column='Check', default=False)),
],
options={
'verbose_name': 'Показание весов',
'verbose_name_plural': 'Показания весов',
},
),
migrations.CreateModel(
name='ShiftReport',
fields=[
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID',
),
),
('time', models.DateTimeField()),
('concentrate', models.FloatField()),
('dropout', models.FloatField()),
('scales_data', models.JSONField()),
],
options={
'verbose_name': 'Отчет за смену',
'verbose_name_plural': 'Отчет за смены',
},
),
migrations.AddIndex(
model_name='shiftreport',
index=models.Index(fields=['time'], name='main_shiftr_time_4e29ee_idx'),
),
migrations.AddIndex(
model_name='scalescontrol',
index=models.Index(fields=['name'], name='main_scales_Name_655485_idx'),
),
migrations.AddIndex(
model_name='scalescontrol',
index=models.Index(
fields=['name', 'time'], name='main_scales_Name_9fd251_idx'
),
),
migrations.AddIndex(
model_name='fabricworktime',
index=models.Index(fields=['time'], name='main_fabric_time_314db2_idx'),
),
]

View File

@ -1,54 +0,0 @@
# Generated by Django 3.2.23 on 2024-05-30 10:46
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
("main", "0001_initial"),
]
operations = [
migrations.AlterModelOptions(
name="accidentstop",
options={
"verbose_name": "Аварийная остановка",
"verbose_name_plural": "Аварийные остановки",
},
),
migrations.AlterModelOptions(
name="fabricworktime",
options={
"verbose_name": "Время работы фабрики",
"verbose_name_plural": "Отрезки времени работы фабрики",
},
),
migrations.AlterModelOptions(
name="position",
options={"verbose_name": "Позиция", "verbose_name_plural": "Позиции"},
),
migrations.AlterModelOptions(
name="scalescontrol",
options={
"verbose_name": "Показание весов",
"verbose_name_plural": "Показания весов",
},
),
migrations.AlterField(
model_name="accidentstop",
name="time",
field=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AlterField(
model_name="fabricworktime",
name="time",
field=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AlterField(
model_name="scalescontrol",
name="time",
field=models.DateTimeField(default=django.utils.timezone.now),
),
]

View File

@ -0,0 +1,36 @@
# Generated by Django 3.2.25 on 2025-04-10 01:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='AspirationUnit',
fields=[
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID',
),
),
('mfsb_id', models.IntegerField()),
('tag', models.CharField(blank=True, max_length=50)),
],
options={
'verbose_name': 'Аспирационная установка',
'verbose_name_plural': 'Аспирационные установки',
},
),
migrations.DeleteModel(
name='ShiftReport',
),
]

View File

@ -1,73 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-05 09:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0002_auto_20240530_1046"),
]
operations = [
migrations.CreateModel(
name="Scale",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
(
"name",
models.CharField(
blank=True, db_column="Name", max_length=150, null=True
),
),
(
"values",
models.CharField(
blank=True, db_column="Values", max_length=150, null=True
),
),
("date", models.DateTimeField(blank=True, db_column="Date", null=True)),
("check", models.BooleanField(db_column="Check")),
],
options={
"db_table": "vesi",
"managed": False,
},
),
migrations.RemoveField(
model_name="scalescontrol",
name="position",
),
migrations.RemoveField(
model_name="scalescontrol",
name="time",
),
migrations.RemoveField(
model_name="scalescontrol",
name="value",
),
migrations.AddField(
model_name="scalescontrol",
name="check",
field=models.BooleanField(db_column="Check", default=False),
),
migrations.AddField(
model_name="scalescontrol",
name="date",
field=models.DateTimeField(blank=True, db_column="Date", null=True),
),
migrations.AddField(
model_name="scalescontrol",
name="name",
field=models.CharField(
blank=True, db_column="Name", max_length=150, null=True
),
),
migrations.AddField(
model_name="scalescontrol",
name="values",
field=models.CharField(
blank=True, db_column="Values", max_length=150, null=True
),
),
]

View File

@ -0,0 +1,31 @@
# Generated by Django 3.2.25 on 2025-04-10 01:31
from django.contrib.auth.models import Group, User
from django.db import migrations
def forwards_func(apps, schema_editor):
db_alias = schema_editor.connection.alias
coal, _ = Group.objects.using(db_alias).get_or_create(name='Уголь')
fin, _ = Group.objects.using(db_alias).get_or_create(name='Финансы')
users = User.objects.using(db_alias).all()
for user in users:
user.groups.add(coal)
def reverse_func(apps, schema_editor):
db_alias = schema_editor.connection.alias
try:
Group.objects.using(db_alias).filter(name='Уголь').delete()
Group.objects.using(db_alias).filter(name='Финансы').delete()
except Group.DoesNotExist:
pass
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20250410_0828'),
]
operations = [
migrations.RunPython(forwards_func, reverse_func),
]

View File

@ -1,20 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-05 12:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0003_auto_20240605_0908"),
]
operations = [
migrations.AlterField(
model_name="scalescontrol",
name="name",
field=models.CharField(
blank=True, db_column="Name", max_length=150, null=True, unique=True
),
),
]

View File

@ -0,0 +1,30 @@
# Generated by Django 3.2.25 on 2025-04-24 05:27
from django.db import migrations
from sabron.models import Settings
def forwards_func(apps, schema_editor):
db_alias = schema_editor.connection.alias
u_name, _ = Settings.objects.using(db_alias).get_or_create(name='charger_username', value='secret')
u_pass, _ = Settings.objects.using(db_alias).get_or_create(name='charger_password', value='secret')
def reverse_func(apps, schema_editor):
db_alias = schema_editor.connection.alias
try:
Settings.objects.using(db_alias).filter(name='charger_username').delete()
Settings.objects.using(db_alias).filter(name='charger_password').delete()
except Settings.DoesNotExist:
pass
class Migration(migrations.Migration):
dependencies = [
('main', '0003_auto_20250410_0831'),
]
operations = [
migrations.RunPython(forwards_func, reverse_func),
]

View File

@ -1,33 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-05 14:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0004_alter_scalescontrol_name"),
]
operations = [
migrations.AlterField(
model_name="scalescontrol",
name="check",
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name="scalescontrol",
name="date",
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.AlterField(
model_name="scalescontrol",
name="name",
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name="scalescontrol",
name="values",
field=models.CharField(blank=True, max_length=255, null=True),
),
]

View File

@ -1,37 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-05 14:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0005_auto_20240605_1426"),
]
operations = [
migrations.AlterField(
model_name="scalescontrol",
name="check",
field=models.BooleanField(db_column="Check", default=False),
),
migrations.AlterField(
model_name="scalescontrol",
name="date",
field=models.DateTimeField(blank=True, db_column="Date", null=True),
),
migrations.AlterField(
model_name="scalescontrol",
name="name",
field=models.CharField(
blank=True, db_column="Name", max_length=150, null=True, unique=True
),
),
migrations.AlterField(
model_name="scalescontrol",
name="values",
field=models.CharField(
blank=True, db_column="Values", max_length=150, null=True
),
),
]

View File

@ -1,20 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-05 16:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0006_auto_20240605_1428"),
]
operations = [
migrations.AlterField(
model_name="scalescontrol",
name="name",
field=models.CharField(
blank=True, db_column="Name", max_length=150, null=True
),
),
]

View File

@ -1,26 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-06 10:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0007_alter_scalescontrol_name"),
]
operations = [
migrations.DeleteModel(
name="Scale",
),
migrations.AddField(
model_name="position",
name="tag",
field=models.CharField(blank=True, max_length=128),
),
migrations.AlterField(
model_name="position",
name="title",
field=models.CharField(blank=True, max_length=100),
),
]

View File

@ -1,24 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-10 02:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0008_auto_20240606_1721"),
]
operations = [
migrations.AlterField(
model_name="scalescontrol",
name="values",
field=models.DecimalField(
blank=True,
db_column="Values",
decimal_places=6,
max_digits=50,
null=True,
),
),
]

View File

@ -1,18 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-10 04:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("main", "0009_alter_scalescontrol_values"),
]
operations = [
migrations.RenameField(
model_name="scalescontrol",
old_name="values",
new_name="value",
),
]

View File

@ -1,38 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-11 03:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0010_rename_values_scalescontrol_value"),
]
operations = [
migrations.AddField(
model_name="position",
name="aver_pred_smena_tag",
field=models.CharField(blank=True, max_length=50),
),
migrations.AddField(
model_name="position",
name="aver_smena",
field=models.CharField(blank=True, max_length=50),
),
migrations.AddField(
model_name="position",
name="month_tag",
field=models.CharField(blank=True, max_length=50),
),
migrations.AddField(
model_name="position",
name="pred_smena_tag",
field=models.CharField(blank=True, max_length=50),
),
migrations.AddField(
model_name="position",
name="smena_tag",
field=models.CharField(blank=True, max_length=50),
),
]

View File

@ -1,47 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-11 03:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0011_auto_20240611_1035"),
]
operations = [
migrations.RemoveField(
model_name="position",
name="tag",
),
migrations.AddField(
model_name="position",
name="sutki",
field=models.CharField(blank=True, max_length=80),
),
migrations.AlterField(
model_name="position",
name="aver_pred_smena_tag",
field=models.CharField(blank=True, max_length=80),
),
migrations.AlterField(
model_name="position",
name="aver_smena",
field=models.CharField(blank=True, max_length=80),
),
migrations.AlterField(
model_name="position",
name="month_tag",
field=models.CharField(blank=True, max_length=80),
),
migrations.AlterField(
model_name="position",
name="pred_smena_tag",
field=models.CharField(blank=True, max_length=80),
),
migrations.AlterField(
model_name="position",
name="smena_tag",
field=models.CharField(blank=True, max_length=80),
),
]

View File

@ -1,18 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-11 04:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0012_auto_20240611_1038"),
]
operations = [
migrations.AddField(
model_name="position",
name="tag",
field=models.CharField(blank=True, max_length=80),
),
]

View File

@ -1,23 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-11 04:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("main", "0013_position_tag"),
]
operations = [
migrations.RenameField(
model_name="position",
old_name="aver_smena",
new_name="aver_smena_tag",
),
migrations.RenameField(
model_name="position",
old_name="sutki",
new_name="sutki_tag",
),
]

View File

@ -1,19 +0,0 @@
# Generated by Django 3.2.23 on 2024-06-17 02:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0014_auto_20240611_1123"),
]
operations = [
migrations.AddIndex(
model_name="scalescontrol",
index=models.Index(
fields=["name", "value"], name="main_scales_Name_d49b74_idx"
),
),
]

View File

@ -1,18 +0,0 @@
# Generated by Django 3.2.23 on 2024-07-22 10:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("main", "0015_scalescontrol_main_scales_name_d49b74_idx"),
]
operations = [
migrations.RenameField(
model_name="scalescontrol",
old_name="date",
new_name="time",
),
]

View File

@ -1,31 +0,0 @@
# Generated by Django 3.2.25 on 2024-08-14 10:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0016_rename_date_scalescontrol_time"),
]
operations = [
migrations.RemoveIndex(
model_name="scalescontrol",
name="main_scales_Name_d49b74_idx",
),
migrations.AddIndex(
model_name="fabricworktime",
index=models.Index(fields=["time"], name="main_fabric_time_314db2_idx"),
),
migrations.AddIndex(
model_name="scalescontrol",
index=models.Index(fields=["name"], name="main_scales_Name_655485_idx"),
),
migrations.AddIndex(
model_name="scalescontrol",
index=models.Index(
fields=["name", "time"], name="main_scales_Name_9fd251_idx"
),
),
]

View File

@ -0,0 +1,13 @@
from django.db import models
class AspirationUnit(models.Model):
mfsb_id = models.IntegerField()
tag = models.CharField(max_length=50, blank=True)
def __str__(self):
return f'{self.mfsb_id} | {self.tag}'
class Meta:
verbose_name = 'Аспирационная установка'
verbose_name_plural = 'Аспирационные установки'

View File

@ -2,28 +2,28 @@ from django.db import models
class ScalesControl(models.Model):
name = models.CharField(db_column="Name", max_length=150, blank=True, null=True)
name = models.CharField(db_column='Name', max_length=150, blank=True, null=True)
value = models.DecimalField(
db_column="Values", decimal_places=6, max_digits=50, blank=True, null=True
db_column='Values', decimal_places=6, max_digits=50, blank=True, null=True
)
time = models.DateTimeField(db_column="Date", blank=True, null=True)
check = models.BooleanField(db_column="Check", default=False)
time = models.DateTimeField(db_column='Date', blank=True, null=True)
check = models.BooleanField(db_column='Check', default=False)
class Meta:
verbose_name = "Показание весов"
verbose_name_plural = "Показания весов"
indexes = (models.Index(fields=["name"]), models.Index(fields=["name", "time"]))
verbose_name = 'Показание весов'
verbose_name_plural = 'Показания весов'
indexes = (models.Index(fields=['name']), models.Index(fields=['name', 'time']))
def json(self):
return {
"name": self.name,
"values": self.value,
"date": self.date,
'name': self.name,
'values': self.value,
'date': self.time.isoformat(),
}
def __str__(self):
name = " ".join(self.name.split(".")[3:])
return f"{name} : {self.time} : {self.value}"
name = ' '.join(self.name.split('.')[3:])
return f'{name} : {self.time} : {self.value}'
class Position(models.Model):
@ -41,8 +41,8 @@ class Position(models.Model):
sutki_tag = models.CharField(max_length=80, blank=True)
class Meta:
verbose_name = "Позиция"
verbose_name_plural = "Позиции"
verbose_name = 'Позиция'
verbose_name_plural = 'Позиции'
def __str__(self):
return self.title

View File

@ -1,3 +1,4 @@
from django.conf import settings
from django.db import models
from django.utils.timezone import now
@ -16,18 +17,18 @@ class FabricWorkTime(models.Model):
time = models.DateTimeField(default=now)
status = models.CharField(
choices=(
("WO", "Работает под нагрузкой"),
("WA", "Работает без нагрузки"),
("NW", "Не работает"),
('WO', 'Работает под нагрузкой'),
('WA', 'Работает без нагрузки'),
('NW', 'Не работает'),
),
max_length=10,
)
class Meta:
verbose_name = "Время работы фабрики"
verbose_name_plural = "Отрезки времени работы фабрики"
verbose_name = 'Время работы фабрики'
verbose_name_plural = 'Отрезки времени работы фабрики'
indexes = (models.Index(fields=["time"]),)
indexes = (models.Index(fields=['time']),)
def __str__(self):
return f"{self.time}: {self.status}"
return f'{self.time.astimezone(settings.TIME_ZONE_OBJECT)}: {self.status}'

View File

@ -0,0 +1,12 @@
from apps.main.models.accident_stops import AccidentStop
from django.db.models import QuerySet
class AccidentStopRepository:
@staticmethod
def get_stops_by_range(start_time, end_time) -> QuerySet:
return AccidentStop.objects.filter(time__range=(start_time, end_time))
@staticmethod
def count_stops_by_range(start_time, end_time) -> int:
return AccidentStopRepository.get_stops_by_range(start_time, end_time).count()

View File

@ -1,21 +1,23 @@
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from apps.main.models.accident_stops import AccidentStop
from apps.main.services.accident_stops.repository import AccidentStopRepository
from apps.main.services.base_service import DashboardBaseService
from dateutil.relativedelta import relativedelta
class AccidentStopsService(DashboardBaseService):
def get_stops_by_ranges(self) -> dict:
now_date = self.get_current_time()
start_month = now_date - relativedelta(hours=730)
start_week = now_date - relativedelta(hours=168)
start_day = now_date - relativedelta(hours=24)
model = AccidentStop
stops_by_month = self.get_qs_by_range(start_month, now_date)
stops_by_week = self.get_qs_by_range(start_week, now_date)
stops_by_day = self.get_qs_by_range(start_day, now_date)
return {
"stops_by_month": stops_by_month.count(),
"stops_by_week": stops_by_week.count(),
"stops_by_day": stops_by_day.count(),
@staticmethod
def get_stops_by_ranges() -> dict:
now_date = AccidentStopsService.get_current_time()
time_ranges = {
'month': now_date - relativedelta(hours=730),
'week': now_date - relativedelta(hours=168),
'day': now_date - relativedelta(hours=24),
}
stops_by_ranges = {}
for key, start_time in time_ranges.items():
stops_by_ranges[f'stops_by_{key}'] = (
AccidentStopRepository.count_stops_by_range(start_time, now_date)
)
return stops_by_ranges

View File

@ -1,11 +1,9 @@
from django.http import JsonResponse
from apps.main.models.accident_stops import AccidentStop
from apps.main.services.accident_stops.service import AccidentStopsService
from apps.util.base_view import base_view
from django.http import JsonResponse
@base_view
def get_accident_stops(request):
service = AccidentStopsService(AccidentStop)
return JsonResponse(service.get_stops_by_ranges())
response_data = AccidentStopsService.get_stops_by_ranges()
return JsonResponse(response_data)

View File

@ -0,0 +1,23 @@
import requests
from sabron.util import logging
from sabron.util.sabronmodule import get_settings
class AspirationUnitAPI:
def __init__(self):
self.api_host = get_settings('api_host')
def get_aspiration_unit_by_id(self, id: int):
try:
response = requests.get(
f'{self.api_host}/api/v2/scada/sensor/{id}', timeout=1
)
except Exception as e:
logging.error(str(e))
return {}
data = response.json()['responce']
return {
'name': data['name'],
'date': data['connect_time'],
'status': bool(data['value']),
}

View File

@ -0,0 +1,17 @@
from apps.main.models.aspiration_unit import AspirationUnit
from apps.main.services.aspiration.api import AspirationUnitAPI
from apps.main.services.base_service import DashboardBaseService
class AspirationService(DashboardBaseService):
@classmethod
def get_aspiration_unit_list(cls) -> list[dict]:
api = AspirationUnitAPI()
qs = AspirationUnit.objects.values_list('mfsb_id', flat=True)
res = []
for id_ in qs:
asp_unit = api.get_aspiration_unit_by_id(id=id_)
if asp_unit:
res.append(asp_unit)
return res

View File

@ -0,0 +1,7 @@
from apps.main.services.aspiration.service import AspirationService
from django.http import JsonResponse
def get_aspiration_units_data(request):
response_data = AspirationService.get_aspiration_unit_list()[::-1]
return JsonResponse({'data': response_data})

View File

@ -1,7 +1,7 @@
from datetime import timedelta, datetime
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.db.models import Model
from django.conf import settings
from django.utils import timezone
@ -11,18 +11,18 @@ class DashboardBaseService:
def get_qs_by_range(self, start, end):
return (
self.model.objects.only("time")
self.model.objects.only('time')
.filter(time__range=(start, end))
.order_by("time")
.order_by('time')
.values()
)
def get_latest_value(self):
self.model.objects.latest("time")
self.model.objects.latest('time')
@staticmethod
def get_current_time():
return timezone.now()
return timezone.now().astimezone(settings.TIME_ZONE_OBJECT)
@staticmethod
def get_shift_start(now_date: datetime):
@ -31,6 +31,19 @@ class DashboardBaseService:
start_shift = now_date.replace(
hour=20, minute=0, second=0, microsecond=0
) - relativedelta(days=1)
elif now_date.hour > 20:
elif now_date.hour >= 20:
start_shift = now_date.replace(hour=20, minute=0, second=0, microsecond=0)
return start_shift
@staticmethod
def round_time(dt: datetime):
# Умножаем минуту на 60 и добавляем секунды для получения общего числа секунд
total_seconds = dt.hour * 3600 + dt.minute * 60 + dt.second
# Округляем до ближайшего часа
if total_seconds % 3600 >= 1800: # Если больше половины часа
total_seconds += 3600 - (total_seconds % 3600) # Округляем вверх
else:
total_seconds -= total_seconds % 3600 # Округляем вниз
# Получаем новые часы, минуты и секунды
new_hour = (total_seconds // 3600) % 24 # 24-часовой формат
return dt.replace(hour=new_hour, minute=0, second=0, microsecond=0)

View File

@ -0,0 +1,33 @@
import requests
from sabron.util import logging
from sabron.util.sabronmodule import get_settings
class DensitySensorAPI:
def __init__(self):
self.api_login = get_settings('api_login')
self.api_password = get_settings('api_password')
self.api_host = get_settings('api_host')
def get_sensors_list(self) -> dict | bool:
try:
response = requests.get(
f'{self.api_host}/api/v1/json/montorem/?method=sensor_list',
auth=(self.api_login, self.api_password),
timeout=1,
)
except Exception as e:
logging.error(str(e))
return {}
if response.status_code == 200:
return response.json()
return False
def get_sensor_value(self, sensor_id: int, interval: str = 'hour') -> dict | bool:
response = requests.post(
f'{self.api_host}/api/v1/json/montorem/?method=sensor_readings&id={sensor_id}&sensor_type={interval}',
auth=(self.api_login, self.api_password),
)
if response.status_code == 200:
return response.json()
return False

View File

@ -1,34 +1,22 @@
import requests
from apps.main.services.base_service import DashboardBaseService
from apps.main.services.density_sensors.api import DensitySensorAPI
class DensitySensorsService(DashboardBaseService):
def __init__(self, api_login: str, api_password: str, api_host: str):
super().__init__()
self.api_host = api_host
self.api_password = api_password
self.api_login = api_login
@staticmethod
def get_sensors_list(interval: str | None) -> list:
api = DensitySensorAPI()
assert isinstance(api_host, str)
assert isinstance(api_password, str)
assert isinstance(api_login, str)
def get_sensors_list(self) -> dict | bool:
response = requests.get(
f"{self.api_host}/api/v1/json/montorem/?method=sensor_list",
auth=(self.api_login, self.api_password),
)
if response.status_code == 200:
return response.json()
return False
def get_sensor_value(self, sensor_id: int, interval: str = "hour") -> dict | bool:
response = requests.post(
f"{self.api_host}/api/v1/json/montorem/?method=sensor_readings&id={sensor_id}&sensor_type={interval}",
auth=(self.api_login, self.api_password),
)
if response.status_code == 200:
return response.json()
return False
sensors = api.get_sensors_list()
if not sensors:
return []
if interval:
sensors_id_list = [sensor['id'] for sensor in sensors['respose']]
sensors_values_list = []
for sensor_id in sensors_id_list:
sensor_value = api.get_sensor_value(sensor_id, interval)
sensor_value['name'] = sensors['respose'][sensor_id - 1]['name']
sensors_values_list.append(sensor_value)
return {'sensors': sensors_values_list}
return sensors

View File

@ -1,26 +1,9 @@
from django.http import JsonResponse
from apps.main.services.density_sensors.service import DensitySensorsService
from apps.util.base_view import base_view
from sabron.util.sabronmodule import get_settings
from django.http import JsonResponse
@base_view
def get_sensors_list(request):
api_login = get_settings("api_login")
api_password = get_settings("api_password")
api_host = get_settings("api_host")
service = DensitySensorsService(
api_login=api_login, api_password=api_password, api_host=api_host
)
sensors = service.get_sensors_list()
interval = request.GET.get("interval")
if interval:
sensors_id_list = [sensor["id"] for sensor in sensors["respose"]]
sensors_values_list = []
for sensor_id in sensors_id_list:
sensor_value = service.get_sensor_value(sensor_id, interval)
sensor_value["name"] = sensors["respose"][sensor_id - 1]["name"]
sensors_values_list.append(sensor_value)
return JsonResponse({"sensors": sensors_values_list})
return JsonResponse(sensors)
interval = request.GET.get('interval')
return JsonResponse(DensitySensorsService.get_sensors_list(interval), safe=False)

View File

@ -0,0 +1,34 @@
import datetime
import traceback
import requests
from sabron.util import logging
from sabron.util.sabronmodule import get_settings
class MeteoStationAPI:
def __init__(self):
self.api_token = get_settings('meteo_api_token')
self.post_id = get_settings('post_id')
def get_latest_post(self) -> dict | bool:
headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {self.api_token}',
}
try:
date_today = datetime.datetime.now().date().isoformat()
url = f'https://mycityair.ru/harvester/v2/Posts/{self.post_id}/measurements?interval=1h&date__gt={date_today}&limit=1'
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()['data']
if len(data) > 0:
return data[-1]
return {}
except Exception:
logging.error(traceback.format_exc())
return {}

View File

@ -0,0 +1,9 @@
from apps.main.services.base_service import DashboardBaseService
from apps.main.services.meteo.api import MeteoStationAPI
class MeteoStationService(DashboardBaseService):
@staticmethod
def get_latest_post():
api = MeteoStationAPI()
return api.get_latest_post()

View File

@ -0,0 +1,9 @@
from apps.main.services.meteo.service import MeteoStationService
from apps.util.base_view import base_view
from django.http import JsonResponse
@base_view
def get_meteo_data(request):
data = MeteoStationService.get_latest_post()
return JsonResponse(data, safe=False)

View File

@ -1,13 +1,13 @@
import logging
import traceback
from datetime import datetime
from django.db.models import QuerySet
from typing import Any
from apps.main.services.base_service import DashboardBaseService
from apps.util.redis_api import RedisService
from django.conf import settings
from django.db.models import QuerySet
from repcofkk.settings import REDIS_HOST, REDIS_PORT
REDIS_HOST = settings.REDIS_HOST
REDIS_PORT = settings.REDIS_PORT
class RedisRepository(DashboardBaseService):
@ -22,50 +22,61 @@ class RedisRepository(DashboardBaseService):
self.service = service
super().__init__()
def get_scales_value(self, positions: QuerySet, interval: str) -> dict:
res = {}
scales = {}
latest_date = None
def get_scales_value(self, positions: QuerySet, interval: str) -> dict[str, Any]:
res: dict[str, Any] = {}
scales: dict[str, int] = {}
latest_date: datetime | None = datetime(1970, 1, 1, 0, 0, 0, 0)
with self.service as redis_service:
for position in positions:
if position.tag == "SIEMENSPLC.AZG01.ReportProdDB.ProdPos13":
if position.tag == 'SIEMENSPLC.AZG01.ReportProdDB.ProdPos13':
pass
position_value = redis_service.hget_value(
f"{position.tag}.{interval}", "Value"
f'{position.tag}.{interval}', 'Value'
)
if position_value is None:
position_value = "0"
position_value = '0'
position_date_str = redis_service.hget_value(
f"{position.tag}.{interval}", "Date"
f'{position.tag}.{interval}', 'Date'
)
position_date: datetime | None = None
if position_date_str is not None:
position_date = datetime.strptime(
position_date_str, "%Y-%m-%d %H:%M:%S.%f"
)
try:
position_date = datetime.strptime(
position_date_str, '%Y-%m-%d %H:%M:%S.%f'
)
except ValueError:
position_date = datetime.strptime(
position_date_str, '%Y-%m-%d %H:%M:%S'
)
scales[position.title] = (
int(float(position_value)) if int(float(position_value)) >= 0 else 0
)
if latest_date:
if latest_date < position_date:
if position_date is not None:
if latest_date is None or latest_date < position_date:
latest_date = position_date
else:
latest_date = position_date
try:
res["scales"] = scales
res["percent_values"] = self.get_percent_values(
scales["Поз. 13"], scales["Поз. 22"], scales["Поз. 4"]
res['scales'] = scales
res['percent_values'] = self.get_percent_values(
scales.get('Поз. 13', 0),
scales.get('Поз. 22', 0),
scales.get('Поз. 4', 0),
)
res["latest_date"] = latest_date
res['latest_date'] = latest_date
except AttributeError:
res["latest_date"] = None
finally:
return res
res['latest_date'] = None
return res
def get_scales_value_by_shifts(self, positions: QuerySet, interval: str) -> dict:
res = {}
current_work_shift = {}
previous_work_shift = {}
res: dict[str, dict[str, Any] | datetime | None] = {}
current_work_shift: dict[str, int] = {}
previous_work_shift: dict[str, int] = {}
latest_previous_shift_date = None
latest_current_shift_date = None
percent_values = {}
@ -75,12 +86,17 @@ class RedisRepository(DashboardBaseService):
position, interval, is_current=False
)
previous_value = int(
float(redis_service.hget_value(previous_shift_tag, "Value"))
)
previous_date_str = redis_service.hget_value(previous_shift_tag, "Date")
previous_date = datetime.strptime(
previous_date_str, "%Y-%m-%d %H:%M:%S.%f"
float(redis_service.hget_value(previous_shift_tag, 'Value'))
)
previous_date_str = redis_service.hget_value(previous_shift_tag, 'Date')
try:
previous_date = datetime.strptime(
previous_date_str, '%Y-%m-%d %H:%M:%S.%f'
)
except Exception:
previous_date = datetime.strptime(
previous_date_str, '%Y-%m-%d %H:%M:%S'
)
previous_work_shift[position.title] = previous_value
if latest_previous_shift_date:
@ -93,12 +109,17 @@ class RedisRepository(DashboardBaseService):
position, interval, is_current=True
)
current_value = int(
float(redis_service.hget_value(current_shift_tag, "Value"))
)
current_date_str = redis_service.hget_value(current_shift_tag, "Date")
current_date = datetime.strptime(
current_date_str, "%Y-%m-%d %H:%M:%S.%f"
float(redis_service.hget_value(current_shift_tag, 'Value'))
)
current_date_str = redis_service.hget_value(current_shift_tag, 'Date')
try:
current_date = datetime.strptime(
current_date_str, '%Y-%m-%d %H:%M:%S.%f'
)
except Exception:
current_date = datetime.strptime(
current_date_str, '%Y-%m-%d %H:%M:%S'
)
current_work_shift[position.title] = current_value
if latest_current_shift_date:
@ -107,30 +128,30 @@ class RedisRepository(DashboardBaseService):
else:
latest_current_shift_date = current_date
percent_values["current_shift"] = self.get_percent_values(
current_work_shift["Поз. 13"],
current_work_shift["Поз. 22"],
current_work_shift["Поз. 4"],
percent_values['current_shift'] = self.get_percent_values(
current_work_shift['Поз. 13'],
current_work_shift['Поз. 22'],
current_work_shift['Поз. 4'],
)
percent_values["previous_shift"] = self.get_percent_values(
previous_work_shift["Поз. 13"],
previous_work_shift["Поз. 22"],
previous_work_shift["Поз. 4"],
percent_values['previous_shift'] = self.get_percent_values(
previous_work_shift['Поз. 13'],
previous_work_shift['Поз. 22'],
previous_work_shift['Поз. 4'],
)
res["percent_values"] = percent_values
res['percent_values'] = percent_values
res["previous_work_shift"] = previous_work_shift
res["current_work_shift"] = current_work_shift
res['previous_work_shift'] = previous_work_shift
res['current_work_shift'] = current_work_shift
if latest_previous_shift_date and latest_current_shift_date:
res["latest_date"] = (
res['latest_date'] = (
latest_current_shift_date
if latest_previous_shift_date < latest_current_shift_date
else latest_previous_shift_date
)
else:
res["latest_date"] = (
res['latest_date'] = (
latest_current_shift_date if latest_current_shift_date else None
)
@ -139,13 +160,39 @@ class RedisRepository(DashboardBaseService):
def get_scales_value_with_plan(self):
with self.service as redis_service:
scales_value = int(
float(redis_service.hget_value(self.control_conveyor_month, "Value"))
float(redis_service.hget_value(self.control_conveyor_month, 'Value'))
)
if scales_value == "0":
return {"value": 0, "percent": 0, "goal": 0}
if scales_value == '0':
return {'value': 0, 'percent': 0, 'goal': 0}
planned_value = int(self.fabric_goal)
percent = str(round(scales_value * 100 / int(planned_value))) + "%"
return {"value": scales_value, "percent": percent, "goal": planned_value}
percent = str(round(scales_value * 100 / int(planned_value))) + '%'
return {'value': scales_value, 'percent': percent, 'goal': planned_value}
def get_concentrate_value(self):
with self.service as redis_service:
kek = redis_service.get_value('kek')
breed = redis_service.get_value('breed')
pos4_value = redis_service.hget_value(
'SIEMENSPLC.AZG01.ReportProdDB.ProdPos4.Smena', 'Value'
)
pos13_value = redis_service.hget_value(
'SIEMENSPLC.AZG01.ReportProdDB.ProdPos13.Smena', 'Value'
)
pos22_value = redis_service.hget_value(
'SIEMENSPLC.AZG01.ReportProdDB.ProdPos22.Smena', 'Value'
)
if kek is None or breed is None:
value = False
else:
value = self.calculate_concentrate_and_dropout_value(
int(float(pos4_value)),
int(float(pos13_value)),
int(float(pos22_value)),
int(float(kek)),
int(float(breed)),
)
return value
@staticmethod
def get_percent_values(pos13_value: int, pos22_value: int, pos4_value: int) -> dict:
@ -165,20 +212,71 @@ class RedisRepository(DashboardBaseService):
except ZeroDivisionError:
dropout = 0
return {
"Y к-та": concentrate,
"Y отсева": dropout,
'Y к-та': concentrate,
'Y отсева': dropout,
}
@staticmethod
def calculate_concentrate_and_dropout_value(
pos4_value: int, pos13_value: int, pos22_value: int, kek: int, breed: int
) -> dict[str, int | str]:
try:
concentrate: int | float = (
pos4_value - pos13_value - (kek * 0.6) - breed
) / (pos4_value / 100)
except ZeroDivisionError:
concentrate = 0 # Возвращаем число вместо строки
try:
dropout: int | float = (pos4_value - pos22_value - (kek * 0.6) - breed) / (
pos4_value / 100
)
except ZeroDivisionError:
dropout = 0 # Возвращаем число вместо строки
result: dict[str, int | str] = {
'concentrate': abs(int(concentrate)),
'dropout': abs(int(dropout)),
}
return result
@staticmethod
def get_shift_tag(position, interval, is_current):
"""
Получает тег смены для заданной позиции в зависимости от интервала и типа смены.
"""
if is_current:
return position.aver_smena_tag if interval == "Aver" else position.smena_tag
return position.aver_smena_tag if interval == 'Aver' else position.smena_tag
else:
return (
position.aver_pred_smena_tag
if interval == "Aver"
if interval == 'Aver'
else position.pred_smena_tag
)
def set_kek_and_breed_values(self, data: dict):
try:
with self.service as redis_service:
redis_service.set_value('kek', data['kek'])
redis_service.set_value('breed', data['breed'])
return True
except Exception:
return False
def get_kek_and_breed_values(self):
try:
with self.service as redis_service:
kek = redis_service.get_value('kek')
breed = redis_service.get_value('breed')
return {'success': True, 'kek': kek, 'breed': breed}
except Exception:
return {'success': False, 'message': 'some error occurred'}
def delete_kek_and_breed_values(self):
try:
with self.service as redis_service:
redis_service.delete_value('kek')
redis_service.delete_value('breed')
return {'success': True}
except Exception:
return {'success': False, 'message': 'some error occurred'}

View File

@ -1,28 +1,81 @@
from django.http import JsonResponse
import json
from apps.main.models.scales_control import ScalesControl, Position
from apps.main.models.scales_control import Position
from apps.main.services.scales_control.redis_repository import RedisRepository
from apps.main.services.scales_control.service import ScalesControlService
from apps.util.base_view import base_view
from sabron.util.sabronmodule import get_settings
from django.http import JsonResponse
from sabron.util.sabronmodule import get_settings, set_settings
@base_view
def get_scales_data(request):
control_conveyor_month = get_settings("conveyor_month")
fabric_goal = get_settings("fabric_goal")
control_conveyor_month = get_settings('conveyor_month')
fabric_goal = get_settings('fabric_goal')
service = RedisRepository(control_conveyor_month, fabric_goal)
positions = Position.objects.order_by("id")
monthly = service.get_scales_value(positions, "Month")
average = service.get_scales_value_by_shifts(positions, "Aver")
daily = service.get_scales_value_by_shifts(positions, "Smena")
positions = Position.objects.order_by('id')
monthly = service.get_scales_value(positions, 'Month')
average = service.get_scales_value_by_shifts(positions, 'Aver')
daily = service.get_scales_value_by_shifts(positions, 'Smena')
plan = service.get_scales_value_with_plan()
concentrate = service.get_concentrate_value()
return JsonResponse(
{"daily": daily, "average": average, "monthly": monthly, "plan": plan}
{
'daily': daily,
'average': average,
'monthly': monthly,
'plan': plan,
'concentrate_and_dropout': concentrate,
}
)
@base_view
def get_positions(request):
positions = Position.objects.values_list("title", flat=True).order_by("id")
positions = Position.objects.values_list('title', flat=True).order_by('id')
return JsonResponse(list(positions), safe=False)
@base_view
def set_kek_and_breed(request):
if request.method == 'POST':
control_conveyor_month = get_settings('conveyor_month')
fabric_goal = get_settings('fabric_goal')
data = json.loads(request.body)
if ('kek' in data and 'breed' in data) and (data['kek'] and data['breed']):
service = RedisRepository(control_conveyor_month, fabric_goal)
if service.set_kek_and_breed_values(data):
return JsonResponse(
{'success': True, 'message': 'Данные успешно переданы'}
)
return JsonResponse(
{'success': False, 'message': 'Возникла ошибка'}, status=418
)
return JsonResponse(
{
'success': False,
'message': 'Поля формы заполнены не корректно или не заполнены!',
},
status=418,
)
return JsonResponse({'success': False, 'message': 'only POST allowed'}, status=400)
@base_view
def get_kek_and_breed(request):
control_conveyor_month = get_settings('conveyor_month')
fabric_goal = get_settings('fabric_goal')
service = RedisRepository(control_conveyor_month, fabric_goal)
return JsonResponse(service.get_kek_and_breed_values())
@base_view
def fabric_goal(request):
if request.method == 'GET':
goal = get_settings('fabric_goal')
return JsonResponse({'goal': goal, 'success': True})
elif request.method == 'PUT':
value = json.loads(request.body)['goal']
set_settings('fabric_goal', value)
return JsonResponse({'success': True, 'message': 'Данные приняты'})
else:
return JsonResponse({'message': 'wrong method', 'success': False})

View File

@ -1,23 +1,38 @@
from django.urls import path
from apps.main.services.accident_stops.views import get_accident_stops
from apps.main.services.aspiration.views import get_aspiration_units_data
from apps.main.services.density_sensors.views import get_sensors_list
from apps.main.services.scales_control.views import get_scales_data, get_positions
from apps.main.services.scales_control.views import (
fabric_goal,
get_kek_and_breed,
get_positions,
get_scales_data,
set_kek_and_breed,
)
from apps.main.services.workstatus.views import get_current_status
from apps.main.services.worktime.views import (
create_worktime,
factory_work_time,
factory_work_time_durations,
)
from django.urls import path
urlpatterns = [
path("accident_stops/", get_accident_stops, name="accident_stops"),
path("worktime/", factory_work_time, name="factory_time"),
path('accident_stops/', get_accident_stops, name='accident_stops'),
path('worktime/', factory_work_time, name='factory_time'),
path(
"worktime/durations/",
'worktime/durations/',
factory_work_time_durations,
name="factory_time_durations",
name='factory_time_durations',
),
path("status/", get_current_status, name="current_status"),
path("positions/", get_positions, name="get_positions"),
path("density_sensors/", get_sensors_list, name="get_sensors_list"),
path("scales/", get_scales_data, name="scales"),
path('worktime/create/', create_worktime, name='create_worktime'),
path('status/', get_current_status, name='current_status'),
path('positions/', get_positions, name='get_positions'),
path('density_sensors/', get_sensors_list, name='get_sensors_list'),
path('scales/', get_scales_data, name='scales'),
path(
'scales/kek_and_breed/recieve/', set_kek_and_breed, name='receive_kek_and_breed'
),
path('scales/kek_and_breed/', get_kek_and_breed, name='get_kek_and_breed'),
path('scales/fabric_goal/', fabric_goal, name='fabric_goal'),
path('aspiration_units/', get_aspiration_units_data),
]

View File

@ -0,0 +1,7 @@
from apps.main.models.worktime import FabricWorkTime
class WorkStatusRepository:
@staticmethod
def get_latest_object() -> FabricWorkTime:
return FabricWorkTime.objects.latest('time')

View File

@ -1,33 +1,11 @@
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from apps.main.services.base_service import DashboardBaseService
from sabron.util import logging
from apps.main.services.workstatus.repository import WorkStatusRepository
class WorkStatusService(DashboardBaseService):
def get_current_status(self):
now_date = self.get_current_time()
start_month = now_date - relativedelta(hours=730)
status_list = list(self.get_qs_by_range(start_month, now_date))
if not status_list:
return {"last_status": "ND", "worktime": timedelta(0)}
last_status = status_list[-1]
if last_status["time"] < (self.get_current_time() - timedelta(minutes=5)):
return {
"last_status": "NW",
"worktime": self.get_current_time() - last_status["time"],
}
if len(status_list) < 2:
return {
"last_status": status_list[0]["status"],
"worktime": self.get_current_time() - status_list[0]["time"],
}
start_status = status_list[-2]
while start_status["status"] == last_status["status"] and len(status_list) >= 1:
start_status = status_list.pop()
now_date = self.get_current_time()
duration = now_date - last_status["time"]
status_worktime = last_status["time"] - start_status["time"] + duration
return {"last_status": last_status["status"], "worktime": status_worktime}
@classmethod
def get_current_status(cls):
now_date = cls.get_current_time()
last_status = WorkStatusRepository.get_latest_object()
duration = now_date - last_status.time
return {'last_status': last_status.status, 'worktime': duration}

View File

@ -1,12 +1,8 @@
from django.http import JsonResponse
from apps.main.models.worktime import FabricWorkTime
from apps.main.services.workstatus.service import WorkStatusService
from apps.util.base_view import base_view
from django.http import JsonResponse
@base_view
def get_current_status(request):
service = WorkStatusService(FabricWorkTime)
return JsonResponse(service.get_current_status())
return JsonResponse(WorkStatusService.get_current_status())

View File

@ -0,0 +1,47 @@
from datetime import timedelta
from apps.main.models.scales_control import ScalesControl
from apps.main.models.worktime import FabricWorkTime
from apps.main.services.base_service import DashboardBaseService
from django.db.models.functions import TruncMinute
from sabron.util.sabronmodule import get_settings
def create_worktime_data() -> bool:
"""
Description: Создает объекты времени работы фабрики, собирая данные с весов.
Returns: 1 | 0
"""
# получение входных данных
now_date = DashboardBaseService.get_current_time()
start_period = now_date - timedelta(hours=0)
control_conveyor = get_settings('control_conveyor')
# получение данных с весов поминутно
latest_records_scales = (
ScalesControl.objects.filter(name=control_conveyor, time__lte=start_period)
.annotate(time_minute=TruncMinute('time'))
.order_by('time_minute')
.distinct('time_minute')
)
# если нет записей с весов - выход из функции
if not latest_records_scales:
return 0
# получение указателя на первую запись в qs
current_record = latest_records_scales[0]
# создание первой записи
FabricWorkTime.objects.get_or_create(time=current_record.time, status='WO')
# цикл по qs с двумя указателями - на текущую и следующую запись
for record in latest_records_scales[1:]:
# вычисление разницы (в минутах) между временем текущей и следующей записи
delta = (record.time - current_record.time).total_seconds() / 60
# если разница больше 5 минут - фабрика не работает в промежутке между текущей и следующей записью
if delta > 5:
# текущая запись - начало остановки
FabricWorkTime.objects.get_or_create(status='NW', time=current_record.time)
# следующая запись - начало работы
FabricWorkTime.objects.get_or_create(status='WO', time=record.time)
current_record = record
return 1

View File

@ -1,6 +1,4 @@
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from datetime import datetime, timedelta
from apps.main.models.worktime import FabricWorkTime
from apps.main.services.base_service import DashboardBaseService
@ -10,16 +8,16 @@ class FabricWorkTimeService(DashboardBaseService):
@classmethod
def calculate_work_time(cls, qs: list, return_duration: bool = False) -> dict:
status_durations = {"WO": timedelta(0), "WA": timedelta(0), "NW": timedelta(0)}
status_durations = {'WO': timedelta(0), 'WA': timedelta(0), 'NW': timedelta(0)}
if not qs:
return
return status_durations
previous_time = qs[0]["time"]
previous_status = qs[0]["status"]
previous_time = qs[0]['time']
previous_status = qs[0]['status']
for work in qs[1:]:
current_time = work["time"]
current_status = work["status"]
current_time = work['time']
current_status = work['status']
duration = current_time - previous_time
status_durations[previous_status] += duration
@ -29,10 +27,7 @@ class FabricWorkTimeService(DashboardBaseService):
now_date = cls.get_current_time()
duration = now_date - previous_time
if duration.seconds // 60 > 5:
status_durations["NW"] += duration
else:
status_durations[previous_status] += duration
status_durations[previous_status] += duration
if return_duration:
return status_durations
status_durations_hours = {
@ -41,62 +36,58 @@ class FabricWorkTimeService(DashboardBaseService):
return status_durations_hours
@classmethod
def calculate_by_last_value(cls, last_value: FabricWorkTime, start, end) -> dict:
# TODO доделать
delta = end - last_value.time
res = start - delta
pass
def add_time_from_last_value(
self, worktime_values: dict, start_period: datetime, diff: timedelta
) -> dict:
try:
last_value = FabricWorkTime.objects.filter(time__lte=start_period).latest(
'time'
)
if last_value is None:
return worktime_values
worktime_values[last_value.status] += diff
except FabricWorkTime.DoesNotExist:
pass
return worktime_values
def return_worktime(self, return_durations: bool = False):
# TODO обработки на то, что qs пуст; на то, что последний статус был давно
now_date = self.get_current_time()
start_month = now_date - relativedelta(hours=730)
start_week = now_date - relativedelta(hours=168)
start_month = now_date.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
start_week = (now_date - timedelta(days=now_date.weekday())).replace(
hour=0, minute=0, second=0, microsecond=0
)
start_shift = self.get_shift_start(now_date)
monthly_qs = self.get_qs_by_range(start_month, now_date)
if not monthly_qs:
monthly = (
{"WO": 0, "WA": 0, "NW": 0}
if not return_durations
else {
"WO": "P0DT00H00M00S",
"WA": "P0DT00H00M00S",
"NW": now_date - start_month,
}
)
else:
monthly = self.calculate_work_time(list(monthly_qs), return_durations)
monthly = self.calculate_work_time(list(monthly_qs), return_durations)
diff_monthly = self.check_worktime_validity(monthly, start_month, now_date)
monthly = self.add_time_from_last_value(monthly, start_month, diff_monthly)
weekly_qs = self.get_qs_by_range(start_week, now_date)
if not weekly_qs:
weekly = (
{"WO": 0, "WA": 0, "NW": 0}
if not return_durations
else {
"WO": "P0DT00H00M00S",
"WA": "P0DT00H00M00S",
"NW": now_date - start_week,
}
)
else:
weekly = self.calculate_work_time(list(monthly_qs), return_durations)
weekly = self.calculate_work_time(list(weekly_qs), return_durations)
diff_weekly = self.check_worktime_validity(weekly, start_week, now_date)
weekly = self.add_time_from_last_value(weekly, start_week, diff_weekly)
shift_qs = self.get_qs_by_range(start_shift, now_date)
if not shift_qs:
daily = (
{"WO": 0, "WA": 0, "NW": 0}
if not return_durations
else {
"WO": "P0DT00H00M00S",
"WA": "P0DT00H00M00S",
"NW": now_date - self.get_shift_start(now_date),
}
)
else:
daily = self.calculate_work_time(list(shift_qs), return_durations)
daily = self.calculate_work_time(list(shift_qs), return_durations)
diff_daily = self.check_worktime_validity(daily, start_shift, now_date)
daily = self.add_time_from_last_value(daily, start_shift, diff_daily)
return {
"monthly": monthly,
"weekly": weekly,
"daily": daily,
'monthly': monthly,
'weekly': weekly,
'daily': daily,
}
@classmethod
def check_worktime_validity(
cls, worktime: dict, start_period: datetime, now_date: datetime
) -> timedelta:
mas_worktime = [i for i in worktime.values()]
total_time = timedelta(hours=0)
for i in mas_worktime:
total_time += i
actual_worktime_duration = now_date - start_period
diff = actual_worktime_duration - total_time
return diff

View File

@ -1,10 +1,9 @@
from django.http import JsonResponse
from apps.main.models.worktime import FabricWorkTime
from apps.main.services.worktime.create_worktime_data import create_worktime_data
from apps.main.services.worktime.service import FabricWorkTimeService
from apps.main.tasks import create_worktime_data
from apps.util.base_view import base_view
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
@base_view
@ -17,3 +16,11 @@ def factory_work_time(request):
def factory_work_time_durations(request):
service = FabricWorkTimeService(FabricWorkTime)
return JsonResponse(service.return_worktime(return_durations=True))
@base_view
def create_worktime(request):
if request.user.is_superuser:
create_worktime_data()
return redirect('administration')
return HttpResponse(status=403)

View File

@ -1,290 +1,244 @@
import decimal
import os
import traceback
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from datetime import datetime
import psycopg2
from celery import shared_task
from django.db.models.functions import TruncMinute
from django.utils import timezone
from psycopg2 import OperationalError
from apps.main.models.scales_control import ScalesControl, Position
import requests
from apps.main.models.worktime import FabricWorkTime
from apps.main.services.base_service import DashboardBaseService
from apps.util.redis_api import RedisService
from repcofkk.production_settings import REDIS_HOST, REDIS_PORT
from apps.util.redis_cache import RedisCache
from celery import shared_task
from django.conf import settings
from psycopg2 import OperationalError
from sabron.util import logging
from sabron.util.sabronmodule import get_settings
@shared_task
def create_worktime_data_redis():
control_conveyor = get_settings("control_conveyor")
now_date = DashboardBaseService.get_current_time()
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service:
value = redis_service.hget_value(control_conveyor, "Value")
date = redis_service.hget_value(control_conveyor, "Date")
obj_from_redis = {"value": value, "date": date}
try:
delta = (now_date - obj_from_redis["time"]).seconds / 60
if delta > 5:
FabricWorkTime.objects.create(status="NW", time=now_date)
# else:
# if
except FabricWorkTime.DoesNotExist:
return FabricWorkTime.objects.create(status="WO", time=date)
REDIS_HOST = settings.REDIS_HOST
REDIS_PORT = settings.REDIS_PORT
@shared_task
def create_worktime_data() -> int:
"""
Создает объекты FabricWorkTime для анализа времени работы фабрики.
Если с весов нет ответа - фабрика не работает - конвейер стоит (5 минут без ответа)
Если с весов с Поз.4 меньше 20 - фабрика работает без нагрузки
"""
# TODO переписать под ситуации, создать модуль настроек для упр. конвейера
# TODO переписать по аналогу SQL скрипта с весами
try:
control_conveyor = get_settings("control_conveyor")
now_date = DashboardBaseService.get_current_time()
start_day = now_date - relativedelta(hours=24)
latest_records = (
ScalesControl.objects.filter(name=control_conveyor, time__gte=start_day)
.annotate(time_minute=TruncMinute("time"))
.order_by("time_minute")
.distinct("time_minute")
)
if not latest_records:
return f"No scales records. {now_date}"
current_record = latest_records[0]
for record in latest_records[1:]:
delta = (record.time - current_record.time).seconds / 60
rec = FabricWorkTime.objects.filter(
time=current_record.time.replace(second=0, microsecond=0)
)
if delta > 5:
status = "NW"
if rec:
last_rec = rec.last()
last_rec.status = status
last_rec.save()
if not rec:
status = "WO" if record.value > decimal.Decimal(20.0) else "WA"
FabricWorkTime.objects.create(
time=current_record.time.replace(second=0, microsecond=0),
status=status,
class RedisScales:
def get_scales_data_from_redis(tag: str = get_settings('control_conveyor')):
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service:
# Получение объекта из Redis с последней актуальной записью по управляющему конвейеру
value = redis_service.hget_value(tag, 'Value')
date_str = redis_service.hget_value(tag, 'Date')
try: # В случае если нет миллисекунд
date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
date = date.replace(tzinfo=settings.TIME_ZONE_OBJECT)
return {'value': value, 'date': date}
class PostgresScales:
@staticmethod
def fetch_scales_data_by_range(start: datetime, end: datetime) -> list:
control_conveyor = get_settings('control_conveyor')
with psycopg2.connect(
dbname=get_settings('scales_db'),
user=get_settings('scales_db_user'),
password=get_settings('scales_db_password'),
host=get_settings('scales_db_host'),
port=get_settings('scales_db_port'),
) as conn_postgres:
with conn_postgres.cursor() as cursor:
cursor.execute(
"""
SELECT DISTINCT ON (date_trunc('minute', "Date"))
"Name",
"Values",
"Date",
"Check"
FROM public.vesi
WHERE
"Name" = %s AND
"Date" BETWEEN %s AND %s
LIMIT 10000;
""",
(control_conveyor, start, end),
)
current_record = record
return "Success"
except Exception as e:
logging.error(traceback.format_exc())
return f"Exception: {e}"
return cursor.fetchall()
@staticmethod
def get_scales_data(limit: int = 20000) -> list:
try:
with psycopg2.connect(
dbname=get_settings('scales_db'),
user=get_settings('scales_db_user'),
password=get_settings('scales_db_password'),
host=get_settings('scales_db_host'),
port=get_settings('scales_db_port'),
) as conn_postgres:
with conn_postgres.cursor() as cursor:
cursor.execute(
"""
SELECT "Name", "Values", "Date", "Check"
FROM public.vesi
ORDER BY id DESC
LIMIT %s;
""",
(limit,),
)
data = cursor.fetchall()
return data[::-1]
except OperationalError:
logging.error(traceback.format_exc())
return None
@staticmethod
def write_scales_data(data: list):
if not data:
return 'No scales data'
try:
with psycopg2.connect(
dbname=os.environ.get('POSTGRES_DB', 'repcofkk_db'),
user=os.environ.get('POSTGRES_USER', 'repcofkk_user'),
password=os.environ.get('POSTGRES_PASSWORD', 'Angstrem*45'),
host=os.environ.get('POSTGRES_HOST', '127.0.0.1'),
port='5432',
) as postgres_conn:
with postgres_conn.cursor() as cursor:
for row in data:
name, value, date, check = row
cursor.execute(
"""
DO $$
DECLARE
value_exists BOOLEAN;
BEGIN
IF %s LIKE '%%Smena' OR %s LIKE '%%Month' THEN
SELECT EXISTS (
SELECT 1
FROM public.main_scalescontrol
WHERE "Name" = %s AND "Values" = %s
) INTO value_exists;
IF value_exists THEN
UPDATE public.main_scalescontrol
SET "Date" = %s
WHERE "Name" = %s AND "Values" = %s;
ELSE
INSERT INTO public.main_scalescontrol ("Name", "Values", "Date", "Check")
VALUES (%s, %s, %s, %s);
END IF;
END IF;
END $$;
""",
(
name,
name,
name,
value,
date,
name,
value,
name,
value,
date,
check,
),
)
postgres_conn.commit()
return 'Success'
except Exception:
logging.error('CELERY: ' + traceback.format_exc())
return traceback.format_exc()
finally:
postgres_conn.close()
def set_cache_value(key: str, value: str) -> str:
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=2) as redis_service:
value = redis_service.set_value("cache_tasks/" + key, value)
return value
@shared_task
def create_worktime_data_from_scales_db(start, stop):
pass
def get_cache_value(key: str) -> bool:
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=2) as redis_service:
value = redis_service.get_value("cache_tasks/" + key)
return bool(int(value))
def is_conveyor_working() -> bool | int:
api_host = get_settings('api_host')
conveyor_bool = get_settings('conveyor_bool')
if not conveyor_bool:
return -1
response = requests.get(
f'{api_host}/api/v2/scada/sensor/tag/{conveyor_bool}', timeout=3
)
return bool(response.json()['responce']['value'])
def delete_cache_value(key: str) -> str:
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=2) as redis_service:
value = redis_service.delete_value("cache_tasks/" + key)
return value
@shared_task
def create_worktime_data():
"""
Description:
Создает объекты времени работы фабрики
Returns: строку со статусом задачи
"""
fabric_unloaded_val = int(get_settings('fabric_unloaded_val', '5'))
obj_from_redis = RedisScales.get_scales_data_from_redis(
get_settings('control_conveyor')
)
conveyor_state = is_conveyor_working()
if conveyor_state == -1:
return 'conveyor_bool is not set'
try:
latest_worktime_obj = FabricWorkTime.objects.latest('time')
except FabricWorkTime.DoesNotExist:
status = (
'NW'
if conveyor_state is False
else ('WO' if obj_from_redis['value'] > fabric_unloaded_val else 'WA')
)
obj = FabricWorkTime.objects.create(status=status, time=obj_from_redis['date'])
return 'Success. Created first obj: ' + str(obj)
status = None
if conveyor_state:
if float(obj_from_redis['value']) > fabric_unloaded_val:
if latest_worktime_obj.status != 'WO':
status = 'WO'
else:
if latest_worktime_obj.status != 'WA':
status = 'WA'
else:
if latest_worktime_obj.status != 'NW':
status = 'NW'
if status:
obj = FabricWorkTime.objects.create(status=status, time=obj_from_redis['date'])
return f'Success. Created obj: {str(obj)} (latest {str(latest_worktime_obj)})'
return 'Success. ' + str(latest_worktime_obj)
@shared_task
def create_scales_control_data():
cache = get_cache_value("create_scales_control_data")
if not cache:
set_cache_value("create_scales_control_data", "1")
scales_data = get_scales_data(300)
res = write_scales_data(scales_data)
delete_cache_value("create_scales_control_data")
return res
return "Skip"
cache = RedisCache(redis_host=REDIS_HOST, redis_port=REDIS_PORT)
cache_value = cache.get_cache_value('create_scales_control_data')
try:
if not cache_value:
cache.set_cache_value('create_scales_control_data', '1')
scales_data = PostgresScales.get_scales_data(300)
res = PostgresScales.write_scales_data(scales_data)
cache.delete_cache_value('create_scales_control_data')
return res
return 'Skip'
except Exception:
logging.error('CELERY' + traceback.format_exc())
cache.delete_cache_value('create_scales_control_data')
@shared_task
def write_scale_control_data_to_redis():
try:
data = get_scales_data(300)
data = PostgresScales.get_scales_data(300)
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service:
for row in data:
redis_service.hset_value(row[0], key="Value", value=str(row[1]))
redis_service.hset_value(row[0], key="Date", value=str(row[2]))
return "Success"
redis_service.hset_value(row[0], key='Value', value=str(row[1]))
redis_service.hset_value(row[0], key='Date', value=str(row[2]))
return 'Success'
except Exception as e:
logging.error("CELERY" + traceback.format_exc())
logging.error('CELERY' + traceback.format_exc())
return str(e)
@shared_task
def thin_out_scales():
positions = Position.objects.all()
for position in positions:
pos_tags = [
position.aver_smena_tag,
position.aver_pred_smena_tag,
position.smena_tag,
position.pred_smena_tag,
position.month_tag,
position.sutki_tag,
]
results = []
for tag in pos_tags:
try:
res = thin_out_scale(tag)
if not res:
results.append({tag: "No scales Data"})
results.append({tag: res})
except Exception:
logging.error(f"Celery: {traceback.format_exc()} \n on tag {tag}")
results.append({tag: {traceback.format_exc()}})
return results
@shared_task
def thin_out_worktime():
worktime_qs = FabricWorkTime.objects.filter(
time__lt=timezone.now() - timedelta(hours=12)
).order_by("time")
if not worktime_qs:
return "No worktime"
prev = worktime_qs[0]
for cur_obj in worktime_qs[1:]:
if cur_obj.status == prev.status:
cur_obj.delete()
prev = cur_obj
return f"Success. Deleted: {len(worktime_qs)} rows"
def thin_out_scale(tag) -> bool | int:
qs = list(
ScalesControl.objects.filter(
name=tag,
time__lte=DashboardBaseService.get_current_time() - timedelta(hours=12),
).order_by("time")
)
if len(qs) <= 2:
return False
i = 0
current_obj = qs[i]
latest_obj = qs[-1]
while current_obj != latest_obj:
end_range_date = current_obj.time + timedelta(hours=1)
rang = ScalesControl.objects.filter(
name=tag, time__range=(current_obj.time, end_range_date)
).order_by("time")
if len(rang) <= 2:
i += 1
current_obj = qs[i + 1]
continue
first_in_range = rang.first()
last_in_range = rang.last()
to_delete = rang.exclude(time=first_in_range.time).exclude(
time=last_in_range.time
)
to_delete.delete()
current_obj = last_in_range
i += 1
return len(to_delete)
def get_scales_data(limit: int = 20000) -> list:
try:
with psycopg2.connect(
dbname="vesi_db",
user="ktp_user",
password="rb,thrjl",
host="192.168.10.2",
port="5432",
) as conn_postgres:
with conn_postgres.cursor() as cursor:
cursor.execute(
"""
SELECT "Name", "Values", "Date", "Check"
FROM public.vesi
ORDER BY id DESC
LIMIT %s;
""",
(limit,),
)
data = cursor.fetchall()
return data[::-1]
except OperationalError:
return None
def write_scales_data(data: list):
if not data:
return "No scales data"
try:
with psycopg2.connect(
dbname=os.environ.get("POSTGRES_DB", "repcofkk_db"),
user=os.environ.get("POSTGRES_USER", "repcofkk_user"),
password=os.environ.get("POSTGRES_PASSWORD", "Angstrem*45"),
host=os.environ.get("POSTGRES_HOST", "127.0.0.1"),
port="5432",
) as postgres_conn:
with postgres_conn.cursor() as cursor: # TODO при настройке ОПС на запись в БД - убрать первое условие
for row in data:
name, value, date, check = row
cursor.execute(
"""
DO $$
DECLARE
value_exists BOOLEAN;
BEGIN
IF %s LIKE '%%Smena' OR %s LIKE '%%Month' THEN
SELECT EXISTS (
SELECT 1
FROM public.main_scalescontrol
WHERE "Name" = %s AND "Values" = %s
) INTO value_exists;
IF value_exists THEN
UPDATE public.main_scalescontrol
SET "Date" = %s
WHERE "Name" = %s AND "Values" = %s;
ELSE
INSERT INTO public.main_scalescontrol ("Name", "Values", "Date", "Check")
VALUES (%s, %s, %s, %s);
END IF;
END IF;
END $$;
""",
(
name,
name,
name,
value,
date,
name,
value,
name,
value,
date,
check,
),
)
postgres_conn.commit()
return "Success"
except Exception:
logging.error("CELERY: " + traceback.format_exc())
return traceback.format_exc()
finally:
postgres_conn.close()

View File

@ -0,0 +1,13 @@
{% extends 'default.html' %}
{% load static %}
{% block content %}
<div class="row m-2 justify-content-center" id="aspirationUnits">
</div>
{% endblock %}
{% block script_footer %}
<script src="{% static 'js/charts/aspirationUnits.js' %}"></script>
{% endblock %}

View File

@ -0,0 +1,91 @@
{% extends 'default.html' %}
{% load static %}
{% block content %}
<div class="row m-1">
<div class="col-xl-4">
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
Выпуск кек и породы (нат. вес)
</h3>
</div>
</div>
</div>
<div class="m-portlet__body">
<div id="kekAndBreedModalAlerts"></div>
<div class="form-group m-form__group">
<label for="kekInput">Выпуск кека (нат.вес):</label>
<input type="number" class="form-control m-input m-input--square" id="kekInput"
placeholder="Введите значение кека">
</div>
<div class="form-group m-form__group">
<label for="breedInput">Выпуск породы (нат.вес):</label>
<input type="number" class="form-control m-input m-input--square" id="breedInput"
placeholder="Введите значение породы">
</div>
</div>
<div class="m-portlet__foot">
<div class="row align-items-center">
<div class="col-lg-6 m--valign-middle"></div>
<div class="col-lg-6 m--align-right">
<button type="button" id="formSubmitBtn" class="btn btn-brand roboto">Сохранить</button>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block script_footer %}
<script>
const kekInput = document.querySelector('#kekInput')
const breedInput = document.querySelector('#breedInput')
const formSubmitBtn = document.querySelector('#formSubmitBtn')
document.addEventListener('DOMContentLoaded', async () => {
const response = await fetch('/main/scales/kek_and_breed')
const json = await response.json()
kekInput.value = json['kek']
breedInput.value = json['breed']
})
formSubmitBtn.addEventListener('click', async () => {
const data = {
kek: kekInput.value,
breed: breedInput.value
}
const response = await fetch('/main/scales/kek_and_breed/recieve/', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
"X-CSRFToken": getCookie("csrftoken")
},
body: JSON.stringify(data)
})
const response_json = await response.json();
const kekAndBreedModalAlerts = document.querySelector('#kekAndBreedModalAlerts')
kekAndBreedModalAlerts.innerHTML = ''
const alert = document.createElement('div')
alert.classList.add('alert', 'roboto', 'bold')
alert.setAttribute('role', 'alert')
alert.textContent = `${response_json.message}`
kekAndBreedModalAlerts.appendChild(alert)
if (response_json.success) {
alert.classList.add('alert-success')
// Спрятать модальное окно
document.getElementById('m_modal_3').classList.remove('show');
document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
} else {
// Отобразить ошибку
alert.classList.add('alert-danger')
}
})
</script>
{% endblock %}

View File

@ -1,172 +0,0 @@
<div class="col-xl-4">
<div class="m-portlet m-portlet--full-height">
<div class="m-portlet__head justify-content-center">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<button type="button"
class="btn m-btn--pill btn-secondary m-btn m-btn--custom m-btn--bolder border-0"
id="fabricCurrentStatusWrapper">
<span class="roboto font-weight-bold text-white" id="fabricCurrentStatus"></span>
</button>
</h3>
</div>
</div>
</div>
<div class="m-portlet__body pt-1">
<div class="m-widget16 h-100 grid-gar-1fr divider-horizontal">
<div class="row align-items-center">
<div class="col-md-6">
<h5 class="roboto text-center">За смену</h5>
<div class="m-widget16__body">
<div class="worktime-between">
<span class=" roboto dark">
Под нагрузкой
</span>
<span class="m-widget16__price m--align-right m--font-success roboto font-weight-bold"
id="dailyWO">0 ч.</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Без нагрузки
</span>
<span class="m-widget16__price m--align-right m--font-primary roboto font-weight-bold"
id="dailyWA">
0 ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Не работала
</span>
<span class="m-widget16__price m--align-right m--font-danger roboto font-weight-bold"
id="dailyNW">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Общее время работы
</span>
<span class="m-widget16__price m--align-right m--font-accent roboto font-weight-bold"
id="dailySUM">
0ч.
</span>
</div>
</div>
</div>
<div class="col-md-6">
<div class="m-widget16__stats">
<div class="m-widget16__visual">
<div id="dailyWorkTimeChart" style="height: 180px">
</div>
</div>
</div>
</div>
</div>
<div class="row align-items-center">
<div class="col-md-6">
<h5 class="roboto text-center">За неделю</h5>
<div class="m-widget16__body">
<div class="worktime-between">
<span class=" roboto">
Под нагрузкой
</span>
<span class="m-widget16__price m--align-right m--font-success roboto font-weight-bold"
id="weeklyWO">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Без нагрузки
</span>
<span class="m-widget16__price m--align-right m--font-primary roboto font-weight-bold"
id="weeklyWA">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Не работала
</span>
<span class="m-widget16__price m--align-right m--font-danger roboto font-weight-bold"
id="weeklyNW">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Общее время работы
</span>
<span class="m-widget16__price m--align-right m--font-accent roboto font-weight-bold"
id="weeklySUM">
0ч.
</span>
</div>
</div>
</div>
<div class="col-md-6">
<div class="m-widget16__stats">
<div class="m-widget16__visual">
<div id="weeklyWorkTimeChart" style="height: 180px">
</div>
</div>
</div>
</div>
</div>
<div class="row align-items-center">
<div class="col-md-6">
<h5 class="roboto text-center">За месяц</h5>
<div class="m-widget16__body">
<div class="worktime-between">
<span class=" roboto">
Под нагрузкой
</span>
<span class="m-widget16__price m--align-right m--font-success roboto font-weight-bold"
id="monthlyWO">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Без нагрузки
</span>
<span class="m-widget16__price m--align-right m--font-primary roboto font-weight-bold"
id="monthlyWA">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Не работала
</span>
<span class="m-widget16__price m--align-right m--font-danger roboto font-weight-bold"
id="monthlyNW">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Общее время работы
</span>
<span class="m-widget16__price m--align-right m--font-accent roboto font-weight-bold"
id="monthlySUM">
0ч.
</span>
</div>
</div>
</div>
<div class="col-md-6">
<div class="m-widget16__stats">
<div class="m-widget16__visual">
<div id="monthlyWorkTimeChart" style="height: 180px">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@ -13,6 +13,9 @@
<div class="">
<a href="/main/scada/" target="_blank" class="btn btn-primary btn-lg">SCADA</a>
</div>
<div>
<a href="/main/scada/flotation/" target="_blank" class="btn btn-primary btn-lg">Флотация</a>
</div>
<div>
<a href="/montorem/" target="_blank" class="btn btn-primary btn-lg">Montorem</a>
</div>
@ -23,15 +26,17 @@
<div class="row">
<!--Виджет времени работы фабрики и ее статуса-->
{% include 'fabric_worktime_widget.html' %}
{% include 'widgets/worktime/widget.html' %}
<div class="col-xl-8">
<div class="row">
<!--Виджет показаний весов -->
{% include 'fabric_scales_control_widget.html' %}
{% include 'widgets/scales/widget.html' %}
<!--Количество аварийных остановок -->
{# {% include 'emergency_stops_widget.html' %}#}
<!--Виджет плотность в тяжелой среде -->
{% include 'density_in_heavy.html' %}
{% include 'widgets/density/widget.html' %}
{% include 'widgets/meteo/widget.html' %}
</div>
<!--end:: Widgets/Support Stats-->
@ -47,5 +52,6 @@
<script src="{% static 'js/charts/workStatus.js' %}?ver={% settings_value 'APP_VERSION' %}"></script>
<script src="{% static 'js/charts/scaleControl.js' %}?ver={% settings_value 'APP_VERSION' %}"></script>
<script src="{% static 'js/charts/densityInHeavy.js' %}?ver={% settings_value 'APP_VERSION' %}"></script>
<script></script>
<script src="{% static 'js/charts/meteo.js' %}?ver={% settings_value 'APP_VERSION' %}"></script>
{% endblock script_footer %}

View File

@ -0,0 +1,63 @@
<html>
{% load static %}
{% load mysettings %}
<head>
<meta charset="utf-8">
</head>
<body style="margin:0;">
<!--<img src="http://192.168.10.251:8000/screen?rand=0.5233895099246539" alt="" id="image" width="100%" height="95%">-->
<img id="skadaimg" alt="" id="image" width="100%" >
<div at-magnifier-wrapper="">
<div class="at-theme-light">
<div class="at-base notranslate" translate="no">
<div class="EuwGd" style="top: 0px; left: 0px;"></div>
</div>
</div>
</div>
<!-- ./wrapper -->
<!-- REQUIRED SCRIPTS -->
<!-- jQuery -->
<script src="{% static 'lte/plugins/jquery/jquery.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<!-- Bootstrap 4 -->
<script src="{% static 'lte/plugins/bootstrap/js/bootstrap.bundle.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<!-- SweetAlert2 -->
<script src="{% static 'lte/plugins/sweetalert2/sweetalert2.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<!-- Toastr -->
<script src="{% static 'lte/plugins/toastr/toastr.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<!-- AdminLTE App -->
<script src="{% static 'lte/dist/js/adminlte.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script src="{% static 'js/main.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script>
function show()
{
cmd = 'refresh';
$.ajax({
type: 'POST', // метод отправки
async:true,
url: window.location.pathname+'ajax/', // путь к обработчику
data: {
"cmd": cmd,
},
success: function (data) {
$('#skadaimg').attr('src',data.img)
},
error: function (dataerr) {
console.log('Ошибка выполнение команды :'+dataerr)
}
});
}
show()
setInterval('show()', 1000);
setInterval(function () {
var image = document.getElementById('image');
image.src = 'http://192.168.10.247:8000/?rand=' + Math.random();
}, 10000);
</script>
</body>
</html>

View File

@ -1,4 +1,4 @@
<div class="col-md-8 col-sm-12">
<div class="col-md-12 col-lg-6">
<div class="m-portlet m-portlet--full-height">
<div class="m-portlet__head justify-content-center">
<div class="m-portlet__head-caption">
@ -10,7 +10,7 @@
</div>
</div>
<div class="m-portlet__body p-1">
<div class="row sparkboxes mt-2 mb-2 divider-vertical">
<div class="row sparkboxes mt-2 mb-2 divider-vertical" id="densityContainer">
<div class="col-md-6">
<div class="box box1">
<div id="density_sensor_100"></div>
@ -24,4 +24,4 @@
</div>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,99 @@
<div class="col-md-12 col-lg-6">
<div class="m-portlet m-portlet--tabs m-portlet--full-height">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<a href="https://mycityair.ru/networks/posts" target="_blank">Данные с метеостанции</a>
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="nav nav-tabs m-tabs m-tabs-line m-tabs-line--right m-tabs-line-danger" role="tablist">
<li class="nav-item m-tabs__item">
<a class="nav-link m-tabs__link active show" data-toggle="tab" href="#m_portlet_tab_1_1"
role="tab" aria-selected="true">
Качество воздуха
</a>
</li>
<li class="nav-item m-tabs__item">
<a class="nav-link m-tabs__link" data-toggle="tab" href="#m_portlet_tab_1_2" role="tab"
aria-selected="false">
Погодные условия
</a>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body p-3" style="min-height: 115px;">
<div class="tab-content">
<div class="tab-pane active show" id="m_portlet_tab_1_1">
<div class="row">
<div class="col-md-6 col-sm-12">
<div style="display: grid; grid-template-columns: 1fr 1fr">
<div>PM2.5</div>
<div><b><span class="meteo_pm2"></span> мгк/м<sup>3</sup></b></div>
<div>PM10</div>
<div><b><span class="meteo_pm10"></span> мгк/м<sup>3</sup></b></div>
<div>CO</div>
<div><b><span class="meteo_co"></span> мгк/м<sup>3</sup></b></div>
</div>
</div>
<div class="col-md-6">
<div style="display: grid; grid-template-columns: 1fr 1fr">
<div>NO<sub>2</sub></div>
<div><b><span class="meteo_no2"></span> мгк/м<sup>3</sup></b></div>
<div>SO<sub>2</sub></div>
<div><b><span class="meteo_so2"></span> мгк/м<sup>3</sup></b></div>
<div>O<sub>3</sub></div>
<div><b><span class="meteo_o3"></span> мгк/м<sup>3</sup></b></div>
<div>H<sub>2</sub>S</div>
<div><b><span class="meteo_h2s"></span> мгк/м<sup>3</sup></b></div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="m_portlet_tab_1_2">
<div class="row">
<div class="col-md-6">
<div style="display: grid; grid-template-columns: 1fr 1fr">
<div>Температура</div>
<div><b><span class="meteo_temperature"></span>&#176C</b></div>
<div>Давление</div>
<div><b><span class="meteo_pressure"></span> мм.рт.ст.</b></div>
<div>Влажность</div>
<div><b><span class="meteo_humidity"></span>%</b></div>
</div>
</div>
<div class="col-md-6">
<div style="display: grid; grid-template-columns: 1fr 1fr">
<div>Направление ветра</div>
<div><b><span class="meteo_wda"></span></b>
<i class="fa fa-arrow-up wda-dir" style="color: var(--primary);"></i>
</div>
<div>Скорость ветра</div>
<div><b><span class="meteo_wva"></span> м/c</b></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,3 @@
<div class="col-sm-12 col-md-6 col-lg-4">
<div id="DropoutAndConcentrate"></div>
</div>

View File

@ -0,0 +1,3 @@
<div class="col-sm-12 col-md-6 col-lg-4">
<div id="GoalProgress"></div>
</div>

View File

@ -1,9 +1,8 @@
<div class="col-12">
<div class="m-portlet m-portlet--full-height w-100 mb-1_4">
<div class="m-portlet__head row">
<div class="col-sm-12 col-md-4">
<div id="chartProgress"></div>
</div>
<div class="m-portlet__head row" style="height: auto;">
{% include 'widgets/scales/goal_progress.html' %}
{% include 'widgets/scales/dropout_and_concentrate.html' %}
</div>
<div class="m-portlet__body p-2">
<div class="m-widget1__item row divider-vertical">
@ -58,4 +57,43 @@
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="m_modal_3" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
aria-hidden="true" style="display: none;">
<div class="modal-dialog" role="document">
<form class="modal-content" id="dropoutAndConcentrateForm">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" id="ModalLabel">Ввод данных</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="kekAndBreedModalAlerts"></div>
<div class="m-portlet__body">
<div class="form-group m-form__group">
<label for="kekInput">Выпуск кека (нат.вес):</label>
<input type="number" class="form-control m-input m-input--square" id="kekInput"
placeholder="Введите значение кека">
</div>
<div class="form-group m-form__group">
<label for="breedInput">Выпуск породы (нат.вес):</label>
<input type="number" class="form-control m-input m-input--square" id="breedInput"
placeholder="Введите значение породы">
<hr>
<span class="m-form__help">
Данные значения можно будет изменить до конца текущей смены (Отчеты <i
class="fa fa-arrow-right"></i> Весы <i class="fa fa-arrow-right"></i> Выход концентрата)
</span>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary roboto" data-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary roboto" id="submitBtn">Отправить</button>
</div>
</form>
</div>
</div>

View File

@ -0,0 +1,174 @@
<div class="col-xl-4">
<div class="m-portlet m-portlet--full-height">
<div class="m-portlet__head justify-content-center">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
{% include 'widgets/worktime/workstatus.html' %}
</h3>
</div>
</div>
</div>
<div class="m-portlet__body pt-1">
<div class="m-widget16 h-100 grid-gar-1fr divider-horizontal">
<div class="row align-items-center">
<div class="col-md-6">
<h5 class="roboto text-center">За смену
<sup><a href="{% url 'worktime_history' %}?scale=shift"><i class="fa fa-info-circle" style="color: var(--primary); cursor: pointer"></i></a></sup>
</h5>
<div class="m-widget16__body">
<div class="worktime-between">
<span class=" roboto dark">
Под нагрузкой
</span>
<span class="m-widget16__price m--align-right m--font-success roboto font-weight-bold"
id="dailyWO">0 ч.</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Без нагрузки
</span>
<span class="m-widget16__price m--align-right m--font-primary roboto font-weight-bold"
id="dailyWA">
0 ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Не работала
</span>
<span class="m-widget16__price m--align-right m--font-danger roboto font-weight-bold"
id="dailyNW">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Общее время работы
</span>
<span class="m-widget16__price m--align-right m--font-accent roboto font-weight-bold"
id="dailySUM">
0ч.
</span>
</div>
</div>
</div>
<div class="col-md-6">
<div class="m-widget16__stats">
<div class="m-widget16__visual">
<div id="dailyWorkTimeChart" style="height: 180px">
</div>
</div>
</div>
</div>
</div>
<div class="row align-items-center">
<div class="col-md-6">
<h5 class="roboto text-center">За неделю
<sup><a href="{% url 'worktime_history' %}?scale=week"><i class="fa fa-info-circle" style="color: var(--primary); cursor: pointer"></i></a></sup>
</h5>
<div class="m-widget16__body">
<div class="worktime-between">
<span class=" roboto">
Под нагрузкой
</span>
<span class="m-widget16__price m--align-right m--font-success roboto font-weight-bold"
id="weeklyWO">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Без нагрузки
</span>
<span class="m-widget16__price m--align-right m--font-primary roboto font-weight-bold"
id="weeklyWA">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Не работала
</span>
<span class="m-widget16__price m--align-right m--font-danger roboto font-weight-bold"
id="weeklyNW">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Общее время работы
</span>
<span class="m-widget16__price m--align-right m--font-accent roboto font-weight-bold"
id="weeklySUM">
0ч.
</span>
</div>
</div>
</div>
<div class="col-md-6">
<div class="m-widget16__stats">
<div class="m-widget16__visual">
<div id="weeklyWorkTimeChart" style="height: 180px">
</div>
</div>
</div>
</div>
</div>
<div class="row align-items-center">
<div class="col-md-6">
<h5 class="roboto text-center">За месяц
<sup><a href="{% url 'worktime_history' %}?scale=month"><i class="fa fa-info-circle" style="color: var(--primary); cursor: pointer"></i></a></sup>
</h5>
<div class="m-widget16__body">
<div class="worktime-between">
<span class=" roboto">
Под нагрузкой
</span>
<span class="m-widget16__price m--align-right m--font-success roboto font-weight-bold"
id="monthlyWO">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Без нагрузки
</span>
<span class="m-widget16__price m--align-right m--font-primary roboto font-weight-bold"
id="monthlyWA">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Не работала
</span>
<span class="m-widget16__price m--align-right m--font-danger roboto font-weight-bold"
id="monthlyNW">
0ч.
</span>
</div>
<div class="worktime-between">
<span class=" roboto">
Общее время работы
</span>
<span class="m-widget16__price m--align-right m--font-accent roboto font-weight-bold"
id="monthlySUM">
0ч.
</span>
</div>
</div>
</div>
<div class="col-md-6">
<div class="m-widget16__stats">
<div class="m-widget16__visual">
<div id="monthlyWorkTimeChart" style="height: 180px">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,5 @@
<button type="button"
class="btn m-btn--pill btn-secondary m-btn m-btn--custom m-btn--bolder border-0"
id="fabricCurrentStatusWrapper">
<span class="roboto font-weight-bold text-white" id="fabricCurrentStatus"></span>
</button>

View File

@ -0,0 +1,53 @@
{% extends 'default.html' %}
{% block content %}
<div class="m-content">
<div class="row">
<div class="col-xl-6 col-lg-12">
<!--Begin::Portlet-->
<div class="m-portlet m-portlet--full-height ">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
Отрезки времени работы фабрики
</h3>
</div>
</div>
</div>
<div class="m-portlet__body">
<div class="m-scrollable m-scroller ps ps--active-y" data-scrollable="true"
style="max-height: 70vh; overflow: hidden;">
{% for object in objects_list %}
<div class="m-list-badge m-list-badge--light-bg m--margin">
{% if object.status == 'WO' %}
<div class="m-list-badge__label m--font-success">{{ object.time|date:"d.m.Y H:i" }}</div>
{% elif object.status == 'WA' %}
<div class="m-list-badge__label m--font-warning">{{ object.time|date:"d.m.Y H:i" }}</div>
{% elif object.status == 'NW' %}
<div class="m-list-badge__label m--font-danger">{{ object.time|date:"d.m.Y H:i" }}</div>
{% endif %}
<div class="m-list-badge__items">
{% if object.status == 'WO' %}
<span class="m-list-badge__item m-list-badge__item--success">Работает</span>
{% elif object.status == 'WA' %}
<span class="m-list-badge__item m-list-badge__item--warning">Работает без нагрузки</span>
{% elif object.status == 'NW' %}
<span class="m-list-badge__item m-list-badge__item--danger">Не работает</span>
{% endif %}
</div>
</div>
<hr>
{% endfor %}
</div>
</div>
</div>
<!--End::Portlet-->
</div>
</div>
</div>
{% endblock %}

View File

@ -1,10 +1,23 @@
from django.urls import path, include
from apps.main import views_main
from apps.main.services.meteo.views import get_meteo_data
from apps.main.views_main import aspiration, scales, worktime_history
from django.urls import include, path
urlpatterns = [
path("", views_main.mainindex, name="mainindex"),
path("scada/", views_main.scada_index, name="scada_index"),
path("scada/ajax/", views_main.get_ajax, name="get_ajax"),
path("", include("apps.main.services.urls")),
# Уголь
path('', views_main.mainindex, name='main_index'),
path('scada/flotation/', views_main.scada_flotation),
path('scada/charger/', views_main.scada_charger),
path('scada/flotation/ajax/', views_main.scada_flotation_get_ajax),
path('scada/', views_main.scada_index, name='scada_index'),
path('scada/ajax/', views_main.get_ajax, name='get_ajax'),
# path('scada/charger/', views_main.scada_charger, name='scada_charger'),
path('', include('apps.main.services.urls')),
path('scale/', scales, name='concentrate_and_dropout'),
path('aspiration/', aspiration, name='aspiration'),
path('worktime/history/', worktime_history, name='worktime_history'),
path('meteo/', get_meteo_data, name='get_meteo_data'),
# re_path(r"^proxy/(?P<path>.*)$", proxy_view),
]
# create_worktime_data()

View File

@ -1,60 +1,140 @@
# -*- coding: utf-8 -*-
import traceback
import datetime
import requests
import base64
import traceback
from datetime import timedelta
from datetime import datetime
from requests.auth import HTTPBasicAuth
from django.conf import settings
from django.db.models import Q
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.db.models import Avg, Max, Min
import requests
from apps.main.models.worktime import FabricWorkTime
from apps.main.services.base_service import DashboardBaseService
from apps.util import generalmodule
from apps.util.base_view import group_required
from apps.util.generalmodule import get_context_template
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.views.decorators.cache import never_cache
from sabron.util import logging
@login_required(login_url="/accounts/login/?next=")
@login_required(login_url='/accounts/login/?next=')
@group_required('Уголь')
@never_cache
def mainindex(request):
try:
if request.method == "GET":
context = {
"updatepage": True,
}
return render(request, "main_index.html", context)
except Exception as err:
if request.method == 'GET':
context = get_context_template(request)
return render(request, 'main_index.html', context)
except Exception:
logging.error(traceback.format_exc())
@login_required(login_url="/accounts/login/?next=")
@login_required(login_url='/accounts/login/?next=')
@never_cache
def get_ajax(request):
try:
dataimage = base64.b64encode(
requests.get("http://192.168.10.251:8000/screen").content
requests.get('http://192.168.10.251:8000/screen').content
)
data = dict()
data.update(img="data:image/png;base64," + dataimage.decode("utf-8"))
data.update(img='data:image/png;base64,' + dataimage.decode('utf-8'))
return generalmodule.ReturnJson(200, data)
except Exception as err:
except Exception:
logging.error(traceback.format_exc())
@login_required(login_url="/accounts/login/?next=")
@login_required(login_url='/accounts/login/?next=')
@group_required('Уголь')
@never_cache
def scada_index(request):
try:
if request.method == "GET":
if request.method == 'GET':
context = {
"updatepage": True,
'updatepage': True,
}
return render(request, "scada_index.html", context)
except Exception as err:
return render(request, 'scada_index.html', context)
except Exception:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@group_required('Уголь')
@never_cache
def scada_flotation(request):
try:
if request.method == 'GET':
context = {
'updatepage': True,
}
return render(request, 'scada_flotation.html', context)
except Exception:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def scada_flotation_get_ajax(request):
try:
dataimage = base64.b64encode(
requests.get('http://192.168.10.247:8000/screen').content
)
data = dict()
data.update(img='data:image/png;base64,' + dataimage.decode('utf-8'))
return generalmodule.ReturnJson(200, data)
except Exception:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@group_required('Уголь')
@never_cache
def scales(request):
return render(request, 'concentrate_and_dropout.html')
@login_required(login_url='/accounts/login/?next=')
@group_required('Уголь')
@never_cache
def aspiration(request):
return render(request, 'aspiration.html')
@login_required(login_url='/accounts/login/?next=')
@group_required('Уголь')
@never_cache
def worktime_history(request):
scale = request.GET.get('scale')
current_time = DashboardBaseService.get_current_time()
if not scale:
return redirect('/main/')
match scale:
case 'shift':
start_shift = DashboardBaseService.get_shift_start(current_time)
objects_list = FabricWorkTime.objects.filter(time__gt=start_shift).order_by(
'-time'
)
case 'week':
start_week = (
current_time - timedelta(days=current_time.weekday())
).replace(hour=0, minute=0, second=0, microsecond=0)
objects_list = FabricWorkTime.objects.filter(time__gt=start_week).order_by(
'-time'
)
case 'month':
start_month = current_time.replace(
day=1, hour=0, minute=0, second=0, microsecond=0
)
objects_list = FabricWorkTime.objects.filter(time__gt=start_month).order_by(
'-time'
)
case _:
return redirect('/main/')
return render(request, 'worktime_history.html', {'objects_list': objects_list})
@login_required(login_url='/accounts/login/?next=')
@group_required('Уголь')
@never_cache
def scada_charger(request):
try:
return redirect('/app/')
except Exception:
logging.error(traceback.format_exc())

View File

View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class ManagementConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.management'

View File

@ -0,0 +1,69 @@
from django import forms
from django.contrib.auth.models import Group, User
class UserForm(forms.ModelForm):
username = forms.CharField(
label='Имя пользователя',
widget=forms.TextInput(attrs={'class': 'form-control m-input'}),
)
password1 = forms.CharField(
label='Пароль',
widget=forms.PasswordInput(attrs={'class': 'form-control m-input'}),
required=False,
)
password2 = forms.CharField(
label='Подтверждение пароля',
widget=forms.PasswordInput(attrs={'class': 'form-control m-input'}),
required=False,
)
groups = forms.ModelMultipleChoiceField(
queryset=Group.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required=False,
label='Права доступа',
)
class Meta:
model = User
fields = ('username', 'groups')
def __init__(self, *args, **kwargs):
self.is_edit = kwargs.pop('is_edit', False)
super().__init__(*args, **kwargs)
if self.is_edit:
self.fields['password1'].help_text = (
'Оставьте пустым, чтобы не менять пароль.'
)
self.fields['password2'].help_text = (
'Оставьте пустым, чтобы не менять пароль.'
)
else:
self.fields['password1'].required = False
self.fields['password2'].required = False
def clean(self):
cleaned_data = super().clean()
password1 = cleaned_data.get('password1')
password2 = cleaned_data.get('password2')
if password1 or password2:
if password1 != password2:
raise forms.ValidationError('Пароли не совпадают.')
return cleaned_data
def save(self, commit=True):
user = super().save(commit=False)
password = self.cleaned_data.get('password1')
if password:
user.set_password(password)
if commit:
user.save()
user.groups.set(self.cleaned_data['groups'])
user.save()
return user

View File

@ -0,0 +1,161 @@
{% extends 'default.html' %}
{% block content %}
<div class="row m-2">
<div class="col-lg-8 col-sm-12">
<div class="m-portlet m-portlet--mobile m-portlet--body-progress-">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
Пользователи
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet__nav">
<li class="m-portlet__nav-item">
<a href="{% url 'management:create_user' %}" class="btn btn-primary m-btn m-btn--icon">
<span>
<i class="fa fa-plus"></i>
<span>Добавить пользователя</span>
</span>
</a>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body p-4" style="max-height: 75vh; overflow-y: scroll">
<div class="tab-content">
<!--begin::Widget 14-->
<div class="m-widget4">
{% for user in users %}
<!--begin::Widget 14 Item-->
<div class="d-flex justify-content-between mb-3 pb-2 border-bottom">
<div class="m-widget4__info d-flex flex-column">
<span class="m-widget4__title" style="font-size: 1.2rem">
<a href="{% url 'management:update_user' user.id %}"
style="text-decoration: underline">
<b>{{ user.username }}</b>
</a>
</span>
<span class="m-widget4__sub" style="font-size: 1rem">
<b>Права доступа:</b>
{% for group in user.groups.all %}
<u>{{ group }}</u>
{% empty %}
-
{% endfor %}
</span>
</div>
<div class="d-flex" style="gap: .5em">
<a href="{% url 'management:delete_user' user.id %}" class="m-btn btn btn-danger">Удалить</a>
</div>
</div>
{% endfor %}
<!--end::Widget 14 Item-->
</div>
</div>
</div>
</div>
</div>
{% if request.user.is_superuser %}
<div class="col-lg-4 col-sm-12">
<div class="m-portlet m-portlet--mobile m-portlet--body-progress-">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
Весы
</h3>
</div>
</div>
</div>
<div class="m-portlet__body p-4">
<div class="d-flex flex-column ">
<div>
<button type="button" class="btn btn-primary roboto mb-4" data-toggle="modal"
data-target="#fabricGoalModal" id="launchModalBtn">
Изменить значение цели по переработке
</button>
</div>
</div>
</div>
</div>
</div>
{% endif %}
</div>
<div class="modal fade" id="fabricGoalModal" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
aria-hidden="true" style="display: none;">
<div class="modal-dialog" role="document">
<form class="modal-content" id="dropoutAndConcentrateForm">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" id="ModalLabel">Изменение значение цели по переработке</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="goalModalAlerts"></div>
<div class="m-portlet__body">
<div class="form-group m-form__group">
<label for="goalInput">Цель по переработке (тонн)</label>
<input type="number" class="form-control m-input m-input--square" id="goalInput"
placeholder="Введите значение в тоннах">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary roboto" data-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary roboto" id="submitBtn">Отправить</button>
</div>
</form>
</div>
</div>
{% endblock %}
{% block script_footer %}
<script>
const input = document.querySelector("#goalInput")
const submitBtn = document.querySelector("#submitBtn")
const goalModalAlerts = document.querySelector('#goalModalAlerts')
document.addEventListener('DOMContentLoaded', async () => {
const goal = await fetch('/main/scales/fabric_goal/').then(response => response.json())
input.value = goal.goal
})
submitBtn.addEventListener('click', async () => {
const data = {goal: input.value}
const response = await fetch('/main/scales/fabric_goal/', {
method: 'PUT',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'X-CSRFToken': window.getCookie('csrftoken')
},
body: JSON.stringify(data)
})
const responseJson = await response.json()
const alert = document.createElement('div')
alert.classList.add('alert', 'roboto', 'bold')
alert.setAttribute('role', 'alert')
alert.textContent = `${responseJson.message}`
goalModalAlerts.appendChild(alert)
if (responseJson.success) {
alert.classList.add('alert-success')
// Спрятать модальное окно
// document.getElementById('fabricGoalModal').classList.remove('show')
document.querySelectorAll('.modal-backdrop').forEach(el => el.remove())
} else {
// Отобразить ошибку
alert.classList.add('alert-danger')
}
})
</script>
{% endblock %}

View File

@ -0,0 +1,28 @@
{% extends 'default.html' %}
{% block content %}
<div class="modal fade show" id="m_modal_1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
style="display: block;">
<div class="modal-dialog" role="document">
<form method="post" class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Удалить пользователя "{{ object.username }}"?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% csrf_token %}
Это действие невозможно отменить.
</div>
<div class="modal-footer">
<a href="{% url 'management:administration' %}" class="btn btn-secondary">Отмена</a>
<button type="submit" class="btn btn-primary">Да, удалить</button>
</div>
</form>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,60 @@
{% extends 'default.html' %}
{% block content %}
<div class="row">
<div class="col-md-6">
<!--begin::Portlet-->
<div class="m-portlet mt-3 ml-3">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon m--hide">
<i class="la la-gear"></i>
</span>
<h3 class="m-portlet__head-text">
{% if object %}
Редактирование
{% else %}
Создание
{% endif %} пользователя
</h3>
</div>
</div>
</div>
<!--begin::Form-->
<form class="m-form m-form--fit m-form--label-align-right" method="post">
{% csrf_token %}
<div class="p-4">
{{ form.as_p }}
</div>
{# <div class="m-portlet__body">#}
{# <div class="form-group m-form__group">#}
{# <label for="{{ form.username.id_for_label }}">Имя пользователя</label>#}
{# {{ form.username }}#}
{# <span class="m-form__help">По этому имени пользователь будет входить в систему.</span>#}
{# </div>#}
{# <div class="form-group m-form__group">#}
{# <label for="{{ form.password.id_for_label }}">Пароль</label>#}
{# {{ form.password }}#}
{# </div>#}
{# <div class="form-group m-form__group">#}
{# <label for="{{ form.groups.id_for_label }}">Права доступа</label>#}
{# {{ form.groups }}#}
{# </div>#}
{# </div>#}
<div class="m-portlet__foot m-portlet__foot--fit">
<div class="m-form__actions p-4">
<button type="submit" class="btn btn-primary">Сохранить</button>
<a href="{% url 'management:administration' %}" class="btn btn-secondary">Отмена</a>
</div>
</div>
</form>
<!--end::Form-->
</div>
<!--end::Portlet-->
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,16 @@
from apps.management.views.view_management import (
UserDeleteView,
administration,
create_user,
update_user,
)
from django.urls import path
app_name = 'management'
urlpatterns = [
path('', administration, name='administration'),
path('users/create/', create_user, name='create_user'),
path('users/<int:pk>/edit/', update_user, name='update_user'),
path('users/<int:pk>/delete/', UserDeleteView.as_view(), name='delete_user'),
]

View File

@ -0,0 +1,74 @@
import traceback
from apps.management.forms import UserForm
from apps.util.generalmodule import get_context_template
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse_lazy
from django.views.decorators.cache import never_cache
from django.views.generic import DeleteView
from sabron.util import logging
@login_required(login_url='/accounts/login/?next=')
@never_cache
def administration(request: HttpRequest) -> HttpResponse:
if not (request.user.profile.role in (1, 2)):
return redirect('mainindex')
users = User.objects.all().exclude(is_superuser=True).order_by('username')
context = get_context_template(request)
context['users'] = users
return render(request, 'management/administration.html', context)
@login_required(login_url='/accounts/login/?next=')
@never_cache
def create_user(request: HttpRequest) -> HttpResponse:
try:
if not (request.user.profile.role in (1, 2)):
return redirect('mainindex')
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
return redirect('management:administration')
elif request.method == 'GET':
context = get_context_template(request)
form = UserForm()
context['form'] = form
return render(request, 'management/form.html', context)
except Exception:
print(traceback.format_exc())
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def update_user(request, pk):
try:
if not (request.user.profile.role in (1, 2)):
return redirect('mainindex')
if request.method == 'POST':
user = get_object_or_404(User, id=pk)
form = UserForm(request.POST, instance=user, is_edit=True)
if form.is_valid():
form.save()
return redirect('management:administration')
elif request.method == 'GET':
user = get_object_or_404(User, id=pk)
context = get_context_template(request)
form = UserForm(instance=user)
context['form'] = form
context['object'] = user
return render(request, 'management/form.html', context)
except Exception:
print(traceback.format_exc())
logging.error(traceback.format_exc())
class UserDeleteView(DeleteView):
model = User
template_name = 'management/confirm_delete.html'
success_url = reverse_lazy('management:administration')

View File

@ -1,14 +1,8 @@
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.conf.urls import (
include,
) # Используйте include() чтобы добавлять URL из каталога приложения
from apps.montorem.views import views_main
from django.urls import path
urlpatterns = [
url(r"^$", views_main.mainindex, name="mainindex"),
url(r"^sensor/$", views_main.sensor, name="sensor"),
url(r"sensor/sensor_ajax/$", views_main.sensor_ajax, name="sensor_ajax"),
path('', views_main.mainindex, name='mainindex'),
path('sensor/', views_main.sensor, name='sensor'),
path('sensor/sensor_ajax/', views_main.sensor_ajax, name='sensor_ajax'),
]

View File

@ -1,10 +1,11 @@
import functools
import traceback
from datetime import datetime
from django.conf import settings
from django.db.models import QuerySet
from django.http import JsonResponse
from django.shortcuts import redirect
from sabron.util import logging
@ -16,8 +17,8 @@ def ret(json_object, status=200):
def error_response(exception):
res = {
"errorMessage": str(exception),
"traceback": traceback.format_exc() if settings.DEBUG else "error occured",
'errorMessage': str(exception),
'traceback': traceback.format_exc() if settings.DEBUG else 'error occured',
}
logging.error(traceback.format_exc())
return ret(res, status=400)
@ -36,8 +37,21 @@ def base_view(fn):
def get_qs_by_range(model, start: datetime, end: datetime) -> QuerySet:
return (
model.objects.only("time")
model.objects.only('time')
.filter(time__range=(start, end))
.order_by("time")
.order_by('time')
.values()
)
def group_required(*groups):
def decorator(function):
def wrapper(request, *args, **kwargs):
if request.user.groups.filter(name__in=groups).exists():
return function(request, *args, **kwargs)
return redirect('router')
return wrapper
return decorator

View File

@ -1,32 +1,28 @@
# -*- coding: utf-8 -*-
import os
import json
import re
import traceback
from datetime import datetime, timedelta
from django.core.files import File
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.views.static import serve
from django.urls import re_path
from django.db.models import Avg, Max, Min
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.http import (
Http404,
HttpResponse,
HttpResponsePermanentRedirect,
HttpResponseRedirect,
)
from django.db import connection
from sabron.util import logging
from django.urls import re_path
from django.views.static import serve
from sabron.models import Settings
def get_context_template():
def get_context_template(request):
context = {}
settings_list = Settings.objects.all()
for setting in settings_list:
context.update({setting.name: setting.value})
user_groups = [group.name for group in request.user.groups.all()]
user_have_fin_group = 'Финансы' in user_groups
user_have_coal_group = 'Уголь' in user_groups
context['user_have_fin_group'] = user_have_fin_group
context['user_have_coal_group'] = user_have_coal_group
return context
@ -43,47 +39,47 @@ def static(prefix, view=serve, **kwargs):
"""
if not prefix:
raise ImproperlyConfigured("Empty static prefix not permitted")
elif not settings.DEBUG or "://" in prefix:
raise ImproperlyConfigured('Empty static prefix not permitted')
elif not settings.DEBUG or '://' in prefix:
# No-op if not in debug mode or a non-local prefix.
return []
User.is_authenticated
return [
re_path(
r"^%s(?P<path>.*)$" % re.escape(prefix.lstrip("/")), view, kwargs=kwargs
r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs
),
]
def getObjectOR404(klassModel, *args, **kwargs):
objectModel = get_object_or_404(klassModel, pk=kwargs["pk"])
objectModel = get_object_or_404(klassModel, pk=kwargs['pk'])
return objectModel
@login_required(login_url="/accounts/login/")
@login_required(login_url='/accounts/login/')
def get_media_URL(View):
return settings.MEDIA_URL
@login_required(login_url="/accounts/login/")
@login_required(login_url='/accounts/login/')
def get_media_ROOT(request):
return settings.MEDIA_ROOT
def convert_number(number):
return (
number.replace("A", "А")
.replace("B", "В")
.replace("C", "С")
.replace("E", "Е")
.replace("H", "Н")
.replace("K", "К")
.replace("M", "М")
.replace("O", "О")
.replace("P", "Р")
.replace("T", "Т")
.replace("X", "Х")
.replace("Y", "У")
number.replace('A', 'А')
.replace('B', 'В')
.replace('C', 'С')
.replace('E', 'Е')
.replace('H', 'Н')
.replace('K', 'К')
.replace('M', 'М')
.replace('O', 'О')
.replace('P', 'Р')
.replace('T', 'Т')
.replace('X', 'Х')
.replace('Y', 'У')
)
@ -93,21 +89,21 @@ def getJobTime(seccond):
m = (a // 60) % 60
s = a % 60
if m < 10:
m = str("0" + str(m))
m = str('0' + str(m))
else:
m = str(m)
if s < 10:
s = str("0" + str(s))
s = str('0' + str(s))
else:
s = str(s)
return str(h) + ":" + str(m) + ":" + str(s)
return str(h) + ':' + str(m) + ':' + str(s)
def ReturnJson(code, data):
httpRespon = HttpResponse()
httpRespon["Content-Type"] = "application/json"
httpRespon['Content-Type'] = 'application/json'
# httpRespon['Cache-Control']='no-cache,no-store'
httpRespon["charset"] = "ASCII"
httpRespon['charset'] = 'ASCII'
httpRespon.status_code = code
httpRespon.write(json.dumps(data, sort_keys=True, indent=4))
return httpRespon
@ -115,7 +111,7 @@ def ReturnJson(code, data):
def Return404():
httpRespon = HttpResponse()
httpRespon["Content-Type"] = "text/plain"
httpRespon['Content-Type'] = 'text/plain'
# httpRespon['charset']='ASCII'
httpRespon.status_code = 404
# httpRespon.write(json.dumps(data, sort_keys=True, indent=4))
@ -124,14 +120,14 @@ def Return404():
def ReturnText(text):
httpRespon = HttpResponse()
httpRespon["Content-Type"] = "text/plain"
httpRespon['Content-Type'] = 'text/plain'
httpRespon.write(text)
return httpRespon
def ReturnApi(code, data):
httpRespon = HttpResponse()
httpRespon["Content-Type"] = "application/json"
httpRespon['Content-Type'] = 'application/json'
httpRespon.status_code = code
httpRespon.write(json.dumps(data, sort_keys=True, indent=4))
return httpRespon
@ -145,6 +141,6 @@ def getSeconds(data1, data2):
def buildblock(size):
return "".join(
return ''.join(
random.choice(string.ascii_letters + string.digits) for _ in range(size)
)

View File

@ -1,9 +1,7 @@
from typing import Union, Optional, Dict
from sabron.util import logging
import redis
from sabron.util import logging
class RedisBaseService:
"""
@ -50,7 +48,7 @@ class RedisBaseService:
class RedisSimpleService(RedisBaseService):
"""Класс для работы с обычными Redis значениями (str)"""
def set_value(self, key: str, value: Union[bytes, str, int, float]):
def set_value(self, key: str, value: bytes | str | int | float):
"""
Устанавливает значение в Redis по ключу.
@ -62,7 +60,7 @@ class RedisSimpleService(RedisBaseService):
self.connection.set(key, value)
return True
except redis.RedisError as e:
logging.error(f"Error setting value: {e}")
logging.error(f'Error setting value: {e}')
return False
def get_value(self, key: str) -> str | None:
@ -75,10 +73,10 @@ class RedisSimpleService(RedisBaseService):
try:
value = self.connection.get(key)
if value is None:
return "0"
return value.decode("utf-8")
return value
return value.decode('utf-8')
except (redis.RedisError, AttributeError) as e:
print(f"Error getting value: {e}")
print(f'Error getting value: {e}')
logging.error(e)
return None
@ -93,15 +91,13 @@ class RedisSimpleService(RedisBaseService):
self.connection.delete(key)
return True
except redis.RedisError as e:
print(f"Error deleting value: {e}")
print(f'Error deleting value: {e}')
logging.error(e)
return False
class RedisHashService(RedisBaseService):
def hset_value(
self, name: str, key: str, value: Union[bytes, str, int, float]
) -> bool:
def hset_value(self, name: str, key: str, value: bytes | str | int | float) -> bool:
"""
Устанавливает значение в хэш по ключу.
@ -114,10 +110,10 @@ class RedisHashService(RedisBaseService):
self.connection.hset(name, key, value)
return True
except redis.RedisError as e:
print(f"Error setting hash value: {e}")
print(f'Error setting hash value: {e}')
return False
def hget_value(self, name: str, key: str) -> Optional[str]:
def hget_value(self, name: str, key: str) -> str | None:
"""
Получает значение из хэша по ключу.
@ -127,9 +123,9 @@ class RedisHashService(RedisBaseService):
"""
try:
value = self.connection.hget(name, key)
return value.decode("utf-8") if value else None
return value.decode('utf-8') if value else None
except redis.RedisError as e:
print(f"Error getting hash value: {e}")
print(f'Error getting hash value: {e}')
return None
def hdel_value(self, name: str, key: str) -> bool:
@ -144,10 +140,10 @@ class RedisHashService(RedisBaseService):
self.connection.hdel(name, key)
return True
except redis.RedisError as e:
print(f"Error deleting hash value: {e}")
print(f'Error deleting hash value: {e}')
return False
def hget_all(self, name: str) -> Optional[Dict[str, str]]:
def hget_all(self, name: str) -> dict[str, str] | None:
"""
Получает все ключи и значения из хэша.
@ -157,14 +153,22 @@ class RedisHashService(RedisBaseService):
try:
result = self.connection.hgetall(name)
return (
{k.decode("utf-8"): v.decode("utf-8") for k, v in result.items()}
{k.decode('utf-8'): v.decode('utf-8') for k, v in result.items()}
if result
else None
)
except redis.RedisError as e:
print(f"Error getting all hash values: {e}")
print(f'Error getting all hash values: {e}')
return None
class RedisService(RedisHashService, RedisSimpleService):
class RedisExpireService(RedisBaseService):
def set_expire(self, key: str, expire: int):
try:
self.connection.expire(key, expire)
except redis.RedisError as e:
print(f'Error getting setting expiring values: {e}')
class RedisService(RedisHashService, RedisSimpleService, RedisExpireService):
pass

View File

@ -0,0 +1,31 @@
from apps.util.redis_api import RedisService
class RedisCache:
def __init__(self, redis_host, redis_port):
self.redis_port = redis_port
self.redis_host = redis_host
def set_cache_value(self, key: str, value: str) -> str:
with RedisService(
host=self.redis_host, port=self.redis_port, db=2
) as redis_service:
value = redis_service.set_value('cache_tasks/' + key, value)
redis_service.set_expire('cache_tasks/' + key, 60)
return value
def get_cache_value(self, key: str) -> bool:
with RedisService(
host=self.redis_host, port=self.redis_port, db=2
) as redis_service:
value = redis_service.get_value('cache_tasks/' + key)
if value is None:
return False
return True
def delete_cache_value(self, key: str) -> str:
with RedisService(
host=self.redis_host, port=self.redis_port, db=2
) as redis_service:
value = redis_service.delete_value('cache_tasks/' + key)
return value

12
app/apps/util/version.py Normal file
View File

@ -0,0 +1,12 @@
from sabron.util.sabronmodule import get_settings, set_settings
def get_version_from_db(version_name):
res = get_settings(version_name)
return res
def print_update(version_name, version_from_file):
print(f'Установлена версия {version_from_file}')
set_settings(version_name, version_from_file)
return 0

560
app/fixtures/users.json Normal file
View File

@ -0,0 +1,560 @@
[
{
"model": "auth.user",
"pk": 1,
"fields": {
"password": "pbkdf2_sha256$260000$EgJKhDBm3iJr79cfHhYa0j$ZB/K7Z1wl+TrPPcgJ5HCrPXIydTxqmp5cfSmcDWr6dA=",
"last_login": "2025-04-09T02:03:02.549Z",
"is_superuser": true,
"username": "admin",
"first_name": "",
"last_name": "",
"email": "admin@my.ru",
"is_staff": true,
"is_active": true,
"date_joined": "2024-01-11T08:33:18.046Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 2,
"fields": {
"password": "pbkdf2_sha256$260000$fMDLwysdSIiWWHVVZhLJdG$vh0xnezDUeixobTiasrdor8yFC+hQ5SndGBiYR4jgOg=",
"last_login": "2025-04-08T22:39:56.771Z",
"is_superuser": false,
"username": "Kranchev",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-12T09:21:18Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 3,
"fields": {
"password": "pbkdf2_sha256$260000$acwTUU03XAyVNvoxRjdlhN$/qyr8BT2zDhHiQ+pvbk4BNYUI+LUplIEzANDMIOTpQg=",
"last_login": "2024-02-15T04:39:05Z",
"is_superuser": false,
"username": "sabron",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-25T04:27:32Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 4,
"fields": {
"password": "pbkdf2_sha256$260000$yLESO9AUgM135jyBAQRMUJ$qcOcp9XMqFI9qK/+yYRPBGEtanjFD0P7QMlsyFmJR9U=",
"last_login": "2025-04-08T09:11:13.784Z",
"is_superuser": false,
"username": "Kuznetsov",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-25T06:33:49.315Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 5,
"fields": {
"password": "pbkdf2_sha256$260000$3ChoU7XMYJVBW6nzE5QCHh$pibL+IRFanoJ09NiOPiUyXKsjXqpObg/rUNXktMmKDM=",
"last_login": "2025-03-26T01:16:08.418Z",
"is_superuser": false,
"username": "Bendin",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-25T09:38:25Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 6,
"fields": {
"password": "pbkdf2_sha256$260000$thj7r3jml9tUkhxV0sYSrj$jAs18cb0zVykn6aZGQvULmDtle7mnw43CWG7X0teMAM=",
"last_login": "2025-04-08T12:50:50.184Z",
"is_superuser": false,
"username": "Arzanov",
"first_name": "Максим",
"last_name": "Арзанов",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-25T10:25:07Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 7,
"fields": {
"password": "pbkdf2_sha256$260000$Vn9uNm00JV2tmHSdKeCJcb$C2r7ELj6uMln0GRF1rXzq8H01fj51Y3T3U+9ENtvxTo=",
"last_login": "2025-03-27T15:02:15.504Z",
"is_superuser": false,
"username": "Turov",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-25T10:27:39.743Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 8,
"fields": {
"password": "pbkdf2_sha256$260000$wLPFq0xOwphZMAFBoTIPJe$iW4teKj2A7svVavQxSM7RyOX6uG8gzZYg9zw369BG08=",
"last_login": "2025-03-30T13:49:59.276Z",
"is_superuser": false,
"username": "Loshenov",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-25T11:41:49.891Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 9,
"fields": {
"password": "pbkdf2_sha256$260000$7719HES3532l3GLieuabxg$D+BidCqd+1biXZDwS8x7QvLusQzd1XBJW1U8uEVZE+4=",
"last_login": "2025-04-09T02:41:27.425Z",
"is_superuser": false,
"username": "Barmin",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-25T12:27:03.955Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 10,
"fields": {
"password": "pbkdf2_sha256$260000$j8SxHIJ7r17Erox6mn0R28$OcMQ8zHkTHQ9GU3ANnPax7yKAnmYfEMtRnaFpPrPoXE=",
"last_login": "2025-04-03T01:21:38.953Z",
"is_superuser": false,
"username": "Mehanik",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-01-25T13:10:48.754Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 11,
"fields": {
"password": "pbkdf2_sha256$260000$f8vVPRACJWz9PdlRRUVbqV$XusTgQTgWTdwh4cCXl8cVuEBpEmLtyS9VRByAcggYo4=",
"last_login": null,
"is_superuser": false,
"username": "Gorbunov",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-02-22T06:11:37.512Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 12,
"fields": {
"password": "pbkdf2_sha256$260000$xu4WSihrVLyUqBVUoP8K3L$vTFcwfZoXBk6a9zPcQuxZ2/I9RldHcRpPXkp6FNvvTg=",
"last_login": "2025-04-05T18:09:55.195Z",
"is_superuser": false,
"username": "Kostyleva",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-02-22T06:12:13.945Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 13,
"fields": {
"password": "pbkdf2_sha256$260000$Fc1C4Bv9XQBKTrq2AwpRC6$M7W3gWjua7lZLbb9l67elENdbd2piNUuWbNFBvdtgkw=",
"last_login": "2025-04-02T23:11:11.261Z",
"is_superuser": false,
"username": "Savelev",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-02-22T06:12:31.439Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 14,
"fields": {
"password": "pbkdf2_sha256$260000$hVUvUFW0vklS3ndXMjG96k$qht8hyI1q66lZu7wJw5vovlsuJLcZ74Gjw/ffxbpstI=",
"last_login": "2025-04-07T21:41:44.559Z",
"is_superuser": false,
"username": "Borodina",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-02-22T06:12:47.942Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 15,
"fields": {
"password": "pbkdf2_sha256$260000$TKVW4SpcLDaAzuu0AyOhQp$yemZWVRfZXm8Khs8mjHvmo6LPsK+DhCNQl7sve0w0Jg=",
"last_login": "2024-12-18T15:06:18.337Z",
"is_superuser": false,
"username": "Churilov",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-02-22T06:13:11.362Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 16,
"fields": {
"password": "pbkdf2_sha256$260000$Xdz5ffOriYqJF0z6zF3xwy$HLvG7J/G6Dvt6VybJEFjvBAywGeQ8eUBFEy62KiBmnw=",
"last_login": null,
"is_superuser": false,
"username": "Markelov",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-02-22T06:13:26.030Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 17,
"fields": {
"password": "pbkdf2_sha256$260000$AI6TNga2uTetqfce8EWf4C$MA4PO/h9lSfDavTaZHz5T0uTfZS2lZYtPMJ5iYNxQnI=",
"last_login": "2025-03-18T03:22:27.362Z",
"is_superuser": false,
"username": "Vakalov",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-03-05T08:56:33.878Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 18,
"fields": {
"password": "pbkdf2_sha256$260000$EYw8AIfGm9A3nsTuRroLt5$pf6/1FpOlukUEcloMAzzukZsiRlkZGF7w77dUpa+YHY=",
"last_login": "2024-12-27T19:35:57.118Z",
"is_superuser": false,
"username": "Slepcov",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-04-10T11:04:43.102Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 19,
"fields": {
"password": "pbkdf2_sha256$260000$Wft8zPi9cHZt3ehygiDAiE$2I7gCl5vOIhWXZJcU53kC/lD03Y3KMrlR8zOJ/KS9yU=",
"last_login": "2024-05-15T13:13:40.679Z",
"is_superuser": false,
"username": "tv",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-05-15T13:12:16.594Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 20,
"fields": {
"password": "pbkdf2_sha256$260000$FZUwXzC4GeFv52pm6Z6hPU$raiu2+7LmWuNtUu/CJ9XxzoggfwAYwLV02dfffQ7jQA=",
"last_login": "2025-02-13T09:13:53.405Z",
"is_superuser": false,
"username": "m.kovalev",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-06-01T22:45:56Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 21,
"fields": {
"password": "pbkdf2_sha256$260000$J3JDlpxFwrEOGa5zTieKCV$0d9Li1gRjIGmXWpKY2lqX64OVA03w1aqvjGD/0gtDkA=",
"last_login": "2024-06-26T11:02:45.024Z",
"is_superuser": false,
"username": "tvk",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-06-26T11:00:57.474Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 22,
"fields": {
"password": "pbkdf2_sha256$260000$Kro3kliyFyCaNcsvUwSEPO$fASxv6Te2zqgUTDvuWKA2qn7dRalIon5g2EEKeQyH5E=",
"last_login": "2025-03-25T06:26:30.470Z",
"is_superuser": false,
"username": "Mihailova",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-07-11T04:06:52.708Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 23,
"fields": {
"password": "pbkdf2_sha256$260000$6dgPphWtHuBA0DUKaKZgc2$RdcHy9FaXPIUVIm0vpU7Mni1/3FBbr7IaKjkiOBGplU=",
"last_login": "2025-04-08T02:36:00.842Z",
"is_superuser": true,
"username": "cybercode",
"first_name": "",
"last_name": "",
"email": "admin@example.com",
"is_staff": true,
"is_active": true,
"date_joined": "2024-08-06T09:06:42Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 24,
"fields": {
"password": "pbkdf2_sha256$260000$xBd1BbKRwLwrhLCx0LXm1y$1i/DcnmZziZfIq6YSbij9Fdb3qzK/hAgXPtKNsuGYF8=",
"last_login": "2025-04-03T07:25:19.651Z",
"is_superuser": false,
"username": "repcofkk_user",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-08-06T10:12:59.120Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 25,
"fields": {
"password": "pbkdf2_sha256$260000$0oP0MilsGAp3K6eU0DDEMj$0ACEAbzHXmPWMCT7DHzyjq3SlfJW4YzB8RsnSQUB97A=",
"last_login": "2025-04-09T02:13:54.839Z",
"is_superuser": false,
"username": "Energy",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-08-07T05:51:24Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 27,
"fields": {
"password": "pbkdf2_sha256$260000$9IJoPgcLcAteJ19Njz7mCh$q9RD1cteBdCNbRn5TyCD7kPA4MY7hh3EF835kOw16UA=",
"last_login": "2024-12-15T01:03:53.485Z",
"is_superuser": false,
"username": "operator",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-11-26T04:18:58.818Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 28,
"fields": {
"password": "pbkdf2_sha256$260000$tR2z8A5OMYEXZKqsbsNOs9$jJfRfM/e7L+1Zydl+fRXBFDYS8X1wA+rT/adcvSIDfg=",
"last_login": "2024-12-12T05:56:50.289Z",
"is_superuser": false,
"username": "test",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2024-12-04T06:19:27.785Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 29,
"fields": {
"password": "pbkdf2_sha256$260000$1jVI4U5UK9asAPZuEgJ0af$PIRljJ6FmixZyouSi9FNzyU0B7FtBcwLznYzylVzAi8=",
"last_login": "2025-04-02T07:46:59.898Z",
"is_superuser": false,
"username": "Nadtochyi",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2025-02-05T06:26:14.613Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 30,
"fields": {
"password": "pbkdf2_sha256$260000$bv2cAffYBjh9fgX4qYwIRH$ILTdbF8eLxxgeNaSmlwAKovZuDKZnszySOUF8UfcNIc=",
"last_login": "2025-04-08T09:26:58.455Z",
"is_superuser": false,
"username": "Kazdorf",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2025-02-05T06:30:07.214Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 31,
"fields": {
"password": "pbkdf2_sha256$260000$vth9OdrdFi1afdkJLcGQIM$GLvqjymxdyndP9kkITLInq+tjtQpV1KPEDbz8459E+g=",
"last_login": null,
"is_superuser": false,
"username": "user",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2025-03-12T08:30:48.377Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 32,
"fields": {
"password": "pbkdf2_sha256$260000$UrA9gmoSjCiWmjGsFssUbr$5FspWwuLsw/jCbhmhudcdeRNjCcUSHSF4HWGT2rxA4U=",
"last_login": "2025-04-09T01:44:00.029Z",
"is_superuser": false,
"username": "Timofeev",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2025-03-17T12:22:06.394Z",
"groups": [],
"user_permissions": []
}
}
]

384
app/poetry.lock generated
View File

@ -1,4 +1,4 @@
# This file is automatically @generated by Poetry 1.8.2 and should not be changed by hand.
# This file is automatically @generated by Poetry 2.1.1 and should not be changed by hand.
[[package]]
name = "amqp"
@ -6,6 +6,7 @@ version = "5.2.0"
description = "Low-level AMQP client for Python (fork of amqplib)."
optional = false
python-versions = ">=3.6"
groups = ["main"]
files = [
{file = "amqp-5.2.0-py3-none-any.whl", hash = "sha256:827cb12fb0baa892aad844fd95258143bce4027fdac4fccddbc43330fd281637"},
{file = "amqp-5.2.0.tar.gz", hash = "sha256:a1ecff425ad063ad42a486c902807d1482311481c8ad95a72694b2975e75f7fd"},
@ -20,6 +21,7 @@ version = "3.8.1"
description = "ASGI specs, helper code, and adapters"
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "asgiref-3.8.1-py3-none-any.whl", hash = "sha256:3e1e3ecc849832fe52ccf2cb6686b7a55f82bb1d6aee72a58826471390335e47"},
{file = "asgiref-3.8.1.tar.gz", hash = "sha256:c343bd80a0bec947a9860adb4c432ffa7db769836c64238fc34bdc3fec84d590"},
@ -37,6 +39,7 @@ version = "4.0.3"
description = "Timeout context manager for asyncio programs"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "async-timeout-4.0.3.tar.gz", hash = "sha256:4640d96be84d82d02ed59ea2b7105a0f7b33abe8703703cd0ab0bf87c427522f"},
{file = "async_timeout-4.0.3-py3-none-any.whl", hash = "sha256:7405140ff1230c310e51dc27b3145b9092d659ce68ff733fb0cefe3ee42be028"},
@ -48,6 +51,7 @@ version = "4.2.0"
description = "Python multiprocessing fork with improvements and bugfixes"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "billiard-4.2.0-py3-none-any.whl", hash = "sha256:07aa978b308f334ff8282bd4a746e681b3513db5c9a514cbdd810cbbdc19714d"},
{file = "billiard-4.2.0.tar.gz", hash = "sha256:9a3c3184cb275aa17a732f93f65b20c525d3d9f253722d26a82194803ade5a2c"},
@ -59,6 +63,7 @@ version = "24.8.0"
description = "The uncompromising code formatter."
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "black-24.8.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:09cdeb74d494ec023ded657f7092ba518e8cf78fa8386155e4a03fdcc44679e6"},
{file = "black-24.8.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:81c6742da39f33b08e791da38410f32e27d632260e599df7245cccee2064afeb"},
@ -95,7 +100,7 @@ typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""}
[package.extras]
colorama = ["colorama (>=0.4.3)"]
d = ["aiohttp (>=3.7.4)", "aiohttp (>=3.7.4,!=3.9.0)"]
d = ["aiohttp (>=3.7.4) ; sys_platform != \"win32\" or implementation_name != \"pypy\"", "aiohttp (>=3.7.4,!=3.9.0) ; sys_platform == \"win32\" and implementation_name == \"pypy\""]
jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"]
uvloop = ["uvloop (>=0.15.2)"]
@ -105,6 +110,7 @@ version = "5.4.0"
description = "Distributed Task Queue."
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "celery-5.4.0-py3-none-any.whl", hash = "sha256:369631eb580cf8c51a82721ec538684994f8277637edde2dfc0dacd73ed97f64"},
{file = "celery-5.4.0.tar.gz", hash = "sha256:504a19140e8d3029d5acad88330c541d4c3f64c789d85f94756762d8bca7e706"},
@ -125,32 +131,32 @@ vine = ">=5.1.0,<6.0"
arangodb = ["pyArango (>=2.0.2)"]
auth = ["cryptography (==42.0.5)"]
azureblockblob = ["azure-storage-blob (>=12.15.0)"]
brotli = ["brotli (>=1.0.0)", "brotlipy (>=0.7.0)"]
brotli = ["brotli (>=1.0.0) ; platform_python_implementation == \"CPython\"", "brotlipy (>=0.7.0) ; platform_python_implementation == \"PyPy\""]
cassandra = ["cassandra-driver (>=3.25.0,<4)"]
consul = ["python-consul2 (==0.1.5)"]
cosmosdbsql = ["pydocumentdb (==2.3.5)"]
couchbase = ["couchbase (>=3.0.0)"]
couchbase = ["couchbase (>=3.0.0) ; platform_python_implementation != \"PyPy\" and (platform_system != \"Windows\" or python_version < \"3.10\")"]
couchdb = ["pycouchdb (==1.14.2)"]
django = ["Django (>=2.2.28)"]
dynamodb = ["boto3 (>=1.26.143)"]
elasticsearch = ["elastic-transport (<=8.13.0)", "elasticsearch (<=8.13.0)"]
eventlet = ["eventlet (>=0.32.0)"]
eventlet = ["eventlet (>=0.32.0) ; python_version < \"3.10\""]
gcs = ["google-cloud-storage (>=2.10.0)"]
gevent = ["gevent (>=1.5.0)"]
librabbitmq = ["librabbitmq (>=2.0.0)"]
memcache = ["pylibmc (==1.6.3)"]
librabbitmq = ["librabbitmq (>=2.0.0) ; python_version < \"3.11\""]
memcache = ["pylibmc (==1.6.3) ; platform_system != \"Windows\""]
mongodb = ["pymongo[srv] (>=4.0.2)"]
msgpack = ["msgpack (==1.0.8)"]
pymemcache = ["python-memcached (>=1.61)"]
pyro = ["pyro4 (==4.82)"]
pyro = ["pyro4 (==4.82) ; python_version < \"3.11\""]
pytest = ["pytest-celery[all] (>=1.0.0)"]
redis = ["redis (>=4.5.2,!=4.5.5,<6.0.0)"]
s3 = ["boto3 (>=1.26.143)"]
slmq = ["softlayer-messaging (>=1.0.3)"]
solar = ["ephem (==4.1.5)"]
solar = ["ephem (==4.1.5) ; platform_python_implementation != \"PyPy\""]
sqlalchemy = ["sqlalchemy (>=1.4.48,<2.1)"]
sqs = ["boto3 (>=1.26.143)", "kombu[sqs] (>=5.3.4)", "pycurl (>=7.43.0.5)", "urllib3 (>=1.26.16)"]
tblib = ["tblib (>=1.3.0)", "tblib (>=1.5.0)"]
sqs = ["boto3 (>=1.26.143)", "kombu[sqs] (>=5.3.4)", "pycurl (>=7.43.0.5) ; sys_platform != \"win32\" and platform_python_implementation == \"CPython\"", "urllib3 (>=1.26.16)"]
tblib = ["tblib (>=1.3.0) ; python_version < \"3.8.0\"", "tblib (>=1.5.0) ; python_version >= \"3.8.0\""]
yaml = ["PyYAML (>=3.10)"]
zookeeper = ["kazoo (>=1.3.1)"]
zstd = ["zstandard (==0.22.0)"]
@ -161,17 +167,31 @@ version = "2024.7.4"
description = "Python package for providing Mozilla's CA Bundle."
optional = false
python-versions = ">=3.6"
groups = ["main"]
files = [
{file = "certifi-2024.7.4-py3-none-any.whl", hash = "sha256:c198e21b1289c2ab85ee4e67bb4b4ef3ead0892059901a8d5b622f24a1101e90"},
{file = "certifi-2024.7.4.tar.gz", hash = "sha256:5a1e7645bc0ec61a09e26c36f6106dd4cf40c6db3a1fb6352b0244e7fb057c7b"},
]
[[package]]
name = "cfgv"
version = "3.4.0"
description = "Validate configuration and produce human readable error messages."
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9"},
{file = "cfgv-3.4.0.tar.gz", hash = "sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560"},
]
[[package]]
name = "charset-normalizer"
version = "3.3.2"
description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet."
optional = false
python-versions = ">=3.7.0"
groups = ["main"]
files = [
{file = "charset-normalizer-3.3.2.tar.gz", hash = "sha256:f30c3cb33b24454a82faecaf01b19c18562b1e89558fb6c56de4d9118a032fd5"},
{file = "charset_normalizer-3.3.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:25baf083bf6f6b341f4121c2f3c548875ee6f5339300e08be3f2b2ba1721cdd3"},
@ -271,6 +291,7 @@ version = "8.1.7"
description = "Composable command line interface toolkit"
optional = false
python-versions = ">=3.7"
groups = ["main", "dev"]
files = [
{file = "click-8.1.7-py3-none-any.whl", hash = "sha256:ae74fb96c20a0277a1d615f1e4d73c8414f5a98db8b799a7931d1582f3390c28"},
{file = "click-8.1.7.tar.gz", hash = "sha256:ca9853ad459e787e2192211578cc907e7594e294c7ccc834310722b41b9ca6de"},
@ -285,6 +306,7 @@ version = "0.3.1"
description = "Enables git-like *did-you-mean* feature in click"
optional = false
python-versions = ">=3.6.2"
groups = ["main"]
files = [
{file = "click_didyoumean-0.3.1-py3-none-any.whl", hash = "sha256:5c4bb6007cfea5f2fd6583a2fb6701a22a41eb98957e63d0fac41c10e7c3117c"},
{file = "click_didyoumean-0.3.1.tar.gz", hash = "sha256:4f82fdff0dbe64ef8ab2279bd6aa3f6a99c3b28c05aa09cbfc07c9d7fbb5a463"},
@ -299,6 +321,7 @@ version = "1.1.1"
description = "An extension module for click to enable registering CLI commands via setuptools entry-points."
optional = false
python-versions = "*"
groups = ["main"]
files = [
{file = "click-plugins-1.1.1.tar.gz", hash = "sha256:46ab999744a9d831159c3411bb0c79346d94a444df9a3a3742e9ed63645f264b"},
{file = "click_plugins-1.1.1-py2.py3-none-any.whl", hash = "sha256:5d262006d3222f5057fd81e1623d4443e41dcda5dc815c06b442aa3c02889fc8"},
@ -316,6 +339,7 @@ version = "0.3.0"
description = "REPL plugin for Click"
optional = false
python-versions = ">=3.6"
groups = ["main"]
files = [
{file = "click-repl-0.3.0.tar.gz", hash = "sha256:17849c23dba3d667247dc4defe1757fff98694e90fe37474f3feebb69ced26a9"},
{file = "click_repl-0.3.0-py3-none-any.whl", hash = "sha256:fb7e06deb8da8de86180a33a9da97ac316751c094c6899382da7feeeeb51b812"},
@ -334,17 +358,32 @@ version = "0.4.6"
description = "Cross-platform colored terminal text."
optional = false
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
groups = ["main", "dev"]
markers = "platform_system == \"Windows\""
files = [
{file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
{file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
[[package]]
name = "distlib"
version = "0.3.8"
description = "Distribution utilities"
optional = false
python-versions = "*"
groups = ["dev"]
files = [
{file = "distlib-0.3.8-py2.py3-none-any.whl", hash = "sha256:034db59a0b96f8ca18035f36290806a9a6e6bd9d1ff91e45a7f172eb17e51784"},
{file = "distlib-0.3.8.tar.gz", hash = "sha256:1530ea13e350031b6312d8580ddb6b27a104275a31106523b8f123787f494f64"},
]
[[package]]
name = "django"
version = "3.2.25"
description = "A high-level Python Web framework that encourages rapid development and clean, pragmatic design."
optional = false
python-versions = ">=3.6"
groups = ["main"]
files = [
{file = "Django-3.2.25-py3-none-any.whl", hash = "sha256:a52ea7fcf280b16f7b739cec38fa6d3f8953a5456986944c3ca97e79882b4e38"},
{file = "Django-3.2.25.tar.gz", hash = "sha256:7ca38a78654aee72378594d63e51636c04b8e28574f5505dff630895b5472777"},
@ -359,12 +398,45 @@ sqlparse = ">=0.2.2"
argon2 = ["argon2-cffi (>=19.1.0)"]
bcrypt = ["bcrypt"]
[[package]]
name = "django-upgrade"
version = "1.24.0"
description = "Automatically upgrade your Django project code."
optional = false
python-versions = ">=3.9"
groups = ["dev"]
files = [
{file = "django_upgrade-1.24.0-py3-none-any.whl", hash = "sha256:198572f31130cd80b4f30c568aa331351176cccf1455741e45ebca272812271d"},
{file = "django_upgrade-1.24.0.tar.gz", hash = "sha256:d761d517f87338291ac73890e15b09775532c5cea8cf794f56ad159da9d63d9b"},
]
[package.dependencies]
tokenize-rt = ">=4.1"
[[package]]
name = "filelock"
version = "3.15.4"
description = "A platform independent file lock."
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "filelock-3.15.4-py3-none-any.whl", hash = "sha256:6ca1fffae96225dab4c6eaf1c4f4f28cd2568d3ec2a44e15a08520504de468e7"},
{file = "filelock-3.15.4.tar.gz", hash = "sha256:2207938cbc1844345cb01a5a95524dae30f0ce089eba5b00378295a17e3e90cb"},
]
[package.extras]
docs = ["furo (>=2023.9.10)", "sphinx (>=7.2.6)", "sphinx-autodoc-typehints (>=1.25.2)"]
testing = ["covdefaults (>=2.3)", "coverage (>=7.3.2)", "diff-cover (>=8.0.1)", "pytest (>=7.4.3)", "pytest-asyncio (>=0.21)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)", "pytest-timeout (>=2.2)", "virtualenv (>=20.26.2)"]
typing = ["typing-extensions (>=4.8) ; python_version < \"3.11\""]
[[package]]
name = "flower"
version = "2.0.1"
description = "Celery Flower"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "flower-2.0.1-py2.py3-none-any.whl", hash = "sha256:9db2c621eeefbc844c8dd88be64aef61e84e2deb29b271e02ab2b5b9f01068e2"},
{file = "flower-2.0.1.tar.gz", hash = "sha256:5ab717b979530770c16afb48b50d2a98d23c3e9fe39851dcf6bc4d01845a02a0"},
@ -383,6 +455,7 @@ version = "22.0.0"
description = "WSGI HTTP Server for UNIX"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "gunicorn-22.0.0-py3-none-any.whl", hash = "sha256:350679f91b24062c86e386e198a15438d53a7a8207235a78ba1b53df4c4378d9"},
{file = "gunicorn-22.0.0.tar.gz", hash = "sha256:4a0b436239ff76fb33f11c07a16482c521a7e09c1ce3cc293c2330afe01bec63"},
@ -404,6 +477,7 @@ version = "4.10.0"
description = "Python humanize utilities"
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "humanize-4.10.0-py3-none-any.whl", hash = "sha256:39e7ccb96923e732b5c2e27aeaa3b10a8dfeeba3eb965ba7b74a3eb0e30040a6"},
{file = "humanize-4.10.0.tar.gz", hash = "sha256:06b6eb0293e4b85e8d385397c5868926820db32b9b654b932f57fa41c23c9978"},
@ -412,12 +486,28 @@ files = [
[package.extras]
tests = ["freezegun", "pytest", "pytest-cov"]
[[package]]
name = "identify"
version = "2.6.0"
description = "File identification library for Python"
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "identify-2.6.0-py2.py3-none-any.whl", hash = "sha256:e79ae4406387a9d300332b5fd366d8994f1525e8414984e1a59e058b2eda2dd0"},
{file = "identify-2.6.0.tar.gz", hash = "sha256:cb171c685bdc31bcc4c1734698736a7d5b6c8bf2e0c15117f4d469c8640ae5cf"},
]
[package.extras]
license = ["ukkonen"]
[[package]]
name = "idna"
version = "3.7"
description = "Internationalized Domain Names in Applications (IDNA)"
optional = false
python-versions = ">=3.5"
groups = ["main"]
files = [
{file = "idna-3.7-py3-none-any.whl", hash = "sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0"},
{file = "idna-3.7.tar.gz", hash = "sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc"},
@ -425,53 +515,132 @@ files = [
[[package]]
name = "kombu"
version = "5.3.7"
version = "5.4.0"
description = "Messaging library for Python."
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "kombu-5.3.7-py3-none-any.whl", hash = "sha256:5634c511926309c7f9789f1433e9ed402616b56836ef9878f01bd59267b4c7a9"},
{file = "kombu-5.3.7.tar.gz", hash = "sha256:011c4cd9a355c14a1de8d35d257314a1d2456d52b7140388561acac3cf1a97bf"},
{file = "kombu-5.4.0-py3-none-any.whl", hash = "sha256:c8dd99820467610b4febbc7a9e8a0d3d7da2d35116b67184418b51cc520ea6b6"},
{file = "kombu-5.4.0.tar.gz", hash = "sha256:ad200a8dbdaaa2bbc5f26d2ee7d707d9a1fded353a0f4bd751ce8c7d9f449c60"},
]
[package.dependencies]
amqp = ">=5.1.1,<6.0.0"
vine = "*"
vine = "5.1.0"
[package.extras]
azureservicebus = ["azure-servicebus (>=7.10.0)"]
azurestoragequeues = ["azure-identity (>=1.12.0)", "azure-storage-queue (>=12.6.0)"]
confluentkafka = ["confluent-kafka (>=2.2.0)"]
consul = ["python-consul2"]
librabbitmq = ["librabbitmq (>=2.0.0)"]
consul = ["python-consul2 (==0.1.5)"]
librabbitmq = ["librabbitmq (>=2.0.0) ; python_version < \"3.11\""]
mongodb = ["pymongo (>=4.1.1)"]
msgpack = ["msgpack"]
pyro = ["pyro4"]
msgpack = ["msgpack (==1.0.8)"]
pyro = ["pyro4 (==4.82)"]
qpid = ["qpid-python (>=0.26)", "qpid-tools (>=0.26)"]
redis = ["redis (>=4.5.2,!=4.5.5,!=5.0.2)"]
slmq = ["softlayer-messaging (>=1.0.3)"]
sqlalchemy = ["sqlalchemy (>=1.4.48,<2.1)"]
sqs = ["boto3 (>=1.26.143)", "pycurl (>=7.43.0.5)", "urllib3 (>=1.26.16)"]
sqs = ["boto3 (>=1.26.143)", "pycurl (>=7.43.0.5) ; sys_platform != \"win32\" and platform_python_implementation == \"CPython\"", "urllib3 (>=1.26.16)"]
yaml = ["PyYAML (>=3.10)"]
zookeeper = ["kazoo (>=2.8.0)"]
[[package]]
name = "markdown"
version = "3.7"
description = "Python implementation of John Gruber's Markdown."
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "Markdown-3.7-py3-none-any.whl", hash = "sha256:7eb6df5690b81a1d7942992c97fad2938e956e79df20cbc6186e9c3a77b1c803"},
{file = "markdown-3.7.tar.gz", hash = "sha256:2ae2471477cfd02dbbf038d5d9bc226d40def84b4fe2986e49b59b6b472bbed2"},
]
[package.extras]
docs = ["mdx-gh-links (>=0.2)", "mkdocs (>=1.5)", "mkdocs-gen-files", "mkdocs-literate-nav", "mkdocs-nature (>=0.6)", "mkdocs-section-index", "mkdocstrings[python]"]
testing = ["coverage", "pyyaml"]
[[package]]
name = "mypy"
version = "1.11.1"
description = "Optional static typing for Python"
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "mypy-1.11.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:a32fc80b63de4b5b3e65f4be82b4cfa362a46702672aa6a0f443b4689af7008c"},
{file = "mypy-1.11.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c1952f5ea8a5a959b05ed5f16452fddadbaae48b5d39235ab4c3fc444d5fd411"},
{file = "mypy-1.11.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e1e30dc3bfa4e157e53c1d17a0dad20f89dc433393e7702b813c10e200843b03"},
{file = "mypy-1.11.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:2c63350af88f43a66d3dfeeeb8d77af34a4f07d760b9eb3a8697f0386c7590b4"},
{file = "mypy-1.11.1-cp310-cp310-win_amd64.whl", hash = "sha256:a831671bad47186603872a3abc19634f3011d7f83b083762c942442d51c58d58"},
{file = "mypy-1.11.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:7b6343d338390bb946d449677726edf60102a1c96079b4f002dedff375953fc5"},
{file = "mypy-1.11.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e4fe9f4e5e521b458d8feb52547f4bade7ef8c93238dfb5bbc790d9ff2d770ca"},
{file = "mypy-1.11.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:886c9dbecc87b9516eff294541bf7f3655722bf22bb898ee06985cd7269898de"},
{file = "mypy-1.11.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fca4a60e1dd9fd0193ae0067eaeeb962f2d79e0d9f0f66223a0682f26ffcc809"},
{file = "mypy-1.11.1-cp311-cp311-win_amd64.whl", hash = "sha256:0bd53faf56de9643336aeea1c925012837432b5faf1701ccca7fde70166ccf72"},
{file = "mypy-1.11.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:f39918a50f74dc5969807dcfaecafa804fa7f90c9d60506835036cc1bc891dc8"},
{file = "mypy-1.11.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0bc71d1fb27a428139dd78621953effe0d208aed9857cb08d002280b0422003a"},
{file = "mypy-1.11.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b868d3bcff720dd7217c383474008ddabaf048fad8d78ed948bb4b624870a417"},
{file = "mypy-1.11.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:a707ec1527ffcdd1c784d0924bf5cb15cd7f22683b919668a04d2b9c34549d2e"},
{file = "mypy-1.11.1-cp312-cp312-win_amd64.whl", hash = "sha256:64f4a90e3ea07f590c5bcf9029035cf0efeae5ba8be511a8caada1a4893f5525"},
{file = "mypy-1.11.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:749fd3213916f1751fff995fccf20c6195cae941dc968f3aaadf9bb4e430e5a2"},
{file = "mypy-1.11.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:b639dce63a0b19085213ec5fdd8cffd1d81988f47a2dec7100e93564f3e8fb3b"},
{file = "mypy-1.11.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4c956b49c5d865394d62941b109728c5c596a415e9c5b2be663dd26a1ff07bc0"},
{file = "mypy-1.11.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:45df906e8b6804ef4b666af29a87ad9f5921aad091c79cc38e12198e220beabd"},
{file = "mypy-1.11.1-cp38-cp38-win_amd64.whl", hash = "sha256:d44be7551689d9d47b7abc27c71257adfdb53f03880841a5db15ddb22dc63edb"},
{file = "mypy-1.11.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2684d3f693073ab89d76da8e3921883019ea8a3ec20fa5d8ecca6a2db4c54bbe"},
{file = "mypy-1.11.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:79c07eb282cb457473add5052b63925e5cc97dfab9812ee65a7c7ab5e3cb551c"},
{file = "mypy-1.11.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:11965c2f571ded6239977b14deebd3f4c3abd9a92398712d6da3a772974fad69"},
{file = "mypy-1.11.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a2b43895a0f8154df6519706d9bca8280cda52d3d9d1514b2d9c3e26792a0b74"},
{file = "mypy-1.11.1-cp39-cp39-win_amd64.whl", hash = "sha256:1a81cf05975fd61aec5ae16501a091cfb9f605dc3e3c878c0da32f250b74760b"},
{file = "mypy-1.11.1-py3-none-any.whl", hash = "sha256:0624bdb940255d2dd24e829d99a13cfeb72e4e9031f9492148f410ed30bcab54"},
{file = "mypy-1.11.1.tar.gz", hash = "sha256:f404a0b069709f18bbdb702eb3dcfe51910602995de00bd39cea3050b5772d08"},
]
[package.dependencies]
mypy-extensions = ">=1.0.0"
tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""}
typing-extensions = ">=4.6.0"
[package.extras]
dmypy = ["psutil (>=4.0)"]
install-types = ["pip"]
mypyc = ["setuptools (>=50)"]
reports = ["lxml"]
[[package]]
name = "mypy-extensions"
version = "1.0.0"
description = "Type system extensions for programs checked with the mypy type checker."
optional = false
python-versions = ">=3.5"
groups = ["dev"]
files = [
{file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"},
{file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"},
]
[[package]]
name = "nodeenv"
version = "1.9.1"
description = "Node.js virtual environment builder"
optional = false
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
groups = ["dev"]
files = [
{file = "nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9"},
{file = "nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f"},
]
[[package]]
name = "packaging"
version = "24.1"
description = "Core utilities for Python packages"
optional = false
python-versions = ">=3.8"
groups = ["main", "dev"]
files = [
{file = "packaging-24.1-py3-none-any.whl", hash = "sha256:5b8f2217dbdbd2f7f384c41c628544e6d52f2d0f53c6d0c3ea61aa5d1d7ff124"},
{file = "packaging-24.1.tar.gz", hash = "sha256:026ed72c8ed3fcce5bf8950572258698927fd1dbda10a5e981cdf0ac37f4f002"},
@ -483,6 +652,7 @@ version = "0.12.1"
description = "Utility library for gitignore style pattern matching of file paths."
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08"},
{file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"},
@ -494,6 +664,7 @@ version = "4.2.2"
description = "A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`."
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "platformdirs-4.2.2-py3-none-any.whl", hash = "sha256:2d7a1657e36a80ea911db832a8a6ece5ee53d8de21edd5cc5879af6530b1bfee"},
{file = "platformdirs-4.2.2.tar.gz", hash = "sha256:38b7b51f512eed9e84a22788b4bce1de17c0adb134d6becb09836e37d8654cd3"},
@ -504,12 +675,32 @@ docs = ["furo (>=2023.9.10)", "proselint (>=0.13)", "sphinx (>=7.2.6)", "sphinx-
test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=7.4.3)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)"]
type = ["mypy (>=1.8)"]
[[package]]
name = "pre-commit"
version = "3.8.0"
description = "A framework for managing and maintaining multi-language pre-commit hooks."
optional = false
python-versions = ">=3.9"
groups = ["dev"]
files = [
{file = "pre_commit-3.8.0-py2.py3-none-any.whl", hash = "sha256:9a90a53bf82fdd8778d58085faf8d83df56e40dfe18f45b19446e26bf1b3a63f"},
{file = "pre_commit-3.8.0.tar.gz", hash = "sha256:8bb6494d4a20423842e198980c9ecf9f96607a07ea29549e180eef9ae80fe7af"},
]
[package.dependencies]
cfgv = ">=2.0.0"
identify = ">=1.0.0"
nodeenv = ">=0.11.1"
pyyaml = ">=5.1"
virtualenv = ">=20.10.0"
[[package]]
name = "prometheus-client"
version = "0.20.0"
description = "Python client for the Prometheus monitoring system."
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "prometheus_client-0.20.0-py3-none-any.whl", hash = "sha256:cde524a85bce83ca359cc837f28b8c0db5cac7aa653a588fd7e84ba061c329e7"},
{file = "prometheus_client-0.20.0.tar.gz", hash = "sha256:287629d00b147a32dcb2be0b9df905da599b2d82f80377083ec8463309a4bb89"},
@ -524,6 +715,7 @@ version = "3.0.47"
description = "Library for building powerful interactive command lines in Python"
optional = false
python-versions = ">=3.7.0"
groups = ["main"]
files = [
{file = "prompt_toolkit-3.0.47-py3-none-any.whl", hash = "sha256:0d7bfa67001d5e39d02c224b663abc33687405033a8c422d0d675a5a13361d10"},
{file = "prompt_toolkit-3.0.47.tar.gz", hash = "sha256:1e1b29cb58080b1e69f207c893a1a7bf16d127a5c30c9d17a25a5d77792e5360"},
@ -538,6 +730,7 @@ version = "2.9.9"
description = "psycopg2 - Python-PostgreSQL Database Adapter"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "psycopg2-binary-2.9.9.tar.gz", hash = "sha256:7f01846810177d829c7692f1f5ada8096762d9172af1b1a28d4ab5b77c923c1c"},
{file = "psycopg2_binary-2.9.9-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c2470da5418b76232f02a2fcd2229537bb2d5a7096674ce61859c3229f2eb202"},
@ -619,6 +812,7 @@ version = "2.9.0.post0"
description = "Extensions to the standard Python datetime module"
optional = false
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7"
groups = ["main"]
files = [
{file = "python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3"},
{file = "python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427"},
@ -633,6 +827,7 @@ version = "1.0.1"
description = "Read key-value pairs from a .env file and set them as environment variables"
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "python-dotenv-1.0.1.tar.gz", hash = "sha256:e324ee90a023d808f1959c46bcbc04446a10ced277783dc6ee09987c37ec10ca"},
{file = "python_dotenv-1.0.1-py3-none-any.whl", hash = "sha256:f7b63ef50f1b690dddf550d03497b66d609393b40b564ed0d674909a68ebf16a"},
@ -647,17 +842,82 @@ version = "2024.1"
description = "World timezone definitions, modern and historical"
optional = false
python-versions = "*"
groups = ["main"]
files = [
{file = "pytz-2024.1-py2.py3-none-any.whl", hash = "sha256:328171f4e3623139da4983451950b28e95ac706e13f3f2630a879749e7a8b319"},
{file = "pytz-2024.1.tar.gz", hash = "sha256:2a29735ea9c18baf14b448846bde5a48030ed267578472d8955cd0e7443a9812"},
]
[[package]]
name = "pyyaml"
version = "6.0.2"
description = "YAML parser and emitter for Python"
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "PyYAML-6.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0a9a2848a5b7feac301353437eb7d5957887edbf81d56e903999a75a3d743086"},
{file = "PyYAML-6.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:29717114e51c84ddfba879543fb232a6ed60086602313ca38cce623c1d62cfbf"},
{file = "PyYAML-6.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8824b5a04a04a047e72eea5cec3bc266db09e35de6bdfe34c9436ac5ee27d237"},
{file = "PyYAML-6.0.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7c36280e6fb8385e520936c3cb3b8042851904eba0e58d277dca80a5cfed590b"},
{file = "PyYAML-6.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ec031d5d2feb36d1d1a24380e4db6d43695f3748343d99434e6f5f9156aaa2ed"},
{file = "PyYAML-6.0.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:936d68689298c36b53b29f23c6dbb74de12b4ac12ca6cfe0e047bedceea56180"},
{file = "PyYAML-6.0.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:23502f431948090f597378482b4812b0caae32c22213aecf3b55325e049a6c68"},
{file = "PyYAML-6.0.2-cp310-cp310-win32.whl", hash = "sha256:2e99c6826ffa974fe6e27cdb5ed0021786b03fc98e5ee3c5bfe1fd5015f42b99"},
{file = "PyYAML-6.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:a4d3091415f010369ae4ed1fc6b79def9416358877534caf6a0fdd2146c87a3e"},
{file = "PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774"},
{file = "PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee"},
{file = "PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c"},
{file = "PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317"},
{file = "PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85"},
{file = "PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4"},
{file = "PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e"},
{file = "PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5"},
{file = "PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44"},
{file = "PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab"},
{file = "PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725"},
{file = "PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5"},
{file = "PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425"},
{file = "PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476"},
{file = "PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48"},
{file = "PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b"},
{file = "PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4"},
{file = "PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8"},
{file = "PyYAML-6.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba"},
{file = "PyYAML-6.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1"},
{file = "PyYAML-6.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133"},
{file = "PyYAML-6.0.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484"},
{file = "PyYAML-6.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5"},
{file = "PyYAML-6.0.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc"},
{file = "PyYAML-6.0.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652"},
{file = "PyYAML-6.0.2-cp313-cp313-win32.whl", hash = "sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183"},
{file = "PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563"},
{file = "PyYAML-6.0.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:24471b829b3bf607e04e88d79542a9d48bb037c2267d7927a874e6c205ca7e9a"},
{file = "PyYAML-6.0.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7fded462629cfa4b685c5416b949ebad6cec74af5e2d42905d41e257e0869f5"},
{file = "PyYAML-6.0.2-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d84a1718ee396f54f3a086ea0a66d8e552b2ab2017ef8b420e92edbc841c352d"},
{file = "PyYAML-6.0.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9056c1ecd25795207ad294bcf39f2db3d845767be0ea6e6a34d856f006006083"},
{file = "PyYAML-6.0.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:82d09873e40955485746739bcb8b4586983670466c23382c19cffecbf1fd8706"},
{file = "PyYAML-6.0.2-cp38-cp38-win32.whl", hash = "sha256:43fa96a3ca0d6b1812e01ced1044a003533c47f6ee8aca31724f78e93ccc089a"},
{file = "PyYAML-6.0.2-cp38-cp38-win_amd64.whl", hash = "sha256:01179a4a8559ab5de078078f37e5c1a30d76bb88519906844fd7bdea1b7729ff"},
{file = "PyYAML-6.0.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:688ba32a1cffef67fd2e9398a2efebaea461578b0923624778664cc1c914db5d"},
{file = "PyYAML-6.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a8786accb172bd8afb8be14490a16625cbc387036876ab6ba70912730faf8e1f"},
{file = "PyYAML-6.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d8e03406cac8513435335dbab54c0d385e4a49e4945d2909a581c83647ca0290"},
{file = "PyYAML-6.0.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f753120cb8181e736c57ef7636e83f31b9c0d1722c516f7e86cf15b7aa57ff12"},
{file = "PyYAML-6.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3b1fdb9dc17f5a7677423d508ab4f243a726dea51fa5e70992e59a7411c89d19"},
{file = "PyYAML-6.0.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0b69e4ce7a131fe56b7e4d770c67429700908fc0752af059838b1cfb41960e4e"},
{file = "PyYAML-6.0.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a9f8c2e67970f13b16084e04f134610fd1d374bf477b17ec1599185cf611d725"},
{file = "PyYAML-6.0.2-cp39-cp39-win32.whl", hash = "sha256:6395c297d42274772abc367baaa79683958044e5d3835486c16da75d2a694631"},
{file = "PyYAML-6.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:39693e1f8320ae4f43943590b49779ffb98acb81f788220ea932a6b6c51004d8"},
{file = "pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e"},
]
[[package]]
name = "redis"
version = "5.0.8"
description = "Python client for Redis database and key-value store"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "redis-5.0.8-py3-none-any.whl", hash = "sha256:56134ee08ea909106090934adc36f65c9bcbbaecea5b21ba704ba6fb561f8eb4"},
{file = "redis-5.0.8.tar.gz", hash = "sha256:0c5b10d387568dfe0698c6fad6615750c24170e548ca2deac10c649d463e9870"},
@ -676,6 +936,7 @@ version = "2.32.3"
description = "Python HTTP for Humans."
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "requests-2.32.3-py3-none-any.whl", hash = "sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6"},
{file = "requests-2.32.3.tar.gz", hash = "sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760"},
@ -697,6 +958,7 @@ version = "1.16.0"
description = "Python 2 and 3 compatibility utilities"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*"
groups = ["main"]
files = [
{file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"},
{file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"},
@ -708,6 +970,7 @@ version = "0.5.1"
description = "A non-validating SQL parser."
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "sqlparse-0.5.1-py3-none-any.whl", hash = "sha256:773dcbf9a5ab44a090f3441e2180efe2560220203dc2f8c0b0fa141e18b505e4"},
{file = "sqlparse-0.5.1.tar.gz", hash = "sha256:bb6b4df465655ef332548e24f08e205afc81b9ab86cb1c45657a7ff173a3a00e"},
@ -717,12 +980,25 @@ files = [
dev = ["build", "hatch"]
doc = ["sphinx"]
[[package]]
name = "tokenize-rt"
version = "6.1.0"
description = "A wrapper around the stdlib `tokenize` which roundtrips."
optional = false
python-versions = ">=3.9"
groups = ["dev"]
files = [
{file = "tokenize_rt-6.1.0-py2.py3-none-any.whl", hash = "sha256:d706141cdec4aa5f358945abe36b911b8cbdc844545da99e811250c0cee9b6fc"},
{file = "tokenize_rt-6.1.0.tar.gz", hash = "sha256:e8ee836616c0877ab7c7b54776d2fefcc3bde714449a206762425ae114b53c86"},
]
[[package]]
name = "tomli"
version = "2.0.1"
description = "A lil' TOML parser"
optional = false
python-versions = ">=3.7"
groups = ["dev"]
files = [
{file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"},
{file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"},
@ -734,6 +1010,7 @@ version = "6.4.1"
description = "Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed."
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "tornado-6.4.1-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:163b0aafc8e23d8cdc3c9dfb24c5368af84a81e3364745ccb4427669bf84aec8"},
{file = "tornado-6.4.1-cp38-abi3-macosx_10_9_x86_64.whl", hash = "sha256:6d5ce3437e18a2b66fbadb183c1d3364fb03f2be71299e7d10dbeeb69f4b2a14"},
@ -748,12 +1025,28 @@ files = [
{file = "tornado-6.4.1.tar.gz", hash = "sha256:92d3ab53183d8c50f8204a51e6f91d18a15d5ef261e84d452800d4ff6fc504e9"},
]
[[package]]
name = "types-requests"
version = "2.32.0.20240712"
description = "Typing stubs for requests"
optional = false
python-versions = ">=3.8"
groups = ["dev"]
files = [
{file = "types-requests-2.32.0.20240712.tar.gz", hash = "sha256:90c079ff05e549f6bf50e02e910210b98b8ff1ebdd18e19c873cd237737c1358"},
{file = "types_requests-2.32.0.20240712-py3-none-any.whl", hash = "sha256:f754283e152c752e46e70942fa2a146b5bc70393522257bb85bd1ef7e019dcc3"},
]
[package.dependencies]
urllib3 = ">=2"
[[package]]
name = "typing-extensions"
version = "4.12.2"
description = "Backported and Experimental Type Hints for Python 3.8+"
optional = false
python-versions = ">=3.8"
groups = ["main", "dev"]
files = [
{file = "typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d"},
{file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"},
@ -765,6 +1058,7 @@ version = "2024.1"
description = "Provider of IANA time zone data"
optional = false
python-versions = ">=2"
groups = ["main"]
files = [
{file = "tzdata-2024.1-py2.py3-none-any.whl", hash = "sha256:9068bc196136463f5245e51efda838afa15aaeca9903f49050dfa2679db4d252"},
{file = "tzdata-2024.1.tar.gz", hash = "sha256:2674120f8d891909751c38abcdfd386ac0a5a1127954fbc332af6b5ceae07efd"},
@ -776,40 +1070,84 @@ version = "2.2.2"
description = "HTTP library with thread-safe connection pooling, file post, and more."
optional = false
python-versions = ">=3.8"
groups = ["main", "dev"]
files = [
{file = "urllib3-2.2.2-py3-none-any.whl", hash = "sha256:a448b2f64d686155468037e1ace9f2d2199776e17f0a46610480d311f73e3472"},
{file = "urllib3-2.2.2.tar.gz", hash = "sha256:dd505485549a7a552833da5e6063639d0d177c04f23bc3864e41e5dc5f612168"},
]
[package.extras]
brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)"]
brotli = ["brotli (>=1.0.9) ; platform_python_implementation == \"CPython\"", "brotlicffi (>=0.8.0) ; platform_python_implementation != \"CPython\""]
h2 = ["h2 (>=4,<5)"]
socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"]
zstd = ["zstandard (>=0.18.0)"]
[[package]]
name = "versioning"
version = "0.1.0"
description = ""
optional = false
python-versions = "^3.10"
groups = ["main"]
files = []
develop = false
[package.dependencies]
django = "^3.2"
markdown = "^3.7"
[package.source]
type = "git"
url = "https://git.cybercode.pro/zakhy/versioning.git"
reference = "HEAD"
resolved_reference = "5acc472975b5c3adccd3bebf30cd408ab4461c38"
[[package]]
name = "vine"
version = "5.1.0"
description = "Python promises."
optional = false
python-versions = ">=3.6"
groups = ["main"]
files = [
{file = "vine-5.1.0-py3-none-any.whl", hash = "sha256:40fdf3c48b2cfe1c38a49e9ae2da6fda88e4794c810050a728bd7413811fb1dc"},
{file = "vine-5.1.0.tar.gz", hash = "sha256:8b62e981d35c41049211cf62a0a1242d8c1ee9bd15bb196ce38aefd6799e61e0"},
]
[[package]]
name = "virtualenv"
version = "20.26.3"
description = "Virtual Python Environment builder"
optional = false
python-versions = ">=3.7"
groups = ["dev"]
files = [
{file = "virtualenv-20.26.3-py3-none-any.whl", hash = "sha256:8cc4a31139e796e9a7de2cd5cf2489de1217193116a8fd42328f1bd65f434589"},
{file = "virtualenv-20.26.3.tar.gz", hash = "sha256:4c43a2a236279d9ea36a0d76f98d84bd6ca94ac4e0f4a3b9d46d05e10fea542a"},
]
[package.dependencies]
distlib = ">=0.3.7,<1"
filelock = ">=3.12.2,<4"
platformdirs = ">=3.9.1,<5"
[package.extras]
docs = ["furo (>=2023.7.26)", "proselint (>=0.13)", "sphinx (>=7.1.2,!=7.3)", "sphinx-argparse (>=0.4)", "sphinxcontrib-towncrier (>=0.2.1a0)", "towncrier (>=23.6)"]
test = ["covdefaults (>=2.3)", "coverage (>=7.2.7)", "coverage-enable-subprocess (>=1)", "flaky (>=3.7)", "packaging (>=23.1)", "pytest (>=7.4)", "pytest-env (>=0.8.2)", "pytest-freezer (>=0.4.8) ; platform_python_implementation == \"PyPy\" or platform_python_implementation == \"CPython\" and sys_platform == \"win32\" and python_version >= \"3.13\"", "pytest-mock (>=3.11.1)", "pytest-randomly (>=3.12)", "pytest-timeout (>=2.1)", "setuptools (>=68)", "time-machine (>=2.10) ; platform_python_implementation == \"CPython\""]
[[package]]
name = "wcwidth"
version = "0.2.13"
description = "Measures the displayed width of unicode strings in a terminal"
optional = false
python-versions = "*"
groups = ["main"]
files = [
{file = "wcwidth-0.2.13-py2.py3-none-any.whl", hash = "sha256:3da69048e4540d84af32131829ff948f1e022c1c6bdb8d6102117aac784f6859"},
{file = "wcwidth-0.2.13.tar.gz", hash = "sha256:72ea0c06399eb286d978fdedb6923a9eb47e1c486ce63e9b4e64fc18303972b5"},
]
[metadata]
lock-version = "2.0"
lock-version = "2.1"
python-versions = "~3.10"
content-hash = "59976517fc9a0a2ef6544f3dc38ba8467fa1eabd0cf20a74fda8af682d1f5dab"
content-hash = "5fe1024dd0a02fce3a8ed5a9f60cc7d1c4413f73f19f615f1a6581f433eb0ec8"

View File

@ -16,10 +16,16 @@ psycopg2-binary = "^2.9.9"
redis = "^5.0.8"
requests = "^2.32.3"
python-dotenv = "^1.0.1"
versioning = {git = "https://git.cybercode.pro/zakhy/versioning.git"}
[tool.poetry.group.dev.dependencies]
black = "^24.8.0"
pre-commit = "^3.8.0"
types-requests = "^2.32.0.20240712"
mypy = "^1.11.1"
django-upgrade = "^1.24.0"
[build-system]
requires = ["poetry-core"]

View File

@ -1,25 +1,29 @@
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
INSTALLED_APPS = [
"users.apps.UsersConfig",
"sabron.apps.SabronConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"apps.main.apps.MainConfig", # Стартовая страница
"apps.montorem.apps.MontoremConfig", # Подсистема монторем
'users.apps.UsersConfig',
'sabron.apps.SabronConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'apps.main.apps.MainConfig', # Стартовая страница
'apps.montorem.apps.MontoremConfig', # Подсистема монторем
'apps.management.apps.ManagementConfig',
'apps.finance.apps.FinanceConfig',
'versioning',
]
"""Информация о приложении """
SITE_TITLE = "Система отчетов"
SITE_TITLE_S = "СиО"
APP_VERSION = "0.6.2"
APP_VEK = "2024 г"
APP_COPPIRIGHT = "Система отчетов"
SITE_TITLE = 'Система отчетов'
SITE_TITLE_S = 'СиО'
APP_VERSION = '1.0.11.0'
APP_VEK = '2024 г'
APP_COPPIRIGHT = 'Система отчетов'
KEYWORDS = ""
DESCRIPTION = "Система отчетов"
AUTHOR = "Киберкод"
KEYWORDS = ''
DESCRIPTION = 'Система отчетов'
AUTHOR = 'Киберкод'

View File

@ -1,38 +1,29 @@
import os
from celery import Celery
from celery.schedules import crontab
# Установить модуль с настройками. Должна идти до следующей строчки
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "repcofkk.settings")
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'repcofkk.settings')
app = Celery("repcofkk")
app = Celery('repcofkk')
# Позволит создавать настройки для celery в settings.py
app.config_from_object("django.conf:settings", namespace="CELERY")
app.config_from_object('django.conf:settings', namespace='CELERY')
# Сканирует все приложения и ищет файл tasks.py
app.autodiscover_tasks()
app.conf.beat_schedule = {
"worktime": {
"task": "apps.main.tasks.create_worktime_data",
"schedule": 30,
'worktime': {
'task': 'apps.main.tasks.create_worktime_data',
'schedule': 30,
},
"scales_control": {
"task": "apps.main.tasks.create_scales_control_data",
"schedule": 30,
},
"write_scale_control_data_to_redis": {
"task": "apps.main.tasks.write_scale_control_data_to_redis",
"schedule": 30,
},
"thin_out_scales": {
"task": "apps.main.tasks.thin_out_scales",
"schedule": crontab(minute=0, hour=0),
},
"thin_out_worktime": {
"task": "apps.main.tasks.thin_out_worktime",
"schedule": crontab(minute=0, hour=1),
# 'scales_control': {
# 'task': 'apps.main.tasks.create_scales_control_data',
# 'schedule': 30,
# },
'write_scale_control_data_to_redis': {
'task': 'apps.main.tasks.write_scale_control_data_to_redis',
'schedule': 30,
},
}

Some files were not shown because too many files have changed in this diff Show More