Commit 9109ff15 authored by ZZH's avatar ZZH

hardware alarm set support mult lang 2024-06-04

parent 6f878baf
...@@ -733,14 +733,16 @@ PHASE_LINE_LANG = { ...@@ -733,14 +733,16 @@ PHASE_LINE_LANG = {
"en_US": "Phase B", "en_US": "Phase B",
"de_DE": "Phase B" "de_DE": "Phase B"
}, },
"C相": { "C相": {
"en_US": "Phase C", "en_US": "Phase C",
"de_DE": "Phase C" "de_DE": "Phase C"
}, },
"N线": { "N线": {
"en_US": "Neutral Line", "en_US": "Neutral Line",
"de_DE": "N-Leitung" "de_DE": "N-Leitung"
}, },
"漏电流": {
"en_US": "Leakage current",
"de_DE": "Elektrizität"
},
} }
...@@ -2,15 +2,12 @@ ...@@ -2,15 +2,12 @@
# #
# Author:jing # Author:jing
# Date: 2020/7/9 # Date: 2020/7/9
import json
from pot_libs.aiohttp_util.aiohttp_utils import AioHttpUtils
from pot_libs.mysql_util.mysql_util import MysqlUtil from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.common.components.responses import Success from pot_libs.common.components.responses import Success
from pot_libs.sanic_api import summary, examples from pot_libs.sanic_api import summary, examples
from pot_libs.logger import log from pot_libs.logger import log
from pot_libs.settings import SETTING from pot_libs.settings import SETTING
from pot_libs.utils.exc_util import BusinessException
from unify_api.constants import EVENT_TYPE_SYNC_DEVICE, RESIDUAL_CURRENT_OP from unify_api.constants import EVENT_TYPE_SYNC_DEVICE, RESIDUAL_CURRENT_OP
from unify_api.modules.alarm_manager.components.alarm_setting import ( from unify_api.modules.alarm_manager.components.alarm_setting import (
AlarmSettingUpdate, AlarmSettingUpdate,
...@@ -21,6 +18,9 @@ from unify_api.modules.alarm_manager.components.alarm_setting import ( ...@@ -21,6 +18,9 @@ from unify_api.modules.alarm_manager.components.alarm_setting import (
) )
from unify_api.modules.alarm_manager.service.alarm_setting_service import \ from unify_api.modules.alarm_manager.service.alarm_setting_service import \
post_update_alarm_emq_service post_update_alarm_emq_service
from unify_api.modules.common.dao.common_dao import load_user_lang
from unify_api.modules.common.procedures.multi_lang import load_e_type_name
from unify_api.constants import PHASE_LINE_LANG
@summary('获取某监测点告警设置列表') @summary('获取某监测点告警设置列表')
...@@ -30,6 +30,7 @@ async def post_point_alarm_setting(req, body: PointAlarmSettingRequest) \ ...@@ -30,6 +30,7 @@ async def post_point_alarm_setting(req, body: PointAlarmSettingRequest) \
point_id = body.point_id point_id = body.point_id
location_ids = body.location_ids location_ids = body.location_ids
enable = body.enable enable = body.enable
user_id = req.ctx.user_id
point_alarm_settings = [] point_alarm_settings = []
location_alarm_settings = [] location_alarm_settings = []
if enable in (0, 1): if enable in (0, 1):
...@@ -67,11 +68,18 @@ async def post_point_alarm_setting(req, body: PointAlarmSettingRequest) \ ...@@ -67,11 +68,18 @@ async def post_point_alarm_setting(req, body: PointAlarmSettingRequest) \
point_id,)) if point_id else {} point_id,)) if point_id else {}
res_location = await conn.fetchall(sql_location, args=( res_location = await conn.fetchall(sql_location, args=(
tuple(location_ids),)) if location_ids else {} tuple(location_ids),)) if location_ids else {}
lang = await load_user_lang(user_id)
for res in res_point: for res in res_point:
if lang != "zh_CN":
etype_name = load_e_type_name(res.get("etype"), lang)
else:
etype_name = res.get("name")
alarm_setting = AlarmSetting( alarm_setting = AlarmSetting(
id=res.get("id"), id=res.get("id"),
type=res.get("etype"), type=res.get("etype"),
name=res.get("name"), name=etype_name,
level=res.get("importance"), level=res.get("importance"),
threshold=res.get("threshold"), threshold=res.get("threshold"),
duration=res.get("duration", None), duration=res.get("duration", None),
...@@ -80,11 +88,18 @@ async def post_point_alarm_setting(req, body: PointAlarmSettingRequest) \ ...@@ -80,11 +88,18 @@ async def post_point_alarm_setting(req, body: PointAlarmSettingRequest) \
point_alarm_settings.append(alarm_setting) point_alarm_settings.append(alarm_setting)
for res in res_location: for res in res_location:
item, name = res.get("item"), res.get("name")
if lang != "zh_CN":
etype_name = load_e_type_name(res.get("etype"), lang)
if item != "default":
item_lang = PHASE_LINE_LANG.get(item, "")
etype_name = f"{item_lang}{etype_name}"
else:
etype_name = f"{item}{name}" if item != "default" else name
alarm_setting = AlarmSetting( alarm_setting = AlarmSetting(
id=res.get("id"), id=res.get("id"),
type=res.get("etype"), type=res.get("etype"),
name=(res.get("item") + res.get("name")) if res.get( name=etype_name,
"item") != "default" else res.get("name"),
level=res.get("importance"), level=res.get("importance"),
threshold=res.get("threshold"), threshold=res.get("threshold"),
duration=res.get("duration", None), duration=res.get("duration", None),
...@@ -94,7 +109,7 @@ async def post_point_alarm_setting(req, body: PointAlarmSettingRequest) \ ...@@ -94,7 +109,7 @@ async def post_point_alarm_setting(req, body: PointAlarmSettingRequest) \
log.exception(e) log.exception(e)
return PointAlarmSettingResponse().db_error() return PointAlarmSettingResponse().db_error()
residual_current_op = 0 residual_current_op = 0
user_id = req.ctx.user_id
if user_id in RESIDUAL_CURRENT_OP: if user_id in RESIDUAL_CURRENT_OP:
residual_current_op = 1 residual_current_op = 1
return PointAlarmSettingResponse( return PointAlarmSettingResponse(
......
# -*- coding:utf-8 -*-
import json import json
import time import time
from datetime import datetime, timedelta from datetime import datetime, timedelta
...@@ -34,6 +35,10 @@ from unify_api.modules.electric_optimization.dao.power_index import ( ...@@ -34,6 +35,10 @@ from unify_api.modules.electric_optimization.dao.power_index import (
from unify_api.utils.taos_new import parse_td_columns, get_td_table_name, \ from unify_api.utils.taos_new import parse_td_columns, get_td_table_name, \
td3_tbl_compate, get_td_engine_data td3_tbl_compate, get_td_engine_data
from unify_api.utils.time_format import CST from unify_api.utils.time_format import CST
from unify_api.constants import PHASE_LINE_LANG
from unify_api.modules.common.dao.common_dao import (
load_user_lang, load_monitor_names
)
async def other_info(cid): async def other_info(cid):
...@@ -142,40 +147,40 @@ async def normal_rate_of_location(cid): ...@@ -142,40 +147,40 @@ async def normal_rate_of_location(cid):
lids = list(loc_infos.keys()) lids = list(loc_infos.keys())
if not lids: if not lids:
return "100%", "100%" return "100%", "100%"
prefix = f"real_time:adio:{SETTING.mysql_db}" prefix = f"real_time:adio:{SETTING.mysql_db}"
keys = [f"{prefix}:{lid}" for lid in lids] keys = [f"{prefix}:{lid}" for lid in lids]
rt_rlts = await RedisUtils().mget(keys) rt_rlts = await RedisUtils().mget(keys)
rt_adios = [json.loads(r) for r in rt_rlts if r] rt_adios = [json.loads(r) for r in rt_rlts if r]
d_rt_adio = {adio["lid"]: adio for adio in rt_adios} d_rt_adio = {adio["lid"]: adio for adio in rt_adios}
now_ts = pendulum.now(tz=CST).int_timestamp now_ts = pendulum.now(tz=CST).int_timestamp
for lid, d_loc in loc_infos.items(): for lid, d_loc in loc_infos.items():
d_stats[d_loc["type"]]["total"] += 1 d_stats[d_loc["type"]]["total"] += 1
if lid not in d_rt_adio: if lid not in d_rt_adio:
continue continue
if not isinstance(d_loc["threshold"], (float, int)): if not isinstance(d_loc["threshold"], (float, int)):
continue continue
try: try:
d_adio = d_rt_adio[lid] d_adio = d_rt_adio[lid]
if (now_ts - d_adio["ts"]) > constants.REAL_EXP_TIME: if (now_ts - d_adio["ts"]) > constants.REAL_EXP_TIME:
log.warn(f"adio_current location_id={lid} has expire!") log.warn(f"adio_current location_id={lid} has expire!")
continue continue
if d_adio["v"] < d_loc["threshold"]: if d_adio["v"] < d_loc["threshold"]:
d_stats[d_loc["type"]]["normal"] += 1 d_stats[d_loc["type"]]["normal"] += 1
except Exception as e: except Exception as e:
log.exception(f"parse real time adio:{d_adio} exc, e:{e}") log.exception(f"parse real time adio:{d_adio} exc, e:{e}")
if d_stats["temperature"]["total"] == 0: if d_stats["temperature"]["total"] == 0:
temp_qr = "100%" temp_qr = "100%"
else: else:
norm = d_stats["temperature"]["normal"] norm = d_stats["temperature"]["normal"]
total = d_stats["temperature"]["total"] total = d_stats["temperature"]["total"]
temp_qr = str(round((norm / total) * 100, )) + "%" temp_qr = str(round((norm / total) * 100, )) + "%"
if d_stats["residual_current"]["total"] == 0: if d_stats["residual_current"]["total"] == 0:
rc_qr = "100%" rc_qr = "100%"
else: else:
...@@ -196,7 +201,7 @@ async def real_time_load(cid, end_dt=None): ...@@ -196,7 +201,7 @@ async def real_time_load(cid, end_dt=None):
tbl = get_td_table_name("electric", mtid) tbl = get_td_table_name("electric", mtid)
td_tbls.append(tbl) td_tbls.append(tbl)
td_tbls.append(f"s_{sid.lower()}_e") td_tbls.append(f"s_{sid.lower()}_e")
td_mt_tables = td3_tbl_compate(td_tbls) td_mt_tables = td3_tbl_compate(td_tbls)
if not end_dt: if not end_dt:
end_dt = pendulum.now(tz=CST) end_dt = pendulum.now(tz=CST)
...@@ -208,7 +213,7 @@ async def real_time_load(cid, end_dt=None): ...@@ -208,7 +213,7 @@ async def real_time_load(cid, end_dt=None):
is_succ, results = await get_td_engine_data(url, sql) is_succ, results = await get_td_engine_data(url, sql)
if not is_succ or not results: if not is_succ or not results:
return 0 return 0
head = parse_td_columns(results) head = parse_td_columns(results)
datas = [] datas = []
for res in results["data"]: for res in results["data"]:
...@@ -226,25 +231,36 @@ async def power_count_info(cid): ...@@ -226,25 +231,36 @@ async def power_count_info(cid):
now = datetime.now() now = datetime.now()
start_time = (now - timedelta(30)).strftime("%Y-%m-%d 00:00:00") start_time = (now - timedelta(30)).strftime("%Y-%m-%d 00:00:00")
end_time = now.strftime("%Y-%m-%d %H:%M:%S") end_time = now.strftime("%Y-%m-%d %H:%M:%S")
max_30d_load, _time = await load_pttl_max(cid, start_time, end_time, -1) max_30d_load, _time = await load_pttl_max(cid, start_time, end_time, -1)
cur_load = await real_time_load(cid) cur_load = await real_time_load(cid)
return round_2(cur_load), round_2(max_30d_load) return round_2(cur_load), round_2(max_30d_load)
async def get_max_aiao_of_filed(cid, start, end, filed="temperature"): async def load_aiao_max(user_id, cid, s_dts, e_dts, filed):
value_max, location_name, occur_time = None, None, None value_max, location_name, occur_time = None, None, None
sql = f"SELECT a.value_max,a.value_max_time,p.name,b.item FROM " \ sql = f"SELECT a.value_max,a.value_max_time,p.name,p.mtid,b.item FROM " \
f"`location_15min_aiao` a LEFT JOIN location b on a.lid=b.lid " \ f"`location_15min_aiao` a LEFT JOIN location b on a.lid=b.lid " \
f"LEFT JOIN point p on p.mtid=a.mtid where " \ f"LEFT JOIN point p on p.mtid=a.mtid where " \
f"a.create_time BETWEEN '{start}' and '{end}' and a.cid=%s " \ f"a.create_time BETWEEN '{s_dts}' and '{e_dts}' and a.cid=%s " \
f" and a.ad_type=%s order by a.value_max desc limit 1" f" and a.ad_type=%s order by a.value_max desc limit 1"
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
datas = await conn.fetchone(sql, args=(cid, filed)) datas = await conn.fetchone(sql, args=(cid, filed))
if datas: if datas:
lang = await load_user_lang(user_id)
mtid = datas["mtid"]
if lang != "zh_CN":
mtr_names = await load_monitor_names([mtid], lang)
mtr_name = mtr_names[mtid]
else:
mtr_name = datas["name"]
value_max = round(datas["value_max"], 2) value_max = round(datas["value_max"], 2)
item_name = '漏电流' if datas['item'] == 'default' else datas['item'] item_name = "漏电流" if datas['item'] == 'default' else datas['item']
location_name = f"{datas['name']}_{item_name}" if lang != "zh_CN":
item_name = PHASE_LINE_LANG.get(datas["item"], "")
location_name = f"{mtr_name}_{item_name}"
occur_time = datas.get("value_max_time") occur_time = datas.get("value_max_time")
occur_time = str(occur_time) if occur_time else None occur_time = str(occur_time) if occur_time else None
return MaxResidualCurrent( return MaxResidualCurrent(
...@@ -318,17 +334,17 @@ async def optimization_count_info(company_id: int): ...@@ -318,17 +334,17 @@ async def optimization_count_info(company_id: int):
:param company_id: :param company_id:
:return: :return:
""" """
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
sql = "SELECT inlid, `name` FROM inline WHERE cid=%s" sql = "SELECT inlid, `name` FROM inline WHERE cid=%s"
inlines = await conn.fetchall(sql, args=(company_id,)) inlines = await conn.fetchall(sql, args=(company_id,))
inline_ids = [inline["inlid"] for inline in inlines] inline_ids = [inline["inlid"] for inline in inlines]
now = datetime.now() now = datetime.now()
start_time = ( start_time = (
pendulum.datetime(now.year, now.month, 1) pendulum.datetime(now.year, now.month, 1)
.subtract(months=1) .subtract(months=1)
.strftime("%Y-%m-%d %H:%M:%S") .strftime("%Y-%m-%d %H:%M:%S")
) )
end_time = pendulum.datetime(now.year, now.month, 1).strftime( end_time = pendulum.datetime(now.year, now.month, 1).strftime(
"%Y-%m-%d %H:%M:%S") "%Y-%m-%d %H:%M:%S")
...@@ -352,7 +368,7 @@ async def optimization_count_info(company_id: int): ...@@ -352,7 +368,7 @@ async def optimization_count_info(company_id: int):
} }
) )
return count_info_map return count_info_map
now = datetime.now() now = datetime.now()
if now.month == 1: if now.month == 1:
last_month_dt = datetime(year=now.year - 1, month=12, day=1) last_month_dt = datetime(year=now.year - 1, month=12, day=1)
...@@ -372,7 +388,7 @@ async def optimization_count_info(company_id: int): ...@@ -372,7 +388,7 @@ async def optimization_count_info(company_id: int):
2, 2,
) )
total_pf_save = 0 if total_pf_save <= 0 else total_pf_save total_pf_save = 0 if total_pf_save <= 0 else total_pf_save
pf_kpi_x_list = [ pf_kpi_x_list = [
i["kpi_x"] for i in power_factor_results if i["kpi_x"] for i in power_factor_results if
type(i["kpi_x"]) in [int, float] type(i["kpi_x"]) in [int, float]
...@@ -388,19 +404,19 @@ async def optimization_count_info(company_id: int): ...@@ -388,19 +404,19 @@ async def optimization_count_info(company_id: int):
pf_desc = "空间适中" pf_desc = "空间适中"
else: else:
pf_desc = "空间较大" pf_desc = "空间较大"
count_info_map["power_factor"] = { count_info_map["power_factor"] = {
"save_charge": total_pf_save if pf_kpi_x != "" else "", "save_charge": total_pf_save if pf_kpi_x != "" else "",
"kpi_x": pf_kpi_x, "kpi_x": pf_kpi_x,
"desc": pf_desc, "desc": pf_desc,
} }
# 移峰填谷指数 # 移峰填谷指数
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
sql = "select `score`, `cost_save` from `algo_plsi_result` " \ sql = "select `score`, `cost_save` from `algo_plsi_result` " \
"where `inlid` in %s and `month` = %s" "where `inlid` in %s and `month` = %s"
pcvfs = await conn.fetchall(sql, args=(inline_ids, last_month_str)) pcvfs = await conn.fetchall(sql, args=(inline_ids, last_month_str))
pcvf_kpi_x_list = [i["score"] for i in pcvfs if pcvf_kpi_x_list = [i["score"] for i in pcvfs if
type(i["score"]) in [int, float]] type(i["score"]) in [int, float]]
pcvf_kpi_x = min(pcvf_kpi_x_list) if len(pcvf_kpi_x_list) else "" pcvf_kpi_x = min(pcvf_kpi_x_list) if len(pcvf_kpi_x_list) else ""
...@@ -408,7 +424,7 @@ async def optimization_count_info(company_id: int): ...@@ -408,7 +424,7 @@ async def optimization_count_info(company_id: int):
sum([i["cost_save"] for i in pcvfs if sum([i["cost_save"] for i in pcvfs if
i["cost_save"] and i["cost_save"] >= 0]), 2 i["cost_save"] and i["cost_save"] >= 0]), 2
) )
if pcvf_kpi_x == "": if pcvf_kpi_x == "":
pcvf_desc = "" pcvf_desc = ""
elif pcvf_kpi_x >= 90: elif pcvf_kpi_x >= 90:
...@@ -419,14 +435,14 @@ async def optimization_count_info(company_id: int): ...@@ -419,14 +435,14 @@ async def optimization_count_info(company_id: int):
pcvf_desc = "空间适中" pcvf_desc = "空间适中"
else: else:
pcvf_desc = "空间较大" pcvf_desc = "空间较大"
total_pcvf_save = 0 if total_pcvf_save <= 0 else total_pcvf_save total_pcvf_save = 0 if total_pcvf_save <= 0 else total_pcvf_save
count_info_map["pcvf"] = { count_info_map["pcvf"] = {
"save_charge": total_pcvf_save if pcvf_kpi_x != "" else "", "save_charge": total_pcvf_save if pcvf_kpi_x != "" else "",
"kpi_x": pcvf_kpi_x, "kpi_x": pcvf_kpi_x,
"desc": pcvf_desc, "desc": pcvf_desc,
} }
# 经济运行 # 经济运行
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
sql = "select `kpi_x`, `save_charge`, `mean_load_factor` " \ sql = "select `kpi_x`, `save_charge`, `mean_load_factor` " \
...@@ -462,13 +478,13 @@ async def optimization_count_info(company_id: int): ...@@ -462,13 +478,13 @@ async def optimization_count_info(company_id: int):
economic_desc = "空间适中" economic_desc = "空间适中"
else: else:
economic_desc = "空间较大" economic_desc = "空间较大"
count_info_map["power_save"] = { count_info_map["power_save"] = {
"save_charge": total_economic_save if economic_kpi_x != "" else "", "save_charge": total_economic_save if economic_kpi_x != "" else "",
"kpi_x": economic_kpi_x, "kpi_x": economic_kpi_x,
"desc": economic_desc, "desc": economic_desc,
} }
# 最大需量 # 最大需量
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
sql = ( sql = (
...@@ -479,7 +495,7 @@ async def optimization_count_info(company_id: int): ...@@ -479,7 +495,7 @@ async def optimization_count_info(company_id: int):
"where b.inlid in %s and a.month = %s and b.valid=1;" "where b.inlid in %s and a.month = %s and b.valid=1;"
) )
md_spaces = await conn.fetchall(sql, args=(inline_ids, last_month_str)) md_spaces = await conn.fetchall(sql, args=(inline_ids, last_month_str))
md_space_kpi_x_list = [i["kpi_x"] for i in md_spaces if md_space_kpi_x_list = [i["kpi_x"] for i in md_spaces if
type(i["kpi_x"]) in [int, float]] type(i["kpi_x"]) in [int, float]]
md_space_kpi_x = max(md_space_kpi_x_list) if len( md_space_kpi_x = max(md_space_kpi_x_list) if len(
...@@ -508,7 +524,7 @@ async def optimization_count_info(company_id: int): ...@@ -508,7 +524,7 @@ async def optimization_count_info(company_id: int):
"kpi_x": md_space_kpi_x, "kpi_x": md_space_kpi_x,
"desc": md_space_desc, "desc": md_space_desc,
} }
total_save_cost = 0 total_save_cost = 0
for _, item in count_info_map.items(): for _, item in count_info_map.items():
total_save_cost += ( total_save_cost += (
...@@ -517,12 +533,12 @@ async def optimization_count_info(company_id: int): ...@@ -517,12 +533,12 @@ async def optimization_count_info(company_id: int):
) )
save_percent = total_save_cost / month_charge if month_charge else "" save_percent = total_save_cost / month_charge if month_charge else ""
count_info_map["save_percent"] = save_percent count_info_map["save_percent"] = save_percent
# 计算最大需量 # 计算最大需量
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
sql = "select `price_md`,`price_tc` from `price_policy` where `cid`=%s" sql = "select `price_md`,`price_tc` from `price_policy` where `cid`=%s"
price_policy = await conn.fetchone(sql, args=(company_id,)) price_policy = await conn.fetchone(sql, args=(company_id,))
total_md_space_charge = sum( total_md_space_charge = sum(
[i["inline_md_charge"] for i in md_spaces if i["inline_md_charge"]]) [i["inline_md_charge"] for i in md_spaces if i["inline_md_charge"]])
total_md_space_p = ( total_md_space_p = (
...@@ -531,7 +547,7 @@ async def optimization_count_info(company_id: int): ...@@ -531,7 +547,7 @@ async def optimization_count_info(company_id: int):
else "" else ""
) )
count_info_map["md_space_p"] = total_md_space_p count_info_map["md_space_p"] = total_md_space_p
# 经济运行最低负载率 # 经济运行最低负载率
mean_load_factors = [ mean_load_factors = [
i["mean_load_factor"] for i in economic_operations if i["mean_load_factor"] for i in economic_operations if
...@@ -587,7 +603,7 @@ async def electric_use_info_points_sdu(start, end, points): ...@@ -587,7 +603,7 @@ async def electric_use_info_points_sdu(start, end, points):
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
results = await conn.fetchall(sql, args=(points, start, end, results = await conn.fetchall(sql, args=(points, start, end,
SDU_ALARM_LIST)) SDU_ALARM_LIST))
first_alarm_cnt = 0 first_alarm_cnt = 0
second_alarm_cnt = 0 second_alarm_cnt = 0
third_alarm_cnt = 0 third_alarm_cnt = 0
...@@ -598,15 +614,15 @@ async def electric_use_info_points_sdu(start, end, points): ...@@ -598,15 +614,15 @@ async def electric_use_info_points_sdu(start, end, points):
second_alarm_cnt += result["doc_count"] second_alarm_cnt += result["doc_count"]
elif result["importance"] == Importance.Third.value: elif result["importance"] == Importance.Third.value:
third_alarm_cnt += result["doc_count"] third_alarm_cnt += result["doc_count"]
alarm_score = (first_alarm_cnt * 2 + second_alarm_cnt * 1 + alarm_score = (first_alarm_cnt * 2 + second_alarm_cnt * 1 +
third_alarm_cnt * 0.5) / len(points) third_alarm_cnt * 0.5) / len(points)
if alarm_score >= 15: if alarm_score >= 15:
alarm_score = 15 alarm_score = 15
electric_use_score = get_electric_index(alarm_score) electric_use_score = get_electric_index(alarm_score)
log.info( log.info(
"point_len={} alarm_score={} electric_use_score={}".format( "point_len={} alarm_score={} electric_use_score={}".format(
len(points), alarm_score, electric_use_score len(points), alarm_score, electric_use_score
...@@ -627,16 +643,16 @@ async def optimization_count_info_new(company_id: int): ...@@ -627,16 +643,16 @@ async def optimization_count_info_new(company_id: int):
:param company_id: :param company_id:
:return: :return:
""" """
inlines = await get_inline_by_cid(company_id) inlines = await get_inline_by_cid(company_id)
inline_ids = [inline["inlid"] for inline in inlines] inline_ids = [inline["inlid"] for inline in inlines]
# 获取公司上月用电 # 获取公司上月用电
now = datetime.now() now = datetime.now()
es_start_time = ( es_start_time = (
pendulum.datetime(now.year, now.month, 1) pendulum.datetime(now.year, now.month, 1)
.subtract(months=1) .subtract(months=1)
.strftime("%Y-%m-%dT%H:%M:%S+08:00") .strftime("%Y-%m-%dT%H:%M:%S+08:00")
) )
es_end_time = pendulum.datetime(now.year, now.month, 1).strftime( es_end_time = pendulum.datetime(now.year, now.month, 1).strftime(
"%Y-%m-%dT%H:%M:%S+08:00") "%Y-%m-%dT%H:%M:%S+08:00")
...@@ -668,7 +684,7 @@ async def optimization_count_info_new(company_id: int): ...@@ -668,7 +684,7 @@ async def optimization_count_info_new(company_id: int):
last_month_dt = datetime(year=now.year, month=now.month - 1, day=1) last_month_dt = datetime(year=now.year, month=now.month - 1, day=1)
last_month_str = datetime.strftime(last_month_dt, "%Y-%m") last_month_str = datetime.strftime(last_month_dt, "%Y-%m")
# 功率因数 # 功率因数
power_factor_results = await get_power_factor_kpi(inline_ids, power_factor_results = await get_power_factor_kpi(inline_ids,
last_month_dt) last_month_dt)
total_pf_save = round( total_pf_save = round(
...@@ -681,7 +697,7 @@ async def optimization_count_info_new(company_id: int): ...@@ -681,7 +697,7 @@ async def optimization_count_info_new(company_id: int):
(i["name"], i["kpi_x"]) for i in power_factor_results if (i["name"], i["kpi_x"]) for i in power_factor_results if
type(i["kpi_x"]) in [int, float] type(i["kpi_x"]) in [int, float]
] ]
if len(pf_kpi_x_list): if len(pf_kpi_x_list):
pf_kpi_x_num = [pf_kpi[1] for pf_kpi in pf_kpi_x_list] pf_kpi_x_num = [pf_kpi[1] for pf_kpi in pf_kpi_x_list]
pf_kpi_x = min(pf_kpi_x_num) pf_kpi_x = min(pf_kpi_x_num)
...@@ -716,12 +732,12 @@ async def optimization_count_info_new(company_id: int): ...@@ -716,12 +732,12 @@ async def optimization_count_info_new(company_id: int):
pcvfs = await get_pcvf_kpi(inline_ids, last_month_str) pcvfs = await get_pcvf_kpi(inline_ids, last_month_str)
pcvf_kpi_x_list = [(i["name"], i["score"]) for i in pcvfs if pcvf_kpi_x_list = [(i["name"], i["score"]) for i in pcvfs if
type(i["score"]) in [int, float]] type(i["score"]) in [int, float]]
if len(pcvf_kpi_x_list): if len(pcvf_kpi_x_list):
pcvf_kpi_x_num = [pcvf_kpi[1] for pcvf_kpi in pcvf_kpi_x_list] pcvf_kpi_x_num = [pcvf_kpi[1] for pcvf_kpi in pcvf_kpi_x_list]
pcvf_kpi_x = min(pcvf_kpi_x_num) pcvf_kpi_x = min(pcvf_kpi_x_num)
pcvf_kpi_x_name = [] pcvf_kpi_x_name = []
if pcvf_kpi_x < 70: if pcvf_kpi_x < 70:
for index, kpi_num in enumerate(pcvf_kpi_x_num): for index, kpi_num in enumerate(pcvf_kpi_x_num):
if kpi_num < 70: if kpi_num < 70:
...@@ -735,7 +751,7 @@ async def optimization_count_info_new(company_id: int): ...@@ -735,7 +751,7 @@ async def optimization_count_info_new(company_id: int):
f"引入新能源,转移高峰电量至低谷" f"引入新能源,转移高峰电量至低谷"
else: else:
pcvf_desc = "平均电价处于较低水平,请继续保持" pcvf_desc = "平均电价处于较低水平,请继续保持"
else: else:
pcvf_kpi_x = "" pcvf_kpi_x = ""
pcvf_desc = "" pcvf_desc = ""
...@@ -753,7 +769,7 @@ async def optimization_count_info_new(company_id: int): ...@@ -753,7 +769,7 @@ async def optimization_count_info_new(company_id: int):
sum([i["cost_save"] for i in pcvfs if sum([i["cost_save"] for i in pcvfs if
i["cost_save"] and i["cost_save"] >= 0]), 2 i["cost_save"] and i["cost_save"] >= 0]), 2
) )
total_pcvf_save = 0 if total_pcvf_save <= 0 else total_pcvf_save total_pcvf_save = 0 if total_pcvf_save <= 0 else total_pcvf_save
count_info_map["pcvf"] = { count_info_map["pcvf"] = {
"save_charge": total_pcvf_save if pcvf_kpi_x != "" else "", "save_charge": total_pcvf_save if pcvf_kpi_x != "" else "",
...@@ -761,7 +777,7 @@ async def optimization_count_info_new(company_id: int): ...@@ -761,7 +777,7 @@ async def optimization_count_info_new(company_id: int):
"desc": pcvf_desc, "desc": pcvf_desc,
"space": pcvf_space "space": pcvf_space
} }
# 经济运行 # 经济运行
economic_operations = await get_economic_kpi(inline_ids, last_month_str) economic_operations = await get_economic_kpi(inline_ids, last_month_str)
economic_kpi_x_list = [ economic_kpi_x_list = [
...@@ -822,14 +838,14 @@ async def optimization_count_info_new(company_id: int): ...@@ -822,14 +838,14 @@ async def optimization_count_info_new(company_id: int):
"desc": economic_desc, "desc": economic_desc,
"space": econ_space "space": econ_space
} }
# 容量、需量价格 # 容量、需量价格
price_policy = await price_policy_by_cid(company_id) price_policy = await price_policy_by_cid(company_id)
price_md = price_policy["price_md"] if price_policy["price_md"] else 0 price_md = price_policy["price_md"] if price_policy["price_md"] else 0
price_tc = price_policy["price_tc"] if price_policy["price_tc"] else 0 price_tc = price_policy["price_tc"] if price_policy["price_tc"] else 0
# 最大需量 # 最大需量
md_spaces = await get_md_space(inline_ids, last_month_dt) md_spaces = await get_md_space(inline_ids, last_month_dt)
md_space_kpi_x_list = [i["kpi_x"] for i in md_spaces if md_space_kpi_x_list = [i["kpi_x"] for i in md_spaces if
type(i["kpi_x"]) in [int, float]] type(i["kpi_x"]) in [int, float]]
md_space_kpi_x = max(md_space_kpi_x_list) if len( md_space_kpi_x = max(md_space_kpi_x_list) if len(
...@@ -859,13 +875,13 @@ async def optimization_count_info_new(company_id: int): ...@@ -859,13 +875,13 @@ async def optimization_count_info_new(company_id: int):
md_space_tc_runtimes[index]["tc_runtime"] * price_tc >= \ md_space_tc_runtimes[index]["tc_runtime"] * price_tc >= \
price_md * item["inline_md_predict"]: price_md * item["inline_md_predict"]:
md_space_name.append(md_space_tc_runtimes[index]["name"]) md_space_name.append(md_space_tc_runtimes[index]["name"])
if len(md_space_name): if len(md_space_name):
md_space_desc = f"若次月负荷无较大变动,建议{'、'.join(md_space_name)}" \ md_space_desc = f"若次月负荷无较大变动,建议{'、'.join(md_space_name)}" \
f"选择按最大需量计费" f"选择按最大需量计费"
else: else:
md_space_desc = "不存在容改需空间" md_space_desc = "不存在容改需空间"
count_info_map["md_space"] = { count_info_map["md_space"] = {
"save_charge": total_md_space_save if md_space_kpi_x != "" else "", "save_charge": total_md_space_save if md_space_kpi_x != "" else "",
"kpi_x": md_space_kpi_x, "kpi_x": md_space_kpi_x,
...@@ -907,7 +923,7 @@ async def cid_alarm_importance_count(cid, start, end): ...@@ -907,7 +923,7 @@ async def cid_alarm_importance_count(cid, start, end):
point_list = [i["pid"] for i in monitor_point_list] point_list = [i["pid"] for i in monitor_point_list]
es_res = await sdu_alarm_importance_dao(start, end, point_list) es_res = await sdu_alarm_importance_dao(start, end, point_list)
es_res_key = {i["key"]: i for i in es_res} es_res_key = {i["key"]: i for i in es_res}
res_list = [] res_list = []
for info in monitor_point_list: for info in monitor_point_list:
name = info.get("name") name = info.get("name")
...@@ -923,7 +939,7 @@ async def cid_alarm_importance_count(cid, start, end): ...@@ -923,7 +939,7 @@ async def cid_alarm_importance_count(cid, start, end):
tmp_dic["second"] += b["doc_count"] tmp_dic["second"] += b["doc_count"]
elif b["key"] == Importance.Third.value: elif b["key"] == Importance.Third.value:
tmp_dic["third"] += b["doc_count"] tmp_dic["third"] += b["doc_count"]
tmp_dic["alarm_count"] = tmp_dic["first"] + tmp_dic["second"] + \ tmp_dic["alarm_count"] = tmp_dic["first"] + tmp_dic["second"] + \
tmp_dic["third"] tmp_dic["third"]
res_list.append(tmp_dic) res_list.append(tmp_dic)
......
import time # -*- coding:utf-8 -*-
from datetime import datetime, timedelta from datetime import datetime, timedelta
from aioredis import RedisError from aioredis import RedisError
...@@ -19,7 +19,7 @@ from unify_api.modules.home_page.components.count_info_proxy_cps import \ ...@@ -19,7 +19,7 @@ from unify_api.modules.home_page.components.count_info_proxy_cps import \
CountInfoProxyResp, IycResp, IycmResp, RtrResp, CmResp, ApcResp, AsiResp, \ CountInfoProxyResp, IycResp, IycmResp, RtrResp, CmResp, ApcResp, AsiResp, \
HsiResp, AiiResp HsiResp, AiiResp
from unify_api.modules.home_page.procedures.count_info_pds import ( from unify_api.modules.home_page.procedures.count_info_pds import (
get_max_aiao_of_filed, normal_rate_of_location, load_aiao_max, normal_rate_of_location,
other_info, other_info,
power_count_info, power_count_info,
electric_use_info, electric_use_info,
...@@ -27,71 +27,59 @@ from unify_api.modules.home_page.procedures.count_info_pds import ( ...@@ -27,71 +27,59 @@ from unify_api.modules.home_page.procedures.count_info_pds import (
cal_power_factor, cal_power_factor,
optimization_count_info, optimization_count_info_new optimization_count_info, optimization_count_info_new
) )
from unify_api.modules.home_page.service.count_info_service import \ from unify_api.modules.home_page.service.count_info_service import (
post_zd_info_factory_service, risk_cost_service, info_yang_chen_service, \ post_zd_info_factory_service, risk_cost_service, rank_type_ranking_service,
info_yang_chen_map_service, rank_type_ranking_service, \ condition_monitor_service, alarm_price_costtl_service,
condition_monitor_service, alarm_price_costtl_service, \
alarm_safe_index_service, all_index_info_service alarm_safe_index_service, all_index_info_service
)
from unify_api.modules.users.procedures.jwt_user import jwt_user
@summary("获取首页统计信息") @summary("获取首页统计信息")
async def post_count_info(request, body: CountInfoReq) -> CountInfoResp: async def post_count_info(request, body: CountInfoReq) -> CountInfoResp:
# 1. 获取company_id # 1. 获取company_id
company_id = body.cid cid = body.cid
# now_tt = time.time() user_id = jwt_user(request)
# start_dt = datetime.now() - timedelta(30) e_dts = str(datetime.now())
# start_tt = datetime_to_timestamp( s_dts = str(datetime.now() - timedelta(30))
# datetime(start_dt.year, start_dt.month, start_dt.day))
now_tt = str(datetime.now())
start_tt = str(datetime.now() - timedelta(30))
try: try:
field = "residual_current"
max_residual_current = await get_max_aiao_of_filed(company_id, max_rc = await load_aiao_max(user_id, cid, s_dts, e_dts, field)
start_tt, now_tt, field = "temperature"
"residual_current") max_temp = await load_aiao_max(user_id, cid, s_dts, e_dts, field)
max_temperature = await get_max_aiao_of_filed(company_id, start_tt,
now_tt, "temperature")
# 温度和漏电流实时达标率 # 温度和漏电流实时达标率
# temperature_qr, residual_current_qr = await normal_rate_of_location( temp_qr, rc_qr = await normal_rate_of_location(cid)
# company_id)
temperature_qr, residual_current_qr = await \
normal_rate_of_location(company_id)
# 今日报警数和累计安全运行天数 # 今日报警数和累计安全运行天数
# today_alarm_count, safe_run_days, alarm_count = await other_info( today_alarm_count, safe_run_days, alarm_count = await other_info(cid)
# company_id)
today_alarm_count, safe_run_days, alarm_count = await other_info(
company_id)
# 实时负荷和近30日最高负荷 # 实时负荷和近30日最高负荷
current_load, max_30d_load = await power_count_info(company_id) current_load, max_30d_load = await power_count_info(cid)
# 用电安全指数, 报警分, 近30天报警1,2,3级数目 # 用电安全指数, 报警分, 近30天报警1,2,3级数目
# electric_info = await electric_use_info(company_id) electric_info = await electric_use_info(cid)
electric_info = await electric_use_info(company_id)
# 昨日平均电价, 上月平均电价 # 昨日平均电价, 上月平均电价
yestoday_price, last_month_price = await power_charge_price( yestoday_price, last_month_price = await power_charge_price(cid)
company_id)
# 实时功率因数, 上月功率因数 # 实时功率因数, 上月功率因数
# cos_ttl, last_month_cos = await power_factor(company_id) cos_ttl, last_month_cos = await cal_power_factor(cid)
cos_ttl, last_month_cos = await cal_power_factor(company_id)
# 其实异常捕获这个东西最好是在框架内部做一次就够了 # 其实异常捕获这个东西最好是在框架内部做一次就够了
except (ElasticsearchException, MySQLError, RedisError) as e: except (ElasticsearchException, MySQLError, RedisError) as e:
log.exception(e) log.exception(e)
return CountInfoResp().db_error() return CountInfoResp().db_error()
except Exception as e: except Exception as e:
log.exception(e) log.exception(e)
return CountInfoResp().server_error() return CountInfoResp().server_error()
return CountInfoResp( return CountInfoResp(
max_residual_current=max_residual_current, max_residual_current=max_rc,
max_temperature=max_temperature, max_temperature=max_temp,
temperature_qr=temperature_qr, temperature_qr=temp_qr,
residual_current_qr=residual_current_qr, residual_current_qr=rc_qr,
today_alarm_count=today_alarm_count, today_alarm_count=today_alarm_count,
safe_run_days=safe_run_days, safe_run_days=safe_run_days,
current_load=current_load, current_load=current_load,
......
# -*- coding:utf-8 -*-
from collections import defaultdict from collections import defaultdict
from datetime import datetime from datetime import datetime
from pot_libs.logger import log from pot_libs.logger import log
from pot_libs.mysql_util.mysql_util import MysqlUtil from pot_libs.mysql_util.mysql_util import MysqlUtil
from unify_api.modules.common.procedures.points import point_to_mid from unify_api.modules.common.procedures.points import point_to_mid
from unify_api.modules.common.dao.common_dao import (
load_user_lang, load_monitor_names
)
async def get_company(company_id): async def get_company(company_id):
...@@ -164,19 +168,28 @@ async def get_user_hardware_info(cid, page_num, page_size): ...@@ -164,19 +168,28 @@ async def get_user_hardware_info(cid, page_num, page_size):
} }
async def get_user_hardware_info_new15(company_id, page_num, page_size): async def load_hardware_info(cid, pg, pg_size, user_id):
sql = "SELECT p.*,m.sid FROM `point` p left join monitor m " \ sql = "SELECT p.*, m.sid, m.mtid FROM `point` p left join monitor m " \
"on p.mtid=m.mtid where m.demolished=0 and p.cid=%s " \ "on p.mtid=m.mtid where m.demolished=0 and p.cid=%s " \
"ORDER BY p.create_time desc" "ORDER BY p.create_time desc"
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
datas = await conn.fetchall(sql=sql, args=(company_id,)) datas = await conn.fetchall(sql=sql, args=(cid,))
results = [] results = []
if page_num > 0 and page_size > 0: if pg > 0 and pg_size > 0:
start = (page_num - 1) * page_size start = (pg - 1) * pg_size
end = page_num * page_size end = pg * pg_size
else: else:
start, end = 0, 10 start, end = 0, 10
lang = await load_user_lang(user_id)
if lang != "zh_CN":
mtids = [r["mtid"] for r in datas]
mtr_names = await load_monitor_names(mtids, lang)
else:
mtr_names = {}
for data in datas: for data in datas:
mtid = data["mtid"]
high_or_low_side = "高压侧" if data["voltage_side"] == 1 else "低压侧" high_or_low_side = "高压侧" if data["voltage_side"] == 1 else "低压侧"
start_time = datetime.strftime( start_time = datetime.strftime(
datetime.fromtimestamp(data["create_time"]), "%Y-%m-%d %H:%M" datetime.fromtimestamp(data["create_time"]), "%Y-%m-%d %H:%M"
...@@ -185,8 +198,10 @@ async def get_user_hardware_info_new15(company_id, page_num, page_size): ...@@ -185,8 +198,10 @@ async def get_user_hardware_info_new15(company_id, page_num, page_size):
datetime.fromtimestamp(data["update_time"]), "%Y-%m-%d %H:%M" datetime.fromtimestamp(data["update_time"]), "%Y-%m-%d %H:%M"
) )
wiring_type = "两表法" if data["ctnum"] == 2 else "三表法" wiring_type = "两表法" if data["ctnum"] == 2 else "三表法"
name = data.get("name") or ''
mtr_name = name if lang == "zh_CN" else mtr_names.get(mtid, "")
results.append({ results.append({
"installed_location": data.get("name") or '', "installed_location": mtr_name,
"device_number": data.get("sid") or '', "device_number": data.get("sid") or '',
"device_type": data.get("device_type") or '', "device_type": data.get("device_type") or '',
"start_time": start_time, "start_time": start_time,
......
# -*- coding:utf-8 -*-
from pot_libs.sanic_api import summary from pot_libs.sanic_api import summary
from unify_api.modules.product_info.components.hardware_cps import ( from unify_api.modules.product_info.components.hardware_cps import (
HardwareInfoRespList, HardwareInfoReq, HardwareInfoCountResp, HardwareInfoRespList, HardwareInfoReq, HardwareInfoCountResp,
...@@ -5,30 +6,30 @@ from unify_api.modules.product_info.components.hardware_cps import ( ...@@ -5,30 +6,30 @@ from unify_api.modules.product_info.components.hardware_cps import (
HardwareInfoManResq, HardwareInfoListReq, HardwareInfoListResq HardwareInfoManResq, HardwareInfoListReq, HardwareInfoListResq
) )
from unify_api.modules.product_info.procedures.hardware_pds import ( from unify_api.modules.product_info.procedures.hardware_pds import (
company_available, get_user_hardware_info_new15, hardware_statistics company_available, load_hardware_info, hardware_statistics
) )
from pot_libs.logger import log from pot_libs.logger import log
from unify_api.modules.product_info.service.hardware_info import \ from unify_api.modules.product_info.service.hardware_info import \
hardware_info_sdu_service, hardware_list_sdu_service, \ hardware_info_sdu_service, hardware_list_sdu_service, \
hardware_info_management_service, hardware_info_list_manage_service hardware_info_management_service, hardware_info_list_manage_service
from unify_api.modules.common.procedures.cids import get_cids, get_proxy_cids from unify_api.modules.common.procedures.cids import get_cids, get_proxy_cids
from unify_api.modules.users.procedures.jwt_user import jwt_user
@summary("获取硬件信息") @summary("获取硬件信息")
async def post_hardware_info_list(request, async def post_hardware_info_list(request,
body: HardwareInfoReq) -> HardwareInfoRespList: body: HardwareInfoReq) -> HardwareInfoRespList:
company_id = body.cid cid = body.cid
page_size, page_num = body.page_size, body.page_num pg_size, pg = body.page_size, body.page_num
log.info( log.info(
f"post_hardware_info company_id={company_id}, page_size={page_size}, page_num={page_num}" f"post_hardware_info cid={cid}, page_size={pg_size}, page_num={pg}"
) )
comp_available = await company_available(company_id) comp_available = await company_available(cid)
if not comp_available: if not comp_available:
return HardwareInfoRespList.user_error() return HardwareInfoRespList.user_error()
# page_map = await get_user_hardware_info(company_id, page_num, page_size) user_id = jwt_user(request)
page_map = await get_user_hardware_info_new15(company_id, page_num, page_map = await load_hardware_info(cid, pg, pg_size, user_id)
page_size)
return HardwareInfoRespList(rows=page_map["rows"], total=page_map["total"]) return HardwareInfoRespList(rows=page_map["rows"], total=page_map["total"])
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment