fix: 更新所监测设备测点的total_production的除0问题2

This commit is contained in:
caoqianming 2024-05-13 18:25:23 +08:00
parent c2933a795a
commit 41370ee971
1 changed files with 77 additions and 70 deletions

View File

@ -15,7 +15,7 @@ from apps.fim.models import Fee
from apps.enm.services import translate_eval_formula
import logging
from server.settings import get_sysconfig
from django.db.models import F, Case, When
from django.db.models import F
from apps.wpm.services import get_pcoal_heat
from django.utils import timezone
from django.db.models import Max
@ -106,9 +106,9 @@ def cal_mpointstat_hour(mpointId: str, year: int, month: int, day: int, hour: in
mpoint = Mpoint.objects.get(id=mpointId)
mytz = tz.gettz(settings.TIME_ZONE)
dt = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=0, second=0, tzinfo=mytz) # 整点时间
dt_hour_p = dt - datetime.timedelta(hours=1) # 上个整点
dt_hour_n = dt + datetime.timedelta(hours=1) # 下个整点
if mpoint.material and mpoint.val_type in ["float", "int"]: # 如果计量的是物料 # 累计量 有的会清零,需要额外处理(还未做)
dt_hour_p= dt - datetime.timedelta(hours=1) # 上个整点
dt_hour_n= dt + datetime.timedelta(hours=1) # 下个整点
if mpoint.material and mpoint.val_type in ['float', 'int']: # 如果计量的是物料 # 累计量 有的会清零,需要额外处理(还未做)
params = {"mpoint": mpoint, "type": "hour"}
params["year"], params["month"], params["day"], params["hour"] = year, month, day, hour
val = 0
@ -117,13 +117,13 @@ def cal_mpointstat_hour(mpointId: str, year: int, month: int, day: int, hour: in
mrs0 = MpLogx.objects.filter(mpoint=mpoint, timex__gte=dt_hour_p, timex__lte=dt).order_by("timex")
mrs = MpLogx.objects.filter(mpoint=mpoint, timex__gte=dt, timex__lte=dt_hour_n).order_by("timex")
if mrs0.exists() and mrs.exists():
last_val = getattr(mrs.last(), f"val_{val_type}")
first_val = getattr(mrs0.last(), f"val_{val_type}")
last_val = getattr(mrs.last(), f'val_{val_type}')
first_val = getattr(mrs0.last(), f'val_{val_type}')
if last_val >= first_val:
val = last_val - first_val
else:
# 这里判断有可能清零了
max_val = max(mrs.aggregate(max=Max(f"val_{val_type}"))["max"], first_val)
max_val = max(mrs.aggregate(max=Max(f'val_{val_type}'))["max"], first_val)
val = max_val - first_val + last_val
elif mpoint.type == Mpoint.MT_COMPUTE and mpoint.formula:
formula = mpoint.formula
@ -139,61 +139,61 @@ def cal_mpointstat_hour(mpointId: str, year: int, month: int, day: int, hour: in
sum_dict_day = MpointStat.objects.filter(type="hour", mpoint=mpoint, year=year, month=month, day=day).aggregate(sum=Sum("val"))
params_day = {"type": "day", "mpoint": mpoint, "year": year, "month": month, "day": day}
ms_day, _ = MpointStat.objects.get_or_create(**params_day, defaults=params_day)
ms_day.val = sum_dict_day["sum"] if sum_dict_day["sum"] is not None else 0
ms_day.val = sum_dict_day['sum'] if sum_dict_day['sum'] is not None else 0
ms_day.save()
if cascade or day in [28, 29, 30, 31]:
sum_dict_month = MpointStat.objects.filter(type="day", mpoint=mpoint, year=year, month=month).aggregate(sum=Sum("val"))
params_month = {"type": "month", "mpoint": mpoint, "year": year, "month": month}
ms_month, _ = MpointStat.objects.get_or_create(**params_month, defaults=params_month)
ms_month.val = sum_dict_month["sum"] if sum_dict_month["sum"] is not None else 0
ms_month.val = sum_dict_month['sum'] if sum_dict_month['sum'] is not None else 0
ms_month.save()
if cascade or month == 12:
sum_dict_year = MpointStat.objects.filter(type="month", mpoint=mpoint, year=year).aggregate(sum=Sum("val"))
params_year = {"type": "year", "mpoint": mpoint, "year": year}
ms_year, _ = MpointStat.objects.get_or_create(**params_year, defaults=params_year)
ms_year.val = sum_dict_year["sum"] if sum_dict_year["sum"] is not None else 0
ms_year.val = sum_dict_year['sum'] if sum_dict_year['sum'] is not None else 0
ms_year.save()
mgroup = mpoint.mgroup
if mgroup:
sflog = get_sflog(mgroup, dt)
if sflog is None:
myLogger.error(f"{mgroup.name}--{dt}")
year_s, month_s, day_s = sflog.get_ymd
sflog = get_sflog(mgroup, dt)
if sflog is None:
myLogger.error(f'{mgroup.name}--{dt}')
year_s, month_s, day_s = sflog.get_ymd
params_hour_s = {
"type": "hour_s",
"mpoint": mpoint,
"sflog": sflog,
"mgroup": mgroup,
"year": year,
"month": month,
"day": day,
"year_s": year_s,
"month_s": month_s,
"day_s": day_s,
"hour": hour,
}
ms_hour_s, _ = MpointStat.objects.get_or_create(**params_hour_s, defaults=params_hour_s)
ms_hour_s.val = ms.val
ms_hour_s.save()
params_hour_s = {
"type": "hour_s",
"mpoint": mpoint,
"sflog": sflog,
"mgroup": mgroup,
"year": year,
"month": month,
"day": day,
"year_s": year_s,
"month_s": month_s,
"day_s": day_s,
"hour": hour,
}
ms_hour_s, _ = MpointStat.objects.get_or_create(**params_hour_s, defaults=params_hour_s)
ms_hour_s.val = ms.val
ms_hour_s.save()
# 开始往上计算
sum_dict_sflog_s = MpointStat.objects.filter(type="hour_s", mpoint=mpoint, year_s=year_s, month_s=month_s, day_s=day_s, sflog=sflog).aggregate(sum=Sum("val"))
params_sflog_s = {"type": "sflog", "mpoint": mpoint, "sflog": sflog, "year_s": year_s, "month_s": month_s, "day_s": day_s, "mgroup": mgroup}
ms_sflog_s, _ = MpointStat.objects.get_or_create(**params_sflog_s, defaults=params_sflog_s)
ms_sflog_s.val = sum_dict_sflog_s["sum"] if sum_dict_sflog_s["sum"] is not None else 0
ms_sflog_s.save()
# 开始往上计算
sum_dict_sflog_s = MpointStat.objects.filter(type="hour_s", mpoint=mpoint, year_s=year_s, month_s=month_s, day_s=day_s, sflog=sflog).aggregate(sum=Sum("val"))
params_sflog_s = {"type": "sflog", "mpoint": mpoint, "sflog": sflog, "year_s": year_s, "month_s": month_s, "day_s": day_s, "mgroup": mgroup}
ms_sflog_s, _ = MpointStat.objects.get_or_create(**params_sflog_s, defaults=params_sflog_s)
ms_sflog_s.val = sum_dict_sflog_s['sum'] if sum_dict_sflog_s['sum'] is not None else 0
ms_sflog_s.save()
# next_cal_dict = [mpoint.material.id, sflog.id, year, month, day, hour, year_s, month_s, day_s]
# if next_cal_dict == cache.get('enm_cal_dict', None):
# next_cal = 0
# else:
# next_cal = 1
# cache.set('enm_cal_dict', next_cal_dict, 60)
cal_mpointstat_manual(mpoint.id, sflog.id, mgroup.id, year, month, day, hour, year_s, month_s, day_s, 0)
# next_cal_dict = [mpoint.material.id, sflog.id, year, month, day, hour, year_s, month_s, day_s]
# if next_cal_dict == cache.get('enm_cal_dict', None):
# next_cal = 0
# else:
# next_cal = 1
# cache.set('enm_cal_dict', next_cal_dict, 60)
cal_mpointstat_manual(mpoint.id, sflog.id, mgroup.id, year, month, day, hour, year_s, month_s, day_s, 0)
@shared_task(base=CustomTask)
@ -217,12 +217,12 @@ def cal_mpointstats(is_now=1, year=None, month=None, day=None, hour=None, m_code
mpoints_related = Mpoint.objects.none()
code2 = []
for code in m_code_list:
mpoints_related = mpoints_related | Mpoint.objects.filter(type=Mpoint.MT_COMPUTE, enabled=True, material__isnull=False, formula__contains="{" + code + "}")
code2.extend(mpoints_related.values_list("code", flat=True))
mpoints_related = mpoints_related | Mpoint.objects.filter(type=Mpoint.MT_COMPUTE, enabled=True, material__isnull=False, formula__contains='{' + code + '}')
code2.extend(mpoints_related.values_list('code', flat=True))
code2 = list(set(code2))
for code in code2:
mpoints_related = mpoints_related | Mpoint.objects.filter(type=Mpoint.MT_COMPUTE, enabled=True, material__isnull=False, formula__contains="{" + code + "}")
mpoints_related = mpoints_related.distinct().order_by("report_sortstr", "create_time")
mpoints_related = mpoints_related | Mpoint.objects.filter(type=Mpoint.MT_COMPUTE, enabled=True, material__isnull=False, formula__contains='{' + code + '}')
mpoints_related = mpoints_related.distinct().order_by('report_sortstr', 'create_time')
for item in mpoints_related:
cal_mpointstat_hour(item.id, year, month, day, hour)
else:
@ -234,7 +234,7 @@ def cal_mpointstats(is_now=1, year=None, month=None, day=None, hour=None, m_code
cal_mpointstat_hour(item.id, year, month, day, hour)
# 再统计计算测点
mpoints_compute = Mpoint.objects.filter(type=Mpoint.MT_COMPUTE, enabled=True, material__isnull=False).exclude(formula="").order_by("report_sortstr", "create_time")
mpoints_compute = Mpoint.objects.filter(type=Mpoint.MT_COMPUTE, enabled=True, material__isnull=False).exclude(formula="").order_by('report_sortstr', 'create_time')
# mpoints_other_group = []
for item in mpoints_compute:
# mpoints_other_group.append(cal_mpointstat_hour.s(item.id, year, month, day, hour))
@ -275,19 +275,19 @@ def cal_mpointstat_manual(mpointId: str, sflogId: str, mgroupId: str, year: int,
sum_dict_day_s = MpointStat.objects.filter(type="sflog", mpoint=mpoint, year_s=year_s, month_s=month_s, day_s=day_s, mgroup=mgroup).aggregate(sum=Sum("val"))
params_day_s = {"type": "day_s", "mpoint": mpoint, "year_s": year_s, "month_s": month_s, "day_s": day_s, "mgroup": mgroup}
ms_day_s, _ = MpointStat.objects.get_or_create(**params_day_s, defaults=params_day_s)
ms_day_s.val = sum_dict_day_s["sum"] if sum_dict_day_s["sum"] is not None else 0
ms_day_s.val = sum_dict_day_s['sum'] if sum_dict_day_s['sum'] is not None else 0
ms_day_s.save()
sum_dict_month_s = MpointStat.objects.filter(type="day_s", mpoint=mpoint, year_s=year_s, month_s=month_s, mgroup=mgroup).aggregate(sum=Sum("val"))
params_month_s = {"type": "month_s", "mpoint": mpoint, "year_s": year_s, "month_s": month_s, "mgroup": mgroup}
ms_month_s, _ = MpointStat.objects.get_or_create(**params_month_s, defaults=params_month_s)
ms_month_s.val = sum_dict_month_s["sum"] if sum_dict_month_s["sum"] is not None else 0
ms_month_s.val = sum_dict_month_s['sum'] if sum_dict_month_s['sum'] is not None else 0
ms_month_s.save()
sum_dict_year_s = MpointStat.objects.filter(type="month_s", mpoint=mpoint, year_s=year_s, mgroup=mgroup).aggregate(sum=Sum("val"))
params_year_s = {"type": "year_s", "mpoint": mpoint, "year_s": year_s, "mgroup": mgroup}
ms_year_s, _ = MpointStat.objects.get_or_create(**params_year_s, defaults=params_year_s)
ms_year_s.val = sum_dict_year_s["sum"] if sum_dict_year_s["sum"] is not None else 0
ms_year_s.val = sum_dict_year_s['sum'] if sum_dict_year_s['sum'] is not None else 0
ms_year_s.save()
if next_cal: # 计算工段级数据,手动录入时调用
@ -441,10 +441,15 @@ def cal_enstat(type, sflogId, mgroupId, year, month, day, hour, year_s, month_s,
enstat.other_cost_data = other_cost_data
enstat.production_cost_unit = imaterial_cost_unit + other_cost_unit
enstat.save()
if mgroup.cate == "section":
if mgroup.cate == 'section':
# 更新所监测设备测点的total_production
total_production = enstat.total_production
if total_production == 0:
elec_consume_unit = 0
else:
elec_consume_unit = F("val") / total_production
MpointStat.objects.filter(mgroup=enstat.mgroup, mpoint__material__code="elec").exclude(mpoint__ep_monitored=None).update(
total_production=enstat.total_production, elec_consume_unit=Case(When(total_production__gt=0, then=F("val") / F("total_production")), default=0)
total_production=total_production, elec_consume_unit=elec_consume_unit
)
if enstat.mgroup.cate == "section":
if "material" in this_cal_attrs:
@ -475,7 +480,7 @@ def cal_enstat(type, sflogId, mgroupId, year, month, day, hour, year_s, month_s,
if enstat.type in ["hour_s", "day_s", "year_s", "month_s"]:
pre_enstat = EnStat.objects.filter(type=enstat.type, year_s=enstat.year_s, month_s=enstat.month_s, day_s=enstat.day_s, hour=enstat.hour, mgroup__name="原料磨").first()
if pre_enstat:
enstat.celec_consume_unit = enstat.elec_consume_unit + get_sysconfig("enm.enm_lhxs") * pre_enstat.elec_consume_unit
enstat.celec_consume_unit = enstat.elec_consume_unit + get_sysconfig('enm.enm_lhxs') * pre_enstat.elec_consume_unit
enstat.save()
# 算总煤耗
@ -510,7 +515,7 @@ def cal_enstat(type, sflogId, mgroupId, year, month, day, hour, year_s, month_s,
# 综合能耗
enstat.cen_consume_unit = enstat.elec_consume_unit * 0.1229 + 0.7 * pre_enstat.cen_consume_unit
enstat.save()
elif enstat.mgroup.name == "余热发电":
elif enstat.mgroup.name == '余热发电':
pre_enstat = EnStat.objects.filter(type=enstat.type, year_s=enstat.year_s, month_s=enstat.month_s, day_s=enstat.day_s, hour=enstat.hour, mgroup__name="回转窑").first()
if pre_enstat:
# 吨熟料发电量
@ -564,7 +569,9 @@ def get_total_hour_now_and_shut_hour(enstat: EnStat):
)
return res["sum1"] if res["sum1"] else 0, res["sum2"] if res["sum2"] else 0
elif enstat.type == "month_st":
res = SfLog.objects.filter(work_date__year=enstat.year_s, work_date__month=enstat.month_s, mgroup=enstat.mgroup, team=enstat.team).aggregate(sum1=Sum("total_hour_now"), sum2=Sum("shut_hour"))
res = SfLog.objects.filter(work_date__year=enstat.year_s, work_date__month=enstat.month_s, mgroup=enstat.mgroup, team=enstat.team).aggregate(
sum1=Sum("total_hour_now"), sum2=Sum("shut_hour")
)
return res["sum1"] if res["sum1"] else 0, res["sum2"] if res["sum2"] else 0
elif enstat.type == "month_s":
res = SfLog.objects.filter(work_date__year=enstat.year_s, work_date__month=enstat.month_s, mgroup=enstat.mgroup).aggregate(sum1=Sum("total_hour_now"), sum2=Sum("shut_hour"))
@ -630,8 +637,8 @@ def cal_enstat2(type: str, year_s: int, month_s: int, day_s: int, cascade=True):
# 全厂电量
# 全厂的耗电量和水量都得单独处理
use_mpoint_elec_val = False
mp_elecs = Mpoint.objects.filter(material__code="elec", code__endswith="__all")
if mp_elecs.exists(): #
mp_elecs = Mpoint.objects.filter(material__code="elec", code__endswith='__all')
if mp_elecs.exists(): #
use_mpoint_elec_val = True
if type == "month_s":
enstat_qs = EnStat.objects.filter(type="month_s", year_s=year_s, month_s=month_s)
@ -641,15 +648,15 @@ def cal_enstat2(type: str, year_s: int, month_s: int, day_s: int, cascade=True):
sum1=Sum("elec_consume"), sum2=Sum("elec_coal_consume"), sum3=Sum("pcoal_consume"), sum4=Sum("pcoal_coal_consume"), sum5=Sum("water_consume"), sum6=Sum("cair_consume")
)
if use_mpoint_elec_val:
if type == "day_s":
enstat2.elec_consume = MpointStat.objects.filter(type="day", mpoint__in=mp_elecs, year=year_s, month=month_s, day=day_s).aggregate(sum=Sum("val"))["sum"]
elif type == "month_s":
enstat2.elec_consume = MpointStat.objects.filter(type="month", mpoint__in=mp_elecs, year=year_s, month=month_s).aggregate(sum=Sum("val"))["sum"]
if type == 'day_s':
enstat2.elec_consume = MpointStat.objects.filter(type='day', mpoint__in=mp_elecs, year=year_s, month=month_s, day=day_s).aggregate(sum=Sum("val"))['sum']
elif type == 'month_s':
enstat2.elec_consume = MpointStat.objects.filter(type='month', mpoint__in=mp_elecs, year=year_s, month=month_s).aggregate(sum=Sum("val"))['sum']
if enstat2.elec_consume is None:
enstat2.elec_consume = 0
else:
enstat2.elec_consume = res_elec_pcoal["sum1"] if res_elec_pcoal["sum1"] else 0
enstat2.elec_coal_consume = enstat2.elec_consume * 0.1229 / 1000
# 其他的统计工段合就行
@ -751,11 +758,11 @@ def enm_alarm(year_s: int, month_s: int, day_s: int):
@shared_task(base=CustomTask)
def king_insert_mplogx():
mpoint_codes = Mpoint.objects.filter(enabled=True, type=Mpoint.MT_AUTO, code__startswith="K_").values_list("code", flat=True)
mpoint_codes = Mpoint.objects.filter(enabled=True, type=Mpoint.MT_AUTO, code__startswith='K_').values_list('code', flat=True)
ml = []
for m in mpoint_codes:
ml.append({"N": m.replace("K_", "")})
_, res = kingClient.request(**kapis["read_batchtagrealvalue"], json={"objs": ml})
ml.append({"N": m.replace('K_', '')})
_, res = kingClient.request(**kapis['read_batchtagrealvalue'], json={"objs": ml})
insert_mplogx_from_king_rest_chunk(res)
@ -763,12 +770,12 @@ def king_insert_mplogx():
def check_mpoint_offline(seconds=100):
"""监测测点采集掉线"""
now = localtime()
for mpoint in Mpoint.objects.filter(enabled=True, type=Mpoint.MT_AUTO) | Mpoint.objects.filter(enabled=True, type=Mpoint.MT_COMPUTE, is_rep_ep_running_state=True):
for mpoint in Mpoint.objects.filter(enabled=True, type=Mpoint.MT_AUTO)| Mpoint.objects.filter(enabled=True, type=Mpoint.MT_COMPUTE, is_rep_ep_running_state=True):
mc = MpointCache(mpoint.code)
mpoint_data = mc.data
last_data = mpoint_data.get("last_data", None)
last_data = mpoint_data.get('last_data', None)
is_offline = True
if last_data and last_data["last_timex"] and (now - last_data["last_timex"]).total_seconds() < seconds:
if last_data and last_data['last_timex'] and (now-last_data['last_timex']).total_seconds() < seconds:
is_offline = False
if is_offline:
mc.set_fail(-2, now)
mc.set_fail(-2, now)