Commit bc96a968 by 杨林龙

添加数据处理脚本--分摊

1 parent f69b96f6
import logging
import time
from datetime import datetime, date
from datetime import datetime
from decimal import Decimal
from dateutil.relativedelta import *
......
import logging
from decimal import Decimal
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'}
def deal_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = '''
SELECT id,sub_order_code FROM temp_dj_car_life_installprice tdcli ;
'''
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
print('row===', row)
sql = f'''
SELECT dclgo.order_time,dclgso.total_price,dclgo.merchant_id FROM dj_car_life_goods_sub_order dclgso ,dj_car_life_goods_order dclgo
WHERE dclgso.order_code=dclgo.order_code AND dclgso.sub_order_code='{row[1]}';
'''
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
orderRow = bizConn.fetchOneRow()
print('orderRow===', orderRow)
if orderRow is None:
continue
startTime = orderRow[0].strftime('%Y-%m-%d %I:%M:%S')
print('startTime', startTime)
logger.info('startTime==' + str(startTime))
sql = f'''
SELECT `营销费分润模式及比例` FROM temp_dj_car_sopfzgz tdcs where tdcs.merchant_id = '{orderRow[2]}' and tdcs.`规则开始时间` <= '{startTime}' and tdcs.`规则结束时间` >= '{startTime}' ;
'''
logger.debug(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
commissionRow = bizConn.fetchOneRow()
print('commissionRow===', commissionRow)
if commissionRow is None:
continue
print('commissionRow is not null===', commissionRow)
logger.info('commissionRow is not null===', commissionRow)
sop_price = orderRow[1] * commissionRow[0]
sop_price = Decimal(sop_price).quantize(Decimal("0.00"))
sql01 = f'''
UPDATE temp_dj_car_life_installprice SET sop_price = '{sop_price}' WHERE id = '{row[0]}';
'''
write_sql(sql01)
def write_sql(sql):
logger.info(sql)
with open("H:\PythonWorkSpaces\deal_mysql_data\\sql05.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)
if __name__ == '__main__':
deal_equity_data()
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.35',
'port': 3306,
'user': 'os_user',
'passwd': 'os#123',
'db': 'saas_shen',
'charset': 'utf8'}
class BaseCreateTable:
def __init__(self, base_table='temp_eq_order_ft', zj_table='temp_eq_order_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 {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 '主键',
`order_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_order_id` (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
'''
self.bizConn.query(create_table_sql)
drop_table_sql = f'''
drop table {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 '主键',
`order_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_order_id` (`order_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 datetime
from dateutil.relativedelta import relativedelta
from my_utils.MysqlUtility import MySQL
# g_pro_biz_dbcfg = {'host': '192.168.5.2', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
# 'db': 'glsx_biz_data', 'charset': 'utf8'}
g_pro_biz_dbcfg = {'host': '192.168.5.5', 'port': 3310, 'user': 'biz_device_detail', 'passwd': 'M6khz3CQ',
'db': 'device_detail',
'charset': 'utf8'}
# g_pro_biz_dbcfg = {'host': '192.168.5.5', 'port': 3310, 'user': 'biz_device_detail', 'passwd': 'M6khz3CQ',
# 'db': 'glsx_data',
# 'charset': 'utf8'}
def get_months(begin, end):
begin_year, end_year = begin.year, end.year
begin_month, end_month = begin.month, end.month
if begin_year == end_year:
months = end_month - begin_month
else:
months = (end_year - begin_year) * 12 + end_month - begin_month
return months + 1
def calc_gap_month_of_year(year, pk_start, pk_end):
yearStart = datetime.datetime.strptime(f"{year}-01-01", '%Y-%m-%d')
yearEnd = datetime.datetime.strptime(f"{year}-12-31", '%Y-%m-%d')
gap_month = 0
if pk_start < yearStart < pk_end:
calcStartTime = yearStart
elif yearStart <= pk_start <= yearEnd:
calcStartTime = pk_start
else:
calcStartTime = None
if pk_end < yearStart:
calcEndTime = None
elif yearStart <= pk_end <= yearEnd:
calcEndTime = pk_end
else:
calcEndTime = yearEnd
if calcStartTime is not None and calcEndTime is not None:
gap_month = get_months(calcStartTime, calcEndTime)
return gap_month
def calc_remain_year(year, start_share_month, end_share_month, price, remainTotal, amount):
"""
计算每年余额
:param year:
:return:
"""
gap_months = calc_gap_month_of_year(year, start_share_month, end_share_month)
if gap_months > 0:
share = gap_months * price #
remainShare = remainTotal - share #
else:
share = 0
remainShare = 0
if remainShare > 1.0:
remainTotal = remainShare
else:
remainTotal = amount
remainShare = 0
return share, remainShare, remainTotal
def calc_income_share(calcType='收入'):
"""
计算收入的分摊
:return:
"""
tblName = "dj_device_details"
# tblName = 'dj_2021_settle_details'
fileName = calcType + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '收入':
# and settle_merchant='重庆卡达能汽车用品有限公司'
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month," \
f"DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel " \
f"order by settle_merchant,settle_month"
elif calcType == '成本':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month," \
f"DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel " \
f"order by settle_merchant,settle_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
# datetime_2017_end = datetime.datetime.strptime("2017-12-31", '%Y-%m-%d')
headName = f"客户名称,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入," \
f"2017年摊销金额,2017年末累计摊销余额,2018年摊销金额," \
f"2018年末累计摊销余额,2019年摊销金额,2019年末累计摊销余额,2020年摊销金额,2020年末累计摊销余额,2021年摊销金额," \
f"2021年末累计摊销余额,2022年摊销金额,2022年末累计摊销余额,产品分类,激活开始月份,激活结束月份,研发开始分摊月份 \n"
fileHandle.write(headName)
for row in result:
settleMer = row[0]
devName = row[1]
period = row[2]
if period == 0 or period is None:
period = 12
settle_start_month = row[3]
settle_end_month = datetime.datetime.strptime(settle_start_month, '%Y-%m') \
+ relativedelta(months=period) - relativedelta(days=1)
active_month = row[4]
total = row[5]
amount = row[6]
channel = row[7]
# returnFlag = row[8]
if active_month is None:
start_share = '2030-12'
active_start_month = ''
active_end_month = ''
else:
start_share = active_month
active_start_month = datetime.datetime.strptime(start_share, '%Y-%m')
active_end_month = active_start_month + relativedelta(months=period) - relativedelta(days=1)
# 代销从结算时间开始
if (channel == '代销' or channel == '广汇') and (active_start_month == '' or active_start_month < settle_end_month):
start_share = settle_start_month
#
elif (channel == '直销' and settle_start_month >= '2022-01') and (
active_start_month == '' or active_start_month < settle_end_month):
start_share = settle_start_month
start_share_month = datetime.datetime.strptime(start_share, '%Y-%m')
end_share_month = start_share_month + relativedelta(months=period) - relativedelta(days=1)
price = amount / total
share_per_month = amount / period
'''
gap_2018_months = get_months(start_share_month, datetime_2017_end)
if gap_2018_months > 0:
remainShare2018 = amount - gap_2018_months * share_per_month #2018年末摊销余额
else:
remainShare2018 = 0
if remainShare2018 > 0:
remainTotal = remainShare2018
else:
remainTotal = amount
'''
remainTotal = amount
share_2017, remainShare2017, remainTotal = calc_remain_year(2017, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2018, remainShare2018, remainTotal = calc_remain_year(2018, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2019, remainShare2019, remainTotal = calc_remain_year(2019, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2020, remainShare2020, remainTotal = calc_remain_year(2020, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2021, remainShare2021, remainTotal = calc_remain_year(2021, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2022, remainShare2022, remainTotal = calc_remain_year(2022, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
lineName = f"{settleMer},{channel},{period},{total},{settle_start_month},{amount},{settle_start_month}," \
f"{settle_end_month},{price},{share_per_month},{share_2017},{remainShare2017},{share_2018}," \
f"{remainShare2018},{share_2019},{remainShare2019},{share_2020},{remainShare2020}," \
f"{share_2021},{remainShare2021},{share_2022},{remainShare2022},{devName}," \
f"{active_start_month},{active_end_month},{start_share_month}\n"
fileHandle.write(lineName)
fileHandle.close()
def calc_return_share(calcType):
"""
退货
:return:
"""
tblName = 'dj_2021_settle_details_return'
tblName = 'dj_device_details_return'
fileName = calcType + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '退货成本':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),channel " \
f"order by settle_merchant,settle_month"
elif calcType == '退货收入':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count," \
f"sum(IFNULL(pk_price, 0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),channel " \
f"order by settle_merchant,settle_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
headName = f"客户名称,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入," \
f"2017年摊销金额,2017年末累计摊销余额,2018年摊销金额," \
f"2018年末累计摊销余额,2019年摊销金额,2019年末累计摊销余额,2020年摊销金额,2020年末累计摊销余额,2021年摊销金额," \
f"2021年末累计摊销余额,2022年摊销金额,2022年末累计摊销余额,产品分类 \n"
fileHandle.write(headName)
for row in result:
settleMer = row[0]
devName = row[1]
period = row[2]
if period == 0 or period is None:
period = 12
settle_start_month = row[3]
settle_end_month = datetime.datetime.strptime(settle_start_month, '%Y-%m') \
+ relativedelta(months=period) - relativedelta(days=1)
total = row[4]
amount = row[5]
channel = row[6]
start_share_month = datetime.datetime.strptime(settle_start_month, '%Y-%m')
end_share_month = settle_end_month
price = amount / total
share_per_month = amount / period
remainTotal = amount
share_2017, remainShare2017, remainTotal = calc_remain_year(2017, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2018, remainShare2018, remainTotal = calc_remain_year(2018, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2019, remainShare2019, remainTotal = calc_remain_year(2019, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2020, remainShare2020, remainTotal = calc_remain_year(2020, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2021, remainShare2021, remainTotal = calc_remain_year(2021, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2022, remainShare2022, remainTotal = calc_remain_year(2022, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
lineName = f"{settleMer},{channel},{period},{total},{settle_start_month},{amount},{settle_start_month}," \
f"{settle_end_month},{price},{share_per_month},{share_2017},{remainShare2017},{share_2018}," \
f"{remainShare2018},{share_2019},{remainShare2019},{share_2020},{remainShare2020}," \
f"{share_2021},{remainShare2021},{share_2022},{remainShare2022},{devName}\n"
fileHandle.write(lineName)
fileHandle.close()
def calc_share_per_month(calcType='收入', deviceType=8, isReturn=0):
if deviceType == 8:
strDevType = '(8)'
strDevName = '追踪器'
elif deviceType == 6:
strDevType = '(6,12501)'
strDevName = '记录仪&车充'
fileName = strDevName + calcType + "分摊.csv"
if isReturn == 0:
tblName = "dj_device_details"
else:
tblName = "dj_device_details_return"
fileName = '退货_' + fileName
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '收入':
# and settle_merchant='重庆卡达能汽车用品有限公司'
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count," \
f"sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type in {strDevType} " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),channel " \
f"order by settle_merchant,settle_month"
elif calcType == '成本':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type in {strDevType} " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),channel " \
f"order by settle_merchant,settle_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
shareYears = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
headName = f"客户名称,渠道,产品,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in shareYears:
for month in range(1, 13):
headName += f",{year}-{'%0#2d' % month}分摊"
headName += "\n"
print(headName)
fileHandle.write(headName)
for row in result:
settleMer = row[0]
devName = row[1]
period = row[2]
if period == 0 or period is None:
period = 12
settle_start_month = datetime.datetime.strptime(row[3], '%Y-%m')
settle_end_month = settle_start_month + relativedelta(months=period) - relativedelta(days=1)
calc_settle_month = settle_start_month
total = row[4]
amount = row[5]
channel = row[6]
price = amount / total
share_per_month = amount / period
lineContent = f"{settleMer},{channel},{devName},{period},{total},{settle_start_month},{amount},{settle_start_month}," \
f"{settle_end_month},{price},{share_per_month}"
shareYears = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
for year in shareYears:
for month in range(1, 13):
if year == calc_settle_month.year and month == calc_settle_month.month and calc_settle_month < settle_end_month:
lineContent += f",{share_per_month}"
calc_settle_month += relativedelta(months=1)
else:
lineContent += ",0"
lineContent += '\n'
# print(lineContent)
fileHandle.write(lineContent)
fileHandle.close()
def calc_share_per_month_by_active_merchant(calcType='收入', deviceType=8, isReturn=0):
if deviceType == 8:
strDevType = '(8)'
strDevName = '追踪器'
elif deviceType == 6:
strDevType = '(6,12501)'
strDevName = '记录仪&车充'
fileName = strDevName + calcType + "分摊.csv"
if isReturn == 0:
tblName = "dj_device_details"
else:
tblName = "dj_device_details_return"
fileName = '退货_' + fileName
fileName = "门店_" + fileName
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '收入':
# and settle_merchant='重庆卡达能汽车用品有限公司'
sql = f"select settle_merchant,active_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(active_time, '%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type in {strDevType} " \
f"GROUP BY settle_merchant,active_merchant,device_type,pk_period,DATE_FORMAT(active_time, '%Y-%m'),channel " \
f"order by settle_merchant,active_merchant,active_month"
elif calcType == '成本':
sql = f"select settle_merchant,active_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(active_time, '%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type in {strDevType} " \
f"GROUP BY settle_merchant,active_merchant,device_type,pk_period,DATE_FORMAT(active_time, '%Y-%m'),channel " \
f"order by settle_merchant,active_merchant,active_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
shareYears = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
headName = f"客户名称,门店,渠道,产品,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in shareYears:
for month in range(1, 13):
headName += f",{year}-{'%0#2d' % month}分摊"
headName += "\n"
print(headName)
fileHandle.write(headName)
for row in result:
settleMer = row[0]
activeMer = row[1]
devName = row[2]
period = row[3]
if period == 0 or period is None:
period = 12
activeMonth = row[4]
if activeMonth is None:
activeMonth = '2028-01'
settle_start_month = datetime.datetime.strptime(activeMonth, '%Y-%m')
settle_end_month = settle_start_month + relativedelta(months=period) - relativedelta(days=1)
calc_settle_month = settle_start_month
total = row[5]
amount = row[6]
channel = row[7]
price = amount / total
share_per_month = amount / period
lineContent = f"{settleMer},{activeMer},{channel},{devName},{period},{total},{settle_start_month},{amount},{settle_start_month}," \
f"{settle_end_month},{price},{share_per_month}"
shareYears = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
for year in shareYears:
for month in range(1, 13):
if year == calc_settle_month.year and month == calc_settle_month.month and calc_settle_month < settle_end_month:
lineContent += f",{share_per_month}"
calc_settle_month += relativedelta(months=1)
else:
lineContent += ",0"
lineContent += '\n'
# print(lineContent)
fileHandle.write(lineContent)
fileHandle.close()
def calc_share_per_month_by_active_merchant_es(calcType='收入', deviceType=8, isReturn=0):
if deviceType == 8:
strDevType = '(8)'
strDevName = '追踪器'
fileName = "E盾门店_" + strDevName + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '收入':
sql = '''
select settle_merchant,active_merchant,'追踪器' as device_type,device_period,
DATE_FORMAT(active_time, '%Y-%m') as active_month,COUNT(1) as count,sum(IFNULL(device_price,0)+IFNULL(install_price,0)) as amount from
(
select settle_merchant,active_merchant,device_period,active_time,settle_time,device_price,install_price from d_eshield_device_details_2018 union all
select settle_merchant,active_merchant,device_period,active_time,settle_time,device_price,install_price from d_eshield_device_details_2019 union all
select settle_merchant,active_merchant,device_period,active_time,settle_time,device_price,install_price from d_eshield_device_details_2020_copy union all
select settle_merchant,active_merchant,device_period,active_time,settle_time,device_price,install_price from d_eshield_device_details_2021_copy union all
select settle_merchant,active_merchant,device_period,active_time,settle_time,device_price,install_price from d_eshield_device_details_2022
) as tt where settle_time < '2023-01-01 00:00:00'
GROUP BY settle_merchant,active_merchant,device_period,DATE_FORMAT(active_time, '%Y-%m') order by settle_merchant,active_merchant,active_month
'''
sql = '''
select settle_merchant,active_merchant,'追踪器' as device_type,service_period,
DATE_FORMAT(active_time, '%Y-%m') as active_month,COUNT(1) as count,sum(IFNULL(service_price,0)) as amount from
(
select settle_merchant,active_merchant,service_period,active_time,settle_time,service_price from d_eshield_service_details_2018 union all
select settle_merchant,active_merchant,service_period,active_time,settle_time,service_price from d_eshield_service_details_2019 union all
select settle_merchant,active_merchant,service_period,active_time,settle_time,service_price from d_eshield_service_details_2020_copy union all
select settle_merchant,active_merchant,service_period,active_time,settle_time,service_price from d_eshield_service_details_2021_copy union all
select settle_merchant,active_merchant,service_period,active_time,settle_time,service_price from d_eshield_service_details_2022
) as tt where settle_time < '2023-01-01 00:00:00'
GROUP BY settle_merchant,active_merchant,service_period,DATE_FORMAT(active_time, '%Y-%m') order by settle_merchant,active_merchant,active_month
'''
sql = '''
select settle_merchant,active_merchant,'追踪器' as device_type,device_period,
DATE_FORMAT(active_time, '%Y-%m') as active_month,COUNT(1) as count,sum(IFNULL(device_price,0)+IFNULL(install_price,0)+IFNULL(service_price,0)) as amount from
(
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2018 A left join ( select * from d_eshield_service_details_2018 where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2019 A left join ( select * from d_eshield_service_details_2019 where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2020_copy A left join ( select * from d_eshield_service_details_2020_copy where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2021_copy A left join ( select * from d_eshield_service_details_2021_copy where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2022 A left join( select * from d_eshield_service_details_2022 where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2018 A where from_type =4
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2019 A where from_type =4
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2020_copy A where from_type =4
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2021_copy A where from_type =4
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2022 A where from_type =4
) as tt
GROUP BY settle_merchant,active_merchant,device_period,DATE_FORMAT(active_time, '%Y-%m') order by settle_merchant,active_merchant,active_month
'''
# TODO
# elif calcType == '成本':
# sql = f"select settle_merchant,active_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
# f"pk_period,DATE_FORMAT(active_time, '%Y-%m') as active_month,COUNT(1) as count," \
# f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
# f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type in {strDevType} " \
# f"GROUP BY settle_merchant,active_merchant,device_type,pk_period,DATE_FORMAT(active_time, '%Y-%m'),channel " \
# f"order by settle_merchant,active_merchant,active_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
shareYears = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
headName = f"客户名称,门店,产品,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in shareYears:
for month in range(1, 13):
headName += f",{year}-{'%0#2d' % month}分摊"
headName += "\n"
print(headName)
fileHandle.write(headName)
for row in result:
settleMer = row[0]
activeMer = row[1]
devName = row[2]
period = row[3]
if period == 0 or period is None:
period = 12
activeMonth = row[4]
if activeMonth is None:
activeMonth = '2028-01'
settle_start_month = datetime.datetime.strptime(activeMonth, '%Y-%m')
settle_end_month = settle_start_month + relativedelta(months=period) - relativedelta(days=1)
calc_settle_month = settle_start_month
total = row[5]
amount = row[6]
price = amount / total
share_per_month = amount / period
lineContent = f"{settleMer},{activeMer},{devName},{period},{total},{settle_start_month},{amount},{settle_start_month}," \
f"{settle_end_month},{price},{share_per_month}"
shareYears = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
for year in shareYears:
for month in range(1, 13):
if year == calc_settle_month.year and month == calc_settle_month.month and calc_settle_month < settle_end_month:
lineContent += f",{share_per_month}"
calc_settle_month += relativedelta(months=1)
else:
lineContent += ",0"
lineContent += '\n'
# print(lineContent)
fileHandle.write(lineContent)
fileHandle.close()
def calc_share_year_by_active_merchant_es(calcType='收入', devType=8):
"""
计算收入的分摊
:return:
"""
if devType == 8:
strDevType = '(8)'
strDevName = '追踪器'
priceColunms = "sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0))"
tblName = "dj_device_details"
# tblName = 'dj_2021_settle_details'
fileName = f'门店_{strDevName}_按年分摊_' + calcType + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '收入':
# and settle_merchant='庞大精配网(天津)网络科技有限公司'
sql = '''
select settle_merchant,active_merchant,'追踪器' as device_type,
device_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count,
sum(IFNULL(device_price,0)+IFNULL(install_price,0)+IFNULL(service_price,0)) as amount from
(
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2018 A left join ( select * from d_eshield_service_details_2018 where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2019 A left join ( select * from d_eshield_service_details_2019 where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2020_copy A left join ( select * from d_eshield_service_details_2020_copy where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2021_copy A left join ( select * from d_eshield_service_details_2021_copy where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.device_period,A.active_time,A.settle_time,A.device_price,A.install_price,B.service_price from d_eshield_device_details_2022 A left join( select * from d_eshield_service_details_2022 where from_type !=4) B on A.sn = B.sn
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2018 A where from_type =4
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2019 A where from_type =4
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2020_copy A where from_type =4
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2021_copy A where from_type =4
union all
select A.settle_merchant,A.active_merchant,A.service_period as device_period,A.active_time,A.settle_time,0 as device_price,0 as install_price,A.service_price from d_eshield_service_details_2022 A where from_type =4
) as tt GROUP BY settle_merchant,active_merchant,device_type,device_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m')
order by settle_merchant,active_merchant,settle_month
'''
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
# datetime_2017_end = datetime.datetime.strptime("2017-12-31", '%Y-%m-%d')
headName = f"客户名称,门店,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入,"
yearList = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
for year in yearList:
headName += f"{year}期初数,{year}期单价,{year}期金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额," \
\
headName += f"产品分类,激活开始月份,激活结束月份,研发开始分摊月份\n"
fileHandle.write(headName)
for row in result:
settleMer = row[0]
activeMer = row[1]
devName = row[2]
period = row[3]
if period == 0 or period is None:
period = 12
settle_start_month = row[4]
settle_end_month = datetime.datetime.strptime(settle_start_month, '%Y-%m') \
+ relativedelta(months=period) - relativedelta(days=1)
active_month = row[5]
total = row[6]
amount = row[7]
# 广汇记录仪修改了单价
if devType == 6 and settleMer == '广汇汽车' and gh_record_price_modify.get(settle_start_month, None) is not None:
amount -= total * gh_record_price_modify.get(settle_start_month)
if active_month is None:
start_share = '2030-12'
active_start_month = ''
active_end_month = ''
else:
start_share = active_month
active_start_month = datetime.datetime.strptime(start_share, '%Y-%m')
active_end_month = active_start_month + relativedelta(months=period) - relativedelta(days=1)
# 代销从结算时间开始
# if (channel == '代销' or channel == '广汇') and (active_start_month == '' or active_start_month < settle_end_month):
# start_share = settle_start_month
#
# elif (channel == '直销' and settle_start_month >= '2022-01') and (
# active_start_month == '' or active_start_month < settle_end_month):
# start_share = settle_start_month
start_share_month = datetime.datetime.strptime(start_share, '%Y-%m')
end_share_month = start_share_month + relativedelta(months=period) - relativedelta(days=1)
price = amount / total
share_per_month = amount / period
remainTotalPkPeriod = period * total
pricePerPeriod = price / period
lineValue = f"{settleMer},{activeMer},{period},{total},{settle_start_month},{amount}," \
f"{settle_start_month},{settle_end_month},{price},{share_per_month}"
for yearx in yearList:
sharePeriod, remainPeriod, remainTotalPkPeriod, yearAddPeriod, yearStartPeriod = calc_remain_pkperoid_year(
yearx,
start_share_month, end_share_month, total, remainTotalPkPeriod)
# f"2017期初数,2017期单价,2017期金额,2017增加数,2017增加单价,2017增加金额,,2017减少数,2017减少单价,2017减少金额"
yearStartPrice = 0
if yearStartPeriod > 0:
yearStartPrice = pricePerPeriod
yearAddPrice = 0
if yearAddPeriod > 0:
yearAddPrice = pricePerPeriod
yearSharePrice = 0
if sharePeriod > 0:
yearSharePrice = pricePerPeriod
lineValue += f",{yearStartPeriod},{yearStartPrice},{yearStartPeriod * yearStartPrice}," \
f"{yearAddPeriod},{yearAddPrice},{yearAddPeriod * yearAddPrice}," \
f"{sharePeriod},{yearSharePrice},{sharePeriod * yearSharePrice}"
lineValue += f",{devName},{active_start_month},{active_end_month},{start_share_month}\n"
fileHandle.write(lineValue)
fileHandle.close()
def calc_share_per_month_es():
fileName = 'e盾服务.csv'
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
'''sql =
select settle_merchant,device_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count,sum(IFNULL(device_price,0)) as amount from
(
select settle_merchant,device_period,settle_time,device_price from d_eshield_device_details_2018 union all
select settle_merchant,device_period,settle_time,device_price from d_eshield_device_details_2019 union all
select settle_merchant,device_period,settle_time,device_price from d_eshield_device_details_2020 union all
select settle_merchant,device_period,settle_time,device_price from d_eshield_device_details_2021 union all
select settle_merchant,device_period,settle_time,device_price from d_eshield_device_details_2022
) as tt
GROUP BY settle_merchant,device_period,DATE_FORMAT(settle_time, '%Y-%m') order by settle_merchant,settle_month
'''
sql = '''
select settle_merchant,service_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count,sum(IFNULL(service_price,0)) as amount from
(
select settle_merchant,service_period,settle_time,service_price from d_eshield_service_details_2018 union all
select settle_merchant,service_period,settle_time,service_price from d_eshield_service_details_2019 union all
select settle_merchant,service_period,settle_time,service_price from d_eshield_service_details_2020 union all
select settle_merchant,service_period,settle_time,service_price from d_eshield_service_details_2021 union all
select settle_merchant,service_period,settle_time,service_price from d_eshield_service_details_2022
) as tt
GROUP BY settle_merchant,service_period,DATE_FORMAT(settle_time, '%Y-%m') order by settle_merchant,settle_month
'''
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
shareYears = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
headName = f"客户名称,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in shareYears:
for month in range(1, 13):
headName += f",{year}-{'%0#2d' % month}分摊"
headName += "\n"
print(headName)
fileHandle.write(headName)
for row in result:
settleMer = row[0]
period = row[1]
if period == 0 or period is None:
period = 12
settle_start_month = datetime.datetime.strptime(row[2], '%Y-%m')
settle_end_month = settle_start_month + relativedelta(months=period) - relativedelta(days=1)
calc_settle_month = settle_start_month
total = row[3]
amount = row[4]
price = amount / total
share_per_month = amount / period
lineContent = f"{settleMer},{period},{total},{settle_start_month},{amount},{settle_start_month}," \
f"{settle_end_month},{price},{share_per_month}"
shareYears = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
for year in shareYears:
for month in range(1, 13):
if year == calc_settle_month.year and month == calc_settle_month.month and calc_settle_month < settle_end_month:
lineContent += f",{share_per_month}"
calc_settle_month += relativedelta(months=1)
else:
lineContent += ",0"
lineContent += '\n'
# print(lineContent)
fileHandle.write(lineContent)
fileHandle.close()
gh_record_price_modify = {
'2020-09': 11.8,
'2020-10': 14.29,
'2020-11': 12.71,
'2020-12': 15.82,
'2021-01': 15.14,
'2021-02': 16.30,
'2021-03': 24.01,
'2021-04': 19.01,
'2021-05': 15.71,
'2021-06': 18.14,
'2021-07': 13.26,
'2021-08': 13.50,
'2021-09': 15.47,
'2021-10': 14.57,
'2021-11': 12.37,
'2021-12': 11.58
}
def calc_share_year_by_active_merchant(calcType='收入', devType=8):
"""
计算收入的分摊
:return:
"""
if devType == 8:
strDevType = '(8)'
strDevName = '追踪器'
priceColunms = "sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0))"
elif devType == 6:
strDevType = '(6,12501)'
strDevName = '记录仪&车充'
priceColunms = "sum(IFNULL(pk_price,0))"
tblName = "dj_device_details"
# tblName = 'dj_2021_settle_details'
fileName = f'门店_{strDevName}_按年分摊_' + calcType + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '收入':
# and settle_merchant='庞大精配网(天津)网络科技有限公司'
sql = f"select settle_merchant,active_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month," \
f"DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count," \
f"{priceColunms} as amount, channel " \
f"from (select settle_merchant, CASE when active_time is null then null else active_merchant end as active_merchant," \
f"device_type,settle_time,pk_price,hw_price,install_price,channel,pk_period,active_time from {tblName} " \
f"where settle_time < '2023-01-01 00:00:00' and device_type in {strDevType}) as T " \
f"GROUP BY settle_merchant,active_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel " \
f"order by settle_merchant,active_merchant,settle_month"
elif calcType == '成本':
sql = f"select settle_merchant,active_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month," \
f"DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from (select settle_merchant, CASE when active_time is null then null else active_merchant end as active_merchant," \
f"device_type,settle_time,pk_price,hw_price,install_price,channel,pk_period,active_time from {tblName} " \
f" where settle_time < '2023-01-01 00:00:00' and device_type in {strDevType}) as T " \
f"GROUP BY settle_merchant,active_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel " \
f"order by settle_merchant,active_merchant,settle_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
# datetime_2017_end = datetime.datetime.strptime("2017-12-31", '%Y-%m-%d')
headName = f"客户名称,门店,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入," \
\
yearList = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026]
for year in yearList:
headName += f"{year}期初数,{year}期单价,{year}期金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额," \
\
headName += f"产品分类,激活开始月份,激活结束月份,研发开始分摊月份\n"
fileHandle.write(headName)
for row in result:
settleMer = row[0]
activeMer = row[1]
devName = row[2]
period = row[3]
if period == 0 or period is None:
period = 12
settle_start_month = row[4]
settle_end_month = datetime.datetime.strptime(settle_start_month, '%Y-%m') \
+ relativedelta(months=period) - relativedelta(days=1)
active_month = row[5]
total = row[6]
amount = row[7]
channel = row[8]
# 广汇记录仪修改了单价
if devType == 6 and settleMer == '广汇汽车' and gh_record_price_modify.get(settle_start_month, None) is not None:
amount -= total * gh_record_price_modify.get(settle_start_month)
if active_month is None:
start_share = '2030-12'
active_start_month = ''
active_end_month = ''
else:
start_share = active_month
active_start_month = datetime.datetime.strptime(start_share, '%Y-%m')
active_end_month = active_start_month + relativedelta(months=period) - relativedelta(days=1)
# 代销从结算时间开始
if (channel == '代销' or channel == '广汇') and (active_start_month == '' or active_start_month < settle_end_month):
start_share = settle_start_month
#
elif (channel == '直销' and settle_start_month >= '2022-01') and (
active_start_month == '' or active_start_month < settle_end_month):
start_share = settle_start_month
start_share_month = datetime.datetime.strptime(start_share, '%Y-%m')
end_share_month = start_share_month + relativedelta(months=period) - relativedelta(days=1)
price = amount / total
share_per_month = amount / period
remainTotalPkPeriod = period * total
pricePerPeriod = price / period
lineValue = f"{settleMer},{activeMer},{channel},{period},{total},{settle_start_month},{amount}," \
f"{settle_start_month},{settle_end_month},{price},{share_per_month}"
for yearx in yearList:
sharePeriod, remainPeriod, remainTotalPkPeriod, yearAddPeriod, yearStartPeriod = calc_remain_pkperoid_year(
yearx,
start_share_month, end_share_month, total, remainTotalPkPeriod)
# f"2017期初数,2017期单价,2017期金额,2017增加数,2017增加单价,2017增加金额,,2017减少数,2017减少单价,2017减少金额"
yearStartPrice = 0
if yearStartPeriod > 0:
yearStartPrice = pricePerPeriod
yearAddPrice = 0
if yearAddPeriod > 0:
yearAddPrice = pricePerPeriod
yearSharePrice = 0
if sharePeriod > 0:
yearSharePrice = pricePerPeriod
lineValue += f",{yearStartPeriod},{yearStartPrice},{yearStartPeriod * yearStartPrice}," \
f"{yearAddPeriod},{yearAddPrice},{yearAddPeriod * yearAddPrice}," \
f"{sharePeriod},{yearSharePrice},{sharePeriod * yearSharePrice}"
lineValue += f",{devName},{active_start_month},{active_end_month},{start_share_month}\n"
fileHandle.write(lineValue)
fileHandle.close()
def calc_remain_pkperoid_year(year, start_share_month, end_share_month, totalDevs, totalPeriod):
"""
计算每年套餐余额
:param totalPeriod:
:param totalDevs:
:param end_share_month:
:param start_share_month:
:param year:
:return: 本年分摊的,剩余分摊
"""
yearStartPeriods = 0 # 期初
yearNewPeriod = 0
if year == start_share_month.year:
yearNewPeriod = totalPeriod
yearStartPeriods = 0
elif year > start_share_month.year:
yearStartPeriods = totalPeriod
gap_months = calc_gap_month_of_year(year, start_share_month, end_share_month)
if gap_months > 0:
sharePeriod = gap_months * totalDevs #
remainPeriod = totalPeriod - sharePeriod #
remainTotal = remainPeriod
else:
remainTotal = totalPeriod
sharePeriod = 0
remainPeriod = 0
return sharePeriod, remainPeriod, remainTotal, yearNewPeriod, yearStartPeriods
'''
计算分摊数据
'''
if __name__ == "__main__":
''''''
# calc_income_share(calcType='收入')
# calc_income_share(calcType='成本')
# calc_return_share('退货收入')
# calc_return_share('退货成本')
# calc_share_per_month('收入', 8)
# calc_share_per_month('收入', 6)
# calc_share_per_month('收入', 8, 1)
# calc_share_per_month('收入', 6, 1)
# calc_share_per_month_by_active_merchant('收入', 8)
#
# calc_share_year_by_active_merchant('收入', 6)
calc_share_year_by_active_merchant_es('收入', 8)
import logging
import time
from datetime import datetime
from decimal import Decimal
from dateutil.relativedelta 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.35',
'port': 3306,
'user': 'os_user',
'passwd': 'os#123',
'db': 'saas_shen',
'charset': 'utf8'}
def deal_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = '''
SELECT `id`,`order_code`,`order_time`,`service_period`,`total_price` FROM temp_eq_order;
'''
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)
order_id = row[0]
订单号 = row[1]
下单时间 = row[2]
分摊期限 = row[3]
总金额 = row[4]
分摊金额 = 总金额 / 分摊期限
分摊金额 = Decimal(分摊金额).quantize(Decimal("0.00"))
values = buildApportionment(order_id, 下单时间, 分摊期限, 分摊金额)
sql01 = f'''
INSERT INTO temp_eq_order_ft (order_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(order_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"({order_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\\sql06.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_eq_order_zj(`order_id`,`order_year`,`qichu_unit_price`,`zengjia_unit_price`,`jianshao_num`,`jianshao_unit_price`)
SELECT order_id ,LEFT(apportionment_date,4) AS `year`,`apportionment_price`,`apportionment_price` ,count(1) AS num , `apportionment_price`
FROM temp_eq_order_ft GROUP BY LEFT(apportionment_date,4),order_id ;
'''
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
sql = '''
UPDATE temp_eq_order_zj SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
'''
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
def deal_zengjia_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = '''
SELECT teo.id , left(teo.order_time,4) AS 'year',teo.service_period ,teo.total_price FROM temp_eq_order teo group BY teo.id ,left(teo.order_time,4);
'''
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)
order_id = row[0]
year = row[1]
service_period = row[2]
total_price = row[3]
sql01 = f'''
UPDATE temp_eq_order_zj SET zengjia_num = {service_period}, zengjia_total_price = {total_price} WHERE order_id = {order_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 = [2022, 2023, 2024, 2025]
for year_num in year_arr:
sql = f'''
SELECT id, order_id, order_year, qichu_num, zengjia_num, jianshao_num FROM temp_eq_order_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]
order_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_eq_order_zj SET qichu_num = {qichu_num + zengjia_num - jianshao_num} WHERE order_id = {order_id} AND order_year = {next_year};
'''
write_sql(sql01)
bizConn.update(sql01)
sql01 = f'''
UPDATE temp_eq_order_zj SET qichu_total_price = qichu_num*qichu_unit_price WHERE order_id = {order_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_eq_order_zj set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
'''
bizConn.update(sql)
sql = f'''
UPDATE temp_eq_order_zj set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
'''
bizConn.update(sql)
def export_csv():
bizConn = MySQL(saas_shen_db_cfg)
fileName = "分摊汇总.csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
yearList = [2022, 2023, 2024, 2025]
headName = "customer_name,customer_phone,contract_no,success_date,billing_date,merchant_id,merchant_name,stand_no,vehicle_brand_name," \
"vehicle_series_name,vehicle_shape_name,package_name,actual_sales_price,effective_date,service_period,rollback_time,expiration_date," \
"order_status,source,created_date,unit_price,car_buttom_price,car_highest_price,price_desc"
headName += ",ID,订单号,订单时间,订单总分摊期数,订单总金额"
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;
sql = f'''
SELECT teo.id ,teo.order_code, teo.order_time, teo.service_period, teo.total_price,
eo.customer_name,eo.customer_phone,eo.contract_no,eo.success_date,eo.billing_date,eo.merchant_id,
eo.merchant_name,eo.stand_no,eo.vehicle_brand_name,eo.vehicle_series_name,eo.vehicle_shape_name,eo.package_name,
eo.actual_sales_price,eo.effective_date,eo.service_period,eo.rollback_time,eo.expiration_date,eo.order_status,
eo.source,eo.created_date,eo.unit_price,eo.car_buttom_price,eo.car_highest_price,eo.price_desc
FROM temp_eq_order teo LEFT JOIN equity_order eo ON eo.contract_no =teo.order_code
'''
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[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]},{row[12]},{row[13]},{row[14]},{row[15]}," \
f"{row[16]},{row[17]},{row[18]},{row[19]},{row[20]},{row[21]},{row[22]},{row[23]},{row[24]},{row[25]},{row[26]},{row[27]},{row[28]}"
lineValue += f",{row[0]},{row[1]},{row[2]},{row[3]},{row[4]}"
for year in yearList:
sql = f'''
SELECT id,order_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_eq_order_zj teoz WHERE teoz.order_id = {row[0]} AND teoz.order_year = {year};
'''
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 row in result:
logger.info(row)
lineValue += f",{paddnum_price(row[3])},{paddnum_price(row[4])},{paddnum_price(row[5])},{paddnum_price(row[6])},{paddnum_price(row[7])},{paddnum_price(row[8])},{paddnum_price(row[9])},{paddnum_price(row[10])},{paddnum_price(row[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()
# bizConn = MySQL(saas_shen_db_cfg)
# sql = f'''
# SELECT id,order_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_eq_order_zj teoz WHERE teoz.order_id = 1 AND teoz.order_year = 2024;
# '''
# if not bizConn.query(sql):
# logger.error("deal_equity_data fail, sql=%s", sql)
# result = bizConn.fetchAllRows()
# logger.info('result:' + str(result))
# print('result:' + str(result))
# if len(result) == 0:
# logger.info("null")
# for row in result:
# logger.info(row)
......@@ -3,7 +3,7 @@ def print_hi(name):
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
from datetime import datetime, timedelta
from datetime import datetime
from dateutil.relativedelta import *
......@@ -29,6 +29,6 @@ if __name__ == '__main__':
# print('i===', i)
# Example usage
date = datetime(2021, 4, 20)
new_date = add_one_month(date, 36)
date = datetime(2021, 5, 1)
new_date = add_one_month(date, 1)
print('new_date', new_date) # Output: 2022-04-30 00:00:00
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!