Commit a1c2704d by 杨林龙

优化成本收入字段的写入

1 parent f25bbef4
/.idea
/.vscode
/__pycache__
yangll/init/__pycache__/base_create_table.cpython-39.pyc
yangll/init/__pycache__/StringBuilder.cpython-39.pyc
yangll/init/__pycache__/Utils.cpython-39.pyc
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'}
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",
)
'''将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)
# pd.set_option('display.max_columns', 40)
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
newData = data[['单据类型', '单据编号', '业务日期', '客户', '渠道', '物料编码', '物料名称', '产品类型', '设备类型', '计价数量',
'含税单价', '单价', '收入', '业务类型', '分摊期限']]
'''
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)
"""
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)
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, '分摊期限'])
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, "分摊期限"],
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)"
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,cost) values "
"(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
)
cs.executemany(sql, valueArr)
conn_updata.commit()
cs.close()
......@@ -67,80 +114,124 @@ def loadFinnanceExcelToMysql(fileName, sheetName):
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')
"""将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)
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)
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, '硬件税率']
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, '安装税率'])
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, "安装税率"],
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)"
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,cost) "
"values "
"(%s,%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')
"""更新客户的渠道"""
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)
......@@ -176,26 +267,84 @@ if __name__ == "__main__":
# sheetName = "汇总"
# loadFinnanceExcelToMysql(fileName, sheetName)
# 一二月份
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据-2023年1月-4月份\\应收拆分数据1-2月份\\"
# 处理财务原表
fileName = filePath + "数据源-激活调整用23年1-2月.xlsx"
sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName)
# E盾
fileName = filePath + "1.拆分数据-虎哥E盾结算单与明细数据-陈冰恋.xlsx"
sheetName = "3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName)
# 渠道嘀加
fileName = filePath + "3.拆分数据-渠道2023年1-2月嘀加数据-柳云飞.xlsx"
sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName)
# 直销
fileName = filePath + "4.拆分数据-广汇23年1-2月-廖敏玲.xlsx"
sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName)
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据-2023年1月-4月份\\应收拆分数据4月份\\"
# 三月份
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据-2023年1月-4月份\\应收拆分数据3月份\\"
# 处理财务原表
# fileName = filePath + "数据源-激活调整用23年4月.xlsx"
# sheetName = "Sheet1"
# loadFinnanceExcelToMysql(fileName, sheetName)
fileName = filePath + "数据源-激活调整用23年2-3月.xlsx"
sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName)
# E盾
fileName = filePath + "4.数据源-激活调整用23年3月-陈冰恋.xlsx"
sheetName = "3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName)
# 渠道嘀加
fileName = filePath + "2.拆分数据-渠道2023年3月嘀加数据-柳云飞.xlsx"
sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName)
# 直销
fileName = filePath + "1.数据源-激活调整用2023年3月-廖敏玲.xlsx"
sheetName = "廖敏玲"
loadDjExcelToMysql(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 + "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 = '廖敏玲'
sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName)
# 五月份
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据5月份"
# 处理财务原表
fileName = filePath + "数据源-激活调整用23年5月.xlsx"
sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName)
# E盾
fileName = filePath + "4.数据源-激活调整用23年5月-陈冰恋.xlsx"
sheetName = "1.3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName)
# 渠道嘀加
fileName = filePath + "2.拆分数据-渠道2023年5月嘀加数据-柳云飞.xlsx"
sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName)
# 直销
fileName = filePath + "1.数据源-激活调整用23年5月-廖敏玲.xlsx"
sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName)
print("done")
......@@ -2,15 +2,27 @@ 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'}
'''
from init.base_create_table import BaseCreateTable
from init.StringBuilder import StringBuilder
from init.Utils import *
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'}
'''
"""
# 设置全局参数
base_table = "temp_ft_table"
def get_months(begin, end):
......@@ -23,10 +35,11 @@ def get_months(begin, end):
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')
def calc_gap_month_of_year(year, pk_start, pk_end, price, device_id):
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
my_fentan_detail_map = {}
if pk_start < yearStart < pk_end:
calcStartTime = yearStart
......@@ -44,16 +57,86 @@ def calc_gap_month_of_year(year, pk_start, pk_end):
if calcStartTime is not None and calcEndTime is not None:
gap_month = get_months(calcStartTime, calcEndTime)
return gap_month
# 将分摊明细写入分摊表中
# insertDataToFt(device_id, calcStartTime, calcEndTime, price)
# 建立分摊map 在内存中处理分摊明细
buildFenTanDetailMap(calcStartTime, calcEndTime, price, my_fentan_detail_map)
return gap_month, my_fentan_detail_map
def buildFenTanDetailMap(calcStartTime, calcEndTime, price, my_fentan_detail_map):
calcStartTime = calcStartTime.replace(
day=1, hour=0, minute=0, second=0, microsecond=0
)
for i in range(12):
# 添加一个月的日期
calculate_time = add_one_month(calcStartTime, i)
if calcStartTime <= calculate_time < calcEndTime:
fentan_detail_time = calculate_time.strftime("%Y-%m-%d")
my_fentan_detail_map[fentan_detail_time] = price
return my_fentan_detail_map
def buildApportionment(device_id, calcStartTime, calcEndTime, price):
# 将业务日期开始时间设置为 1号 方便比较
calcStartTime = calcStartTime.replace(
day=1, hour=0, minute=0, second=0, microsecond=0
)
sb = StringBuilder()
def calc_remain_year(year, start_share_month, end_share_month, price, remainTotal, amount):
for i in range(12):
# 添加一个月的日期
calculate_time = add_one_month(calcStartTime, i)
if calcStartTime <= calculate_time < calcEndTime:
sb.append(f"({device_id},'{calculate_time}',{price}),")
return str(sb)[0 : len(str(sb)) - 1]
def insertDataToFt(device_id, calcStartTime, calcEndTime, price):
"""
calcStartTime 开始分摊时间
calcEndTime 结束分摊时间
price 每月分摊金额
"""
values = buildApportionment(device_id, calcStartTime, calcEndTime, price)
bizConn = MySQL(g_pro_biz_dbcfg)
sql01 = f"""
INSERT INTO {base_table} (device_id,apportionment_date,apportionment_price) values {values};
"""
bizConn.insert(sql01)
def getMonthPriceByYear(my_fentan_detail_map, year):
sb = StringBuilder()
yearStart = datetime.datetime.strptime(f"{year}-01-01", "%Y-%m-%d").date()
yearEnd = datetime.datetime.strptime(f"{year}-12-31", "%Y-%m-%d").date()
d_str = f"{year}-01-01"
first_month = datetime.datetime.strptime(d_str, "%Y-%m-%d").date()
for i in range(12):
# 添加一个月的日期
calculate_time = add_one_month(first_month, i)
if yearStart <= calculate_time < yearEnd:
fentan_detail_time = calculate_time.strftime("%Y-%m-%d")
# print("fentan_detail_time==", fentan_detail_time)
price = my_fentan_detail_map.get(fentan_detail_time, 0)
sb.append(str(price) + ",")
return str(sb)
def calc_remain_year(
year, start_share_month, end_share_month, price, remainTotal, amount, device_id
):
"""
price 每月分摊金额
计算每年余额
:param year:
:return:
"""
gap_months = calc_gap_month_of_year(year, start_share_month, end_share_month)
gap_months, my_fentan_detail_map = calc_gap_month_of_year(
year, start_share_month, end_share_month, price, device_id
)
if gap_months > 0:
share = gap_months * price #
remainShare = remainTotal - share #
......@@ -66,47 +149,55 @@ def calc_remain_year(year, start_share_month, end_share_month, price, remainTota
else:
remainTotal = amount
remainShare = 0
return share, remainShare, remainTotal
return share, remainShare, remainTotal, my_fentan_detail_map
def calc_income_share(calcType='收入'):
def calc_income_share(calcType="收入"):
"""
计算收入的分摊
:return:
"""
tblName = "dj_device_details"
tblName = 'dj_2021_settle_details'
# tblName = "dj_device_details"
tblName = "dj_2021_settle_details"
fileName = calcType + "_01.csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '收入':
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"
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 ,id "
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 ,id "
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"
headName = f"客户名称,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入,"
year_list = [2017, 2018, 2019, 2020, 2021, 2022]
for year in year_list:
headName += f"{year}年摊销金额,{year}年末累计摊销余额,"
headName += f"{year}-01月分摊,{year}-02月分摊,{year}-03月分摊,{year}-04月分摊,{year}-05月分摊,{year}-06月分摊,{year}-07月分摊,{year}-08月分摊,{year}-09月分摊,{year}-10月分摊,{year}-11月分摊,{year}-12月分摊,"
headName += f"产品分类,激活开始月份,激活结束月份,是否退货,研发开始分摊月份"
headName += "\n"
fileHandle.write(headName)
for row in result:
settleMer = row[0]
......@@ -115,38 +206,54 @@ def calc_income_share(calcType='收入'):
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)
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]
device_id = row[9]
if active_month is None:
start_share = '2025-12'
active_start_month = ''
active_end_month = ''
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)
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):
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):
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)
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: 每年每月摊销多少
# 每月分摊金额
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年末摊销余额
......@@ -157,36 +264,112 @@ def calc_income_share(calcType='收入'):
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"
(
share_2017,
remainShare2017,
remainTotal,
my_fentan_detail_map_2017,
) = calc_remain_year(
2017,
start_share_month,
end_share_month,
share_per_month,
remainTotal,
amount,
device_id,
)
(
share_2018,
remainShare2018,
remainTotal,
my_fentan_detail_map_2018,
) = calc_remain_year(
2018,
start_share_month,
end_share_month,
share_per_month,
remainTotal,
amount,
device_id,
)
(
share_2019,
remainShare2019,
remainTotal,
my_fentan_detail_map_2019,
) = calc_remain_year(
2019,
start_share_month,
end_share_month,
share_per_month,
remainTotal,
amount,
device_id,
)
(
share_2020,
remainShare2020,
remainTotal,
my_fentan_detail_map_2020,
) = calc_remain_year(
2020,
start_share_month,
end_share_month,
share_per_month,
remainTotal,
amount,
device_id,
)
(
share_2021,
remainShare2021,
remainTotal,
my_fentan_detail_map_2021,
) = calc_remain_year(
2021,
start_share_month,
end_share_month,
share_per_month,
remainTotal,
amount,
device_id,
)
(
share_2022,
remainShare2022,
remainTotal,
my_fentan_detail_map_2022,
) = calc_remain_year(
2022,
start_share_month,
end_share_month,
share_per_month,
remainTotal,
amount,
device_id,
)
lineName = f"{settleMer},{channel},{period},{total},{settle_start_month},{amount},{settle_start_month},{settle_end_month},{price},{share_per_month},"
lineName += f"{share_2017},{remainShare2017},"
lineName += getMonthPriceByYear(my_fentan_detail_map_2017, 2017)
lineName += f"{share_2018},{remainShare2018},"
lineName += getMonthPriceByYear(my_fentan_detail_map_2018, 2018)
lineName += f"{share_2019},{remainShare2019},"
lineName += getMonthPriceByYear(my_fentan_detail_map_2019, 2019)
lineName += f"{share_2020},{remainShare2020},"
lineName += getMonthPriceByYear(my_fentan_detail_map_2020, 2020)
lineName += f"{share_2021},{remainShare2021},"
lineName += getMonthPriceByYear(my_fentan_detail_map_2021, 2021)
lineName += f"{share_2022},{remainShare2022},"
lineName += getMonthPriceByYear(my_fentan_detail_map_2022, 2022)
lineName += f"{devName},{active_start_month},{active_end_month},{returnFlag},{start_share_month}"
lineName += "\n"
fileHandle.write(lineName)
fileHandle.close()
......@@ -196,32 +379,38 @@ def calc_return_share(calcType):
退货
:return:
"""
tblName = 'dj_2021_settle_details_return'
tblName = "dj_2021_settle_details_return"
fileName = calcType + "_01.csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
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 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"
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]
......@@ -230,13 +419,16 @@ def calc_return_share(calcType):
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)
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')
start_share_month = datetime.datetime.strptime(settle_start_month, "%Y-%m")
end_share_month = settle_end_month
price = amount / total
......@@ -244,39 +436,74 @@ def calc_return_share(calcType):
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"
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('退货成本')
# BaseCreateTable(base_table).create_table()
# calc_income_share(calcType="收入")
calc_income_share(calcType="成本")
# calc_return_share("退货收入")
# calc_return_share("退货成本")
print("end===")
File mode changed
# -*- coding:utf-8 -*-
from __future__ import print_function
import time
import MySQLdb
# reload(sys)
# sys.setdefaultencoding('utf8')
#
def paddstr(strx):
return (
"NULL"
if strx == None
else "'" + MySQLdb.escape_string(str(strx)).decode() + "'"
)
def paddnum(numx, default="NULL"):
return default if numx == None else str(numx)
class MySQL:
"""对MySQLdb常用函数进行封装的类"""
error_code = "" # MySQL错误号码
_instance = None # 本类的实例
_conn = None # 数据库conn
_cur = None # 游标
_TIMEOUT = 30 # 默认超时30秒
_timecount = 0
def __init__(self, dbconfig):
"构造器:根据数据库连接参数,创建MySQL连接"
try:
self._conn = MySQLdb.connect(
host=dbconfig["host"],
port=dbconfig["port"],
user=dbconfig["user"],
passwd=dbconfig["passwd"],
db=dbconfig["db"],
charset=dbconfig["charset"],
)
except MySQLdb.Error as e:
self.error_code = e.args[0]
error_msg = "MySQL error! ", e.args[0], e.args[1]
print(error_msg)
# 如果没有超过预设超时时间,则再次尝试连接,
if self._timecount < self._TIMEOUT:
interval = 5
self._timecount += interval
time.sleep(interval)
return self.__init__(dbconfig)
else:
raise Exception(error_msg)
self._cur = self._conn.cursor()
self._instance = MySQLdb
def query(self, sql):
"执行 SELECT 语句"
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def update(self, sql):
"执行 UPDATE 及 DELETE 语句"
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def insert(self, sql, data=None):
"执行 INSERT 语句。如主键为自增长int,则返回新生成的ID"
try:
self._cur.execute("SET NAMES utf8")
if data == None:
self._cur.execute(sql)
else:
self._cur.executemany(sql, data)
self._conn.commit()
return True
return self._conn.insert_id()
except MySQLdb.Error as e:
self.error_code = e.args[0]
return False
def callproc(self, procname, *arg):
try:
self._cur.execute("SET NAMES utf8")
self._cur.callproc(procname, arg)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def fetchAllRows(self):
"返回结果列表"
return self._cur.fetchall()
def fetchOneRow(self):
"返回一行结果,然后游标指向下一行。到达最后一行以后,返回None"
return self._cur.fetchone()
def getRowCount(self):
"获取结果行数"
return self._cur.rowcount
def commit(self):
"数据库commit操作"
self._conn.commit()
def rollback(self):
"数据库回滚操作"
self._conn.rollback()
def __del__(self):
"释放资源(系统GC自动调用)"
try:
self._cur.close()
self._conn.close()
except:
pass
def close(self):
"关闭数据库连接"
self.__del__()
class StringBuilder:
def __init__(self):
self.strings = []
def append(self, string):
self.strings.append(string)
def __str__(self):
return "".join(self.strings)
from dateutil.relativedelta import *
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
import logging
from 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.2",
"port": 3306,
"user": "biz_glsx_data",
"passwd": "unEKczDc",
"db": "glsx_biz_data",
"charset": "utf8",
}
# saas_shen_db_cfg = {
# "host": "192.168.3.222",
# "port": 3306,
# "user": "biz_audit",
# "passwd": "hqVIs6jF",
# "db": "saas_shen_ft",
# "charset": "utf8",
# }
class BaseCreateTable:
def __init__(self, base_table):
self.bizConn = MySQL(saas_shen_db_cfg)
self.base_table = base_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)
if __name__ == "__main__":
my_base = BaseCreateTable()
my_base.create_table()
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'}
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",
)
'''将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)
# pd.set_option('display.max_columns', 40)
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
newData = data[['单据类型', '单据编号', '业务日期', '客户', '渠道', '物料编码', '物料名称', '产品类型', '设备类型', '计价数量',
'含税单价', '单价', '收入', '业务类型', '分摊期限']]
'''
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)
"""
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)
newData["成本金额"].fillna(0, 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, '分摊期限'])
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, "分摊期限"],
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)"
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,cost) values "
"(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
)
cs.executemany(sql, valueArr)
conn_updata.commit()
cs.close()
......@@ -67,80 +114,124 @@ def loadFinnanceExcelToMysql(fileName, sheetName):
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')
"""将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)
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)
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, '硬件税率']
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, '安装税率'])
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, "安装税率"],
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)"
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,cost) "
"values "
"(%s,%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')
"""更新客户的渠道"""
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)
......@@ -176,26 +267,84 @@ if __name__ == "__main__":
# sheetName = "汇总"
# loadFinnanceExcelToMysql(fileName, sheetName)
# 一二月份
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据-2023年1月-4月份\\应收拆分数据1-2月份\\"
# 处理财务原表
fileName = filePath + "数据源-激活调整用23年1-2月.xlsx"
sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName)
# E盾
fileName = filePath + "1.拆分数据-虎哥E盾结算单与明细数据-陈冰恋.xlsx"
sheetName = "3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName)
# 渠道嘀加
fileName = filePath + "3.拆分数据-渠道2023年1-2月嘀加数据-柳云飞.xlsx"
sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName)
# 直销
fileName = filePath + "4.拆分数据-广汇23年1-2月-廖敏玲.xlsx"
sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName)
# 三月份
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据-2023年1月-4月份\\应收拆分数据3月份\\"
# 处理财务原表
fileName = filePath + "数据源-激活调整用23年2-3月.xlsx"
sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName)
# E盾
fileName = filePath + "4.数据源-激活调整用23年3月-陈冰恋.xlsx"
sheetName = "3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName)
# 渠道嘀加
fileName = filePath + "2.拆分数据-渠道2023年3月嘀加数据-柳云飞.xlsx"
sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName)
# 直销
fileName = filePath + "1.数据源-激活调整用2023年3月-廖敏玲.xlsx"
sheetName = "廖敏玲"
loadDjExcelToMysql(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盾--渠道应收单原表'
sheetName = "1.3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName)
# # 渠道嘀加
# 渠道嘀加
fileName = filePath + "2.拆分数据-渠道2023年4月嘀加数据-柳云飞.xlsx"
sheetName = 'Sheet2'
sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName)
# # # 直销
# 直销
fileName = filePath + "1.数据源-激活调整用23年4月-廖敏玲.xlsx"
sheetName = '廖敏玲'
sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName)
# 五月份
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据5月份"
# 处理财务原表
fileName = filePath + "数据源-激活调整用23年5月.xlsx"
sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName)
# E盾
fileName = filePath + "4.数据源-激活调整用23年5月-陈冰恋.xlsx"
sheetName = "1.3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName)
# 渠道嘀加
fileName = filePath + "2.拆分数据-渠道2023年5月嘀加数据-柳云飞.xlsx"
sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName)
# 直销
fileName = filePath + "1.数据源-激活调整用23年5月-廖敏玲.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!