dealHengxinEdr.py 9.36 KB
import logging
import pandas as pdas
import os
import chardet
from datetime import datetime, timezone
import re
import json

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

import sys,traceback,Ice
Ice.loadSlice("--all -I.. djcardrenewal/supplychain/ice/bsd.ice")
Ice.loadSlice("--all -I.. djcardrenewal/supplychain/ice/Hdao_gps.ice")
Ice.loadSlice("--all -I.. --underscore djcardrenewal/supplychain/ice/district.ice")
Ice.loadSlice("--all -I.. --underscore djcardrenewal/supplychain/ice/ipoi.ice")
Ice.loadSlice("--all -I.. --underscore djcardrenewal/supplychain/ice/HDao_mile.ice")
import BaseStationData
import HDaoGps

print("sys config " + __name__)
log_name = './log/supplychain/dealHengxinEdr.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 DealHengXinEdrMain:

    handleDescription = ''
    handleMonth = ''
    hmonth = ''
    module_file_path = ''
    defaultExportReleasePath = ''

    supplychainDb = None
    djDb = None
    cybDb = None

    env_host = "192.168.5.26"

    def __init__(self, handle_month):
        logging.info("init construct bean")
        self.handleDescription = "---业务导出恒信数据---脚本执行..."
        self.handleMonth = handle_month
        self.hmonth = handle_month.replace('-', '')[2:6]
        self.supplychainDb = MysqlHelper(DbConect.DB_supplychain_release_slave)
        self.djDb = MysqlHelper(DbConect.dj_release_slave)
        self.cybDb = MysqlHelper(DbConect.cyb_release_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 getIceHdaoService(self):
        communicator = Ice.initialize(sys.argv)
        obj = communicator.stringToProxy(f'HDaoGpsSvc:default -h {self.env_host} -p 23470')
        obj.ice_ping()
        iceService = HDaoGps.DaoGpsServicePrx.checkedCast(obj)
        return iceService

    def getLatestGpsRecord(self, iceService, sn, type = 5):
        try:
            if not iceService:
                raise RuntimeError("Invalid proxy")
            req = HDaoGps.LatestGpsGetRequest()
            req.userID = int(sn)
            req.apType = type
            req.extraMapReq = 0

            rsp = iceService.getLatestGpsRecord(req)
            # print(rsp[1].record.gpsTime)
            # print(rsp)
            return rsp
        except:
            traceback.print_exc()
            return None

    def getUserInfoBySn(self, sn):
        selectUserInfoSql = f'''SELECT a.`sn`,date_format(b.active_time, '%Y-%m-%d %H:%i:%s') as bintTime,pula.mobile FROM `glsx_common_physical_device` a
                    LEFT JOIN `platform_protocol` b ON a.`id`=b.`card_id`
                    left join platform_user_login_account pula on pula.id=b.account_id
                    WHERE  a.`sn`='{sn}';'''
        cybUserInfoData = self.cybDb.execute_selectOne(selectUserInfoSql)
        # print(cybUserInfoData)
        json_data = json.dumps(cybUserInfoData)
        # print(json_data)
        return json_data


    # 定义修改函数
    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
                                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;'''
        # 供应链的数据
        print('查询供应链数据')
        supplychainDbData = self.supplychainDb.execute_select(selectSupplychainSql)
        if supplychainDbData is None :
            logging.info("db supplychain enddate is NONE")
            return
        elif supplychainDbData is False:
            logging.info("db supplychain enddate is FALSE")
            return
        
        print('组装SN列表')
        snListStr = ''
        for chainItem in supplychainDbData:
            currentSn = f''''{chainItem[0]}',''';
            snListStr += currentSn;

        snListStr = snListStr[0:-1]
        # print(snListStr)

        # 匹配设备是否在DJ入库
        print('查询DJ导入记录')
        selectDjSql = f'''select * from dj_customer_device dcd where dcd.imei in ({snListStr});'''
        djDbData = self.djDb.execute_select(selectDjSql)

        dataExport = pdas.DataFrame(supplychainDbData)
        dataExport.columns = ['设备号','设备编码','最后上点时间','订单号','批次','套餐ID','发往商户号','入库时间','出库时间','出库类型','子订单号','收件人','用户手机号','用户绑定时间']
        
        print('匹配DJ导入状态')
        djSnMapper = {}
        if djDbData is None or djDbData is False :
            print('dont match dj sn data')
        else:
            for djItem in djDbData:
                djMerchantId = djItem[3]
                djMerchantName = djItem[4]
                djSn = djItem[5]
                dataExport.loc[dataExport['设备号'] == djSn, '是否录入嘀加系统'] = '是'
                dataExport.loc[dataExport['设备号'] == djSn, '录入嘀加商户号'] = djMerchantId
                dataExport.loc[dataExport['设备号'] == djSn, '录入嘀加商户名称'] = djMerchantName

        # 为每一个设备匹配最后位置信息
        print('为每一个设备匹配最后位置信息')
        iceService = self.getIceHdaoService()
        for supplyChainItem in supplychainDbData:
            supSn = supplyChainItem[0]
            # 组装位置信息
            gpsLocation = self.getLatestGpsRecord(iceService, supSn, 11)
            if gpsLocation is not None and gpsLocation[1] is not None and gpsLocation[1].record.gpsTime>0:
                gpsTime = gpsLocation[1].record.gpsTime
                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)
            dataExport.loc[dataExport['设备号'] == supSn, '最后上点时间'] = formatted_str
            # 组装用户信息
            userinfo = self.getUserInfoBySn(supSn)
            logging.info('get userinfo is:',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]
            

        print('输出excel数据')
        # 输出数据到excel
        dataExport.to_excel(f'{self.defaultExportReleasePath}', index=False)



if __name__ == "__main__":
    handle_month = '2021-2024'
    dedRes = False
    diRes = False
    urRes = False

    print('==========================跑数据根据SN获取发货信息及状态==========================')

    
    #启动初始化
    dealMain = DealHengXinEdrMain(handle_month)
    logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)

    # 测试获取位置信息
    dealMain.getLatestGpsRecord('561063062795826', 11)

    dealMain.module_file_path = 'E:/work/000 - 运营数据导出/恒信-C580记录仪设备明细-template.xlsx'
    dealMain.defaultExportReleasePath = 'E:/work/000 - 运营数据导出/export/恒信-C580记录仪设备明细-20240402-002.xlsx'

    dealMain.dealContentFile() 
    print('导出完成。')