Commit e71d8887 by 杨林龙

提交审计计算代码

1 parent 569e7f46
Showing 40 changed files with 4831 additions and 0 deletions
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {
"host": "192.168.3.222",
"port": 3306,
"user": "biz_audit",
"passwd": "hqVIs6jF",
"db": "saas_shen_ft",
"charset": "utf8",
}
class BaseCreateTable:
def __init__(
self,
base_table="temp_dj_device_details_modify_serins_gps_ft",
zj_table="temp_dj_device_details_modify_serins_gps_zj",
):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = base_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f"""
drop table if exists {self.base_table};
"""
self.bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
"""
self.bizConn.query(create_table_sql)
drop_table_sql = f"""
drop table if exists {self.zj_table};
"""
self.bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
"""
self.bizConn.query(create_table_sql)
if __name__ == "__main__":
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
import MySQLdb
from base_create_table import BaseCreateTable
from dateutil.relativedelta import *
from my_config.config import *
from my_utils.MysqlUtility import MySQL
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",
}
def deal_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price FROM temp_dj_device_details_modify_serins where `device_type` IN (8) 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, 分摊时间, 服务期限, 分摊金额)
sql01 = f"""
INSERT INTO temp_dj_device_details_modify_serins_gps_ft (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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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\\sql15.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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
INSERT INTO temp_dj_device_details_modify_serins_gps_zj(`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 temp_dj_device_details_modify_serins_gps_ft GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = """
UPDATE temp_dj_device_details_modify_serins_gps_zj SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price
FROM temp_dj_device_details_modify_serins where `device_type` IN (8) 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 temp_dj_device_details_modify_serins_gps_zj 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():
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 temp_dj_device_details_modify_serins_gps_zj 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 temp_dj_device_details_modify_serins_gps_zj 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 temp_dj_device_details_modify_serins_gps_zj 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():
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
UPDATE temp_dj_device_details_modify_serins_gps_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE temp_dj_device_details_modify_serins_gps_zj set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv(fileName):
bizConn = MySQL(saas_shen_db_cfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
yearList = [2020, 2021, 2022, 2023, 2024, 2025]
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 yearList:
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_modify_serins 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 yearList:
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_modify_serins_gps_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(fileName):
bizConn = MySQL(saas_shen_db_cfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
year_list = [2022]
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)
# 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_modify_serins where `device_type` IN (8) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time, SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0) as pk_price,
SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0))/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM temp_dj_device_details_modify_serins where `device_type` IN (8) 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[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
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_modify_serins_gps_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])}"
monthList = getMonthListByYear(year)
for month in monthList:
my_map = getMonthDataMap(row[0])
row_data = my_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.debug(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(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 temp_dj_device_details_modify_serins_gps_ft 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
if __name__ == "__main__":
# 创建数据表
# BaseCreateTable().create_table()
# 处理基础数据
# deal_equity_data()
# 处理减少数据
# deal_jianshao_equity_data()
# 处理增加数据
# deal_zengjia_equity_data()
# 处理期初数据
# deal_qichu_equity_data()
# 处理为NULL的数据
# deal_null_equity_data()
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2("2022年GPS收入分摊出货汇总-20230621.csv")
# monthList = getMonthListByYear("2022")
# print("monthList==", monthList)
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {'host': '192.168.3.222',
'port': 3306,
'user': 'biz_audit',
'passwd': 'hqVIs6jF',
'db': 'saas_shen_ft',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, base_table='temp_dj_device_details_20230620_active_gps_ft', zj_table='temp_dj_device_details_20230620_active_gps_zj'):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = base_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f'''
drop table if exists {self.base_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
'''
self.bizConn.query(create_table_sql)
drop_table_sql = f'''
drop table if exists {self.zj_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
'''
self.bizConn.query(create_table_sql)
if __name__ == '__main__':
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price FROM temp_dj_device_details_20230620 where `device_type` IN (8) 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, 分摊时间, 服务期限, 分摊金额)
sql01 = f"""
INSERT INTO temp_dj_device_details_20230620_active_gps_ft (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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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")
# 添加一个月的日期
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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
INSERT INTO temp_dj_device_details_20230620_active_gps_zj(`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 temp_dj_device_details_20230620_active_gps_ft GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = """
UPDATE temp_dj_device_details_20230620_active_gps_zj SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(case WHEN pk_price is NULL then 0 else pk_price end) as total_price
FROM temp_dj_device_details_20230620 where `device_type` IN (8) 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 temp_dj_device_details_20230620_active_gps_zj 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():
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 temp_dj_device_details_20230620_active_gps_zj 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 temp_dj_device_details_20230620_active_gps_zj 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 temp_dj_device_details_20230620_active_gps_zj 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():
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
UPDATE temp_dj_device_details_20230620_active_gps_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE temp_dj_device_details_20230620_active_gps_zj set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv(fileName):
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 (8) 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_active_gps_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(fileName):
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 += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
headName += "\n"
fileHandle.write(headName)
# 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 (8) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time, sum(pk_price) 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 temp_dj_device_details_20230620 where `device_type` IN (8) 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[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
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_active_gps_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])}"
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.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
if __name__ == "__main__":
# 创建数据表
BaseCreateTable().create_table()
# 处理基础数据
deal_equity_data()
# 处理减少数据
deal_jianshao_equity_data()
# 处理增加数据
deal_zengjia_equity_data()
# 处理期初数据
deal_qichu_equity_data()
# 处理为NULL的数据
deal_null_equity_data()
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2("GPS激活维度计算分摊出货汇总-20236020.csv")
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {'host': '192.168.3.222',
'port': 3306,
'user': 'biz_audit',
'passwd': 'hqVIs6jF',
'db': 'saas_shen_ft',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, base_table='temp_dj_device_details_20230620_active_record_ft', zj_table='temp_dj_device_details_20230620_active_record_zj'):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = base_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f'''
drop table if exists {self.base_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
'''
self.bizConn.query(create_table_sql)
drop_table_sql = f'''
drop table if exists {self.zj_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
'''
self.bizConn.query(create_table_sql)
if __name__ == '__main__':
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
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():
"""
SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price
SUM(case WHEN pk_price is NULL then 0 else pk_price end) as total_price
"""
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price 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:
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, 分摊时间, 服务期限, 分摊金额)
sql01 = f"""
INSERT INTO temp_dj_device_details_20230620_active_record_ft (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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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")
# 添加一个月的日期
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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
INSERT INTO temp_dj_device_details_20230620_active_record_zj(`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 temp_dj_device_details_20230620_active_record_ft GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = """
UPDATE temp_dj_device_details_20230620_active_record_zj SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price
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:
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 temp_dj_device_details_20230620_active_record_zj 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():
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 temp_dj_device_details_20230620_active_record_zj 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 temp_dj_device_details_20230620_active_record_zj 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 temp_dj_device_details_20230620_active_record_zj 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():
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
UPDATE temp_dj_device_details_20230620_active_record_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE temp_dj_device_details_20230620_active_record_zj set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv(fileName):
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_active_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(fileName):
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 += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
headName += "\n"
fileHandle.write(headName)
# 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 ;
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time, sum(pk_price) 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 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[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
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_active_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])}"
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.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
if __name__ == "__main__":
# 创建数据表
BaseCreateTable().create_table()
# 处理基础数据
deal_equity_data()
# 处理减少数据
deal_jianshao_equity_data()
# 处理增加数据
deal_zengjia_equity_data()
# 处理期初数据
deal_qichu_equity_data()
# 处理为NULL的数据
deal_null_equity_data()
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2("记录仪激活维度计算分摊出货汇总-20236020.csv")
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {'host': '192.168.3.222',
'port': 3306,
'user': 'biz_audit',
'passwd': 'hqVIs6jF',
'db': 'saas_shen_ft',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, base_table='temp_dj_device_details_20230620_settle_gps_ft', zj_table='temp_dj_device_details_20230620_settle_gps_zj'):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = base_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f'''
drop table if exists {self.base_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
'''
self.bizConn.query(create_table_sql)
drop_table_sql = f'''
drop table if exists {self.zj_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
'''
self.bizConn.query(create_table_sql)
if __name__ == '__main__':
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`,`sn`,`settle_time`,`pk_period`,SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price FROM temp_dj_device_details_20230620 where `device_type` IN (8) 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, 分摊时间, 服务期限, 分摊金额)
sql01 = f"""
INSERT INTO temp_dj_device_details_20230620_settle_gps_ft (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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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")
# 添加一个月的日期
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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
INSERT INTO temp_dj_device_details_20230620_settle_gps_zj(`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 temp_dj_device_details_20230620_settle_gps_ft GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = """
UPDATE temp_dj_device_details_20230620_settle_gps_zj SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(case WHEN pk_price is NULL then 0 else pk_price end) as total_price
FROM temp_dj_device_details_20230620 where `device_type` IN (8) 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 temp_dj_device_details_20230620_settle_gps_zj 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():
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 temp_dj_device_details_20230620_settle_gps_zj 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 temp_dj_device_details_20230620_settle_gps_zj 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 temp_dj_device_details_20230620_settle_gps_zj 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():
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
UPDATE temp_dj_device_details_20230620_settle_gps_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE temp_dj_device_details_20230620_settle_gps_zj set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv(fileName):
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 (8) 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_gps_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(fileName):
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 += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
headName += "\n"
fileHandle.write(headName)
# 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 (8) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time, sum(pk_price) 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(settle_time),max(settle_time),settle_time,left(settle_time,4)
FROM temp_dj_device_details_20230620 where `device_type` IN (8) 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[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
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_gps_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])}"
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.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
if __name__ == "__main__":
# 创建数据表
BaseCreateTable().create_table()
# 处理基础数据
deal_equity_data()
# 处理减少数据
deal_jianshao_equity_data()
# 处理增加数据
deal_zengjia_equity_data()
# 处理期初数据
deal_qichu_equity_data()
# 处理为NULL的数据
deal_null_equity_data()
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2("GPS结算维度计算分摊出货汇总-20230620.csv")
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {'host': '192.168.3.222',
'port': 3306,
'user': 'biz_audit',
'passwd': 'hqVIs6jF',
'db': 'saas_shen_ft',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, base_table='temp_dj_device_details_20230620_settle_record_ft', zj_table='temp_dj_device_details_20230620_settle_record_zj'):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = base_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f'''
drop table if exists {self.base_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
'''
self.bizConn.query(create_table_sql)
drop_table_sql = f'''
drop table if exists {self.zj_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
'''
self.bizConn.query(create_table_sql)
if __name__ == '__main__':
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`,`sn`,`settle_time`,`pk_period`,SUM(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as total_price FROM temp_dj_device_details_20230620 where `device_type` IN (6,12501) 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, 分摊时间, 服务期限, 分摊金额)
sql01 = f"""
INSERT INTO temp_dj_device_details_20230620_settle_record_ft (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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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")
# 添加一个月的日期
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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
INSERT INTO temp_dj_device_details_20230620_settle_record_zj(`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 temp_dj_device_details_20230620_settle_record_ft GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = """
UPDATE temp_dj_device_details_20230620_settle_record_zj SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(case WHEN pk_price is NULL then 0 else pk_price end) as total_price
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:
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 temp_dj_device_details_20230620_settle_record_zj 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():
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 temp_dj_device_details_20230620_settle_record_zj 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 temp_dj_device_details_20230620_settle_record_zj 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 temp_dj_device_details_20230620_settle_record_zj 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():
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
UPDATE temp_dj_device_details_20230620_settle_record_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE temp_dj_device_details_20230620_settle_record_zj set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv(fileName):
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(fileName):
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 += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
headName += "\n"
fileHandle.write(headName)
# 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 ;
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time, sum(pk_price) 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(settle_time),max(settle_time),settle_time,left(settle_time,4)
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[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
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])}"
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.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
if __name__ == "__main__":
# 创建数据表
BaseCreateTable().create_table()
# 处理基础数据
deal_equity_data()
# 处理减少数据
deal_jianshao_equity_data()
# 处理增加数据
deal_zengjia_equity_data()
# 处理期初数据
deal_qichu_equity_data()
# 处理为NULL的数据
deal_null_equity_data()
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2("记录仪结算维度计算分摊出货汇总-20230620.csv")
import logging
from my_utils.MysqlUtility import MySQL
logger = logging.getLogger('deal_equity_data')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('../fentan_0522/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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {'host': '192.168.3.222',
'port': 3306,
'user': 'biz_audit',
'passwd': 'hqVIs6jF',
'db': 'saas_shen_ft',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, base_table='temp_dj_device_details_modify_serins_gps_ft', zj_table='temp_dj_device_details_modify_serins_gps_zj'):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = base_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f'''
drop table if exists {self.base_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
'''
self.bizConn.query(create_table_sql)
drop_table_sql = f'''
drop table if exists {self.zj_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
'''
self.bizConn.query(create_table_sql)
if __name__ == '__main__':
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
import MySQLdb
from base_create_table import BaseCreateTable
from dateutil.relativedelta import *
from my_config.config import *
from my_utils.MysqlUtility import MySQL
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",
}
def deal_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(hw_cost,0)+IFNULL(install_cost,0)) as total_price FROM temp_dj_device_details_modify_serins where `device_type` IN (8) 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, 分摊时间, 服务期限, 分摊金额)
sql01 = f"""
INSERT INTO temp_dj_device_details_modify_serins_cost_gps_ft (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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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\\sql15.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():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
INSERT INTO temp_dj_device_details_modify_serins_cost_gps_zj(`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 temp_dj_device_details_modify_serins_cost_gps_ft GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = """
UPDATE temp_dj_device_details_modify_serins_cost_gps_zj SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(IFNULL(hw_cost,0)+IFNULL(install_cost,0)) as total_price
FROM temp_dj_device_details_modify_serins where `device_type` IN (8) 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 temp_dj_device_details_modify_serins_cost_gps_zj 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():
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 temp_dj_device_details_modify_serins_cost_gps_zj 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 temp_dj_device_details_modify_serins_cost_gps_zj 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 temp_dj_device_details_modify_serins_cost_gps_zj 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():
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
UPDATE temp_dj_device_details_modify_serins_cost_gps_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE temp_dj_device_details_modify_serins_cost_gps_zj set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv_2(fileName):
bizConn = MySQL(saas_shen_db_cfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
headName = "客户名称,门店,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
year_list = [2022]
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)
# 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_modify_serins where `device_type` IN (8) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time, SUM(IFNULL(hw_cost,0)+IFNULL(install_cost,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,IFNULL(hw_cost,0)+IFNULL(install_cost,0) as pk_price,
SUM(IFNULL(hw_cost,0)+IFNULL(install_cost,0))/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM temp_dj_device_details_modify_serins where `device_type` IN (8) 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[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
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_modify_serins_cost_gps_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])}"
monthList = getMonthListByYear(year)
for month in monthList:
my_map = getMonthDataMap(row[0])
row_data = my_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.debug(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(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 temp_dj_device_details_modify_serins_cost_gps_ft 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
if __name__ == "__main__":
# 创建数据表
BaseCreateTable(
"temp_dj_device_details_modify_serins_cost_gps_ft",
"temp_dj_device_details_modify_serins_cost_gps_zj",
).create_table()
# 处理基础数据
deal_equity_data()
# 处理减少数据
deal_jianshao_equity_data()
# 处理增加数据
deal_zengjia_equity_data()
# 处理期初数据
deal_qichu_equity_data()
# 处理为NULL的数据
deal_null_equity_data()
# 导出 csv
export_csv_2("2022年GPS成本分摊出货汇总-20230621.csv")
# monthList = getMonthListByYear("2022")
# print("monthList==", monthList)
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {'host': '192.168.3.222',
'port': 3306,
'user': 'biz_audit',
'passwd': 'hqVIs6jF',
'db': 'saas_shen_ft',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, ft_table='temp_dj_device_details_20230620_settle_record_ft', zj_table='temp_dj_device_details_20230620_settle_record_zj'):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = ft_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f'''
drop table if exists {self.base_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
'''
self.bizConn.query(create_table_sql)
drop_table_sql = f'''
drop table if exists {self.zj_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
'''
self.bizConn.query(create_table_sql)
if __name__ == '__main__':
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
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):
"""
以结算为维度
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, 分摊时间, 服务期限, 分摊金额)
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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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):
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):
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, zj_table, device_type, fileName):
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 += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
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()
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]}"
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 {zj_table} 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])}"
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.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def calculate(base_table, ft_table, zj_table, device_type, service_type, file_name):
"""
以结算为维度
service_type 1 硬件 hw 2 服务 pk 3 安装 install
"""
# 创建数据表
BaseCreateTable(ft_table, zj_table).create_table()
# 处理基础数据
deal_equity_data(base_table, ft_table, device_type, service_type)
# 处理减少数据
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)
# 处理为NULL的数据
deal_null_equity_data(zj_table)
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2(base_table, zj_table, device_type, file_name)
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 = "记录仪硬件激活维度计算分摊出货汇总-20230620.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 = "记录仪服务激活维度计算分摊出货汇总-20230620.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 = "记录仪安装激活维度计算分摊出货汇总-20230620.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硬件激活维度计算分摊出货汇总-20230620.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服务激活维度计算分摊出货汇总-20230620.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安装激活维度计算分摊出货汇总-20230620.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {
"host": "192.168.3.222",
"port": 3306,
"user": "biz_audit",
"passwd": "hqVIs6jF",
"db": "saas_shen_ft",
"charset": "utf8",
}
class BaseCreateTable:
def __init__(self, ft_table, zj_table):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = ft_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f"""
drop table if exists {self.base_table};
"""
self.bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
"""
self.bizConn.query(create_table_sql)
drop_table_sql = f"""
drop table if exists {self.zj_table};
"""
self.bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
"""
self.bizConn.query(create_table_sql)
if __name__ == "__main__":
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
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):
"""
以结算为维度
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, 分摊时间, 服务期限, 分摊金额)
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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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("2017-01-01", "%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):
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):
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, zj_table, device_type, fileName):
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 += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
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()
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]}"
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 {zj_table} 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])}"
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.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def calculate(base_table, ft_table, zj_table, device_type, service_type, file_name):
"""
以结算为维度
service_type 1 硬件 hw 2 服务 pk 3 安装 install
"""
# 创建数据表
BaseCreateTable(ft_table, zj_table).create_table()
# 处理基础数据
deal_equity_data(base_table, ft_table, device_type, service_type)
# 处理减少数据
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)
# 处理为NULL的数据
deal_null_equity_data(zj_table)
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2(base_table, zj_table, device_type, file_name)
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 = "记录仪硬件结算维度计算分摊出货汇总-20230620.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 = "记录仪服务结算维度计算分摊出货汇总-20230620.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 = "记录仪安装结算维度计算分摊出货汇总-20230620.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硬件结算维度计算分摊出货汇总-20230620.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服务结算维度计算分摊出货汇总-20230620.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安装结算维度计算分摊出货汇总-20230620.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {'host': '192.168.3.222',
'port': 3306,
'user': 'biz_audit',
'passwd': 'hqVIs6jF',
'db': 'saas_shen_ft',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, ft_table='temp_dj_device_details_20230620_settle_record_ft', zj_table='temp_dj_device_details_20230620_settle_record_zj'):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = ft_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f'''
drop table if exists {self.base_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
'''
self.bizConn.query(create_table_sql)
drop_table_sql = f'''
drop table if exists {self.zj_table};
'''
self.bizConn.query(drop_table_sql)
create_table_sql = f'''
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
'''
self.bizConn.query(create_table_sql)
if __name__ == '__main__':
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
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):
"""
以结算为维度
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, 分摊时间, 服务期限, 分摊金额)
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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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):
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):
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):
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()
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]}"
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 {zj_table} 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])}"
monthList = getMonthListByYear(year)
for month in monthList:
my_map = getMonthDataMap(ft_table, row[0])
row_data = my_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.debug(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 calculate(base_table, ft_table, zj_table, device_type, service_type, file_name):
"""
以结算为维度
service_type 1 硬件 hw 2 服务 pk 3 安装 install
"""
# 创建数据表
BaseCreateTable(ft_table, zj_table).create_table()
# 处理基础数据
deal_equity_data(base_table, ft_table, device_type, service_type)
# 处理减少数据
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)
# 处理为NULL的数据
deal_null_equity_data(zj_table)
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2(base_table, ft_table, zj_table, device_type, file_name)
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 = "记录仪硬件激活维度计算分摊出货汇总-20230620.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 = "记录仪服务激活维度计算分摊出货汇总-20230620.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 = "记录仪安装激活维度计算分摊出货汇总-20230620.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硬件激活维度计算分摊出货汇总-20230620.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服务激活维度计算分摊出货汇总-20230620.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安装激活维度计算分摊出货汇总-20230620.csv"
# calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
import logging
from my_utils.MysqlUtility import MySQL
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.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
saas_shen_db_cfg = {
"host": "192.168.3.222",
"port": 3306,
"user": "biz_audit",
"passwd": "hqVIs6jF",
"db": "saas_shen_ft",
"charset": "utf8",
}
class BaseCreateTable:
def __init__(self, ft_table, zj_table):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = ft_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f"""
drop table if exists {self.base_table};
"""
self.bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
"""
self.bizConn.query(create_table_sql)
drop_table_sql = f"""
drop table if exists {self.zj_table};
"""
self.bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
"""
self.bizConn.query(create_table_sql)
if __name__ == "__main__":
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
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):
"""
以结算为维度
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, 分摊时间, 服务期限, 分摊金额)
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, 分摊时间, 服务期限, 分摊金额):
# 将业务日期开始时间设置为 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("2017-01-01", "%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):
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):
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):
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 += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
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()
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]}"
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 {zj_table} 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])}"
monthList = getMonthListByYear(year)
for month in monthList:
my_map = getMonthDataMap(ft_table, row[0])
row_data = my_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.debug(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 calculate(base_table, ft_table, zj_table, device_type, service_type, file_name):
"""
以结算为维度
service_type 1 硬件 hw 2 服务 pk 3 安装 install
"""
# 创建数据表
BaseCreateTable(ft_table, zj_table).create_table()
# 处理基础数据
deal_equity_data(base_table, ft_table, device_type, service_type)
# 处理减少数据
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)
# 处理为NULL的数据
deal_null_equity_data(zj_table)
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv")
export_csv_2(base_table, ft_table, zj_table, device_type, file_name)
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 = "记录仪硬件结算维度计算分摊出货汇总-20230620.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 = "记录仪服务结算维度计算分摊出货汇总-20230620.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 = "记录仪安装结算维度计算分摊出货汇总-20230620.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硬件结算维度计算分摊出货汇总-20230620.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服务结算维度计算分摊出货汇总-20230620.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安装结算维度计算分摊出货汇总-20230620.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"
# GPS
# year_list = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028]
# range_num = 160
# 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!