Commit fe8ae8d9 by 杨林龙

优化分摊代码

1 parent e71d8887
......@@ -2,6 +2,7 @@ import logging
import time
from datetime import datetime
from decimal import Decimal
from itertools import groupby
import MySQLdb
from dateutil.relativedelta import *
......@@ -414,6 +415,45 @@ def getMonthDataMap(ft_table, device_id):
return my_map
def get_job_id(job_info_data):
return job_info_data[1]
def getMonthDataBigMap(ft_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,device_id,apportionment_date,apportionment_price FROM {ft_table};
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_month_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_month_big_map[job_id] = {i[2].strftime("%Y-%m-%d"): i for i in group_list}
return my_month_big_map
def getYearDataBigMap(zj_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,device_id,order_year,qichu_num,qichu_unit_price,qichu_total_price,zengjia_num,zengjia_unit_price,zengjia_total_price,jianshao_num,jianshao_unit_price,jianshao_total_price
FROM {zj_table} tddz;
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_year_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_year_big_map[job_id] = {i[2]: i for i in group_list}
return my_year_big_map
def calculate(base_table, ft_table, zj_table, device_type, service_type, file_name):
"""
以结算为维度
......
import logging
import time
from datetime import datetime
from decimal import Decimal
from itertools import groupby
import MySQLdb
from dateutil.relativedelta import *
from base_create_table import BaseCreateTable
from my_utils.MysqlUtility import MySQL
from my_config.config import *
logger = logging.getLogger("deal_equity_data")
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler("import.log")
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
saas_shen_db_cfg = {
"host": "192.168.3.222",
"port": 3306,
"user": "biz_audit",
"passwd": "hqVIs6jF",
"db": "saas_shen_ft",
"charset": "utf8",
}
# year_list = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028]
# range_num = 120
def deal_equity_data(
base_table, ft_table, device_type, service_type, range_num, start_month
):
"""
以结算为维度
service_type 1 硬件 2 服务 3 安装
"""
bizConn = MySQL(saas_shen_db_cfg)
if service_type == 1:
sql = f"""
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(hw_price,0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(pk_price,0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(install_price, 0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
device_id = row[0]
设备号 = row[1]
分摊时间 = row[2]
服务期限 = paddnum_price(row[3])
服务总金额 = paddnum_price(row[4])
if 服务期限 == 0:
logger.warning("服务期限为0")
continue
分摊金额 = 服务总金额 / 服务期限
分摊金额 = Decimal(分摊金额).quantize(Decimal("0.00"))
values = buildApportionment(device_id, 分摊时间, 服务期限, 分摊金额, range_num, start_month)
sql01 = f"""
INSERT INTO {ft_table} (device_id,apportionment_date,apportionment_price) values {values};
"""
write_sql(sql01)
bizConn.insert(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def buildApportionment(device_id, 分摊时间, 服务期限, 分摊金额, range_num, start_month):
# 将业务日期开始时间设置为 1号 方便比较
分摊时间 = 分摊时间.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
sb = StringBuilder()
# 计算分摊的最后日期
分摊最后日期 = add_one_month(分摊时间, 服务期限)
print("分摊最后日期==", 分摊最后日期)
for i in range(range_num):
start_time = datetime.strptime(start_month, "%Y-%m-%d")
# 添加一个月的日期
calculate_time = add_one_month(start_time, i)
if 分摊时间 <= calculate_time < 分摊最后日期:
sb.append(f"({device_id},'{calculate_time}',{分摊金额}),")
return str(sb)[0 : len(str(sb)) - 1]
def add_one_month(date, i):
# Add one month to the date using timedelta
next_month = date + relativedelta(months=+i)
# print(next_month)
new_date = next_month.replace(day=1)
return new_date
def write_sql(sql):
logger.info(sql)
with open(
"H:\PythonWorkSpaces\deal_mysql_data\\sql14.txt", "a+", encoding="utf8"
) as fw:
fw.write(sql.strip())
fw.write("\n")
class StringBuilder:
def __init__(self):
self.strings = []
def append(self, string):
self.strings.append(string)
def __str__(self):
return "".join(self.strings)
def deal_jianshao_equity_data(ft_table, zj_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
INSERT INTO {zj_table}(`device_id`,`order_year`,`qichu_unit_price`,`zengjia_unit_price`,`jianshao_num`,`jianshao_unit_price`)
SELECT device_id ,LEFT(apportionment_date,4) AS `year`,`apportionment_price`,`apportionment_price` ,count(1) AS num , `apportionment_price`
FROM {ft_table} GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = f"""
UPDATE {zj_table} SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data(base_table, zj_table, device_type, service_type):
bizConn = MySQL(saas_shen_db_cfg)
if service_type == 1:
sql = f"""
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(IFNULL(hw_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7), pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(IFNULL(pk_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7), pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(IFNULL(install_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7), pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
device_id = row[0]
year = row[1]
pk_period = row[2]
pk_price = row[3]
sql01 = f"""
UPDATE {zj_table} SET zengjia_num = {pk_period}, zengjia_total_price = {pk_price} WHERE device_id = {device_id} AND order_year = {year};
"""
logger.info(sql01)
bizConn.update(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def deal_qichu_equity_data(zj_table, year_list):
bizConn = MySQL(saas_shen_db_cfg)
for year_num in year_list:
sql = f"""
SELECT id, device_id, order_year, qichu_num, zengjia_num, jianshao_num FROM {zj_table} WHERE order_year= {year_num} ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
id = row[0]
device_id = row[1]
order_year = row[2]
qichu_num = paddnum_price(row[3])
zengjia_num = paddnum_price(row[4])
jianshao_num = paddnum_price(row[5])
# 上一年 下一年期初的数据=当年期初+当年新增-当年减少
next_year = int(order_year) + 1
sql01 = f"""
UPDATE {zj_table} SET qichu_num = {qichu_num + zengjia_num - jianshao_num} WHERE device_id = {device_id} AND order_year = {next_year};
"""
write_sql(sql01)
bizConn.update(sql01)
sql01 = f"""
UPDATE {zj_table} SET qichu_total_price = qichu_num*qichu_unit_price WHERE device_id = {device_id} AND order_year = {next_year};
"""
write_sql(sql01)
bizConn.update(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def paddnum_price(num):
return num if num is not None else 0
def paddstr(strx):
return (
"NULL"
if strx == None
else "'" + MySQLdb.escape_string(str(strx)).decode() + "'"
)
def deal_null_equity_data(zj_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
UPDATE {zj_table} set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE {zj_table} set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv(fileName, year_list):
bizConn = MySQL(saas_shen_db_cfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
headName = (
"id,channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,"
"settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost,fentan_time"
)
for year in year_list:
headName += f",{year}期初数,{year}期初单价,{year}期初金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额"
headName += "\n"
fileHandle.write(headName)
# SELECT teo.id ,teo.order_code, teo.order_time, teo.service_period, teo.total_price FROM temp_eq_order; where teo.id = 251
sql = f"""
SELECT id,channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,sum(pk_price)
,hw_price,install_price,hw_cost,install_cost ,fentan_time FROM temp_dj_device_details_20230620 where `device_type` IN (6,12501) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
logger.info(row)
lineValue = f"{row[0]},{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]},{row[12]},{row[13]},{row[14]},{row[15]},{row[16]},{row[17]},{row[18]}"
for year in year_list:
logger.info("device_id" + str(row[0]) + ";year" + str(year))
sql = f"""
SELECT id,device_id,order_year,qichu_num,qichu_unit_price,qichu_total_price,zengjia_num,zengjia_unit_price,zengjia_total_price,jianshao_num,jianshao_unit_price,jianshao_total_price
FROM temp_dj_device_details_20230620_settle_record_zj tddz WHERE tddz.device_id = {row[0]} AND tddz.order_year = '{year}';
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
if len(result) == 0:
logger.debug(row)
lineValue += f",0,0,0,0,0,0,0,0,0"
else:
for row01 in result:
logger.info(row01)
lineValue += f",{paddnum_price(row01[3])},{paddnum_price(row01[4])},{paddnum_price(row01[5])},{paddnum_price(row01[6])},{paddnum_price(row01[7])},{paddnum_price(row01[8])},{paddnum_price(row01[9])},{paddnum_price(row01[10])},{paddnum_price(row01[11])}"
# 写入一行数据
lineValue += "\n"
logger.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def export_csv_2(base_table, ft_table, zj_table, device_type, fileName, year_list):
bizConn = MySQL(saas_shen_db_cfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
headName = "客户名称,门店,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in year_list:
headName += f",{year}期初数,{year}期初单价,{year}期初金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额"
headName += f",{year}-01分摊,{year}-02分摊,{year}-03分摊,{year}-04分摊,{year}-05分摊,{year}-06分摊,{year}-07分摊,{year}-08分摊,{year}-09分摊,{year}-10分摊,{year}-11分摊,{year}-12分摊"
headName += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
headName += "\n"
fileHandle.write(headName)
if service_type == 1:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(hw_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,hw_price,
sum(hw_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(pk_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,pk_price,
sum(pk_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(install_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,install_price,
sum(install_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_year_big_map = getYearDataBigMap(zj_table)
my_month_big_map = getMonthDataBigMap(ft_table)
for row in result:
logger.info(row)
lineValue = f"{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
my_year_map = my_year_big_map.get(row[0])
my_month_map = my_month_big_map.get(row[0])
for year in year_list:
logger.info("device_id" + str(row[0]) + ";year" + str(year))
result = my_year_map.get(str(year))
if result is None or len(result) == 0:
logger.debug(row)
lineValue += f",0,0,0,0,0,0,0,0,0"
else:
logger.info(result)
lineValue += f",{paddnum_price(result[3])},{paddnum_price(result[4])},{paddnum_price(result[5])},{paddnum_price(result[6])},{paddnum_price(result[7])},{paddnum_price(result[8])},{paddnum_price(result[9])},{paddnum_price(result[10])},{paddnum_price(result[11])}"
monthList = getMonthListByYear(year)
for month in monthList:
# my_map = getMonthDataMap(ft_table, row[0])
row_data = my_month_map.get(str(month))
# logger.info(
# "device_id"
# + str(row[0])
# + ",month=="
# + str(month)
# + ",row_data=="
# + str(row_data)
# )
if row_data is None or len(row_data) == 0:
lineValue += f",0"
else:
lineValue += f",{paddnum_price(row_data[3])}"
if row[12] == 6:
lineValue += ",记录仪"
elif row[12] == 12501:
lineValue += ",车充"
elif row[12] == 8:
lineValue += ",GPS"
lineValue += f",{row[13]},{row[14]},{row[15]},{row[16]}"
# 写入一行数据
lineValue += "\n"
logger.info(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def getMonthListByYear(year):
monthList = []
d_str = f"{year}-01-01"
first_month = datetime.strptime(d_str, "%Y-%m-%d").date()
logger.info("first_month==" + str(first_month))
for i in range(12):
next_month = add_one_month(first_month, i)
monthList.append(next_month)
logger.info("monthList==" + str(monthList))
return monthList
def getMonthDataMap(ft_table, device_id):
bizConn = MySQL(saas_shen_db_cfg)
logger.info("device_id" + str(device_id))
sql = f"""
SELECT id,device_id,apportionment_date,apportionment_price FROM {ft_table} WHERE device_id ={device_id};
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_map = {i[2].strftime("%Y-%m-%d"): i for i in result}
logger.info(my_map)
return my_map
def get_job_id(job_info_data):
return job_info_data[1]
def getMonthDataBigMap(ft_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,device_id,apportionment_date,apportionment_price FROM {ft_table};
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_month_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_month_big_map[job_id] = {i[2].strftime("%Y-%m-%d"): i for i in group_list}
print("my_month_big_map:", my_month_big_map)
return my_month_big_map
def getYearDataBigMap(zj_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,device_id,order_year,qichu_num,qichu_unit_price,qichu_total_price,zengjia_num,zengjia_unit_price,zengjia_total_price,jianshao_num,jianshao_unit_price,jianshao_total_price
FROM {zj_table} tddz;
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_year_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_year_big_map[job_id] = {i[2]: i for i in group_list}
print("my_year_big_map:", my_year_big_map)
return my_year_big_map
def calculate(base_table, ft_table, zj_table, device_type, service_type, file_name):
"""
以结算为维度
service_type 1 硬件 hw 2 服务 pk 3 安装 install
"""
if device_type == "8":
year_list = gps_year_list
range_num = gps_range_num
start_month = gps_start_month
else:
year_list = obd_year_list
range_num = obd_range_num
start_month = obd_start_month
# 创建数据表
# BaseCreateTable(ft_table, zj_table).create_table()
# # 处理基础数据
# deal_equity_data(
# base_table, ft_table, device_type, service_type, range_num, start_month
# )
# # 处理减少数据
# deal_jianshao_equity_data(ft_table, zj_table)
# # 处理增加数据
# deal_zengjia_equity_data(base_table, zj_table, device_type, service_type)
# # 处理期初数据
# deal_qichu_equity_data(zj_table, year_list)
# # 处理为NULL的数据
# deal_null_equity_data(zj_table)
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv", year_list)
export_csv_2(base_table, ft_table, zj_table, device_type, file_name, year_list)
if __name__ == "__main__":
# 追踪器
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_active_hw_record_ft"
zj_table = "temp_dj_device_details_20230620_active_hw_record_zj"
device_type = "6,12501"
service_type = 1
file_name = "记录仪硬件激活维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_active_pk_record_ft"
zj_table = "temp_dj_device_details_20230620_active_pk_record_zj"
device_type = "6,12501"
service_type = 2
file_name = "记录仪服务激活维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_active_install_record_ft"
zj_table = "temp_dj_device_details_20230620_active_install_record_zj"
device_type = "6,12501"
service_type = 3
file_name = "记录仪安装激活维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
# GPS
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_active_hw_gps_ft"
zj_table = "temp_dj_device_details_20230620_active_hw_gps_zj"
device_type = "8"
service_type = 1
file_name = "GPS硬件激活维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_active_pk_gps_ft"
zj_table = "temp_dj_device_details_20230620_active_pk_gps_zj"
device_type = "8"
service_type = 2
file_name = "GPS服务激活维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_active_install_gps_ft"
zj_table = "temp_dj_device_details_20230620_active_install_gps_zj"
device_type = "8"
service_type = 3
file_name = "GPS安装激活维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
import logging
import time
from datetime import datetime
from decimal import Decimal
from itertools import groupby
import MySQLdb
from dateutil.relativedelta import *
from base_create_table import BaseCreateTable
from my_utils.MysqlUtility import MySQL
from my_config.config import *
logger = logging.getLogger("deal_equity_data")
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler("import.log")
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
saas_shen_db_cfg = {
"host": "192.168.3.222",
"port": 3306,
"user": "biz_audit",
"passwd": "hqVIs6jF",
"db": "saas_shen_ft",
"charset": "utf8",
}
# year_list = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028]
# range_num = 120
def deal_equity_data(
base_table, ft_table, device_type, service_type, range_num, start_month
):
"""
以结算为维度
service_type 1 硬件 2 服务 3 安装
"""
bizConn = MySQL(saas_shen_db_cfg)
if service_type == 1:
sql = f"""
SELECT `id`,`sn`,`settle_time`,`pk_period`,SUM(IFNULL(hw_price,0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7),pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT `id`,`sn`,`settle_time`,`pk_period`,SUM(IFNULL(pk_price,0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7),pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT `id`,`sn`,`settle_time`,`pk_period`,SUM(IFNULL(install_price, 0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
device_id = row[0]
设备号 = row[1]
分摊时间 = row[2]
服务期限 = paddnum_price(row[3])
服务总金额 = paddnum_price(row[4])
if 服务期限 == 0:
logger.warning("服务期限为0")
continue
分摊金额 = 服务总金额 / 服务期限
分摊金额 = Decimal(分摊金额).quantize(Decimal("0.00"))
values = buildApportionment(device_id, 分摊时间, 服务期限, 分摊金额, range_num, start_month)
sql01 = f"""
INSERT INTO {ft_table} (device_id,apportionment_date,apportionment_price) values {values};
"""
write_sql(sql01)
bizConn.insert(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def buildApportionment(device_id, 分摊时间, 服务期限, 分摊金额, range_num, start_month):
# 将业务日期开始时间设置为 1号 方便比较
分摊时间 = 分摊时间.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
sb = StringBuilder()
# 计算分摊的最后日期
分摊最后日期 = add_one_month(分摊时间, 服务期限)
print("分摊最后日期==", 分摊最后日期)
for i in range(range_num):
# start_time = datetime.strptime("2020-01-01", "%Y-%m-%d")
start_time = datetime.strptime(start_month, "%Y-%m-%d")
# 添加一个月的日期
calculate_time = add_one_month(start_time, i)
if 分摊时间 <= calculate_time < 分摊最后日期:
sb.append(f"({device_id},'{calculate_time}',{分摊金额}),")
return str(sb)[0 : len(str(sb)) - 1]
def add_one_month(date, i):
# Add one month to the date using timedelta
next_month = date + relativedelta(months=+i)
# print(next_month)
new_date = next_month.replace(day=1)
return new_date
def write_sql(sql):
logger.info(sql)
with open(
"H:\PythonWorkSpaces\deal_mysql_data\\sql14.txt", "a+", encoding="utf8"
) as fw:
fw.write(sql.strip())
fw.write("\n")
class StringBuilder:
def __init__(self):
self.strings = []
def append(self, string):
self.strings.append(string)
def __str__(self):
return "".join(self.strings)
def deal_jianshao_equity_data(ft_table, zj_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
INSERT INTO {zj_table}(`device_id`,`order_year`,`qichu_unit_price`,`zengjia_unit_price`,`jianshao_num`,`jianshao_unit_price`)
SELECT device_id ,LEFT(apportionment_date,4) AS `year`,`apportionment_price`,`apportionment_price` ,count(1) AS num , `apportionment_price`
FROM {ft_table} GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = f"""
UPDATE {zj_table} SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data(base_table, zj_table, device_type, service_type):
bizConn = MySQL(saas_shen_db_cfg)
if service_type == 1:
sql = f"""
SELECT `id`, left(`settle_time`,4) AS 'year',`pk_period`,SUM(IFNULL(hw_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7), pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT `id`, left(`settle_time`,4) AS 'year',`pk_period`,SUM(IFNULL(pk_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7), pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT `id`, left(`settle_time`,4) AS 'year',`pk_period`,SUM(IFNULL(install_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7), pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
device_id = row[0]
year = row[1]
pk_period = row[2]
pk_price = row[3]
sql01 = f"""
UPDATE {zj_table} SET zengjia_num = {pk_period}, zengjia_total_price = {pk_price} WHERE device_id = {device_id} AND order_year = {year};
"""
logger.info(sql01)
bizConn.update(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def deal_qichu_equity_data(zj_table, year_list):
bizConn = MySQL(saas_shen_db_cfg)
for year_num in year_list:
sql = f"""
SELECT id, device_id, order_year, qichu_num, zengjia_num, jianshao_num FROM {zj_table} WHERE order_year= {year_num} ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
id = row[0]
device_id = row[1]
order_year = row[2]
qichu_num = paddnum_price(row[3])
zengjia_num = paddnum_price(row[4])
jianshao_num = paddnum_price(row[5])
# 上一年 下一年期初的数据=当年期初+当年新增-当年减少
next_year = int(order_year) + 1
sql01 = f"""
UPDATE {zj_table} SET qichu_num = {qichu_num + zengjia_num - jianshao_num} WHERE device_id = {device_id} AND order_year = {next_year};
"""
write_sql(sql01)
bizConn.update(sql01)
sql01 = f"""
UPDATE {zj_table} SET qichu_total_price = qichu_num*qichu_unit_price WHERE device_id = {device_id} AND order_year = {next_year};
"""
write_sql(sql01)
bizConn.update(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def paddnum_price(num):
return num if num is not None else 0
def paddstr(strx):
return (
"NULL"
if strx == None
else "'" + MySQLdb.escape_string(str(strx)).decode() + "'"
)
def deal_null_equity_data(zj_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
UPDATE {zj_table} set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE {zj_table} set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv(fileName, year_list):
bizConn = MySQL(saas_shen_db_cfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
headName = (
"id,channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,"
"settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost,fentan_time"
)
for year in year_list:
headName += f",{year}期初数,{year}期初单价,{year}期初金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额"
headName += "\n"
fileHandle.write(headName)
# SELECT teo.id ,teo.order_code, teo.order_time, teo.service_period, teo.total_price FROM temp_eq_order; where teo.id = 251
sql = f"""
SELECT id,channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,sum(pk_price)
,hw_price,install_price,hw_cost,install_cost ,fentan_time FROM temp_dj_device_details_20230620 where `device_type` IN (6,12501) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
logger.info(row)
lineValue = f"{row[0]},{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]},{row[12]},{row[13]},{row[14]},{row[15]},{row[16]},{row[17]},{row[18]}"
for year in year_list:
logger.info("device_id" + str(row[0]) + ";year" + str(year))
sql = f"""
SELECT id,device_id,order_year,qichu_num,qichu_unit_price,qichu_total_price,zengjia_num,zengjia_unit_price,zengjia_total_price,jianshao_num,jianshao_unit_price,jianshao_total_price
FROM temp_dj_device_details_20230620_settle_record_zj tddz WHERE tddz.device_id = {row[0]} AND tddz.order_year = '{year}';
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
if len(result) == 0:
logger.debug(row)
lineValue += f",0,0,0,0,0,0,0,0,0"
else:
for row01 in result:
logger.info(row01)
lineValue += f",{paddnum_price(row01[3])},{paddnum_price(row01[4])},{paddnum_price(row01[5])},{paddnum_price(row01[6])},{paddnum_price(row01[7])},{paddnum_price(row01[8])},{paddnum_price(row01[9])},{paddnum_price(row01[10])},{paddnum_price(row01[11])}"
# 写入一行数据
lineValue += "\n"
logger.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def export_csv_2(base_table, ft_table, zj_table, device_type, fileName, year_list):
bizConn = MySQL(saas_shen_db_cfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
headName = "客户名称,门店,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in year_list:
headName += f",{year}期初数,{year}期初单价,{year}期初金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额"
headName += f",{year}-01分摊,{year}-02分摊,{year}-03分摊,{year}-04分摊,{year}-05分摊,{year}-06分摊,{year}-07分摊,{year}-08分摊,{year}-09分摊,{year}-10分摊,{year}-11分摊,{year}-12分摊"
headName += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
headName += "\n"
fileHandle.write(headName)
if service_type == 1:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(hw_price,0)) as total_price,settle_time,DATE_ADD(settle_time,INTERVAL pk_period MONTH ) as fentan_end_time,hw_price,
sum(hw_price)/pk_period, device_type,min(settle_time),max(settle_time),settle_time,left(settle_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7),pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(pk_price,0)) as total_price,settle_time,DATE_ADD(settle_time,INTERVAL pk_period MONTH ) as fentan_end_time,pk_price,
sum(pk_price)/pk_period, device_type,min(settle_time),max(settle_time),settle_time,left(settle_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7),pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(install_price,0)) as total_price,settle_time,DATE_ADD(settle_time,INTERVAL pk_period MONTH ) as fentan_end_time,install_price,
sum(install_price)/pk_period, device_type,min(settle_time),max(settle_time),settle_time,left(settle_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and settle_time is not null GROUP BY settle_merchant,LEFT(settle_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_year_big_map = getYearDataBigMap(zj_table)
my_month_big_map = getMonthDataBigMap(ft_table)
for row in result:
logger.info(row)
lineValue = f"{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
my_year_map = my_year_big_map.get(row[0])
my_month_map = my_month_big_map.get(row[0])
for year in year_list:
logger.info("device_id" + str(row[0]) + ";year" + str(year))
result = my_year_map.get(str(year))
if result is None or len(result) == 0:
logger.debug(row)
lineValue += f",0,0,0,0,0,0,0,0,0"
else:
logger.info(result)
lineValue += f",{paddnum_price(result[3])},{paddnum_price(result[4])},{paddnum_price(result[5])},{paddnum_price(result[6])},{paddnum_price(result[7])},{paddnum_price(result[8])},{paddnum_price(result[9])},{paddnum_price(result[10])},{paddnum_price(result[11])}"
monthList = getMonthListByYear(year)
for month in monthList:
# my_map = getMonthDataMap(ft_table, row[0])
row_data = my_month_map.get(str(month))
# logger.info(
# "device_id"
# + str(row[0])
# + ",month=="
# + str(month)
# + ",row_data=="
# + str(row_data)
# )
if row_data is None or len(row_data) == 0:
lineValue += f",0"
else:
lineValue += f",{paddnum_price(row_data[3])}"
if row[12] == 6:
lineValue += ",记录仪"
elif row[12] == 12501:
lineValue += ",车充"
elif row[12] == 8:
lineValue += ",GPS"
lineValue += f",{row[13]},{row[14]},{row[15]},{row[16]}"
# 写入一行数据
lineValue += "\n"
logger.info(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def getMonthListByYear(year):
monthList = []
d_str = f"{year}-01-01"
first_month = datetime.strptime(d_str, "%Y-%m-%d").date()
logger.info("first_month==" + str(first_month))
for i in range(12):
next_month = add_one_month(first_month, i)
monthList.append(next_month)
logger.info("monthList==" + str(monthList))
return monthList
def getMonthDataMap(ft_table, device_id):
bizConn = MySQL(saas_shen_db_cfg)
logger.info("device_id" + str(device_id))
sql = f"""
SELECT id,device_id,apportionment_date,apportionment_price FROM {ft_table} WHERE device_id ={device_id};
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_map = {i[2].strftime("%Y-%m-%d"): i for i in result}
logger.info(my_map)
return my_map
def get_job_id(job_info_data):
return job_info_data[1]
def getMonthDataBigMap(ft_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,device_id,apportionment_date,apportionment_price FROM {ft_table};
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_month_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_month_big_map[job_id] = {i[2].strftime("%Y-%m-%d"): i for i in group_list}
print("my_month_big_map:", my_month_big_map)
return my_month_big_map
def getYearDataBigMap(zj_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,device_id,order_year,qichu_num,qichu_unit_price,qichu_total_price,zengjia_num,zengjia_unit_price,zengjia_total_price,jianshao_num,jianshao_unit_price,jianshao_total_price
FROM {zj_table} tddz;
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_year_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_year_big_map[job_id] = {i[2]: i for i in group_list}
print("my_year_big_map:", my_year_big_map)
return my_year_big_map
def calculate(base_table, ft_table, zj_table, device_type, service_type, file_name):
"""
以结算为维度
service_type 1 硬件 hw 2 服务 pk 3 安装 install
"""
if device_type == "8":
year_list = gps_year_list
range_num = gps_range_num
start_month = gps_start_month
else:
year_list = obd_year_list
range_num = obd_range_num
start_month = obd_start_month
# 创建数据表
# BaseCreateTable(ft_table, zj_table).create_table()
# # 处理基础数据
# deal_equity_data(
# base_table, ft_table, device_type, service_type, range_num, start_month
# )
# # 处理减少数据
# deal_jianshao_equity_data(ft_table, zj_table)
# # 处理增加数据
# deal_zengjia_equity_data(base_table, zj_table, device_type, service_type)
# # 处理期初数据
# deal_qichu_equity_data(zj_table, year_list)
# # 处理为NULL的数据
# deal_null_equity_data(zj_table)
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv",year_list)
export_csv_2(base_table, ft_table, zj_table, device_type, file_name, year_list)
if __name__ == "__main__":
# 追踪器
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_settle_hw_record_ft"
zj_table = "temp_dj_device_details_20230620_settle_hw_record_zj"
device_type = "6,12501"
service_type = 1
file_name = "记录仪硬件结算维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_settle_pk_record_ft"
zj_table = "temp_dj_device_details_20230620_settle_pk_record_zj"
device_type = "6,12501"
service_type = 2
file_name = "记录仪服务结算维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_settle_install_record_ft"
zj_table = "temp_dj_device_details_20230620_settle_install_record_zj"
device_type = "6,12501"
service_type = 3
file_name = "记录仪安装结算维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
# GPS
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_settle_hw_gps_ft"
zj_table = "temp_dj_device_details_20230620_settle_hw_gps_zj"
device_type = "8"
service_type = 1
file_name = "GPS硬件结算维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_settle_pk_gps_ft"
zj_table = "temp_dj_device_details_20230620_settle_pk_gps_zj"
device_type = "8"
service_type = 2
file_name = "GPS服务结算维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_20230620"
ft_table = "temp_dj_device_details_20230620_settle_install_gps_ft"
zj_table = "temp_dj_device_details_20230620_settle_install_gps_zj"
device_type = "8"
service_type = 3
file_name = "GPS安装结算维度计算分摊出货汇总-20230626.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
# 记录仪
year_list = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028]
range_num = 120
start_month = "2020-01-01"
obd_year_list = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028]
obd_range_num = 120
obd_start_month = "2020-01-01"
# GPS
# year_list = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028]
# range_num = 160
# start_month = "2017-01-01"
gps_year_list = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028]
gps_range_num = 160
gps_start_month = "2017-01-01"
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!