Commit d24d0a8a by 杨林龙

添加分摊脚本

1 parent b486562d
/.vscode
/.idea
import logging
from my_utils.MysqlUtility import MySQL
logger = logging.getLogger('deal_equity_data')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('../20230404/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',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, base_table='temp_device_details_return_ft', zj_table='temp_device_details_return_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 fentan_0517.base_create_table import BaseCreateTable
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',
'charset': 'utf8'}
def deal_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = '''
SELECT `id`,`sn`,`settle_time`,`pk_period`,`pk_price` FROM dj_device_details_return where `device_type` IN (6,12501);
'''
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_device_details_return_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(103):
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\\sql12.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_device_details_return_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_device_details_return_ft GROUP BY LEFT(apportionment_date,4),device_id ;
'''
logger.info(sql)
bizConn.insert(sql)
sql = '''
UPDATE temp_device_details_return_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)
# SELECT `id`, left(`settle_time`,4) AS 'year',`pk_period`,`pk_price` FROM dj_device_details_return where `device_type` IN (6,12501) group BY id ,left(settle_time,4);
sql = '''
SELECT `id`, left(`settle_time`,4) AS 'year',`pk_period`,`pk_price` FROM dj_device_details_return where `device_type` IN (6,12501);
'''
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_device_details_return_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)
year_arr = [2020, 2021, 2022, 2023, 2024, 2025]
for year_num in year_arr:
sql = f'''
SELECT id, device_id, order_year, qichu_num, zengjia_num, jianshao_num FROM temp_device_details_return_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_device_details_return_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)
sql02 = f'''
UPDATE temp_device_details_return_zj SET qichu_total_price = qichu_num*qichu_unit_price WHERE device_id = {device_id} AND order_year = {next_year};
'''
write_sql(sql02)
bizConn.update(sql02)
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_device_details_return_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
'''
logger.info(sql)
bizConn.update(sql)
sql = f'''
UPDATE temp_device_details_return_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"
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,pk_price
,hw_price,install_price,hw_cost,install_cost FROM dj_device_details_return where `device_type` IN (6,12501);
'''
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]}"
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_device_details_return_zj tddrz WHERE tddrz.device_id = {row[0]} AND tddrz.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()
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")
File mode changed
import logging
from my_utils.MysqlUtility import MySQL
logger = logging.getLogger('deal_equity_data')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('../20230404/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',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, base_table='temp_device_details_ft', zj_table='temp_device_details_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 fentan_0517_02.base_create_table import BaseCreateTable
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',
'charset': 'utf8'}
def deal_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = '''
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(case WHEN pk_price is NULL then 0 else pk_price end) as total_price FROM temp_dj_device_details_jly where `device_type` IN (6,12501) 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_device_details_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(103):
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\\sql12.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_device_details_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_device_details_ft GROUP BY LEFT(apportionment_date,4),device_id ;
'''
logger.info(sql)
bizConn.insert(sql)
sql = '''
UPDATE temp_device_details_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_jly where `device_type` IN (6,12501) 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_device_details_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)
year_arr = [2020, 2021, 2022, 2023, 2024, 2025]
for year_num in year_arr:
sql = f'''
SELECT id, device_id, order_year, qichu_num, zengjia_num, jianshao_num FROM temp_device_details_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_device_details_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_device_details_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_device_details_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
'''
logger.info(sql)
bizConn.update(sql)
sql = f'''
UPDATE temp_device_details_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_jly where `device_type` IN (6,12501) 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_device_details_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")
yearList = [2020, 2021, 2022, 2023, 2024, 2025]
headName = "客户名称,门店,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in yearList:
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_jly where `device_type` IN (6,12501) 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_jly where `device_type` IN (6,12501) 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 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_device_details_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 += ",车充"
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("分摊出货汇总-20230518-2.csv")
File mode changed
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!