Commit fd3450a0 authored by lcn's avatar lcn

修改安电管理版

parent 91a67783
......@@ -473,4 +473,7 @@ ELECTRIC_PARAM_MAP = {
"unbalanceI", # 三相电流不平衡度
"unbalanceU", # 三相电压不平衡度
"overPR"
}
\ No newline at end of file
}
CST = "Asia/Shanghai"
\ No newline at end of file
......@@ -67,7 +67,7 @@ async def new_list_alarm_service(cid, storeys, offset, page_size, start, end,
url = None
redirect_type = ""
cid = int(res.get("cid")) if res.get("cid") else res.get("cid")
storey_name = point_storey_map[point_id]["storey_name"]
room_name = point_storey_map[point_id]["room_name"]
alarm = Alarm(
......@@ -138,14 +138,14 @@ async def list_alarm_zdu_service(cid, point_list, page_num, page_size, start,
"""报警信息分页列表"""
if not point_list or not event_type or not importance:
return ListAlarmResponse(total=0, rows=[])
# # 1. es查询结果
# es_res = await list_alarm_zdu_dao(cid, point_list, page_num, page_size,
# start, end, importance, event_type)
results = await list_alarm_zdu_dao_new15(cid, point_list, start, end,
importance, event_type)
real_total = len(results)
results = results[(page_num-1)*page_size, page_num*page_size]
results = results[(page_num - 1) * page_size, page_num * page_size]
# 2. 获取工厂, 报警type对应的描述信息
event_dic = await company_extend_dao(cid)
event_dic_map = {event["key"]: event for event in event_dic}
......@@ -171,7 +171,7 @@ async def list_alarm_zdu_service(cid, point_list, page_num, page_size, start,
else:
url = None
redirect_type = ""
alarm = Alarm(
name=res.get("name"),
importance=res.get("importance"),
......@@ -187,7 +187,7 @@ async def list_alarm_zdu_service(cid, point_list, page_num, page_size, start,
content=res.get("message"),
)
rows.append(alarm)
total = real_total if real_total < constants.ES_TOTAL_LIMIT \
else constants.ES_TOTAL_LIMIT
return ListAlarmResponse(total=total, rows=rows)
......@@ -225,7 +225,7 @@ async def wx_list_alarm_zdu_service(cid, point_list, start, end):
else:
url = None
redirect_type = ""
alarm = Alarm(
name=source.get("name"),
importance=source.get("importance"),
......@@ -241,7 +241,7 @@ async def wx_list_alarm_zdu_service(cid, point_list, start, end):
content=source.get("message"),
)
rows.append(alarm)
# total小程序不分页, 返回了但是不用
total = es_res["hits"]["total"]
return ListAlarmResponse(total=total, rows=rows)
......@@ -253,7 +253,10 @@ async def list_alarm_service_new15(cid, point_id, start, end, importance,
if point_id:
li.append(f"pid={point_id}")
else:
li.append(f"cid={cid}")
if not isinstance(cid, list):
cid = [cid]
cid_where = str(tuple(cid)).replace(",)", ")")
li.append(f"cid in {cid_where}")
if start and end:
li.append(f"event_datetime BETWEEN '{start}' and '{end}'")
if importance:
......@@ -270,7 +273,7 @@ async def list_alarm_service_new15(cid, point_id, start, end, importance,
li.append(f"event_type in {str(tuple(alarm_type)).strip(',')}")
mid_sql = " and ".join(li)
total = await get_total_list_alarm_dao(mid_sql)
mid_sql2 = " and ".join(["point_1min_event."+i for i in li])
mid_sql2 = " and ".join(["point_1min_event." + i for i in li])
datas = await get_list_alarm_dao(mid_sql2, page_size, page_num)
rows = []
for data in datas:
......@@ -279,7 +282,10 @@ async def list_alarm_service_new15(cid, point_id, start, end, importance,
type_str = constants.EVENT_TYPE_MAP.get(event_type)
location_id = data.get("lid")
es_id = data.get("id")
if location_id and (event_type in constants.TEMP_SCOPE_URL_TYPE):
if point_id and data.get("event_mode") == "scope":
url = "/scope_details?doc_id=%s" % es_id
redirect_type = "scope"
elif location_id and type in constants.TEMP_SCOPE_URL_TYPE:
url = "/temp_trend?doc_id=%s" % es_id
redirect_type = "temp_trend"
else:
......@@ -300,4 +306,4 @@ async def list_alarm_service_new15(cid, point_id, start, end, importance,
company_name=data.get("fullname") or '',
)
rows.append(alarm)
return ListAlarmResponse(total=total, rows=rows)
\ No newline at end of file
return ListAlarmResponse(total=total, rows=rows)
......@@ -18,6 +18,7 @@ from unify_api.modules.alarm_manager.service.list_alarm_service import \
wx_list_alarm_zdu_service, list_alarm_service_new15
from unify_api.modules.common.procedures.cids import get_cid_info, get_cids, \
get_proxy_cids
from unify_api.modules.users.procedures.jwt_user import jwt_user
from unify_api.utils import time_format
from unify_api import constants
from pot_libs.common.components.query import PageRequest, Equal, Range, Filter, \
......@@ -55,7 +56,31 @@ async def post_list_alarm(req, body: PageRequest) -> ListAlarmResponse:
alarm_type = in_group.group
elif in_group.field == 'importance':
importance = in_group.group
return await list_alarm_service_new15(cid, point_id, start, end,
cids = []
if req.json.get("product") == Product.AndianUManage.value:
proxy_id = req.json.get("proxy_id")
product = req.json.get("product")
user_id = jwt_user(req)
req_cids = req.json.get("cids")
# cids = await get_cids(user_id, product)
proxy_cids = await get_proxy_cids(user_id, product, proxy_id)
cids = list(set(req_cids) & set(proxy_cids))
if req.json.get("product") in [Product.RecognitionElectric.value,
Product.IntelligentU.value]:
if not cid:
product = req.json.get("product")
user_id = jwt_user(req)
cids = await get_cids(user_id, product)
else:
cids = [cid]
if not cids and cid:
cids = [cid]
if not cids:
raise BusinessException(message=f"你没有工厂权限")
return await list_alarm_service_new15(cids, point_id, start, end,
importance, page_size, page_num,
alarm_type)
......@@ -77,19 +102,19 @@ async def post_list_alarm_bak(req, body: PageRequest) -> ListAlarmResponse:
ranges = [_range]
else:
ranges = []
# TODO:当没有选择监测点的时候,需要从req取cid,作为筛选条件
if req.json.get("cid"):
cid = req.json["cid"]
equal = Equal(field="cid", value=cid)
body.filter.equals.append(equal)
if req.json.get("product") == Product.AndianUManage.value:
proxy_id = req.json.get("proxy_id")
product = req.json.get("product")
user_id = req.ctx.user_id
req_cids = req.json.get("cids")
# cids = await get_cids(user_id, product)
cids = await get_proxy_cids(user_id, product, proxy_id)
if req_cids:
......@@ -100,7 +125,7 @@ async def post_list_alarm_bak(req, body: PageRequest) -> ListAlarmResponse:
else:
in_group = InGroup(field="cid", group=cids)
body.filter.in_groups.append(in_group)
if req.json.get("product") in [Product.RecognitionElectric.value,
Product.IntelligentU.value]:
req_cid = req.json.get("cid")
......@@ -112,14 +137,14 @@ async def post_list_alarm_bak(req, body: PageRequest) -> ListAlarmResponse:
cids = [req_cid]
in_group = InGroup(field="cid", group=cids)
body.filter.in_groups.append(in_group)
filter = Filter(
equals=body.filter.equals,
ranges=ranges,
in_groups=body.filter.in_groups,
keywords=body.filter.keywords,
)
# 重新封装PageRequest
page_request = PageRequest(
page_size=body.page_size, page_num=body.page_num, sort=body.sort,
......@@ -127,7 +152,8 @@ async def post_list_alarm_bak(req, body: PageRequest) -> ListAlarmResponse:
)
query_body = EsQuery().query(page_request)
if not query_body.get("query"):
query = {"bool": {"must_not": [{"terms": {"mode.keyword": ["scope"]}}]}}
query = {
"bool": {"must_not": [{"terms": {"mode.keyword": ["scope"]}}]}}
query_body["query"] = query
else:
must_not = [{"terms": {"mode.keyword": ["scope"]}}]
......@@ -140,7 +166,7 @@ async def post_list_alarm_bak(req, body: PageRequest) -> ListAlarmResponse:
log.warning(
"Can not find data on es(index: %s): %s" % (index, query_body))
raise DBException
cid_info_map = await get_cid_info(all=True)
rows = []
for info in es_results["hits"]["hits"]:
......@@ -181,7 +207,7 @@ async def post_list_alarm_bak(req, body: PageRequest) -> ListAlarmResponse:
company_name=cid_info_map.get(cid, {}).get("fullname", ""),
)
rows.append(alarm)
real_total = es_results["hits"]["total"]
total = real_total if real_total < constants.ES_TOTAL_LIMIT else constants.ES_TOTAL_LIMIT
return ListAlarmResponse(total=total, rows=rows)
......@@ -206,7 +232,6 @@ async def post_new_list_alarm(req, body: NlaReq) -> ListAlarmResponse:
product)
@summary("小程序消息列表")
async def post_wx_list_alarm(req, body: WlaReq) -> ListAlarmResponse:
# 1. 获取参数
......
......@@ -21,26 +21,26 @@ async def get_points(company_ids):
company_point_ids_map = defaultdict(list)
for point in points:
company_point_ids_map[point["cid"]].append(point["pid"])
point_map = {i["pid"]: i for i in points}
point_ids = list(point_map.keys())
pid_field, start_time_field = "pid", "start_time"
sql = f"SELECT pid, mid FROM change_meter_record WHERE pid in %s ORDER BY {pid_field}, {start_time_field}"
records = await conn.fetchall(sql, args=(point_ids,))
newest_point_meter_relation = {i["pid"]: i["mid"] for i in records if
i["mid"]}
valid_mids = list(newest_point_meter_relation.values())
newest_record_map = {i["pid"]: point_map.get(i["pid"]) for i in records
if i["mid"]}
# 根据有效的meter id查询meter参数
async with MysqlUtil() as conn:
mid_field, start_time_field = "mid", "start_time"
mp_sql = f"SELECT vc, mid, ctnum FROM meter_param_record WHERE mid in %s ORDER BY {mid_field}, {start_time_field}"
mps = await conn.fetchall(mp_sql, args=(valid_mids,))
meter_param_map = {i["mid"]: i for i in mps}
for cid, point_ids in company_point_ids_map.items():
for point_id in point_ids:
if point_id in newest_record_map:
......@@ -56,13 +56,14 @@ async def get_points(company_ids):
async def get_points_new15(cids):
sql = "SELECT p.pid,p.cid,p.inlid FROM `point` p INNER JOIN monitor m " \
"on m.mtid=p.mtid where p.cid in %s and m.demolished=0;"
sql = "SELECT p.pid,p.cid,p.inlid,vc,ctnum " \
"FROM `point` p INNER JOIN " \
"monitor m on m.mtid=p.mtid where p.cid in %s and m.demolished=0;"
async with MysqlUtil() as conn:
points = await conn.fetchall(sql, args=(cids,))
company_point_map = defaultdict(dict)
for point in points:
company_point_map[point["cid"]][point["pid"]] = points
company_point_map[point["cid"]][point["pid"]] = point
return company_point_map
......@@ -121,7 +122,7 @@ async def list_point(cid):
for res in result:
pid = res.get("pid")
points[pid] = res
sql = "SELECT id, `group`, item FROM location WHERE cid=%s and `type` in %s"
async with MysqlUtil() as conn:
result = await conn.fetchall(sql, args=(
......@@ -131,7 +132,7 @@ async def list_point(cid):
group = res.get("group")
item = res.get("item")
groups.setdefault(group, []).append((id, item))
for pid, point_info in points.items():
name = point_info.get("name")
add_to_company = point_info["add_to_company"]
......@@ -145,7 +146,7 @@ async def list_point(cid):
comm_point = {"name": name, "point_id": pid, "locations": locations,
"add_to_company": add_to_company}
list_point.append(comm_point)
async with MysqlUtil() as conn:
sql = "SELECT inlid, `name` FROM inline WHERE cid=%s"
inlines = await conn.fetchall(sql, args=(cid,))
......
......@@ -175,61 +175,19 @@ async def alarm_summary(company_ids, start, end, date_type):
:param date_type:
:return:
"""
start_dt = datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
end_dt = datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
es_start_str = datetime(year=start_dt.year, month=start_dt.month,
day=start_dt.day).strftime(
"%Y-%m-%dT%H:%M:%S+08:00"
)
es_end_str = end_dt.strftime("%Y-%m-%dT%H:%M:%S+08:00")
if date_type == "day":
_format = "yyyy-MM-dd HH:mm:ss"
_min = start_dt.strftime("%Y-%m-%d %H:%M:%S")
_max = end_dt.strftime("%Y-%m-%d %H:%M:%S")
else:
# date_type == "month"
_format = "yyyy-MM-dd"
_min = start_dt.strftime("%Y-%m-%d")
_max = end_dt.strftime("%Y-%m-%d")
filter_list = [
{"range": {"datetime": {"gte": es_start_str, "lte": es_end_str, }}},
{"term": {"mode": "alarm"}},
]
filter_list.append({"terms": {"cid": company_ids}})
query_body = {
"query": {"bool": {"filter": filter_list}},
"size": 0,
"aggs": {
"cid_aggs": {
"terms": {"field": "cid", "size": 10000},
"aggs": {
"date_alarms": {
"date_histogram": {
"field": "datetime",
"order": {"_key": "desc"},
"min_doc_count": 1,
"interval": "day",
"format": "yyyy-MM-dd",
"time_zone": "+08:00",
}
}
},
}
},
}
log.info("alarm_summary query_body={}".format(query_body))
async with EsUtil() as es:
es_result = await es.search_origin(body=query_body,
index=constants.POINT_1MIN_EVENT)
print(f"es_result = {es_result}")
buckets = es_result["aggregations"]["cid_aggs"]["buckets"] or []
sql = f"""
select cid,count(*) count from point_1min_event
where cid in %s and event_mode = 'alarm' and event_datetime >= %s
and event_datetime <= %s
group by cid
"""
log.info("alarm_summary sql={}".format(sql))
async with MysqlUtil() as conn:
datas = await conn.fetchall(sql, args=(company_ids, start, end))
print(f"datas = {datas}")
total_alarm_cnt, alarm_company_cnt = sum(
[i["doc_count"] for i in buckets]), len(buckets)
cid_alarmcnt_list = [i["doc_count"] for i in buckets]
[i["count"] for i in datas]), len(datas)
cid_alarmcnt_list = [i["count"] for i in datas]
safe_run_map = await proxy_safe_run_info(company_ids, start_time_str=start,
end_time_str=end)
......
......@@ -48,6 +48,7 @@ from unify_api.modules.home_page.service.count_info_service import \
safe_run_sdu, safe_run_sdu_new15
from unify_api.modules.elec_charge.components.elec_charge_cps import \
ProductProxyReq
from unify_api.modules.users.procedures.jwt_user import jwt_user
@summary("代理版首页统计信息-安电U")
......@@ -55,7 +56,7 @@ async def post_count_info_proxy(req) -> CountInfoProxyResp:
# 1. 获取cid_list
host = req.host
product = PRODUCT.get(host)
user_id = req.ctx.user_id
user_id = jwt_user(req)
proxy_id = req.json.get("proxy_id")
# cid_list = await get_cids(user_id, product)
cid_list = await get_proxy_cids(user_id, product, proxy_id)
......@@ -105,7 +106,7 @@ async def post_security_level_count(
async def post_alarm_percentage_count(
request, body: ProxySecurityLevelCntReq
) -> ProxyAlarmPercentageCntResp:
user_id = request.ctx.user_id
user_id = jwt_user(request)
product = body.product
req_cid = body.cid
if not req_cid:
......@@ -137,7 +138,7 @@ async def post_alarm_percentage_count(
@summary("代理版本首页地图数据")
async def post_proxy_map_info(request,
body: ProxySecurityLevelCntReq) -> ProxyIndexMapResp:
user_id = request.ctx.user_id
user_id = jwt_user(request)
product = body.product
req_cid = body.cid
if not req_cid:
......
......@@ -23,6 +23,7 @@ from unify_api.modules.home_page.components.security_info_cps import (
from unify_api.modules.home_page.procedures.security_info_pds import (
alarm_summary, alarm_count_info_new15,
)
from unify_api.modules.users.procedures.jwt_user import jwt_user
@summary("获取首页今日或者近30天安全报警统计信息")
......@@ -164,7 +165,7 @@ async def post_alarm_summary(request, body: SecurityCommonReq) -> AlarmSummaryRe
if not req_cids:
raise BusinessException(message=f"暂无工厂")
if product == Product.AndianUManage.value:
user_id = request.ctx.user_id
user_id = jwt_user(request)
# cids = await get_cids(user_id, product)
proxy_id = body.proxy_id
cids = await get_proxy_cids(user_id, product, proxy_id)
......
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