repcofkk/apps/main/dashboard.py
2024-06-26 09:37:14 +07:00

182 lines
6.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import pytz
from datetime import datetime, timedelta
from django.utils import timezone
from django.db.models import QuerySet
from apps.main.models.dashboard_models import ScalesControl
def get_qs_by_range(model, start: datetime, end: datetime) -> QuerySet:
return model.objects.only('time').filter(time__range=(start, end)).values()
def calculate_work_time(qs: list):
status_durations = {
'WO': timedelta(0),
'WA': timedelta(0),
'NW': timedelta(0)
}
if not qs:
return status_durations
previous_time = qs[0]['time']
previous_status = qs[0]['status']
for work in qs[1:]:
current_time = work['time']
current_status = work['status']
duration = current_time - previous_time
status_durations[previous_status] += duration
previous_time = current_time
previous_status = current_status
now_date = timezone.now()
duration = now_date - previous_time
status_durations[previous_status] += duration
status_durations_hours = {k: round(v.total_seconds() / 3600) for k, v in status_durations.items()}
return status_durations_hours
def get_scales_value(positions: QuerySet, interval: str) -> dict:
res = {}
scales = {}
latest_date = None
for position in positions:
try:
obj = (ScalesControl.objects
.only('name', 'date')
.filter(name__endswith=f'{position.tag}.{interval}')
.latest('date'))
scales[position.title] = int(obj.value) if obj.value >= 0 else 0
if latest_date:
if latest_date < obj.date:
latest_date = obj.date
else:
latest_date = obj.date
except ScalesControl.DoesNotExist:
scales[position.title] = '0'
new_timezone = pytz.timezone('etc/GMT-7')
res['scales'] = scales
res['percent_values'] = get_percent_values(scales['Поз. 13'],
scales['Поз. 22'],
scales['Поз. 4'])
res['latest_date'] = latest_date.replace(tzinfo=new_timezone)
return res
def get_latest_shift_value(tag: str) -> tuple:
"""
Получает последнее значение и дату для заданного тега смены.
Возвращает кортеж: (значение, дата)
"""
try:
shift_obj = (ScalesControl.objects
.only('name', 'date')
.filter(name=tag)
.latest('date'))
value = round(float(shift_obj.value)) if shift_obj.value >= 0 else 0
return value, shift_obj.date
except ScalesControl.DoesNotExist:
return "0", None
def get_shift_tag(position, interval, is_current):
"""
Получает тег смены для заданной позиции в зависимости от интервала и типа смены.
"""
if is_current:
return position.aver_smena_tag if interval == 'Aver' else position.smena_tag
else:
return position.aver_pred_smena_tag if interval == 'Aver' else position.pred_smena_tag
def get_scales_value_by_shifts(positions: QuerySet, interval: str) -> dict:
"""
Получает показания весов с базы данных.
Возвращает словарь.
0 int - Показание меньше нуля либо равно нулю
0 str - Показания нет в базе
"""
res = {}
current_work_shift = {}
previous_work_shift = {}
latest_previous_shift_date = None
latest_current_shift_date = None
percent_values = {
'current_shift': {
'Y к-та': 60,
'Y отсева': 30,
},
'previous_shift': {
'Y к-та': 70,
'Y отсева': 40,
}
}
for position in positions:
# Обработка предыдущей смены
previous_shift_tag = get_shift_tag(position, interval, is_current=False)
previous_value, previous_date = get_latest_shift_value(previous_shift_tag)
previous_work_shift[position.title] = previous_value
if latest_previous_shift_date:
if previous_date and latest_previous_shift_date < previous_date:
latest_previous_shift_date = previous_date
else:
latest_previous_shift_date = previous_date
# Обработка текущей смены
current_shift_tag = get_shift_tag(position, interval, is_current=True)
current_value, current_date = get_latest_shift_value(current_shift_tag)
current_work_shift[position.title] = current_value
if latest_current_shift_date:
if current_date and latest_current_shift_date < current_date:
latest_current_shift_date = current_date
else:
latest_current_shift_date = current_date
percent_values['current_shift'] = get_percent_values(current_work_shift['Поз. 13'],
current_work_shift['Поз. 22'],
current_work_shift['Поз. 4'])
percent_values['previous_shift'] = get_percent_values(previous_work_shift['Поз. 13'],
previous_work_shift['Поз. 22'],
previous_work_shift['Поз. 4'])
res['percent_values'] = percent_values
res['previous_work_shift'] = previous_work_shift
res['current_work_shift'] = current_work_shift
new_timezone = pytz.timezone('etc/GMT-7')
if latest_previous_shift_date and latest_current_shift_date:
res['latest_date'] = latest_current_shift_date.replace(
tzinfo=new_timezone) if latest_previous_shift_date < latest_current_shift_date \
else latest_previous_shift_date.replace(tzinfo=new_timezone)
else:
res['latest_date'] = latest_current_shift_date.replace(
tzinfo=new_timezone) if latest_current_shift_date else None
return res
def get_percent_values(pos13_value: int, pos22_value: int, pos4_value: int) -> dict:
"""
Формула для вычисления Y отсева:
Поз.13 * 100 / Поз.4
Формула для вычисления Y концентрата:
Поз.22 * 100 / Поз.4
"""
concentrate = round(int(pos22_value) * 100 / int(pos4_value))
dropout = round(int(pos13_value) * 100 / int(pos4_value))
return {
'Y к-та': concentrate,
'Y отсева': dropout,
}