test/apps/gto/views/views_report.py
zakhy 8c4f160253 Форматирование кода под PEP8
Не убраны неиспользованные импорты
2025-02-26 11:50:11 +07:00

426 lines
14 KiB
Python

import traceback
from datetime import datetime, timedelta
import requests
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db.models import Avg, Max, Min, Q
from django.db.models.functions import (Greatest, TruncDate, TruncDay,
TruncHour, TruncMinute, TruncSecond)
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.views.decorators.cache import never_cache
from requests.auth import HTTPBasicAuth
from apps.gto.models.model_alarm import GtoAlarm
from apps.gto.models.model_tracking import EquipmentTracking
from apps.util import generalmodule
from sabron.util import logging
def float_range(A, L=None, D=None):
# Use float number in range() function
# if L and D argument is null set A=0.0 and D = 1.0
if L == None:
L = A + 0.0
A = 0.0
if D == None:
D = 1.0
while True:
if D > 0 and A >= L:
break
elif D < 0 and A <= L:
break
yield ("%g" % A) # return float number
A = A + D
# end of function float_range()
@login_required(login_url="/accounts/login/?next=")
@never_cache
def show_report_value_ToHTML(request):
try:
dict_param = request.POST.dict()
data_start = datetime.strptime(
dict_param["DataStart"] + " 00:00:00", "%Y-%m-%d %H:%M:%S"
)
data_stop = datetime.strptime(
dict_param["DataStop"] + " 23:59:59", "%Y-%m-%d %H:%M:%S"
)
myquery = Q()
myquery &= Q(time__range=[data_start, data_stop])
indicators_list = (
EquipmentTracking.objects.filter(myquery)
.order_by("time")
.all()
.prefetch_related("equipment")
)
html = """
<table id = 'id_table' class='table table-bordered'>
<thead>
<tr>
<th style='width: 15px'>№</th>
<th>Время</th>
<th>Объект</th>
<th>Широта</th>
<th>Долгота</th>
<th style='width: 40px'>Скорость</th>
</tr>
</thead>
<tbody>
"""
nom = 0
for indicators in indicators_list:
nom = nom + 1
style = "color:red;"
html = (
html
+ """
<tr>
<td style="""
+ style
+ """'>"""
+ str(nom)
+ """</td>
<td style="""
+ style
+ """'>"""
+ indicators.time.strftime("%d.%m.%Y %H:%M")
+ """</td>
<td style="""
+ style
+ """'>"""
+ str(indicators.equipment)
+ """</td>
<td style="""
+ style
+ """'>"""
+ str(indicators.lat)
+ """</td>
<td style="""
+ style
+ """'>"""
+ str(indicators.lon)
+ """</td>
<td style="""
+ style
+ """'>"""
+ str(indicators.speed)
+ """</td>
</tr>"""
)
html = (
html
+ """
</tbody>
</table>
"""
)
return HttpResponse(html, content_type="application/text")
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url="/accounts/login/?next=")
@never_cache
def show_report_alarm_ToHTML(request):
try:
dict_param = request.POST.dict()
data_start = datetime.strptime(
dict_param["DataStart"] + " 00:00:00", "%Y-%m-%d %H:%M:%S"
)
data_stop = datetime.strptime(
dict_param["DataStop"] + " 23:59:59", "%Y-%m-%d %H:%M:%S"
)
myquery = Q()
myquery &= Q(time__range=[data_start, data_stop])
indicators_list = (
GtoAlarm.objects.filter(myquery)
.order_by("time")
.all()
.prefetch_related("equipment")
)
html = """
<table id = 'id_table' class='table table-bordered'>
<thead>
<tr>
<th style='width: 15px'>№</th>
<th>Дата</th>
<th>Объект</th>
<th>Тип события</th>
</tr>
</thead>
<tbody>
"""
nom = 0
for indicators in indicators_list:
nom = nom + 1
style = "color:black;"
html = (
html
+ """
<tr>
<td style="""
+ style
+ """'>"""
+ str(nom)
+ """</td>
<td style="""
+ style
+ """'>"""
+ indicators.time.strftime("%d.%m.%Y %H:%M")
+ """</td>
<td style="""
+ style
+ """'>"""
+ str(indicators.equipment)
+ """</td>
<td style="""
+ style
+ """'>"""
+ str(indicators.alarm_type)
+ """</td>
</tr>
"""
)
html = (
html
+ """
</tbody>
</table>
<br>
<br>
<br>
"""
)
return HttpResponse(html, content_type="application/text")
except Exception as err:
logging.error(traceback.format_exc())
def get_ajax(request):
try:
if request.method == "POST":
param = request.GET.dict()
type = 0
myquery = Q(active=True)
if "type" in param:
type = param["type"]
myquery &= Q(type=type)
sensor_list = AcsSensor.objects.filter(myquery).all().order_by("name")
m_sensor = []
for sensor in sensor_list:
sensor_dict = dict()
sensor_dict.update(sensor_id=sensor.id)
sensor_dict.update(value=sensor.value / sensor.ratio)
sensor_dict.update(critical_value=sensor.critical_value)
sensor_dict.update(unit=sensor.unit)
pecent = ((sensor.value / sensor.ratio) * 100) / sensor.critical_value
sensor_dict.update(pecent_value=pecent)
# sensor.critical_value
# color=0 зеленый
# color=1 желтый
# color=2 красный
color = "bg-success"
if sensor.critical_type == "max":
if sensor.value / sensor.ratio >= sensor.critical_value:
color = "bg-danger"
else:
if sensor.value / sensor.ratio <= sensor.critical_value:
color = "bg-danger"
sensor_dict.update(color=color)
m_sensor.append(sensor_dict)
return generalmodule.ReturnJson(200, m_sensor)
except Exception as err:
logging.error(traceback.format_exc())
data = dict()
data.update(status=-1)
return generalmodule.ReturnJson(200, data)
def MainIndexDefault(request):
if request.method == "GET":
position_list = (
BlockSensor.objects.values("position").order_by("position").distinct()
)
i = 0
for position in position_list:
i = i + 1
position_dict = dict()
position_dict.update(id=i)
position_dict.update(name=position["position"])
param = request.GET.dict()
type = 0
sensor_list = BlockSensor.objects.all().order_by("value").order_by("name")
m_sensor = []
for sensor in sensor_list:
str_value = str(sensor.value)
sensor_dict = dict()
sensor_dict.update(position=sensor.position)
sensor_dict.update(sensor=sensor)
sensor_dict.update(name=sensor.name)
sensor_dict.update(value=sensor.value)
sensor_dict.update(connect_time=sensor.connect_time)
sensor_dict.update(str_value=str_value)
m_sensor.append(sensor_dict)
context = {
"updatepage": True,
"sensor_list": sensor_list,
"m_sensor": m_sensor,
"type": int(type),
}
return render(request, "block_main.html", context)
@login_required(login_url="/accounts/login/?next=")
@never_cache
def sensor_ajax(request):
try:
if request.method == "POST":
sensor_dict = dict()
param = request.POST.dict()
sensor = AcsSensor.objects.filter(id=param["id"]).first()
critical_type = sensor.critical_type
connect_time = sensor.connect_time
value = sensor.value
end_date = sensor.connect_time
if param["sensor_type"] == "sec":
strftime = "%H:%M:%S"
start_date = end_date - timedelta(seconds=30)
elif param["sensor_type"] == "min":
strftime = "%H:%M"
start_date = end_date - timedelta(minutes=30)
else:
strftime = "%H:00"
start_date = end_date - timedelta(hours=30)
sensor_links = (
AcsIndicators.objects.filter(sensor=sensor)
.filter(date_time__range=[start_date, end_date])
.order_by("date_time")
.order_by("id")
)
strftimeend = "%d.%m.%Y %H"
m_sensor = []
value_old = 0
for i in range(31):
if param["sensor_type"] == "sec":
strftimeend = "%d.%m.%Y %H:%M:%S"
date_time = start_date + timedelta(seconds=i)
start_date_day = date_time
end_date_day = date_time + timedelta(milliseconds=1000)
elif param["sensor_type"] == "min":
strftimeend = "%d.%m.%Y %H:%M"
date_time = start_date + timedelta(minutes=i)
start_date_day = datetime(
date_time.year,
date_time.month,
date_time.day,
date_time.hour,
date_time.minute,
0,
)
end_date_day = datetime(
date_time.year,
date_time.month,
date_time.day,
date_time.hour,
date_time.minute,
59,
9999,
)
else:
strftimeend = "%d.%m.%Y %H"
date_time = start_date + timedelta(hours=i)
start_date_day = datetime(
date_time.year,
date_time.month,
date_time.day,
date_time.hour,
0,
0,
)
end_date_day = datetime(
date_time.year,
date_time.month,
date_time.day,
date_time.hour,
59,
59,
9999,
)
sensor_dict = dict()
sensor_dict.update(date_max=str(connect_time))
if critical_type == "max":
value_date = 0
else:
value_date = 9999999
result = sensor_links.filter(
date_time__range=[start_date_day, end_date_day]
).aggregate(Max("value"))
sensor_dict.update(date_time=date_time.strftime(strftime))
if result["value__max"] == None:
sensor_dict.update(value=value_old)
else:
value_old = result["value__max"] / sensor.ratio
sensor_dict.update(value=result["value__max"] / sensor.ratio)
m_sensor.append(sensor_dict)
return generalmodule.ReturnJson(200, m_sensor)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url="/accounts/login/?next=")
@never_cache
def report_value(request):
try:
if request.method == "GET":
context = generalmodule.get_context_template()
return render(request, "report/repor_speed.html", context)
if request.method == "POST":
dict_param = request.POST.dict()
if dict_param["metod"] == "create":
return show_report_value_ToHTML(request)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url="/accounts/login/?next=")
@never_cache
def report_alarm(request):
try:
if request.method == "GET":
context = generalmodule.get_context_template()
return render(request, "report/repor_alarm.html", context)
if request.method == "POST":
dict_param = request.POST.dict()
if dict_param["metod"] == "create":
return show_report_alarm_ToHTML(request)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url="/accounts/login/?next=")
@never_cache
def report_list(request):
try:
param = request.GET.dict()
if "name" in param:
name = param["name"]
if name == "reportspeed":
return report_value(request)
if name == "reportskuv":
return report_alarm(request)
context = generalmodule.get_context_template()
return render(request, "gto_report_list.html", context)
except Exception as err:
logging.error(traceback.format_exc())