Commit 63e90ba7 by 杨林龙

添加记录仪分摊脚本

1 parent a8a54e52
2024-01~02 gps 2024-01~03 gps
联通租赁集团有限公司 商务表未设置安装费 ( 财务GPS安装服务费 属于服务,商务数据未计) 联通租赁集团有限公司 商务表未设置安装费 (商务没有分摊安装费用)
2024-01 gps 记录仪 2024-01 gps 记录仪
广汇汽车 广汇汽车
2023-03 记录仪 gps
浙江元通汽车零部件有限公司 GPS多分摊了服务费 记录仪少分摊了服务费
2023-03 记录仪
广汇汽车服务有限责任公司东台分公司 商务没有分摊安装费用
2023-03 记录仪
东台宝通汽车服务有限责任公司 商务没有分摊安装费用
\ No newline at end of file \ No newline at end of file
...@@ -85,10 +85,16 @@ IT审计的线索数据: ...@@ -85,10 +85,16 @@ IT审计的线索数据:
同步D+客户数据到dj_system_merchant 同步D+客户数据到dj_system_merchant
192.168.5.23 3306 glsx_dj user_yangll vGxw9jWg 192.168.5.23 3306 glsx_dj user_yangll vGxw9jWg
GPS生成分摊报表脚本 calc_month_share_yangll_20230627.py
注意点 : settle_time < '2024-01-01 00:00:00' 需要修改截止时间
审计代码仓库
同步D+设备到审计数据库 glsx-liber-design http://192.168.3.233:8090/eshiled-new/glsx-liber-design.git
梳理审计数据脚本 audit_2021 http://192.168.3.233:8090/eshiled-new/audit_2021.git
平常处理数据脚本项目 deal_mysql_data http://192.168.3.233:8090/eshiled-new/deal_mysql_data.git
......
...@@ -489,49 +489,49 @@ def runScript(): ...@@ -489,49 +489,49 @@ def runScript():
# sheetName = "廖敏玲" # sheetName = "廖敏玲"
# loadDjExcelToMysql(fileName, sheetName) # loadDjExcelToMysql(fileName, sheetName)
# 2024年 一月份 # # 2024年 一月份
filePath = "G:\\财务审计\\2024EXCEL文档\\应收拆分数据-2024-01\\" # filePath = "G:\\财务审计\\2024EXCEL文档\\应收拆分数据-2024-01\\"
# 处理财务原表 # # 处理财务原表
fileName = filePath + "数据源-激活调整用24年1月.xlsx" # fileName = filePath + "数据源-激活调整用24年1月.xlsx"
sheetName = "Sheet1" # sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName) # loadFinnanceExcelToMysql(fileName, sheetName)
# E盾 # # E盾
fileName = filePath + "1数据源-激活调整用24年1月-陈冰恋.xlsx" # fileName = filePath + "1数据源-激活调整用24年1月-陈冰恋.xlsx"
sheetName = "1.3.虎哥E盾--渠道应收单原表" # sheetName = "1.3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName) # loadDjExcelToMysql(fileName, sheetName)
# 渠道嘀加 # # 渠道嘀加
fileName = filePath + "2拆分数据-渠道2024年1嘀加数据-柳云飞..xlsx" # fileName = filePath + "2拆分数据-渠道2024年1嘀加数据-柳云飞..xlsx"
sheetName = "Sheet2" # sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName) # loadDjExcelToMysql(fileName, sheetName)
# 直销 # # 直销
fileName = filePath + "4数据源-激活调整用24年1月-廖敏玲.xlsx" # fileName = filePath + "4数据源-激活调整用24年1月-廖敏玲.xlsx"
sheetName = "廖敏玲" # sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName) # loadDjExcelToMysql(fileName, sheetName)
# 2024年 二月份 # # 2024年 二月份
filePath = "G:\\财务审计\\2024EXCEL文档\\应收拆分数据-2024-02\\" # filePath = "G:\\财务审计\\2024EXCEL文档\\应收拆分数据-2024-02\\"
# 处理财务原表 # # 处理财务原表
fileName = filePath + "数据源-激活调整用24年2月.xlsx" # fileName = filePath + "数据源-激活调整用24年2月.xlsx"
sheetName = "Sheet1" # sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName) # loadFinnanceExcelToMysql(fileName, sheetName)
# E盾 # # E盾
fileName = filePath + "4.数据源-激活调整用24年2月-陈冰恋.xlsx" # fileName = filePath + "4.数据源-激活调整用24年2月-陈冰恋.xlsx"
sheetName = "1.3.虎哥E盾--渠道应收单原表" # sheetName = "1.3.虎哥E盾--渠道应收单原表"
loadDjExcelToMysql(fileName, sheetName) # loadDjExcelToMysql(fileName, sheetName)
# 渠道嘀加 # # 渠道嘀加
fileName = filePath + "3.拆分数据-渠道2024年2月嘀加数据-柳云飞..xlsx" # fileName = filePath + "3.拆分数据-渠道2024年2月嘀加数据-柳云飞..xlsx"
sheetName = "Sheet2" # sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName) # loadDjExcelToMysql(fileName, sheetName)
# 直销 # # 直销
fileName = filePath + "1.数据源-激活调整用24年2月-廖敏玲.xlsx" # fileName = filePath + "1.数据源-激活调整用24年2月-廖敏玲.xlsx"
sheetName = "廖敏玲" # sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName) # loadDjExcelToMysql(fileName, sheetName)
# 2024年 三月份 # 2024年 三月份
filePath = "G:\\财务审计\\2024EXCEL文档\\应收拆分数据-2024-03\\" filePath = "G:\\财务审计\\2024EXCEL文档\\应收拆分数据-2024-03\\"
# 处理财务原表 # # 处理财务原表
fileName = filePath + "数据源-激活调整用24年3月(1).xlsx" fileName = filePath + "数据源-激活调整用24年3月(1).xlsx"
sheetName = "Sheet1" sheetName = "Sheet1"
loadFinnanceExcelToMysql(fileName, sheetName) loadFinnanceExcelToMysql(fileName, sheetName)
...@@ -545,7 +545,7 @@ def runScript(): ...@@ -545,7 +545,7 @@ def runScript():
sheetName = "Sheet2" sheetName = "Sheet2"
loadDjExcelToMysql(fileName, sheetName) loadDjExcelToMysql(fileName, sheetName)
# 直销 # 直销
fileName = filePath + "4数据源-激活调整用24年3月-廖敏玲.xlsx" fileName = filePath + "4数据源-激活调整用24年3月-2次-廖敏玲.xlsx"
sheetName = "廖敏玲" sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName) loadDjExcelToMysql(fileName, sheetName)
......
...@@ -118,36 +118,42 @@ def rollback(startTime, endTime): ...@@ -118,36 +118,42 @@ def rollback(startTime, endTime):
update_device_alloc(6, startTime, endTime) update_device_alloc(6, startTime, endTime)
bizConn = MySQL(g_pro_biz_dbcfg) bizConn = MySQL(g_pro_biz_dbcfg)
sqlList = [] sqlList = []
# 退货标记还原
updateSql = f""" updateSql = f"""
update dj_2021_settle_details set `return` = 0 where sn in (SELECT sn from dj_2024_settle_details_return where settle_time >= '{startTime}'); update dj_2021_settle_details set `return` = 0 where sn in (SELECT sn from dj_2024_settle_details_return where settle_time >= '{startTime}');
""" """
print("updateSql==" + updateSql) print("updateSql==" + updateSql)
sqlList.append(updateSql) sqlList.append(updateSql)
# 整体
updateSql01 = f""" updateSql01 = f"""
DELETE from dj_2021_settle_details where settle_time >= '{startTime}'; DELETE from dj_2021_settle_details where settle_time >= '{startTime}';
""" """
print("updateSql01==" + updateSql01) print("updateSql01==" + updateSql01)
sqlList.append(updateSql01) sqlList.append(updateSql01)
# GPS
updateSql02 = f""" updateSql02 = f"""
DELETE from dj_2024_settle_details where settle_time >= '{startTime}'; DELETE from dj_2024_settle_details where settle_time >= '{startTime}';
""" """
print("updateSql02==" + updateSql02) print("updateSql02==" + updateSql02)
sqlList.append(updateSql02) sqlList.append(updateSql02)
# 记录仪
updateSql03 = f""" updateSql03 = f"""
DELETE from dj_2024_settle_details_record where settle_time >= '{startTime}' ; DELETE from dj_2024_settle_details_record where settle_time >= '{startTime}' ;
""" """
print("updateSql03==" + updateSql03) print("updateSql03==" + updateSql03)
sqlList.append(updateSql03) sqlList.append(updateSql03)
# 退货表
updateSql04 = f""" updateSql04 = f"""
DELETE from dj_2024_settle_details_return where settle_time >= '{startTime}' ; DELETE from dj_2024_settle_details_return where settle_time >= '{startTime}' ;
""" """
print("updateSql04==" + updateSql04) print("updateSql04==" + updateSql04)
sqlList.append(updateSql04) sqlList.append(updateSql04)
# 商务表
updateSql05 = f""" updateSql05 = f"""
update dj_2024_settlment_order set match_total=NULL,`status`=0 where finance_time >= '{startTime}' and finance_time <= '{endTime}'; update dj_2024_settlment_order set match_total=NULL,`status`=0 where finance_time >= '{startTime}' and finance_time <= '{endTime}';
""" """
...@@ -224,17 +230,17 @@ def pre_deal(startTime, endTime): ...@@ -224,17 +230,17 @@ def pre_deal(startTime, endTime):
if __name__ == "__main__": if __name__ == "__main__":
# 第一步修改时间 # 第一步修改时间
startTime = "2024-01-01" startTime = "2024-03-01"
endTime = "2025-01-01" endTime = "2025-01-01"
# 将财务和商务表导入到数据库 # 将财务和商务表导入到数据库
# runScript() # runScript()
# pre_deal(startTime, endTime) # pre_deal(startTime, endTime)
# 寻找差异 # 寻找差异
# 手动 # 比较财务和商务的差异
# 处理数据 # 手动处理数据
deal_data(startTime, endTime) deal_data(startTime, endTime)
# 激活数据 # 激活数据
# active() active()
# 回滚数据 # 回滚数据
# rollback(startTime, endTime) # rollback(startTime, endTime)
......
No preview for this file type
No preview for this file type
# 记录仪
obd_year_list = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030]
obd_range_num = 120
obd_start_month = "2020-01-01"
# GPS
gps_year_list = [
2017,
2018,
2019,
2020,
2021,
2022,
2023,
2024,
2025,
2026,
2027,
2028,
2029,
2030,
]
gps_range_num = 160
gps_start_month = "2017-01-01"
# -*- 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:
u'''对MySQLdb常用函数进行封装的类'''
error_code = '' # MySQL错误号码
_instance = None # 本类的实例
_conn = None # 数据库conn
_cur = None # 游标
_TIMEOUT = 30 # 默认超时30秒
_timecount = 0
def __init__(self, dbconfig):
u'构造器:根据数据库连接参数,创建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):
u'执行 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):
u'执行 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):
u'执行 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):
u'返回结果列表'
return self._cur.fetchall()
def fetchOneRow(self):
u'返回一行结果,然后游标指向下一行。到达最后一行以后,返回None'
return self._cur.fetchone()
def getRowCount(self):
u'获取结果行数'
return self._cur.rowcount
def commit(self):
u'数据库commit操作'
self._conn.commit()
def rollback(self):
u'数据库回滚操作'
self._conn.rollback()
def __del__(self):
u'释放资源(系统GC自动调用)'
try:
self._cur.close()
self._conn.close()
except:
pass
def close(self):
u'关闭数据库连接'
self.__del__()
import logging
from my_utils.MysqlUtility import MySQL
logger = logging.getLogger("deal_equity_data")
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler("import.log")
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
# saas_shen_db_cfg = {'host': '192.168.5.77',
# 'port': 3306,
# 'user': 'biz_saas_plus',
# 'passwd': 'lOmEudkc',
# 'db': 'saas_plus',
# 'charset': 'utf8'}
g_pro_biz_dbcfg = {
"host": "192.168.5.2",
"port": 3306,
"user": "biz_glsx_data",
"passwd": "unEKczDc",
"db": "glsx_biz_data",
"charset": "utf8",
}
class BaseCreateTable:
def __init__(
self,
ft_table="temp_dj_device_details_20230620_settle_record_ft",
zj_table="temp_dj_device_details_20230620_settle_record_zj",
):
self.bizConn = MySQL(g_pro_biz_dbcfg)
self.base_table = ft_table
self.zj_table = zj_table
def create_table(self):
drop_table_sql = f"""
drop table if exists {self.base_table};
"""
self.bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `{self.base_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`apportionment_date` datetime DEFAULT NULL COMMENT '分摊日期',
`apportionment_price` decimal(12,2) DEFAULT NULL COMMENT '分摊金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础分摊表';
"""
self.bizConn.query(create_table_sql)
drop_table_sql = f"""
drop table if exists {self.zj_table};
"""
self.bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `{self.zj_table}` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_id` int(11) DEFAULT NULL COMMENT '设备表ID',
`order_year` varchar(32) DEFAULT NULL COMMENT '订单年份',
`qichu_num` int(11) DEFAULT NULL COMMENT '期初数量',
`qichu_unit_price` decimal(12,2) DEFAULT NULL COMMENT '期初单价',
`qichu_total_price` decimal(12,2) DEFAULT NULL COMMENT '期初金额',
`zengjia_num` int(11) DEFAULT NULL COMMENT '增加数量',
`zengjia_unit_price` decimal(12,2) DEFAULT NULL COMMENT '增加单价',
`zengjia_total_price` decimal(12,2) DEFAULT NULL COMMENT '增加金额',
`jianshao_num` int(11) DEFAULT NULL COMMENT '减少数量',
`jianshao_unit_price` decimal(12,2) DEFAULT NULL COMMENT '减少单价',
`jianshao_total_price` decimal(12,2) DEFAULT NULL COMMENT '减少金额',
PRIMARY KEY (`id`),
KEY `idx_device_id` (`device_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='增减表';
"""
self.bizConn.query(create_table_sql)
if __name__ == "__main__":
my_base = BaseCreateTable()
my_base.create_table()
import logging
import time
from datetime import datetime
from decimal import Decimal
from itertools import groupby
import MySQLdb
from dateutil.relativedelta import *
from base_create_table import BaseCreateTable
from my_utils.MysqlUtility import MySQL
from my_config.config import *
logger = logging.getLogger("deal_equity_data")
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler("import.log")
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_pro_biz_dbcfg = {
"host": "192.168.5.2",
"port": 3306,
"user": "biz_glsx_data",
"passwd": "unEKczDc",
"db": "glsx_biz_data",
"charset": "utf8",
}
def deal_equity_data(
base_table, ft_table, device_type, service_type, range_num, start_month
):
"""
以结算为维度
service_type 1 硬件 2 服务 3 安装
"""
bizConn = MySQL(g_pro_biz_dbcfg)
if service_type == 1:
sql = f"""
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(hw_price,0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(pk_price,0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT `id`,`sn`,`fentan_time`,`pk_period`,SUM(IFNULL(install_price, 0)) as total_price FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
device_id = row[0]
设备号 = row[1]
分摊时间 = row[2]
服务期限 = paddnum_price(row[3])
服务总金额 = paddnum_price(row[4])
if 服务期限 == 0:
logger.warning("服务期限为0")
continue
分摊金额 = 服务总金额 / 服务期限
分摊金额 = Decimal(分摊金额).quantize(Decimal("0.00"))
values = buildApportionment(device_id, 分摊时间, 服务期限, 分摊金额, range_num, start_month)
sql01 = f"""
INSERT INTO {ft_table} (device_id,apportionment_date,apportionment_price) values {values};
"""
write_sql(sql01)
bizConn.insert(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def buildApportionment(device_id, 分摊时间, 服务期限, 分摊金额, range_num, start_month):
# 将业务日期开始时间设置为 1号 方便比较
分摊时间 = 分摊时间.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
sb = StringBuilder()
# 计算分摊的最后日期
分摊最后日期 = add_one_month(分摊时间, 服务期限)
print("分摊最后日期==", 分摊最后日期)
for i in range(range_num):
start_time = datetime.strptime(start_month, "%Y-%m-%d")
# 添加一个月的日期
calculate_time = add_one_month(start_time, i)
if 分摊时间 <= calculate_time < 分摊最后日期:
sb.append(f"({device_id},'{calculate_time}',{分摊金额}),")
return str(sb)[0 : len(str(sb)) - 1]
def add_one_month(date, i):
# Add one month to the date using timedelta
next_month = date + relativedelta(months=+i)
# print(next_month)
new_date = next_month.replace(day=1)
return new_date
def write_sql(sql):
logger.info(sql)
with open(
"H:\PythonWorkSpaces\deal_mysql_data\\sql14.txt", "a+", encoding="utf8"
) as fw:
fw.write(sql.strip())
fw.write("\n")
class StringBuilder:
def __init__(self):
self.strings = []
def append(self, string):
self.strings.append(string)
def __str__(self):
return "".join(self.strings)
def deal_jianshao_equity_data(ft_table, zj_table):
bizConn = MySQL(g_pro_biz_dbcfg)
sql = f"""
INSERT INTO {zj_table}(`device_id`,`order_year`,`qichu_unit_price`,`zengjia_unit_price`,`jianshao_num`,`jianshao_unit_price`)
SELECT device_id ,LEFT(apportionment_date,4) AS `year`,`apportionment_price`,`apportionment_price` ,count(1) AS num , `apportionment_price`
FROM {ft_table} GROUP BY LEFT(apportionment_date,4),device_id ;
"""
logger.info(sql)
bizConn.insert(sql)
sql = f"""
UPDATE {zj_table} SET `jianshao_total_price` = `jianshao_num`*`jianshao_unit_price` WHERE 1=1;
"""
logger.info(sql)
bizConn.update(sql)
def deal_zengjia_equity_data(base_table, zj_table, device_type, service_type):
bizConn = MySQL(g_pro_biz_dbcfg)
if service_type == 1:
sql = f"""
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(IFNULL(hw_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7), pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(IFNULL(pk_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7), pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT `id`, left(`fentan_time`,4) AS 'year',`pk_period`,SUM(IFNULL(install_price,0)) as total_price
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7), pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
device_id = row[0]
year = row[1]
pk_period = row[2]
pk_price = row[3]
sql01 = f"""
UPDATE {zj_table} SET zengjia_num = {pk_period}, zengjia_total_price = {pk_price} WHERE device_id = {device_id} AND order_year = {year};
"""
logger.info(sql01)
bizConn.update(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def deal_qichu_equity_data(zj_table, year_list):
bizConn = MySQL(g_pro_biz_dbcfg)
for year_num in year_list:
sql = f"""
SELECT id, device_id, order_year, qichu_num, zengjia_num, jianshao_num FROM {zj_table} WHERE order_year= {year_num} ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
id = row[0]
device_id = row[1]
order_year = row[2]
qichu_num = paddnum_price(row[3])
zengjia_num = paddnum_price(row[4])
jianshao_num = paddnum_price(row[5])
# 上一年 下一年期初的数据=当年期初+当年新增-当年减少
next_year = int(order_year) + 1
sql01 = f"""
UPDATE {zj_table} SET qichu_num = {qichu_num + zengjia_num - jianshao_num} WHERE device_id = {device_id} AND order_year = {next_year};
"""
write_sql(sql01)
bizConn.update(sql01)
sql01 = f"""
UPDATE {zj_table} SET qichu_total_price = qichu_num*qichu_unit_price WHERE device_id = {device_id} AND order_year = {next_year};
"""
write_sql(sql01)
bizConn.update(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def paddnum_price(num):
return num if num is not None else 0
def paddstr(strx):
return (
"NULL"
if strx == None
else "'" + MySQLdb.escape_string(str(strx)).decode() + "'"
)
def deal_null_equity_data(zj_table):
bizConn = MySQL(g_pro_biz_dbcfg)
sql = f"""
UPDATE {zj_table} set zengjia_num = 0 ,zengjia_total_price = 0 WHERE zengjia_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
sql = f"""
UPDATE {zj_table} set qichu_num = 0 ,qichu_total_price = 0 WHERE qichu_num IS NULL ;
"""
logger.info(sql)
bizConn.update(sql)
def export_csv(fileName, year_list):
bizConn = MySQL(g_pro_biz_dbcfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
headName = (
"id,channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,"
"settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost,fentan_time"
)
for year in year_list:
headName += f",{year}期初数,{year}期初单价,{year}期初金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额"
headName += "\n"
fileHandle.write(headName)
# SELECT teo.id ,teo.order_code, teo.order_time, teo.service_period, teo.total_price FROM temp_eq_order; where teo.id = 251
sql = f"""
SELECT id,channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,sum(pk_price)
,hw_price,install_price,hw_cost,install_cost ,fentan_time FROM temp_dj_device_details_20230620 where `device_type` IN (6,12501) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
logger.info(row)
lineValue = f"{row[0]},{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]},{row[12]},{row[13]},{row[14]},{row[15]},{row[16]},{row[17]},{row[18]}"
for year in year_list:
logger.info("device_id" + str(row[0]) + ";year" + str(year))
sql = f"""
SELECT id,device_id,order_year,qichu_num,qichu_unit_price,qichu_total_price,zengjia_num,zengjia_unit_price,zengjia_total_price,jianshao_num,jianshao_unit_price,jianshao_total_price
FROM temp_dj_device_details_20230620_settle_record_zj tddz WHERE tddz.device_id = {row[0]} AND tddz.order_year = '{year}';
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
if len(result) == 0:
logger.debug(row)
lineValue += f",0,0,0,0,0,0,0,0,0"
else:
for row01 in result:
logger.info(row01)
lineValue += f",{paddnum_price(row01[3])},{paddnum_price(row01[4])},{paddnum_price(row01[5])},{paddnum_price(row01[6])},{paddnum_price(row01[7])},{paddnum_price(row01[8])},{paddnum_price(row01[9])},{paddnum_price(row01[10])},{paddnum_price(row01[11])}"
# 写入一行数据
lineValue += "\n"
logger.debug(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def export_csv_2(base_table, ft_table, zj_table, device_type, fileName, year_list):
bizConn = MySQL(g_pro_biz_dbcfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
headName = "客户名称,门店,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in year_list:
headName += f",{year}期初数,{year}期初单价,{year}期初金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额"
headName += f",{year}-01分摊,{year}-02分摊,{year}-03分摊,{year}-04分摊,{year}-05分摊,{year}-06分摊,{year}-07分摊,{year}-08分摊,{year}-09分摊,{year}-10分摊,{year}-11分摊,{year}-12分摊"
headName += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
headName += "\n"
fileHandle.write(headName)
if service_type == 1:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(hw_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,hw_price,
sum(hw_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(pk_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,pk_price,
sum(pk_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(install_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,install_price,
sum(install_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_year_big_map = getYearDataBigMap(zj_table)
my_month_big_map = getMonthDataBigMap(ft_table)
for row in result:
logger.info(row)
lineValue = f"{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
my_year_map = my_year_big_map.get(row[0])
my_month_map = my_month_big_map.get(row[0])
for year in year_list:
logger.info("device_id" + str(row[0]) + ";year" + str(year))
result = my_year_map.get(str(year))
if result is None or len(result) == 0:
logger.debug(row)
lineValue += f",0,0,0,0,0,0,0,0,0"
else:
logger.info(result)
lineValue += f",{paddnum_price(result[3])},{paddnum_price(result[4])},{paddnum_price(result[5])},{paddnum_price(result[6])},{paddnum_price(result[7])},{paddnum_price(result[8])},{paddnum_price(result[9])},{paddnum_price(result[10])},{paddnum_price(result[11])}"
monthList = getMonthListByYear(year)
for month in monthList:
# my_map = getMonthDataMap(ft_table, row[0])
row_data = my_month_map.get(str(month))
# logger.info(
# "device_id"
# + str(row[0])
# + ",month=="
# + str(month)
# + ",row_data=="
# + str(row_data)
# )
if row_data is None or len(row_data) == 0:
lineValue += f",0"
else:
lineValue += f",{paddnum_price(row_data[3])}"
if row[12] == 6:
lineValue += ",记录仪"
elif row[12] == 12501:
lineValue += ",车充"
elif row[12] == 8:
lineValue += ",GPS"
lineValue += f",{row[13]},{row[14]},{row[15]},{row[16]}"
# 写入一行数据
lineValue += "\n"
logger.info(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def export_csv_3(base_table, ft_table, zj_table, device_type, fileName, year_list):
bizConn = MySQL(g_pro_biz_dbcfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
headName = "客户名称,门店,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入"
for year in year_list:
# headName += f",{year}期初数,{year}期初单价,{year}期初金额,{year}增加数,{year}增加单价,{year}增加金额,{year}减少数,{year}减少单价,{year}减少金额"
headName += f",{year}-01分摊,{year}-02分摊,{year}-03分摊,{year}-04分摊,{year}-05分摊,{year}-06分摊,{year}-07分摊,{year}-08分摊,{year}-09分摊,{year}-10分摊,{year}-11分摊,{year}-12分摊"
headName += ",产品分类,激活开始月份,激活结束月份,研发开始分摊月份,开始分摊年份"
headName += "\n"
fileHandle.write(headName)
if service_type == 1:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(hw_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,hw_price,
sum(hw_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 2:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(pk_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,pk_price,
sum(pk_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
elif service_type == 3:
sql = f"""
SELECT id,settle_merchant,'门店',channel,pk_period,count(1) as num, settle_time,sum(IFNULL(install_price,0)) as total_price,fentan_time,DATE_ADD(fentan_time,INTERVAL pk_period MONTH ) as fentan_end_time,install_price,
sum(install_price)/pk_period, device_type,min(active_time),max(active_time),fentan_time,left(fentan_time,4)
FROM {base_table} where `device_type` IN ({device_type}) and fentan_time is not null GROUP BY settle_merchant,LEFT(fentan_time ,7),pk_period ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
# my_year_big_map = getYearDataBigMap(zj_table)
my_month_big_map = getMonthDataBigMap(ft_table)
for row in result:
logger.info(row)
lineValue = f"{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]}"
# my_year_map = my_year_big_map.get(row[0])
my_month_map = my_month_big_map.get(row[0])
for year in year_list:
logger.info("device_id" + str(row[0]) + ";year" + str(year))
# result = my_year_map.get(str(year))
# if result is None or len(result) == 0:
# logger.debug(row)
# lineValue += f",0,0,0,0,0,0,0,0,0"
# else:
# logger.info(result)
# lineValue += f",{paddnum_price(result[3])},{paddnum_price(result[4])},{paddnum_price(result[5])},{paddnum_price(result[6])},{paddnum_price(result[7])},{paddnum_price(result[8])},{paddnum_price(result[9])},{paddnum_price(result[10])},{paddnum_price(result[11])}"
monthList = getMonthListByYear(year)
for month in monthList:
# my_map = getMonthDataMap(ft_table, row[0])
row_data = my_month_map.get(str(month))
# logger.info(
# "device_id"
# + str(row[0])
# + ",month=="
# + str(month)
# + ",row_data=="
# + str(row_data)
# )
if row_data is None or len(row_data) == 0:
lineValue += f",0"
else:
lineValue += f",{paddnum_price(row_data[3])}"
if row[12] == 6:
lineValue += ",记录仪"
elif row[12] == 12501:
lineValue += ",车充"
elif row[12] == 8:
lineValue += ",GPS"
lineValue += f",{row[13]},{row[14]},{row[15]},{row[16]}"
# 写入一行数据
lineValue += "\n"
logger.info(lineValue)
fileHandle.write(lineValue)
# 关闭流
fileHandle.close()
def getMonthListByYear(year):
monthList = []
d_str = f"{year}-01-01"
first_month = datetime.strptime(d_str, "%Y-%m-%d").date()
logger.info("first_month==" + str(first_month))
for i in range(12):
next_month = add_one_month(first_month, i)
monthList.append(next_month)
logger.info("monthList==" + str(monthList))
return monthList
def getMonthDataMap(ft_table, device_id):
bizConn = MySQL(g_pro_biz_dbcfg)
logger.info("device_id" + str(device_id))
sql = f"""
SELECT id,device_id,apportionment_date,apportionment_price FROM {ft_table} WHERE device_id ={device_id} order by device_id;
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_map = {i[2].strftime("%Y-%m-%d"): i for i in result}
logger.info(my_map)
return my_map
def get_job_id(job_info_data):
return job_info_data[1]
def getMonthDataBigMap(ft_table):
bizConn = MySQL(g_pro_biz_dbcfg)
sql = f"""
SELECT id,device_id,apportionment_date,apportionment_price FROM {ft_table} order by device_id;
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_month_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_month_big_map[job_id] = {i[2].strftime("%Y-%m-%d"): i for i in group_list}
print("my_month_big_map:", my_month_big_map)
return my_month_big_map
def getYearDataBigMap(zj_table):
bizConn = MySQL(g_pro_biz_dbcfg)
sql = f"""
SELECT id,device_id,order_year,qichu_num,qichu_unit_price,qichu_total_price,zengjia_num,zengjia_unit_price,zengjia_total_price,jianshao_num,jianshao_unit_price,jianshao_total_price
FROM {zj_table} tddz order by device_id;
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_year_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_year_big_map[job_id] = {i[2]: i for i in group_list}
print("my_year_big_map:", my_year_big_map)
return my_year_big_map
def calculate(base_table, ft_table, zj_table, device_type, service_type, file_name):
"""
以结算为维度
service_type 1 硬件 hw 2 服务 pk 3 安装 install
"""
if device_type == "8":
year_list = gps_year_list
range_num = gps_range_num
start_month = gps_start_month
else:
year_list = obd_year_list
range_num = obd_range_num
start_month = obd_start_month
# 创建数据表
BaseCreateTable(ft_table, zj_table).create_table()
# 处理基础数据
deal_equity_data(
base_table, ft_table, device_type, service_type, range_num, start_month
)
# 处理减少数据
deal_jianshao_equity_data(ft_table, zj_table)
# 处理增加数据
deal_zengjia_equity_data(base_table, zj_table, device_type, service_type)
# 处理期初数据
deal_qichu_equity_data(zj_table, year_list)
# 处理为NULL的数据
deal_null_equity_data(zj_table)
# 导出 csv
# export_csv("分摊出货汇总-20230518.csv", year_list)
# export_csv_2(base_table, ft_table, zj_table, device_type, file_name, year_list)
export_csv_3(
base_table, ft_table, zj_table, device_type, file_name + "(按月维度展示)", year_list
)
if __name__ == "__main__":
# 追踪器
# base_table = "temp_dj_device_details_20230620"
# ft_table = "temp_dj_device_details_20230620_active_hw_record_ft"
# zj_table = "temp_dj_device_details_20230620_active_hw_record_zj"
# device_type = "6,12501"
# service_type = 1
# file_name = "记录仪硬件激活维度计算分摊出货汇总-20230626.csv"
# calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
base_table = "temp_dj_device_details_modify_serins"
ft_table = "temp_dj_device_details_modify_serins_record_ft"
zj_table = "temp_dj_device_details_modify_serins_record_zj"
device_type = "6,12501"
service_type = 2
file_name = "记录仪分摊出货汇总-20240201.csv"
calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
# base_table = "temp_dj_device_details_20230620"
# ft_table = "temp_dj_device_details_20230620_active_install_record_ft"
# zj_table = "temp_dj_device_details_20230620_active_install_record_zj"
# device_type = "6,12501"
# service_type = 3
# file_name = "记录仪安装激活维度计算分摊出货汇总-20230626.csv"
# calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
# # GPS
# base_table = "temp_dj_device_details_20230620"
# ft_table = "temp_dj_device_details_20230620_active_hw_gps_ft"
# zj_table = "temp_dj_device_details_20230620_active_hw_gps_zj"
# device_type = "8"
# service_type = 1
# file_name = "GPS硬件激活维度计算分摊出货汇总-20230626.csv"
# calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
# base_table = "temp_dj_device_details_20230620"
# ft_table = "temp_dj_device_details_20230620_active_pk_gps_ft"
# zj_table = "temp_dj_device_details_20230620_active_pk_gps_zj"
# device_type = "8"
# service_type = 2
# file_name = "GPS服务激活维度计算分摊出货汇总-20230626.csv"
# calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
# base_table = "temp_dj_device_details_20230620"
# ft_table = "temp_dj_device_details_20230620_active_install_gps_ft"
# zj_table = "temp_dj_device_details_20230620_active_install_gps_zj"
# device_type = "8"
# service_type = 3
# file_name = "GPS安装激活维度计算分摊出货汇总-20230626.csv"
# calculate(base_table, ft_table, zj_table, device_type, service_type, file_name)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!