Commit f25bbef4 by 杨林龙

添加杨林龙脚本工作文件夹

1 parent 664466ea
对外审计库: 对外审计库:
192.168.5.25:3310@device_detail 192.168.5.25:3310@glsx_data
内部开发库: 内部开发库:
192.168.5.20:3306@glsx_biz_data 192.168.5.20:3306@glsx_biz_data
......
from MysqlUtility import MySQL, paddstr, paddnum
import datetime
from dateutil.relativedelta import relativedelta
import logging
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.25', 'port': 3310, 'user': 'biz_device_detail', 'passwd': 'M6khz3CQ',
'db': 'device_detail',
'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 + "_01.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"case when `return`=1 then '退货' else '正常' end " \
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,`return` " \
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"case when `return`=1 then '退货' else '正常' end " \
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,`return` " \
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 = '2025-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 #share_per_month: 每年每月摊销多少
'''
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},{returnFlag},{start_share_month}\n"
fileHandle.write(lineName)
fileHandle.close()
def calc_return_share(calcType):
"""
退货
:return:
"""
tblName = 'dj_2021_settle_details_return'
fileName = calcType + "_01.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()
'''
计算分摊数据
'''
if __name__ == "__main__":
calc_income_share(calcType='收入')
calc_income_share(calcType='成本')
calc_return_share('退货收入')
calc_return_share('退货成本')
import pandas as pd
import pymysql
g_pro_biz_dbcfg = {'host': '192.168.5.2', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
def loadFinnanceExcelToMysql(fileName, sheetName):
tableName = "dj_2023_settlment_order_finance"
'''将Excel表数据导入mysql'''
conn_updata = pymysql.Connect(host='192.168.5.2', port=3306, user='biz_glsx_data',
passwd='unEKczDc', db='glsx_biz_data', charset='utf8')
#pd.set_option('display.max_columns', 40)
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
newData = data[['单据类型', '单据编号', '业务日期', '客户', '渠道', '物料编码', '物料名称', '产品类型', '设备类型', '计价数量',
'含税单价', '单价', '收入', '业务类型', '分摊期限']]
'''
newData.rename(columns={'单据类型': 'order_type', '单据编号':'order_no', '业务日期':'finance_time',
'客户':'cus_name', '渠道':'sale_type', '物料编码':'product_code',
'物料名称':'product_name', '产品类型':'product_type', '设备类型':'device_type',
'计价数量':'total', '含税单价':'hw_unit_price_tax', '单价':'hw_unit_price',
'收入':'income', '业务类型':'business_type', '分摊期限':'hw_term'})
'''
newData['含税单价'].fillna(0, inplace=True)
newData['单价'].fillna(0, inplace=True)
newData['收入'].fillna(0, inplace=True)
newData['分摊期限'].fillna(0, inplace=True)
newData['设备类型'].fillna('', inplace=True)
newData['产品类型'].fillna('', inplace=True)
newData['计价数量'].fillna(0, inplace=True)
newData['业务类型'].fillna('', inplace=True)
newData['物料名称'].fillna('', inplace=True)
newData['物料编码'].fillna('', inplace=True)
newData['单据类型'].fillna('', inplace=True)
newData['单据编号'].fillna('', inplace=True)
newData['业务日期'].fillna('', inplace=True)
newData['客户'].fillna('', inplace=True)
newData['渠道'].fillna('', inplace=True)
print(newData.head())
valueArr = []
for idx in newData.index:
hwPriceTax = newData.loc[idx, '含税单价']
hwPrice = newData.loc[idx, '单价']
value = (newData.loc[idx, '单据类型'], newData.loc[idx, '单据编号'], newData.loc[idx, '业务日期'], newData.loc[idx, '客户'],
newData.loc[idx, '渠道'], newData.loc[idx, '物料编码'], newData.loc[idx, '物料名称'], newData.loc[idx, '产品类型'],
newData.loc[idx, '设备类型'], newData.loc[idx, '计价数量'], hwPriceTax, hwPrice,
newData.loc[idx, '收入'], newData.loc[idx, '业务类型'], newData.loc[idx, '分摊期限'])
# print(value)
valueArr.append(value)
cs = conn_updata.cursor()
sql = "insert into " + tableName + "(order_type,order_no,finance_time,cus_name,sale_type,product_code," \
"product_name,product_type,device_type,total,hw_unit_price_tax," \
"hw_unit_price,income,business_type,hw_term) values " \
"(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cs.executemany(sql, valueArr)
conn_updata.commit()
cs.close()
def loadDjExcelToMysql(fileName, sheetName):
tableName = "dj_2023_settlment_order"
'''将Excel表数据导入mysql'''
conn_updata = pymysql.Connect(host='192.168.5.2', port=3306, user='biz_glsx_data',
passwd='unEKczDc', db='glsx_biz_data', charset='utf8')
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
newData = data[['单据类型', '单据编号', '业务日期', '客户', '渠道', '物料编码', '物料名称', '产品类型', '设备类型', '计价数量',
'含税单价', '单价', '硬件(总)(不含税)', '硬件税率', '服务(不含税)', '服务税率', '服务套餐', '收入', '业务类型',
'分摊期限', '安装', '安装税率']]
newData['含税单价'].fillna(0, inplace=True)
newData['单价'].fillna(0, inplace=True)
newData['收入'].fillna(0, inplace=True)
newData['分摊期限'].fillna(0, inplace=True)
newData['硬件(总)(不含税)'].fillna(0, inplace=True)
newData['硬件税率'].fillna(0, inplace=True)
newData['服务(不含税)'].fillna(0, inplace=True)
newData['服务税率'].fillna(0, inplace=True)
newData['服务套餐'].fillna('', inplace=True)
newData['产品类型'].fillna('', inplace=True)
newData['设备类型'].fillna('', inplace=True)
newData['安装'].fillna(0, inplace=True)
newData['安装税率'].fillna(0, inplace=True)
#print(newData)
valueArr = []
for idx in newData.index:
hwPriceTax = newData.loc[idx, '含税单价']
hwPrice = newData.loc[idx, '单价']
newHwPrice = newData.loc[idx, '硬件(总)(不含税)']
newHwTaxRate = newData.loc[idx, '硬件税率']
if newHwPrice != 0:
hwPrice = newHwPrice
hwPriceTax = newHwTaxRate
pkPrice = newData.loc[idx, '服务(不含税)']
pkPriceRate = newData.loc[idx, '服务税率']
client = newData.loc[idx, '客户'].strip()
value = (newData.loc[idx, '单据类型'],
newData.loc[idx, '单据编号'],
newData.loc[idx, '业务日期'],
client,
newData.loc[idx, '渠道'],
newData.loc[idx, '物料编码'],
newData.loc[idx, '物料名称'],
newData.loc[idx, '产品类型'],
newData.loc[idx, '设备类型'],
newData.loc[idx, '计价数量'],
hwPriceTax,
hwPrice,
pkPrice,
pkPriceRate,
newData.loc[idx, '服务套餐'],
newData.loc[idx, '收入'],
newData.loc[idx, '业务类型'],
newData.loc[idx, '分摊期限'],
newData.loc[idx, '分摊期限'],
newData.loc[idx, '安装'],
newData.loc[idx, '安装税率'])
print(value)
valueArr.append(value)
cs = conn_updata.cursor()
sql = "insert into " + tableName + "(order_type,order_no,finance_time,cus_name,sale_type,product_code," \
"product_name,product_type,device_type,total,hw_unit_price_tax," \
"hw_unit_price,pk_unit_price,pk_unit_price_tax,pk_name,income," \
"business_type,hw_term,pk_term,install_unit_price,install_unit_price_tax) " \
"values " \
"(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cs.executemany(sql, valueArr)
conn_updata.commit()
def updateCustomerChannel():
'''更新客户的渠道'''
dbConn = pymysql.Connect(host='192.168.5.2', port=3306, user='biz_glsx_data',
passwd='unEKczDc', db='glsx_biz_data', charset='utf8')
querySql = "SELECT cus_name,sale_type,count(1) from dj_2022_settlment_order_finance group by cus_name,sale_type"
dbCursor = dbConn.cursor()
dbCursor.execute(querySql)
result = dbCursor.fetchall()
cusNameDict = {}
for v in result:
cusName = v[0]
saleType = v[1]
cusNameDict[cusName] = saleType
querySql = "SELECT cus_name,count(1) from dj_2022_settlment_order where finance_time < '2022-02-01' group by cus_name"
dbCursor = dbConn.cursor()
dbCursor.execute(querySql)
result = dbCursor.fetchall()
for v in result:
newCusName = v[0]
newSaleType = cusNameDict.get(newCusName, None)
if newSaleType is None:
print(f"can not find cusname={newCusName}")
continue
updateSql = f"update dj_2022_settlment_order set sale_type='{newSaleType}' where finance_time < '2022-02-01' and cus_name='{newCusName}'"
dbCursor = dbConn.cursor()
dbCursor.execute(updateSql)
dbConn.commit()
print("done")
if __name__ == "__main__":
# 财务原表
# filePath = "C:\\Users\\333\\Desktop\\2022审计\\"
# fileName = filePath + "财务与研发收入数据核对-0116.xlsx"
# sheetName = "汇总"
# loadFinnanceExcelToMysql(fileName, sheetName)
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据-2023年1月-4月份\\应收拆分数据4月份\\"
# 处理财务原表
fileName = filePath + "数据源-激活调整用23年4月.xlsx"
sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName)
# E盾
fileName = filePath + "4.数据源-激活调整用23年4月-陈冰恋.xlsx"
sheetName = '1.3.虎哥E盾--渠道应收单原表'
loadDjExcelToMysql(fileName, sheetName)
# # 渠道嘀加
fileName = filePath + "2.拆分数据-渠道2023年4月嘀加数据-柳云飞.xlsx"
sheetName = 'Sheet2'
loadDjExcelToMysql(fileName, sheetName)
# # # 直销
fileName = filePath + "1.数据源-激活调整用23年4月-廖敏玲.xlsx"
sheetName = '廖敏玲'
loadDjExcelToMysql(fileName, sheetName)
print("done")
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!