diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000..5970f82
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,48 @@
+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/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/project/settings.py"
+ args: [ "--ignore=E501,F821", "--max-line-length=120" ]
+
+ - repo: https://github.com/gitleaks/gitleaks
+ rev: v8.18.4
+ hooks:
+ - id: gitleaks
diff --git a/app/apps/main/admin.py b/app/apps/main/admin.py
index 637205d..7992d7c 100644
--- a/app/apps/main/admin.py
+++ b/app/apps/main/admin.py
@@ -1,41 +1,45 @@
-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.scales_control import Position, ScalesControl, ShiftReport
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"]
+ list_display = ['date_created', 'name', 'value']
+ list_filter = ['time', 'name']
ordering = [
- "-time",
+ '-time',
]
def date_created(self, obj):
- return obj.time.strftime("%x - %X")
+ 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(ShiftReport)
+class ShiftReportAdmin(admin.ModelAdmin):
+ pass
diff --git a/app/apps/main/migrations/0018_shiftreport.py b/app/apps/main/migrations/0018_shiftreport.py
new file mode 100644
index 0000000..b5005a6
--- /dev/null
+++ b/app/apps/main/migrations/0018_shiftreport.py
@@ -0,0 +1,27 @@
+# Generated by Django 3.2.25 on 2024-08-21 17:22
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('main', '0017_auto_20240814_1055'),
+ ]
+
+ operations = [
+ 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': 'Отчет за смены',
+ },
+ ),
+ ]
diff --git a/app/apps/main/migrations/0019_shiftreport_main_shiftr_time_4e29ee_idx.py b/app/apps/main/migrations/0019_shiftreport_main_shiftr_time_4e29ee_idx.py
new file mode 100644
index 0000000..a280273
--- /dev/null
+++ b/app/apps/main/migrations/0019_shiftreport_main_shiftr_time_4e29ee_idx.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.25 on 2024-08-21 17:23
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('main', '0018_shiftreport'),
+ ]
+
+ operations = [
+ migrations.AddIndex(
+ model_name='shiftreport',
+ index=models.Index(fields=['time'], name='main_shiftr_time_4e29ee_idx'),
+ ),
+ ]
diff --git a/app/apps/main/models/scales_control.py b/app/apps/main/models/scales_control.py
index b030276..f25119a 100644
--- a/app/apps/main/models/scales_control.py
+++ b/app/apps/main/models/scales_control.py
@@ -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.date,
}
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,25 @@ 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
+
+
+class ShiftReport(models.Model):
+ time = models.DateTimeField()
+ concentrate = models.FloatField()
+ dropout = models.FloatField()
+ scales_data = models.JSONField()
+
+ class Meta:
+ verbose_name = 'Отчет за смену'
+ verbose_name_plural = 'Отчет за смены'
+ indexes = [
+ models.Index(fields=['time'])
+ ]
+
+ def __str__(self):
+ return f'{self.time}'
diff --git a/app/apps/main/services/base_service.py b/app/apps/main/services/base_service.py
index 072de96..50bb820 100644
--- a/app/apps/main/services/base_service.py
+++ b/app/apps/main/services/base_service.py
@@ -1,7 +1,6 @@
-from datetime import timedelta, datetime
+from datetime import datetime
from dateutil.relativedelta import relativedelta
-from django.db.models import Model
from django.utils import timezone
@@ -11,14 +10,14 @@ 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():
@@ -31,6 +30,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)
diff --git a/app/apps/main/services/scales_control/redis_repository.py b/app/apps/main/services/scales_control/redis_repository.py
index f0f7ce0..10bae7f 100644
--- a/app/apps/main/services/scales_control/redis_repository.py
+++ b/app/apps/main/services/scales_control/redis_repository.py
@@ -1,71 +1,83 @@
-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.db.models import QuerySet
-from repcofkk.settings import REDIS_HOST, REDIS_PORT
+try:
+ from repcofkk.local_settings import REDIS_HOST, REDIS_PORT
+except ModuleNotFoundError:
+ from repcofkk.production_settings import REDIS_HOST, REDIS_PORT
class RedisRepository(DashboardBaseService):
def __init__(
- self,
- control_conveyor_month: str,
- fabric_goal: str,
- service: RedisService = RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1),
+ self,
+ control_conveyor_month: str,
+ fabric_goal: str,
+ service: RedisService = RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1),
):
self.fabric_goal = fabric_goal
self.control_conveyor_month = control_conveyor_month
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 +87,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 +110,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 +129,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 +161,29 @@ 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.PredSmena', 'Value')
+ pos13_value = redis_service.hget_value('SIEMENSPLC.AZG01.ReportProdDB.ProdPos13.PredSmena', 'Value')
+ pos22_value = redis_service.hget_value('SIEMENSPLC.AZG01.ReportProdDB.ProdPos22.PredSmena', '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 +203,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'}
diff --git a/app/apps/main/services/scales_control/views.py b/app/apps/main/services/scales_control/views.py
index 6a8c647..d328f6e 100644
--- a/app/apps/main/services/scales_control/views.py
+++ b/app/apps/main/services/scales_control/views.py
@@ -1,28 +1,54 @@
-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 django.http import JsonResponse
from sabron.util.sabronmodule import get_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())
diff --git a/app/apps/main/services/urls.py b/app/apps/main/services/urls.py
index 11362ce..36d9ead 100644
--- a/app/apps/main/services/urls.py
+++ b/app/apps/main/services/urls.py
@@ -1,23 +1,32 @@
-from django.urls import path
from apps.main.services.accident_stops.views import get_accident_stops
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 (
+ 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')
]
diff --git a/app/apps/main/services/workstatus/service.py b/app/apps/main/services/workstatus/service.py
index 27710c1..71eb037 100644
--- a/app/apps/main/services/workstatus/service.py
+++ b/app/apps/main/services/workstatus/service.py
@@ -2,6 +2,7 @@ from datetime import timedelta
from dateutil.relativedelta import relativedelta
+from apps.main.models.worktime import FabricWorkTime
from apps.main.services.base_service import DashboardBaseService
from sabron.util import logging
@@ -9,25 +10,6 @@ from sabron.util import logging
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}
+ last_status = FabricWorkTime.objects.latest('time')
+ duration = now_date - last_status.time
+ return {"last_status": last_status.status, "worktime": duration}
diff --git a/app/apps/main/services/worktime/create_worktime_data.py b/app/apps/main/services/worktime/create_worktime_data.py
new file mode 100644
index 0000000..6e0ba69
--- /dev/null
+++ b/app/apps/main/services/worktime/create_worktime_data.py
@@ -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
diff --git a/app/apps/main/services/worktime/service.py b/app/apps/main/services/worktime/service.py
index a2d11f2..3597b1b 100644
--- a/app/apps/main/services/worktime/service.py
+++ b/app/apps/main/services/worktime/service.py
@@ -1,25 +1,24 @@
-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
+from dateutil.relativedelta import relativedelta
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 +28,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 = {
@@ -44,8 +40,8 @@ class FabricWorkTimeService(DashboardBaseService):
@classmethod
def calculate_by_last_value(cls, last_value: FabricWorkTime, start, end) -> dict:
# TODO доделать
- delta = end - last_value.time
- res = start - delta
+ # delta = end - last_value.time
+ # res = start - delta
pass
def return_worktime(self, return_durations: bool = False):
@@ -54,49 +50,28 @@ class FabricWorkTimeService(DashboardBaseService):
start_month = now_date - relativedelta(hours=730)
start_week = now_date - relativedelta(hours=168)
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)
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)
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)
+
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
diff --git a/app/apps/main/services/worktime/views.py b/app/apps/main/services/worktime/views.py
index 70ae79c..97ebca2 100644
--- a/app/apps/main/services/worktime/views.py
+++ b/app/apps/main/services/worktime/views.py
@@ -1,10 +1,8 @@
-from django.http import JsonResponse
-
from apps.main.models.worktime import FabricWorkTime
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 JsonResponse
@base_view
@@ -17,3 +15,9 @@ 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):
+ res = create_worktime_data()
+ return JsonResponse({'success': bool(res)}, safe=False)
diff --git a/app/apps/main/tasks.py b/app/apps/main/tasks.py
index 4738b3a..e4dfa9b 100644
--- a/app/apps/main/tasks.py
+++ b/app/apps/main/tasks.py
@@ -1,118 +1,120 @@
-import decimal
+import json
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
+from apps.main.models.scales_control import Position, ShiftReport
from apps.main.models.worktime import FabricWorkTime
from apps.main.services.base_service import DashboardBaseService
+from apps.main.services.scales_control.redis_repository import RedisRepository
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.core.serializers.json import DjangoJSONEncoder
+from psycopg2 import OperationalError
from sabron.util import logging
from sabron.util.sabronmodule import get_settings
+try:
+ from repcofkk.local_settings import REDIS_HOST, REDIS_PORT
+except ModuleNotFoundError:
+ from repcofkk.production_settings import REDIS_HOST, REDIS_PORT
-@shared_task
-def create_worktime_data_redis():
- control_conveyor = get_settings("control_conveyor")
- now_date = DashboardBaseService.get_current_time()
+
+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:
- 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 с последней актуальной записью по управляющему конвейеру
+ 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')
+
+ return {'value': value, 'date': date}
@shared_task
-def create_worktime_data() -> int:
+def create_start_shift_worktime():
"""
- Создает объекты FabricWorkTime для анализа времени работы фабрики.
- Если с весов нет ответа - фабрика не работает - конвейер стоит (5 минут без ответа)
- Если с весов с Поз.4 меньше 20 - фабрика работает без нагрузки
+ Description:
+ Создает копию FabricWorkTime под время начала смены.
+ Вызывается в 8:00 и 20:00
+ Returns:
+
"""
- # TODO переписать под ситуации, создать модуль настроек для упр. конвейера
- # TODO переписать по аналогу SQL скрипта с весами
+ scales_data = get_scales_data_from_redis()
+ now_date = DashboardBaseService.get_current_time()
+ shift_start = DashboardBaseService.get_shift_start(now_date)
+ delta = (now_date - scales_data['date']).total_seconds() / 60
+
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")
+ latest_worktime_obj = FabricWorkTime.objects.latest('time')
+ except FabricWorkTime.DoesNotExist:
+ latest_worktime_obj = FabricWorkTime.objects.create(
+ time=scales_data['date'],
+ status='WO' if delta < 5 else 'NW'
)
- 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,
- )
- current_record = record
- return "Success"
- except Exception as e:
- logging.error(traceback.format_exc())
- return f"Exception: {e}"
+
+ created_record = FabricWorkTime.objects.create(time=shift_start, status=latest_worktime_obj.status)
+ return f'Success. Created start shift record {str(created_record)}'
-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():
+ """
+ Description:
+ Создает объекты времени работы фабрики. Получает данные с Redis по весам конвейера. Если разница текущего времени записи с
+ Redis больше чем 5 минут с текущим временем - фабрика не работает Запись будет создаваться только в случае если
+ статус изменился.
+ Вызывается каждые 30 секунд
+ Returns: строку со статусом задачи
+ """
+ now_date = DashboardBaseService.get_current_time()
-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))
+ obj_from_redis = get_scales_data_from_redis(get_settings('control_conveyor'))
+ delta_now_and_redis = (now_date - obj_from_redis['date']).total_seconds() / 60
-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
+ try:
+ latest_worktime_obj = FabricWorkTime.objects.latest('time')
+ except FabricWorkTime.DoesNotExist:
+ obj = FabricWorkTime.objects.create(status='WO' if delta_now_and_redis < 5 else 'NW',
+ time=obj_from_redis['date'])
+ return 'Success. Created first obj: ' + str(obj)
+
+ status = None
+
+ if latest_worktime_obj.status == 'NW' and delta_now_and_redis < 5:
+ status = 'WO'
+
+ elif latest_worktime_obj.status == 'WO' and delta_now_and_redis > 5:
+ 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 = get_scales_data(300)
+ res = 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
@@ -121,97 +123,22 @@ def write_scale_control_data_to_redis():
data = 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",
+ 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(
@@ -226,21 +153,22 @@ def get_scales_data(limit: int = 20000) -> list:
data = cursor.fetchall()
return data[::-1]
except OperationalError:
+ logging.error(traceback.format_exc())
return None
def write_scales_data(data: list):
if not data:
- return "No scales 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",
+ 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 при настройке ОПС на запись в БД - убрать первое условие
+ with postgres_conn.cursor() as cursor:
for row in data:
name, value, date, check = row
cursor.execute(
@@ -255,7 +183,7 @@ def write_scales_data(data: list):
FROM public.main_scalescontrol
WHERE "Name" = %s AND "Values" = %s
) INTO value_exists;
-
+
IF value_exists THEN
UPDATE public.main_scalescontrol
SET "Date" = %s
@@ -267,24 +195,37 @@ def write_scales_data(data: list):
END IF;
END $$;
""",
- (
- name,
- name,
- name,
- value,
- date,
- name,
- value,
- name,
- value,
- date,
- check,
- ),
+ (name, name, name, value, date, name, value, name, value, date, check,),
)
postgres_conn.commit()
- return "Success"
+ return 'Success'
except Exception:
- logging.error("CELERY: " + traceback.format_exc())
+ logging.error('CELERY: ' + traceback.format_exc())
return traceback.format_exc()
finally:
postgres_conn.close()
+
+
+@shared_task
+def create_shift_report():
+ 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')
+ average = service.get_scales_value_by_shifts(positions, 'Aver')
+ daily = service.get_scales_value_by_shifts(positions, 'Smena')
+ concentrate = service.get_concentrate_value()
+ if not concentrate:
+ concentrate = {'concentrate': 0,
+ 'dropout': 0}
+ scales_data = json.dumps({'daily': daily, 'average': average},
+ sort_keys=True,
+ indent=1,
+ cls=DjangoJSONEncoder
+ )
+ obj = ShiftReport.objects.create(time=DashboardBaseService.get_current_time(),
+ concentrate=concentrate['concentrate'],
+ dropout=concentrate['dropout'],
+ scales_data=scales_data)
+ service.delete_kek_and_breed_values()
+ return obj
diff --git a/app/apps/main/templates/aspiration.html b/app/apps/main/templates/aspiration.html
new file mode 100644
index 0000000..2400ce1
--- /dev/null
+++ b/app/apps/main/templates/aspiration.html
@@ -0,0 +1,133 @@
+{% extends 'default.html' %}
+{% load static %}
+{% block extra_head %}
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+ Аспирационная установка №1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Аспирационная установка №1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Аспирационная установка №1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Аспирационная установка №1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Аспирационная установка №1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+{% endblock %}
+
+{% block script_footer %}
+
+
+{% endblock %}
diff --git a/app/apps/main/templates/concentrate_and_dropout.html b/app/apps/main/templates/concentrate_and_dropout.html
new file mode 100644
index 0000000..6198f88
--- /dev/null
+++ b/app/apps/main/templates/concentrate_and_dropout.html
@@ -0,0 +1,91 @@
+{% extends 'default.html' %}
+{% load static %}
+
+{% block content %}
+
+
+
+
+
+
+
+ Выпуск кек и породы (нат. вес)
+
+
+
+
+
+
+
+ Выпуск кека (нат.вес):
+
+
+
+ Выпуск породы (нат.вес):
+
+
+
+
+
+
+
+{% endblock %}
+
+{% block script_footer %}
+
+{% endblock %}
diff --git a/app/apps/main/templates/main_index.html b/app/apps/main/templates/main_index.html
index 9af3ff6..baebd2a 100644
--- a/app/apps/main/templates/main_index.html
+++ b/app/apps/main/templates/main_index.html
@@ -23,15 +23,15 @@
- {% include 'fabric_worktime_widget.html' %}
+ {% include 'widgets/fabric_worktime_widget.html' %}
- {% include 'fabric_scales_control_widget.html' %}
+ {% include 'widgets/fabric_scales_control_widget.html' %}
{# {% include 'emergency_stops_widget.html' %}#}
- {% include 'density_in_heavy.html' %}
+ {% include 'widgets/density_in_heavy_widget.html' %}
diff --git a/app/apps/main/templates/density_in_heavy.html b/app/apps/main/templates/widgets/density_in_heavy_widget.html
similarity index 99%
rename from app/apps/main/templates/density_in_heavy.html
rename to app/apps/main/templates/widgets/density_in_heavy_widget.html
index 91d1cea..bfa1ac5 100644
--- a/app/apps/main/templates/density_in_heavy.html
+++ b/app/apps/main/templates/widgets/density_in_heavy_widget.html
@@ -24,4 +24,4 @@
-
\ No newline at end of file
+
diff --git a/app/apps/main/templates/emergency_stops_widget.html b/app/apps/main/templates/widgets/emergency_stops_widget.html
similarity index 100%
rename from app/apps/main/templates/emergency_stops_widget.html
rename to app/apps/main/templates/widgets/emergency_stops_widget.html
diff --git a/app/apps/main/templates/fabric_scales_control_widget.html b/app/apps/main/templates/widgets/fabric_scales_control_widget.html
similarity index 54%
rename from app/apps/main/templates/fabric_scales_control_widget.html
rename to app/apps/main/templates/widgets/fabric_scales_control_widget.html
index 34a8856..00e172f 100644
--- a/app/apps/main/templates/fabric_scales_control_widget.html
+++ b/app/apps/main/templates/widgets/fabric_scales_control_widget.html
@@ -2,7 +2,10 @@
-
\ No newline at end of file
+
+
+
diff --git a/app/apps/main/templates/fabric_worktime_widget.html b/app/apps/main/templates/widgets/fabric_worktime_widget.html
similarity index 99%
rename from app/apps/main/templates/fabric_worktime_widget.html
rename to app/apps/main/templates/widgets/fabric_worktime_widget.html
index 289212d..22b0c2f 100644
--- a/app/apps/main/templates/fabric_worktime_widget.html
+++ b/app/apps/main/templates/widgets/fabric_worktime_widget.html
@@ -169,4 +169,4 @@
-
\ No newline at end of file
+
diff --git a/app/apps/main/urls.py b/app/apps/main/urls.py
index 5c6f8a8..3653efa 100644
--- a/app/apps/main/urls.py
+++ b/app/apps/main/urls.py
@@ -1,10 +1,12 @@
-from django.urls import path, include
-
from apps.main import views_main
+from apps.main.views_main import aspiration, scales
+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='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('scale/', scales, name='concentrate_and_dropout'),
+ path('aspiration/', aspiration, name='aspiration')
]
diff --git a/app/apps/main/views_main.py b/app/apps/main/views_main.py
index 204dce0..7434c7c 100644
--- a/app/apps/main/views_main.py
+++ b/app/apps/main/views_main.py
@@ -1,60 +1,61 @@
-# -*- coding: utf-8 -*-
-import traceback
-import datetime
-import requests
import base64
+import traceback
-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.util import generalmodule
+from django.contrib.auth.decorators import login_required
+from django.shortcuts import 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=')
@never_cache
def mainindex(request):
try:
- if request.method == "GET":
+ if request.method == 'GET':
context = {
- "updatepage": True,
+ 'updatepage': True,
}
- return render(request, "main_index.html", context)
- except Exception as err:
+ 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=')
@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=')
+@never_cache
+def scales(request):
+ return render(request, 'concentrate_and_dropout.html')
+
+
+@login_required(login_url='/accounts/login/?next=')
+@never_cache
+def aspiration(request):
+ return render(request, 'aspiration.html')
diff --git a/app/apps/util/redis_api.py b/app/apps/util/redis_api.py
index 8da0c76..4dc7220 100644
--- a/app/apps/util/redis_api.py
+++ b/app/apps/util/redis_api.py
@@ -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,14 +91,14 @@ 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]
+ self, name: str, key: str, value: bytes | str | int | float
) -> bool:
"""
Устанавливает значение в хэш по ключу.
@@ -114,10 +112,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 +125,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 +142,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 +155,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
diff --git a/app/apps/util/redis_cache.py b/app/apps/util/redis_cache.py
new file mode 100644
index 0000000..c0beeba
--- /dev/null
+++ b/app/apps/util/redis_cache.py
@@ -0,0 +1,25 @@
+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
diff --git a/app/poetry.lock b/app/poetry.lock
index 76f64fa..f5505d8 100644
--- a/app/poetry.lock
+++ b/app/poetry.lock
@@ -166,6 +166,17 @@ files = [
{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"
+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"
@@ -339,6 +350,17 @@ files = [
{file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
+[[package]]
+name = "distlib"
+version = "0.3.8"
+description = "Distribution utilities"
+optional = false
+python-versions = "*"
+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"
@@ -359,6 +381,22 @@ sqlparse = ">=0.2.2"
argon2 = ["argon2-cffi (>=19.1.0)"]
bcrypt = ["bcrypt"]
+[[package]]
+name = "filelock"
+version = "3.15.4"
+description = "A platform independent file lock."
+optional = false
+python-versions = ">=3.8"
+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)"]
+
[[package]]
name = "flower"
version = "2.0.1"
@@ -412,6 +450,20 @@ 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"
+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"
@@ -425,28 +477,28 @@ files = [
[[package]]
name = "kombu"
-version = "5.3.7"
+version = "5.4.0"
description = "Messaging library for Python."
optional = false
python-versions = ">=3.8"
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"]
+consul = ["python-consul2 (==0.1.5)"]
librabbitmq = ["librabbitmq (>=2.0.0)"]
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)"]
@@ -455,6 +507,53 @@ sqs = ["boto3 (>=1.26.143)", "pycurl (>=7.43.0.5)", "urllib3 (>=1.26.16)"]
yaml = ["PyYAML (>=3.10)"]
zookeeper = ["kazoo (>=2.8.0)"]
+[[package]]
+name = "mypy"
+version = "1.11.1"
+description = "Optional static typing for Python"
+optional = false
+python-versions = ">=3.8"
+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"
@@ -466,6 +565,17 @@ files = [
{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"
+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"
@@ -504,6 +614,24 @@ 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"
+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"
@@ -652,6 +780,68 @@ files = [
{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"
+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"
@@ -748,6 +938,20 @@ 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"
+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"
@@ -798,6 +1002,26 @@ files = [
{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"
+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)", "pytest-mock (>=3.11.1)", "pytest-randomly (>=3.12)", "pytest-timeout (>=2.1)", "setuptools (>=68)", "time-machine (>=2.10)"]
+
[[package]]
name = "wcwidth"
version = "0.2.13"
@@ -812,4 +1036,4 @@ files = [
[metadata]
lock-version = "2.0"
python-versions = "~3.10"
-content-hash = "59976517fc9a0a2ef6544f3dc38ba8467fa1eabd0cf20a74fda8af682d1f5dab"
+content-hash = "329ca421a9211ca34d1c853447757aa9aac41bb76d3d7bed9b7dac9787fe397c"
diff --git a/app/pyproject.toml b/app/pyproject.toml
index e9d9037..baaa9ff 100644
--- a/app/pyproject.toml
+++ b/app/pyproject.toml
@@ -18,8 +18,12 @@ requests = "^2.32.3"
python-dotenv = "^1.0.1"
+
[tool.poetry.group.dev.dependencies]
black = "^24.8.0"
+pre-commit = "^3.8.0"
+types-requests = "^2.32.0.20240712"
+mypy = "^1.11.1"
[build-system]
requires = ["poetry-core"]
diff --git a/app/repcofkk/app_settings.py b/app/repcofkk/app_settings.py
index 379fa90..b42736d 100644
--- a/app/repcofkk/app_settings.py
+++ b/app/repcofkk/app_settings.py
@@ -1,25 +1,25 @@
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',
+ 'apps.main.apps.MainConfig', # Стартовая страница
+ 'apps.montorem.apps.MontoremConfig', # Подсистема монторем
]
"""Информация о приложении """
-SITE_TITLE = "Система отчетов"
-SITE_TITLE_S = "СиО"
-APP_VERSION = "0.6.2"
-APP_VEK = "2024 г"
-APP_COPPIRIGHT = "Система отчетов"
+SITE_TITLE = 'Система отчетов'
+SITE_TITLE_S = 'СиО'
+APP_VERSION = '0.7'
+APP_VEK = '2024 г'
+APP_COPPIRIGHT = 'Система отчетов'
-KEYWORDS = ""
-DESCRIPTION = "Система отчетов"
-AUTHOR = "Киберкод"
+KEYWORDS = ''
+DESCRIPTION = 'Система отчетов'
+AUTHOR = 'Киберкод'
diff --git a/app/repcofkk/celery.py b/app/repcofkk/celery.py
index 270de7a..0245dd9 100644
--- a/app/repcofkk/celery.py
+++ b/app/repcofkk/celery.py
@@ -4,35 +4,35 @@ 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,
+ '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,
+ '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),
+ 'shift_report': {
+ 'task': 'apps.main.tasks.create_shift_report',
+ 'schedule': crontab(hour='7,19', minute=50),
},
+ 'shift_start_worktime': {
+ 'task': 'apps.main.tasks.create_start_shift_worktime',
+ 'schedule': crontab(hour='8,20', minute=0)
+ }
}
diff --git a/app/static/css/style.css b/app/static/css/style.css
index 35f49cc..2084cd3 100644
--- a/app/static/css/style.css
+++ b/app/static/css/style.css
@@ -1,5 +1,6 @@
.roboto {
font-family: Arial, sans-serif, -apple-system, system-ui, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
+!important;
}
.col-3 > *, .h-title, .m-widget1__title, .m-widget_content-title {
@@ -8,6 +9,12 @@
* {
box-sizing: border-box;
+ font-family: Roboto, sans-serif;
+}
+
+.m-form__help {
+ font-size: 0.9rem;
+ color: var(--gray);
}
.h-title {
@@ -93,14 +100,14 @@ body {
/*Лента - ДЕМО*/
.box {
- z-index: 0;
+ z-index: auto;
}
.ribbon {
position: fixed;
right: -5px;
top: -5px;
- z-index: 1;
+ z-index: 1000;
overflow: hidden;
width: 93px;
height: 93px;
@@ -132,7 +139,7 @@ body {
position: absolute;
left: 0px;
top: 100%;
- z-index: -1;
+ z-index: 999;
border-left: 3px solid #79A70A;
border-right: 3px solid transparent;
border-bottom: 3px solid transparent;
@@ -144,7 +151,7 @@ body {
position: absolute;
right: 0%;
top: 100%;
- z-index: -1;
+ z-index: 999;
border-right: 3px solid #79A70A;
border-left: 3px solid transparent;
border-bottom: 3px solid transparent;
@@ -211,4 +218,6 @@ body {
padding-top: 0.7rem;
padding-bottom: 0.7rem;
}
-
+.aspiration_img {
+ width: 100%;
+}
diff --git a/app/static/img/aspiration.gif b/app/static/img/aspiration.gif
new file mode 100644
index 0000000..ba4fa23
Binary files /dev/null and b/app/static/img/aspiration.gif differ
diff --git a/app/static/img/aspiration.png b/app/static/img/aspiration.png
new file mode 100644
index 0000000..696160f
Binary files /dev/null and b/app/static/img/aspiration.png differ
diff --git a/app/static/js/charts/scaleControl.js b/app/static/js/charts/scaleControl.js
index 18c2c10..4cd5b22 100644
--- a/app/static/js/charts/scaleControl.js
+++ b/app/static/js/charts/scaleControl.js
@@ -1,492 +1,713 @@
(async function () {
- let positions
- positions = await fetch('positions/').then(response => {
- return response.json()
- })
- const boldLabel = {
+ const positions = await fetch('positions/').then(response => {
+ return response.json()
+ })
+ const boldLabel = {
+ show: true,
+ maxHeight: 120,
+ style: {
+ fontSize: '13px',
+ cssClass: 'apexcharts-xaxis-label bold'
+ }
+ }
+ const locales = [{
+ name: 'ru',
+ options: {
+ months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентрябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
+ shortMonths: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июнь', 'Июль ', 'Авг', 'Сент', 'Окт', 'Нояб', 'Дек'],
+ days: ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'],
+ shortDays: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'],
+ toolbar: {
+ exportToSVG: 'Скачать SVG',
+ exportToPNG: 'Скачать PNG',
+ exportToCSV: 'Скачать CSV',
+ menu: 'Меню',
+ selection: 'Выборка',
+ selectionZoom: 'Приближение выборки',
+ zoomIn: 'Приблизить',
+ zoomOut: 'Отдалить',
+ pan: 'Панорамирование',
+ reset: 'Сбросить приближение'
+ }
+ }
+ }]
+ const colors = ['var(--success)', 'var(--primary)', 'var(--danger)']
+
+ const commonChartOptions = {
+ colors,
+ chart: {
+ type: 'bar',
+ height: 300,
+ locales,
+ defaultLocale: 'ru'
+ },
+ fill: {
+ opacity: 1
+ },
+ xaxis: {
+ categories: positions
+ },
+ noData: {
+ text: 'Загрузка...'
+ }
+ }
+
+ const commonRadialBarOptions = {
+ chart: {
+ type: 'radialBar',
+ height: 220
+ },
+ labels: ['т. смена ', 'пр. смена '],
+ series: [],
+ plotOptions: {
+ radialBar: {
+ size: undefined,
+ inverseOrder: false,
+ hollow: {
+ margin: 5,
+ size: '48%',
+ background: 'transparent'
+ },
+ track: {
+ show: true,
+ background: '#40475D',
+ strokeWidth: '10%',
+ opacity: 1,
+ margin: 3
+ },
+ dataLabels: {
+ name: {
show: true,
- maxHeight: 120,
+ color: '#888',
+ fontSize: '12px',
+ fontWeight: 400
+ },
+ value: {
+ color: '#111',
+ offsetY: -2,
+ fontSize: '12px',
+ fontWeight: 400,
+ show: true
+ }
+ }
+ }
+ },
+ colors,
+ legend: {
+ show: true,
+ position: 'bottom',
+ formatter: function (val, opts) {
+ return val + ' - ' + opts.w.globals.series[opts.seriesIndex] + '%'
+ }
+ },
+ noData: {
+ text: 'Загрузка...'
+ }
+ }
+
+ const hoursBarOptions = {
+ ...commonChartOptions,
+ series: [{
+ name: 'Текущая смена',
+ data: []
+ }, {
+ name: 'Предыдущая смена',
+ data: []
+ }],
+ plotOptions: {
+ bar: {
+ horizontal: true
+ }
+ },
+ dataLabels: {
+ enabled: true,
+ textAnchor: 'start',
+ offsetX: -7,
+ dropShadow: {
+ enabled: false
+ },
+ animation: {
+ enabled: false
+ }
+ },
+ stroke: {
+ show: true,
+ width: 2,
+ colors: ['transparent']
+ },
+ tooltip: {
+ y: {
+ formatter: function (val) {
+ return val + ' тонн в час'
+ }
+ }
+ },
+ title: {
+ text: 'часовая нагрузка'
+ }
+ }
+
+ const dailyBarOptions = {
+ ...commonChartOptions,
+ series: [],
+ chart: {
+ ...commonChartOptions.chart,
+ stacked: true,
+ toolbar: {
+ show: true
+ }
+ },
+ responsive: [{
+ breakpoint: 480,
+ options: {
+ legend: {
+ position: 'bottom',
+ offsetX: -10,
+ offsetY: 0
+ }
+ }
+ }],
+ plotOptions: {
+ bar: {
+ horizontal: false,
+ dataLabels: {
+ total: {
+ enabled: true,
style: {
- fontSize: '13px',
- cssClass: 'apexcharts-xaxis-label bold',
- },
+ fontSize: '13px',
+ fontWeight: 900
+ }
+ }
}
- const locales = [{
- "name": "ru",
- "options": {
- "months": ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентрябрь", "Октябрь", "Ноябрь", "Декабрь"],
- "shortMonths": ["Янв", "Фев", "Мар", "Апр", "Май", "Июнь", "Июль ", "Авг", "Сент", "Окт", "Нояб", "Дек"],
- "days": ["Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"],
- "shortDays": ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
- "toolbar": {
- "exportToSVG": "Скачать SVG",
- "exportToPNG": "Скачать PNG",
- "exportToCSV": "Скачать CSV",
- "menu": "Меню",
- "selection": "Выборка",
- "selectionZoom": "Приближение выборки",
- "zoomIn": "Приблизить",
- "zoomOut": "Отдалить",
- "pan": "Панорамирование",
- "reset": "Сбросить приближение"
- }
- }
- }]
- const colors = ['var(--success)', 'var(--primary)', 'var(--danger)']
+ }
+ },
+ legend: {
+ position: 'bottom'
+ },
+ title: {
+ text: 'тонн за сутки'
+ }
+ }
- const commonChartOptions = {
- colors: colors,
- chart: {
- type: 'bar',
- height: 300,
- locales: locales,
- defaultLocale: "ru",
- },
- fill: {
- opacity: 1
- },
- xaxis: {
- categories: positions,
- },
- noData: {
- text: 'Загрузка...'
- }
- };
-
- const commonRadialBarOptions = {
- chart: {
- type: 'radialBar',
- height: 220
- },
- labels: ['т. смена ', 'пр. смена '],
- series: [],
- plotOptions: {
- radialBar: {
- size: undefined,
- inverseOrder: false,
- hollow: {
- margin: 5,
- size: '48%',
- background: 'transparent',
- },
- track: {
- show: true,
- background: '#40475D',
- strokeWidth: '10%',
- opacity: 1,
- margin: 3,
- },
- dataLabels: {
- name: {
- show: true,
- color: '#888',
- fontSize: '12px',
- fontWeight: 400,
- },
- value: {
- color: '#111',
- offsetY: -2,
- fontSize: '12px',
- fontWeight: 400,
- show: true,
- }
- }
- },
- },
- colors: colors,
- legend: {
- show: true,
- position: 'bottom',
- formatter: function (val, opts) {
- return val + " - " + opts.w.globals.series[opts.seriesIndex] + '%';
- }
- },
- noData: {
- text: 'Загрузка...'
- }
- };
-
- const hoursBarOptions = {
- ...commonChartOptions,
- series: [{
- name: 'Текущая смена',
- data: []
- }, {
- name: 'Предыдущая смена',
- data: []
- }],
- plotOptions: {
- bar: {
- horizontal: true,
- },
- },
- dataLabels: {
- enabled: true,
- textAnchor: 'start',
- offsetX: -7,
- dropShadow: {
- enabled: false
- },
- animation: {
- enabled: false
- }
- },
- stroke: {
- show: true,
- width: 2,
- colors: ['transparent']
- },
- tooltip: {
- y: {
- formatter: function (val) {
- return val + " тонн в час";
- }
- }
- },
- title: {
- text: 'часовая нагрузка'
- }
- };
-
- const dailyBarOptions = {
- ...commonChartOptions,
- series: [],
- chart: {
- ...commonChartOptions.chart,
- stacked: true,
- toolbar: {
- show: true
- }
- },
- responsive: [{
- breakpoint: 480,
- options: {
- legend: {
- position: 'bottom',
- offsetX: -10,
- offsetY: 0
- }
- }
- }],
- plotOptions: {
- bar: {
- horizontal: false,
- dataLabels: {
- total: {
- enabled: true,
- style: {
- fontSize: '13px',
- fontWeight: 900
- }
- }
- }
- },
- },
- legend: {
- position: 'bottom',
- },
- title: {
- text: 'тонн за сутки'
- }
- };
-
- const monthlyBarOptions = {
- ...commonChartOptions,
- series: [],
- chart: {
- ...commonChartOptions.chart,
- stacked: true,
- toolbar: {
- show: true
- },
- zoom: {
- enabled: true
- }
- },
- responsive: [{
- breakpoint: 480,
- options: {
- legend: {
- position: 'bottom',
- offsetX: 10,
- offsetY: 20
- }
- }
- }],
- plotOptions: {
- bar: {
- dataLabels: {
- total: {
- enabled: true,
- style: {
- fontSize: '13px',
- fontWeight: 900
- }
- }
- },
- columnWidth: '60%',
- }
- },
- dataLabels: {
- enabled: true,
- style: {
- colors: ['rgba(0,0,0,0)']
- },
- offsetY: 0,
- offsetX: 0,
- textAnchor: 'start',
- formatter: function (val) {
- return val;
- }
- },
- legend: {
- position: 'bottom',
- },
- title: {
- text: 'тонн за месяц'
- },
- tooltip: {
- y: {
- formatter: function (val) {
- return val + ' тонн'
- }
- }
- }
- };
-
- const hourOptionsCircle_1 = {
- ...commonRadialBarOptions,
- labels: ['Y к-та', 'Y отсева'],
- title: {
- text: 'т. смена'
- }
- };
-
- const hourOptionsCircle_2 = {
- ...commonRadialBarOptions,
- labels: ['Y к-та', 'Y отсева'],
- title: {
- text: 'пр. смена'
- }
- };
-
- const doubleOptionsCircle = {
- ...commonRadialBarOptions,
- labels: ['Y к-та', 'Y отсева'],
- legend: {
- ...commonRadialBarOptions.legend,
- position: 'left'
- }
- };
-
- const optionsProgress = {
- chart: {
- height: 70,
- width: '100%',
- type: 'bar',
- stacked: true,
- sparkline: {
- enabled: true
- }
- },
- plotOptions: {
- bar: {
- horizontal: true,
- barHeight: '40%',
- colors: {
- backgroundBarColors: ['#40475D']
- }
- },
- },
- dataLabels: {
- enabled: true,
- formatter: function (val, opts) {
- return val;
- },
- style: {
- colors: ['#fff'],
-
- fontSize: '16px',
-
- fontWeight: 'bold'
-
- },
- textAnchor: 'start',
- },
- colors: colors,
- stroke: {
- width: 0,
- },
- series: [
- {
- name: 'Факт',
- data: [
- {
- x: 'Тонн за месяц',
- y: 0,
- goals: [
- {
- name: 'План',
- value: 250000,
- strokeHeight: 15,
- strokeColor: 'var(--danger)'
- }
- ]
- },
- ]
- },
- ],
- noData: 'Загрузка...',
- title: {
- floating: true,
- offsetX: -10,
- offsetY: 5,
- text: 'Пераработанное сырье',
- style: {
- fontSize: '14px'
- }
- },
- subtitle: {
- floating: true,
- align: 'right',
- offsetY: 3,
- text: '',
- style: {
- fontSize: '15px'
- }
- },
- tooltip: {
- enabled: true,
- shared: true,
- intersect: false
- },
- xaxis: {
- categories: ['Тонн за месяц'],
- },
- yaxis: {
- max: 400000
- },
+ const monthlyBarOptions = {
+ ...commonChartOptions,
+ series: [],
+ chart: {
+ ...commonChartOptions.chart,
+ stacked: true,
+ toolbar: {
+ show: true
+ },
+ zoom: {
+ enabled: true
+ }
+ },
+ responsive: [{
+ breakpoint: 480,
+ options: {
+ legend: {
+ position: 'bottom',
+ offsetX: 10,
+ offsetY: 20
}
-
-
- const chartProgress = new ApexCharts(document.querySelector('#chartProgress'), optionsProgress);
- await chartProgress.render();
-
- const hoursBarChart = new ApexCharts(document.querySelector("#byHourScales"), hoursBarOptions);
- await hoursBarChart.render();
- hoursBarChart.updateOptions({
- yaxis: {
- labels: {...boldLabel}
+ }
+ }],
+ plotOptions: {
+ bar: {
+ dataLabels: {
+ total: {
+ enabled: true,
+ style: {
+ fontSize: '13px',
+ fontWeight: 900
}
- })
-
- const dailyScalesChart = new ApexCharts(document.querySelector("#dailyScales"), dailyBarOptions);
- await dailyScalesChart.render();
- dailyScalesChart.updateOptions({
- xaxis: {
- labels: {...boldLabel}
- }
- })
- const monthlyScalesChart = new ApexCharts(document.querySelector("#monthlyScales"), monthlyBarOptions);
- await monthlyScalesChart.render();
- monthlyScalesChart.updateOptions({
- xaxis: {
- labels: {...boldLabel}
- }
- })
- const hourChartCircle_1 = new ApexCharts(document.querySelector('#HourCircle_1'), hourOptionsCircle_1);
- await hourChartCircle_1.render();
-
- const hourChartCircle_2 = new ApexCharts(document.querySelector('#HourCircle_2'), hourOptionsCircle_2);
- await hourChartCircle_2.render();
-
- const dailyDoubleChartCircle_1 = new ApexCharts(document.querySelector('#dailyCircle'), doubleOptionsCircle);
- await dailyDoubleChartCircle_1.render();
-
- const monthlyDoubleChartCircle_2 = new ApexCharts(document.querySelector('#monthlyCircle'), doubleOptionsCircle);
- await monthlyDoubleChartCircle_2.render();
-
- async function getChartsData() {
- const response = await fetch('scales/');
- return response.json();
+ }
+ },
+ columnWidth: '60%'
+ }
+ },
+ dataLabels: {
+ enabled: true,
+ style: {
+ colors: ['rgba(0,0,0,0)']
+ },
+ offsetY: 0,
+ offsetX: 0,
+ textAnchor: 'start',
+ formatter: function (val) {
+ return val
+ }
+ },
+ legend: {
+ position: 'bottom'
+ },
+ title: {
+ text: 'тонн за месяц'
+ },
+ tooltip: {
+ y: {
+ formatter: function (val) {
+ return val + ' тонн'
}
+ }
+ }
+ }
- function setChartsData(response) {
- chartProgress.updateOptions({
- subtitle: {
- text: response.plan.percent
- },
- yaxis: {
- max: response.plan.goal + 100000
- }
- })
- chartProgress.updateSeries([
- {
- name: 'Факт',
- data: [
- {
- x: 'Тонн за месяц',
- y: response.plan.value,
- goals: [
- {
- name: 'План',
- value: response.plan.goal,
- strokeHeight: 15,
- strokeColor: 'var(--danger)'
- }
- ]
- },
- ]
- },
- ],)
+ const hourOptionsCircle1 = {
+ ...commonRadialBarOptions,
+ labels: ['Y к-та', 'Y отсева'],
+ title: {
+ text: 'т. смена'
+ }
+ }
- monthlyScalesChart.updateSeries([{
- name: 'Месяц',
- data: Object.values(response.monthly.scales)
- }], true)
+ const hourOptionsCircle2 = {
+ ...commonRadialBarOptions,
+ labels: ['Y к-та', 'Y отсева'],
+ title: {
+ text: 'пр. смена'
+ }
+ }
- hoursBarChart.updateSeries([{
- name: 'Текущая смена',
- data: Object.values(response.average.current_work_shift)
- }, {
- name: 'Предыдущая смена',
- data: Object.values(response.average.previous_work_shift)
- }])
- dailyScalesChart.updateSeries([{
- name: 'Текущая смена',
- data: Object.values(response.daily.current_work_shift)
- }, {
- name: 'Предыдущая смена',
- data: Object.values(response.daily.previous_work_shift)
- }], true)
- for (let item of ['daily', 'monthly', 'average']) {
- let latestDate = document.querySelector(`#${item}LatestDate`)
- const dateObj = new Date(response[`${item}`].latest_date)
- const padZero = (num) => num.toString().padStart(2, '0');
- const day = padZero(dateObj.getDate());
- const month = padZero(dateObj.getMonth() + 1);
- const year = dateObj.getFullYear();
- const hours = padZero(dateObj.getHours());
- const minutes = padZero(dateObj.getMinutes());
- const seconds = padZero(dateObj.getSeconds());
- latestDate.textContent = `Данные от ${day}.${month}.${year} ${hours}:${minutes}:${seconds}`
- }
- hourChartCircle_1.updateSeries(Object.values(response.average.percent_values.current_shift))
- hourChartCircle_2.updateSeries(Object.values(response.average.percent_values.previous_shift))
+ const doubleOptionsCircle = {
+ ...commonRadialBarOptions,
+ labels: ['Y к-та', 'Y отсева'],
+ legend: {
+ ...commonRadialBarOptions.legend,
+ position: 'left'
+ }
+ }
- dailyDoubleChartCircle_1.updateSeries(Object.values(response.daily.percent_values.current_shift))
- monthlyDoubleChartCircle_2.updateSeries(Object.values(response.monthly.percent_values))
+ const optionsFabricGoal = {
+ chart: {
+ height: 70,
+ width: '100%',
+ type: 'bar',
+ stacked: true,
+ sparkline: {
+ enabled: true
+ }
+ },
+ plotOptions: {
+ bar: {
+ horizontal: true,
+ barHeight: '40%',
+ colors: {
+ backgroundBarColors: ['#40475D']
}
+ }
+ },
+ dataLabels: {
+ enabled: true,
+ formatter: function (val, opts) {
+ return val + ' т.'
+ },
+ style: {
+ colors: ['#fff'],
- async function buildCharts() {
- const response = await getChartsData()
- setChartsData(response)
+ fontSize: '16px',
+
+ fontWeight: 'bold'
+
+ },
+ textAnchor: 'start'
+ },
+ colors,
+ stroke: {
+ width: 0
+ },
+ series: [
+ {
+ name: 'Факт',
+ data: [
+ {
+ x: 'Тонн за месяц',
+ y: 0,
+ goals: [
+ {
+ name: 'План',
+ value: 250000,
+ strokeHeight: 15,
+ strokeColor: 'var(--danger)'
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ noData: 'Загрузка...',
+ title: {
+ floating: true,
+ offsetX: -10,
+ offsetY: 5,
+ text: 'Пераработанное сырье',
+ style: {
+ fontSize: '14px'
+ }
+ },
+ subtitle: {
+ floating: true,
+ align: 'right',
+ offsetY: 3,
+ text: '',
+ style: {
+ fontSize: '15px'
+ }
+ },
+ tooltip: {
+ enabled: true,
+ shared: true,
+ intersect: false
+ },
+ xaxis: {
+ categories: ['Тонн за месяц']
+ },
+ yaxis: {
+ max: 400000
+ }
+ }
+
+ // const optionsConcentrate = {
+ // chart: {
+ // height: 70,
+ // width: '100%',
+ // type: 'bar',
+ // stacked: true,
+ // sparkline: {
+ // enabled: true
+ // }
+ // },
+ // plotOptions: {
+ // bar: {
+ // horizontal: true,
+ // barHeight: '40%',
+ // colors: {
+ // backgroundBarColors: ['#40475D']
+ // }
+ // },
+ // },
+ // dataLabels: {
+ // enabled: true,
+ // formatter: function (val, opts) {
+ // return val + '%';
+ // },
+ // style: {
+ // colors: ['#fff'],
+ //
+ // fontSize: '16px',
+ //
+ // fontWeight: 'bold'
+ //
+ // },
+ // textAnchor: 'middle',
+ // },
+ // colors: colors,
+ // stroke: {
+ // width: 0,
+ // },
+ // series: [
+ // {
+ // name: 'Концентрат',
+ // data: [
+ // {
+ // x: 'Концентрат %',
+ // y: 56,
+ // },
+ // ]
+ // },
+ // ],
+ // noData: 'Загрузка...',
+ // title: {
+ // floating: true,
+ // offsetX: -10,
+ // offsetY: 5,
+ // text: 'Выход концентрата',
+ // style: {
+ // fontSize: '14px'
+ // }
+ // },
+ // subtitle: {
+ // floating: true,
+ // align: 'right',
+ // offsetY: 3,
+ // text: '',
+ // style: {
+ // fontSize: '15px'
+ // }
+ // },
+ // tooltip: {
+ // enabled: true,
+ // shared: true,
+ // intersect: false
+ // },
+ // xaxis: {
+ // categories: ['Выход концентрата'],
+ // },
+ // yaxis: {
+ // max: 100
+ // },
+ // }
+
+ const optionsDoubleProgress = {
+ chart: {
+ height: 70,
+ width: '100%',
+ type: 'bar',
+ stacked: false,
+ sparkline: {
+ enabled: true
+ }
+ },
+ plotOptions: {
+ bar: {
+ horizontal: true,
+ barHeight: '50%',
+ colors: {
+ backgroundBarColors: ['#40475D']
}
+ }
+ },
+ dataLabels: {
+ enabled: true,
+ formatter: function (val, opts) {
+ if (val !== 0) {
+ const title = opts.config.series[opts.seriesIndex].name
+ return title + ' ' + val + '%'
+ } else {
+ return ''
+ }
+ },
+ style: {
+ colors: ['#fff'],
+ fontSize: '15px',
+ fontWeight: 'bold'
+ },
+ textAnchor: 'middle',
+ offsetX: 35
+ },
+ colors,
+ stroke: {
+ width: 0
+ },
+ series: [{
+ name: 'Концентрат',
+ data: [0]
+ }, {
+ name: 'Отсев',
+ data: [0]
+ }],
+ noData: 'Загрузка...',
+ title: {
+ floating: true,
+ offsetX: -10,
+ offsetY: 5,
+ text: 'Выход отсева и концентрата',
+ style: {
+ fontSize: '14px'
+ }
+ },
+ subtitle: {
+ floating: true,
+ align: 'right',
+ offsetY: 3,
+ text: '',
+ style: {
+ fontSize: '15px'
+ }
+ },
+ tooltip: {
+ enabled: true,
+ shared: true,
+ intersect: false,
+ y: {
+ formatter: function (val) {
+ return val + '%'
+ }
+ }
+ },
+ xaxis: {
+ categories: ['Выход отсева и концентрата за месяц']
+ },
+ yaxis: {
+ max: 100
+ }
+ }
- await buildCharts()
- setInterval(buildCharts, 5000)
+ const GoalProgressChart = new ApexCharts(document.querySelector('#GoalProgress'), optionsFabricGoal)
+ await GoalProgressChart.render()
+ const DropoutAndConcentrateChart = new ApexCharts(
+ document.querySelector('#DropoutAndConcentrate'),
+ optionsDoubleProgress)
+ // Рендерится не сразу
+
+ const hoursBarChart = new ApexCharts(document.querySelector('#byHourScales'), hoursBarOptions)
+ await hoursBarChart.render()
+ hoursBarChart.updateOptions({
+ yaxis: {
+ labels: { ...boldLabel }
+ }
+ })
+
+ const dailyScalesChart = new ApexCharts(document.querySelector('#dailyScales'), dailyBarOptions)
+ await dailyScalesChart.render()
+ dailyScalesChart.updateOptions({
+ xaxis: {
+ labels: { ...boldLabel }
+ }
+ })
+ const monthlyScalesChart = new ApexCharts(document.querySelector('#monthlyScales'), monthlyBarOptions)
+ await monthlyScalesChart.render()
+ monthlyScalesChart.updateOptions({
+ xaxis: {
+ labels: { ...boldLabel }
+ }
+ })
+ const hourChartCircle1 = new ApexCharts(document.querySelector('#HourCircle_1'), hourOptionsCircle1)
+ await hourChartCircle1.render()
+
+ const hourChartCircle2 = new ApexCharts(document.querySelector('#HourCircle_2'), hourOptionsCircle2)
+ await hourChartCircle2.render()
+
+ const dailyDoubleChartCircle2 = new ApexCharts(document.querySelector('#dailyCircle'), doubleOptionsCircle)
+ await dailyDoubleChartCircle2.render()
+
+ const monthlyDoubleChartCircle2 = new ApexCharts(document.querySelector('#monthlyCircle'), doubleOptionsCircle)
+ await monthlyDoubleChartCircle2.render()
+
+ async function getChartsData () {
+ const response = await fetch('scales/')
+ return response.json()
+ }
+
+ function setChartsData (response) {
+ GoalProgressChart.updateOptions({
+ subtitle: {
+ text: response.plan.percent
+ },
+ yaxis: {
+ max: response.plan.goal + 100000
+ }
+ })
+ GoalProgressChart.updateSeries([
+ {
+ name: 'Факт',
+ data: [
+ {
+ x: 'Тонн за месяц',
+ y: response.plan.value,
+ goals: [
+ {
+ name: 'План',
+ value: response.plan.goal,
+ strokeHeight: 15,
+ strokeColor: 'var(--danger)'
+ }
+ ]
+ }
+ ]
+ }
+ ])
+
+ if (response.concentrate_and_dropout !== false) {
+ DropoutAndConcentrateChart.render()
+ DropoutAndConcentrateChart.updateSeries([{
+ name: 'Концентрат',
+ data: [response.concentrate_and_dropout.concentrate]
+ }, {
+ name: 'Отсев',
+ data: [response.concentrate_and_dropout.dropout]
+ }])
+ } else {
+ const widgetDiv = document.querySelector('#DropoutAndConcentrate')
+ widgetDiv.classList.add('d-flex', 'justify-content-between', 'align-items-center', 'h-100')
+ widgetDiv.textContent = 'Для отображения виджета необходимо'
+ widgetDiv.insertAdjacentHTML('beforeend', 'Ввести данные ')
}
-)
-();
\ No newline at end of file
+ monthlyScalesChart.updateSeries([{
+ name: 'Месяц',
+ data: Object.values(response.monthly.scales)
+ }], true)
+
+ hoursBarChart.updateSeries([{
+ name: 'Текущая смена',
+ data: Object.values(response.average.current_work_shift)
+ }, {
+ name: 'Предыдущая смена',
+ data: Object.values(response.average.previous_work_shift)
+ }])
+ dailyScalesChart.updateSeries([{
+ name: 'Текущая смена',
+ data: Object.values(response.daily.current_work_shift)
+ }, {
+ name: 'Предыдущая смена',
+ data: Object.values(response.daily.previous_work_shift)
+ }], true)
+ for (const item of ['daily', 'monthly', 'average']) {
+ const latestDate = document.querySelector(`#${item}LatestDate`)
+ const dateObj = new Date(response[`${item}`].latest_date)
+ const padZero = (num) => num.toString().padStart(2, '0')
+ const day = padZero(dateObj.getDate())
+ const month = padZero(dateObj.getMonth() + 1)
+ const year = dateObj.getFullYear()
+ const hours = padZero(dateObj.getHours())
+ const minutes = padZero(dateObj.getMinutes())
+ const seconds = padZero(dateObj.getSeconds())
+ latestDate.textContent = `Данные от ${day}.${month}.${year} ${hours}:${minutes}:${seconds}`
+ }
+ hourChartCircle1.updateSeries(Object.values(response.average.percent_values.current_shift))
+ hourChartCircle2.updateSeries(Object.values(response.average.percent_values.previous_shift))
+
+ dailyDoubleChartCircle2.updateSeries(Object.values(response.daily.percent_values.current_shift))
+ monthlyDoubleChartCircle2.updateSeries(Object.values(response.monthly.percent_values))
+ }
+
+ async function buildCharts () {
+ const response = await getChartsData()
+ setChartsData(response)
+ }
+
+ await buildCharts()
+ setInterval(buildCharts, 5000)
+})()
+
+const kekInput = document.querySelector('#kekInput')
+const breedInput = document.querySelector('#breedInput')
+const submitBtn = document.querySelector('#submitBtn')
+submitBtn.addEventListener('click', async (e) => {
+ const data = {
+ kek: kekInput.value,
+ breed: breedInput.value
+ }
+ const response = await fetch('scales/kek_and_breed/recieve', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ 'X-CSRFToken': window.getCookie('csrftoken')
+ },
+ body: JSON.stringify(data)
+ })
+
+ const responseJson = 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 = `${responseJson.message}`
+
+ kekAndBreedModalAlerts.appendChild(alert)
+
+ if (responseJson.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')
+ }
+})
diff --git a/app/templates/default.html b/app/templates/default.html
index 0c17b35..55d2321 100644
--- a/app/templates/default.html
+++ b/app/templates/default.html
@@ -18,6 +18,7 @@
+ {% block extra_head %}{% endblock %}
@@ -65,7 +66,7 @@
+ class="logo">