Commit 379ab231 by 杨林龙

优化审计脚本代码

1 parent 4275e25f
# -*- coding:utf-8 -*-
from __future__ import print_function
import time
# import MySQLdb
import pymysql as MySQLdb
import sys
......@@ -13,17 +14,21 @@ import sys
#
def paddstr(strx):
# return "NULL" if strx == None else "\'" + MySQLdb.escape_string(str(strx)).decode() + "\'"
return "NULL" if strx == None else "\'" + MySQLdb.converters.escape_string(str(strx)) + "\'"
return (
"NULL"
if strx == None
else "'" + MySQLdb.converters.escape_string(str(strx)) + "'"
)
def paddnum(numx, default='NULL'):
def paddnum(numx, default="NULL"):
return default if numx == None else str(numx)
class MySQL:
u'''对MySQLdb常用函数进行封装的类'''
"""对MySQLdb常用函数进行封装的类"""
error_code = '' # MySQL错误号码
error_code = "" # MySQL错误号码
_instance = None # 本类的实例
_conn = None # 数据库conn
......@@ -33,17 +38,19 @@ class MySQL:
_timecount = 0
def __init__(self, dbconfig):
u'构造器:根据数据库连接参数,创建MySQL连接'
"构造器:根据数据库连接参数,创建MySQL连接"
try:
self._conn = MySQLdb.connect(host=dbconfig['host'],
port=dbconfig['port'],
user=dbconfig['user'],
passwd=dbconfig['passwd'],
db=dbconfig['db'],
charset=dbconfig['charset'])
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]
error_msg = "MySQL error! ", e.args[0], e.args[1]
print(error_msg)
# 如果没有超过预设超时时间,则再次尝试连接,
......@@ -59,7 +66,7 @@ class MySQL:
self._instance = MySQLdb
def query(self, sql):
u'执行 SELECT 语句'
"执行 SELECT 语句"
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
......@@ -70,8 +77,21 @@ class MySQL:
result = False
return result
def queryList(self, sqlList):
"执行 SELECT 语句"
try:
for sql in sqlList:
# 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 语句'
"执行 UPDATE 及 DELETE 语句"
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
......@@ -83,8 +103,22 @@ class MySQL:
result = False
return result
def updateList(self, sqlList):
"执行 UPDATE 及 DELETE 语句"
try:
for sql in sqlList:
# 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'
"执行 INSERT 语句。如主键为自增长int,则返回新生成的ID"
try:
self._cur.execute("SET NAMES utf8")
if data == None:
......@@ -111,27 +145,27 @@ class MySQL:
return result
def fetchAllRows(self):
u'返回结果列表'
"返回结果列表"
return self._cur.fetchall()
def fetchOneRow(self):
u'返回一行结果,然后游标指向下一行。到达最后一行以后,返回None'
"返回一行结果,然后游标指向下一行。到达最后一行以后,返回None"
return self._cur.fetchone()
def getRowCount(self):
u'获取结果行数'
"获取结果行数"
return self._cur.rowcount
def commit(self):
u'数据库commit操作'
"数据库commit操作"
self._conn.commit()
def rollback(self):
u'数据库回滚操作'
"数据库回滚操作"
self._conn.rollback()
def __del__(self):
u'释放资源(系统GC自动调用)'
"释放资源(系统GC自动调用)"
try:
self._cur.close()
self._conn.close()
......@@ -139,5 +173,5 @@ class MySQL:
pass
def close(self):
u'关闭数据库连接'
"关闭数据库连接"
self.__del__()
......@@ -1235,7 +1235,9 @@ def active_direct_merchant_device():
)
return
bizConn.commit()
logger.info(f"active_direct_merchant_device settle_merchant={settleMer} month={activeMonth} total={activeTotal}")
logger.info(
f"active_direct_merchant_device settle_merchant={settleMer} month={activeMonth} total={activeTotal}"
)
logger.info("active_direct_merchant_device done")
......@@ -1957,7 +1959,7 @@ if __name__ == "__main__":
""""""
startTime = "2023-01-01"
endTime = "2023-04-31"
endTime = "2023-05-31"
# # 导入GPS OBD 车充设备
# query_supplychain_delivery_device(startTime, endTime, devType=8)
# 导入记录仪 车充设备
......@@ -1967,42 +1969,42 @@ if __name__ == "__main__":
# update_delivery_device_settle_merchant(6, 2021)
# update_delivery_device_settle_merchant(8, 2021)
# # #GPS OBD 处理直销 (原代销)
# GPS OBD 处理直销 (原代销)
# match_not_direct_settlement_delivery_order(startTime, 8, 0)
# # #GPS OBD 匹配客户渠道 (原直销)
# GPS OBD 匹配客户渠道 (原直销)
# match_direct_settlement_delivery_order(startTime, devType=8, findmode=0)
#
# 记录仪直销 (原代销)
# match_not_direct_settlement_delivery_order(startTime, devType=6, mode=0)
# #记录仪渠道 (原直销)
# 记录仪渠道 (原直销)
# match_direct_settlement_delivery_order(startTime, devType=6, findmode=0)
#
# #车充直销 (原代销)
# 车充直销 (原代销)
# match_not_direct_settlement_delivery_order(startTime, devType=12501, mode=0)
# #车充渠道 (原直销)
# 车充渠道 (原直销)
# match_direct_settlement_delivery_order(startTime, devType=12501, findmode=0)
# 处理退货
# 直销追踪器退货 -- 一般不会有直销的退货
# #追踪器
# handle_return_device('直销', data=2021, devType=8)
# # #记录仪
# handle_return_device('直销', data=2021, devType=6)
# # #车充退货
# handle_return_device('直销', data=2021, devType=12501)
# #
# # #车充退货
# handle_return_device('渠道', data=2021, devType=12501)
# # #渠道追踪器退货
# handle_return_device('渠道', data=2021, devType=8)
# # #记录仪
# handle_return_device('渠道', data=2021, devType=6)
# 追踪器
handle_return_device("直销", data=2021, devType=8)
# #记录仪
handle_return_device("直销", data=2021, devType=6)
# #车充退货
handle_return_device("直销", data=2021, devType=12501)
#
# #车充退货
handle_return_device("渠道", data=2021, devType=12501)
# #渠道追踪器退货
handle_return_device("渠道", data=2021, devType=8)
# #记录仪
handle_return_device("渠道", data=2021, devType=6)
# 记录仪渠道激活
# active_direct_record_device()
# 追踪器渠道测算激活
active_direct_merchant_device()
# active_direct_merchant_device()
print("done")
......@@ -13,11 +13,11 @@ import calendar
import pandas as pd
import pymysql
logger = logging.getLogger('unmatchlog')
logger = logging.getLogger("unmatchlog")
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('unmatchlog.log')
fileHandler = logging.FileHandler("unmatchlog.log")
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
fileHandler.setFormatter(formatter)
# logger.addHandler(fileHandler)
cnslhandler = logging.StreamHandler()
......@@ -25,147 +25,146 @@ cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_supply_dbcfg = {'host': '192.168.5.23', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_supplychain', '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'}
g_presto_host = '192.168.5.35'
g_supply_dbcfg = {
"host": "192.168.5.23",
"port": 3306,
"user": "data_house_user",
"passwd": "ZhaiMiAxIg",
"db": "glsx_supplychain",
"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",
}
g_presto_host = "192.168.5.35"
g_presto_port = 9090
'''
"""
有源GPS设备-无屏追踪器终端
'''
"""
g_meterial_map = {
'无源GPS设备-GT702': 'GT702',
'无源GPS设备(GT702)': 'GT702',
'无源GPS设备(GT703B)': 'GT703B',
'无源GPS设备(GT703小)': 'GT703',
'无源GPS设备(GT703)': 'GT703',
'无源GPS设备(GT705)': 'GT705',
'无源GPS设备(GT803)': 'GT803',
'无源GPS设备(GT805)': 'GT805',
'无源GPS设备(GT806-62)': 'GT806-62',
'有源GPS设备-GT701': 'GT701',
'有源GPS设备(GT700B)': 'GT700B',
'有源GPS设备(GT700F)': 'GT700F',
'有源GPS设备(GT701C)': 'GT701C',
'有源GPS设备(GT800B)': 'GT800B',
'有源GPS设备(GT800B)(含流量)': 'GT800B',
'有源GPS设备(GT800C)': 'GT800C',
'有源GPS设备(GT800F)': 'GT800F',
'有源GPS设备(GT801A)': 'GT801A', # 3
'有源GPS设备(GT801C-1)': 'GT801C',
'有源GPS设备(GT801C)': 'GT801C',
'有源GPS设备(GT801C)(含流量)': 'GT801C',
'有源GPS设备(GT801D)': 'GT801D',
'有源GPS设备(GT801F)': 'GT801F',
'有源GPS设备(GT801F)(含流量)': 'GT801F',
'有源GPS设备(GT801)': 'GT801',
'有源GPS设备-无屏追踪器终端': 'GT700',
'4GAI小精灵记录仪 通用(含卡)': 'RE001',
'4GAI小精灵记录仪(豪华专用版)': 'RE001',
'隐藏记录仪(中低端)': 'RE002',
'隐藏记录仪 通用/U型 (不含卡)': 'RE002',
'4GAI小精灵记录仪 专用(含卡)': 'RE001',
"无源GPS设备-GT702": "GT702",
"无源GPS设备(GT702)": "GT702",
"无源GPS设备(GT703B)": "GT703B",
"无源GPS设备(GT703小)": "GT703",
"无源GPS设备(GT703)": "GT703",
"无源GPS设备(GT705)": "GT705",
"无源GPS设备(GT803)": "GT803",
"无源GPS设备(GT805)": "GT805",
"无源GPS设备(GT806-62)": "GT806-62",
"有源GPS设备-GT701": "GT701",
"有源GPS设备(GT700B)": "GT700B",
"有源GPS设备(GT700F)": "GT700F",
"有源GPS设备(GT701C)": "GT701C",
"有源GPS设备(GT800B)": "GT800B",
"有源GPS设备(GT800B)(含流量)": "GT800B",
"有源GPS设备(GT800C)": "GT800C",
"有源GPS设备(GT800F)": "GT800F",
"有源GPS设备(GT801A)": "GT801A", # 3
"有源GPS设备(GT801C-1)": "GT801C",
"有源GPS设备(GT801C)": "GT801C",
"有源GPS设备(GT801C)(含流量)": "GT801C",
"有源GPS设备(GT801D)": "GT801D",
"有源GPS设备(GT801F)": "GT801F",
"有源GPS设备(GT801F)(含流量)": "GT801F",
"有源GPS设备(GT801)": "GT801",
"有源GPS设备-无屏追踪器终端": "GT700",
"4GAI小精灵记录仪 通用(含卡)": "RE001",
"4GAI小精灵记录仪(豪华专用版)": "RE001",
"隐藏记录仪(中低端)": "RE002",
"隐藏记录仪 通用/U型 (不含卡)": "RE002",
"4GAI小精灵记录仪 专用(含卡)": "RE001",
}
g_device_prefix_dict = {
'GT702': '7',
'GT703B': '16',
'GT703': '5',
'GT705': '19',
'GT803': '26',
'GT805': '29',
'GT806-62': '62',
'GT806': '56',
'GT701': '4',
'GT700B': '15',
'GT700F': '11',
'GT701C': '18',
'GT800B': '15',
'GT800C': '63',
'GT800F': '11',
'GT801A': '35',
'GT801C': '17',
'GT801D': '82',
'GT801F': '87',
'GT801': '25',
'GT700': '8',
'RE001': 'SH26H',
'RE002': 'SH26H'
"GT702": "7",
"GT703B": "16",
"GT703": "5",
"GT705": "19",
"GT803": "26",
"GT805": "29",
"GT806-62": "62",
"GT806": "56",
"GT701": "4",
"GT700B": "15",
"GT700F": "11",
"GT701C": "18",
"GT800B": "15",
"GT800C": "63",
"GT800F": "11",
"GT801A": "35",
"GT801C": "17",
"GT801D": "82",
"GT801F": "87",
"GT801": "25",
"GT700": "8",
"RE001": "SH26H",
"RE002": "SH26H",
}
snPreDict = {
'11': '22',
'15': '21',
'16': '23',
'17': '24',
'26': '36',
'29': '39',
'62': '68'
"11": "22",
"15": "21",
"16": "23",
"17": "24",
"26": "36",
"29": "39",
"62": "68",
}
monthDict = {
'2020年1月':'2020-01-31',
'2020年2月':'2020-02-28',
'2020年3月':'2020-03-31',
'2020年4月':'2020-04-30',
'2020年5月':'2020-05-30',
'2020年6月':'2020-06-30',
'2020年7月':'2020-07-31',
'2020年8月':'2020-08-30',
'2020年9月':'2020-09-30',
'2020年10月':'2020-10-30',
'2020年11月':'2020-11-30',
'2020年12月':'2020-12-30',
'2021年1月': '2021-01-30',
'2021年2月': '2021-02-28',
'2021年3月': '2021-03-31',
'2021年4月': '2021-04-30',
'2021年5月': '2021-05-31',
'2021年6月': '2021-06-30',
'2021年7月': '2021-07-30',
'2021年8月': '2021-08-30',
'2021年9月': '2021-09-30',
'2021年10月': '2021-10-31',
'2021年11月': '2021-11-30',
'2021年12月': '2021-12-30',
"2020年1月": "2020-01-31",
"2020年2月": "2020-02-28",
"2020年3月": "2020-03-31",
"2020年4月": "2020-04-30",
"2020年5月": "2020-05-30",
"2020年6月": "2020-06-30",
"2020年7月": "2020-07-31",
"2020年8月": "2020-08-30",
"2020年9月": "2020-09-30",
"2020年10月": "2020-10-30",
"2020年11月": "2020-11-30",
"2020年12月": "2020-12-30",
"2021年1月": "2021-01-30",
"2021年2月": "2021-02-28",
"2021年3月": "2021-03-31",
"2021年4月": "2021-04-30",
"2021年5月": "2021-05-31",
"2021年6月": "2021-06-30",
"2021年7月": "2021-07-30",
"2021年8月": "2021-08-30",
"2021年9月": "2021-09-30",
"2021年10月": "2021-10-31",
"2021年11月": "2021-11-30",
"2021年12月": "2021-12-30",
}
def genDeliveryTime(settleDate, mode=0):
"""根据结算随机生成发货时间"""
settleDate = datetime.datetime.strptime(settleDate, '%Y-%m-%d')
settleDate = datetime.datetime.strptime(settleDate, "%Y-%m-%d")
monthRange = calendar.monthrange(settleDate.year, settleDate.month)
if mode == -1:
dayx = 0 - random.randint(7, 60)
deliveryDate = settleDate + relativedelta(days=dayx)
else:
#dayx = random.randint(1, monthRange[1] - 7)
# dayx = random.randint(1, monthRange[1] - 7)
deliveryDate = settleDate
hour = random.randint(0, 199) % 13 + 8 # 8点开始
munite = random.randint(0, 199) % 60
sencond = random.randint(0, 199) % 60
delivryDate = datetime.datetime.now().replace(year=deliveryDate.year, month=deliveryDate.month,
day=deliveryDate.day, hour=hour, minute=munite, second=sencond)
delivryDate = datetime.datetime.now().replace(
year=deliveryDate.year,
month=deliveryDate.month,
day=deliveryDate.day,
hour=hour,
minute=munite,
second=sencond,
)
return delivryDate
......@@ -173,14 +172,20 @@ def genDeliveryOrder(deliveryDate):
"""生成订单"""
# 2021 01 04 16 43 51 79849566
# deliveryDate = datetime.datetime.now()
strOrder = "%04d%02d%02d%02d%02d%02d%03d" % \
(deliveryDate.year, deliveryDate.month, deliveryDate.day, deliveryDate.hour,
deliveryDate.minute, deliveryDate.second, deliveryDate.microsecond)
strOrder = "%04d%02d%02d%02d%02d%02d%03d" % (
deliveryDate.year,
deliveryDate.month,
deliveryDate.day,
deliveryDate.hour,
deliveryDate.minute,
deliveryDate.second,
deliveryDate.microsecond,
)
return strOrder
def query_alloc_gps_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefix):
'''虚拟设备'''
"""虚拟设备"""
sql = f"select SUBSTR(sn,1,7),max(sn) from {tableName} where is_virtual = 1 and sn like '{prefix}%' GROUP BY SUBSTR(sn,1,7)"
if not dbConn.query(sql):
print(f"query_alloc_virtual_sn fail, sql={sql}")
......@@ -189,23 +194,23 @@ def query_alloc_gps_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefix):
dateGenDict = devPrefixAllocDict.get(prefix)
if dateGenDict is None:
dateGenDict = {}
#sn = 'SH25H%02d%02d%02d%04d'
# sn = 'SH25H%02d%02d%02d%04d'
for row in result:
preSn = row[0]
sn = row[1]
'''FFYMMDDNNN'''
yearx = preSn[2: 3]
"""FFYMMDDNNN"""
yearx = preSn[2:3]
monthx = preSn[3:5]
dayx = preSn[5:7]
maxNum = sn[7:11]
genDate = f"202{yearx}-{monthx}-{dayx} 00:00:00"
newDate = datetime.datetime.strptime(genDate, "%Y-%m-%d %H:%M:%S")
dateGenDict[newDate] = int(maxNum)+1
dateGenDict[newDate] = int(maxNum) + 1
devPrefixAllocDict[prefix] = dateGenDict
def query_alloc_chechong_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefix):
'''虚拟设备'''
"""虚拟设备"""
sql = f"select SUBSTR(sn,1,8),max(sn) from {tableName} where is_virtual = 1 and sn like '{prefix}%' GROUP BY SUBSTR(sn,1,8)"
if not dbConn.query(sql):
print(f"query_alloc_virtual_sn fail, sql={sql}")
......@@ -217,19 +222,19 @@ def query_alloc_chechong_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefi
for row in result:
preSn = row[0]
sn = row[1]
'''FFFYMMDDNNN'''
yearx = preSn[3: 4]
"""FFFYMMDDNNN"""
yearx = preSn[3:4]
monthx = preSn[4:6]
dayx = preSn[6:8]
maxNum = sn[8:12]
genDate = f"202{yearx}-{monthx}-{dayx} 00:00:00"
newDate = datetime.datetime.strptime(genDate, "%Y-%m-%d %H:%M:%S")
dateGenDict[newDate] = int(maxNum)+1
dateGenDict[newDate] = int(maxNum) + 1
devPrefixAllocDict[prefix] = dateGenDict
def query_alloc_record_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefix):
'''虚拟设备'''
"""虚拟设备"""
sql = f"select SUBSTR(sn,1,11),max(sn) from {tableName} where is_virtual = 1 and LENGTH(sn) = 15 and sn like '{prefix}%' GROUP BY SUBSTR(sn,1,11)"
if not dbConn.query(sql):
print(f"query_alloc_virtual_sn fail, sql={sql}")
......@@ -241,34 +246,36 @@ def query_alloc_record_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefix)
for row in result:
preSn = row[0]
sn = row[1]
'''SH23G2201290003'''
yearx = preSn[5: 7]
"""SH23G2201290003"""
yearx = preSn[5:7]
monthx = preSn[7:9]
dayx = preSn[9:11]
maxNum = sn[11:16]
genDate = f"20{yearx}-{monthx}-{dayx} 00:00:00"
newDate = datetime.datetime.strptime(genDate, "%Y-%m-%d %H:%M:%S")
dateGenDict[newDate] = int(maxNum)+1
dateGenDict[newDate] = int(maxNum) + 1
devPrefixAllocDict[prefix] = dateGenDict
def gen_device_by_delivery(deliveryDate, deliveryNum, devPrefixAllocDict, snList, prefix):
'''根据发货生成设备号'''
def gen_device_by_delivery(
deliveryDate, deliveryNum, devPrefixAllocDict, snList, prefix, dbSnList=[]
):
"""根据发货生成设备号"""
productDate = deliveryDate - relativedelta(days=1)
productDate = productDate.replace(hour=0, minute=0, second=0, microsecond=0)
# prefix = '863'
devAlloc = devPrefixAllocDict.get(prefix, None)
if devAlloc is None:
''''''
""""""
devAlloc = {}
# 获取
needAllocNum = deliveryNum
while needAllocNum > 0:
''''''
""""""
alloc = devAlloc.get(productDate, None)
if alloc is None:
alloc = 0
if prefix in ('SH26H', 'SH23G', 'SH24G'):
if prefix in ("SH26H", "SH23G", "SH24G"):
dateTotal = 9999
else:
# 后3位是序列号
......@@ -291,25 +298,46 @@ def gen_device_by_delivery(deliveryDate, deliveryNum, devPrefixAllocDict, snList
for idx in range(startId, startId + allocThisTime):
if len(prefix) == 1:
'''FYYMMDDNNN'''
"""FYYMMDDNNN"""
sn = prefix + "%02d%02d%02d%03d" % (
productDate.year % 100, productDate.month, productDate.day, idx)
elif prefix == 'SH26H':
sn = 'SH25H%02d%02d%02d%04d' % (
productDate.year % 100, productDate.month, productDate.day, idx)
elif prefix in ['SH23G','SH24G']:
sn = 'SH23G%02d%02d%02d%04d' % (
productDate.year % 100, productDate.month, productDate.day, idx)
productDate.year % 100,
productDate.month,
productDate.day,
idx,
)
elif prefix == "SH26H":
sn = "SH25H%02d%02d%02d%04d" % (
productDate.year % 100,
productDate.month,
productDate.day,
idx,
)
elif prefix in ["SH23G", "SH24G"]:
sn = "SH23G%02d%02d%02d%04d" % (
productDate.year % 100,
productDate.month,
productDate.day,
idx,
)
else:
# 86207100129
'''FFYMMDDNNN'''
"""FFYMMDDNNN"""
sn = prefix + "%d%02d%02d%03d" % (
productDate.year % 10, productDate.month, productDate.day, idx)
productDate.year % 10,
productDate.month,
productDate.day,
idx,
)
# logger.info("gen_device_by_delivery deliverydate=%s productdate=%s %s",deliveryDate,productDate,sn)
# (delivery_id,delivery_date,sn,product_date)
# strValue = "(%d,'%s','%s','%s','%s')" % (delivId, deliveryDate, devType, sn, productDate)
# arrValues.append(strValue)
snList.append(sn)
if sn in dbSnList:
needAllocNum += 1
print("needAllocNum:", needAllocNum)
else:
snList.append(sn)
productDate = productDate - relativedelta(days=1)
if devPrefixAllocDict.get(prefix) is None:
......@@ -318,12 +346,30 @@ def gen_device_by_delivery(deliveryDate, deliveryNum, devPrefixAllocDict, snList
return prefix
def getAllSnInDB(devType):
bizConn = MySQL(g_pro_biz_dbcfg)
sql = f"""
SELECT sn FROM dj_2021_settle_details WHERE device_type = {devType};
"""
if not bizConn.query(sql):
logger.error("sync_device_data fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
snList = []
for row in res:
snList.append(row[0])
return snList
def calc_un_match_order():
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "SELECT id,finance_time,cus_name,product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,hw_term,pk_name,match_total from " \
"dj_2021_settlment_order where product_code <> 'GLSX50029' and product_code not like '%FW%' and status = 0"
sql = (
"SELECT id,finance_time,cus_name,product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax,"
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,hw_term,pk_name,match_total from "
"dj_2021_settlment_order where product_code <> 'GLSX50029' and product_code not like '%FW%' and status = 0"
)
if not bizConn.query(sql):
logger.error("sync_device_data fail, sql=%s", sql)
......@@ -333,10 +379,10 @@ def calc_un_match_order():
for row in res:
rowId = row[0]
finnTime = row[1] # 财务时间
if finnTime == '21年1月份':
settleTime = '2021-01-31'
elif finnTime == '21年2月份':
settleTime = '2021-02-28'
if finnTime == "21年1月份":
settleTime = "2021-01-31"
elif finnTime == "21年2月份":
settleTime = "2021-02-28"
# 生成发货时间
deliveryTime = genDeliveryTime(settleTime)
deliveryOrder = genDeliveryOrder(deliveryTime)
......@@ -356,91 +402,113 @@ def calc_un_match_order():
if matchTotal is not None:
total -= matchTotal
genDevList = []
prefix = gen_device_by_delivery(prodName, deliveryTime, total, devPrefixAllocDict, genDevList)
prefix = gen_device_by_delivery(
prodName, deliveryTime, total, devPrefixAllocDict, genDevList
)
arrValues = []
for sn in genDevList:
# (sn, is_virtual, device_type, material_code, delivery_order, delivery_time, delivery_merchant, pk_name,
# pk_period, settle_merchant, settle_order, settle_time, pk_price, pk_price_tax, hw_price, hw_price_tax,
# install_price, install_price_tax)
if prefix == 'SH26H':
if prefix == "SH26H":
devtype = 6
else:
devtype = 8
settleDetail = "(%s,1,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % \
(paddstr(sn), paddnum(devtype), paddstr(prodCode), paddstr(deliveryOrder),
paddstr(deliveryTime), paddstr(cusName), paddstr(pkName), paddnum(hwTerm), paddstr(cusName),
paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice), paddnum(pkPriceTax),
paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice), paddnum(installPriceTax))
settleDetail = "(%s,1,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % (
paddstr(sn),
paddnum(devtype),
paddstr(prodCode),
paddstr(deliveryOrder),
paddstr(deliveryTime),
paddstr(cusName),
paddstr(pkName),
paddnum(hwTerm),
paddstr(cusName),
paddstr(str(rowId)),
paddstr(settleTime),
paddnum(pkPrice),
paddnum(pkPriceTax),
paddnum(hwPrice),
paddnum(hwPriceTax),
paddnum(installPrice),
paddnum(installPriceTax),
)
arrValues.append(settleDetail)
if len(arrValues) > 0:
insertSql = "insert into dj_2021_settle_details (sn,is_virtual,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time," \
"pk_price,pk_price_tax,hw_price,hw_price_tax,install_price, install_price_tax) values " + \
",".join(arrValues)
insertSql = (
"insert into dj_2021_settle_details (sn,is_virtual,device_type,material_code,delivery_order,"
"delivery_time,delivery_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,"
"pk_price,pk_price_tax,hw_price,hw_price_tax,install_price, install_price_tax) values "
+ ",".join(arrValues)
)
if not bizConn.insert(insertSql):
logger.error("calc_un_match_order fail, sql=%s", insertSql)
return
logger.info("calc_un_match_order cusname=%s total devs %d", cusName, len(arrValues))
logger.info(
"calc_un_match_order cusname=%s total devs %d", cusName, len(arrValues)
)
logger.info("calc_un_match_order done")
class ShopMerSales:
merId = 0
merName = ''
settName = ''
channel = ''
merName = ""
settName = ""
channel = ""
sales = 0
class SettleMerSales:
settleName = ''
settleName = ""
sales = 0
shopList = []
merIdList = []
def getPkName(pkName, period):
if pkName is None or pkName == '':
if pkName is None or pkName == "":
if period == 12:
pkName = '驾宝无忧-基础版一年期'
pkName = "驾宝无忧-基础版一年期"
elif period == 24:
pkName = '驾宝无忧-基础版二年期'
pkName = "驾宝无忧-基础版二年期"
elif period == 36:
pkName = '驾宝无忧-基础版三年期'
pkName = "驾宝无忧-基础版三年期"
elif period == 48:
pkName = '驾宝无忧-基础版四年期'
pkName = "驾宝无忧-基础版四年期"
elif period == 60:
pkName = '驾宝无忧-基础版五年期'
pkName = "驾宝无忧-基础版五年期"
else:
pkName = '驾宝无忧-基础版'
pkName = "驾宝无忧-基础版"
return pkName
def getPkTerm(pkName):
pkTerm = 0
if pkName is not None and pkName != '':
if pkName == '位置服务三年期':
if pkName is not None and pkName != "":
if pkName == "位置服务三年期":
pkTerm = 36
elif pkName == '记录仪运营服务一年版':
elif pkName == "记录仪运营服务一年版":
pkTerm = 12
elif pkName == '记录仪运营服务三年版':
elif pkName == "记录仪运营服务三年版":
pkTerm = 36
elif pkName == '驾宝无忧-基础版一年期':
elif pkName == "驾宝无忧-基础版一年期":
pkTerm = 12
elif pkName == '驾宝无忧-基础版三年期':
elif pkName == "驾宝无忧-基础版三年期":
pkTerm = 36
elif pkName == '驾宝无忧-基础版三年期、驾宝无忧-基础版一年期':
elif pkName == "驾宝无忧-基础版三年期、驾宝无忧-基础版一年期":
pkTerm = 36
elif pkName == '驾宝无忧-畅享版三年期':
elif pkName == "驾宝无忧-畅享版三年期":
pkTerm = 36
return pkTerm
def query_settlement_merchant(auditConn, settMerDict={}):
'''查询每个结算客户下属门店'''
sql = "select merchant_id,merchant_name,settle_merchant_name,svr_merchant_name from dj_system_merchant " \
"where settle_merchant_name <>'' and svr_merchant_name <> '二次转化客户'"
"""查询每个结算客户下属门店"""
sql = (
"select merchant_id,merchant_name,settle_merchant_name,svr_merchant_name from dj_system_merchant "
"where settle_merchant_name <>'' and svr_merchant_name <> '二次转化客户'"
)
if False == auditConn.query(sql):
logger.error("query_settlement_merchant query fail, sql=%s", sql)
......@@ -455,12 +523,12 @@ def query_settlement_merchant(auditConn, settMerDict={}):
shopInfo.settName = str(v[2]).strip()
channel = str(v[3]).strip()
if channel == '广汇门店':
channel = '广汇直销'
elif channel == '渠道客户':
channel = '渠道'
elif channel == '非广汇直销' or channel == '非广汇直销客户':
channel = '非广汇直销'
if channel == "广汇门店":
channel = "广汇直销"
elif channel == "渠道客户":
channel = "渠道"
elif channel == "非广汇直销" or channel == "非广汇直销客户":
channel = "非广汇直销"
shopInfo.channel = channel
settMerInfo = settMerDict.get(shopInfo.settName, None)
......@@ -472,13 +540,15 @@ def query_settlement_merchant(auditConn, settMerDict={}):
else:
settMerInfo.shopList.append(shopInfo)
settMerDict[shopInfo.settName] = settMerInfo
logger.info("query_settlement_merchant total settlemer = %d", len(settMerDict.keys()))
logger.info(
"query_settlement_merchant total settlemer = %d", len(settMerDict.keys())
)
def calc_not_direct_device_active_time(deliveryTime, settleTime):
'''计算发货时间到结算时间之间的时间'''
deliveryDate = deliveryTime#datetime.datetime.strptime(str(deliveryTime), '%Y-%m-%d %H:%M:%S')
settleDate = datetime.datetime.strptime(str(settleTime), '%Y-%m-%d')
"""计算发货时间到结算时间之间的时间"""
deliveryDate = deliveryTime # datetime.datetime.strptime(str(deliveryTime), '%Y-%m-%d %H:%M:%S')
settleDate = datetime.datetime.strptime(str(settleTime), "%Y-%m-%d")
if deliveryDate.month == settleDate.month:
lastMonthOfSettle = settleDate
else:
......@@ -493,41 +563,55 @@ def calc_not_direct_device_active_time(deliveryTime, settleTime):
munite = random.randint(0, 199) % 60
sencond = random.randint(0, 199) % 60
strTime = "%04d-%02d-%02d %02d:%02d:%02d" % (
activeDate.year, activeDate.month, activeDate.day, hour, munite, sencond)
activeDate.year,
activeDate.month,
activeDate.day,
hour,
munite,
sencond,
)
return strTime
gPrefixAllocDict = {}
def match_gen_sn_settlement_delivery_order(startTime,devType, prefix):
def match_gen_sn_settlement_delivery_order(startTime, devType, prefix):
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
mode = 0
settMerDict = {}
# 获取数据库所有设备进行去重校验
dbSnList = getAllSnInDB(devType)
query_settlement_merchant(bizConn, settMerDict)
if devType == 8:
resultTblName = 'dj_2023_settle_details'
resultTblName = "dj_2023_settle_details"
strType = "('GPS','OBD')"
tblName = 'dj_2023_settlment_order'
tblName = "dj_2023_settlment_order"
query_alloc_gps_virtual_sn(bizConn, gPrefixAllocDict, resultTblName, prefix)
elif devType == 6:
resultTblName = 'dj_2023_settle_details_record'
resultTblName = "dj_2023_settle_details_record"
strType = "('记录仪')"
tblName = 'dj_2023_settlment_order'
tblName = "dj_2023_settlment_order"
query_alloc_record_virtual_sn(bizConn, gPrefixAllocDict, resultTblName, prefix)
elif devType == 12501:
resultTblName = 'dj_2023_settle_details_record'
resultTblName = "dj_2023_settle_details_record"
strType = "('车充')"
tblName = 'dj_2023_settlment_order'
query_alloc_chechong_virtual_sn(bizConn, gPrefixAllocDict, resultTblName, prefix)
#sale_type = '代销' and business_type = '智慧门店SAAS服务' and
sql = "SELECT id,finance_time,trim(cus_name),product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,match_total," \
"sale_type from %s where device_type in %s and product_type = '硬件' " \
"and status <> 1 and business_type = 'SAAS系统订阅服务—旧版本' " \
"and finance_time >= '%s' order by finance_time " % (tblName, strType, startTime)
tblName = "dj_2023_settlment_order"
query_alloc_chechong_virtual_sn(
bizConn, gPrefixAllocDict, resultTblName, prefix
)
# sale_type = '代销' and business_type = '智慧门店SAAS服务' and
sql = (
"SELECT id,finance_time,trim(cus_name),product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax,"
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,match_total,"
"sale_type from %s where device_type in %s and product_type = '硬件' "
"and status <> 1 and business_type = 'SAAS系统订阅服务—旧版本' "
"and finance_time >= '%s' order by finance_time "
% (tblName, strType, startTime)
)
if not bizConn.query(sql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", sql)
......@@ -536,27 +620,37 @@ def match_gen_sn_settlement_delivery_order(startTime,devType, prefix):
for v in res:
rowId = v[0]
finDate = v[1]
#finDate = datetime.datetime.strptime(finTime, '%Y-%m-%d %H:%M:%S')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
# finDate = datetime.datetime.strptime(finTime, '%Y-%m-%d %H:%M:%S')
strFinDate = finDate.strftime("%Y-%m")
settleTime = finDate.strftime("%Y-%m-%d")
cusName = v[2]
matchCusName = cusName
saleType = v[16]
if cusName == '绵阳鑫驰骋商贸有限公司' or cusName == '成都市艾潇商贸有限公司':
matchCusName = '四川新艾潇商贸有限公司'
elif cusName in ('广汇汽车服务有限责任公司天津武清分公司', '东台宝通汽车服务有限责任公司',
'广汇汽车服务有限责任公司东台分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司'):
matchCusName = '广汇汽车'
cusName = '广汇汽车'
saleType = '广汇'
if cusName == "绵阳鑫驰骋商贸有限公司" or cusName == "成都市艾潇商贸有限公司":
matchCusName = "四川新艾潇商贸有限公司"
elif cusName in (
"广汇汽车服务有限责任公司天津武清分公司",
"东台宝通汽车服务有限责任公司",
"广汇汽车服务有限责任公司东台分公司",
"上海宝信实嘉汽车销售有限公司天津武清分公司",
):
matchCusName = "广汇汽车"
cusName = "广汇汽车"
saleType = "广汇"
productCode = v[3]
total = v[4]
if total <= 0:
logger.error("match_direct_settlement_delivery_order cusName=%s month=%s total=%d ",
cusName, strFinDate, total)
logger.error(
"match_direct_settlement_delivery_order cusName=%s month=%s total=%d ",
cusName,
strFinDate,
total,
)
continue
logger.info("matchCusName:" + str(matchCusName) + "total:" + str(total))
hwPriceTax = v[5]
hwPrice = v[6]
pkPriceTax = v[7]
......@@ -587,7 +681,7 @@ def match_gen_sn_settlement_delivery_order(startTime,devType, prefix):
shopList = settMerInfo.shopList
# 生成发货时间
if saleType == '渠道':
if saleType == "渠道":
deliveryTime = genDeliveryTime(settleTime, 0)
else:
deliveryTime = genDeliveryTime(settleTime, -1)
......@@ -595,17 +689,21 @@ def match_gen_sn_settlement_delivery_order(startTime,devType, prefix):
deliveryOrder = genDeliveryOrder(deliveryTime)
genDevList = []
gen_device_by_delivery(deliveryTime, total, gPrefixAllocDict, genDevList, prefix)
gen_device_by_delivery(
deliveryTime, total, gPrefixAllocDict, genDevList, prefix, dbSnList
)
values = []
for sn in genDevList:
sn = sn
delivery_order = deliveryOrder
delivery_time = deliveryTime
send_merchant_name = cusName
if saleType == '渠道':
if saleType == "渠道":
activeTime = None
else:
activeTime = calc_not_direct_device_active_time(delivery_time, settleTime)
activeTime = calc_not_direct_device_active_time(
delivery_time, settleTime
)
if len(shopList) == 0:
activeMerchant = send_merchant_name
else:
......@@ -613,42 +711,78 @@ def match_gen_sn_settlement_delivery_order(startTime,devType, prefix):
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,flag)
strValue = "(%s,1,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s)" % (
paddstr(sn), paddnum(devType), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(cusName), paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddstr(activeTime), paddstr(activeMerchant),
paddnum(mode), paddstr(saleType))
strValue = (
"(%s,1,%s,%s,%s,%s,%s,%s,%s,"
"%s,%s,%s,%s,%s,%s,%s,%s,"
"%s,%s,%s,%s,%s,%s)"
% (
paddstr(sn),
paddnum(devType),
paddstr(productCode),
paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name),
paddstr(pkName),
paddnum(pkTerm),
paddstr(cusName),
paddstr(str(rowId)),
paddstr(settleTime),
paddnum(pkPrice),
paddnum(pkPriceTax),
paddnum(hwPrice),
paddnum(hwPriceTax),
paddnum(installPrice),
paddnum(installPriceTax),
paddnum(unitCost),
paddstr(activeTime),
paddstr(activeMerchant),
paddnum(mode),
paddstr(saleType),
)
)
values.append(strValue)
matchTotal = len(values)
if matchTotal > 0:
insertSql = "insert into " + resultTblName + " (sn,is_virtual,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,active_time,active_merchant,flag,channel) values %s" % \
','.join(values)
insertSql = (
"insert into "
+ resultTblName
+ " (sn,is_virtual,device_type,material_code,delivery_order,"
"delivery_time,delivery_merchant,pk_name,pk_period,"
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,"
"install_price,install_price_tax,cost,active_time,active_merchant,flag,channel) values %s"
% ",".join(values)
)
if not bizConn.insert(insertSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", insertSql)
logger.error(
"match_direct_settlement_delivery_order fail, sql=%s", insertSql
)
return
status = 2
if total == matchTotal:
status = 1
matchTotal += preMatchTotal
updateSql = "update %s set status = %d,match_total=%d where id=%d" % (tblName, status, matchTotal, rowId)
updateSql = "update %s set status = %d,match_total=%d where id=%d" % (
tblName,
status,
matchTotal,
rowId,
)
if not bizConn.update(updateSql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", updateSql)
logger.error(
"match_not_direct_settlement_delivery_order fail, sql=%s", updateSql
)
return
# logger.info("match_direct_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
# cusName, strFinDate, total, len(result))
else:
logger.error("match_not_direct_settlement_delivery_order cusName=%s month=%s devtype=%d need=%d find=%d",
cusName, strFinDate, devType, total, len(values))
logger.error(
"match_not_direct_settlement_delivery_order cusName=%s month=%s devtype=%d need=%d find=%d",
cusName,
strFinDate,
devType,
total,
len(values),
)
def add_record_settlement_delivery_order():
......@@ -658,29 +792,29 @@ def add_record_settlement_delivery_order():
devType = 6
settMerDict = {}
query_settlement_merchant(bizConn, settMerDict)
resultTblName = 'dj_2021_settle_details_record'
fileName = 'C:\\Users\\333\\Desktop\\记录仪修改.xlsx'
sheetName = '新增客户'
resultTblName = "dj_2021_settle_details_record"
fileName = "C:\\Users\\333\\Desktop\\记录仪修改.xlsx"
sheetName = "新增客户"
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
for idx in data.index:
settleMonth = data.loc[idx, '月份']
cusName = data.loc[idx, '客户']
total = data.loc[idx, '数量']
pkPrice = data.loc[idx, '套餐价格']
hwPrice = data.loc[idx, '硬件价格']
saleType = data.loc[idx, '渠道']
settleMonth = data.loc[idx, "月份"]
cusName = data.loc[idx, "客户"]
total = data.loc[idx, "数量"]
pkPrice = data.loc[idx, "套餐价格"]
hwPrice = data.loc[idx, "硬件价格"]
saleType = data.loc[idx, "渠道"]
settleTime = monthDict.get(settleMonth)
if pkPrice is not None and pkPrice > 0.0:
pkTerm = 36
pkName = '记录仪运营服务三年版'
pkName = "记录仪运营服务三年版"
else:
pkTerm = None
pkName = ''
productCode = ''
finDate = datetime.datetime.strptime(settleTime, '%Y-%m-%d')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
pkName = ""
productCode = ""
finDate = datetime.datetime.strptime(settleTime, "%Y-%m-%d")
strFinDate = finDate.strftime("%Y-%m")
settleTime = finDate.strftime("%Y-%m-%d")
hwPriceTax = None
pkPriceTax = None
......@@ -694,7 +828,7 @@ def add_record_settlement_delivery_order():
shopList = settMerInfo.shopList
# 生成发货时间
if saleType == '渠道':
if saleType == "渠道":
deliveryTime = genDeliveryTime(settleTime, 0)
else:
deliveryTime = genDeliveryTime(settleTime, -1)
......@@ -709,10 +843,12 @@ def add_record_settlement_delivery_order():
delivery_order = deliveryOrder
delivery_time = deliveryTime
send_merchant_name = cusName
if saleType == '渠道':
if saleType == "渠道":
activeTime = None
else:
activeTime = calc_not_direct_device_active_time(delivery_time, settleTime)
activeTime = calc_not_direct_device_active_time(
delivery_time, settleTime
)
if len(shopList) == 0:
activeMerchant = send_merchant_name
else:
......@@ -720,59 +856,96 @@ def add_record_settlement_delivery_order():
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,flag)
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s)" % (
paddstr(sn), paddnum(devType), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(cusName), paddstr(None), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddstr(activeTime), paddstr(activeMerchant),
paddnum(mode), paddstr(saleType))
strValue = (
"(%s,%s,%s,%s,%s,%s,%s,%s,"
"%s,%s,%s,%s,%s,%s,%s,%s,"
"%s,%s,%s,%s,%s,%s)"
% (
paddstr(sn),
paddnum(devType),
paddstr(productCode),
paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name),
paddstr(pkName),
paddnum(pkTerm),
paddstr(cusName),
paddstr(None),
paddstr(settleTime),
paddnum(pkPrice),
paddnum(pkPriceTax),
paddnum(hwPrice),
paddnum(hwPriceTax),
paddnum(installPrice),
paddnum(installPriceTax),
paddnum(unitCost),
paddstr(activeTime),
paddstr(activeMerchant),
paddnum(mode),
paddstr(saleType),
)
)
values.append(strValue)
matchTotal = len(values)
if matchTotal > 0:
insertSql = "insert into " + resultTblName + " (sn,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,active_time,active_merchant,flag,channel) values %s" % \
','.join(values)
insertSql = (
"insert into "
+ resultTblName
+ " (sn,device_type,material_code,delivery_order,"
"delivery_time,delivery_merchant,pk_name,pk_period,"
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,"
"install_price,install_price_tax,cost,active_time,active_merchant,flag,channel) values %s"
% ",".join(values)
)
if not bizConn.insert(insertSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", insertSql)
logger.error(
"match_direct_settlement_delivery_order fail, sql=%s", insertSql
)
return
else:
logger.error("match_not_direct_settlement_delivery_order cusName=%s month=%s devtype=%d need=%d find=%d",
cusName, strFinDate, total, len(values))
logger.error(
"match_not_direct_settlement_delivery_order cusName=%s month=%s devtype=%d need=%d find=%d",
cusName,
strFinDate,
total,
len(values),
)
def update_device_price():
''''''
""""""
bizConn = MySQL(g_pro_biz_dbcfg)
resultTblName = 'dj_2021_settle_details_record'
fileName = 'C:\\Users\\333\\Desktop\\记录仪修改.xlsx'
sheetName = '修改单价'
resultTblName = "dj_2021_settle_details_record"
fileName = "C:\\Users\\333\\Desktop\\记录仪修改.xlsx"
sheetName = "修改单价"
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
strFormat = "date_format(settle_time,'%Y-%m')"
for idx in data.index:
settleTime = data.loc[idx, '月份']
cusName = data.loc[idx, '客户']
addpkPrice = data.loc[idx, '价格']
settleTime = data.loc[idx, "月份"]
cusName = data.loc[idx, "客户"]
addpkPrice = data.loc[idx, "价格"]
settleMonth = monthDict.get(settleTime)
finDate = datetime.datetime.strptime(settleMonth, '%Y-%m-%d')
strFinDate = finDate.strftime('%Y-%m')
finDate = datetime.datetime.strptime(settleMonth, "%Y-%m-%d")
strFinDate = finDate.strftime("%Y-%m")
updateSql = "update dj_2021_settle_details_record set pk_price=pk_price+%f " \
"where settle_merchant='%s' and %s='%s'" % (addpkPrice, cusName,strFormat,strFinDate)
updateSql = (
"update dj_2021_settle_details_record set pk_price=pk_price+%f "
"where settle_merchant='%s' and %s='%s'"
% (addpkPrice, cusName, strFormat, strFinDate)
)
if not bizConn.update(updateSql):
logger.info("update_device_price fail, sql=%s", updateSql)
return
logger.info("update_device_price settleTime=%s settleMerchant=%s ", strFinDate, cusName,)
logger.info(
"update_device_price settleTime=%s settleMerchant=%s ",
strFinDate,
cusName,
)
def update_device_alloc(deviceType, startTime, endTime):
'''回滚'''
"""回滚"""
bizConn = MySQL(g_pro_biz_dbcfg)
if deviceType == 8:
detailTable = "dj_2023_settle_details"
......@@ -781,7 +954,7 @@ def update_device_alloc(deviceType, startTime, endTime):
detailTable = "dj_2023_settle_details_record"
deliveryTable = "dj_2021_delivery_device_record"
sql = f"SELECT sn FROM {detailTable} where settle_time >= '{startTime}' and settle_time < '{endTime}' and is_virtual = 0"
sql = f"SELECT sn FROM {detailTable} where settle_time >= '{startTime}' and settle_time < '{endTime}' and is_virtual = 0"
if not bizConn.query(sql):
return
res = bizConn.fetchAllRows()
......@@ -791,36 +964,35 @@ def update_device_alloc(deviceType, startTime, endTime):
snList.append(paddstr(v[0]))
progess += 1
if len(snList) >= 100:
updateSql = f"update {deliveryTable} set alloc=0 where sn in ({','.join(snList)})"
updateSql = (
f"update {deliveryTable} set alloc=0 where sn in ({','.join(snList)})"
)
if not bizConn.update(updateSql):
logger.error("fail, sql=" + updateSql)
return
print(f"total={len(res)} progress={progess} ")
snList = []
if len(snList) > 0:
updateSql = f"update {deliveryTable} set alloc=0 where sn in ({','.join(snList)})"
updateSql = (
f"update {deliveryTable} set alloc=0 where sn in ({','.join(snList)})"
)
bizConn.update(updateSql)
print(f"total={len(res)} done ")
if __name__ == "__main__":
''''''
startTime = '2023-01-01'
endTime = '2023-04-31'
""""""
startTime = "2023-01-01"
endTime = "2023-05-31"
#追踪器设备
match_gen_sn_settlement_delivery_order(startTime, devType=8, prefix='19')
# 追踪器设备
match_gen_sn_settlement_delivery_order(startTime, devType=8, prefix="19")
# #记录仪设备
match_gen_sn_settlement_delivery_order(startTime, devType=6, prefix='SH23G')
match_gen_sn_settlement_delivery_order(startTime, devType=6, prefix="SH23G")
# #'SH26H', 'SH23G', 'SH24G'
# #车充设备
match_gen_sn_settlement_delivery_order(startTime, devType=12501, prefix='864')
#回滚分配的设备
update_device_alloc(8, startTime, endTime)
update_device_alloc(6, startTime, endTime)
match_gen_sn_settlement_delivery_order(startTime, devType=12501, prefix="864")
# update_device_alloc(8, startTime, endTime)
# 回滚分配的设备
# update_device_alloc(6, startTime, endTime)
......@@ -70,7 +70,7 @@ def loadFinnanceExcelToMysql(fileName, sheetName):
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 = []
......@@ -260,7 +260,7 @@ def updateCustomerChannel():
print("done")
if __name__ == "__main__":
def runScript():
# 财务原表
# filePath = "C:\\Users\\333\\Desktop\\2022审计\\"
# fileName = filePath + "财务与研发收入数据核对-0116.xlsx"
......@@ -328,7 +328,7 @@ if __name__ == "__main__":
loadDjExcelToMysql(fileName, sheetName)
# 五月份
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据5月份"
filePath = "G:\\财务审计\\EXCEL文档\\应收拆分数据5月份\\"
# 处理财务原表
fileName = filePath + "数据源-激活调整用23年5月.xlsx"
sheetName = "Sheet1"
......@@ -347,4 +347,7 @@ if __name__ == "__main__":
sheetName = "廖敏玲"
loadDjExcelToMysql(fileName, sheetName)
if __name__ == "__main__":
runScript()
print("done")
from loadExcelData import *
from calc_dj_income_2021 import *
from handle_unmatch_delivery_device import *
def merge():
print("merge start==")
bizConn = MySQL(g_pro_biz_dbcfg)
sqlList = []
# 记录仪&车充合并
updateSql = """
insert into dj_2021_settle_details (`channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,
`pk_period`,`settle_merchant`,`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,`install_price_tax`,`cost`,`flag`,`return`)
SELECT `channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,
`pk_period`,`settle_merchant`,`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,`install_price_tax`,`cost`,`flag`,`return` from
dj_2023_settle_details_record where settle_time >='2023-01-01';
"""
sqlList.append(updateSql)
# 追踪器合并
updateSql01 = """
insert into dj_2021_settle_details (`channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,
`pk_period`,`settle_merchant`,`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,`install_price_tax`,`cost`,`flag`,`return`)
SELECT `channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,
`pk_period`,`settle_merchant`,`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,`install_price_tax`,`cost`,`flag`,`return` from
dj_2023_settle_details where settle_time >='2023-01-01';
"""
sqlList.append(updateSql01)
if not bizConn.updateList(sqlList):
logger.error("handle_return_device fail, sql=%s", ",".join(sqlList))
print("merge end==")
def deal_data(startTime, endTime):
# # 导入GPS OBD 车充设备
query_supplychain_delivery_device(startTime, endTime, devType=8)
# 导入记录仪 车充设备
query_supplychain_delivery_device(startTime, endTime, devType=6)
# 更新供应链出库设备的结算客户 6表示: 记录仪 车充
update_delivery_device_settle_merchant(6, 2021)
update_delivery_device_settle_merchant(8, 2021)
# GPS OBD 处理直销 (原代销)
match_not_direct_settlement_delivery_order(startTime, 8, 0)
# GPS OBD 匹配客户渠道 (原直销)
match_direct_settlement_delivery_order(startTime, devType=8, findmode=0)
# 记录仪直销 (原代销)
match_not_direct_settlement_delivery_order(startTime, devType=6, mode=0)
# 记录仪渠道 (原直销)
match_direct_settlement_delivery_order(startTime, devType=6, findmode=0)
# 车充直销 (原代销)
match_not_direct_settlement_delivery_order(startTime, devType=12501, mode=0)
# 车充渠道 (原直销)
match_direct_settlement_delivery_order(startTime, devType=12501, findmode=0)
# 生成未匹配的设备数据
# 追踪器设备
match_gen_sn_settlement_delivery_order(startTime, devType=8, prefix="19")
# 记录仪设备
match_gen_sn_settlement_delivery_order(startTime, devType=6, prefix="SH23G")
# 'SH26H', 'SH23G', 'SH24G'
# 车充设备
match_gen_sn_settlement_delivery_order(startTime, devType=12501, prefix="864")
# 合并汇总数据
merge()
# 处理退货
# 直销追踪器退货 -- 一般不会有直销的退货
# 追踪器
handle_return_device("直销", data=2021, devType=8)
# 记录仪
handle_return_device("直销", data=2021, devType=6)
# 车充退货
handle_return_device("直销", data=2021, devType=12501)
# 车充退货
handle_return_device("渠道", data=2021, devType=12501)
# 渠道追踪器退货
handle_return_device("渠道", data=2021, devType=8)
# 记录仪
handle_return_device("渠道", data=2021, devType=6)
def active():
# 记录仪渠道激活
active_direct_record_device()
# 追踪器渠道测算激活
active_direct_merchant_device()
def rollback(startTime, endTime):
update_device_alloc(8, startTime, endTime)
update_device_alloc(6, startTime, endTime)
bizConn = MySQL(g_pro_biz_dbcfg)
sqlList = []
updateSql = """
update dj_2021_settle_details set `return` = 0 where sn in (SELECT sn from dj_2023_settle_details_return where settle_time >= '2023-01-01');
"""
sqlList.append(updateSql)
updateSql01 = """
DELETE from dj_2021_settle_details where settle_time >= '2023-01-01';
"""
sqlList.append(updateSql01)
updateSql02 = """
DELETE from dj_2023_settle_details where settle_time >= '2023-01-01';
"""
sqlList.append(updateSql02)
updateSql03 = """
DELETE from dj_2023_settle_details_record where settle_time >= '2023-01-01' ;
"""
sqlList.append(updateSql03)
updateSql04 = """
DELETE from dj_2023_settle_details_return where settle_time >= '2023-01-01' ;
"""
sqlList.append(updateSql04)
updateSql05 = """
update dj_2023_settlment_order set match_total=NULL,`status`=0 where finance_time >= '2023-01-01' and finance_time <= '2023-05-31';
"""
sqlList.append(updateSql05)
updateSql06 = """
truncate TABLE dj_2023_settle_details;
"""
sqlList.append(updateSql06)
updateSql07 = """
truncate TABLE dj_2023_settle_details_record;
"""
sqlList.append(updateSql07)
updateSql08 = """
truncate TABLE dj_2023_settle_details_return;
"""
sqlList.append(updateSql08)
updateSql09 = """
truncate TABLE dj_2023_settlment_order;
"""
sqlList.append(updateSql09)
updateSql10 = """
truncate TABLE dj_2023_settlment_order_finance;
"""
sqlList.append(updateSql10)
if not bizConn.updateList(sqlList):
logger.error("handle_return_device fail, sql=%s", ",".join(sqlList))
def pre_deal():
bizConn = MySQL(g_pro_biz_dbcfg)
sqlList = []
updateSql = """
UPDATE dj_2023_settlment_order_finance SET device_type = '其他' WHERE product_name LIKE '%无忧卡%';
"""
sqlList.append(updateSql)
updateSql01 = """
UPDATE dj_2023_settlment_order SET device_type = '其他' WHERE product_name LIKE '%无忧卡%';
"""
sqlList.append(updateSql01)
updateSql02 = """
UPDATE dj_2023_settlment_order SET cus_name = '遵义千汇汽车销售服务有限公司' WHERE cus_name = '遵义市千汇汽车销售服务有限公司';
"""
sqlList.append(updateSql02)
updateSql03 = """
UPDATE dj_2023_settlment_order_finance SET cus_name = '遵义千汇汽车销售服务有限公司' WHERE cus_name = '遵义市千汇汽车销售服务有限公司';
"""
sqlList.append(updateSql03)
if not bizConn.updateList(sqlList):
logger.error("handle_return_device fail, sql=%s", ",".join(sqlList))
if __name__ == "__main__":
startTime = "2023-01-01"
endTime = "2023-05-31"
# 将财务和商务表导入到数据库
# runScript()
# pre_deal()
# 寻找差异
# 手动
# 处理数据
deal_data(startTime, endTime)
# 激活数据
# active()
# 回滚数据
# rollback(startTime, endTime)
print("end===")
File mode changed
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!