Commit fca2c85f by 王欣伟

更新数据库连接,恒信增加ICCID数据的导出,发货单逻辑优化,账户中心车辆品牌数据处理脚本

1 parent 03a5083a
import logging
import pandas as pdas
import os
import chardet
from datetime import datetime, timezone
import json
from collections import OrderedDict
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/bizcommon/dealCarBrandChange.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 DealDeviceLocationMain:
handleDescription = ''
handleMonth = ''
hmonth = ''
module_file_path = ''
defaultExportReleasePath = ''
scrmDb = None
# 定义一个字典数据
dicMapper = {'2366':'2695','2431':'2695','2691':'2695','2692':'2698','2697':'2698'}
def __init__(self, handle_month):
logging.info("init construct bean")
self.handleDescription = "---业务导出恒信数据---脚本执行..."
self.handleMonth = handle_month
self.hmonth = handle_month.replace('-', '')[2:6]
self.scrmDb = MysqlHelper(DbConect.release_scrm_account_db)
def initCurrentMonthTable(self):
logging.info("初始化:暂无操作")
# 定义修改函数
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 dealContentFile(self):
# and pm.merchantNo=44212086
selectSql = 'select pm.merchantNo,pm.merchant_brand,pm.merchant_brand_main from platform_merchant pm where (pm.merchant_brand is not null or pm.merchant_brand_main is not null) ;'
# 1、读取文件内容
scrmAccountDb = self.scrmDb.execute_select(selectSql)
# 初始化一个空的DataFrame,定义列名
data_list = []
for rowData in scrmAccountDb:
merchantId = rowData[0]
merchantBrand = rowData[1]
merchantBrandMain = rowData[2]
brandReplaced = False
brandMainReplaced = False
if merchantBrand is not None and merchantBrand != '':
# 分割字符串为列表
elements = merchantBrand.split(',')
# 使用字典映射替换列表中的元素,并记录是否有元素被替换
mapped_elements = []
for element in elements:
mapped_element = self.dicMapper.get(element, element)
if mapped_element != element:
brandReplaced = True
mapped_elements.append(mapped_element)
# 将处理后的列表元素重新组合成字符串
output_merchantBrand = ','.join(mapped_elements)
if merchantBrandMain is not None and merchantBrandMain != '':
# 使用正则表达式分割字符串,匹配逗号或分号作为分隔符
parts = merchantBrandMain.split(';')
output_parts = []
for part in parts:
# 分割每个部分内部的逗号
numbers = part.split(',')
# 替换并去重
mapped_numbers_curr = list(OrderedDict.fromkeys(self.dicMapper.get(num, num) for num in numbers)) # 使用OrderedDict去重并保持顺序
mapped_numbers = []
for num in mapped_numbers_curr:
if num is not None and num!='':
mapped_numbers.append(num)
if len(mapped_numbers)==0:
continue;
# 检查是否有所替换(去重后的列表与原列表比较)
if len(mapped_numbers) != len(set(numbers)) or any(mapped != num for num, mapped in zip(numbers, mapped_numbers)):
brandMainReplaced = True
# 过滤掉去重后为空的子串
if mapped_numbers:
output_part = ','.join(mapped_numbers)
output_parts.append(output_part)
# 合并处理后的子串
output_merchantBrandMain = ';'.join(output_parts)
if brandReplaced or brandMainReplaced:
data_list.append({'MerchantID': merchantId, 'MerchantBrand': output_merchantBrand, 'MerchantBrandMain': output_merchantBrandMain})
output_merchantBrand=''
output_merchantBrandMain=''
# 使用pd.concat()将数据列表转换为DataFrame
data_df = pdas.DataFrame(data_list)
data_df.to_excel(self.defaultExportReleasePath, index=False)
if __name__ == "__main__":
handle_month = '2021-2024'
dedRes = False
diRes = False
urRes = False
print('==========================处理账户中心商户对应的品牌信息==========================')
#启动初始化
dealMain = DealDeviceLocationMain(handle_month)
logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)
dealMain.module_file_path = 'D:/work_doc/dataexport/gpslocation/gpslocation20240410.xlsx'
dealMain.defaultExportReleasePath = 'D:/work_doc/dataexport/accountbrand/gpslocation20240513-result.xlsx'
dealMain.dealContentFile()
print('导出完成。')
\ No newline at end of file
......@@ -22,8 +22,11 @@ DB_supplychain_release_slave = {"host": '192.168.5.23', "port": 3306, "user": 'u
# 当月临时表
# 测试权益库
test_equity_db = {"host": '192.168.1.39', "port": 3306, "user": 'os_user', "password": 'os#123', "db": 'scrm_equity', "charset": 'utf8'}
# 当月临时表
# 生产FRMS库
release_gps_db = {"host": '192.168.5.22', "port": 3307, "user": 'user_wangxw1', "password": 'wbOTHHX5', "db": 'gps', "charset": 'utf8'}
# 生产账户中心库
release_scrm_account_db = {"host": '192.168.5.1', "port": 3310, "user": 'user_wangxw1', "password": 'wbOTHHX5', "db": 'scrm_account', "charset": 'utf8'}
\ No newline at end of file
......@@ -5,6 +5,9 @@ import chardet
from datetime import datetime, timezone
import re
import json
import requests
import hashlib
import time
import openpyxl
from openpyxl import Workbook
......@@ -132,14 +135,35 @@ class DealHengXinEdrMain:
# print(json_data)
return json_data
def getCardInfoByIccid(self, iccid):
serverUrl = 'http://card.didihu.com.cn/openApi/getCardIccid'
appid = 19180009
appsecret = 'abcdef'
timeStr = str(int(time.time()))
date = timeStr
data = str(appid) + appsecret + date
token = hashlib.md5(data.encode()).hexdigest()
data = {'appid':19180009,'invoker':'glsx'}
data['time'] = timeStr
data['cardno_imsi_iccid'] = iccid
data['token'] = token
json_str = json.dumps(data)
response = requests.post(serverUrl, data=json_str)
responseJson = json.loads(response.text)
# print(responseJson)
return responseJson['cardno']
# 定义修改函数
def dealContentFile(self):
selectSupplychainSql = f'''select df.SN as '设备号',df.DEVICE_CODE as '设备编码','' as '最后上点时间',df.ORDER_CODE as '订单号',df.BATCH_NO as '批次',df.PACKAGE_ID as '套餐ID',df.SEND_MERCHANT_NO as '发往商户号',df.IN_STORAGE_TIME as '入库时间',df.OUT_STORAGE_TIME as '出库时间',df.OUT_STORAGE_TYPE as '出库类型',bmov.merchant_order as '子订单号',emo.ADDRESSEE as '收件人','' as '用户手机号','' as '用户绑定时间'
from device_file df,device_code dc ,bs_merchant_order_vehicle bmov,ec_merchant_order emo
selectSupplychainSql = f'''select df.SN as '设备号',dcm.ICCID,dcm.IMSI,'' as '卡号',df.DEVICE_CODE as '设备编码','' as '最后上点时间',df.ORDER_CODE as '订单号',df.BATCH_NO as '批次',df.PACKAGE_ID as '套餐ID',df.SEND_MERCHANT_NO as '发往商户号',df.IN_STORAGE_TIME as '入库时间',df.OUT_STORAGE_TIME as '出库时间',df.OUT_STORAGE_TYPE as '出库类型',bmov.merchant_order as '子订单号',emo.ADDRESSEE as '收件人','' as '用户手机号','' as '用户绑定时间'
from device_file df,device_code dc ,bs_merchant_order_vehicle bmov,ec_merchant_order emo,device_card_manager dcm
where df.SEND_MERCHANT_NO=44193436
and df.DEVICE_CODE =dc.DEVICE_CODE and dc.TYPE_ID =6 and dc.DEVICE_CODE =100138
and df.ORDER_CODE =bmov.dispatch_order_code and bmov.merchant_order=emo.ORDER_NUMBER;'''
and df.ORDER_CODE =bmov.dispatch_order_code and bmov.merchant_order=emo.ORDER_NUMBER
and df.CARD_ID=dcm.ID;'''
# 供应链的数据
print('查询供应链数据')
supplychainDbData = self.supplychainDb.execute_select(selectSupplychainSql)
......@@ -165,7 +189,7 @@ class DealHengXinEdrMain:
djDbData = self.djDb.execute_select(selectDjSql)
dataExport = pdas.DataFrame(supplychainDbData)
dataExport.columns = ['设备号','设备编码','最后上点时间','订单号','批次','套餐ID','发往商户号','入库时间','出库时间','出库类型','子订单号','收件人','用户手机号','用户绑定时间']
dataExport.columns = ['设备号','ICCID','IMSI','卡号','设备编码','最后上点时间','订单号','批次','套餐ID','发往商户号','入库时间','出库时间','出库类型','子订单号','收件人','用户手机号','用户绑定时间']
print('匹配DJ导入状态')
djSnMapper = {}
......@@ -185,6 +209,8 @@ class DealHengXinEdrMain:
iceService = self.getIceHdaoService()
for supplyChainItem in supplychainDbData:
supSn = supplyChainItem[0]
supIccid = supplyChainItem[1]
# 组装位置信息
gpsLocation = self.getLatestGpsRecord(iceService, supSn, 11)
if gpsLocation is not None and gpsLocation[1] is not None and gpsLocation[1].record.gpsTime>0:
......@@ -192,16 +218,22 @@ class DealHengXinEdrMain:
dt_object = datetime.fromtimestamp(gpsTime)
# 格式化为字符串
formatted_str = dt_object.strftime('%Y-%m-%d %H:%M:%S')
logging.info('get gps time is:', supSn, gpsTime, formatted_str)
logging.info('get gps time is: %s %s %s', supSn, gpsTime, formatted_str)
dataExport.loc[dataExport['设备号'] == supSn, '最后上点时间'] = formatted_str
# 组装用户信息
userinfo = self.getUserInfoBySn(supSn)
logging.info('get userinfo is:',userinfo)
logging.info('get userinfo is: %s ',userinfo)
if userinfo is not None and userinfo!='null':
userJson = json.loads(userinfo)
dataExport.loc[dataExport['设备号'] == supSn, '用户手机号'] = userJson[2]
dataExport.loc[dataExport['设备号'] == supSn, '用户绑定时间'] = userJson[1]
# 组装卡信息
cardNo = self.getCardInfoByIccid(supIccid)
if cardNo is not None:
dataExport.loc[dataExport['设备号'] == supSn, '卡号'] = cardNo
print('输出excel数据')
# 输出数据到excel
......@@ -223,10 +255,16 @@ if __name__ == "__main__":
logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)
# 测试获取位置信息
dealMain.getLatestGpsRecord('561063062795826', 11)
# iceService = self.getIceHdaoService()
# dealMain.getLatestGpsRecord(iceService, '561063062795826', 11)
# 测试获取卡信息接口
# iccidStr = '8986062355005148287'
# res = dealMain.getCardInfoByIccid(iccidStr)
# print('card info: %s', res)
dealMain.module_file_path = 'E:/work/000 - 运营数据导出/恒信-C580记录仪设备明细-template.xlsx'
dealMain.defaultExportReleasePath = 'E:/work/000 - 运营数据导出/export/恒信-C580记录仪设备明细-20240402-002.xlsx'
dealMain.defaultExportReleasePath = 'E:/work/000 - 运营数据导出/export/恒信-C580记录仪设备明细-20240416-02.xlsx'
dealMain.dealContentFile()
print('导出完成。')
\ No newline at end of file
......@@ -8,12 +8,6 @@ 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]'
......@@ -318,5 +312,5 @@ if __name__ == "__main__":
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年发货清单明细/2024年3月/'
contentPath = 'D:/work_doc/003 - 商务脚本/2021年-2023年发货清单明细/2024年4月/'
dealMain.dealContentFile(contentPath)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!