HandleMain.py 9.7 KB
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-09'
    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()