Commit 0462a911 by 王欣伟

首次提交脚本文件

0 parents
Showing 62 changed files with 6580 additions and 0 deletions
import logging
import pandas as pdas
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/compareCrowFunding/withConversion.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class DealConversion:
def __init__(self) -> None:
pass
def runCompare(self):
# 查询1.3众筹订单数据
# 查询嘀加智享众筹订单数据
# 1、比较条数
print('compare order count, bussCount:%d converCount:%d' %(10, 20))
# 2、比较订单-执行比较逻辑
if __name__=='__main__':
print('deal compare with conversion start')
mainBean = DealConversion()
mainBean.runCompare()
\ No newline at end of file \ No newline at end of file
# -*- coding:utf-8 -*-
from __future__ import print_function
import datetime
import logging
import sys
from logging.handlers import TimedRotatingFileHandler
log = logging.getLogger('yyx')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
log_file_handler = TimedRotatingFileHandler(filename="../../log/supplychian/HandleExcelSign.log", when="D", interval=1)
log_file_handler.setFormatter(formatter)
log_file_handler.setLevel(logging.DEBUG)
log.addHandler(log_file_handler)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
def paddstr(strx):
return 'NULL' if strx == None else '\'' + strx + '\''
def paddnum(numx):
return 'NULL' if numx == None else str(numx)
class DEVICECARD:
iccid = ''
sn = ''
devcetype=0
outtime=''
sendmerchant = ''
activetime=''
deviceCode = 0
deviceName = ''
class DEVICEINFO:
sn = ''
iccid=''
imsi=''
cardid = 0
class SNINMERCHANT:
sn=''
merchantCode = ''
merchantName = ''
shopMerchantCode = ''
shopMerchantName = ''
class WAREHOUSERELATION:
warehosueCode = ''
warehosueName = ''
merchantCode = ''
merchantName = ''
class DEALERUSERINFO:
merchantCode = ''
merchantName = ''
class MATERIALINFO:
merchantCode = ''
merchantName = ''
class CComonUnit:
def getYearFromDateYM(self,dateYm):
dateYmp = datetime.datetime.strptime(dateYm,"%Y%m")
return dateYmp.year
def getMonthFromDateYM(self,dateYm):
dateYmp = datetime.datetime.strptime(dateYm, "%Y%m")
def getYearFromDate(self,dateYm):
dateYmp = datetime.datetime.strptime(dateYm,"%Y-%m")
return dateYmp.year
def getMonthFromDate(self,dateYm):
dateYmp = datetime.datetime.strptime(dateYm, "%Y-%m")
return dateYmp.month
def getDateFromDateYM(self,dateYm):
return datetime.datetime.strptime(dateYm, "%Y-%m")
def getNowDateYMD(self):
curTime = datetime.datetime.now()
return curTime.strftime('%Y-%m-%d')
def getDateFomatDate(self,dateYmd):
return datetime.datetime.strptime(dateYmd,"%Y-%m-%d")
def getDateStrYmdFromDateYmd(self,dateYmd):
return datetime.datetime.strftime(dateYmd,"%Y%m%d")
def getDateStrYmFromDateYm(self,dateYm):
return datetime.datetime.strftime(dateYm,"%Y%m")
def getDateStrY_M_DFromDateYmd(self,dateYmd):
return datetime.datetime.strftime(dateYmd, "%Y-%m-%d")
def getNextDateYMD(self,dateYmd):
dateYmdP = datetime.datetime.strptime(dateYmd,'%Y-%m-%d')
nexDayP = dateYmdP + datetime.timedelta(days=1)
return nexDayP.strftime('%Y-%m-%d')
def getPreDateYMD(self,dateYmd,intervalDay):
dateYmdP = datetime.datetime.strptime(dateYmd, '%Y-%m-%d')
preDayP = dateYmdP - datetime.timedelta(days=intervalDay)
return preDayP.strftime('%Y-%m-%d')
def getNowDateYMDHMS(self):
curTime = datetime.datetime.now()
return curTime.strftime('%Y-%m-%d %H:%M:%S')
def getNowDateYMDHMSD(self):
curTime = datetime.datetime.now()
return curTime.strftime('%Y%m%d%H%M%S')
def getNowDate(self):
return datetime.datetime.now()
def getPreMonth(self,dateYmd):
curdate = self.getDateFomatDate(dateYmd)
first = curdate.replace(day=1)
lastMonth = first - datetime.timedelta(days=1)
return lastMonth.strftime("%Y-%m")
def betweenTwoDate(self,strDate,strDateStart,strDateEnd):
dateYmp = datetime.datetime.strptime(strDate,"%Y-%m-%d")
dateYmpStart = datetime.datetime.strptime(strDateStart,"%Y-%m-%d")
dateYmpEnd = datetime.datetime.strptime(strDateEnd,"%Y-%m-%d")
if dateYmp>= dateYmpStart and dateYmp <= dateYmpEnd:
return True
return False
\ No newline at end of file \ No newline at end of file
# -*- coding:utf-8 -*-
from SupplyChain import DbConnection
from SupplyChain.CommonDef import log, DEVICEINFO, SNINMERCHANT, DEVICECARD, WAREHOUSERELATION, MATERIALINFO, \
DEALERUSERINFO
class DateBase:
dbConnection = ''
def __init__(self):
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain_slave)
def getDbConnection(self):
if self.dbConnection is None:
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain_slave)
return self.dbConnection
def mapWarehouseCode2Info(self):
mapResult = {}
sql = "select warehouse_code,warehouse_name,merchant_code,merchant_name from am_kc_warehouse_relation"
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapWarehouseCode2Info sql query error, sql=%s", sql)
return mapResult
dbData = connect.fetchAllRows()
for item in dbData:
warehouseRelation = WAREHOUSERELATION()
warehouseRelation.warehosueCode = item[0]
warehouseRelation.warehosueName = item[1]
warehouseRelation.merchantCode = item[2]
warehouseRelation.merchantName = item[3]
mapResult[warehouseRelation.warehosueCode] = warehouseRelation
return mapResult
def mapMaterialInfo(self):
mapResult = {}
sql = "select material_code,material_name from am_material_info"
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapMaterialInfo sql query error, sql=%s", sql)
return mapResult
dbData = connect.fetchAllRows()
for item in dbData:
materialInfo = MATERIALINFO()
materialInfo.merchantCode = item[0]
materialInfo.merchantName = item[1]
mapResult[materialInfo.merchantCode] = materialInfo
return mapResult
def mapDealerUserInfo(self):
mapResult = {}
sql = "select merchant_code,merchant_name from bs_dealer_user_info"
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapDealerUserInfo sql query error, sql=%s", sql)
return mapResult
dbData = connect.fetchAllRows()
for item in dbData:
dealerUserInfo = DEALERUSERINFO()
dealerUserInfo.merchantCode = item[0]
dealerUserInfo.merchantName = item[1]
mapResult[dealerUserInfo.merchantCode] = dealerUserInfo
return mapResult
def mapDeviceCard(self,listIccid):
mapResult = {}
if listIccid is None:
return mapResult
sql = "select df.sn,dc.type_id,df.out_storage_time,df.send_merchant_no,dfs.PACKAGE_USER_TIME,dcm.iccid,dc.device_code,dc.device_name " \
"from device_file as df left join device_card_manager AS dcm ON(df.card_id=dcm.id) " \
"left join device_file_snapshot AS dfs ON(df.sn=dfs.sn) " \
"left join device_code AS dc ON(dc.id=df.device_code) " \
"where df.deleted_flag='N' and dcm.iccid in(%s)"%(','.join(["'%s'" % x for x in listIccid]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapDeviceCard sql query error, sql=%s", sql)
return mapResult
dbData = connect.fetchAllRows()
for item in dbData:
sn = item[0]
typeId = item[1]
outStorageTime = item[2]
sendMerchantNo = item[3]
packageUserTime = item[4]
iccid = item[5]
deviceCode = item[6]
deviceName = item[7]
if typeId is None:
typeId = 0
if outStorageTime is None:
outStorageTime = ''
if sendMerchantNo is None:
sendMerchantNo = ''
if packageUserTime is None:
packageUserTime = ''
if iccid is None:
continue
deviceCard = DEVICECARD()
deviceCard.iccid = iccid
deviceCard.sn = sn
deviceCard.activetime = packageUserTime
deviceCard.devcetype = typeId
deviceCard.outtime = outStorageTime
deviceCard.sendmerchant = sendMerchantNo
deviceCard.deviceCode = deviceCode
deviceCard.deviceName = deviceName
mapResult[iccid] = deviceCard
return mapResult
def mapOrderSendMerchant(self,listSn):
mapResult = {}
if listSn is None:
return mapResult
if len(listSn) == 0:
return mapResult
sql = "SELECT oid.sn,oi.send_merchant_no,oi.send_merchant_name FROM order_info_detail AS oid " \
"LEFT JOIN order_info AS oi ON(oid.order_code=oi.order_code) " \
"where oid.sn in(%s)"%(','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapOrderSendMerchant sql query error, sql=%s", sql)
return mapResult
dbData = connect.fetchAllRows()
for item in dbData:
sn = item[0]
merchantCode = item[1]
merchantName = item[2]
snInMerchant = SNINMERCHANT()
snInMerchant.sn = sn
snInMerchant.merchantCode = merchantCode
snInMerchant.merchantName = merchantName
snInMerchant.shopMerchantCode = ''
snInMerchant.shopMerchantName = ''
mapResult[sn] = snInMerchant
return mapResult
def insertDeviceCardManager(self,listDeviceInfo):
if listDeviceInfo is None:
return
sql = "insert into device_card_manager(`iccid`,`imsi`,`company_id`,`created_by`,`updated_by`) values"
sqlDb = []
for item in listDeviceInfo:
strValue = "('%s','%s',1,'admin','admin')" % \
(item.iccid,item.imsi)
sqlDb.append(strValue)
sql += ','.join(sqlDb)
sql += " on duplicate key update `iccid`=values(`iccid`),`imsi`=values(`imsi`),`company_id`=values(`company_id`),`created_by`=values(`created_by`),updated_by=values(`updated_by`)"
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBaseSupply::insertDeviceCardManager sql query error, sql=%s", sql)
return False
connect.commit()
def filtIdDeviceCardManager(self,listDeviceInfo):
if listDeviceInfo is None:
return
sql = "select id,iccid,imsi from device_card_manager where imsi in(%s)"%(','.join(["'%s'" % x.imsi for x in listDeviceInfo]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapOrderSendMerchant sql query error, sql=%s", sql)
return listDeviceInfo
dbData = connect.fetchAllRows()
for item in dbData:
id = item[0]
iccid = item[1]
imsi = item[2]
for device in listDeviceInfo:
if device.imsi == imsi:
device.cardid = id
break;
return listDeviceInfo
def updateDeviceFileCard(self,sn,cardid):
if sn is None:
return
if cardid is None:
return
sql = "update device_file set card_id=%d where sn='%s'"%(cardid,sn)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBaseSupply::updateDeviceFileCard sql query error, sql=%s", sql)
return False
connect.commit()
def updateDeviceFileSnapshot(self,sn,cardid):
if sn is None:
return
if cardid is None:
return
sql = "update device_file_snapshot set card_id=%d where sn='%s'"%(cardid,sn)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBaseSupply::updateDeviceFileSnapshot sql query error, sql=%s", sql)
return False
connect.commit()
def mapStockSendMerchant(self,listSn):
mapResult = {}
if listSn is None:
return mapResult
if len(listSn) == 0:
return mapResult
sql = "SELECT bmsod.sn,bmso.bsso_agent_merchant_code,bmso.bsso_agent_merchant_name,bmso.bsso_merchant_code,bmso.bsso_merchant_name FROM bs_merchant_stock_order_detail AS bmsod " \
"LEFT JOIN bs_merchant_stock_order AS bmso ON(bmsod.bsso_order_code=bmsod.bsso_order_code) " \
"WHERE bmsod.sn IN(%s)"%(','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapOrderSendMerchant sql query error, sql=%s", sql)
return mapResult
dbData = connect.fetchAllRows()
for item in dbData:
sn = item[0]
merchantCode = item[1]
merchantName = item[2]
shopMerchantCode = item[3]
shopMerchantName = item[4]
snInMerchant = SNINMERCHANT()
snInMerchant.sn = sn
snInMerchant.merchantCode = merchantCode
snInMerchant.merchantName = merchantName
snInMerchant.shopMerchantCode = shopMerchantCode
snInMerchant.shopMerchantName = shopMerchantName
mapResult[sn] = snInMerchant
return mapResult
def mapShopSendMerchant(self,listSn):
mapResult = {}
if listSn is None:
return mapResult
if len(listSn) == 0:
return mapResult
sql = "SELECT jsod.sn,jso.agent_merchant_code,jso.agent_merchant_name,jso.shop_merchant_code,jso.SHOP_NAME FROM jst_shop_order_detail AS jsod " \
"LEFT JOIN jst_shop_order AS jso ON(jso.shop_order_code=jsod.shop_order_code) " \
"WHERE jsod.sn IN(%s)"%(','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapOrderSendMerchant sql query error, sql=%s", sql)
return mapResult
dbData = connect.fetchAllRows()
for item in dbData:
sn = item[0]
merchantCode = item[1]
merchantName = item[2]
shopMerchantCode = item[3]
shopMerchantName = item[4]
snInMerchant = SNINMERCHANT()
snInMerchant.sn = sn
snInMerchant.merchantCode = merchantCode
snInMerchant.merchantName = merchantName
snInMerchant.shopMerchantCode = shopMerchantCode
snInMerchant.shopMerchantName = shopMerchantName
mapResult[sn] = snInMerchant
return mapResult
def mapCardInfoBySn(self,listSn):
mapResult = {}
if listSn is None:
return mapResult
if len(listSn) == 0:
return mapResult
sql = "select df.sn,dcm.iccid,dcm.imsi from device_file AS df left join device_card_manager as dcm ON(df.card_id=dcm.id) where df.sn in(%s)"%(','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::getListStatShopStock sql query error, sql=%s", sql)
return mapResult
dbData = connect.fetchAllRows()
for item in dbData:
sn = item[0]
iccid = item[1]
imsi = item[2]
if sn is None:
continue
if iccid is None:
iccid = ''
if imsi is None:
imsi = ''
deviceInfo = DEVICEINFO()
deviceInfo.imsi = imsi
deviceInfo.iccid = iccid
deviceInfo.sn = sn
mapResult[sn] = deviceInfo
return mapResult
# -*- coding:utf-8 -*-
from __future__ import print_function
import logging
import time
import MySQLdb
#from pyhive import presto # or import hive
import datetime
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__()
env='release'
if env == 'test':
g_dbconnect_merchant_stock = {'host': '192.168.3.227', 'port': 3306, 'user': 'dev_admin', 'passwd': '1f7e1ed2','db': 'glsx_merchant_stock_copy', 'charset': 'utf8'}
g_dbconnect_supplychain = {'host': '192.168.1.39', 'port': 3306, 'user': 'glsxsupplychain', 'passwd': 'GlSxSSChain', 'db': 'glsx_supplychain', 'charset': 'utf8'}
g_dbconnect_fb={'host': '192.168.1.39', 'port': 3306, 'user': 'fin_user', 'passwd': '3e7D5Hm9', 'db': 'glsx_finacial_business', 'charset': 'utf8'}
g_dbconnect_cybos = {'host': '192.168.1.39', 'port': 3306, 'user': 'dev_liuquan', 'passwd': '123456','db': 'cyb_os', 'charset': 'utf8'}
g_dbconnect_flow = {'host': '192.168.3.22', 'port': 3307, 'user': 'root', 'passwd': 'Msd^*$@online','db': 'flowplat', 'charset': 'utf8'}
g_dbconnect_dj = {'host': '192.168.1.39', 'port': 3306, 'user': 'dev_liuquan', 'passwd': '123456','db': 'glsx_dj', 'charset': 'utf8'}
g_dbconnect_dj_46 = None
g_dbconnect_dj_carbodyguard = {'host': '192.168.1.39', 'port': 3306, 'user': 'dev_liuquan', 'passwd': '123456','db': 'glsx_dj', 'charset': 'utf8'}
g_dbconnect_dj_gldj = {'host': '192.168.1.39', 'port': 3306, 'user': 'dev_liuquan', 'passwd': '123456','db': 'glsx_dj', 'charset': 'utf8'}
g_dbconnect_dj_xydj = {'host': '192.168.1.39', 'port': 3306, 'user': 'dev_liuquan', 'passwd': '123456','db': 'glsx_dj', 'charset': 'utf8'}
g_dbconnect_gps = {'host': '192.168.3.222', 'port': 3307, 'user': 'root', 'passwd': 'Msd^*$@online','db': 'newgps', 'charset': 'utf8'}
else:
g_dbconnect_supplychain_slave = {'host': '192.168.5.23', 'port': 3306, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J','db': 'glsx_supplychain', 'charset': 'utf8'}
g_dbconnect_supplychain = {'host': '192.168.5.24', 'port': 3306, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J', 'db': 'glsx_supplychain', 'charset': 'utf8'}
g_dbconnect_fb = {'host': '192.168.5.24', 'port': 3307, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J','db': 'glsx_finacial_business', 'charset': 'utf8'}
g_dbconnect_cybos = {'host': '172.16.0.8', 'port': 3306, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J','db': 'cyb_os', 'charset': 'utf8'}
g_dbconnect_flow = {'host': '192.168.5.22', 'port': 3309, 'user': 'dev_liuquan', 'passwd': 'hm8C0u7J','db': 'flowplat', 'charset': 'utf8'}
g_dbconnect_dj = {'host': '47.97.203.216', 'port': 3306, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J', 'db': 'glsx_dj','charset': 'utf8'}
g_dbconnect_dj_46 = {'host': '172.16.0.8', 'port': 3306, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J', 'db': 'glsx_dj','charset': 'utf8'}
g_dbconnect_dj_carbodyguard = {'host': '47.97.203.216', 'port': 3306, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J','db': 'glsx_dj', 'charset': 'utf8'}
g_dbconnect_dj_gldj = {'host': '121.37.201.170', 'port': 3306, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J','db': 'glsx_dj', 'charset': 'utf8'}
g_dbconnect_dj_xydj = {'host': '121.18.128.91', 'port': 3306, 'user': 'user_liuquan', 'passwd': 'kuewr80w','db': 'glsx_dj', 'charset': 'utf8'}
g_dbconnect_gps = {'host': '192.168.5.22', 'port': 3307, 'user': 'user_liuquan', 'passwd': 'hm8C0u7J', 'db': 'gps','charset': 'utf8'}
g_dbconnect_dj31 = {'host': '47.115.93.31', 'port': 3306, 'user': 'user_zengqi', 'passwd': 'ABJjgwOK', 'db': 'glsx_dj',
'charset': 'utf8'}
g_dbconnect_dj216 = {'host': '47.97.203.216', 'port': 3306, 'user': 'user_zengqi', 'passwd': 'ABJjgwOK', 'db': 'glsx_dj',
'charset': 'utf8'}
g_dbconnect_dj170 = {'host': '121.37.201.170', 'port': 3306, 'user': 'user_zengqi', 'passwd': 'ABJjgwOK', 'db': 'scrm_equity',
'charset': 'utf8'}
g_dbconnect_dj131 = {'host': '10.10.134.131', 'port': 3306, 'user': 'biz_read', 'passwd': 'frewi0ew', 'db': 'scrm_equity',
'charset': 'utf8'}
import openpyxl
from SupplyChain import DbConnection
from SupplyChain.CommonDef import log, CComonUnit
from SupplyChain.DataBase import DateBase
class DTMerchantStockInit:
bmsMerchantCode = ''
bmsMerchantName = ''
bmsWarehouseCode = ''
bmsWarehouseName = ''
bmsMaterialCode = ''
bmsMaterialName = ''
bmsYearMonth = ''
bmsCount = 0
createdBy = ''
updatedBy = ''
createdDate = ''
updatedDate = ''
deletedFlag = ''
class HandleMerchantStockInit:
fileName = ''
dbConnection = None
dataBase = None
mapDealerUserInfo = None
mapMaterialInfo = None
mapWarehouseRelation = None
communit = None
def __init__(self):
self.fileName = ''
self.dbConnection = None
self.dataBase = DateBase()
self.mapDealerUserInfo = self.dataBase.mapDealerUserInfo()
self.mapMaterialInfo = self.dataBase.mapMaterialInfo()
self.mapWarehouseRelation = self.dataBase.mapWarehouseCode2Info()
self.communit = CComonUnit()
def getDbConnection(self):
if self.dbConnection is None:
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain)
return self.dbConnection
def setFileName(self, fileName):
self.fileName = fileName
def readExcel(self):
listResult = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
# rows = sheet.max_row
rows = 16
for i in range(2, rows + 1):
merchantCode = sheet['A%d' % (i)].value
merchantName = sheet['B%d' % (i)].value
warehouseCode = sheet['C%d' % (i)].value
warehouseName = sheet['D%d' % (i)].value
materialCode = sheet['E%d' % (i)].value
materialName = sheet['F%d' % (i)].value
yearMonth = sheet['G%d' % (i)].value
count = sheet['H%d' % (i)].value
if merchantCode is None:
log.error("HandleMerchantStockInit::readExcel merchantcode is None i=%d", i)
return None
if merchantName is None:
log.error("HandleMerchantStockInit::readExcel merchantName is None i=%d", i)
return None
if warehouseCode is None:
log.error("HandleMerchantStockInit::readExcel warehouseCode is None i=%d", i)
return None
if warehouseName is None:
log.error("HandleMerchantStockInit::readExcel warehouseName is None i=%d", i)
return None
if materialCode is None:
log.error("HandleMerchantStockInit::readExcel materialCode is None i=%d", i)
return None
if materialName is None:
log.error("HandleMerchantStockInit::readExcel materialName is None i=%d", i)
return None
if yearMonth is None:
log.error("HandleMerchantStockInit::readExcel yearMonth is None i=%d", i)
return None
if count is None:
log.error("HandleMerchantStockInit::readExcel count is None i=%d", i)
return None
dealerUserInfo = self.mapDealerUserInfo.get(merchantCode)
if dealerUserInfo is None:
log.error("HandleMerchantStockInit::readExcel merchantcode is not exists merchantCode='%s'",
merchantCode)
return None
warehouseInfo = self.mapWarehouseRelation.get(warehouseCode)
if warehouseInfo is None:
log.error("HandleMerchantStockInit::readExcel warehosuecode is not exists warehouseCode='%s'",
warehouseCode)
return None
materialInfo = self.mapMaterialInfo.get(materialCode)
if materialInfo is None:
log.error("HandleMerchantStockInit::readExcel materialCode is not exists materialCode='%s'",
materialCode)
return None
if warehouseInfo.merchantCode != merchantCode:
log.error("HandleMerchantStockInit::readExcel merchantcode is not equal whsinfo merchantcode warehouseInfo.merchantCode='%s',merchantCode='%s'",
warehouseInfo.merchantCode,merchantCode)
return None
initObject = DTMerchantStockInit()
initObject.bmsCount = count
initObject.bmsMaterialCode = materialCode
initObject.bmsMaterialName = materialName
initObject.bmsMerchantCode = merchantCode
initObject.bmsMerchantName = merchantName
initObject.bmsWarehouseCode = warehouseCode
initObject.bmsWarehouseName = warehouseName
strYearMonth = self.communit.getDateStrY_M_DFromDateYmd(yearMonth)
initObject.bmsYearMonth = strYearMonth[0:7]
initObject.createdBy = "admin"
initObject.updatedBy = "admin"
initObject.createdDate = self.communit.getNowDate()
initObject.updatedDate = self.communit.getNowDate()
initObject.deletedFlag = "N"
listResult.append(initObject)
return listResult
def insertMerchantStockInit(self,listObject):
if listObject is None:
return
if len(listObject) == 0:
return
sql = "insert into bst_merchant_stock_init(`bms_merchant_code`,`bms_merchant_name`,`bms_warehouse_code`,`bms_warehouse_name`,`bms_material_code`,`bms_material_name`,`bms_year_month`,`bms_count`,`created_by`,`created_date`,`updated_by`,`updated_date`,`deleted_flag`) values"
sqlDb = []
for item in listObject:
strValue = "('%s','%s','%s','%s','%s','%s','%s','%d','%s',now(),'%s',now(),'%s')"%\
(item.bmsMerchantCode,item.bmsMerchantName,item.bmsWarehouseCode,item.bmsWarehouseName,item.bmsMaterialCode,item.bmsMaterialName,item.bmsYearMonth,item.bmsCount,item.createdBy,item.updatedBy,item.deletedFlag)
sqlDb.append(strValue)
sql += ','.join(sqlDb)
sql += " on duplicate key update `bms_merchant_code`=values(`bms_merchant_code`),`bms_merchant_name`=values(`bms_merchant_name`),`bms_warehouse_code`=values(`bms_warehouse_code`),`bms_warehouse_name`=values(`bms_warehouse_name`),`bms_material_code`=values(`bms_material_code`),`bms_material_name`=values(`bms_material_name`),`bms_year_month`=values(`bms_year_month`),`bms_count`=values(`bms_count`),`created_by`=values(`created_by`),`created_date`=values(`created_date`),`updated_by`=values(`updated_by`),`updated_date`=values(`updated_date`),`deleted_flag`=values(`deleted_flag`)"
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBaseSupply::insertDeviceCardManager sql query error, sql=%s", sql)
return False
connect.commit()
def doWork(self):
listObject = self.readExcel()
self.insertMerchantStockInit(listObject)
if __name__ == "__main__":
handleTask = HandleMerchantStockInit()
handleTask.setFileName("F:\\a\\商户库存V3.5 商户库存盘点初始表 (3).xlsx")
handleTask.doWork()
import openpyxl
from SupplyChain.CommonDef import log, DEVICEINFO
from SupplyChain.DataBase import DateBase
class HandleDeviceSn:
dataBase = None
fileName = ''
def __init__(self):
self.dataBase = DateBase()
self.fileName = ''
def setFileName(self,fileName):
self.fileName = fileName
def ReadExcelC(self):
workbook = openpyxl.load_workbook(self.fileName)
listIccid = []
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
iccid = sheet['A%d' % (i)].value
if iccid is None:
continue
listIccid.append(iccid)
workbook.close()
return listIccid
def WriteExcelC(self,mapIccid):
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
iccid = sheet['A%d' % (i)].value
if iccid is None:
continue
deviceCard = mapIccid.get(iccid)
if deviceCard is None:
continue
sheet['B%d' % (i)] = deviceCard.sn
sheet['C%d' % (i)] = deviceCard.devcetype
sheet['D%d' % (i)] = deviceCard.outtime
sheet['E%d' % (i)] = deviceCard.sendmerchant
sheet['F%d' % (i)] = deviceCard.activetime
sheet['G%d' % (i)] = deviceCard.deviceCode
sheet['H%d' % (i)] = deviceCard.deviceName
workbook.save(self.fileName)
workbook.close()
def DoWork1(self):
listIccid = self.ReadExcelC()
mapIccid = self.dataBase.mapDeviceCard(listIccid)
self.WriteExcelC(mapIccid)
log.info("Ok")
def DoWork(self):
listIccid = self.ReadExcelB()
mapIccid = self.dataBase.mapDeviceCard(listIccid)
self.WriteExcelB(mapIccid)
log.info("Ok")
# listDeviceInfo = self.ReadExcelA()
# listDeviceInfo = self.SendCard(listDeviceInfo)
# for item in listDeviceInfo:
# self.dataBase.updateDeviceFileCard(item.sn,item.cardid)
# self.dataBase.updateDeviceFileSnapshot(item.sn,item.cardid)
# log.info("Ok")
def ReadExcelB(self):
workbook = openpyxl.load_workbook(self.fileName)
listIccid = []
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
iccid = sheet['B%d'%(i)].value
if iccid is None:
continue
listIccid.append(iccid)
workbook.close()
return listIccid
def WriteExcelB(self,mapIccid):
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
iccid = sheet['B%d' % (i)].value
if iccid is None:
continue
deviceCard = mapIccid.get(iccid)
if deviceCard is None:
continue
sheet['E%d' % (i)] = deviceCard.sn
sheet['F%d' % (i)] = deviceCard.devcetype
sheet['G%d' % (i)] = deviceCard.outtime
sheet['H%d' % (i)] = deviceCard.sendmerchant
sheet['I%d' % (i)] = deviceCard.activetime
workbook.save(self.fileName)
workbook.close()
def ReadExcelA(self):
workbook = openpyxl.load_workbook(self.fileName)
listDeviceInfo = []
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['A%d'%(i)].value
iccid = sheet['B%d'%(i)].value
imsi = sheet['D%d'%(i)].value
deviceInfo = DEVICEINFO()
deviceInfo.sn = sn
deviceInfo.imsi = imsi
deviceInfo.iccid = iccid
listDeviceInfo.append(deviceInfo)
return listDeviceInfo
def SendCard(self,listDeviceInfo):
mapSnCard = {}
if listDeviceInfo is None:
return listDeviceInfo
self.dataBase.insertDeviceCardManager(listDeviceInfo);
listDeviceInfo = self.dataBase.filtIdDeviceCardManager(listDeviceInfo);
return listDeviceInfo
def StartWork(self):
listSn = self.ReadExcel();
mapSendOrderMerchant = self.dataBase.mapOrderSendMerchant(listSn)
mapStockOrderMerchant = self.dataBase.mapStockSendMerchant(listSn)
mapShopOrderMerchant = self.dataBase.mapShopSendMerchant(listSn)
self.WriteExcel(mapSendOrderMerchant,mapStockOrderMerchant,mapShopOrderMerchant)
log.info("Ok")
def ReadExcel(self):
listSn = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['C%d'%(i)].value
if sn is not None:
listSn.append(sn)
workbook.close()
return listSn
def WriteExcel(self,mapSendOrderMerchant,mapStockOrderMerchant,mapShopOrderMerchant):
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['C%d'%(i)].value
if sn is None:
continue
snInMerchant = mapStockOrderMerchant.get(sn)
if snInMerchant is not None:
sheet['S%d' % (i)] = snInMerchant.merchantCode
sheet['T%d' % (i)] = snInMerchant.merchantName
sheet['U%d' % (i)] = snInMerchant.shopMerchantCode
sheet['V%d' % (i)] = snInMerchant.shopMerchantName
continue
snInMerchant = mapShopOrderMerchant.get(sn)
if snInMerchant is not None:
sheet['S%d' % (i)] = snInMerchant.merchantCode
sheet['T%d' % (i)] = snInMerchant.merchantName
sheet['U%d' % (i)] = snInMerchant.shopMerchantCode
sheet['V%d' % (i)] = snInMerchant.shopMerchantName
continue
snInMerchant = mapSendOrderMerchant.get(sn)
if snInMerchant is not None:
sheet['S%d' % (i)] = snInMerchant.merchantCode
sheet['T%d' % (i)] = snInMerchant.merchantName
sheet['U%d' % (i)] = snInMerchant.shopMerchantCode
sheet['V%d' % (i)] = snInMerchant.shopMerchantName
continue
workbook.save(self.fileName)
workbook.close()
if __name__ == "__main__":
handleDeviceSn = HandleDeviceSn()
handleDeviceSn.setFileName("F:\\xiaochuan\\需查询设备名称和入库时间2021.11.12.xlsx")
handleDeviceSn.DoWork1()
#handleDeviceSn.DoWork()
#handleDeviceSn.StartWork()
import openpyxl
from SupplyChain import DbConnection
from SupplyChain.CommonDef import log
from SupplyChain.DataBase import DateBase
class ExcelData:
sendOrderCode = ''
sn = ''
materialCode = ''
materialName = ''
class MerchantStockOrder:
orderCombileCode = ''
orderCode = ''
merchantCode = ''
merchantName = ''
merchantType = ''
shopCode = ''
agentMerchantCode = ''
agentMerchantName = ''
arear = ''
materialCode = ''
materialName = ''
count = 0
receiveTime=''
scanType = ''
createdBy = ''
updatedBy = ''
class MerchantStockOrderDetail:
orderCode = ''
sn = ''
createdBy = ''
updatedBy = ''
class HandleExcelMerchantStock:
dataBase = None
fileName = ''
dbConnection = None
def __init__(self):
self.dataBase = DateBase()
self.fileName = ''
def setFileName(self, fileName):
self.fileName = fileName
def StartWork(self):
self.ReadExcel()
def getLastSendTime(self):
listSn = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['A%d' % (i)].value
if sn is None:
continue
listSn.append(sn)
mapSnSendTime = {}
mapSnSendTime = self.getLastSendTimeByListSn(listSn,mapSnSendTime)
for i in range(2, rows + 1):
sn = sheet['A%d' % (i)].value
sendTime = mapSnSendTime.get(sn)
if sendTime is None:
sendTime = ""
sheet['L%d' % (i)] = sendTime
workbook.save(self.fileName)
workbook.close()
log.info("OK")
def getLastSendTimeByListSn(self,listSn,mapSnSendTime):
if listSn is None:
return mapSnSendTime
if len(listSn) == 0:
return mapSnSendTime
sql = "select sn,created_date from order_info_detail where sn in(%s) order by id asc"%(','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBaseSupply::getLastSendTimeByListSn sql query error, sql=%s", sql)
return False
dbData = connect.fetchAllRows()
for item in dbData:
sn = item[0]
sendTime = item[1]
if sn is None:
continue
mapSnSendTime[sn] = sendTime
return mapSnSendTime
def generatorMerchantAgentMerchant(self):
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
objectSqls = []
orderSqls = []
for i in range(2, rows + 1):
shopName = sheet['B%d' % (i)].value
shopMerchantCode = sheet['C%d' % (i)].value
agentMerchantName = sheet['D%d' % (i)].value
agentMerchantCode = sheet['E%d' % (i)].value
if shopMerchantCode is None:
continue
if agentMerchantCode == '':
continue
objectSql = "update jst_shop_agent_relation set AGENT_MERCHANT_CODE='%s',AGENT_MERCHANT_NAME='%s' where shop_merchant_code='%s'" % (
agentMerchantCode, agentMerchantName,shopMerchantCode)
objectSqls.append(objectSql)
orderSql = "update jst_shop_order set AGENT_MERCHANT_CODE='%s',AGENT_MERCHANT_NAME='%s' where shop_merchant_code='%s'" % (
agentMerchantCode, agentMerchantName,shopMerchantCode)
orderSqls.append(orderSql)
sqlObject = ';\n'.join(objectSqls)
sqlOrder = ';\n'.join(orderSqls)
log.info("OK")
def generatorMerchantShopName(self):
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
objectSqls = []
orderSqls = []
for i in range(2, rows + 1):
merchantCode = sheet['A%d' % (i)].value
merchantName = sheet['B%d' % (i)].value
if merchantCode is None:
continue
if merchantCode == '':
continue
objectSql = "update jst_shop_agent_relation set shop_name='%s' where shop_merchant_code='%s'" % (merchantName,merchantCode)
objectSqls.append(objectSql)
orderSql = "update jst_shop_order set shop_name='%s' where shop_merchant_code='%s'" % (merchantName,merchantCode)
orderSqls.append(orderSql)
sqlObject = ';\n'.join(objectSqls)
sqlOrder = ';\n'.join(orderSqls)
log.info("OK")
def generatorMerchantStockObjectSql(self):
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
objectSqls = []
orderSqls= []
for i in range(2, rows + 1):
arear = sheet['A%d' % (i)].value
merchantName = sheet['B%d' % (i)].value
shopCode = sheet['C%d' % (i)].value
merchantCode = sheet['D%d' % (i)].value
merchantType = sheet['E%d' % (i)].value
agentMerchantName = sheet['F%d' % (i)].value
agentMerchantCode = sheet['G%d' % (i)].value
if shopCode is None:
shopCode = ''
if merchantCode is None:
continue
if merchantCode == '':
continue
objectSql = "update jst_shop_agent_relation set shop_name ='%s' where shop_merchant_code='%s'"%(merchantName,merchantCode)
# objectSql = "update bs_merchant_stock_object set bsso_arear='%s',bsso_merchant_name='%s',bsso_shop_code='%s',bsso_merchant_type='%s',bsso_agent_merchant_name='%s',bsso_agent_merchant_code='%s' where bsso_merchant_code='%s'"%(arear,merchantName,shopCode,merchantType,agentMerchantName,agentMerchantCode,merchantCode)
objectSqls.append(objectSql)
# orderSql = "update bs_merchant_stock_order set bsso_arear='%s',bsso_merchant_name='%s',bsso_shop_code='%s',bsso_merchant_type='%s',bsso_agent_merchant_name='%s',bsso_agent_merchant_code='%s' where bsso_merchant_code='%s'"%(arear,merchantName,shopCode,merchantType,agentMerchantName,agentMerchantCode,merchantCode)
orderSql = "update jst_shop_order set shop_name ='%s' where shop_merchant_code='%s'" % (merchantName, merchantCode)
orderSqls.append(orderSql)
sqlObject = ';\n'.join(objectSqls)
sqlOrder = ';\n'.join(orderSqls)
log.info("OK")
def getDbConnection(self):
if self.dbConnection is None:
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain)
return self.dbConnection
def ReadExcel(self):
listExcel = []
listMerchantStockDetail = []
mapMaterial2CombileCode = {}
mapMaterial2OrderInfo = {}
mapOrderCode2Count = {}
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
sendOrderCode = sheet['A%d' % (i)].value
sn = sheet['B%d' % (i)].value
materialCode = sheet['E%d' % (i)].value
materialName = sheet['F%d' % (i)].value
orderCode = ""
mmo = ("oc:%s,mc:%s")%(sendOrderCode,materialCode)
orderInfo = mapMaterial2OrderInfo.get(mmo)
if orderInfo is None:
orderCode = "MSOD" + sendOrderCode[2:]
combileCode = mapMaterial2CombileCode.get(materialCode)
if combileCode is None:
combileCode = "MSOC" + sendOrderCode[2:]
mapMaterial2CombileCode[materialCode] = combileCode
merchantStockOrder = MerchantStockOrder();
merchantStockOrder.orderCombileCode = combileCode
merchantStockOrder.orderCode = orderCode
merchantStockOrder.merchantCode = "104424"
merchantStockOrder.merchantName = "重庆施麦卡科技有限公司"
merchantStockOrder.merchantType = "服务商"
merchantStockOrder.shopCode = ""
merchantStockOrder.agentMerchantCode = "104424"
merchantStockOrder.agentMerchantName = "重庆施麦卡科技有限公司"
merchantStockOrder.arear = "重庆"
merchantStockOrder.materialCode = materialCode
merchantStockOrder.materialName = materialName
merchantStockOrder.count = 1
merchantStockOrder.receiveTime = "2021-04-17"
merchantStockOrder.createdBy = "19180009"
merchantStockOrder.updatedBy = "19180009"
merchantStockOrder.scanType = "Y"
mapMaterial2OrderInfo[mmo] = merchantStockOrder
else:
orderCode = merchantStockOrder.orderCode
merchantStockOrder.count = merchantStockOrder.count + 1
merchantOrderDetail = MerchantStockOrderDetail()
merchantOrderDetail.sn = sn
merchantOrderDetail.orderCode = orderCode
listMerchantStockDetail.append(merchantOrderDetail)
listMerchantStock = list(mapMaterial2OrderInfo.values())
self.inserMerchantStock(listMerchantStock)
self.insertMerchantStockDetail(listMerchantStockDetail)
log.info("OK")
def inserMerchantStock(self,listMerchantStock):
if listMerchantStock is None:
return
if len(listMerchantStock) == 0:
return
sql = "insert into bs_merchant_stock_order(`bsso_order_combile_code`,`bsso_order_code`,`bsso_merchant_code`,`bsso_merchant_name`,`bsso_merchant_type`," \
"`bsso_shop_code`,`bsso_agent_merchant_name`,`bsso_agent_merchant_code`,`bsso_arear`,`bsso_material_code`,`bsso_material_name`,`bsso_count`,`bsso_receive_time`," \
"`created_by`,`updated_by`,`bsso_scan_type`) values"
sqlDb = []
for item in listMerchantStock:
strValue = "('%s','%s','%s','%s','%s'," \
"'%s','%s','%s','%s','%s','%s',%d,'%s'," \
"'%s','%s','%s')" % \
(item.orderCombileCode, item.orderCode, item.merchantCode, item.merchantName, item.merchantType,
item.shopCode, item.agentMerchantName, item.agentMerchantCode, item.arear,item.materialCode,item.materialName,item.count,item.receiveTime,
item.createdBy,item.updatedBy,item.scanType)
sqlDb.append(strValue)
sql += ','.join(sqlDb)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBaseSupply::inserMerchantStock sql query error, sql=%s", sql)
return False
connect.commit()
return True
def insertMerchantStockDetail(self,listMerchantStockDetail):
if listMerchantStockDetail is None:
return
if len(listMerchantStockDetail) == 0:
return
sql = "insert into bs_merchant_stock_order_detail(`bsso_order_code`,`sn`,`created_by`,`updated_by`) values"
sqlDb = []
for item in listMerchantStockDetail:
strValue = "('%s','%s','%s','%s')"%(item.orderCode,item.sn,item.createdBy,item.updatedBy)
sqlDb.append(strValue)
sql += ','.join(sqlDb)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBaseSupply::insertMerchantStockDetail sql query error, sql=%s", sql)
return False
connect.commit()
return True
if __name__ == "__main__":
handleExcelMerchantStock = HandleExcelMerchantStock()
# handleExcelMerchantStock.setFileName("F:\\gujj\\修改名称-云车汇-0427.xlsx")
# handleExcelMerchantStock.StartWork()
# handleExcelMerchantStock.setFileName("F:\\gujj\\修改名称-云车汇-0427.xlsx");
# handleExcelMerchantStock.generatorMerchantStockObjectSql()
# handleExcelMerchantStock.generatorMerchantAgentMerchant()
# handleExcelMerchantStock.generatorMerchantStockObjectSql()
handleExcelMerchantStock.setFileName("F:\\gujj\\388454302223704064_盘点明细列表.xlsx");
handleExcelMerchantStock.getLastSendTime()
import openpyxl
import self as self
from openpyxl import Workbook
from SupplyChain import DbConnection
from SupplyChain.CommonDef import CComonUnit, log
class DataImsiSn:
no = None
imsi = ""
sn = ""
outtime=""
deviceNo=""
deviceName=""
group = ""
category = ""
activeTime = ""
packageFinishTime = ""
insureTime = ""
sendMerchantNo = ""
class FindSnByImis:
fileName = ''
dbConnection = None
communit = None
dbConnection31 = None
dbConnection216 = None
dbConnection170 = None
dbConnection131 = None
def __init__(self):
self.fileName = ''
self.dbConnection = None
self.communit = CComonUnit()
def getDbConnection(self):
if self.dbConnection is None:
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain)
return self.dbConnection
def getDbConnection31(self):
if self.dbConnection31 is None:
self.dbConnection31 = DbConnection.MySQL(DbConnection.g_dbconnect_dj31)
return self.dbConnection31
def getDbConnection216(self):
if self.dbConnection216 is None:
self.dbConnection216 = DbConnection.MySQL(DbConnection.g_dbconnect_dj216)
return self.dbConnection216
def getDbConnection170(self):
if self.dbConnection170 is None:
self.dbConnection170 = DbConnection.MySQL(DbConnection.g_dbconnect_dj170)
return self.dbConnection170
def getDbConnection131(self):
if self.dbConnection131 is None:
self.dbConnection131 = DbConnection.MySQL(DbConnection.g_dbconnect_dj131)
return self.dbConnection131
def setFileName(self,fileName):
self.fileName = fileName
def readData2(self):
listResult = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['D%d' % (i)].value
if sn is None:
continue
if sn == "":
continue
dataImsiSn = DataImsiSn()
dataImsiSn.sn = sn
dataImsiSn.no = i
listResult.append(dataImsiSn)
workbook.close()
return listResult
def readDataFK(self):
mapFK = {}
workbook = openpyxl.load_workbook("F:\\a\\风控分组分类,用户体系套餐到期.xlsx")
sheet = workbook.get_sheet_by_name("风控数据")
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['A%d'%(i)].value
group = sheet['B%d'%(i)].value
category = sheet['C%d' % (i)].value
activeTime = sheet['D%d' % (i)].value
if sn is None:
continue
if sn == "":
continue
dataImsiSn = DataImsiSn()
dataImsiSn.sn = sn
dataImsiSn.group = group
dataImsiSn.category = category
dataImsiSn.activeTime = activeTime
mapFK[sn] = dataImsiSn
workbook.close()
return mapFK
def readDataUser(self):
mapUser = {}
workbook = openpyxl.load_workbook("F:\\a\\风控分组分类,用户体系套餐到期.xlsx")
sheet = workbook.get_sheet_by_name("用户体系数据")
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['D%d' % (i)].value
packageFinishTime = sheet['F%d' % (i)].value
if sn is None:
continue
if sn == "":
continue
mapUser[sn] = packageFinishTime
workbook.close()
return mapUser
def readData(self):
listResult = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
imsi = sheet['B%d' % (i)].value
if imsi is None:
continue
dataImsiSn = DataImsiSn()
dataImsiSn.imsi = imsi
dataImsiSn.no = i
listResult.append(dataImsiSn)
return listResult
def readData4(self):
listResult = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
imsi = sheet['B%d' % (i)].value
sn = sheet['D%d' % (i)].value
if imsi is None:
continue
if sn is None:
sn = 'A'
dataImsiSn = DataImsiSn()
dataImsiSn.imsi = imsi
dataImsiSn.no = i
dataImsiSn.sn = sn
listResult.append(dataImsiSn)
return listResult
def findDataInMySqlVirturl(self,listImsi,mapImsi):
if listImsi is None:
return
if len(listImsi) == 0:
return
sql = "select imsi,send_merchant_no,updated_date from device_file_virtual where imsi in(%s)"%(','.join(["'%s'" % x for x in listImsi]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapDeviceCard sql query error, sql=%s", sql)
return ""
dbData = connect.fetchAllRows()
for item in dbData:
imsi = item[0]
sendMerchantNo = item[1]
updateDate = item[2]
dataImsiSn = DataImsiSn()
dataImsiSn.imsi = imsi
dataImsiSn.outtime = updateDate
dataImsiSn.sendMerchantNo = sendMerchantNo
mapImsi[imsi] = dataImsiSn
def findDataInMySql(self,listImsi,mapImsi):
if listImsi is None:
return
if len(listImsi) == 0:
return
sql = "select df.sn,df.device_code,df.out_storage_time,dcm.imsi,dc.device_name,df.send_merchant_no from device_card_manager as dcm " \
"left join device_file as df on(df.card_id=dcm.id) " \
"left join device_code as dc on(dc.device_code = df.device_code) " \
"where df.deleted_flag = 'N' and dcm.imsi in(%s)"%(','.join(["'%s'" % x for x in listImsi]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapDeviceCard sql query error, sql=%s", sql)
return ""
dbData = connect.fetchAllRows()
for item in dbData:
sn = item[0]
deviceCode = item[1]
outStorageTime = item[2]
imsi = item[3]
deviceName = item[4]
sendMerchantNo = item[5]
if sn is None:
sn = ""
if deviceCode is None:
deviceCode = ""
if outStorageTime is None:
outStorageTime = ""
if imsi is None:
continue
if deviceName is None:
deviceName = ""
if sendMerchantNo is None:
sendMerchantNo = ""
dataImsiSn = DataImsiSn()
dataImsiSn.sn = sn
dataImsiSn.imsi = imsi
dataImsiSn.deviceNo = deviceCode
dataImsiSn.outtime = outStorageTime
dataImsiSn.deviceName = deviceName
dataImsiSn.sendMerchantNo = sendMerchantNo
mapImsi[imsi] = dataImsiSn
def findListResult(self,listResult):
if listResult is None:
return
if len(listResult) == 0:
return
listImsi = []
mapImsi = {}
iSize = 0
for item in listResult:
listImsi.append(item.imsi)
if len(listImsi) == 10000:
self.findDataInMySql(listImsi,mapImsi)
iSize = iSize + len(listImsi)
listImsi.clear()
log.info("findListResult iSize=%d",iSize)
if len(listImsi) > 0:
self.findDataInMySql(listImsi,mapImsi)
iSize = iSize + len(listImsi)
listImsi.clear()
log.info("findListResult iSize=%d", iSize)
listImsi.clear()
for item in listResult:
if item.sn == 'A':
listImsi.append(item.imsi)
self.findDataInMySqlVirturl(listImsi,mapImsi)
for item in listResult:
dataImsiSn = mapImsi.get(item.imsi)
if dataImsiSn is None:
continue
item.sn = dataImsiSn.sn
item.deviceNo = dataImsiSn.deviceNo
item.outtime = dataImsiSn.outtime
item.deviceName = dataImsiSn.deviceName
item.sendMerchantNo = dataImsiSn.sendMerchantNo
def writeExcel4(self, listExcelData):
if listExcelData is None:
return
if len(listExcelData) == 0:
return
workbook = Workbook()
sheet = workbook.active
i = 2
for excelData in listExcelData:
# sheet['F%d' % (excelData.no)] = excelData.sn
# sheet['G%d' % (excelData.no)] = excelData.deviceName
sheet['J%d' % (excelData.no)] = excelData.outtime
sheet['k%d' % (excelData.no)] = excelData.sendMerchantNo
i = i + 1
workbook.save(self.fileName)
workbook.close()
def writeExcel(self,listExcelData):
if listExcelData is None:
return
if len(listExcelData) == 0:
return
workbook = Workbook()
sheet = workbook.active
i = 2
for excelData in listExcelData:
sheet['F%d' % (excelData.no)] = excelData.sn
sheet['G%d' % (excelData.no)] = excelData.deviceName
sheet['H%d' % (excelData.no)] = excelData.outtime
i = i + 1
workbook.save(self.fileName)
workbook.close()
def writeExcel2(self,listExcelData):
if listExcelData is None:
return
if len(listExcelData) == 0:
return
workbook = Workbook()
sheet = workbook.active
for excelData in listExcelData:
sheet['I%d' % (excelData.no)] = excelData.group
sheet['J%d' % (excelData.no)] = excelData.category
sheet['K%d' % (excelData.no)] = excelData.activeTime
sheet['N%d' % (excelData.no)] = excelData.packageFinishTime
workbook.save(self.fileName)
workbook.close()
def writeExcel3(self,listExcelData):
if listExcelData is None:
return
if len(listExcelData) == 0:
return
workbook = Workbook()
sheet = workbook.active
for excelData in listExcelData:
sheet['P%d' % (excelData.no)] = excelData.insureTime
workbook.save(self.fileName)
workbook.close()
def doWork4(self):
listExcelData = self.readData4()
self.findListResult(listExcelData)
self.writeExcel4(listExcelData)
log.info("doWork ok")
def doWork(self):
listExcelData = self.readData()
self.findListResult(listExcelData)
self.writeExcel(listExcelData)
log.info("doWork ok")
def doWork2(self):
listExcelData = self.readData2()
mapFk = self.readDataFK()
mapUser = self.readDataUser()
for item in listExcelData:
fkData = mapFk.get(item.sn)
if fkData is not None:
item.group = fkData.group
item.category = fkData.category
item.activeTime = fkData.activeTime
userData = mapUser.get(item.sn)
if userData is not None:
item.packageFinishTime = userData
self.writeExcel2(listExcelData)
def readData_31(self,listSn,mapSn2Time):
sql = "select end_date,sub_device_sn from dj_insure_order where insurance_status IN ( 1, 7, 11 ) and sub_device_sn in(%s) union all " \
"select end_date,sub_device_sn from dj_insure_equity where equity_status IN ( 1, 11, 7 ) and sub_device_sn in(%s)"%(','.join(["'%s'" % x for x in listSn]),','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection31()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapDeviceCard sql query error, sql=%s", sql)
return
dbData = connect.fetchAllRows()
for item in dbData:
insureTime = item[0]
sn = item[1]
if sn is None:
continue
mapSn2Time[sn] = insureTime
return
def readData_216(self,listSn,mapSn2Time):
sql = "select end_date,sub_device_sn from dj_insure_order where insurance_status IN ( 1, 7, 11 ) and sub_device_sn in(%s) union all " \
"select end_date,sub_device_sn from dj_insure_equity where equity_status IN ( 1, 11, 7 ) and sub_device_sn in(%s)"%(','.join(["'%s'" % x for x in listSn]),','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection216()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapDeviceCard sql query error, sql=%s", sql)
return
dbData = connect.fetchAllRows()
for item in dbData:
insureTime = item[0]
sn = item[1]
if sn is None:
continue
mapSn2Time[sn] = insureTime
return
def readData_170(self,listSn,mapSn2Time):
sql = "select expiration_date,sn from service_equity_order where order_status in(2,5,7,8,10,11) and sn in(%s) " %(','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection170()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapDeviceCard sql query error, sql=%s", sql)
return
dbData = connect.fetchAllRows()
for item in dbData:
insureTime = item[0]
sn = item[1]
if sn is None:
continue
mapSn2Time[sn] = insureTime
return
def readData_131(self,listSn,mapSn2Time):
sql = "select expiration_date,sn from service_equity_order where order_status in(2,5,7,8,10,11) and sn in(%s) " %(','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection131()
result = connect.query(sql)
if result == False:
log.error("DateBase::mapDeviceCard sql query error, sql=%s", sql)
return
dbData = connect.fetchAllRows()
for item in dbData:
insureTime = item[0]
sn = item[1]
if sn is None:
continue
mapSn2Time[sn] = insureTime
return
def readDataDj(self,listExcelData):
mapSn2Time = {}
listSn = []
for excelData in listExcelData:
sn = excelData.sn
if sn is None:
continue
listSn.append(sn)
if len(listSn) == 10000:
self.readData_31(listSn,mapSn2Time)
self.readData_216(listSn, mapSn2Time)
self.readData_170(listSn,mapSn2Time)
self.readData_131(listSn,mapSn2Time)
listSn.clear()
if len(listSn) > 0:
self.readData_31(listSn, mapSn2Time)
self.readData_216(listSn, mapSn2Time)
self.readData_170(listSn, mapSn2Time)
self.readData_131(listSn, mapSn2Time)
return mapSn2Time
def doWork3(self):
listExcelData = self.readData2()
mapSn2Time = self.readDataDj(listExcelData)
insureTime = None
for item in listExcelData:
insureTime = mapSn2Time.get(item.sn)
if insureTime is None:
continue
item.insureTime = insureTime
self.writeExcel3(listExcelData)
if __name__ == "__main__":
workInstance = FindSnByImis()
workInstance.setFileName("F:\\a\\6月套餐切换套餐,匹配需要字段.xlsx")
# workInstance.doWork4()
# workInstance.doWork2()
workInstance.doWork3()
\ No newline at end of file \ No newline at end of file
import openpyxl
from SupplyChain import DbConnection
from SupplyChain.CommonDef import CComonUnit, log
class DVSnInitRecord:
sn = ''
iccid = ''
imei = ''
remark = ''
class HandleDeviceInitRecordImport:
fileName = ''
dbConnection = None
communit = None
def __init__(self):
self.fileName = ''
self.dbConnection = None
self.communit = CComonUnit()
def getDbConnection(self):
if self.dbConnection is None:
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain)
return self.dbConnection
def setFileName(self,fileName):
self.fileName = fileName
def readData(self):
listResult = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['A%d' % (i)].value
iccid = sheet['B%d' % (i)].value
imei = sheet['C%d' % (i)].value
remark = sheet['D%d' % (i)].value
snRecord = DVSnInitRecord()
if sn is None:
continue
if iccid is None:
iccid = ''
if imei is None:
imei = ''
if remark is None:
remark = ''
snRecord.sn = sn
snRecord.iccid = iccid
snRecord.imei = imei
snRecord.remark = remark
listResult.append(snRecord)
return listResult
def insertDb(self,listData):
if listData is None:
return
if len(listData)== 0:
return
seekTag = self.communit.getNowDateYMDHMSD()
sql = "insert into device_sn_init_record(`DV_SN`,`DV_ICCID`,`DV_IMEI`,`DV_REMARK`,`SEED_TAG`,`created_by`,`updated_by`) values"
sqlDb = []
for item in listData:
strValue = "('%s','%s','%s','%s','%s','admin','admin')"%\
(item.sn,item.iccid,item.imei,item.remark,seekTag)
sqlDb.append(strValue)
sql += ','.join(sqlDb)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("DateBaseSupply::insertDeviceCardManager sql query error, sql=%s", sql)
return False
connect.commit()
def handleWork(self):
log.info("start")
listData = self.readData()
self.insertDb(listData)
log.info("ok")
if __name__ == "__main__":
task = HandleDeviceInitRecordImport()
task.setFileName("f:\\a\\device_sn_init_record.xlsx")
task.handleWork()
from SupplyChain import DbConnection
from SupplyChain.CommonDef import CComonUnit, log
class MATERIALINFO:
materialCode = ''
materialName = ''
class ORDERINFO:
orderCode = ''
attribCode = ''
materialCode = ''
materialName = ''
class MERCAHNT:
merchantCode = ''
merchantName = ''
class HandleTask:
dbConnection = None
communit = None
mapMaterial = None
mapAttrib = None
def __init__(self):
self.dbConnection = None
self.mapMaterial = {}
self.mapAttrib = {}
self.communit = CComonUnit()
def getDbConnection(self):
if self.dbConnection is None:
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain)
return self.dbConnection
def getOrderInfo(self):
listOrderInfo = []
sql = "select order_code,attrib_code from order_info where deleted_flag='N' and (material_code='' OR material_code IS NULL OR attrib_code='' OR attrib_code IS NULL)"
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getOrderInfo sql query error, sql=%s", sql)
return None
dbData = connect.fetchAllRows()
for item in dbData:
orderCode = item[0]
attribCode = item[1]
if orderCode is None:
continue
orderInfo = ORDERINFO()
orderInfo.orderCode = orderCode
orderInfo.attribCode = attribCode
listOrderInfo.append(orderInfo)
return listOrderInfo
def getAttribCodeByMaterialCode(self,materialCode):
attribCode = self.mapAttrib.get(materialCode)
if attribCode is not None:
return attribCode
sql= "select attrib_code from attrib_mana where attrib_code='%s'"%(materialCode)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getMapMaterialCode2attribCode sql query error, sql=%s", sql)
return None
dbData = connect.fetchAllRows()
for item in dbData:
attribCode = item[0]
if attribCode is None:
return None
self.mapAttrib[attribCode] = attribCode
return attribCode
def getMaterialNameByMaterialCode(self,materialCode):
materialName = self.mapMaterial.get(materialCode)
if materialName is not None:
return materialName
sql = "select material_name from am_material_info where material_code='%s'"%(materialCode)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getMaterialNameByMaterialCode sql query error, sql=%s", sql)
return None
dbData = connect.fetchAllRows()
for item in dbData:
materialName = item[0]
if materialName is None:
materialName = ''
self.mapMaterial[materialCode] = materialName
return materialName
def getMapOrderCode2MaterialInfo(self,listOrderCode):
mapOrderCode2Material={}
if listOrderCode is None:
return
if len(listOrderCode) == 0:
return
sql = "select bpd.material_code,bpd.material_name,bmov.dispatch_order_code from bs_merchant_order_vehicle as bmov " \
"left join bs_merchant_order_detail as bmod on(bmov.merchant_order=bmod.merchant_order_number) " \
"left join bs_product_detail as bpd on(bpd.product_code = bmod.product_code AND bpd.type IN(0,7)) " \
"where bmov.dispatch_order_code in (%s)"%(','.join(["'%s'" % x for x in listOrderCode]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getMapOrderCode2MaterialInfo sql query error, sql=%s", sql)
return None
dbData = connect.fetchAllRows()
for item in dbData:
materialCode = item[0]
materialName = item[1]
orderCode = item[2]
if materialCode is None or materialCode == '':
continue
if materialName is None or materialName == '':
materialName = self.getMaterialNameByMaterialCode(materialCode)
material = MATERIALINFO()
material.materialCode = materialCode
material.materialName = materialName
mapOrderCode2Material[orderCode] = material
return mapOrderCode2Material
def updateOrderInfoDB(self,orderInfo):
sql = "update order_info set attrib_code='%s',material_code='%s',material_name='%s' where order_code='%s'"%(orderInfo.attribCode,orderInfo.materialCode,orderInfo.materialName,orderInfo.orderCode)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("updateOrderInfoDB sql query error, sql=%s", sql)
return None
connect.commit()
def getMerchantFromUserInfo(self):
listMerchant = []
sql = "select merchant_code,merchant_name from bs_dealer_user_info where deleted_flag='N'"
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getMapOrderCode2MaterialInfo sql query error, sql=%s", sql)
return None
dbData = connect.fetchAllRows()
for item in dbData:
merchantCode = item[0]
merchantName = item[1]
merchant = MERCAHNT()
merchant.merchantCode = merchantCode
merchant.merchantName = merchantName
listMerchant.append(merchant)
return listMerchant
def updateMerchantBelong(self,listMerchant):
sql = "insert into bs_merchant_belong(merchant_code,merchant_name,wh_merchant_code,wh_merchant_name) values"
sqlDb = []
for item in listMerchant:
strValue = "('%s','%s','%s','%s')" % \
(item.merchantCode, item.merchantName,item.merchantCode, item.merchantName)
sqlDb.append(strValue)
sql += ','.join(sqlDb)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("updateMerchantBelong sql query error, sql=%s", sql)
return None
connect.commit()
def updateOrderInfo(self,listOrderInfo):
for item in listOrderInfo:
if item.orderCode is None or item.orderCode == '':
continue
if item.attribCode is None:
item.attribCode = ''
if item.materialName is None:
item.materialName = ''
if item.materialCode is None:
item.materialCode = ''
self.updateOrderInfoDB(item)
def getListOrderCodeFromOrderInfo(self,listOrderInfo):
listOrderCode = []
for item in listOrderInfo:
listOrderCode.append(item.orderCode)
return listOrderCode
def getMapOrderCode2Material(self,listOrderInfo):
listOrderCode = self.getListOrderCodeFromOrderInfo(listOrderInfo)
return self.getMapOrderCode2MaterialInfo(listOrderCode)
def filtMaterialCode2OrderInfo(self):
log.info("filtMaterialCode2OrderInfo start")
listOrderInfo = self.getOrderInfo()
if listOrderInfo is None:
return
mapOrderCode2Material = self.getMapOrderCode2Material(listOrderInfo)
for item in listOrderInfo:
if item.orderCode is None or item.orderCode == '':
continue
if item.attribCode is not None:
materialName = self.getMaterialNameByMaterialCode(item.attribCode)
if materialName is not None and materialName != '':
item.materialName = materialName
item.materialCode = item.attribCode
continue
material = mapOrderCode2Material.get(item.orderCode)
if material is None:
continue
attribCode = self.getAttribCodeByMaterialCode(material.materialCode)
if attribCode is not None:
item.attribCode = material.materialCode
else:
item.attribCode = ''
item.materialCode = material.materialCode
item.materialName = material.materialName
self.updateOrderInfo(listOrderInfo)
log.info("filtMaterialCode2OrderInfo end")
def filtMerchantBelong(self):
listMerchant = self.getMerchantFromUserInfo()
self.updateMerchantBelong(listMerchant)
if __name__ == "__main__":
taskInstance = HandleTask()
taskInstance.filtMaterialCode2OrderInfo()
taskInstance.filtMerchantBelong()
import openpyxl
from SupplyChain import DbConnection
from SupplyChain.CommonDef import CComonUnit, log
class GPSPREIMPORT:
orderCode = ''
simcardNo = ''
iccid = ''
imsi = ''
imei = ''
sn = ''
batch = ''
vcode = ''
createdBy = ''
createdDate = ''
updatedBy = ''
updatedDate = ''
class ORDERINFO:
orderCode = ''
deviceId = 0
deviceName = ''
packageOne = ''
packageTwo = ''
operatorMerchantNo = ''
warehouseId = 0
sendMerchantNo = ''
sendMerchantName = ''
attribCode = ''
class DEVICECARD:
id = 0
imsi = ''
class DEVICEINFO:
iccid = ''
imei = ''
batch = ''
status = 'OUT'
warehouseId = 0
warehouseIdUp = 0
orderCode = ''
createdBy = ''
createdDate = ''
updatedBy = ''
updatedDate = ''
deletedFlag = 'N'
sn = ''
vcode = ''
imsi = ''
simCardNo = ''
sendTime = ''
attribCode = ''
class DEVICEFILE:
sn = ''
deviceCode = 0
orderCode = ''
verifCode = ''
batchNo = ''
packageId = 0
androidPackageId = 0
operatorMerchantNo = ''
sendMerchantNo = ''
sendMerchantName = ''
inStorageTime = ''
outStorageTime = ''
outStorageType = ''
terminalDiscode = ''
externalFlag = ''
manufacturerCode = ''
firmwareId = 0
cardId = 0
createdBy = ''
createdDate = ''
updatedBy = ''
updatedDate = ''
deletedFlag = 'N'
remark = ''
imei = ''
sendTime = ''
class DEVICEFILESNAPSHOT:
sn = ''
packageStatu = 'UA'
packageId = 0
androidPackageId = 0
cardId = 0
cardTime = 0
createdBy = ''
createdDate = ''
updatedBy = ''
updatedDate = ''
deletedFlag = 'N'
class HandleSyncDeviceFile:
fileName = ''
dbConnection = None
communit = None
def __init__(self):
self.fileName = ''
self.dbConnection = None
self.communit = CComonUnit()
def getDbConnection(self):
if self.dbConnection is None:
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain)
return self.dbConnection
def setFileName(self,fileName):
self.fileName = fileName
def readData(self):
listSn = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
sn = sheet['A%d' % (i)].value
listSn.append(sn)
return listSn
def getDeviceCard(self,imsi):
deviceCard = DEVICECARD()
sql = "select id,imsi from device_card_manager where imsi='%s'"%(imsi)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getDeviceCard sql query error, sql=%s", sql)
return None
dbData = connect.fetchAllRows()
for item in dbData:
deviceCard.id = item[0]
deviceCard.imsi = item[1]
return deviceCard
def getOrderInfo(self,orderCode):
orderInfo = ORDERINFO()
sql = "select order_code,device_id,device_name,package_one,package_two,operator_merchant_no,warehouse_id,send_merchant_no,send_merchant_name,attrib_code from order_info where order_code='%s'"%(orderCode)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getOrderInfo sql query error, sql=%s", sql)
return None
dbData = connect.fetchAllRows()
for item in dbData:
orderInfo.orderCode = item[0]
orderInfo.deviceId = item[1]
orderInfo.deviceName = item[2]
orderInfo.packageOne = item[3]
orderInfo.packageTwo = item[4]
orderInfo.operatorMerchantNo = item[5]
orderInfo.warehouseId = item[6]
orderInfo.sendMerchantNo = item[7]
orderInfo.sendMerchantName = item[8]
orderInfo.attribCode = item[9]
if orderInfo.operatorMerchantNo is None:
orderInfo.operatorMerchantNo = ''
if orderInfo.sendMerchantNo is None:
orderInfo.sendMerchantNo = ''
return orderInfo
def getGpsPreimport(self,sn):
gpsPreImport = GPSPREIMPORT()
sql = "select order_code,SIM_CARD_NO,iccid,imsi,imei,sn,batch,vcode,created_by,created_date,updated_by,updated_date from device_info_gps_preimport where sn='%s'"%(sn)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getGpsPreimport sql query error, sql=%s", sql)
return None
dbData = connect.fetchAllRows()
for item in dbData:
gpsPreImport.orderCode = item[0]
gpsPreImport.simcardNo = item[1]
gpsPreImport.iccid = item[2]
gpsPreImport.imsi = item[3]
gpsPreImport.imei = item[4]
gpsPreImport.sn = item[5]
gpsPreImport.batch = item[6]
gpsPreImport.vcode = item[7]
gpsPreImport.createdBy = item[8]
gpsPreImport.createdDate = item[9]
gpsPreImport.updatedBy = item[10]
gpsPreImport.updatedDate = item[11]
return gpsPreImport
def getDeviceFileSnapshot(self,gpsPreImport,orderInfo,deviceCard):
deviceFileSnapshot = DEVICEFILESNAPSHOT()
deviceFileSnapshot.sn = gpsPreImport.sn
deviceFileSnapshot.packageId = int(orderInfo.packageOne)
deviceFileSnapshot.androidPackageId = int(orderInfo.packageTwo)
deviceFileSnapshot.packageStatu = 'UA'
deviceFileSnapshot.cardId = deviceCard.id
deviceFileSnapshot.cardTime = gpsPreImport.createdDate
deviceFileSnapshot.createdDate = gpsPreImport.createdDate
deviceFileSnapshot.createdBy = gpsPreImport.createdBy
deviceFileSnapshot.updatedDate = gpsPreImport.updatedDate
deviceFileSnapshot.updatedBy = gpsPreImport.updatedBy
deviceFileSnapshot.deletedFlag = 'N'
return deviceFileSnapshot
def getDeviceFile(self,gpsPreImport,orderInfo,deviceCard):
deviceFile = DEVICEFILE()
deviceFile.sn = gpsPreImport.sn
deviceFile.deviceCode = orderInfo.deviceId
deviceFile.orderCode = orderInfo.orderCode
deviceFile.verifCode = gpsPreImport.vcode
deviceFile.batchNo = gpsPreImport.batch
deviceFile.packageId = int(orderInfo.packageOne)
deviceFile.androidPackageId = int(orderInfo.packageTwo)
deviceFile.operatorMerchantNo = orderInfo.operatorMerchantNo
deviceFile.sendMerchantNo = orderInfo.sendMerchantNo
deviceFile.sendMerchantName = orderInfo.sendMerchantName
deviceFile.inStorageTime = gpsPreImport.createdDate
deviceFile.outStorageTime = gpsPreImport.createdDate
deviceFile.outStorageType = 'SC'
deviceFile.terminalDiscode = ''
deviceFile.externalFlag = 'IN'
deviceFile.manufacturerCode = ''
deviceFile.firmwareId = 0
deviceFile.cardId = deviceCard.id
deviceFile.createdBy = gpsPreImport.createdBy
deviceFile.createdDate = gpsPreImport.createdDate
deviceFile.updatedBy = gpsPreImport.updatedBy
deviceFile.updatedDate = gpsPreImport.updatedDate
deviceFile.deletedFlag = 'N'
deviceFile.remark = ''
deviceFile.imei = gpsPreImport.sn
deviceFile.sendTime = gpsPreImport.createdDate
return deviceFile
def getDeviceInfo(self,gpsPreImport,orderInfo,deviceCard):
deviceInfo = DEVICEINFO()
deviceInfo.sn = gpsPreImport.sn
deviceInfo.imsi = gpsPreImport.imsi
deviceInfo.imei = gpsPreImport.sn
deviceInfo.vcode = gpsPreImport.vcode
deviceInfo.orderCode = orderInfo.orderCode
deviceInfo.warehouseId = orderInfo.warehouseId
deviceInfo.warehouseIdUp = orderInfo.warehouseId
deviceInfo.updatedDate = gpsPreImport.updatedDate
deviceInfo.updatedBy = gpsPreImport.updatedBy
deviceInfo.createdBy = gpsPreImport.createdBy
deviceInfo.createdDate = gpsPreImport.createdDate
deviceInfo.batch = gpsPreImport.batch
deviceInfo.iccid = gpsPreImport.iccid
deviceInfo.deletedFlag = 'N'
deviceInfo.sendTime = gpsPreImport.updatedDate
deviceInfo.status = 'OUT'
deviceInfo.attribCode = orderInfo.attribCode
deviceInfo.simCardNo = gpsPreImport.simcardNo
return deviceInfo
def updateDeviceInfo(self, deviceInfo):
if deviceInfo is None:
return
if deviceInfo.sn is None:
return
if len(deviceInfo.sn) < 3:
return
sql = "update device_info set iccid='%s',imei='%s',attrib_code='%s',batch='%s',`status`='%s',warehouse_id=%d,warehouse_id_up=%d,order_code='%s',created_by='%s',created_date='%s',updated_by='%s',updated_date='%s',deleted_flag='%s',vcode='%s',imsi='%s',sim_card_no='%s' where `sn`='%s'" \
% (deviceInfo.iccid, deviceInfo.imei, deviceInfo.attribCode,deviceInfo.batch,deviceInfo.status,deviceInfo.warehouseId,deviceInfo.warehouseIdUp,deviceInfo.orderCode,deviceInfo.createdBy,deviceInfo.createdDate,deviceInfo.updatedBy,deviceInfo.updatedDate,deviceInfo.deletedFlag,deviceInfo.vcode,deviceInfo.imsi,deviceInfo.simCardNo,deviceInfo.sn)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("updateDeviceInfo sql query error, sql=%s", sql)
return
connect.commit()
def updateDeviceFile(self,deviceFile):
if deviceFile is None:
return
if deviceFile.sn is None:
return
if len(deviceFile.sn) < 3:
return
sql = "update device_file set device_code=%d,order_code='%s',verif_code='%s',BATCH_NO='%s',PACKAGE_ID=%d,ANDROID_PACKAGE_ID=%d,OPERATOR_MERCHANT_NO='%s',SEND_MERCHANT_NO='%s'," \
"IN_STORAGE_TIME='%s',OUT_STORAGE_TIME='%s',OUT_STORAGE_TYPE='%s',EXTERNAL_FLAG='%s',CARD_ID=%d,CREATED_BY='%s',CREATED_DATE='%s',UPDATED_BY='%s',UPDATED_DATE='%s',DELETED_FLAG='%s',IMEI='%s',send_time='%s' where sn='%s'"\
%(deviceFile.deviceCode,deviceFile.orderCode,deviceFile.verifCode,deviceFile.batchNo,deviceFile.packageId,deviceFile.androidPackageId,deviceFile.operatorMerchantNo,deviceFile.sendMerchantNo,
deviceFile.inStorageTime,deviceFile.outStorageTime,deviceFile.outStorageType,deviceFile.externalFlag,deviceFile.cardId,deviceFile.createdBy,deviceFile.createdDate,deviceFile.updatedBy,deviceFile.updatedDate,deviceFile.deletedFlag,deviceFile.imei,deviceFile.sendTime,deviceFile.sn)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("updateDeviceFile sql query error, sql=%s", sql)
return
connect.commit()
def updateDeviceFileSnapshot(self,deviceFileSnapshot):
if deviceFileSnapshot is None:
return
if deviceFileSnapshot.sn is None:
return
if len(deviceFileSnapshot.sn) < 3:
return
sql = "update device_file_snapshot set PACKAGE_STATU='%s',PACKAGE_ID=%d,ANDROID_PACKAGE_ID=%d,CARD_ID=%d,CARD_TIME='%s',CREATED_BY='%s',CREATED_DATE='%s',UPDATED_BY='%s',UPDATED_DATE='%s',DELETED_FLAG='%s' where sn='%s'"%\
(deviceFileSnapshot.packageStatu,deviceFileSnapshot.packageId,deviceFileSnapshot.androidPackageId,deviceFileSnapshot.cardId,deviceFileSnapshot.cardTime,deviceFileSnapshot.createdBy,deviceFileSnapshot.createdDate,deviceFileSnapshot.updatedBy,deviceFileSnapshot.updatedDate,deviceFileSnapshot.deletedFlag,deviceFileSnapshot.sn)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("updateDeviceFileSnapshot sql query error, sql=%s", sql)
return
connect.commit()
def doWork(self):
listSn = self.readData()
for sn in listSn:
log.info("sn=%s",sn)
gpsPreImport = self.getGpsPreimport(sn)
if gpsPreImport.sn is None or len(gpsPreImport.sn) <= 3:
continue
orderInfo = self.getOrderInfo(gpsPreImport.orderCode)
if orderInfo is None:
continue
deviceCard = self.getDeviceCard(gpsPreImport.imsi)
if deviceCard is None:
continue
deviceInfo = self.getDeviceInfo(gpsPreImport,orderInfo,deviceCard)
deviceFile = self.getDeviceFile(gpsPreImport, orderInfo, deviceCard)
deviceFileSnapshot = self.getDeviceFileSnapshot(gpsPreImport, orderInfo, deviceCard)
self.updateDeviceInfo(deviceInfo)
self.updateDeviceFile(deviceFile)
self.updateDeviceFileSnapshot(deviceFileSnapshot)
log.info("OK")
if __name__ == "__main__":
workInstance = HandleSyncDeviceFile()
workInstance.setFileName("F:\\sn.xlsx")
workInstance.doWork()
import openpyxl
from SupplyChain import DbConnection
from SupplyChain.CommonDef import CComonUnit, log
class UPDATA:
dispatchOrderCode = ''
merchantOrderCode = ''
sendTime = ''
class HandleUpdSendTime:
fileName = ''
dbConnection = None
communit = None
def __init__(self):
self.fileName = ''
self.dbConnection = None
self.communit = CComonUnit()
def getDbConnection(self):
if self.dbConnection is None:
self.dbConnection = DbConnection.MySQL(DbConnection.g_dbconnect_supplychain)
return self.dbConnection
def setFileName(self,fileName):
self.fileName = fileName
def readData(self):
ccomonunit = CComonUnit()
listUpdata = []
workbook = openpyxl.load_workbook(self.fileName)
sheet = workbook.active
rows = sheet.max_row
for i in range(2, rows + 1):
upData = UPDATA()
upData.dispatchOrderCode = sheet['E%d' % (i)].value
upData.merchantOrderCode = sheet['F%d' % (i)].value
upData.sendTime = ccomonunit.getDateStrY_M_DFromDateYmd(sheet['C%d' % (i)].value)
listUpdata.append(upData)
return listUpdata
def updateOrderDetail(self,updata):
#sql = "update order_info_detail set created_date='%s',updated_date='%s',send_time='%s' where order_code='%s'"%\
# (updata.sendTime,updata.sendTime,updata.sendTime,updata.dispatchOrderCode)
sql = "update order_info_detail set send_time=REPLACE(send_time,SUBSTRING(send_time,1,10),'%s') where order_code='%s'" % \
(updata.sendTime, updata.dispatchOrderCode)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("updateOrderDetail sql query error, sql=%s", sql)
return
connect.commit()
def updateLogistics(self,updata):
#sql = "update bs_logistics set send_time='%s' where service_code='%s' and `type` in(4,5)"%\
# (updata.sendTime,updata.dispatchOrderCode)
sql = "update bs_logistics set send_time=REPLACE(send_time,SUBSTRING(send_time,1,10),'%s') where service_code='%s' and `type` in(4,5)" % \
(updata.sendTime, updata.dispatchOrderCode)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("updateLogistics sql query error, sql=%s", sql)
return
connect.commit()
def getlistSnFromOrderDetail(self,orderCode):
listSn = []
sql = "select sn from order_info_detail where order_code='%s' and deleted_flag='N'"%(orderCode)
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("getlistSnFromOrderDetail sql query error, sql=%s", sql)
return False
dbData = connect.fetchAllRows()
for item in dbData:
sn = item[0]
listSn.append(sn)
return listSn
def updateDeviceFile(self,listSn,updata):
sql = "update device_file set in_storage_time=REPLACE(in_storage_time,SUBSTRING(in_storage_time,1,10),'%s'),out_storage_time=REPLACE(out_storage_time,SUBSTRING(out_storage_time,1,10),'%s') where sn in(%s)"%(updata.sendTime,updata.sendTime,','.join(["'%s'" % x for x in listSn]))
connect = self.getDbConnection()
result = connect.query(sql)
if result == False:
log.error("updateDeviceFile sql query error, sql=%s", sql)
return
connect.commit()
def doWork(self,):
listUpdata = self.readData()
for item in listUpdata:
log.info("dispatchOrderCode=%s!",item.dispatchOrderCode)
if item.dispatchOrderCode is None:
continue
if len(item.dispatchOrderCode) <= 3:
continue
if item.sendTime is None:
continue
if len(item.sendTime) <= 3:
continue
listSn = self.getlistSnFromOrderDetail(item.dispatchOrderCode)
if listSn is None or len(listSn) == 0:
self.updateLogistics(item)
self.updateOrderDetail(item)
continue
self.updateLogistics(item)
self.updateOrderDetail(item)
self.updateDeviceFile(listSn,item)
log.info("OK!")
if __name__ == "__main__":
workInstance = HandleUpdSendTime()
workInstance.setFileName("F:\\更改平台日期.xlsx")
workInstance.doWork()
# -*- coding:utf-8 -*-
from __future__ import print_function
import datetime
import logging
import sys
from logging.handlers import TimedRotatingFileHandler
log = logging.getLogger('yyx')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
log_file_handler = TimedRotatingFileHandler(filename="./HandleExcelSign.log", when="D", interval=1)
log_file_handler.setFormatter(formatter)
log_file_handler.setLevel(logging.DEBUG)
log.addHandler(log_file_handler)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
def paddstr(strx):
return 'NULL' if strx == None else '\'' + strx + '\''
def paddnum(numx):
return 'NULL' if numx == None else str(numx)
class StructSyncMerchantStock:
id = 1
lastStockSnDay = ''
createdBy = ''
updatedBy = ''
createdDate = ''
updatedDate = ''
deletedFlag = ''
class StructMerchantStock:
merchantCode = ''
deviceType = 0
materialCode = ''
stockMonth = ''
openingInventory = ''
endingInventory = ''
monthSales = 0
monthReceives = 0
monthCallin = 0
monthCallout = 0
monthRet = 0
monthLosses = 0
monthActives = 0
monthDemolish = 0
openingUnatInv = 0
endingUnatInv = 0
createdBy = ''
updatedBy = ''
createdDate = ''
updatedDate = ''
deletedFlag = ''
class StructMerchantStockSn:
id = None
sn = ''
toMerchantCode = ''
toMerchantName = ''
curMerchantCode = ''
curMerchantName = ''
deviceType=8
deviceCode=100006
materialCode = ''
materialName = ''
activeTime = ''
sendTime = ''
transferTime = ''
activeSysFlag = ''
demolishFlag = ''
createdBy = ''
updatedBy = ''
createdDate = ''
updatedDate = ''
deletedFlag = ''
class StructDeviceType:
typeId = None
typeName = ''
class StructMaterial:
materialCode = ''
materialName = ''
deviceType = None
class StructMerchant:
merchantCode = ''
merchantName = ''
class StructTransferMerchant:
merchantCode = ''
merchantName = ''
transferTime = ''
class StructSendMerchant:
merchantCode = ''
merchantName = ''
sendTime = ''
class StructMerchantStockStatDay:
tradeDate = ''
merchantCode = ''
deviceType = ''
materialCode = ''
materialName = ''
tradeTotal = 0
createdBy = ''
updatedBy = ''
createdDate = ''
updatedDate = ''
deletedFlag = ''
class StructLogisticsInfo:
servieCode = ''
shipmentQuantity = ''
sendTime=''
class StructServiceCodeInfo:
serviceCode = ''
merchantCode = ''
deviceType = ''
materialCode = ''
materialName = ''
class StructTransfer:
tradeDate = ''
outMerchantCode = ''
inMerchantCode = ''
materialCode = ''
materialName = ''
tradeTotal = ''
deviceType = None
class StructStatement:
tradeDate = ''
warehouseCode = ''
warehouseName = ''
merchantCode = ''
merchantName = ''
tradeTotal = ''
materialCode = ''
materialName = ''
deviceType = None
class StructProductConfig:
configCode = ''
merchantCode = ''
periodStart = ''
periodEnd = ''
class StructProductConfigDetail:
configCode = ''
materialCode = ''
materialName = ''
deviceType = None
total = 0
typeFlag = None
class StructWarningSet:
warningCode = ''
warningType = ''
channelType = ''
merchantChannelId = 0
merchantChannelName = ''
merchantCode = ''
merchantName = ''
deviceType = 0
thresholdLow = None
thresholdHigh = None
class StructWarningWaresale:
warningCode = ''
merchantCode = ''
merchantName = ''
warningMonth = ''
deviceType = 0
waresaleRate = None
class StructWarningDeviceSn:
id = None
warningCode = ''
sn = ''
toMerchantCode = ''
toMerchantName = ''
curMerchantCode = ''
curMerchantName = ''
deviceType = None
materialCode = ''
materialName = ''
activeTime = ''
sendTime = ''
transferTime = ''
createdBy = ''
createdDate = ''
updatedBy = ''
updatedDate = ''
deletedFlag = ''
class StructWarningSlowCodeAssume:
warningCode = ''
deviceTotal = 0
class StructWarningSlowMaterialAssume:
warningCode = ''
merchantCode = ''
merchantName = ''
materialCode = ''
materialName = ''
deviceTotal = ''
class StructSnStat:
deviceType = None
toMerchantCode = ''
toMerchantName = ''
deviceTotal = 0
unActiveDays = 0
activeOrNot = ''
class CComonUnit:
def getYearFromDateYM(self,dateYm):
dateYmp = datetime.datetime.strptime(dateYm,"%Y%m")
return dateYmp.year
def getMonthFromDateYM(self,dateYm):
dateYmp = datetime.datetime.strptime(dateYm, "%Y%m")
def getYearFromDate(self,dateYm):
dateYmp = datetime.datetime.strptime(dateYm,"%Y-%m")
return dateYmp.year
def getMonthFromDate(self,dateYm):
dateYmp = datetime.datetime.strptime(dateYm, "%Y-%m")
return dateYmp.month
def getDateFromDateYM(self,dateYm):
return datetime.datetime.strptime(dateYm, "%Y-%m")
def getNowDateYMD(self):
curTime = datetime.datetime.now()
return curTime.strftime('%Y-%m-%d')
def getDateFomatDate(self,dateYmd):
return datetime.datetime.strptime(dateYmd,"%Y-%m-%d")
def getDateStrYmdFromDateYmd(self,dateYmd):
return datetime.datetime.strftime(dateYmd,"%Y%m%d")
def getDateStrYmFromDateYm(self,dateYm):
return datetime.datetime.strftime(dateYm,"%Y%m")
def getDateStrY_M_DFromDateYmd(self,dateYmd):
return datetime.datetime.strftime(dateYmd, "%Y-%m-%d")
def getNextDateYMD(self,dateYmd):
dateYmdP = datetime.datetime.strptime(dateYmd,'%Y-%m-%d')
nexDayP = dateYmdP + datetime.timedelta(days=1)
return nexDayP.strftime('%Y-%m-%d')
def getPreDateYMD(self,dateYmd,intervalDay):
dateYmdP = datetime.datetime.strptime(dateYmd, '%Y-%m-%d')
preDayP = dateYmdP - datetime.timedelta(days=intervalDay)
return preDayP.strftime('%Y-%m-%d')
def getNowDateYMDHMS(self):
curTime = datetime.datetime.now()
return curTime.strftime('%Y-%m-%d %H:%M:%S')
def getNowDate(self):
return datetime.datetime.now()
def getPreMonth(self,dateYmd):
curdate = self.getDateFomatDate(dateYmd)
first = curdate.replace(day=1)
lastMonth = first - datetime.timedelta(days=1)
return lastMonth.strftime("%Y-%m")
def betweenTwoDate(self,strDate,strDateStart,strDateEnd):
dateYmp = datetime.datetime.strptime(strDate,"%Y-%m-%d")
dateYmpStart = datetime.datetime.strptime(strDateStart,"%Y-%m-%d")
dateYmpEnd = datetime.datetime.strptime(strDateEnd,"%Y-%m-%d")
if dateYmp>= dateYmpStart and dateYmp <= dateYmpEnd:
return True
return False
\ No newline at end of file \ No newline at end of file
# -*- coding:utf-8 -*-
import logging
import os
import datetime
import time
import openpyxl
from openpyxl import Workbook
class CRecordData:
genFileName = ''
billNo = ''
merchantOrders = ''
isPrint = ''
orderDate = ''
recvName = ''
merchantName = ''
class OrderNoIndex:
orderNo = ''
excelId = None
class CSale:
recvMerchantName = ''
sendMerchantName = ''
orderDate = ''
orderNo = ''
recvName = ''
recvPhone = ''
recvAddr = ''
currency = ''
idx = 0
totalCount = 0
totalCobilePrice = 0
listSaleDetail = None
class CSaleDetail:
productCode = ''
productName = ''
productCount = 0
unitPrice = 0.0
cobilePrice = 0.0
remark = ''
class CHandleExcelSale:
ccomunit = None
pathRootCatalog = ''
genFoldName = ''
listExcelFileNames = None
listRecord = None
modelFileName = ''
mapOrderDate = None
listOrderIndex = None
listSale = None
genCount = 0
def __init__(self):
self.ccomunit = CComonUnit()
self.pathRootCatalog = ''
self.genFoldName = ''
self.listExcelFileNames = []
self.listRecord = []
self.modelFileName = ''
self.mapOrderDate = {}
self.listOrderIndex = []
self.listSale = []
self.genCount = 0
def setRecordFileName(self,recordFileName):
self.recordFileName = recordFileName
def SetRootPath(self, rootPath):
self.pathRootCatalog = rootPath
def setFoldName(self,folderName):
self.genFoldName = folderName
def GetGenFileName(self,foldName,cpyName,orderNo):
fileName = "%s%s\\%s_%s.xlsx"%(self.pathRootCatalog,foldName,orderNo,cpyName)
self.genCount = self.genCount + 1
return fileName
def SetModelFileName(self,modelFileName):
self.modelFileName = "%s%s" % (self.pathRootCatalog, modelFileName)
def AddExcelFileNames(self,fileName):
strFileName = "%s%s"%(self.pathRootCatalog,fileName)
self.listExcelFileNames.append(strFileName)
def ReadExcelData(self):
if self.listExcelFileNames is None:
return
if len(self.listExcelFileNames) == 0:
return
for item in self.listExcelFileNames:
self.ReadExcelDataFromExcelFile(item)
self.SetOrderNoBack2ExcelFile(item)
def ReadExcelDataFromExcelFile(self, fileName):
dateTimeSplit = self.ccomunit.getDateFomatDate("2020-11-01")
mapSales = {}
workbook = openpyxl.load_workbook(fileName)
sheet = workbook.active
rows = sheet.max_row
merchantType = ""
if "同盟会" in fileName:
merchantType = "TMH"
elif "租赁服务商" in fileName:
merchantType = "ZLY"
elif "爱车保镖" in fileName:
merchantType = "ACB"
elif "金融风控" in fileName:
merchantType = "JRF"
elif "广汇服务" in fileName:
merchantType = "GHH"
else:
merchantType = "SSF"
log.info("filename=%s",fileName)
for i in range(2, rows + 1):
sendCpyName = sheet['A%d'%(i)].value
recvMerchantName = sheet['E%d'%(i)].value
productCode = sheet['F%d'%(i)].value
productName = sheet['G%d'%(i)].value
orderDateDt = sheet['H%d'%(i)].value
productCount = sheet['I%d'%(i)].value
unitPrice = sheet['J%d'%(i)].value
cobilePrice = sheet['K%d'%(i)].value
recvName = sheet['Q%d'%(i)].value
recvPhone = sheet['R%d'%(i)].value
recvAddress = sheet['S%d'%(i)].value
remark = sheet['X%d'%(i)].value
if recvMerchantName is None or recvMerchantName=='':
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile recvMerchantName is None i=%d",i)
continue
if productCode is None or productCode=='':
# log.error("CHandleExcelSale::ReadExcelDataFromExcelFile productCode is None i=%d",i)
productCode = ''
if productName is None or productName=='':
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile productName is None i=%d",i)
continue
if isinstance(orderDateDt, datetime.datetime) is not True:
sendTimetemp = None
try:
sendTimetemp = datetime.datetime.strptime(orderDateDt, "%Y/%m/%d")
except ValueError:
sendTimetemp = datetime.datetime.strptime(orderDateDt, "%Y-%m-%d")
#else:
# log.error("CHandleExcelSign::ReadExcelDataFromExcelFile orderDateDt wrong format i=%d", i)
# continue
orderDateDt = sendTimetemp
if productCount is None:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile productCount is None i=%d", i)
productCount = 0
if isinstance(productCount,int) is not True:
try:
productCount = int(productCount)
except ValueError:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile productCount is not int i=%d", i)
continue
if unitPrice is None:
#log.error("CHandleExcelSale::ReadExcelDataFromExcelFile unitPrice is None i=%d", i)
unitPrice = 0
if cobilePrice is None:
#log.error("CHandleExcelSale::ReadExcelDataFromExcelFile cobilePrice is None i=%d", i)
cobilePrice = 0
if isinstance(cobilePrice,int) is not True:
if isinstance(cobilePrice,float) is not True:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile cobilePrice is not int or float i=%d", i)
continue
if recvName is None or recvName=='':
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile recvName is None i=%d",i)
recvName = ""
if recvPhone is None:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile recvPhone is None i=%d",i)
recvPhone = ""
if recvAddress is None:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile recvAddress is None i=%d",i)
recvAddress = ""
if remark is None:
remark = ''
#if orderDateDt >= dateTimeSplit:
# sendCpyName = "深圳广联赛讯股份有限公司"
#else:
# sendCpyName = "深圳广联赛讯有限公司"
orderDate = self.ccomunit.getDateStrY_M_DFromDateYmd(orderDateDt)
sale = None
j = 0
idx = 0
while (True):
keyData = "mt:%s,mn:%s,st:%s,rc:%s,rp:%s,ra:%s,i:%d" % (
merchantType,recvMerchantName, orderDate, recvName, recvPhone, recvAddress,j)
sale = mapSales.get(keyData)
if sale is not None:
if len(sale.listSaleDetail) >= 10:
j = j + 1
idx = sale.idx + 1
continue
break
if j > 1000:
break
j = j + 1
if sale is None:
sale = CSale()
sale.sendMerchantName = sendCpyName
sale.recvMerchantName = recvMerchantName
sale.orderDate = orderDate
sale.orderNo = self.GetOrderNo(self.ccomunit.getDateStrYmFromDateYm(orderDateDt),merchantType)
sale.recvName = recvName
sale.recvPhone = recvPhone
sale.recvAddr = recvAddress
sale.currency = '人民币'
sale.idx = idx
keyData = "mt:%s,mn:%s,st:%s,rc:%s,rp:%s,ra:%s,i:%d" % (
merchantType, recvMerchantName, orderDate, recvName, recvPhone, recvAddress, sale.idx)
mapSales[keyData] = sale
if sale.listSaleDetail is None:
sale.listSaleDetail = []
if len(sale.listSaleDetail) >= 10:
nsale = CSale()
nsale.sendMerchantName = sendCpyName
nsale.recvMerchantName = recvMerchantName
nsale.orderDate = orderDate
nsale.orderNo = self.GetOrderNo(self.ccomunit.getDateStrYmFromDateYm(orderDateDt),merchantType)
nsale.recvName = recvName
nsale.recvPhone = recvPhone
nsale.recvAddr = recvAddress
nsale.currency = '人民币'
nsale.idx = sale.idx + 1
keyData = "mt:%s,mn:%s,st:%s,rc:%s,rp:%s,ra:%s,i:%d" % (
merchantType, recvMerchantName, orderDate, recvName, recvPhone, recvAddress, nsale.idx)
mapSales[keyData] = nsale
sale = nsale
if sale.listSaleDetail is None:
sale.listSaleDetail = []
saleDetail = CSaleDetail()
saleDetail.productCode = productCode
saleDetail.productName = productName
saleDetail.productCount = productCount
saleDetail.unitPrice = unitPrice
saleDetail.cobilePrice = cobilePrice
saleDetail.remark = remark
sale.listSaleDetail.append(saleDetail)
orderIndex = OrderNoIndex()
orderIndex.orderNo = sale.orderNo
orderIndex.excelId = i
self.listOrderIndex.append(orderIndex)
workbook.close()
self.listSale = self.listSale + list(mapSales.values())
return None
def GetOrderNo(self,strOrderDateYm,merchantType):
keyData = strOrderDateYm + merchantType
orderCount = self.mapOrderDate.get(keyData)
if orderCount is None:
orderCount = 1
else:
orderCount = orderCount + 1
self.mapOrderDate[keyData] = orderCount
result = "GL" + strOrderDateYm + merchantType + str(orderCount).zfill(4)
return result
def SetOrderNoBack2ExcelFile(self,excelFileName):
if self.listOrderIndex is None:
return
if len(self.listOrderIndex) == 0:
return
workbook = openpyxl.load_workbook(excelFileName)
sheet = workbook.active
sheet["Z1"]="生成的订单号"
for item in self.listOrderIndex:
sheet["Z%d"%(item.excelId)] = item.orderNo
workbook.save(excelFileName)
workbook.close()
def HandleListSale(self):
if self.listSale is None:
return
if len(self.listSale) == 0:
return
i = 0
for item in self.listSale:
if item.listSaleDetail is None:
continue
if len(item.listSaleDetail) == 0:
continue
wtFileName = self.GetGenFileName(self.genFoldName,item.recvMerchantName,item.orderNo)
workbook = openpyxl.load_workbook(self.modelFileName)
sheet = workbook.active
sheet['C2'] = item.recvMerchantName
sheet['C3'] = item.sendMerchantName
sheet['C4'] = item.recvAddr
sheet['G2'] = item.orderDate
sheet['G3'] = item.recvName
sheet['I2'] = item.orderNo
sheet['I3'] = item.recvPhone
sheet['I4'] = item.currency
detailItem = 7
totalCount = 0
totalPrice = 0.0
for subitem in item.listSaleDetail:
sheet['B%d' % (detailItem)] = subitem.productCode
sheet['D%d' % (detailItem)] = subitem.productName
sheet['E%d' % (detailItem)] = subitem.productCount
sheet['F%d' % (detailItem)] = subitem.unitPrice
sheet['G%d' % (detailItem)] = subitem.cobilePrice
sheet['H%d' % (detailItem)] = subitem.remark
totalCount = totalCount + int(subitem.productCount)
totalPrice = totalPrice + float(subitem.cobilePrice)
detailItem = detailItem + 1
sheet['E17'] = totalCount
sheet['G17'] = totalPrice
if i%50 == 0:
log.info("HandleListBill 正在生成文件 wtFileName=%s,i=%d",wtFileName,i)
i = i+1
workbook.save(wtFileName)
recordData = CRecordData()
recordData.isPrint = 0
recordData.billNo = item.orderNo
recordData.genFileName = wtFileName
recordData.recvName = item.recvName
recordData.orderDate = item.orderDate
recordData.merchantName = item.recvMerchantName
self.listRecord.append(recordData)
workbook.close()
def WriteRecord(self):
if self.listRecord is None:
return
if len(self.listRecord) == 0:
return
recordFileName = "%s\\%s"%(self.pathRootCatalog,self.recordFileName)
workbook = Workbook()
sheet = workbook.active
i = 2
sheet['A1'] = "单据编号"
sheet['B1'] = "文件名"
for item in self.listRecord:
sheet['A%d'%(i)] = item.billNo
sheet['B%d'%(i)] = item.genFileName
sheet['C%d'%(i)] = item.isPrint
sheet['D%d' % (i)] = item.orderDate[0:7]
sheet['E%d' % (i)] = item.recvName
sheet['F%d' % (i)] = item.merchantName
i = i + 1
workbook.save(recordFileName)
workbook.close()
def StartWork(self):
self.ReadExcelData()
self.HandleListSale()
self.WriteRecord()
log.error("handle ok!")
log.error("handle ok!")
if __name__ == "__main__":
handleExcelSale = CHandleExcelSale()
handleExcelSale.SetRootPath("F:\\a\\b\\sale\\")
handleExcelSale.setFoldName("generate")
handleExcelSale.setRecordFileName("record.xlsx")
handleExcelSale.AddExcelFileNames("商务采购订单汇总2022年5月附件1.xlsx")
#handleExcelSale.AddExcelFileNames("2019年租赁服务商采购订单.xlsx")
handleExcelSale.SetModelFileName("客户采购订单模版.xlsx")
handleExcelSale.StartWork()
# -*- coding:utf-8 -*-
import logging
import os
import datetime
import time
import openpyxl
from openpyxl import Workbook
from MerchantStock.CommonDef import CComonUnit, log
class CRecordData:
genFileName = ''
billNo = ''
merchantOrders = ''
isPrint = ''
orderDate = ''
recvName = ''
merchantName = ''
class OrderNoIndex:
orderNo = ''
excelId = None
class CSale:
recvMerchantName = ''
sendMerchantName = ''
orderDate = ''
orderNo = ''
recvName = ''
recvPhone = ''
recvAddr = ''
currency = ''
idx = 0
totalCount = 0
totalCobilePrice = 0
listSaleDetail = None
class CSaleDetail:
productCode = ''
productName = ''
productCount = 0
unitPrice = 0.0
cobilePrice = 0.0
remark = ''
class CHandleExcelSale:
ccomunit = None
pathRootCatalog = ''
genFoldName = ''
listExcelFileNames = None
listRecord = None
modelFileName = ''
mapOrderDate = None
listOrderIndex = None
listSale = None
genCount = 0
def __init__(self):
self.ccomunit = CComonUnit()
self.pathRootCatalog = ''
self.genFoldName = ''
self.listExcelFileNames = []
self.listRecord = []
self.modelFileName = ''
self.mapOrderDate = {}
self.listOrderIndex = []
self.listSale = []
self.genCount = 0
def setRecordFileName(self,recordFileName):
self.recordFileName = recordFileName
def SetRootPath(self, rootPath):
self.pathRootCatalog = rootPath
def setFoldName(self,folderName):
self.genFoldName = folderName
def GetGenFileName(self,foldName,cpyName,orderNo):
fileName = "%s%s\\%s_%s.xlsx"%(self.pathRootCatalog,foldName,orderNo,cpyName)
self.genCount = self.genCount + 1
return fileName
def SetModelFileName(self,modelFileName):
self.modelFileName = "%s%s" % (self.pathRootCatalog, modelFileName)
def AddExcelFileNames(self,fileName):
strFileName = "%s%s"%(self.pathRootCatalog,fileName)
self.listExcelFileNames.append(strFileName)
def ReadExcelData(self):
if self.listExcelFileNames is None:
return
if len(self.listExcelFileNames) == 0:
return
for item in self.listExcelFileNames:
self.ReadExcelDataFromExcelFile(item)
self.SetOrderNoBack2ExcelFile(item)
def ReadExcelDataFromExcelFile(self, fileName):
dateTimeSplit = self.ccomunit.getDateFomatDate("2020-11-01")
mapSales = {}
workbook = openpyxl.load_workbook(fileName)
sheet = workbook.active
rows = sheet.max_row
merchantType = ""
if "同盟会" in fileName:
merchantType = "TMH"
elif "租赁服务商" in fileName:
merchantType = "ZLY"
elif "爱车保镖" in fileName:
merchantType = "ACB"
elif "金融风控" in fileName:
merchantType = "JRF"
elif "广汇服务" in fileName:
merchantType = "GHH"
else:
merchantType = "SSE"
log.info("filename=%s",fileName)
for i in range(2, rows + 1):
sendCpyName = sheet['A%d'%(i)].value
recvMerchantName = sheet['B%d'%(i)].value
productCode = sheet['C%d'%(i)].value
productName = sheet['D%d'%(i)].value
orderDateDt = sheet['E%d'%(i)].value
productCount = sheet['F%d'%(i)].value
unitPrice = sheet['G%d'%(i)].value
cobilePrice = sheet['H%d'%(i)].value
recvName = sheet['I%d'%(i)].value
recvPhone = sheet['J%d'%(i)].value
recvAddress = sheet['K%d'%(i)].value
remark = sheet['X%d'%(i)].value
if recvMerchantName is None or recvMerchantName=='':
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile recvMerchantName is None i=%d",i)
continue
if productCode is None or productCode=='':
# log.error("CHandleExcelSale::ReadExcelDataFromExcelFile productCode is None i=%d",i)
productCode = ''
if productName is None or productName=='':
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile productName is None i=%d",i)
continue
if isinstance(orderDateDt, datetime.datetime) is not True:
sendTimetemp = None
try:
sendTimetemp = datetime.datetime.strptime(orderDateDt, "%Y/%m/%d")
except ValueError:
sendTimetemp = datetime.datetime.strptime(orderDateDt, "%Y-%m-%d")
#else:
# log.error("CHandleExcelSign::ReadExcelDataFromExcelFile orderDateDt wrong format i=%d", i)
# continue
orderDateDt = sendTimetemp
if productCount is None:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile productCount is None i=%d", i)
productCount = 0
if isinstance(productCount,int) is not True:
try:
productCount = int(productCount)
except ValueError:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile productCount is not int i=%d", i)
continue
if unitPrice is None:
#log.error("CHandleExcelSale::ReadExcelDataFromExcelFile unitPrice is None i=%d", i)
unitPrice = 0
if cobilePrice is None:
#log.error("CHandleExcelSale::ReadExcelDataFromExcelFile cobilePrice is None i=%d", i)
cobilePrice = 0
if isinstance(cobilePrice,int) is not True:
if isinstance(cobilePrice,float) is not True:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile cobilePrice is not int or float i=%d", i)
continue
if recvName is None or recvName=='':
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile recvName is None i=%d",i)
recvName = ""
if recvPhone is None:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile recvPhone is None i=%d",i)
recvPhone = ""
if recvAddress is None:
log.error("CHandleExcelSale::ReadExcelDataFromExcelFile recvAddress is None i=%d",i)
recvAddress = ""
if remark is None:
remark = ''
#if orderDateDt >= dateTimeSplit:
# sendCpyName = "深圳广联赛讯股份有限公司"
#else:
# sendCpyName = "深圳广联赛讯有限公司"
orderDate = self.ccomunit.getDateStrY_M_DFromDateYmd(orderDateDt)
sale = None
j = 0
idx = 0
while (True):
keyData = "mt:%s,mn:%s,st:%s,rc:%s,rp:%s,ra:%s,i:%d" % (
merchantType,recvMerchantName, orderDate, recvName, recvPhone, recvAddress,j)
sale = mapSales.get(keyData)
if sale is not None:
if len(sale.listSaleDetail) >= 10:
j = j + 1
idx = sale.idx + 1
continue
break
if j > 1000:
break
j = j + 1
if sale is None:
sale = CSale()
sale.sendMerchantName = sendCpyName
sale.recvMerchantName = recvMerchantName
sale.orderDate = orderDate
sale.orderNo = self.GetOrderNo(self.ccomunit.getDateStrYmFromDateYm(orderDateDt),merchantType)
sale.recvName = recvName
sale.recvPhone = recvPhone
sale.recvAddr = recvAddress
sale.currency = '人民币'
sale.idx = idx
keyData = "mt:%s,mn:%s,st:%s,rc:%s,rp:%s,ra:%s,i:%d" % (
merchantType, recvMerchantName, orderDate, recvName, recvPhone, recvAddress, sale.idx)
mapSales[keyData] = sale
if sale.listSaleDetail is None:
sale.listSaleDetail = []
if len(sale.listSaleDetail) >= 10:
nsale = CSale()
nsale.sendMerchantName = sendCpyName
nsale.recvMerchantName = recvMerchantName
nsale.orderDate = orderDate
nsale.orderNo = self.GetOrderNo(self.ccomunit.getDateStrYmFromDateYm(orderDateDt),merchantType)
nsale.recvName = recvName
nsale.recvPhone = recvPhone
nsale.recvAddr = recvAddress
nsale.currency = '人民币'
nsale.idx = sale.idx + 1
keyData = "mt:%s,mn:%s,st:%s,rc:%s,rp:%s,ra:%s,i:%d" % (
merchantType, recvMerchantName, orderDate, recvName, recvPhone, recvAddress, nsale.idx)
mapSales[keyData] = nsale
sale = nsale
if sale.listSaleDetail is None:
sale.listSaleDetail = []
saleDetail = CSaleDetail()
saleDetail.productCode = productCode
saleDetail.productName = productName
saleDetail.productCount = productCount
saleDetail.unitPrice = unitPrice
saleDetail.cobilePrice = cobilePrice
saleDetail.remark = remark
sale.listSaleDetail.append(saleDetail)
orderIndex = OrderNoIndex()
orderIndex.orderNo = sale.orderNo
orderIndex.excelId = i
self.listOrderIndex.append(orderIndex)
workbook.close()
self.listSale = self.listSale + list(mapSales.values())
return None
def GetOrderNo(self,strOrderDateYm,merchantType):
keyData = strOrderDateYm + merchantType
orderCount = self.mapOrderDate.get(keyData)
if orderCount is None:
orderCount = 1
else:
orderCount = orderCount + 1
self.mapOrderDate[keyData] = orderCount
result = "GL" + strOrderDateYm + merchantType + str(orderCount).zfill(4)
return result
def SetOrderNoBack2ExcelFile(self,excelFileName):
if self.listOrderIndex is None:
return
if len(self.listOrderIndex) == 0:
return
workbook = openpyxl.load_workbook(excelFileName)
sheet = workbook.active
sheet["Z1"]="生成的订单号"
for item in self.listOrderIndex:
sheet["Z%d"%(item.excelId)] = item.orderNo
workbook.save(excelFileName)
workbook.close()
def HandleListSale(self):
if self.listSale is None:
return
if len(self.listSale) == 0:
return
i = 0
for item in self.listSale:
if item.listSaleDetail is None:
continue
if len(item.listSaleDetail) == 0:
continue
wtFileName = self.GetGenFileName(self.genFoldName,item.sendMerchantName,item.orderNo)
workbook = openpyxl.load_workbook(self.modelFileName)
sheet = workbook.active
sheet['C2'] = item.recvMerchantName
sheet['C3'] = item.sendMerchantName
sheet['C4'] = item.recvAddr
sheet['G2'] = item.orderDate
sheet['G3'] = item.recvName
sheet['I2'] = item.orderNo
sheet['I3'] = item.recvPhone
sheet['I4'] = item.currency
detailItem = 7
totalCount = 0
totalPrice = 0.0
for subitem in item.listSaleDetail:
sheet['B%d' % (detailItem)] = subitem.productCode
sheet['D%d' % (detailItem)] = subitem.productName
sheet['E%d' % (detailItem)] = subitem.productCount
sheet['F%d' % (detailItem)] = subitem.unitPrice
sheet['G%d' % (detailItem)] = subitem.cobilePrice
sheet['H%d' % (detailItem)] = subitem.remark
totalCount = totalCount + int(subitem.productCount)
totalPrice = totalPrice + float(subitem.cobilePrice)
detailItem = detailItem + 1
sheet['E17'] = totalCount
sheet['G17'] = totalPrice
if i%50 == 0:
log.info("HandleListBill 正在生成文件 wtFileName=%s,i=%d",wtFileName,i)
i = i+1
workbook.save(wtFileName)
recordData = CRecordData()
recordData.isPrint = 0
recordData.billNo = item.orderNo
recordData.genFileName = wtFileName
recordData.recvName = item.recvName
recordData.orderDate = item.orderDate
recordData.merchantName = item.sendMerchantName
self.listRecord.append(recordData)
workbook.close()
def WriteRecord(self):
if self.listRecord is None:
return
if len(self.listRecord) == 0:
return
recordFileName = "%s\\%s"%(self.pathRootCatalog,self.recordFileName)
workbook = Workbook()
sheet = workbook.active
i = 2
sheet['A1'] = "单据编号"
sheet['B1'] = "文件名"
for item in self.listRecord:
sheet['A%d'%(i)] = item.billNo
sheet['B%d'%(i)] = item.genFileName
sheet['C%d'%(i)] = item.isPrint
sheet['D%d' % (i)] = item.orderDate[0:7]
sheet['E%d' % (i)] = item.recvName
sheet['F%d' % (i)] = item.merchantName
i = i + 1
workbook.save(recordFileName)
workbook.close()
def StartWork(self):
self.ReadExcelData()
self.HandleListSale()
self.WriteRecord()
log.error("handle ok!")
log.error("handle ok!")
if __name__ == "__main__":
handleExcelSale = CHandleExcelSale()
handleExcelSale.SetRootPath("F:\\a\\b\\sale\\")
handleExcelSale.setFoldName("generate")
handleExcelSale.setRecordFileName("record.xlsx")
handleExcelSale.AddExcelFileNames("广汇区域自采采购订单汇总2022.5月附件2.xlsx")
#handleExcelSale.AddExcelFileNames("2019年租赁服务商采购订单.xlsx")
handleExcelSale.SetModelFileName("客户采购订单模版.xlsx")
handleExcelSale.StartWork()
import chardet
def detect_encoding(file_path):
with open(file_path, 'rb') as f:
result = chardet.detect(f.read())
return result['encoding']
def subLineStr(text):
# 找到 "调用" 和 "时发生异常" 的位置
start_index = text.find("调用") + len("调用")
end_index = text.find("时发生异常")
# 使用切片截取中间部分
result = text[start_index:end_index]
# print(result) # 输出:stoassistant.api.score.detail
return result
# 使用 chardet 检测编码格式
file_path = 'F:/users/tecent/qwechat/WXWork/1688853634415099/Cache/File/2023-07/rop-scrm-xxxxx.log'
file_encoding = detect_encoding(file_path)
print(f'文件编码格式:{file_encoding}')
methodMapper = {}
# 打开文件并读取内容,指定正确的编码格式
with open(file_path, 'r', encoding=file_encoding) as file:
line = file.readline()
while line:
# 处理当前行的内容,例如打印
# print(line.strip()) # 使用 strip() 方法去除行末尾的换行符
line = file.readline()
prifex = line[:4]
if prifex=='2023':
methodName = subLineStr(line)
methodMapper[methodName] = 0
for mekey,meValue in methodMapper.items():
print(f'method:{mekey}')
import logging
class DjRenewalDevice:
handleMonth = ''
def __init__(self, handle_month):
self.handleMonth = handle_month
def loadDeviceListByMonth():
if __name__ == '__main__':
handle_month = '2022-05'
djRenwalDevice = DjRenewalDevice(handle_month)
deviceList = djRenwalDevice.loadDeviceListByMonth()
\ No newline at end of file \ No newline at end of file
import logging
import pandas as pdas
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/djcardrenewal/handlemain.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class HandelMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
db = None
ghDb = None
glDb = None
cybDb = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "dj renewal match iccid and device location"
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.db = MysqlHelper(DbConect.current_month_DB)
self.ghDb = MysqlHelper(DbConect.djGH_release_slave)
self.glDb = MysqlHelper(DbConect.dj_release_slave)
self.cybDb = MysqlHelper(DbConect.cyb_release_DB)
def initCurrentMonthTable(self):
logging.info("初始化:删除中间表")
for drtable in CurMonthYzl.drop_table_meta:
dropSql = drtable + self.hmonth
print('===dropSql=',dropSql)
self.db.execute_modify(dropSql)
#################################################################################
#创建设备到期表
createSqlEndDate = f'''CREATE TABLE `insu_enddate_device_{self.hmonth}` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`sn` VARCHAR(32) DEFAULT NULL,
`end_date` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_sn` (`sn`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT '设备卡信息';'''
print('===createSql endDate=')
self.db.execute_modify(createSqlEndDate)
#创建卡信息表
createSqlCardInfo = f'''CREATE TABLE `insu_card_info_{self.hmonth}` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`sn` VARCHAR(32) DEFAULT NULL,
`iccid` VARCHAR(64) DEFAULT NULL,
`imsi` VARCHAR(64) DEFAULT NULL,
`protocol_id` INT(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_sn` (`sn`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT '设备到期数据';'''
print('===createSql cardInfo=')
self.db.execute_modify(createSqlCardInfo)
#创建续费表
createSqlRenewl = f'''CREATE TABLE `insu_renewl_{self.hmonth}` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`protocol_id` INT(11) DEFAULT NULL,
`max_renewal_time` DATETIME DEFAULT NULL,
`sn` VARCHAR(32) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_sn` (`sn`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT '续费数据';'''
print('===createSql renewl=')
self.db.execute_modify(createSqlRenewl)
#################################################################################
def dealDeviceEndDateList(self):
selectDeviceEndDateSql = f'''SELECT
end_date AS '保单到期时间',
sub_device_sn AS sn
FROM dj_insure_order
WHERE deleted_flag = 'N' AND insurance_status IN ('1','6','7') AND sub_device_sn IS NOT NULL AND DATE_FORMAT(end_date, '%Y-%m')='{self.handleMonth}' AND LENGTH(sub_device_sn)>1
UNION
SELECT
end_date AS '保单到期时间',
sub_device_sn AS sn
FROM dj_insure_equity
WHERE deleted_flag = 'N' AND equity_status IN ('1','6','7') AND sub_device_sn IS NOT NULL AND DATE_FORMAT(end_date, '%Y-%m')='{self.handleMonth}' AND LENGTH(sub_device_sn)>1
;'''
#广汇的数据
ghDbData = self.ghDb.execute_select(selectDeviceEndDateSql)
self.executeInsertEndDate(ghDbData)
#广联的数据
glDbData = self.glDb.execute_select(selectDeviceEndDateSql)
self.executeInsertEndDate(glDbData)
return True
# 插入 到期设备的数据
def executeInsertEndDate(self, dbData):
if dbData is None :
logging.info("db device enddate is none")
return
elif dbData is False:
logging.info("db device enddate is exception")
return
sqlSb = StringBuilder()
sqlSb.append(f'insert into insu_enddate_device_{self.hmonth}(sn,end_date) values ')
for item in dbData:
snValue = item[1]
endDateValue = item[0]
currentLine = f'''('{snValue}','{endDateValue}'),'''
sqlSb.append(currentLine)
sqlSb.append(';')
insertSql = str(sqlSb)[0:-2]+';'
logging.info('insert sql enddata print:%s', len(dbData))
self.db.execute_modify(insertSql)
return True
def dealDeviceIccidList(self):
# 获取所有设备号
selectSnListSql = f'select sn from insu_enddate_device_{self.hmonth};'
snData = self.db.execute_select(selectSnListSql)
if snData is None:
logging.info("db device enddate snList is none")
return False
whereSnSb = ''
for item in snData:
whereSnSb += ("'" + item[0] + "',")
whereSn = whereSnSb[0:-1]
# 获取设备号对应的设备信息
selectIccidSql = f'''SELECT a.`sn`,a.`iccid`,a.`imsi`,b.`protocol_id` FROM `glsx_common_physical_device` a
LEFT JOIN `platform_protocol` b ON a.`id`=b.`card_id`
WHERE a.`sn` IN ({whereSn});'''
iccidDbData = self.cybDb.execute_select(selectIccidSql)
if iccidDbData is None:
logging.info("db device iccid is none")
return False
sqlSb = StringBuilder()
sqlSb.append(f'insert into insu_card_info_{self.hmonth}(sn,iccid,imsi,protocol_id) values ')
for item in iccidDbData:
snValue = item[0]
iccidValue = item[1]
imsiValue = item[2]
protocolIdValue = item[3] if item[3] is not None else 0
sqlSb.append(f'''('{snValue}','{iccidValue}','{imsiValue}',{protocolIdValue}),''')
sqlSb.append(';')
insertSql = str(sqlSb)[0:-2]+';'
logging.info('insert sql iccid print:%s', len(iccidDbData))
self.db.execute_modify(insertSql)
return True
def dealUserRenewalList(self):
# 获取所有嘀嘀号
selectProtocolSql = f'select protocol_id from insu_card_info_{self.hmonth} where protocol_id>0';
proDbData = self.db.execute_select(selectProtocolSql)
if proDbData is None:
logging.info("db device enddate snList is none")
return False;
proIds = ''
for item in proDbData:
proIds += (str(item[0]) + ",")
whereProIds = proIds[0:-1]
selectRenewalSql = f'''SELECT c.`sn`,a.`user_id`,MAX(a.`create_time`) AS renewaltime FROM `platform_common_renewal_task` a,`platform_protocol` b,`glsx_common_physical_device` c
WHERE a.`user_id`=b.`protocol_id` AND b.`card_id`=c.`id`
AND a.`user_id` IN ({whereProIds})
GROUP BY c.`sn`;'''
proDbRes = self.cybDb.execute_select(selectRenewalSql)
if proDbRes is None:
logging.info("db user protocol is none")
return False
sqlSb = StringBuilder()
sqlSb.append(f'insert into insu_renewl_{self.hmonth}(protocol_id,max_renewal_time,sn) values ')
for item in proDbRes:
protocolValue = item[1]
renewalTimeValue = item[2]
snValue = item[0]
sqlSb.append(f'''({protocolValue},'{renewalTimeValue}','{snValue}'),''')
sqlSb.append(';')
insertSql = str(sqlSb)[0:-2]+';'
logging.info('insert sql renewal print:%s', len(proDbRes))
self.db.execute_modify(insertSql)
return True
def dealTheMonthData(self):
# 初始化表
handleMain.initCurrentMonthTable();
# 插入设备到期数据
dedRes = handleMain.dealDeviceEndDateList()
logging.info(f'===device enddate is:{dedRes}')
# 插入设备对应卡信息
diRes = handleMain.dealDeviceIccidList()
logging.info(f'===device iccid is:{diRes}')
# 插入续费数据
urRes = handleMain.dealUserRenewalList();
logging.info(f'===device userRenewal is:{urRes}')
def exportDataToExcel(self):
selectExportSql = f'''SELECT a.`sn`,a.`end_date`,b.`iccid`,b.`imsi`,c.`max_renewal_time` FROM `insu_enddate_device_{self.hmonth}` a
LEFT JOIN `insu_card_info_{self.hmonth}` b ON b.`sn`=a.`sn`
LEFT JOIN `insu_renewl_{self.hmonth}` c ON c.`sn`=a.`sn`;'''
exportDbRes = self.db.execute_select(selectExportSql)
if exportDbRes is None:
logging.info("db export is none")
return False
dataExport = pdas.DataFrame(exportDbRes)
dataExport.columns = ['设备号','服务到期时间','ICCID','IMSI','最后续费时间']
dataExport.to_excel(f'{self.hmonth}月到期未续费的iccid信息.xlsx', index=False)
if __name__ == "__main__":
handle_month = '2023-07'
dedRes = False
diRes = False
urRes = False
#启动初始化
handleMain = HandelMain(handle_month)
logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)
# 整理数据
# handleMain.dealTheMonthData()
#将结果输出到excel
handleMain.exportDataToExcel()
# 广联DJ
dj_release_slave = {"host": '47.115.93.31', "port": 3306, "user": 'user_wangxw1', "password": 'wbOTHHX5', "db": 'glsx_dj', "charset": 'utf8'}
# 广汇DJ
djGH_release_slave = {"host": '47.97.203.216', "port": 3306, "user": 'user_wangxw1', "password": 'wbOTHHX5', "db": 'glsx_dj', "charset": 'utf8'}
# 当月临时表
current_month_DB = {"host": '192.168.1.39', "port": 3306, "user": 'os_user', "password": 'os#123', "db": 'glsx_music', "charset": 'utf8'}
# cybDB
cyb_release_DB = {"host": '192.168.5.5', "port": 3311, "user": 'user_wangxw1', "password": 'wbOTHHX5', "db": 'cyb_os', "charset": 'utf8'}
# 审计库 生产 DJ
DB_shen_release_dj = {"host": '192.168.5.5', "port": 3310, "user": 'biz_device_detail', "password": 'M6khz3CQ', "db": 'glsx_data', "charset": 'utf8'}
# 审计库 生产 SAAS+
DB_shen_release_plus = {"host": '192.168.5.77', "port": 3306, "user": 'user_audit', "password": 'lRmOuNkc', "db": 'saas_plus', "charset": 'utf8'}
\ No newline at end of file \ No newline at end of file
#import os,sys
import logging
import pymysql
from djcardrenewal.common.dbase import DbConect
#print(sys.path)
class MysqlHelper:
_instance = None # 本类的实例
con = None # 数据库conn
cursor = None # 游标
def __init__(self, config) -> None:
self.host = config['host']
self.port = config["port"]
self.user = config["user"]
self.password = config["password"]
self.db = config["db"]
self.charset = config["charset"]
self.con = None
self.cursor = None
try:
self.con = pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.db, charset='utf8')
self.cursor = self.con.cursor()
self._instance = MysqlHelper
except Exception as e:
print(e)
return False
# 创建连接
def create_con(self):
# try:
# self.con = pymysql.connect(
# host=self.host,
# port=self.port,
# user=self.user,
# password=self.password,
# database=self.db, charset='utf8')
# self.cursor = self.con.cursor()
# return True
# except Exception as e:
# print(e)
# return False
pass
# 关闭链接
def close_con(self):
if self.cursor:
self.cursor.close()
if self.con:
self.con.close()
# sql执行
def execute_modify(self, sql):
"""
执行插入/更新/删除语句
"""
try:
self.cursor.execute(sql)
self.con.commit()
result = True
except Exception as e:
logging.error(e)
self.con.rollback
result = False
return result
# sql执行 - return all
def execute_select(self, sql):
"""
执行查询语句
"""
try:
self.cursor.execute(sql)
res = self.cursor.fetchall()
return res
except Exception as e:
logging.error(e)
return False
finally:
pass
# sql执行 - return one
def execute_selectOne(self, sql):
"""
执行查询语句
"""
try:
logging.info(sql)
self.cursor.execute(sql)
res = self.cursor.fetchone
return res
except Exception as e:
logging.error(e)
return False
finally:
pass
if __name__ == '__main__':
db = MysqlHelper(DbConect.dj_release_slave)
#添加
# db.execute_sql("insert into user (username, password) values ('username4','password4')")
#修改
# db.execute_sql("update channellist set is_active=1 where id=2")
#查询
selectSql = ("SELECT `end_date` AS '保单到期时间',`sub_device_sn` AS sn "
"FROM dj_insure_order "
"WHERE `deleted_flag` = 'N' AND `insurance_status` IN ('1','6','7') AND `sub_device_sn` IS NOT NULL AND DATE_FORMAT(`end_date`, '%Y-%m')='2022-07' AND LENGTH(`sub_device_sn`)>1 order by `end_date` asc")
print("execute sql:%s" %selectSql)
res = db.execute_select(selectSql)
print(len(res))
cybDb = MysqlHelper(DbConect.cyb_release_DB)
cybSelectSql = 'select * from platform_configuration';
cybRes = cybDb.execute_select(cybSelectSql)
print(len(cybRes))
drop_table_meta=("drop table insu_card_info_", "drop table insu_enddate_device_", "drop table insu_renewl_")
\ No newline at end of file \ No newline at end of file
renewal_select = ("SELECT `end_date` AS '保单到期时间',`sub_device_sn` AS sn "
"FROM dj_insure_order "
"WHERE `deleted_flag` = 'N' AND `insurance_status` IN ('1','6','7') AND `sub_device_sn` IS NOT NULL AND DATE_FORMAT(`end_date`, '%Y-%m')='{}' AND LENGTH(`sub_device_sn`)>1 order by `end_date` asc")
\ No newline at end of file \ No newline at end of file
class StringBuilder:
def __init__(self):
self.strings = []
def append(self, string):
self.strings.append(string)
def __str__(self):
return "".join(self.strings)
\ No newline at end of file \ No newline at end of file
import logging
import pandas as pdas
import os
import chardet
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/cwrenewal/handlexcelmerge.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class HandelCwExcelMergeMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
db = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "dj renewal match iccid and device location"
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.db = MysqlHelper(DbConect.current_month_DB)
def initCurrentMonthTable(self):
logging.info("初始化:删除中间表")
# 判断文件编码
def detect_file_encoding(self, filename):
with open(filename, 'rb') as f:
content = f.read()
result = chardet.detect(content)
return result['encoding']
def dealDeviceEndDateList(self):
return True
# 定义修改函数
def modify_data(self, x):
# 进行批量修改的逻辑
if x is None:
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(self, x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
def exportDataToExcel(self):
# 指定目录路径
directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2022年电商/excelall/'
# 获取目录中的所有文件
files = os.listdir(directory)
# 读取 Excel 文件并合并数据
dataframes_121_01 = []
dataframes_121_02 = []
dataframes_124_01 = []
dataframes_124_02 = []
dataframes_208_01 = []
for file in files:
print("===文件名称:", file)
if file.startswith('1219139301All') :
# file_path = os.path.join(directory, file)
file_path = directory + file
df = pdas.read_csv(file_path, delimiter=',')
dataframes_121_01.append(df)
if file.startswith('1219139301基本') :
# file_path = os.path.join(directory, file)
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode)
dataframes_121_02.append(df)
if (file.startswith('1244414702All') or file.startswith('1414496902All')
or file.startswith('1466262802All') or file.startswith('1480056732All')
or file.startswith('1578954081All') or file.startswith('1623406898All')
):
# file_path = os.path.join(directory, file)
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode)
dataframes_124_01.append(df)
if (file.startswith('1244414702基本') or file.startswith('1414496902基本')
or file.startswith('1466262802基本') or file.startswith('1480056732基本')
or file.startswith('1578954081基本') or file.startswith('1623406898基本')
):
# file_path = os.path.join(directory, file)
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode)
dataframes_124_02.append(df)
if file.startswith('2088411221') :
# file_path = os.path.join(directory, file)
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode, skiprows=2)
dataframes_208_01.append(df)
# 合并所有数据
column_name = '交易状态'
merged_121_01_df = pdas.concat(dataframes_121_01, ignore_index=True)
merged_121_01_df = merged_121_01_df.dropna(subset=[column_name])
merged_121_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2022年电商/excelout/1219139301All_data_2305.xlsx', index=False)
column_name = '收支金额(元)'
merged_121_02_df = pdas.concat(dataframes_121_02, ignore_index=True)
merged_121_02_df = merged_121_02_df.dropna(subset=[column_name])
merged_121_02_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2022年电商/excelout/1219139301基本_data_2305.xlsx', index=False)
column_name = '应结订单金额'
merged_124_01_df = pdas.concat(dataframes_124_01, ignore_index=True)
merged_124_01_df = merged_124_01_df.dropna(subset=[column_name])
merged_124_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2022年电商/excelout/1244414702All_data_2305.xlsx', index=False)
column_name = '收支金额(元)'
merged_124_02_df = pdas.concat(dataframes_124_02, ignore_index=True)
merged_124_02_df = merged_124_02_df.dropna(subset=[column_name])
merged_124_02_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2022年电商/excelout/1244414702基本_data_2305.xlsx', index=False)
column_name = '入账时间'
merged_208_01_df = pdas.concat(dataframes_208_01, ignore_index=True)
merged_208_01_df = merged_208_01_df.dropna(subset=[column_name])
merged_208_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2022年电商/excelout/2088411221_data_2305.xlsx', index=False)
def deleteEmptyData(self):
# 指定目录路径
directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2022年电商/excelout/'
# 获取目录中的所有文件
files = os.listdir(directory)
# 读取 Excel 文件并合并数据
dataframes_121_01 = []
dataframes_121_02 = []
dataframes_124_01 = []
dataframes_124_02 = []
dataframes_208_01 = []
for file in files:
print("===文件名称:", file)
if file.startswith('1219139301All') :
file_path = directory + file
dataframes_121_01 = pdas.read_excel(file_path)
# if file.startswith('1219139301基本') :
# file_path = directory + file
# dataframes_121_02 = pdas.read_excel(file_path)
if file.startswith('1244414702All') :
file_path = directory + file
dataframes_124_01 = pdas.read_excel(file_path)
# if file.startswith('1244414702基本') :
# file_path = directory + file
# dataframes_124_02 = pdas.read_excel(file_path)
if file.startswith('2088411221') :
file_path = directory + file
dataframes_208_01 = pdas.read_excel(file_path)
select_column = ['交易时间','微信订单号','商户订单号','应结订单金额','手续费']
dataframes_121_01_res = dataframes_121_01[select_column]
dataframes_121_01_res['收支类型'] = None
# select_column = ['记账时间','微信支付业务单号','业务凭证号','收支金额(元)','收支类型']
# dataframes_121_02_res = dataframes_121_02[select_column]
# dataframes_121_02_res = dataframes_121_02_res.rename(columns={'记账时间': '交易时间', '微信支付业务单号': '微信订单号', '业务凭证号': '商户订单号', '收支金额(元)': '应结订单金额'})
select_column = ['交易时间','微信订单号','商户订单号','应结订单金额','手续费']
dataframes_124_01_res = dataframes_124_01[select_column]
dataframes_124_01_res['收支类型'] = None
# select_column = ['记账时间','微信支付业务单号','业务凭证号','收支金额(元)','收支类型']
# dataframes_124_02_res = dataframes_124_02[select_column]
# dataframes_124_02_res = dataframes_124_02_res.rename(columns={'记账时间': '交易时间', '微信支付业务单号': '微信订单号', '业务凭证号': '商户订单号', '收支金额(元)': '应结订单金额'})
select_column = ['入账时间','支付宝交易号','业务订单号','收入(+元)','支出(-元)','账务类型']
dataframes_208_01_res = dataframes_208_01[select_column]
dataframes_208_01_res = dataframes_208_01_res.rename(columns={'入账时间': '交易时间', '支付宝交易号': '微信订单号', '业务订单号': '商户订单号', '收入(+元)': '应结订单金额', '支出(-元)': '手续费', '账务类型': '收支类型'})
# 批量修改某一列的数据
dataframes_208_01_res['商户订单号'] = dataframes_208_01_res['商户订单号'].apply(self.modify_data)
res_pd = pdas.concat([dataframes_121_01_res, dataframes_124_01_res, dataframes_208_01_res], axis=0)
res_pd = res_pd[res_pd['应结订单金额'] != '应结订单金额']
res_pd['应结订单金额'] = res_pd['应结订单金额'].apply(self.modify_float_data).astype(float)
res_pd['手续费'] = res_pd['手续费'].apply(self.modify_float_data).astype(float)
res_pd.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2022年电商/excelout/merge_All_data_2305.xlsx', index=False)
if __name__ == "__main__":
handle_month = '2023-05'
dedRes = False
diRes = False
urRes = False
#启动初始化
handleMain = HandelCwExcelMergeMain(handle_month)
logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)
# 整理数据
#handleMain.dealTheMonthData()
#将结果输出到excel
# handleMain.exportDataToExcel()
handleMain.deleteEmptyData()
import logging
import pandas as pdas
import os
import chardet
import math
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/cwrenewal/handlexcelmerge2019.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class HandelCwExcelMergeMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
db = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "dj renewal match iccid and device location"
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.db = MysqlHelper(DbConect.current_month_DB)
def initCurrentMonthTable(self):
logging.info("初始化:删除中间表")
# 判断文件编码
def detect_file_encoding(self, filename):
with open(filename, 'rb') as f:
content = f.read()
result = chardet.detect(content)
return result['encoding']
def dealDeviceEndDateList(self):
return True
# 定义修改函数
def modify_data(self, x):
# 进行批量修改的逻辑
if (x is None or math.isnan(x)):
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(self, x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
def exportDataToExcel(self):
# 指定目录路径
directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelall/'
# 获取目录中的所有文件
files = os.listdir(directory)
# 读取 Excel 文件并合并数据
dataframes_121_01 = []
dataframes_121_02 = []
dataframes_124_01 = []
dataframes_124_02 = []
dataframes_208_01 = []
dataframes_208_02 = []
for file in files:
print("===文件名称:", file)
if file.startswith('支付宝') :
if file=='支付宝账户明细.csv':
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode, skiprows=4)
dataframes_208_01.append(df)
elif (file.endswith('csv')):
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode, skiprows=2)
dataframes_208_01.append(df)
else:
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_excel(file_path, skiprows=2)
dataframes_208_02.append(df)
else:
if (file.endswith('csv')):
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode)
dataframes_124_01.append(df)
else:
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_excel(file_path)
dataframes_124_01.append(df)
# 合并所有数据
column_name = '应结订单金额'
merged_124_01_df = pdas.concat(dataframes_124_01, ignore_index=True)
merged_124_01_df = merged_124_01_df.dropna(subset=[column_name])
merged_124_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/1244414702All_data_2305.xlsx', index=False)
column_name = '入账时间'
# merged_208_01_df = pdas.concat(dataframes_208_01, ignore_index=True)
# merged_208_01_df = merged_208_01_df.dropna(subset=[column_name])
# merged_208_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/2088411221_zhi1data_2305.xlsx', index=False)
column_name = '入账时间'
merged_208_02_df = pdas.concat(dataframes_208_02, ignore_index=True)
merged_208_02_df = merged_208_02_df.dropna(subset=[column_name])
merged_208_02_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/2088411221_zhi2data_2305.xlsx', index=False)
def deleteEmptyData(self):
# 指定目录路径
directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/'
# 获取目录中的所有文件
files = os.listdir(directory)
# 读取 Excel 文件并合并数据
dataframes_121_01 = []
dataframes_121_02 = []
dataframes_124_01 = []
dataframes_124_02 = []
dataframes_208_01 = []
for file in files:
print("===文件名称:", file)
if file.startswith('1244414702All') :
file_path = directory + file
dataframes_124_01 = pdas.read_excel(file_path)
if file.startswith('2088411221') :
file_path = directory + file
dataframes_208_01 = pdas.read_excel(file_path)
select_column = ['交易时间','微信订单号','商户订单号','应结订单金额','手续费']
dataframes_124_01_res = dataframes_124_01[select_column]
dataframes_124_01_res['收支类型'] = None
select_column = ['入账时间','支付宝交易号','业务订单号','收入(+元)','支出(-元)','账务类型']
dataframes_208_01_res = dataframes_208_01[select_column]
dataframes_208_01_res = dataframes_208_01_res.rename(columns={'入账时间': '交易时间', '支付宝交易号': '微信订单号', '业务订单号': '商户订单号', '收入(+元)': '应结订单金额', '支出(-元)': '手续费', '账务类型': '收支类型'})
# 批量修改某一列的数据
dataframes_208_01_res['商户订单号'] = dataframes_208_01_res['商户订单号'].apply(self.modify_data)
res_pd = pdas.concat([dataframes_124_01_res, dataframes_208_01_res], axis=0)
res_pd = res_pd[res_pd['应结订单金额'] != '应结订单金额']
res_pd['应结订单金额'] = res_pd['应结订单金额'].apply(self.modify_float_data).astype(float)
res_pd['手续费'] = res_pd['手续费'].apply(self.modify_float_data).astype(float)
res_pd.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2019年电商/excelout/merge_2019All_data_2305.xlsx', index=False)
if __name__ == "__main__":
handle_month = '2023-05'
dedRes = False
diRes = False
urRes = False
#启动初始化
handleMain = HandelCwExcelMergeMain(handle_month)
logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)
# 整理数据
#handleMain.dealTheMonthData()
#将结果输出到excel
# handleMain.exportDataToExcel()
handleMain.deleteEmptyData()
import logging
import pandas as pdas
import os
import chardet
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/cwrenewal/handlexcelmerge2020.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class HandelCwExcelMergeMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
db = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "dj renewal match iccid and device location"
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.db = MysqlHelper(DbConect.current_month_DB)
def initCurrentMonthTable(self):
logging.info("初始化:删除中间表")
# 判断文件编码
def detect_file_encoding(self, filename):
with open(filename, 'rb') as f:
content = f.read()
result = chardet.detect(content)
return result['encoding']
def dealDeviceEndDateList(self):
return True
# 定义修改函数
def modify_data(self, x):
# 进行批量修改的逻辑
if x is None:
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(self, x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
def exportDataToExcel(self):
# 指定目录路径
directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2020年电商/excelall/'
# 获取目录中的所有文件
files = os.listdir(directory)
# 读取 Excel 文件并合并数据
dataframes_121_01 = []
dataframes_121_02 = []
dataframes_124_01 = []
dataframes_124_02 = []
dataframes_208_01 = []
for file in files:
print("===文件名称:", file)
if (file.startswith('109All') or file.startswith('10014015_10037109All')
or file.startswith('10037109All') or file.startswith('1219139301All')
or file.startswith('1230909502All') or file.startswith('1232525202All')
or file.startswith('1244414702All') or file.startswith('1414496902All') or file.startswith('1251712801All')
or file.startswith('1466262802All') or file.startswith('1480056732All')
or file.startswith('1578954081All') or file.startswith('180000')
):
# file_path = os.path.join(directory, file)
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode)
dataframes_124_01.append(df)
if file.startswith('2088411221') :
# file_path = os.path.join(directory, file)
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode, skiprows=2)
dataframes_208_01.append(df)
# 合并所有数据
column_name = '应结订单金额'
merged_124_01_df = pdas.concat(dataframes_124_01, ignore_index=True)
merged_124_01_df = merged_124_01_df.dropna(subset=[column_name])
merged_124_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2020年电商/excelout/1244414702All_data_2305.xlsx', index=False)
column_name = '入账时间'
merged_208_01_df = pdas.concat(dataframes_208_01, ignore_index=True)
merged_208_01_df = merged_208_01_df.dropna(subset=[column_name])
merged_208_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2020年电商/excelout/2088411221_data_2305.xlsx', index=False)
def deleteEmptyData(self):
# 指定目录路径
directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2020年电商/excelout/'
# 获取目录中的所有文件
files = os.listdir(directory)
# 读取 Excel 文件并合并数据
dataframes_121_01 = []
dataframes_121_02 = []
dataframes_124_01 = []
dataframes_124_02 = []
dataframes_208_01 = []
for file in files:
print("===文件名称:", file)
if file.startswith('1244414702All') :
file_path = directory + file
dataframes_124_01 = pdas.read_excel(file_path)
if file.startswith('2088411221') :
file_path = directory + file
dataframes_208_01 = pdas.read_excel(file_path)
select_column = ['交易时间','微信订单号','商户订单号','应结订单金额','手续费']
dataframes_124_01_res = dataframes_124_01[select_column]
dataframes_124_01_res['收支类型'] = None
select_column = ['入账时间','支付宝交易号','业务订单号','收入(+元)','支出(-元)','账务类型']
dataframes_208_01_res = dataframes_208_01[select_column]
dataframes_208_01_res = dataframes_208_01_res.rename(columns={'入账时间': '交易时间', '支付宝交易号': '微信订单号', '业务订单号': '商户订单号', '收入(+元)': '应结订单金额', '支出(-元)': '手续费', '账务类型': '收支类型'})
# 批量修改某一列的数据
dataframes_208_01_res['商户订单号'] = dataframes_208_01_res['商户订单号'].apply(self.modify_data)
res_pd = pdas.concat([dataframes_124_01_res, dataframes_208_01_res], axis=0)
res_pd = res_pd[res_pd['应结订单金额'] != '应结订单金额']
res_pd['应结订单金额'] = res_pd['应结订单金额'].apply(self.modify_float_data).astype(float)
res_pd['手续费'] = res_pd['手续费'].apply(self.modify_float_data).astype(float)
res_pd.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2020年电商/excelout/merge_2020All_data_2305.xlsx', index=False)
if __name__ == "__main__":
handle_month = '2023-05'
dedRes = False
diRes = False
urRes = False
#启动初始化
handleMain = HandelCwExcelMergeMain(handle_month)
logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)
# 整理数据
#handleMain.dealTheMonthData()
#将结果输出到excel
# handleMain.exportDataToExcel()
handleMain.deleteEmptyData()
import logging
import pandas as pdas
import os
import chardet
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/cwrenewal/handlexcelmerge2021.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class HandelCwExcelMergeMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
db = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "dj renewal match iccid and device location"
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.db = MysqlHelper(DbConect.current_month_DB)
def initCurrentMonthTable(self):
logging.info("初始化:删除中间表")
# 判断文件编码
def detect_file_encoding(self, filename):
with open(filename, 'rb') as f:
content = f.read()
result = chardet.detect(content)
return result['encoding']
def dealDeviceEndDateList(self):
return True
# 定义修改函数
def modify_data(self, x):
# 进行批量修改的逻辑
if x is None:
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(self, x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
def exportDataToExcel(self):
# 指定目录路径
directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2021年电商/excelall/'
# 获取目录中的所有文件
files = os.listdir(directory)
# 读取 Excel 文件并合并数据
dataframes_121_01 = []
dataframes_121_02 = []
dataframes_124_01 = []
dataframes_124_02 = []
dataframes_208_01 = []
for file in files:
print("===文件名称:", file)
if (file.startswith('109All') or file.startswith('10014015_10037109All')
or file.startswith('10037109All') or file.startswith('1219139301All')
or file.startswith('1230909502All') or file.startswith('1232525202All')
or file.startswith('1244414702All') or file.startswith('1414496902All') or file.startswith('1251712801All')
or file.startswith('1466262802All') or file.startswith('1480056732All')
or file.startswith('1578954081All') or file.startswith('180000')
):
# file_path = os.path.join(directory, file)
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode)
dataframes_124_01.append(df)
if file.startswith('2088411221') :
# file_path = os.path.join(directory, file)
file_path = directory + file
file_encode = self.detect_file_encoding(file_path)
df = pdas.read_csv(file_path, delimiter=',', encoding=file_encode, skiprows=2)
dataframes_208_01.append(df)
# 合并所有数据
column_name = '应结订单金额'
merged_124_01_df = pdas.concat(dataframes_124_01, ignore_index=True)
merged_124_01_df = merged_124_01_df.dropna(subset=[column_name])
merged_124_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2021年电商/excelout/1244414702All_data_2305.xlsx', index=False)
column_name = '入账时间'
merged_208_01_df = pdas.concat(dataframes_208_01, ignore_index=True)
merged_208_01_df = merged_208_01_df.dropna(subset=[column_name])
merged_208_01_df.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2021年电商/excelout/2088411221_data_2305.xlsx', index=False)
def deleteEmptyData(self):
# 指定目录路径
directory = 'D:/work_doc/000 - 审计/续费数据-商城续费/2021年电商/excelout/'
# 获取目录中的所有文件
files = os.listdir(directory)
# 读取 Excel 文件并合并数据
dataframes_121_01 = []
dataframes_121_02 = []
dataframes_124_01 = []
dataframes_124_02 = []
dataframes_208_01 = []
for file in files:
print("===文件名称:", file)
if file.startswith('1244414702All') :
file_path = directory + file
dataframes_124_01 = pdas.read_excel(file_path)
if file.startswith('2088411221') :
file_path = directory + file
dataframes_208_01 = pdas.read_excel(file_path)
select_column = ['交易时间','微信订单号','商户订单号','应结订单金额','手续费']
dataframes_124_01_res = dataframes_124_01[select_column]
dataframes_124_01_res['收支类型'] = None
select_column = ['入账时间','支付宝交易号','业务订单号','收入(+元)','支出(-元)','账务类型']
dataframes_208_01_res = dataframes_208_01[select_column]
dataframes_208_01_res = dataframes_208_01_res.rename(columns={'入账时间': '交易时间', '支付宝交易号': '微信订单号', '业务订单号': '商户订单号', '收入(+元)': '应结订单金额', '支出(-元)': '手续费', '账务类型': '收支类型'})
# 批量修改某一列的数据
dataframes_208_01_res['商户订单号'] = dataframes_208_01_res['商户订单号'].apply(self.modify_data)
res_pd = pdas.concat([dataframes_124_01_res, dataframes_208_01_res], axis=0)
res_pd = res_pd[res_pd['应结订单金额'] != '应结订单金额']
res_pd['应结订单金额'] = res_pd['应结订单金额'].apply(self.modify_float_data).astype(float)
res_pd['手续费'] = res_pd['手续费'].apply(self.modify_float_data).astype(float)
res_pd.to_excel('D:/work_doc/000 - 审计/续费数据-商城续费/2021年电商/excelout/merge_2021All_data_2305.xlsx', index=False)
if __name__ == "__main__":
handle_month = '2023-05'
dedRes = False
diRes = False
urRes = False
#启动初始化
handleMain = HandelCwExcelMergeMain(handle_month)
logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)
# 整理数据
#handleMain.dealTheMonthData()
#将结果输出到excel
handleMain.exportDataToExcel()
# handleMain.deleteEmptyData()
import logging
import pandas as pdas
import os
import chardet
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/cwrenewal/handlexcelmerge.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class HandelCwExcelMergeMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
db = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "dj renewal match iccid and device location"
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.db = MysqlHelper(DbConect.current_month_DB)
def initCurrentMonthTable(self):
logging.info("初始化:删除中间表")
# 判断文件编码
def detect_file_encoding(self, filename):
with open(filename, 'rb') as f:
content = f.read()
result = chardet.detect(content)
return result['encoding']
def dealDeviceEndDateList(self):
return True
# 定义修改函数
def modify_data(self, x):
# 进行批量修改的逻辑
if x is None:
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(self, x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
def exportDataToExcel(self):
# 指定目录路径
directory = 'D:\\work_doc\\003 - 商务脚本\\11111111111111.xlsx'
df = pdas.read_excel(directory)
print(df)
df.iat[3,3] = '深圳广联赛讯'
df.to_excel('D:\\work_doc\\003 - 商务脚本\\dev_test\\11111111111111.xlsx', index=False)
if __name__ == "__main__":
handle_month = '2023-05'
dedRes = False
diRes = False
urRes = False
#启动初始化
handleMain = HandelCwExcelMergeMain(handle_month)
logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)
#将结果输出到excel
handleMain.exportDataToExcel()
# 定义修改函数
def modify_data(x):
# 进行批量修改的逻辑
if x is None:
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
#---------------执行Main----------------
order_code = 'M{202201291647148133}'
order_code = modify_data(order_code);
print(order_code)
order_price = ''
order_p = modify_float_data(order_price)
print(order_p)
import logging
import pandas as pdas
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/djcardrenewal/handlemain.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class HandelMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
djdb = None
plusDb = None
yearArray = ['2020','2021','2022']
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "dj renewal match iccid and device location"
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.djdb = MysqlHelper(DbConect.DB_shen_release_dj)
self.plusDb = MysqlHelper(DbConect.DB_shen_release_plus)
#------1 1.1转化店面数据 ------
def dealTransformMerchant(self):
for yearline in self.yearArray:
selectSql = f'''SELECT COUNT(DISTINCT (CASE WHEN b.`sub_shop_merchant_id` THEN b.`sub_shop_merchant_id` ELSE b.`merchant_id` END)) AS '数量'
FROM `dj_car_life_goods_sub_order` a
INNER JOIN `dj_car_life_goods_order` b ON b.`order_code`=a.`order_code`
LEFT JOIN `dj_car_life_order_expense_category_calculated` d ON d.sub_order_code=a.sub_order_code
LEFT JOIN `dj_car_life_goods` e ON e.`id`=a.`goods_id`
LEFT JOIN `temp_dj_car_life_pricetype` f ON f.`id`=a.`id`
WHERE DATE_FORMAT(b.`success_date`, '%Y')='{yearline}' AND e.`business_scene_type`=1 AND b.`upgrade_flag`='Y'
;'''
merData = self.plusDb.execute_select(selectSql)
print("---Plus_1.1转化 %s 商户数:%s" % (yearline, merData[0][0]))
return True
#------1 1.3众筹 ------
def dealDyEquitMerchant(self):
for yearline in self.yearArray:
selectSql = f'''SELECT count(distinct b.`merchant_id`) FROM `shopmall_order` a
LEFT JOIN `shopmall_activity_info` b ON b.`activity_id`=a.`activity_id` AND a.source=b.source
WHERE a.`marketing_status`=1 and DATE_FORMAT(a.`created_date`, '%Y')='{yearline}'
;'''
merData = self.plusDb.execute_select(selectSql)
print("---Plus_1.3众筹 %s 商户数:%s" % (yearline, merData[0][0]))
return True
#------1 合并 ------
def dealDyXsAndEqMerchant(self):
for yearline in self.yearArray:
selectSql = f'''select count(distinct aat.merchantId) from (
SELECT DISTINCT (CASE WHEN b.`sub_shop_merchant_id` THEN b.`sub_shop_merchant_id` ELSE b.`merchant_id` END) as merchantId
FROM `dj_car_life_goods_sub_order` a
INNER JOIN `dj_car_life_goods_order` b ON b.`order_code`=a.`order_code`
LEFT JOIN `dj_car_life_order_expense_category_calculated` d ON d.sub_order_code=a.sub_order_code
LEFT JOIN `dj_car_life_goods` e ON e.`id`=a.`goods_id`
LEFT JOIN `temp_dj_car_life_pricetype` f ON f.`id`=a.`id`
WHERE DATE_FORMAT(b.`success_date`, '%Y')='{yearline}' AND e.`business_scene_type`=1 AND b.`upgrade_flag`='Y'
UNION ALL
SELECT distinct b.`merchant_id` as merchantId FROM `shopmall_order` a
LEFT JOIN `shopmall_activity_info` b ON b.`activity_id`=a.`activity_id` AND a.source=b.source
WHERE a.`marketing_status`=1 and DATE_FORMAT(a.`created_date`, '%Y')='{yearline}'
) aat
;'''
merData = self.plusDb.execute_select(selectSql)
print("---Plus_合并 %s 商户数:%s" % (yearline, merData[0][0]))
return True
#------2 saasPlus在订阅中开展业务的店面数 ------
def dealPlusInnerDyMerchant(self):
return True
#------2 saasPlus在订阅中开展业务的店面数 ------
def dealPlusMergeDyMerchant(self):
return True
def proxySaasPlusMerchantCount(self):
# 处理 1.1转化业务
xsRes = False
xsRes = handleMain.dealTransformMerchant()
logging.info(f'===Plus1.1转化:{xsRes}')
# 处理 1.3众筹业务
qyRes = False
qyRes = handleMain.dealDyEquitMerchant()
logging.info(f'===Plus1.3众筹:{qyRes}')
# 合并数据
hbRes = False
hbRes = handleMain.dealDyXsAndEqMerchant()
logging.info(f'===Plus合并处理OK:{hbRes}')
def proxyXXXMerchantCount(self):
# 处理 xxx
xsRes = False
xsRes = handleMain.dealPlusInnerDyMerchant()
logging.info(f'===xxx:{xsRes}')
# 合并数据
hbRes = False
hbRes = handleMain.dealPlusMergeDyMerchant()
logging.info(f'===xxx合并处理OK:{hbRes}')
if __name__ == "__main__":
handle_month = '2022-12'
dedRes = False
diRes = False
urRes = False
#启动初始化
handleMain = HandelMain(handle_month)
logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)
# 输出店面数据
handleMain.proxySaasPlusMerchantCount()
# 输出XXX店面数据
# handleMain.proxyXXXMerchantCount()
import logging
import pandas as pdas
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/djcardrenewal/handlemain.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class HandelMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
djdb = None
plusDb = None
yearArray = ['2020','2021','2022']
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "dj renewal match iccid and device location"
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.djdb = MysqlHelper(DbConect.DB_shen_release_dj)
self.plusDb = MysqlHelper(DbConect.DB_shen_release_plus)
#------1 线索 ------
def dealDyXiansuoMerchant(self):
for yearline in self.yearArray:
selectSql = f'''SELECT count(distinct dsm.merchant_id)
FROM dj_device_details d LEFT JOIN dj_system_merchant dsm ON d.active_merchant =dsm.merchant_name
WHERE active_merchant <> '' AND
((active_time < '{yearline}-01-01 00:00:00' AND DATE_ADD(active_time,INTERVAL pk_period MONTH) > '{yearline}-01-01 00:00:00') OR
(active_time >= '{yearline}-01-01 00:00:00' AND active_time < '{yearline}-12-31 23:59:59'))
;'''
merData = self.djdb.execute_select(selectSql)
print("---订阅_线索 %s 商户数:%s" % (yearline, merData[0][0]))
return True
#------1 权益 ------
def dealDyEquitMerchant(self):
for yearline in self.yearArray:
selectSql = f'''SELECT count(DISTINCT merchant_id )
FROM equity_order
WHERE DATE_ADD(success_date,INTERVAL 12 MONTH)>'{yearline}-01-01 00:00:00' and success_date<'{yearline}-12-31 23:59:59'
;'''
merData = self.djdb.execute_select(selectSql)
print("---订阅_权益 %s 商户数:%s" % (yearline, merData[0][0]))
return True
#------1 合并 ------
def dealDyXsAndEqMerchant(self):
for yearline in self.yearArray:
selectSql = f'''SELECT COUNT(DISTINCT aat.merchant_id) FROM (
SELECT DISTINCT dsm.merchant_id
FROM dj_device_details d LEFT JOIN dj_system_merchant dsm ON d.active_merchant =dsm.merchant_name
WHERE active_merchant <> '' AND
((active_time < '{yearline}-01-01 00:00:00' AND DATE_ADD(active_time,INTERVAL pk_period MONTH) > '{yearline}-01-01 00:00:00') OR
(active_time >= '{yearline}-01-01 00:00:00' AND active_time < '{yearline}-12-31 23:59:59'))
UNION ALL
SELECT DISTINCT merchant_id
FROM equity_order
WHERE DATE_ADD(success_date,INTERVAL 12 MONTH)>'{yearline}-01-01 00:00:00' AND success_date<'{yearline}-12-31 23:59:59'
) aat
;'''
merData = self.djdb.execute_select(selectSql)
print("---订阅_合并 %s 商户数:%s" % (yearline, merData[0][0]))
return True
#------2 saasPlus在订阅中开展业务的店面数 ------
def dealPlusInnerDyMerchant(self):
for yearline in self.yearArray:
selectSql = f'''SELECT COUNT(*) FROM `temp_saasplus_bus_merchant_22` aat WHERE aat.`merchant_id` IN (
SELECT DISTINCT merchant_id AS merId
FROM (
SELECT DISTINCT dsm.merchant_id
FROM glsx_data.dj_device_details d LEFT JOIN dj_system_merchant dsm ON d.active_merchant =dsm.merchant_name
WHERE active_merchant <> '' AND
((active_time < '{yearline}-01-01 00:00:00' AND DATE_ADD(active_time,INTERVAL pk_period MONTH) > '{yearline}-01-01 00:00:00') OR
(active_time >= '{yearline}-01-01 00:00:00' AND active_time < '{yearline}-12-31 23:59:59'))
UNION ALL
SELECT DISTINCT merchant_id
FROM equity_order
WHERE YEAR(success_date) ='{yearline}'
) a
) AND aat.`bus_year`={yearline}
;'''
merData = self.djdb.execute_select(selectSql)
print("---SAASPLUS_Inner %s 商户数:%s" % (yearline, merData[0][0]))
return True
#------2 saasPlus在订阅中开展业务的店面数 ------
def dealPlusMergeDyMerchant(self):
for yearline in self.yearArray:
selectSql = f'''SELECT count(DISTINCT aat.merchant_id)
FROM (
SELECT (CASE WHEN dsm.merchant_id THEN dsm.merchant_id ELSE 1 END) merchant_id
FROM glsx_data.dj_device_details d LEFT JOIN dj_system_merchant dsm ON d.active_merchant =dsm.merchant_name
WHERE active_merchant <> '' AND dsm.`merchant_id` IS NOT NULL AND
((active_time < '{yearline}-01-01 00:00:00' AND DATE_ADD(active_time,INTERVAL pk_period MONTH) > '{yearline}-01-01 00:00:00') OR
(active_time >= '{yearline}-01-01 00:00:00' AND active_time < '{yearline}-12-31 23:59:59'))
UNION ALL
SELECT DISTINCT merchant_id
FROM equity_order
WHERE DATE_ADD(success_date,INTERVAL 12 MONTH)>'{yearline}-01-01 00:00:00' AND success_date<'{yearline}-12-31 23:59:59'
UNION ALL
SELECT merchant_id FROM `temp_saasplus_bus_merchant_22` WHERE `bus_year`={yearline}
) aat
;'''
merData = self.djdb.execute_select(selectSql)
print("---SAASPLUS_合并订阅 %s 商户数:%s" % (yearline, merData[0][0]))
return True
def proxySaasDYMerchantCount(self):
# 处理 订阅数据
xsRes = False
xsRes = handleMain.dealDyXiansuoMerchant()
logging.info(f'===订阅线索:{xsRes}')
# 处理 权益数据
qyRes = False
qyRes = handleMain.dealDyEquitMerchant()
logging.info(f'===订阅权益:{qyRes}')
# 合并数据
hbRes = False
hbRes = handleMain.dealDyXsAndEqMerchant()
logging.info(f'===订阅合并处理OK:{hbRes}')
def proxyDyAndSaasPlusMerchantCount(self):
# 处理 SAAS_PLUS在订阅中有业务的店面数
xsRes = False
xsRes = handleMain.dealPlusInnerDyMerchant()
logging.info(f'===PLUS_inner:{xsRes}')
# 合并数据
hbRes = False
hbRes = handleMain.dealPlusMergeDyMerchant()
logging.info(f'===PLUS订阅合并处理OK:{hbRes}')
if __name__ == "__main__":
handle_month = '2022-12'
dedRes = False
diRes = False
urRes = False
#启动初始化
handleMain = HandelMain(handle_month)
logging.info("start handle" + handleMain.handleDescription + ' the month:' + handleMain.handleMonth)
# 输出店面数据
# handleMain.proxySaasDYMerchantCount()
# 输出SAAS+与DJ重叠业务的店面数据
handleMain.proxyDyAndSaasPlusMerchantCount()
import logging
import pandas as pdas
import os
import chardet
import datetime
import openpyxl
from openpyxl import Workbook
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/supplychain/dealSendSomeList.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class DealSupplychainSomeListMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
db = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "供应链批量打印发货单需求脚本执行..."
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
#self.db = MysqlHelper(DbConect.current_month_DB)
def initCurrentMonthTable(self):
logging.info("初始化:暂无操作")
# 判断文件编码
def detect_file_encoding(self, filename):
with open(filename, 'rb') as f:
content = f.read()
result = chardet.detect(content)
return result['encoding']
def dealDeviceEndDateList(self):
return True
# 定义修改函数
def modify_data(self, x):
# 进行批量修改的逻辑
if x is None:
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(self, x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
# 定义修改函数
def dealSendDate(self, sendDate):
# 进行批量修改的逻辑
if ',' in sendDate:
return sendDate.split(',')[0]
return sendDate
# 定义修改函数
def dealReadSendMapper(self, dataframes_source):
sendMapper = {}
currentKey = {}
splitSize = 0
for drow in dataframes_source.itertuples():
# print(f'[DEBUG] {drow}')
# 需求: 根据发货清单明细:(同一 下单客户,同一 发货时间,同一 出库仓库,同一 收货 联系人,收货 联系地址,同一 审核人,同一 结算主体),可打印在一张送货单
sendDate = datetime.datetime.strptime(self.dealSendDate(drow.发货时间), "%Y-%m-%d %H:%M:%S")
mapkey = "cus:%s,date:%s,stor:%s,peo:%s,add:%s,check:%s,main:%s" % (drow.下单客户, sendDate.strftime("%Y-%m-%d"), drow.出库仓库, drow.联系人, drow.联系地址, drow.审核人, drow.结算主体)
curMapkey = currentKey.get(mapkey)
if curMapkey is None:
currentKey[mapkey] = mapkey
curMapkey = mapkey
# print(f'[DEBUG] curMapkey:{curMapkey}')
dataList = sendMapper.get(curMapkey)
# 每个key包含6条数据,超过6条后用新的key存储
if dataList is not None and len(dataList)==5:
curMapkey = "%s_%s" % (mapkey, splitSize)
currentKey[mapkey] = curMapkey
if dataList is None:
dataList = []
dataList.append(drow)
sendMapper[curMapkey] = dataList
else:
dataList.append(drow)
splitSize+=1
return sendMapper
# 定义修改函数
def dealStorePeopleMapper(self):
storePeopleMapper = {}
storePeople_dataframes = pdas.read_excel('D:\\work_doc\\003 - 商务脚本\\仓别-发研发.xlsx', skiprows=1)
for drow in storePeople_dataframes.itertuples():
# print(f'[DEBUG] {drow}')
key1 = drow._2 + '2021制单人'
key2 = drow._2 + '2021发货人'
key3 = drow._2 + '2022制单人'
key4 = drow._2 + '2022发货人'
key5 = drow._2 + '2023制单人'
key6 = drow._2 + '2023发货人'
storePeopleMapper[key1] = drow.制单人
storePeopleMapper[key2] = drow.发货人
storePeopleMapper[key3] = drow._5
storePeopleMapper[key4] = drow._6
storePeopleMapper[key5] = drow._7
storePeopleMapper[key6] = drow._8
return storePeopleMapper
def dealDataToExcel(self, sourceFile, exportPath, module_file_path, dealContentPath):
# 读取 Excel 文件
dataframes_source = pdas.read_excel(sourceFile)
# 读取原始数据:
# 每个mapper value代表一个发货单(每个发货单最大6条发货信息),
# mapper key按照商务需求+数值的方式确保唯一用来表示一张发货单(业务操作中不会用到 mapper key,只是用来将原始数据分割成一个一个的 mapper value)
sendMapper = self.dealReadSendMapper(dataframes_source)
print('文件任务总数:%s' % len(sendMapper))
# 不再使用pandas读取模板数据,换成后面的openpyxl default_dataframes = pdas.read_excel(module_file_path, sheet_name='发货签收单模板')
mainMapper = {'广联数科': '深圳广联数科科技有限公司','广联赛讯': '深圳广联赛讯股份有限公司','嘀加智慧云': '深圳市嘀加智慧云服务有限公司'}
storePeopleMapper = self.dealStorePeopleMapper()
dealindex = 0
orderNumMapper = {}
expSizeMapper = {}
dataframes_source['自动生成单号'] = '-'
# 打开模板文件
curWorkBook = openpyxl.load_workbook(module_file_path)
for sendKey,sendList in sendMapper.items():
oneRow = sendList[0]
# 供货方
mainName = mainMapper.get(oneRow.结算主体)
# 发货日期
sendDate = datetime.datetime.strptime(self.dealSendDate(oneRow.发货时间), "%Y-%m-%d %H:%M:%S")
# 发货单号
sendDateStr = sendDate.strftime("%Y-%m-%d")
orYear = sendDate.strftime("%Y")
# 每天的订单进行序号递增,并使用mapper存储
orkey = sendDate.strftime("%Y%m%d")
orderNum = orderNumMapper.get(orkey)
if orderNum is None:
orderNum = (int(orkey) * 10000)
orderNum+=1
orderNumMapper[orkey] = orderNum
sendOrderCode = str(orderNum)
# 收货方
reciverCustomer = oneRow.下单客户
# 收货地址
reciverAdd = oneRow.联系地址
# 收货人
reciverPeople = oneRow.联系人
# 收货人电话
reciverPeopleMobile = str(oneRow.联系电话)
# 发货仓
sendStore = oneRow.出库仓库
curSheet = curWorkBook.active
# ---清空内存中的表格 start---
curSheet['C3'] = ''
curSheet['H3'] = ''
curSheet['J3'] = ''
curSheet['C4'] = ''
curSheet['I4'] = ''
curSheet['C5'] = ''
curSheet['I5'] = ''
curSheet['J5'] = ''
loopList = [7,8,9,10,11,12]
for loopItem in loopList:
curSheet[f'C{loopItem}'] = ''
curSheet[f'D{loopItem}'] = ''
curSheet[f'E{loopItem}'] = ''
curSheet[f'G{loopItem}'] = ''
curSheet[f'H{loopItem}'] = ''
curSheet[f'I{loopItem}'] = ''
curSheet[f'I{loopItem}'] = ''
curSheet['C14'] = ''
curSheet['F14'] = ''
# ---清空内存中的表格 END---
curSheet['C3'] = mainName
curSheet['H3'] = sendDateStr
curSheet['J3'] = sendOrderCode
curSheet['C4'] = reciverCustomer
curSheet['I4'] = sendStore
curSheet['C5'] = reciverAdd
curSheet['I5'] = reciverPeople
curSheet['J5'] = reciverPeopleMobile
loopIndex = 7
for sendRow in sendList:
# 物料编码
marterCode = sendRow.实发物料编码
# 销售编码
saleMarterCode = sendRow.订单物料编码
# 产品名称
productName = sendRow.实发物料名称
# 子订单号
childOrderCode = sendRow.子订单号
# 数量
orderCount = sendRow.已发数量
# 备注
lineRemark = sendRow.发货单号
# 制单人
mlpKey = f'{sendRow.出库仓库}{orYear}制单人'
markListPeople = storePeopleMapper.get(mlpKey)
# 发货人
slpKey = f'{sendRow.出库仓库}{orYear}发货人'
sendListPeople = storePeopleMapper.get(slpKey)
curSheet[f'C{loopIndex}'] = marterCode
curSheet[f'D{loopIndex}'] = saleMarterCode
curSheet[f'E{loopIndex}'] = productName
curSheet[f'G{loopIndex}'] = childOrderCode
curSheet[f'H{loopIndex}'] = orderCount
curSheet[f'I{loopIndex}'] = lineRemark
curSheet[f'I{loopIndex}'] = lineRemark
curSheet['C14'] = markListPeople
curSheet['F14'] = sendListPeople
loopIndex+=1
# 在源文件中增加列:自动生成单号
dataframes_source.loc[dataframes_source['发货单号'] == sendRow.发货单号, '自动生成单号'] = sendOrderCode
# 同订单号计数
expSize = expSizeMapper.get(sendOrderCode)
if expSize is None:
expSize = 0
expSize+=1
expSizeMapper[sendOrderCode] = expSize
orderNumValue = "%s_%s" % (sendOrderCode, expSize)
exPath = "%s%s_%s.xlsx" % (exportPath, orderNumValue, reciverCustomer)
# write_dataframes.to_excel(exPath, index=False)
curWorkBook.save(exPath)
dealindex+=1
print('[%s] 生成文件索引:%s' % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), dealindex))
# 关闭openpyxl的IO流操作
curWorkBook.close()
# 将源文件写出到新文件
sourceExportFilePath = f'{exportPath}exportsource_{dealContentPath}.xlsx'
dataframes_source.to_excel(sourceExportFilePath, index=False)
if __name__ == "__main__":
handle_month = '2021-2023'
dedRes = False
diRes = False
urRes = False
print('==========================按单个文件跑数据==========================')
#启动初始化
dealMain = DealSupplychainSomeListMain(handle_month)
logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)
defaultExportPath = 'D:/work_doc/003 - 商务脚本/'
module_file_path = 'D:/work_doc/003 - 商务脚本/发货签收单-模板-rel.xlsx'
# dealContentPath = 'test'
# sourceFile = 'D:/work_doc/003 - 商务脚本/678018835261169664_商务订单 - 222.xlsx'
dealContentPath = 'export_2023年1月'
sourceFile = 'D:/work_doc/003 - 商务脚本/商务订单-2023年1月-系统导出.xlsx'
exportPath = defaultExportPath + '' + dealContentPath + '/'
# 处理核心逻辑
dealMain.dealDataToExcel(sourceFile, exportPath, module_file_path, dealContentPath)
import logging
import pandas as pdas
import os
import chardet
import datetime
import re
import openpyxl
from openpyxl import Workbook
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/supplychain/dealSendSomeList.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class DealSupplychainSomeListMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
module_file_path = ''
defaultExportReleasePath = ''
db = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "供应链批量打印发货单需求脚本执行..."
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
#self.db = MysqlHelper(DbConect.current_month_DB)
def initCurrentMonthTable(self):
logging.info("初始化:暂无操作")
# 判断文件编码
def detect_file_encoding(self, filename):
with open(filename, 'rb') as f:
content = f.read()
result = chardet.detect(content)
return result['encoding']
def dealDeviceEndDateList(self):
return True
# 定义修改函数
def modify_data(self, x):
# 进行批量修改的逻辑
if x is None:
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(self, x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
# 定义修改函数
def dealSendDate(self, sendDate):
# 去除字符串中的汉字
sendDate = re.sub(r'[\u4e00-\u9fa5]', '', sendDate)
# 进行批量修改的逻辑
if ',' in sendDate:
return sendDate.split(',')[0]
if len(sendDate)<19:
sendDate = sendDate + ' 00:00:00'
return sendDate
# 定义修改函数
def dealReadSendMapper(self, dataframes_source):
sendMapper = {}
currentKey = {}
splitSize = 0
for drow in dataframes_source.itertuples():
# print(f'[DEBUG] {drow}')
# 需求: 根据发货清单明细:(同一 下单客户,同一 发货时间,同一 出库仓库,同一 收货 联系人,收货 联系地址,同一 审核人,同一 结算主体),可打印在一张送货单
sendDate = pdas.to_datetime(self.dealSendDate(drow.发货时间))
# print(sendDate.strftime("%Y-%m-%d"))
# sendDate = datetime.datetime.strptime(self.dealSendDate(drow.发货时间), "%Y-%m-%d %H:%M:%S")
mapkey = "cus:%s,date:%s,stor:%s,peo:%s,add:%s,check:%s,main:%s" % (drow.下单客户, sendDate.strftime("%Y-%m-%d"), drow.出库仓库, drow.联系人, drow.联系地址, drow.审核人, drow.结算主体)
curMapkey = currentKey.get(mapkey)
if curMapkey is None:
currentKey[mapkey] = mapkey
curMapkey = mapkey
# print(f'[DEBUG] curMapkey:{curMapkey}')
dataList = sendMapper.get(curMapkey)
# 每个key包含6条数据,超过6条后用新的key存储
if dataList is not None and len(dataList)==5:
curMapkey = "%s_%s" % (mapkey, splitSize)
currentKey[mapkey] = curMapkey
if dataList is None:
dataList = []
dataList.append(drow)
sendMapper[curMapkey] = dataList
else:
dataList.append(drow)
splitSize+=1
return sendMapper
# 定义修改函数
def dealStorePeopleMapper(self):
storePeopleMapper = {}
storePeople_dataframes = pdas.read_excel('D:/work_doc/003 - 商务脚本/仓别-发研发.xlsx', skiprows=1)
for drow in storePeople_dataframes.itertuples():
# print(f'[DEBUG] {drow}')
key1 = drow._2 + '2021制单人'
key2 = drow._2 + '2021发货人'
key3 = drow._2 + '2022制单人'
key4 = drow._2 + '2022发货人'
key5 = drow._2 + '2023制单人'
key6 = drow._2 + '2023发货人'
storePeopleMapper[key1] = drow.制单人
storePeopleMapper[key2] = drow.发货人
storePeopleMapper[key3] = drow._5
storePeopleMapper[key4] = drow._6
storePeopleMapper[key5] = drow._7
storePeopleMapper[key6] = drow._8
return storePeopleMapper
def dealDataToExcel(self, sourceFile, exportPath, module_file_path, dealContentPath):
# 读取 Excel 文件
dataframes_source = pdas.read_excel(sourceFile)
dataframes_source.columns = dataframes_source.columns.str.strip()
# 读取原始数据:
# 每个mapper value代表一个发货单(每个发货单最大6条发货信息),
# mapper key按照商务需求+数值的方式确保唯一用来表示一张发货单(业务操作中不会用到 mapper key,只是用来将原始数据分割成一个一个的 mapper value)
sendMapper = self.dealReadSendMapper(dataframes_source)
print('文件任务总数:%s' % len(sendMapper))
# 不再使用pandas读取模板数据,换成后面的openpyxl default_dataframes = pdas.read_excel(module_file_path, sheet_name='发货签收单模板')
mainMapper = {'广联数科': '深圳广联数科科技有限公司','广联赛讯': '深圳广联赛讯股份有限公司','嘀加智慧云': '深圳市嘀加智慧云服务有限公司'}
storePeopleMapper = self.dealStorePeopleMapper()
dealindex = 0
orderNumMapper = {}
expSizeMapper = {}
dataframes_source['自动生成单号'] = '-'
# 打开模板文件
curWorkBook = openpyxl.load_workbook(module_file_path)
for sendKey,sendList in sendMapper.items():
oneRow = sendList[0]
# 供货方
mainName = mainMapper.get(oneRow.结算主体)
# 发货日期
sendDate = pdas.to_datetime(self.dealSendDate(oneRow.发货时间))
# 发货单号
sendDateStr = sendDate.strftime("%Y-%m-%d")
orYear = sendDate.strftime("%Y")
# 每天的订单进行序号递增,并使用mapper存储
orkey = sendDate.strftime("%Y%m%d")
orderNum = orderNumMapper.get(orkey)
if orderNum is None:
orderNum = (int(orkey) * 10000)
orderNum+=1
orderNumMapper[orkey] = orderNum
sendOrderCode = orderNum
# 收货方
reciverCustomer = oneRow.下单客户
# 收货地址
reciverAdd = oneRow.联系地址
# 收货人
reciverPeople = oneRow.联系人
# 收货人电话
reciverPeopleMobile = str(oneRow.联系电话)
# 发货仓
sendStore = oneRow.出库仓库
curSheet = curWorkBook.active
# ---清空内存中的表格 start---
curSheet['C3'] = ''
curSheet['H3'] = ''
curSheet['J3'] = ''
curSheet['C4'] = ''
curSheet['I4'] = ''
curSheet['C5'] = ''
curSheet['I5'] = ''
curSheet['J5'] = ''
loopList = [7,8,9,10,11,12]
for loopItem in loopList:
curSheet[f'C{loopItem}'] = ''
curSheet[f'D{loopItem}'] = ''
curSheet[f'E{loopItem}'] = ''
curSheet[f'G{loopItem}'] = ''
curSheet[f'H{loopItem}'] = ''
curSheet[f'I{loopItem}'] = ''
curSheet[f'I{loopItem}'] = ''
curSheet['C14'] = ''
curSheet['F14'] = ''
# ---清空内存中的表格 END---
curSheet['C3'] = mainName
curSheet['H3'] = sendDateStr
curSheet['J3'] = str(sendOrderCode)
curSheet['C4'] = reciverCustomer
curSheet['I4'] = sendStore
curSheet['C5'] = reciverAdd
curSheet['I5'] = reciverPeople
curSheet['J5'] = reciverPeopleMobile
loopIndex = 7
for sendRow in sendList:
# 物料编码
marterCode = sendRow.实发物料编码
# 销售编码
saleMarterCode = sendRow.订单物料编码
# 产品名称
productName = sendRow.实发物料名称
# 子订单号
childOrderCode = sendRow.子订单号
# 数量
orderCount = sendRow.已发数量
# 备注
lineRemark = sendRow.发货单号
# 制单人
mlpKey = f'{sendRow.出库仓库}{orYear}制单人'
markListPeople = storePeopleMapper.get(mlpKey)
# 发货人
slpKey = f'{sendRow.出库仓库}{orYear}发货人'
sendListPeople = storePeopleMapper.get(slpKey)
curSheet[f'C{loopIndex}'] = marterCode
curSheet[f'D{loopIndex}'] = saleMarterCode
curSheet[f'E{loopIndex}'] = productName
curSheet[f'G{loopIndex}'] = childOrderCode
curSheet[f'H{loopIndex}'] = orderCount
curSheet[f'I{loopIndex}'] = lineRemark
curSheet[f'I{loopIndex}'] = lineRemark
curSheet['C14'] = markListPeople
curSheet['F14'] = sendListPeople
loopIndex+=1
# 在源文件中增加列:自动生成单号
dataframes_source.loc[dataframes_source['发货单号'] == sendRow.发货单号, '自动生成单号'] = sendOrderCode
# 同订单号计数
expSize = expSizeMapper.get(sendOrderCode)
if expSize is None:
expSize = 0
expSize+=1
expSizeMapper[sendOrderCode] = expSize
orderNumValue = "%s_%s" % (sendOrderCode, expSize)
exPath = "%s%s_%s.xlsx" % (exportPath, orderNumValue, reciverCustomer)
# write_dataframes.to_excel(exPath, index=False)
curWorkBook.save(exPath)
dealindex+=1
print('[%s] 生成文件索引:%s' % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), dealindex))
# 关闭openpyxl的IO流操作
curWorkBook.close()
# 将源文件写出到新文件
sourceExportFilePath = f'{exportPath}exportsource_{dealContentPath}.xlsx'
dataframes_source.to_excel(sourceExportFilePath, index=False)
# 定义修改函数
def dealContentFile(self, contentPath):
# 获取目录中的所有文件
files = os.listdir(contentPath)
for file in files:
sourceFile = f'{contentPath}{file}'
dealContentPath = file.split('-')[1].replace('.xlsx', '')
# print("=1=文件名称:", sourceFile)
# print("=2=DefaultExport:", self.defaultExportReleasePath)
print('=3=dealContent:', dealContentPath)
exportPath = self.defaultExportReleasePath + '' + dealContentPath + '/'
if not os.path.exists(exportPath):
# 创建目录
os.makedirs(exportPath)
print(f"Directory '{exportPath}' created.")
else:
print(f"Directory '{exportPath}' already exists.")
# 处理核心逻辑
dealMain.dealDataToExcel(sourceFile, exportPath, self.module_file_path, dealContentPath)
if __name__ == "__main__":
handle_month = '2021-2023'
dedRes = False
diRes = False
urRes = False
print('==========================按年跑数据==========================')
#启动初始化
dealMain = DealSupplychainSomeListMain(handle_month)
logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)
dealMain.module_file_path = 'D:/work_doc/003 - 商务脚本/发货签收单-模板-rel.xlsx'
dealMain.defaultExportReleasePath = 'D:/work_doc/003 - 商务脚本/export_relaese/'
contentPath = 'D:/work_doc/003 - 商务脚本/2021年-2023年发货清单明细/2023年/'
dealMain.dealContentFile(contentPath)
import logging
import pandas as pdas
import os
import chardet
import datetime
import threading
import openpyxl
from openpyxl import Workbook
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder
print("sys config " + __name__)
log_name = './log/supplychain/dealSendSomeList.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)
class DealSupplychainSomeListMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
db = None
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "供应链批量打印发货单需求脚本执行..."
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
#self.db = MysqlHelper(DbConect.current_month_DB)
def initCurrentMonthTable(self):
logging.info("初始化:暂无操作")
# 判断文件编码
def detect_file_encoding(self, filename):
with open(filename, 'rb') as f:
content = f.read()
result = chardet.detect(content)
return result['encoding']
def dealDeviceEndDateList(self):
return True
# 定义修改函数
def modify_data(self, x):
# 进行批量修改的逻辑
if x is None:
return x
return x.replace("M{", "").replace("}", "")
# 定义修改函数
def modify_float_data(self, x):
# 进行批量修改的逻辑
if x is None:
return 0
current = str(x).replace("`", "").replace(' ', '')
if current == '':
return 0
return current
# 定义修改函数
def dealSendDate(self, sendDate):
# 进行批量修改的逻辑
if ',' in sendDate:
return sendDate.split(',')[0]
return sendDate
def dealDataToExcel(self, sourceFile, exportPath, module_file_path):
# 读取 Excel 文件
dataframes_source = pdas.read_excel(sourceFile)
sendMapper = {}
currentKey = {}
splitSize = 0
for drow in dataframes_source.itertuples():
# print(f'[DEBUG] {drow}')
# 需求: 根据发货清单明细:(同一 下单客户,同一 发货时间,同一 出库仓库,同一 收货 联系人,收货 联系地址,同一 审核人,同一 结算主体),可打印在一张送货单
sendDate = datetime.datetime.strptime(self.dealSendDate(drow.发货时间), "%Y-%m-%d %H:%M:%S")
mapkey = "cus:%s,date:%s,stor:%s,peo:%s,add:%s,check:%s,main:%s" % (drow.下单客户, sendDate.strftime("%Y-%m-%d"), drow.出库仓库, drow.联系人, drow.联系地址, drow.审核人, drow.结算主体)
curMapkey = currentKey.get(mapkey)
if curMapkey is None:
currentKey[mapkey] = mapkey
curMapkey = mapkey
# print(f'[DEBUG] curMapkey:{curMapkey}')
dataList = sendMapper.get(curMapkey)
if dataList is not None and len(dataList)==5:
curMapkey = "%s_%s" % (mapkey, splitSize)
currentKey[mapkey] = curMapkey
if dataList is None:
dataList = []
dataList.append(drow)
sendMapper[curMapkey] = dataList
else:
dataList.append(drow)
splitSize+=1
print('文件任务总数:%s' % len(sendMapper))
default_dataframes = pdas.read_excel(module_file_path, sheet_name='发货签收单模板')
mainMapper = {'广联数科': '深圳广联数科科技有限公司','广联赛讯': '深圳广联赛讯股份有限公司','嘀加智慧云': '深圳市嘀加智慧云服务有限公司'}
storePeopleMapper = {}
storePeople_dataframes = pdas.read_excel('D:\\work_doc\\003 - 商务脚本\\仓别-发研发.xlsx', skiprows=1)
for drow in storePeople_dataframes.itertuples():
# print(f'[DEBUG] {drow}')
key1 = drow._2 + '2021制单人'
key2 = drow._2 + '2021发货人'
key3 = drow._2 + '2022制单人'
key4 = drow._2 + '2022发货人'
key5 = drow._2 + '2023制单人'
key6 = drow._2 + '2023发货人'
storePeopleMapper[key1] = drow.制单人
storePeopleMapper[key2] = drow.发货人
storePeopleMapper[key3] = drow._5
storePeopleMapper[key4] = drow._6
storePeopleMapper[key5] = drow._7
storePeopleMapper[key6] = drow._8
threadDataMapper = {}
# 将业务数据通过规则进行拆分,多线程执行
for sendKey,sendList in sendMapper.items():
oneRow = sendList[0]
# 发货日期
sendDate = datetime.datetime.strptime(self.dealSendDate(oneRow.发货时间), "%Y-%m-%d %H:%M:%S")
orkey = int(sendDate.strftime("%Y%m%d"))
hashCode = orkey%6
print('sendDate:%s hashCode:%d' %(sendDate, hashCode))
itemMapper = threadDataMapper.get(hashCode)
if itemMapper is None:
itemMapper = {}
threadDataMapper[hashCode] = itemMapper
itemMapper[sendKey] = sendList
print(len(threadDataMapper))
# 创建线程
threads = []
for threadKey, threadMapper in threadDataMapper.items():
print(f'threadName:{threadKey} threadDataSize:{len(threadMapper)}')
thread = threading.Thread(target=self.dealWriteContentFile, args=(threadMapper, mainMapper, storePeopleMapper, threadKey))
threads.append(thread)
# 启动线程
for thread in threads:
thread.start()
# 等待线程结束
for thread in threads:
thread.join()
# 处理完的数据在共享列表中
print('[OK] data deal end.')
def dealWriteContentFile(self, sendMapper, mainMapper, storePeopleMapper, threadKey):
dealindex = 0
write_dataframes = []
orderNumMapper = {}
expSizeMapper = {}
for sendKey,sendList in sendMapper.items():
oneRow = sendList[0]
# 供货方
mainName = mainMapper.get(oneRow.结算主体)
# 发货日期
sendDate = datetime.datetime.strptime(self.dealSendDate(oneRow.发货时间), "%Y-%m-%d %H:%M:%S")
# 发货单号
sendDateStr = sendDate.strftime("%Y-%m-%d")
orkey = sendDate.strftime("%Y%m%d")
orYear = sendDate.strftime("%Y")
orderNum = orderNumMapper.get(orkey)
if orderNum is None:
orderNum = (int(orkey) * 10000)
orderNum+=1
orderNumMapper[orkey] = orderNum
sendOrderCode = orderNum
# 收货方
reciverCustomer = oneRow.下单客户
# 收货地址
reciverAdd = oneRow.联系地址
# 收货人
reciverPeople = oneRow.联系人
# 收货人电话
reciverPeopleMobile = str(oneRow.联系电话)
# 发货仓
sendStore = oneRow.出库仓库
curWorkBook = openpyxl.load_workbook(module_file_path)
curSheet = curWorkBook.active
curSheet['C3'] = mainName
curSheet['H3'] = sendDateStr
curSheet['J3'] = str(sendOrderCode)
curSheet['C4'] = reciverCustomer
curSheet['I4'] = sendStore
curSheet['C5'] = reciverAdd
curSheet['I5'] = reciverPeople
curSheet['J5'] = reciverPeopleMobile
loopIndex = 7
for sendRow in sendList:
# 物料编码
marterCode = sendRow.实发物料编码
# 销售编码
saleMarterCode = sendRow.订单物料编码
# 产品名称
productName = sendRow.实发物料名称
# 子订单号
childOrderCode = sendRow.子订单号
# 数量
orderCount = sendRow.已发数量
# 备注
lineRemark = sendRow.发货单号
# 制单人
mlpKey = f'{sendRow.出库仓库}{orYear}制单人'
markListPeople = storePeopleMapper.get(mlpKey)
# 发货人
slpKey = f'{sendRow.出库仓库}{orYear}发货人'
sendListPeople = storePeopleMapper.get(slpKey)
curSheet[f'C{loopIndex}'] = marterCode
curSheet[f'D{loopIndex}'] = saleMarterCode
curSheet[f'E{loopIndex}'] = productName
curSheet[f'G{loopIndex}'] = childOrderCode
curSheet[f'H{loopIndex}'] = orderCount
curSheet[f'I{loopIndex}'] = lineRemark
curSheet[f'I{loopIndex}'] = lineRemark
curSheet['C14'] = markListPeople
curSheet['F14'] = sendListPeople
loopIndex+=1
# 同订单号计数
expSize = expSizeMapper.get(sendOrderCode)
if expSize is None:
expSize = 0
expSize+=1
expSizeMapper[sendOrderCode] = expSize
orderNumValue = "%s_%s" % (sendOrderCode, expSize)
exPath = "%s%s.xlsx" % (exportPath, orderNumValue)
# write_dataframes.to_excel(exPath, index=False)
curWorkBook.save(exPath)
curWorkBook.close()
dealindex+=1
print('[%s] thread:%s 生成文件索引:%s' % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), threadKey, dealindex))
if __name__ == "__main__":
handle_month = '2021-2023'
dedRes = False
diRes = False
urRes = False
print('==========================多线程跑数据==========================')
#启动初始化
dealMain = DealSupplychainSomeListMain(handle_month)
logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)
# defaultExportPath = 'D:/work_doc/003 - 商务脚本/thrad_export_'
defaultExportPath = 'C:/export_supplychain/thrad_export_'
module_file_path = 'D:/work_doc/003 - 商务脚本/发货签收单-模板-rel.xlsx'
# sourceFile = 'D:/work_doc/003 - 商务脚本/678018835261169664_商务订单 - 222.xlsx'
# exportPath = defaultExportPath + 'test/'
sourceFile = 'D:/work_doc/003 - 商务脚本/商务订单-2023年1月-系统导出.xlsx'
exportPath = defaultExportPath + '2023年1月/'
# 处理核心逻辑
dealMain.dealDataToExcel(sourceFile, exportPath, module_file_path)
import logging
import os
import sys
from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
#sys.path.append("E://pythonworkspace//djcardrenewal//common")
#print(sys.path)
class TestDataCheck:
def __init__(self) -> None:
print("init default")
if __name__ == '__main__':
db = MysqlHelper(DbConect.dj_release_slave)
#添加
# db.execute_sql("insert into user (username, password) values ('username4','password4')")
#修改
# db.execute_sql("update channellist set is_active=1 where id=2")
#查询
print(DjSql.renewal_select)
selectSql = DjSql.renewal_select.format("2022-07")
print("execute sql:%s" %selectSql)
res = db.execute_select(selectSql)
print("data size: %s" %len(res))
\ No newline at end of file \ No newline at end of file
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapp'
# Generated by Django 4.2 on 2023-04-19 10:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('content', models.TextField()),
('created_at', models.DateTimeField(auto_now_add=True)),
],
),
]
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
from rest_framework import serializers
from myapp.models import Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ['id', 'title', 'content', 'created_at']
from django.test import TestCase
# Create your tests here.
from django.shortcuts import render
# Create your views here.
from rest_framework import generics
from myapp.models import Article
from myapp.serializers import ArticleSerializer
class ArticleList(generics.ListCreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
"""
ASGI config for myproject project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_asgi_application()
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 4.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=1q994q_+c4v2g!ku)8a#er9aw_2ka5d!q%z0wr5_s%92ngy0w'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'myapp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
"""
URL configuration for myproject project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myapp.views import ArticleList, ArticleDetail
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', ArticleList.as_view()),
path('articles/<int:pk>/', ArticleDetail.as_view()),
]
"""
WSGI config for myproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()
from operator import truediv
print("hello word")
if True:
print("ok")
else:
print("error")
if True:
print(" ok")
print(" come on")
else:
print(" error")
print(" not")
\ No newline at end of file \ No newline at end of file
basestr = "hello,world"
print(basestr)
print(basestr[2:3])
print(basestr[-4:-1])
print("=====================")
print(basestr[2:7])
print(basestr[2:7:2])
print("=====================")
list = ['John', 20.10, 'Lucy', 10, 12]
shortList = [123, 'Lala']
print(list)
print(list[1:3])
print(shortList*2)
print("=====================")
listLoop = ['John', 20.10, 'Lucy', 10, 12]
print(len(listLoop))
print(range(len(listLoop)))
print(range(2,10))
orderNo = 'GLSX1111111'
j = 1
orderCur = "%s-%s" % (orderNo, j)
print(orderCur)
revName = '发货人:' + orderCur
print(revName)
\ No newline at end of file \ No newline at end of file
baseStr = "jim names"
print(baseStr.capitalize())
#多行字符串打印
str = ('hello world'
' look the dog'
)
print(str)
import os
from pickle import APPEND
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.writer.excel import ExcelWriter
relatePath = os.path.dirname(os.path.abspath(__file__));
print("相对路径为:%s" %relatePath)
excelPath = os.path.join(relatePath, "template\\test_data.xlsx")
print("绝对路径为:%s" %excelPath)
excelWorkBook = load_workbook(excelPath);
operateSheet = excelWorkBook["全量1"]
print("总行数:%s" %(operateSheet.max_row))
print("总列数:%s" %(operateSheet.max_column))
startRow = 1
titleList = []
for rowItem in operateSheet.rows:
print(startRow)
itemDirc = {}
for columnItem in range(len(rowItem)):
if startRow==1:
titleList.append(rowItem[columnItem].value)
else:
print(titleList[columnItem], rowItem[columnItem].value)
startRow = startRow+1
excelWorkBook.close
\ No newline at end of file \ No newline at end of file
name = 'bill'
age = 30
salary = 300000.01
print("my name is %s ." %name)
print('my age is %d .'%age)
print('my salary is %.2f .'%salary) # 浮点数可以设置保留几位小数位
print('My name is %s , my age is %d , my salary is %.4f .' %(name, age, salary))
\ No newline at end of file \ No newline at end of file
import mysql.connector
#print("hello word")
# 1、打开数据库连接
db = MySQLdb.connect(host="192.168.3.190", port="3306", user="dev_user", password="df234fl", db="cyb_os", charset="utf8")
# 2、使用cursor()方法获取操作游标
cursor = db.cursor()
# 3、使用execute方法执行SQL语句
cursor.execute("select * from platform_protocol")
# 4、使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print("Database version : %s " %data)
# 关闭数据库连接
db.close()
import mysql.connector
db = mysql.connector.connect(
host="192.168.3.190",
port="3306",
user="dev_user",
password="df234fl",
db="cyb_os",
charset="utf8"
)
cursor = db.cursor()
cursor.execute("select * from platform_protocol")
data = cursor.fetchone()
#print("Database version : %s " %data)
print(data)
db.close()
\ No newline at end of file \ No newline at end of file
import imp
import abc
class Animal:
def __init__(self) -> None:
pass
\ No newline at end of file \ No newline at end of file
import itchat
itchat.auto_login()
itchat.send('晚上加班', toUserName='filehelper')
\ No newline at end of file \ No newline at end of file
from datetime import datetime
dt = datetime(2022,1,12,11,11,12)
dtstr = dt.strftime('"%Y-%m-%d %H:%M:%S"')
print("dt value:%s" %dtstr)
dataMapper = {}
dataList = []
dataMapper["jim"]=dataList
print(dataMapper)
dataList.append("higer:170")
dataList.append("size:78")
print(dataMapper)
loopIndex = 7
rowprefix = 'C'
curname = f'C{loopIndex}'
print(curname)
\ No newline at end of file \ No newline at end of file
from kafka import KafkaProducer, KafkaConsumer
# 生产者示例
def produce_message():
# 创建 KafkaProducer 对象
#producer = KafkaProducer(bootstrap_servers='192.168.3.207:9092')
producer = KafkaProducer(bootstrap_servers='192.168.3.131:9092')
# 发送消息到指定主题
#topic = 'test_topic_1222'
topic = 'my_test_topic'
message = b'Hello, Kafka!'
producer.send(topic, message)
# 关闭生产者
producer.close()
# 消费者示例
def consume_messages():
# 创建 KafkaConsumer 对象
consumer = KafkaConsumer('my_topic', bootstrap_servers='localhost:9092', group_id='my_group')
# 持续消费消息
for message in consumer:
print(f'Received message: {message.value.decode()}')
# 关闭消费者
consumer.close()
# 执行生产者示例
produce_message()
# 执行消费者示例
# consume_messages()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!