From 0454d5c0db780a6aa811b2c29f79976bc4adb2c9 Mon Sep 17 00:00:00 2001 From: zakhy Date: Wed, 21 Aug 2024 15:41:55 +0700 Subject: [PATCH] =?UTF-8?q?=D0=92=D0=B8=D0=B4=D0=B6=D0=B5=D1=82=20"=D0=92?= =?UTF-8?q?=D1=8B=D1=85=D0=BE=D0=B4=20=D0=BE=D1=82=D1=81=D0=B5=D0=B2=D0=B0?= =?UTF-8?q?=20=D0=B8=20=D0=BA=D0=BE=D0=BD=D1=86=D0=B5=D0=BD=D1=82=D1=80?= =?UTF-8?q?=D0=B0=D1=82=D0=B0"=20+=20pre=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .pre-commit-config.yaml | 14 - .../scales_control/redis_repository.py | 183 ++- .../main/services/scales_control/views.py | 48 +- app/apps/main/services/urls.py | 27 +- .../templates/concentrate_and_dropout.html | 90 ++ .../fabric_scales_control_widget.html | 46 +- app/apps/main/urls.py | 13 +- app/apps/main/views_main.py | 55 +- app/static/js/charts/scaleControl.js | 1167 ++++++++++------- app/templates/default.html | 9 +- 10 files changed, 1042 insertions(+), 610 deletions(-) create mode 100644 app/apps/main/templates/concentrate_and_dropout.html diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9db8310..5970f82 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -42,20 +42,6 @@ repos: exclude: "app/project/settings.py" args: [ "--ignore=E501,F821", "--max-line-length=120" ] - # Проверка статических типов с помощью mypy - - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.11.1 - hooks: - - id: mypy - exclude: 'migrations' - args: [--ignore-missing-imports] - - # Линтер JS - - repo: https://github.com/standard/standard - rev: v17.1.0 - hooks: - - id: standard - - repo: https://github.com/gitleaks/gitleaks rev: v8.18.4 hooks: diff --git a/app/apps/main/services/scales_control/redis_repository.py b/app/apps/main/services/scales_control/redis_repository.py index 69020c6..0aed85d 100644 --- a/app/apps/main/services/scales_control/redis_repository.py +++ b/app/apps/main/services/scales_control/redis_repository.py @@ -1,13 +1,11 @@ -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 +from repcofkk.local_settings import REDIS_HOST, REDIS_PORT class RedisRepository(DashboardBaseService): @@ -22,54 +20,61 @@ class RedisRepository(DashboardBaseService): self.service = service super().__init__() - def get_scales_value(self, positions: QuerySet, interval: str) -> dict: - res = {} - scales = {} - latest_date = None + def get_scales_value(self, positions: QuerySet, interval: str) -> dict[str, Any]: + res: dict[str, Any] = {} + scales: dict[str, int] = {} + latest_date: datetime | None = datetime(1970, 1, 1, 0, 0, 0, 0) + with self.service as redis_service: for position in positions: - if position.tag == "SIEMENSPLC.AZG01.ReportProdDB.ProdPos13": + if position.tag == 'SIEMENSPLC.AZG01.ReportProdDB.ProdPos13': pass position_value = redis_service.hget_value( - f"{position.tag}.{interval}", "Value" + f'{position.tag}.{interval}', 'Value' ) if position_value is None: - position_value = "0" + position_value = '0' + position_date_str = redis_service.hget_value( - f"{position.tag}.{interval}", "Date" + f'{position.tag}.{interval}', 'Date' ) + position_date: datetime | None = None + if position_date_str is not None: try: position_date = datetime.strptime( - position_date_str, "%Y-%m-%d %H:%M:%S.%f" + position_date_str, '%Y-%m-%d %H:%M:%S.%f' ) - except Exception: + except ValueError: position_date = datetime.strptime( - position_date_str, "%Y-%m-%d %H:%M:%S" + 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 = {} @@ -79,16 +84,16 @@ class RedisRepository(DashboardBaseService): position, interval, is_current=False ) previous_value = int( - float(redis_service.hget_value(previous_shift_tag, "Value")) + float(redis_service.hget_value(previous_shift_tag, 'Value')) ) - previous_date_str = redis_service.hget_value(previous_shift_tag, "Date") + 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" + 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_date_str, '%Y-%m-%d %H:%M:%S' ) previous_work_shift[position.title] = previous_value @@ -102,16 +107,16 @@ class RedisRepository(DashboardBaseService): position, interval, is_current=True ) current_value = int( - float(redis_service.hget_value(current_shift_tag, "Value")) + float(redis_service.hget_value(current_shift_tag, 'Value')) ) - current_date_str = redis_service.hget_value(current_shift_tag, "Date") + 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" + 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_date_str, '%Y-%m-%d %H:%M:%S' ) current_work_shift[position.title] = current_value @@ -121,30 +126,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 ) @@ -153,13 +158,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: @@ -179,20 +200,62 @@ 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'} 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..c7ab711 100644 --- a/app/apps/main/services/urls.py +++ b/app/apps/main/services/urls.py @@ -1,23 +1,30 @@ -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 ( 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('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/templates/concentrate_and_dropout.html b/app/apps/main/templates/concentrate_and_dropout.html new file mode 100644 index 0000000..a65f99f --- /dev/null +++ b/app/apps/main/templates/concentrate_and_dropout.html @@ -0,0 +1,90 @@ +{% extends 'default.html' %} + +{% block content %} +
+
+
+
+
+
+

+ Выпуск кек и породы (нат. вес) +

+
+
+
+
+
+
+ + +
+
+ + +
+
+
+
+
+
+ +
+
+
+
+
+
+{% endblock %} + +{% block script_footer %} + +{% endblock %} diff --git a/app/apps/main/templates/fabric_scales_control_widget.html b/app/apps/main/templates/fabric_scales_control_widget.html index 34a8856..00e172f 100644 --- a/app/apps/main/templates/fabric_scales_control_widget.html +++ b/app/apps/main/templates/fabric_scales_control_widget.html @@ -2,7 +2,10 @@
-
+
+
+
+
@@ -58,4 +61,43 @@
- \ No newline at end of file + + + diff --git a/app/apps/main/urls.py b/app/apps/main/urls.py index 5c6f8a8..2347f45 100644 --- a/app/apps/main/urls.py +++ b/app/apps/main/urls.py @@ -1,10 +1,11 @@ -from django.urls import path, include - from apps.main import views_main +from apps.main.views_main import 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'), ] diff --git a/app/apps/main/views_main.py b/app/apps/main/views_main.py index 204dce0..e17444a 100644 --- a/app/apps/main/views_main.py +++ b/app/apps/main/views_main.py @@ -1,60 +1,55 @@ -# -*- 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') 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..0dbe9a7 100644 --- a/app/templates/default.html +++ b/app/templates/default.html @@ -65,7 +65,7 @@ + class="logo"> @@ -247,4 +248,4 @@ {% block script_footer %}{% endblock script_footer %} - \ No newline at end of file +