Commit 61200aa0 authored by wang.wenrong's avatar wang.wenrong

Merge branch 'develop' into wwr

parents 9fc31e09 8663e19b
...@@ -19,7 +19,7 @@ async def point_day_power_dao(cid, start, end): ...@@ -19,7 +19,7 @@ async def point_day_power_dao(cid, start, end):
ORDER BY pp.create_time ORDER BY pp.create_time
""" """
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
data = await conn.fetchall(sql, args=(cid, )) data = await conn.fetchall(sql, args=(cid,))
return data return data
...@@ -31,7 +31,7 @@ async def get_total_kwh_dao(cid, start, end): ...@@ -31,7 +31,7 @@ async def get_total_kwh_dao(cid, start, end):
and pp.create_time<='{end}' and m.demolished=0 and pp.create_time<='{end}' and m.demolished=0
""" """
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
total_kwh = await conn.fetchone(sql, args=(cid, )) total_kwh = await conn.fetchone(sql, args=(cid,))
return total_kwh return total_kwh
...@@ -40,7 +40,7 @@ async def get_kwh_charge(table_name, name, value, start, end): ...@@ -40,7 +40,7 @@ async def get_kwh_charge(table_name, name, value, start, end):
f"FROM {table_name} where create_time>='{start}' and " \ f"FROM {table_name} where create_time>='{start}' and " \
f"create_time<='{end}' and {name} = %s" f"create_time<='{end}' and {name} = %s"
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
datas = await conn.fetchone(sql, args=(value, )) datas = await conn.fetchone(sql, args=(value,))
return datas return datas
...@@ -73,7 +73,7 @@ async def query_charge_aggs(date_start, date_end, cid_list): ...@@ -73,7 +73,7 @@ async def query_charge_aggs(date_start, date_end, cid_list):
""" """
start_es = convert_es_str(date_start) start_es = convert_es_str(date_start)
end_es = convert_es_str(date_end) end_es = convert_es_str(date_end)
query_body = { query_body = {
"size": 0, "size": 0,
"query": { "query": {
...@@ -138,132 +138,46 @@ async def power_charge_p_aggs(date_start, date_end, cid_list, interval): ...@@ -138,132 +138,46 @@ async def power_charge_p_aggs(date_start, date_end, cid_list, interval):
""" """
date_histogram, date_histogram,
""" """
start_es = convert_es_str(date_start) if interval == "hour":
end_es = convert_es_str(date_end) time_fmt = "%%Y-%%m-%%d %%H"
elif interval == "day":
query_body = { time_fmt = "%%Y-%%m-%%d"
"size": 0, else:
"query": { time_fmt = "%%Y-%%m-%%d %%H:%%i"
"bool": { sql = f"""
"must": [ select date_format(create_time,"{time_fmt}") as create_time,sum(kwh)
{ kwh,sum(charge) charge,sum(p) p
"terms": { from company_15min_power
"cid": cid_list where cid in %s and create_time >= %s and create_time <= %s
} group by date_format(create_time,"{time_fmt}")
}, """
{ async with MysqlUtil() as conn:
"range": { results = await conn.fetchall(sql,
"quarter_time": { args=(cid_list, date_start, date_end))
"gte": start_es, return results or []
"lte": end_es
}
}
}
]
}
},
"aggs": {
"quarter_time": {
"date_histogram": {
"field": "quarter_time",
"interval": interval,
"time_zone": "+08:00",
"format": "yyyy-MM-dd HH:mm:ss"
},
"aggs": {
"kwh": {
"sum": {
"field": "kwh"
}
},
"charge": {
"sum": {
"field": "charge"
}
},
"p": {
"sum": {
"field": "p"
}
}
}
}
}
}
log.info(query_body)
async with EsUtil() as es:
es_re = await es.search_origin(body=query_body, index=index)
return es_re["aggregations"]["quarter_time"]["buckets"]
async def power_charge_p_cid_aggs(date_start, date_end, cid_list, interval): async def power_charge_p_cid_aggs(date_start, date_end, cid_list, interval):
""" """
excel下载, 按照cid,date_histogram两次聚合,求电量电费 excel下载, 按照cid,date_histogram两次聚合,求电量电费
""" """
start_es = convert_es_str(date_start) if interval == "hour":
end_es = convert_es_str(date_end) time_fmt = "%%Y-%%m-%%d %%H"
elif interval == "day":
query_body = { time_fmt = "%%Y-%%m-%%d"
"size": 0, else:
"query": { time_fmt = "%%Y-%%m-%%d %%H:%%i"
"bool": { sql = f"""
"must": [ select cid,date_format(create_time,"{time_fmt}") as create_time,
{ sum(kwh) kwh,sum(charge) charge,sum(p) p
"terms": { from company_15min_power
"cid": cid_list where cid in %s and create_time >= %s and create_time <= %s
} group by cid,date_format(create_time,"{time_fmt}")
}, """
{ async with MysqlUtil() as conn:
"range": { results = await conn.fetchall(sql,
"quarter_time": { args=(cid_list, date_start, date_end))
"gte": start_es, return results or []
"lte": end_es
}
}
}
]
}
},
"aggs": {
"cids": {
"terms": {
"field": "cid",
"size": 1000
},
"aggs": {
"quarter_time": {
"date_histogram": {
"field": "quarter_time",
"interval": interval,
"time_zone": "+08:00",
"format": "yyyy-MM-dd HH:mm:ss"
},
"aggs": {
"kwh": {
"sum": {
"field": "kwh"
}
},
"charge": {
"sum": {
"field": "charge"
}
},
"p": {
"sum": {
"field": "p"
}
}
}
}
}
}
}
}
log.info(query_body)
async with EsUtil() as es:
es_re = await es.search_origin(body=query_body, index=index)
return es_re["aggregations"]["cids"]["buckets"]
async def query_charge_aggs_points(date_start, date_end, point_list): async def query_charge_aggs_points(date_start, date_end, point_list):
...@@ -293,7 +207,7 @@ async def query_charge_aggs_points(date_start, date_end, point_list): ...@@ -293,7 +207,7 @@ async def query_charge_aggs_points(date_start, date_end, point_list):
""" """
start_es = convert_es_str(date_start) start_es = convert_es_str(date_start)
end_es = convert_es_str(date_end) end_es = convert_es_str(date_end)
query_body = { query_body = {
"size": 0, "size": 0,
"query": { "query": {
...@@ -348,7 +262,7 @@ async def query_charge_aggs_points_new15(start, end, point_list): ...@@ -348,7 +262,7 @@ async def query_charge_aggs_points_new15(start, end, point_list):
f"where pid in %s and create_time BETWEEN '{start}' and '{end}' " \ f"where pid in %s and create_time BETWEEN '{start}' and '{end}' " \
f"GROUP BY pid" f"GROUP BY pid"
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
datas = await conn.fetchall(sql, args=(point_list, )) datas = await conn.fetchall(sql, args=(point_list,))
return datas return datas
...@@ -356,7 +270,7 @@ async def histogram_aggs_points(date_start, date_end, point_list, interval): ...@@ -356,7 +270,7 @@ async def histogram_aggs_points(date_start, date_end, point_list, interval):
"""date_histogram""" """date_histogram"""
start_es = convert_es_str(date_start) start_es = convert_es_str(date_start)
end_es = convert_es_str(date_end) end_es = convert_es_str(date_end)
query_body = { query_body = {
"size": 0, "size": 0,
"query": { "query": {
...@@ -418,7 +332,7 @@ async def power_charge_p_point_aggs(date_start, date_end, pid_list, interval): ...@@ -418,7 +332,7 @@ async def power_charge_p_point_aggs(date_start, date_end, pid_list, interval):
""" """
start_es = convert_es_str(date_start) start_es = convert_es_str(date_start)
end_es = convert_es_str(date_end) end_es = convert_es_str(date_end)
query_body = { query_body = {
"size": 0, "size": 0,
"query": { "query": {
...@@ -495,7 +409,6 @@ async def point_aggs_kwh(point_list, start=None, end=None): ...@@ -495,7 +409,6 @@ async def point_aggs_kwh(point_list, start=None, end=None):
return data return data
async def point_aggs_kwh_new15(point_list, start=None, end=None): async def point_aggs_kwh_new15(point_list, start=None, end=None):
"""1.5版本根据pid,求电量电费""" """1.5版本根据pid,求电量电费"""
if start and end: if start and end:
...@@ -506,7 +419,7 @@ async def point_aggs_kwh_new15(point_list, start=None, end=None): ...@@ -506,7 +419,7 @@ async def point_aggs_kwh_new15(point_list, start=None, end=None):
sql = "SELECT sum(kwh) kwh,sum(charge) charge FROM point_15min_power" \ sql = "SELECT sum(kwh) kwh,sum(charge) charge FROM point_15min_power" \
" where pid in %s" " where pid in %s"
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
data = await conn.fetchone(sql, args=(point_list, )) data = await conn.fetchone(sql, args=(point_list,))
return data return data
...@@ -516,7 +429,7 @@ async def extended_bounds_agg(date_start, date_end, cid_list, interval): ...@@ -516,7 +429,7 @@ async def extended_bounds_agg(date_start, date_end, cid_list, interval):
""" """
start_es = convert_es_str(date_start) start_es = convert_es_str(date_start)
end_es = convert_es_str(date_end) end_es = convert_es_str(date_end)
query_body = { query_body = {
"size": 0, "size": 0,
"query": { "query": {
......
...@@ -217,7 +217,7 @@ async def power_aggs_cid_proxy(start, end, cid_list, date_type): ...@@ -217,7 +217,7 @@ async def power_aggs_cid_proxy(start, end, cid_list, date_type):
for info in es_re_this: for info in es_re_this:
cid = info.get("key") cid = info.get("key")
cid_name = com_dic[cid]["shortname"] cid_name = com_dic[cid]["shortname"]
kwh = round_2(info.get("kwh")["value"]) kwh = round_2(info.get("kwh")["value"])
if kwh == 0: if kwh == 0:
continue continue
...@@ -229,9 +229,10 @@ async def power_aggs_cid_proxy(start, end, cid_list, date_type): ...@@ -229,9 +229,10 @@ async def power_aggs_cid_proxy(start, end, cid_list, date_type):
continue continue
except Exception as e: except Exception as e:
log.error(e) log.error(e)
log.info(f"本次有电量数据, 上周期没有电量数据, cid:{cid}, start:{start}, end:{end}") log.info(
f"本次有电量数据, 上周期没有电量数据, cid:{cid}, start:{start}, end:{end}")
continue continue
charge = round_2(info.get("charge")["value"]) charge = round_2(info.get("charge")["value"])
try: try:
charge_last = es_re_last_dic[cid]["charge"]["value"] charge_last = es_re_last_dic[cid]["charge"]["value"]
...@@ -241,7 +242,8 @@ async def power_aggs_cid_proxy(start, end, cid_list, date_type): ...@@ -241,7 +242,8 @@ async def power_aggs_cid_proxy(start, end, cid_list, date_type):
except Exception as e: except Exception as e:
log.error(e) log.error(e)
log.info("本次有数据, 上周期没有数据") log.info("本次有数据, 上周期没有数据")
log.info(f"本次有电费数据, 上周期没有电费数据, cid:{cid}, start:{start}, end:{end}") log.info(
f"本次有电费数据, 上周期没有电费数据, cid:{cid}, start:{start}, end:{end}")
continue continue
price = round_2(charge / kwh) price = round_2(charge / kwh)
price_last = round_2(charge_last / kwh_last) price_last = round_2(charge_last / kwh_last)
......
...@@ -113,11 +113,11 @@ def by_slots(slots, es_re_dic): ...@@ -113,11 +113,11 @@ def by_slots(slots, es_re_dic):
for slot in slots: for slot in slots:
if slot in es_re_dic: if slot in es_re_dic:
# 1.每个时间点,电量信息 # 1.每个时间点,电量信息
kwh_value = round_2(es_re_dic[slot].get("kwh").get("value")) kwh_value = round_2(es_re_dic[slot].get("kwh"))
# 2.每个时间点,电费信息 # 2.每个时间点,电费信息
charge_value = round_2(es_re_dic[slot].get("charge").get("value")) charge_value = round_2(es_re_dic[slot].get("charge"))
# 3. 功率 # 3. 功率
p_value = round_2(es_re_dic[slot].get("p").get("value")) p_value = round_2(es_re_dic[slot].get("p"))
# 4. 电价 # 4. 电价
try: try:
price_value = round_2(charge_value / kwh_value) price_value = round_2(charge_value / kwh_value)
...@@ -141,16 +141,18 @@ async def power_charge_p_proxy(cid_list, start, end, date_type, interval): ...@@ -141,16 +141,18 @@ async def power_charge_p_proxy(cid_list, start, end, date_type, interval):
# 1. 96个点数据 # 1. 96个点数据
slots_96 = SLOTS_15MIN slots_96 = SLOTS_15MIN
es_re_96 = await power_charge_p_aggs(start, end, cid_list, "15m") es_re_96 = await power_charge_p_aggs(start, end, cid_list, "15m")
es_re_96_dic = es_process(es_re_96, fmat="HH:mm") # 为了es结果和slots对应 es_re_96_dic = es_process(es_re_96, fmat="HH:mm",
time_key="create_time") # 为了es结果和slots对应
kwh_24, charge_24, p_24, price_24 = by_slots(slots_96, es_re_96_dic) kwh_24, charge_24, p_24, price_24 = by_slots(slots_96, es_re_96_dic)
# 96个点,工厂电量电费 # 96个点,工厂电量电费
# 2. 24个点数据 # 2. 24个点数据
slots_24 = SLOTS[date_type] slots_24 = SLOTS[date_type]
es_re_24 = await power_charge_p_aggs(start, end, cid_list, "hour") es_re_24 = await power_charge_p_aggs(start, end, cid_list, "hour")
es_re_24_dic = es_process(es_re_24, fmat="HH:mm") # 为了es结果和slots对应 es_re_24_dic = es_process(es_re_24, fmat="HH:mm",
time_key="create_time") # 为了es结果和slots对应
kwh_24, charge_24, p_24, price_24 = by_slots(slots_24, es_re_24_dic) kwh_24, charge_24, p_24, price_24 = by_slots(slots_24, es_re_24_dic)
# elif date_type == "month": # elif date_type == "month":
# intervel, slots = time_pick_transf(start, end) # intervel, slots = time_pick_transf(start, end)
# es_re = es_process(es_re, fmat="MM-DD") # 为了es结果和slots对应 # es_re = es_process(es_re, fmat="MM-DD") # 为了es结果和slots对应
import pendulum
from unify_api.constants import POINT_LEVEL_MAP from unify_api.constants import POINT_LEVEL_MAP
from unify_api.modules.common.components.common_cps import LevelResp from unify_api.modules.common.components.common_cps import LevelResp
from unify_api.modules.common.procedures.points import points_by_storeys from unify_api.modules.common.procedures.points import points_by_storeys
...@@ -6,6 +8,8 @@ from unify_api.modules.elec_charge.dao.elec_charge_dao import \ ...@@ -6,6 +8,8 @@ from unify_api.modules.elec_charge.dao.elec_charge_dao import \
query_charge_aggs_points, query_charge_aggs_points_new15 query_charge_aggs_points, query_charge_aggs_points_new15
from unify_api.modules.electric.dao.electric_dao import \ from unify_api.modules.electric.dao.electric_dao import \
monitor_point_join_by_points monitor_point_join_by_points
from unify_api.modules.home_page.procedures.count_info_pds import current_load, \
current_load_new15
from unify_api.utils.common_utils import round_2, division_two from unify_api.utils.common_utils import round_2, division_two
...@@ -86,11 +90,11 @@ async def kwh_card_level_service(cid, point_list, start, end): ...@@ -86,11 +90,11 @@ async def kwh_card_level_service(cid, point_list, start, end):
kwh = round_2(es_res[point_id]["kwh"]) kwh = round_2(es_res[point_id]["kwh"])
charge = round_2(es_res[point_id]["charge"]) charge = round_2(es_res[point_id]["charge"])
price = round_2(division_two(charge, kwh)) price = round_2(division_two(charge, kwh))
res_dic["kwh"] = kwh res_dic["kwh"] = kwh
res_dic["charge"] = charge res_dic["charge"] = charge
res_dic["price"] = price res_dic["price"] = price
ret_data[m_type].append(res_dic) ret_data[m_type].append(res_dic)
return LevelResp( return LevelResp(
inline=ret_data["inline"], inline=ret_data["inline"],
...@@ -101,4 +105,11 @@ async def kwh_card_level_service(cid, point_list, start, end): ...@@ -101,4 +105,11 @@ async def kwh_card_level_service(cid, point_list, start, end):
) )
async def load_info_service(cid_list):
# 实时负荷
cur_load = await current_load_new15(cid_list)
yesterday_dt = pendulum.now(tz="Asia/Shanghai").subtract(days=1)
yes_load = await current_load_new15(cid_list, yesterday_dt)
load_percent = round((cur_load - yes_load) / yes_load,
2) if cur_load and yes_load else ""
return cur_load, yes_load, load_percent
...@@ -16,14 +16,16 @@ from unify_api.modules.elec_charge.components.elec_charge_cps import \ ...@@ -16,14 +16,16 @@ from unify_api.modules.elec_charge.components.elec_charge_cps import \
power_overview_example, PricePolicyReq, PricePolicyResp, \ power_overview_example, PricePolicyReq, PricePolicyResp, \
PricePolicy, AverPriceReq, PowerViewRes, Spvf, AverPriceResp, ChargeKwh, \ PricePolicy, AverPriceReq, PowerViewRes, Spvf, AverPriceResp, ChargeKwh, \
IndexChargeReq, IndexChargeResp, PopReq, PopResp, MtpResp, PspResp, \ IndexChargeReq, IndexChargeResp, PopReq, PopResp, MtpResp, PspResp, \
IpspResp, KpReq, KpResp, KclReq, ProductProxyReq IpspResp, KpReq, KpResp, KclReq, ProductProxyReq, LoadInfoReq, LoadInfoResp
from unify_api.modules.elec_charge.dao.elec_charge_dao import \ from unify_api.modules.elec_charge.dao.elec_charge_dao import \
query_charge_aggs_points, get_kwh_charge, query_charge_aggs_points_new15 query_charge_aggs_points, get_kwh_charge, query_charge_aggs_points_new15
from unify_api.modules.elec_charge.procedures.elec_charge_pds import \ from unify_api.modules.elec_charge.procedures.elec_charge_pds import \
quarters_trans, power_overview_proxy, total_value, power_aggs_cid_proxy_new15, \ quarters_trans, power_overview_proxy, total_value, \
power_aggs_cid_proxy_new15, \
power_index_cid_proxy_new15, power_overview_proxy15 power_index_cid_proxy_new15, power_overview_proxy15
from unify_api.modules.elec_charge.service.elec_charge_service import \ from unify_api.modules.elec_charge.service.elec_charge_service import \
kwh_points_service, kwh_card_level_service kwh_points_service, kwh_card_level_service, load_info_service
from unify_api.modules.users.procedures.jwt_user import jwt_user
from unify_api.utils.common_utils import round_2, round_4, NumListHelper from unify_api.utils.common_utils import round_2, round_4, NumListHelper
from unify_api.utils.es_query_body import agg_statistics from unify_api.utils.es_query_body import agg_statistics
from unify_api.utils.request_util import filed_value_from_list from unify_api.utils.request_util import filed_value_from_list
...@@ -289,7 +291,7 @@ async def post_power_overview_proxy(req, body: PopReq) -> PopResp: ...@@ -289,7 +291,7 @@ async def post_power_overview_proxy(req, body: PopReq) -> PopResp:
proxy_id = body.proxy_id proxy_id = body.proxy_id
host = req.host host = req.host
product = PRODUCT.get(host) product = PRODUCT.get(host)
user_id = req.ctx.user_id user_id = jwt_user(req)
# 全部工厂 # 全部工厂
if not cid_list: if not cid_list:
log.info(f"power_overview_proxy根据用户userId:{user_id} " log.info(f"power_overview_proxy根据用户userId:{user_id} "
...@@ -314,13 +316,14 @@ async def post_power_overview_proxy(req, body: PopReq) -> PopResp: ...@@ -314,13 +316,14 @@ async def post_power_overview_proxy(req, body: PopReq) -> PopResp:
# 获取上一周期开始结束时间 # 获取上一周期开始结束时间
start_last, end_last = last_time_str(start, end, date_type) start_last, end_last = last_time_str(start, end, date_type)
power, charge = await power_overview_proxy15(start, end, cid_list) power, charge = await power_overview_proxy15(start, end, cid_list)
power_last, charge_last = await power_overview_proxy15(start_last, end_last, power_last, charge_last = await power_overview_proxy15(start_last,
cid_list) end_last,
cid_list)
if not all([power, charge, power_last, charge_last]): if not all([power, charge, power_last, charge_last]):
return PopResp(power=Spvf(), charge=Spvf()) return PopResp(power=Spvf(), charge=Spvf())
total_power = total_value(power) total_power = total_value(power)
total_charge = total_value(charge) total_charge = total_value(charge)
total_power_last = total_value(power_last) total_power_last = total_value(power_last)
total_charge_last = total_value(charge_last) total_charge_last = total_value(charge_last)
# 增长率 # 增长率
...@@ -351,7 +354,7 @@ async def post_month_today_proxy(req, body: ProductProxyReq) -> MtpResp: ...@@ -351,7 +354,7 @@ async def post_month_today_proxy(req, body: ProductProxyReq) -> MtpResp:
# 1. 获取参数 # 1. 获取参数
host = req.host host = req.host
product = PRODUCT.get(host) product = PRODUCT.get(host)
user_id = req.ctx.user_id user_id = jwt_user(req)
# cid_list = await get_cids(user_id, product) # cid_list = await get_cids(user_id, product)
proxy_id = body.proxy_id proxy_id = body.proxy_id
cid_list = await get_proxy_cids(user_id, product, proxy_id) \ cid_list = await get_proxy_cids(user_id, product, proxy_id) \
...@@ -364,7 +367,7 @@ async def post_month_today_proxy(req, body: ProductProxyReq) -> MtpResp: ...@@ -364,7 +367,7 @@ async def post_month_today_proxy(req, body: ProductProxyReq) -> MtpResp:
today_start, today_end, month_start, month_end = today_month_date() today_start, today_end, month_start, month_end = today_month_date()
# 2. 本月/上月数据 # 2. 本月/上月数据
last_month_start, last_month_end = last_time_str(month_start, month_end, last_month_start, last_month_end = last_time_str(month_start, month_end,
"month") "month", True)
this_month_p, this_month_charge = await power_overview_proxy15( this_month_p, this_month_charge = await power_overview_proxy15(
month_start, month_end, cid_list) month_start, month_end, cid_list)
last_month_p, last_month_charge = await power_overview_proxy15( last_month_p, last_month_charge = await power_overview_proxy15(
...@@ -541,3 +544,31 @@ async def post_kwh_card_level(req, body: KclReq) -> LevelResp: ...@@ -541,3 +544,31 @@ async def post_kwh_card_level(req, body: KclReq) -> LevelResp:
start = body.start start = body.start
end = body.end end = body.end
return await kwh_card_level_service(cid, point_list, start, end) return await kwh_card_level_service(cid, point_list, start, end)
@summary("获取知电管理版首页负荷信息")
async def post_load_info(request, body: LoadInfoReq) -> LoadInfoResp:
# 1. 获取company_id
# 1. 获取参数
product = PRODUCT.get(request.host)
user_id = jwt_user(request)
proxy_id = body.proxy_id
cid_list = await get_proxy_cids(user_id, product, proxy_id) \
if proxy_id else None
# 全部工厂
if not cid_list:
log.info(f"未查询到工厂, userId:{user_id} product:{product}")
return LoadInfoResp()
try:
# 实时负荷,昨日同时负荷,对比昨日
current_load, yesterday_load, load_percent = await load_info_service(
cid_list)
except Exception as e:
log.exception(e)
return LoadInfoResp().server_error()
return LoadInfoResp(
current_load=current_load,
yesterday_load=yesterday_load,
load_percent=load_percent
)
...@@ -5,7 +5,7 @@ async def monitor_point_join_by_points(points): ...@@ -5,7 +5,7 @@ async def monitor_point_join_by_points(points):
"""monitor和point关联""" """monitor和point关联"""
sql = "SELECT m.mtid,p.ctnum,m.name, m.m_type, p.pid,p.cid " \ sql = "SELECT m.mtid,p.ctnum,m.name, m.m_type, p.pid,p.cid " \
"FROM monitor m inner join point p on m.mtid = p.mtid " \ "FROM monitor m inner join point p on m.mtid = p.mtid " \
"WHERE p.pid in %s and m.demolished = 0 order by field(p.pid,{})".\ "WHERE p.pid in %s and m.demolished = 0 order by field(p.pid,{})". \
format(str(points).replace("[", "").replace("]", "")) format(str(points).replace("[", "").replace("]", ""))
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
monitor_point_list = await conn.fetchall(sql, args=(tuple(points),)) monitor_point_list = await conn.fetchall(sql, args=(tuple(points),))
...@@ -26,7 +26,7 @@ async def get_electric_datas_dao(table_name, pid, start, end): ...@@ -26,7 +26,7 @@ async def get_electric_datas_dao(table_name, pid, start, end):
sql = f"SELECT * FROM {table_name} where pid=%s and create_time " \ sql = f"SELECT * FROM {table_name} where pid=%s and create_time " \
f"BETWEEN '{start}' and '{end}' ORDER BY create_time desc" f"BETWEEN '{start}' and '{end}' ORDER BY create_time desc"
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
electric_datas = await conn.fetchall(sql, args=(pid, )) electric_datas = await conn.fetchall(sql, args=(pid,))
return electric_datas return electric_datas
...@@ -35,7 +35,7 @@ async def get_qual_history_dao(table_name, pid, start, end, date_format): ...@@ -35,7 +35,7 @@ async def get_qual_history_dao(table_name, pid, start, end, date_format):
f"p.* FROM {table_name} p where p.pid=%s and p.create_time " \ f"p.* FROM {table_name} p where p.pid=%s and p.create_time " \
f"BETWEEN '{start}' and '{end}' order by p.create_time" f"BETWEEN '{start}' and '{end}' order by p.create_time"
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
datas = await conn.fetchall(sql, args=(pid, )) datas = await conn.fetchall(sql, args=(pid,))
return datas return datas
...@@ -51,6 +51,12 @@ async def get_elec_history_dao(table_name, pid, start, end, date_format): ...@@ -51,6 +51,12 @@ async def get_elec_history_dao(table_name, pid, start, end, date_format):
async def get_elec_mtid_sid_by_cid(cid): async def get_elec_mtid_sid_by_cid(cid):
if isinstance(cid, tuple):
cid_tuple = cid
elif isinstance(cid, list):
cid_tuple = tuple(cid)
else:
cid_tuple = (cid,)
sql = ( sql = (
f""" f"""
SELECT SELECT
...@@ -59,9 +65,9 @@ async def get_elec_mtid_sid_by_cid(cid): ...@@ -59,9 +65,9 @@ async def get_elec_mtid_sid_by_cid(cid):
FROM FROM
monitor monitor
WHERE WHERE
cid = {cid}; cid in %s;
""" """
) )
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
datas = await conn.fetchall(sql) datas = await conn.fetchall(sql, args=(cid_tuple,))
return datas if datas else [] return datas if datas else []
from pot_libs.mysql_util.mysql_util import MysqlUtil from pot_libs.mysql_util.mysql_util import MysqlUtil
async def get_kwh_p_dao(table_name, terms, start, end): async def get_kwh_p_dao(terms, start_time, end_time,
sql = f"SELECT create_time,kwh,p FROM {table_name} WHERE cid in %s " \ table_name="company_15min_power",
f"and create_time BETWEEN '{start}' and '{end}'" time_fmt="%%Y-%%m-%%d"):
"""
负荷实际数据
:param terms:
:param start_time:
:param end_time:
:param table_name:
:param time_fmt:
:return:
"""
sql = f"""
select p,kwh,DATE_FORMAT(create_time,"{time_fmt}") as cal_time
from {table_name} where cid in %s and create_time >= %s
and create_time <= %s
"""
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
datas = await conn.fetchall(sql, args=(terms, )) result = await conn.fetchall(sql, args=(terms, start_time, end_time))
return datas return result or []
async def get_pred_p_dao(terms, start, end): async def get_pred_p_dao(terms, start_time, end_time,
sql = f"SELECT create_time,p FROM company_day_ahead_predict " \ time_fmt="%%Y-%%m-%%d"):
f"WHERE cid in %s and create_time BETWEEN '{start}' and '{end}'" """
负荷预测数据
:param terms:
:param start_time:
:param end_time:
:param time_fmt:
:return:
"""
sql = f"""
select avg(p) p ,count(*) p_count,DATE_FORMAT(create_time,
"{time_fmt}") as cal_time
from company_day_ahead_predict
where cid in %s and create_time >= %s and create_time <= %s
group by cal_time
"""
async with MysqlUtil() as conn: async with MysqlUtil() as conn:
datas = await conn.fetchall(sql, args=(terms,)) result = await conn.fetchall(sql, args=(terms, start_time, end_time))
return datas return result or []
\ No newline at end of file
...@@ -5,6 +5,7 @@ from unify_api.modules.load_analysis.components.load_forecast_cps import ( ...@@ -5,6 +5,7 @@ from unify_api.modules.load_analysis.components.load_forecast_cps import (
) )
from unify_api.modules.load_analysis.service.load_forecast_service import \ from unify_api.modules.load_analysis.service.load_forecast_service import \
load_forecast_service, load_forecast_service_new15 load_forecast_service, load_forecast_service_new15
from unify_api.utils.time_format import time_pick_transf_new
@summary("负荷预测") @summary("负荷预测")
...@@ -17,4 +18,8 @@ async def post_load_forecast(req, body: ForecastReq) -> ForecastResp: ...@@ -17,4 +18,8 @@ async def post_load_forecast(req, body: ForecastReq) -> ForecastResp:
# 管理版本多个工厂的情况, 兼容能力最强的参数cids, 保留旧有的cid: # 管理版本多个工厂的情况, 兼容能力最强的参数cids, 保留旧有的cid:
cids = body.cids cids = body.cids
# return await load_forecast_service(cid, cids, start, end) # return await load_forecast_service(cid, cids, start, end)
return await load_forecast_service_new15(cid, cids, start, end) terms = cids if cids else [cid]
# 获取时间差
interval, slots = time_pick_transf_new(start, end)
return await load_forecast_service_new15(terms, start, end,
interval, slots)
...@@ -60,6 +60,41 @@ def time_pick_transf(start, end, is_range=0): ...@@ -60,6 +60,41 @@ def time_pick_transf(start, end, is_range=0):
return intervel, slots return intervel, slots
def time_pick_transf_new(start, end):
"""获取intervel和slots, 详细显示时间轴信息,新接口都使用这个来获取时间"""
start_f = my_pendulum.from_format(start, 'YYYY-MM-DD HH:mm:ss')
end_f = my_pendulum.from_format(end, 'YYYY-MM-DD HH:mm:ss')
diff = end_f.int_timestamp - start_f.int_timestamp
# 1. 计算intervel
# 1.1 区间48小时之内, 返回15min
if diff <= 48 * 3600:
intervel = 15 * 60
# 1.2 区间在60天以内, 返回1day
elif 48 * 3600 < diff <= 60 * 86400:
intervel = 86400
# 1.3 选择年, 返回1个月
else:
intervel = 30 * 86400
# 2. 计算slots
# 2.1 取到点的个数, 比如15min的96个点
slots = []
slot_num = round((end_f.int_timestamp - start_f.int_timestamp) / intervel)
for i in range(slot_num):
# 区间48小时之内
if diff <= 48 * 3600:
dt = start_f.add(minutes=15 * i).format("YYYY-MM-DD HH:mm")
dt_str = str(dt)
# 区间在60天以内
elif 48 * 3600 < diff <= 60 * 86400:
dt = start_f.add(days=1 * i).format("YYYY-MM-DD")
dt_str = str(dt)
else:
dt = start_f.add(months=1 * i).format("YYYY-MM")
dt_str = str(dt)
slots.append(dt_str)
return intervel, slots
def power_slots(start, end): def power_slots(start, end):
"""电量电费,用电统计,time=range slots计算""" """电量电费,用电统计,time=range slots计算"""
start_f = my_pendulum.from_format(start, 'YYYY-MM-DD HH:mm:ss') start_f = my_pendulum.from_format(start, 'YYYY-MM-DD HH:mm:ss')
...@@ -115,6 +150,7 @@ def proxy_power_slots(start, end, date_format="MM-DD", is_duration=False): ...@@ -115,6 +150,7 @@ def proxy_power_slots(start, end, date_format="MM-DD", is_duration=False):
slots.append(dt) slots.append(dt)
return slots return slots
def day_of_month(start): def day_of_month(start):
"""这个月有几天""" """这个月有几天"""
start_f = my_pendulum.from_format(start, 'YYYY-MM-DD HH:mm:ss') start_f = my_pendulum.from_format(start, 'YYYY-MM-DD HH:mm:ss')
...@@ -269,7 +305,7 @@ def start_end_date(): ...@@ -269,7 +305,7 @@ def start_end_date():
def time_str_to_str(date_str, format="HH:mm"): def time_str_to_str(date_str, format="HH:mm"):
"""YYYY-MM-DD HH:mm:ss格式转换为format格式""" """YYYY-MM-DD HH:mm:ss格式转换为format格式"""
start_f = my_pendulum.from_format(date_str, 'YYYY-MM-DD HH:mm:ss') start_f = my_pendulum.parse(date_str)
start_f = start_f.format(format) start_f = start_f.format(format)
return start_f return start_f
...@@ -311,7 +347,7 @@ def convert_to_es_str(str1, format="YYYY-MM-DD HH:mm:ss"): ...@@ -311,7 +347,7 @@ def convert_to_es_str(str1, format="YYYY-MM-DD HH:mm:ss"):
return str(es_date) return str(es_date)
def last_time_str(start, end, date_type): def last_time_str(start, end, date_type, date_end=False):
"""年月日, 获取上一周期时间""" """年月日, 获取上一周期时间"""
if date_type not in ("day", "month", "year"): if date_type not in ("day", "month", "year"):
return None return None
...@@ -319,13 +355,22 @@ def last_time_str(start, end, date_type): ...@@ -319,13 +355,22 @@ def last_time_str(start, end, date_type):
end_f = my_pendulum.from_format(end, 'YYYY-MM-DD HH:mm:ss') end_f = my_pendulum.from_format(end, 'YYYY-MM-DD HH:mm:ss')
if date_type == "day": if date_type == "day":
start_last = start_f.subtract(days=1) start_last = start_f.subtract(days=1)
end_last = end_f.subtract(days=1) if date_end:
end_last = start_last.end_of(unit=date_type)
else:
end_last = end_f.subtract(days=1)
elif date_type == "month": elif date_type == "month":
start_last = start_f.subtract(months=1) start_last = start_f.subtract(months=1)
end_last = end_f.subtract(months=1) if date_end:
end_last = start_last.end_of(unit=date_type)
else:
end_last = end_f.subtract(months=1)
else: else:
start_last = start_f.subtract(years=1) start_last = start_f.subtract(years=1)
end_last = end_f.subtract(years=1) if date_end:
end_last = start_last.end_of(unit=date_type)
else:
end_last = end_f.subtract(years=1)
return start_last.format("YYYY-MM-DD HH:mm:ss"), end_last.format( return start_last.format("YYYY-MM-DD HH:mm:ss"), end_last.format(
"YYYY-MM-DD HH:mm:ss") "YYYY-MM-DD HH:mm:ss")
...@@ -356,7 +401,7 @@ def get_datetime_str(timestamp): ...@@ -356,7 +401,7 @@ def get_datetime_str(timestamp):
''' '''
if not timestamp: if not timestamp:
timestamp = time.time() timestamp = time.time()
time_array = time.localtime(timestamp) time_array = time.localtime(timestamp)
return time.strftime("%Y-%m-%d %H:%M:%S", time_array) return time.strftime("%Y-%m-%d %H:%M:%S", time_array)
...@@ -671,7 +716,7 @@ def get_last_3month_start_end(date=None): ...@@ -671,7 +716,7 @@ def get_last_3month_start_end(date=None):
:param dt: datetime obj :param dt: datetime obj
:return: :return:
""" """
if not date: if not date:
dt = get_current_date_time() dt = get_current_date_time()
else: else:
...@@ -733,7 +778,7 @@ def get_this_year_start_end(date=None): ...@@ -733,7 +778,7 @@ def get_this_year_start_end(date=None):
:param dt: datetime obj :param dt: datetime obj
:return: :return:
""" """
if not date: if not date:
dt = get_current_date_time() dt = get_current_date_time()
else: else:
...@@ -749,7 +794,7 @@ def get_last_year_start_end(date=None): ...@@ -749,7 +794,7 @@ def get_last_year_start_end(date=None):
:param dt: datetime obj :param dt: datetime obj
:return: :return:
""" """
if not date: if not date:
dt = get_current_date_time() dt = get_current_date_time()
else: else:
...@@ -765,7 +810,7 @@ def get_last_month_start_end(date=None): ...@@ -765,7 +810,7 @@ def get_last_month_start_end(date=None):
:param dt: datetime obj :param dt: datetime obj
:return: :return:
""" """
if not date: if not date:
dt = get_current_date_time() dt = get_current_date_time()
else: else:
...@@ -873,7 +918,7 @@ def get_current_start_n_end_dt(date_type, include_end_day=False): ...@@ -873,7 +918,7 @@ def get_current_start_n_end_dt(date_type, include_end_day=False):
start_year += 1 start_year += 1
start_month = start_month - 12 start_month = start_month - 12
start = datetime.datetime(start_year, start_month, 1) start = datetime.datetime(start_year, start_month, 1)
elif date_type == "season": elif date_type == "season":
season_number = int((current_dt.month - 1) / 3) season_number = int((current_dt.month - 1) / 3)
start = datetime.datetime(current_dt.year, season_number * 3 + 1, 1) start = datetime.datetime(current_dt.year, season_number * 3 + 1, 1)
...@@ -984,7 +1029,7 @@ def get_previous_slot(slots, date_type, compare_type=None): ...@@ -984,7 +1029,7 @@ def get_previous_slot(slots, date_type, compare_type=None):
return get_slots_between_date( return get_slots_between_date(
start - datetime.timedelta(days=days), start - datetime.timedelta(days=days),
end - datetime.timedelta(days=days), date_type) end - datetime.timedelta(days=days), date_type)
elif date_type == "hour": elif date_type == "hour":
hours = int((end - start).total_seconds() / 3600) + 1 hours = int((end - start).total_seconds() / 3600) + 1
return get_slots_between_date(start - datetime.timedelta(hours=hours), return get_slots_between_date(start - datetime.timedelta(hours=hours),
...@@ -1032,8 +1077,8 @@ def get_slots_between_date(start, end, interval_type, growth_type=None): ...@@ -1032,8 +1077,8 @@ def get_slots_between_date(start, end, interval_type, growth_type=None):
while start <= end: while start <= end:
date_dts.append([start, start + datetime.timedelta(days=1)]) date_dts.append([start, start + datetime.timedelta(days=1)])
start += datetime.timedelta(days=1) start += datetime.timedelta(days=1)
elif interval_type == "month": elif interval_type == "month":
start_months = start.year * 12 + start.month start_months = start.year * 12 + start.month
end_months = end.year * 12 + end.month end_months = end.year * 12 + end.month
...@@ -1145,7 +1190,7 @@ def deco_convert_date_to_dt(f): ...@@ -1145,7 +1190,7 @@ def deco_convert_date_to_dt(f):
if kwarg in kwargs and kwargs[kwarg]: if kwarg in kwargs and kwargs[kwarg]:
kwargs[kwarg] = convert_to_dt(kwargs[kwarg]) kwargs[kwarg] = convert_to_dt(kwargs[kwarg])
return f(*args, **kwargs) return f(*args, **kwargs)
return deco return deco
...@@ -1432,7 +1477,7 @@ def get_time_duration_by_str(duration_str): ...@@ -1432,7 +1477,7 @@ def get_time_duration_by_str(duration_str):
days = int(duration_str / (60 * 60 * 24)) days = int(duration_str / (60 * 60 * 24))
if days > 0: if days > 0:
return_str += "%s天" % str(days) return_str += "%s天" % str(days)
hours = int(duration_str % (60 * 60 * 24) / (60 * 60)) hours = int(duration_str % (60 * 60 * 24) / (60 * 60))
if hours > 0: if hours > 0:
return_str += "%s时" % str(hours) return_str += "%s时" % str(hours)
......
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