Виджет "Выход отсева и концентрата" + pre commit

This commit is contained in:
zakhy 2024-08-21 15:41:55 +07:00
parent 7dd81d03dc
commit 0454d5c0db
10 changed files with 1042 additions and 610 deletions

View File

@ -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:

View File

@ -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'}

View File

@ -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())

View File

@ -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')
]

View File

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

View File

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

View File

@ -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'),
]

View File

@ -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')

File diff suppressed because it is too large Load Diff

View File

@ -65,7 +65,7 @@
<a href="/main">
<img src="{% static 'img/Cybercode.png' %}?ver={% settings_value 'APP_VERSION' %}"
alt=""
class="logo">
class="logo">
</a>
</li>
<li class="m-menu__item m-menu__item--submenu m-menu__item--rel"
@ -119,9 +119,10 @@
<ul class="m-menu__inner">
<li class="m-menu__item " m-menu-link-redirect="1"
aria-haspopup="true">
<a href="/montorem/" class="m-menu__link ">
<a href="{% url 'concentrate_and_dropout' %}"
class="m-menu__link ">
<i class="m-menu__link-icon flaticon-graphic-2"></i>
<span class="m-menu__link-text">Концентрат и отсева</span>
<span class="m-menu__link-text">Выход концентрата</span>
</a>
</li>
</ul>
@ -247,4 +248,4 @@
{% block script_footer %}{% endblock script_footer %}
</body>
</html>
</html>