Ejemplo n.º 1
0
def runSession():
    try:
        print("run session start" + str(datetime.datetime.now()))
        loginpingan = Login()
        hn = Hn_Login()

        log1 = logincic()
        loginRes = login()
        pingan_session = loginpingan.login()
        ancheng = login_ancheng()
        hn_session = hn.hn_login()
        print("run session end " + str(datetime.datetime.now()))
    except Exception as e:
        print(e)
        print(traceback.format_exc())
Ejemplo n.º 2
0
def getSession():
    sessiondt = get_session(["1", "4", "5", "12", "13"])
    pingansession = sessiondt[0]
    sessio4 = sessiondt[1]
    sessio5 = sessiondt[2]
    ancheng_session = sessiondt[3]
    hn_session = sessiondt[4]

    # 测试session是否有效
    if sessio4 is not None:
        CUST_DATA = 'plateNo=' + '' + '&frmNo=' + 'LBELMBKC2EY568468'
        getcodeinfo_url = 'http://carply.cic.cn/pcis/policy/universal/quickapp/actionservice.ai'
        getcodeinfo_data = 'ADAPTER_TYPE=JSON_TYPE&SERVICE_TYPE=ACTION_SERVIC&CODE_TYPE=CODE_TYPE&BEAN_HANDLE=baseAction&ACTION_HANDLE=perform&SERVICE_NAME=vhlPlatformCommonAction&SERVICE_MOTHOD=getJsCheckInfo&DW_DATA=%255B%255D&HELPCONTROLMETHOD=common&SCENE=UNDEFINED&BIZ_SYNCH_CONTINUE=false&CUST_DATA=' + CUST_DATA
        headers = se.headers
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        try:
            getcodeinforesp = sessio4.post(url=getcodeinfo_url,
                                           data=getcodeinfo_data,
                                           headers=headers)
        except Exception as e:
            print(e)
            sessio4 = logincic()
        print('curru_url = %s' % getcodeinforesp.url)
    else:
        sessio4 = logincic()

    if sessio5 is None:
        sessio5 = login()

    if pingansession is None:
        loginpingan = Login()
        pingansession = loginpingan.login()

    if ancheng_session is None:
        ancheng_session = login_ancheng()

    if hn_session is None:
        hn = Hn_Login()
        hn_session = hn.hn_login()
    return {
        '4': sessio4,
        '5': sessio5,
        "1": pingansession,
        "12": ancheng_session,
        "13": hn_session
    }
Ejemplo n.º 3
0
def is_ancheng_renewal(session, plateNumber):
    try:
        # 获取CPlyNo, 判断有没有续保信息
        ret = get_xubao_1(session, plateNumber)

        if 'JSP Processing Error' in ret.text:
            session = login_ancheng()
            return is_ancheng_renewal(session, plateNumber)

        ra = "DATA:\['(.*?)'\]"
        rb = re.compile(ra)

        title_list = re.findall(rb, ret.content)

        html = title_list[0]

        # 没有续保信息返回0
        if "CPlyNo" not in html:
            log.info(u"未查询到续信息%s" % plateNumber)
            return 0

        soup = BeautifulSoup(html, 'html.parser')

        sy_premium, jq_premium = 0, 0
        syPlyNo, jqPlyNo = 0, 0
        try:
            premiums = soup.findAll("attribute", attrs={"name": "NPrm"})
            PlyNo = soup.findAll("attribute", attrs={"name": "CPlyNo"})

            premium_1 = float(premiums[0].get_text())
            premium_2 = float(premiums[1].get_text())

            if premium_1 > premium_2:
                syPlyNo = PlyNo[0].get_text()
                jqPlyNo = PlyNo[1].get_text()
            else:
                syPlyNo = PlyNo[1].get_text()
                jqPlyNo = PlyNo[0].get_text()

            sy_premium = max(premium_1, premium_2)
            jq_premium = min(premium_1, premium_2)

        except Exception as e:
            log.info('查询商业险和交强险出错 - {0}'.format(e))

        if not syPlyNo or not jqPlyNo:
            log.info('查询保单号出错')
            return

        # 获取续保信息
        ret = get_xubao_2(session, syPlyNo, jqPlyNo)

        response_body = json.loads(ret.content)

        fields = ["Insured.CInsuredNme", "Insured.CCertfCde", "Insured.CMobile", "Insured.CSuffixAddr", "Vhl.CFrmNo",
                  "Vhl.CPlateNo", "Vhl.CEngNo", "Vhl.CModelCde", "Vhl.CModelNme", "Vhl.CFstRegYm", "Vhl.NSeatNum",
                  "SY_Base.TInsrncEndTm", "SY_Base.TInsrncBgnTm", "JQ_Base.TInsrncEndTm", "JQ_Base.TInsrncBgnTm",
                  "Vhl.CRegVhlTyp"]

        Insured_DW = jsonpath.jsonpath(response_body, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.Insured_DW')]")[0]
        Insured_DW_dataObjVoList = jsonpath.jsonpath(Insured_DW, "$.dataObjVoList")
        dict_1 = Insured_DW_dataObjVoList[0][0]['attributeVoList']

        Vhl_DW = jsonpath.jsonpath(response_body, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.Vhl_DW')]")[0]
        Vhl_DW_dataObjVoList = jsonpath.jsonpath(Vhl_DW, "$.dataObjVoList")
        dict_2 = Vhl_DW_dataObjVoList[0][0]['attributeVoList']

        Base_DW = jsonpath.jsonpath(response_body, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.Base_DW')]")[0]
        Base_DW_dataObjVoList = jsonpath.jsonpath(Base_DW, "$.dataObjVoList")
        dict_3 = Base_DW_dataObjVoList[0][0]['attributeVoList']

        dict_4 = dict(dict_1, **dict_2)
        dict_5 = dict(dict_4, **dict_3)

        # print dict_5

        _data = {field: dict_5[field]['value'] for field in fields}

        VsTax_DW = jsonpath.jsonpath(response_body, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.VsTax_DW')]")[0]
        VsTax_DW_dataObjVoList = jsonpath.jsonpath(VsTax_DW, "$.dataObjVoList")
        dict_6 = VsTax_DW_dataObjVoList[0][0]['attributeVoList']

        VsTax_NAggTax = dict_6.get('VsTax.NTaxableAmt').get('value', 0)
        jq_premium += float(VsTax_NAggTax)

        nAggTax = '1' if VsTax_NAggTax else '0'

        # 获取险别
        Cvrg_DW = jsonpath.jsonpath(response_body, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.Cvrg_DW')]")[
            0]
        Cvrg_DW_dataObjVoList = jsonpath.jsonpath(Cvrg_DW, "$.dataObjVoList")

        attrs = Cvrg_DW_dataObjVoList[0]

        # print attrs

        insuranceType = {
            "otherHurtPremium": {
                "Amount": '0',
                "isCheck": "0"
            },
            "driverDutyPremium": {
                "Amount": "0",
                "isCheck": "0"
            },
            "passengerDutyPremium": {
                "Amount": '0',
                "isCheck": "0"
            },
            "carDamagePremium": "0",
            "carFireBrokenBenchMarkPremium": "0",
            "carTheftPremium": "0",
            "otherHurtBenchMarkPremium": "0",
            "carTheftBenchMarkPremium": "0",
            "engineWadingBenchMarkPremium": "0",
            "JqSumPremium": jq_premium,
            "carNickPremium": {
                "Amount": "0",
                "isCheck": "0"
            },
            "carDamageBenchMarkPremium": "0",
            "carNickBenchMarkPremium": "0",
            "engineWadingPremium": "0",
            "passengerBenchMarkPremium": "0",
            "SySumPremium": sy_premium,
            "driverDutyBenchMarkPremium": "0",
            "carFirePremium": "0",
            "glassBrokenPremium": "0",
            "compulsoryInsurance": "0",
            "nAggTax": nAggTax
        }

        for i, k in enumerate(attrs):
            num = int(k["attributeVoList"]["Cvrg.NSeqNo"]["value"])
            if num == 15:
                _otherHurtPremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 三者险
                otherHurtBenchMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_otherHurtPremium) + u' 三者险')

                otherHurtPremium = {}
                otherHurtPremium['Amount'] = str(_otherHurtPremium)
                otherHurtPremium['isCheck'] = '1'

                insuranceType['otherHurtPremium'] = otherHurtPremium
                insuranceType['otherHurtBenchMarkPremium'] = '1' if otherHurtBenchMarkPremium == '345021001' else '0'

            elif num == 20:
                _carDamagePremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 车损险
                carDamageBenchMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_carDamagePremium) + u' 车损险')

                carDamagePremium = '1'
                insuranceType['carDamagePremium'] = carDamagePremium
                insuranceType['carDamageBenchMarkPremium'] = '1' if carDamageBenchMarkPremium == '345021001' else '0'

            elif num == 13:
                _driverDutyPremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 车上人员险(司机)
                driverDutyBenchMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_driverDutyPremium) + u' 车上人员险(司机)')

                driverDutyPremium = {}
                driverDutyPremium['Amount'] = _driverDutyPremium
                driverDutyPremium['isCheck'] = '1'

                insuranceType['driverDutyPremium'] = driverDutyPremium
                insuranceType['driverDutyBenchMarkPremium'] = '1' if driverDutyBenchMarkPremium == '345021001' else '0'

            elif num == 14:
                _passengerDutyPremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 车上人员险(乘客)
                passengerBenchMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_passengerDutyPremium) + u' 车上人员险(乘客)')

                passengerDutyPremium = {}
                passengerDutyPremium['Amount'] = _passengerDutyPremium
                passengerDutyPremium['isCheck'] = '1'

                insuranceType['passengerDutyPremium'] = passengerDutyPremium
                insuranceType['passengerBenchMarkPremium'] = '1' if passengerBenchMarkPremium == '345021001' else '0'

            elif num == 18:
                _carTheftPremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 盗抢险
                carTheftBenchMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_carTheftPremium) + u' 盗抢险')

                carTheftPremium = '1'
                insuranceType['carTheftPremium'] = carTheftPremium
                insuranceType['carTheftBenchMarkPremium'] = '1' if carTheftBenchMarkPremium == '345021001' else '0'

            elif num == 19:
                _carNickPremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 划痕险
                carNickBenchMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_carNickPremium) + u' 划痕险')

                carNickPremium = {}
                carNickPremium['Amount'] = _carNickPremium
                carNickPremium['isCheck'] = '1'

                insuranceType['carNickPremium'] = carNickPremium
                insuranceType['carNickBenchMarkPremium'] = '1' if carNickBenchMarkPremium == '345021001' else '0'

            elif num == 8:
                _glassBrokenPremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 玻璃破碎险
                glassBrokenMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_glassBrokenPremium) + u' 玻璃破碎险')

                glassBrokenPremium = '1'
                insuranceType['glassBrokenPremium'] = glassBrokenPremium
                insuranceType['glassBrokenMarkPremium'] = '1' if glassBrokenMarkPremium == '345021001' else '0'

            elif num == 5:
                _carFirePremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 自燃险
                carFireBrokenBenchMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_carFirePremium) + u' 自燃险')

                carFirePremium = '1'
                insuranceType['carFirePremium'] = carFirePremium
                insuranceType[
                    'carFireBrokenBenchMarkPremium'] = '1' if carFireBrokenBenchMarkPremium == '345021001' else '0'

            elif num == 10:
                _engineWadingPremium = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 涉水险
                engineWadingBenchMarkPremium = k["attributeVoList"]["Cvrg.CDductMrk"]["value"]
                log.info(str(_engineWadingPremium) + u' 涉水险')

                engineWadingPremium = '1'
                insuranceType['engineWadingPremium'] = engineWadingPremium
                insuranceType[
                    'engineWadingBenchMarkPremium'] = '1' if engineWadingBenchMarkPremium == '345021001' else '0'

            elif num == 1:
                _compulsory_insurance = float(k["attributeVoList"]["Cvrg.NAmt"]["value"])  # 交强险
                log.info(str(_compulsory_insurance) + u' 交强险')

                compulsoryInsurance = '1'
                insuranceType['compulsoryInsurance'] = compulsoryInsurance

        # print _data

        out = {
            'licenseNo': _data['Vhl.CPlateNo'],  # 车牌号
            'vinNo': _data['Vhl.CFrmNo'],  # 车架号
            'endDate': utils.getlatedate(-365, str_date=_data['SY_Base.TInsrncEndTm'][:10]),  # 保险结束期
            'CCardDetail': _data['Vhl.CRegVhlTyp'],  # 车辆类型
            'brandName': _data['Vhl.CModelNme'],  # 汽车名字
            'insuredName': _data['Insured.CInsuredNme'],  # 车主
            'identifyNumber': _data['Insured.CCertfCde'],  # 身份证号
            'mobile': _data['Insured.CMobile'],  # 手机号
            'insuredAddress': _data['Insured.CSuffixAddr'],  # 地址
            'CUsageCde': "",
            'NNewPurchaseValue': "",
            'enrollDate': _data['Vhl.CFstRegYm'],  # 初登日期
            'engineNo': _data['Vhl.CEngNo'],  # 发动机号
            'CModelCde': _data['Vhl.CModelCde'],
            'NSeatNum': _data['Vhl.NSeatNum'],  # 座位数
            'COMPANY_ID': "12",
            'insuranceType': insuranceType,
            'insuranceTime': {
                'syEnd': utils.getlatedate(-365, str_date=_data['SY_Base.TInsrncEndTm'][:10]) + ' 23:59:59',
                'syStart': utils.getlatedate(-365, str_date=_data['SY_Base.TInsrncBgnTm'][:10]) + ' 00:00:00',
                'jqStart': utils.getlatedate(-365, str_date=_data['JQ_Base.TInsrncBgnTm'][:10]) + ' 00:00:00',
                'jqEnd': utils.getlatedate(-365, str_date=_data['JQ_Base.TInsrncEndTm'][:10]) + ' 23:59:59'}
        }

        # print out
        return out
    except Exception as e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0
Ejemplo n.º 4
0
            'engineNo': _data['Vhl.CEngNo'],  # 发动机号
            'CModelCde': _data['Vhl.CModelCde'],
            'NSeatNum': _data['Vhl.NSeatNum'],  # 座位数
            'COMPANY_ID': "12",
            'insuranceType': insuranceType,
            'insuranceTime': {
                'syEnd': utils.getlatedate(-365, str_date=_data['SY_Base.TInsrncEndTm'][:10]) + ' 23:59:59',
                'syStart': utils.getlatedate(-365, str_date=_data['SY_Base.TInsrncBgnTm'][:10]) + ' 00:00:00',
                'jqStart': utils.getlatedate(-365, str_date=_data['JQ_Base.TInsrncBgnTm'][:10]) + ' 00:00:00',
                'jqEnd': utils.getlatedate(-365, str_date=_data['JQ_Base.TInsrncEndTm'][:10]) + ' 23:59:59'}
        }

        # print out
        return out
    except Exception as e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0


if __name__ == "__main__":
    r = CRedis()
    sessBase = r.get('12_COMPANY')
    if not sessBase:
        session = login_ancheng()
    else:
        session = pickle.loads(codecs.decode(sessBase.encode(), "base64"))
    plateNumber = "苏JL5099"

    is_ancheng_renewal(session, plateNumber)
Ejemplo n.º 5
0
def get_premium(session, data):
    if not session:
        session = login_ancheng()

    if not session:
        log.info(u'安诚登录失败')
        return

    searchVin = data['vinNo']
    insureCarId = data['insureCarId']
    isPhone = data['isPhone']
    sessionId = data['sessionId']
    client = data['client']
    CPlateNo = data['plateNumber']

    insuranceType = data.get("insuranceType", {})
    insuranceType_list = []
    if isinstance(insuranceType, list):
        insuranceType_list = insuranceType
    else:
        insuranceType_list.append(insuranceType)

    insuranceTypeGroupId = insuranceType_list[0].get("insuranceTypeGroupId",
                                                     "")
    insuranceTypeGroup = insuranceType_list[0].get("insuranceTypeGroup", "")

    try:
        insuranceTime = data.get("insuranceTime", None)
        if insuranceTime:
            jqStart = insuranceTime.get("jqStart")
            syStart = insuranceTime.get("syStart")
        else:
            jqStart, syStart = utils.getlatedate(1), utils.getlatedate(1)

        # 查询redis中是否有信息
        r = CRedis()
        car_info = r.get_vin(searchVin, "12")
        if not car_info:
            car_info = query_car_info(session, data, syStart, CPlateNo,
                                      searchVin)
        else:
            car_info = eval(car_info)

        if not car_info:
            log.error(u'查询车辆信息失败')
            send_mq(client, CPlateNo, "查询车辆信息失败", "2", "12", sessionId,
                    isPhone, insuranceTypeGroupId, insuranceTypeGroup)
            return

        for insuranceType in insuranceType_list:

            # 车辆信息中塞入 licenseType
            car_info['licenseType'] = data.get("licenseType", "02")
            DW_DATA, Base_CProdNo, Vhl_NNewPurchaseValue = get_premium_request(
                session, jqStart, syStart, CPlateNo, searchVin, insuranceType,
                car_info)

            ret = get_premium_data(session, DW_DATA)
            ratio, jq_ratio = '0', '0'
            try:
                if '计算完毕' not in ret.json(
                )['RESULT_MSG'] and '重复投保' in ret.json()['RESULT_MSG']:
                    log.info(u'重复投保,重新获取终保日期')

                    sy_end_date, jq_end_date, = None, None
                    if Base_CProdNo == "0336" or Base_CProdNo == "0335":
                        if '计算完毕' not in ret.json(
                        )['RESULT_MSG'] and '商业' in ret.json()['RESULT_MSG']:

                            ra = "\\\\n终保日期:(.+?)\\\\n"
                            rb = re.compile(ra)
                            rc = re.findall(rb, ret.content)
                            if rc and 'null' not in rc:
                                sy_end_date = rc[0][:4] + '-' + rc[0][
                                    4:6] + '-' + rc[0][6:8]

                                log.info(u'商业险终保日期 - {0}'.format(sy_end_date))

                    if Base_CProdNo == "0330":
                        ra = "\d{4}-\d{2}-\d{2}"
                        rb = re.compile(ra)

                        rc = re.findall(rb, ret.json()['RESULT_MSG'])
                        if rc and 'null' not in rc:

                            if len(rc) == 2:
                                jq_end_date = rc[1] if rc[1] > rc[0] else rc[0]
                            else:
                                jq_end_date = rc[0]

                                log.info(u'交强险终保日期 - {0}'.format(jq_end_date))

                    if Base_CProdNo == "0336_0330" or Base_CProdNo == "0335_0330":

                        if '计算完毕' not in ret.json(
                        )['RESULT_MSG'] and '商业' in ret.json()['RESULT_MSG']:

                            ra = "\\\\n终保日期:(.+?)\\\\n"
                            rb = re.compile(ra)
                            rc = re.findall(rb, ret.content)
                            if rc and 'null' not in rc:
                                end_date = rc[0][:4] + '-' + rc[0][
                                    4:6] + '-' + rc[0][6:8]

                                if 'E51' in ret.json()['RESULT_MSG']:
                                    jq_end_date = end_date
                                    log.info(
                                        u'交强险终保日期 - {0}'.format(jq_end_date))
                                else:
                                    sy_end_date = end_date
                                    log.info(
                                        u'商业险终保日期 - {0}'.format(sy_end_date))

                        elif '计算完毕' not in ret.json(
                        )['RESULT_MSG'] and '商业' not in ret.json(
                        )['RESULT_MSG']:
                            ra = "\d{4}-\d{2}-\d{2}"
                            rb = re.compile(ra)

                            rc = re.findall(rb, ret.json()['RESULT_MSG'])
                            if rc and 'null' not in rc:

                                if len(rc) == 2:
                                    end_date = rc[1] if rc[1] > rc[0] else rc[0]
                                else:
                                    end_date = rc[0]

                                if 'E51' in ret.json()['RESULT_MSG']:
                                    jq_end_date = end_date
                                    log.info(
                                        u'交强险终保日期 - {0}'.format(jq_end_date))
                                else:
                                    sy_end_date = end_date
                                    log.info(
                                        u'商业险终保日期 - {0}'.format(sy_end_date))

                    if sy_end_date or jq_end_date:

                        if jq_end_date:
                            jqStart = jq_end_date
                        if sy_end_date:
                            syStart = sy_end_date

                        # car_info['endDate'] = endDate
                        # 当是重复投保,取终保日期重新发送获取保费请求
                        DW_DATA, Base_CProdNo, Vhl_NNewPurchaseValue = get_premium_request(
                            session, jqStart, syStart, CPlateNo, searchVin,
                            insuranceType, car_info)
                        ret = get_premium_data(session, DW_DATA)

                        # 将交强险的终保日期替换后还是重复投保
                        if '终保日期' in ret.json(
                        )['RESULT_MSG'] and '重复投保' in ret.json()['RESULT_MSG']:
                            log.info(u'将交强险的终保日期替换后还是重复投保')
                            if '商业' in json.dumps(ret.json(),
                                                  ensure_ascii=False):

                                ra = "\\\\n终保日期:(.+?)\\\\n"
                                rb = re.compile(ra)
                                rc = re.findall(rb, ret.content)
                                if rc and 'null' not in rc:
                                    sy_end_date = rc[0][:4] + '-' + rc[0][
                                        4:6] + '-' + rc[0][6:8]

                                    log.info(
                                        u'商业险终保日期 - {0}'.format(sy_end_date))

                                if sy_end_date:
                                    syStart = sy_end_date
                                    DW_DATA, Base_CProdNo, Vhl_NNewPurchaseValue = get_premium_request(
                                        session, jqStart, syStart, CPlateNo,
                                        searchVin, insuranceType, car_info)
                                    ret = get_premium_data(session, DW_DATA)

                        if '计算完毕' not in ret.json(
                        )['RESULT_MSG'] and '重复投保' in ret.json()['RESULT_MSG']:
                            log.info(u'重复投保,获取终保日期还是重复投保')
                            send_mq(client, CPlateNo, "重复投保,获取终保日期还是重复投保", "2",
                                    "12", sessionId, isPhone,
                                    insuranceTypeGroupId, insuranceTypeGroup)
                            return

                    else:
                        log.info(u'重复投保,无法获取终保日期,程序结束')
                        send_mq(client, CPlateNo, "重复投保,无法获取终保日期", "2", "12",
                                sessionId, isPhone, insuranceTypeGroupId,
                                insuranceTypeGroup)
                        return

                if len(ret.json()['WEB_DATA']) > 0:
                    response_body_1 = json.loads(ret.text)
                    PrmCoef_DW = \
                        jsonpath.jsonpath(response_body_1, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.PrmCoef_DW')]")[0]
                    PrmCoef_DW_dataObjVoList = jsonpath.jsonpath(
                        PrmCoef_DW, "$.dataObjVoList")
                    PrmCoef_DW_dict = PrmCoef_DW_dataObjVoList[0][0][
                        'attributeVoList']

                    SY_PrmCoef_NResvNum1, PrmCoef_NTrafficVi = None, None
                    if PrmCoef_DW_dict["SY_PrmCoef.NResvNum1"]["value"]:
                        SY_PrmCoef_NResvNum1 = float(
                            PrmCoef_DW_dict["SY_PrmCoef.NResvNum1"]
                            ["value"])  # 无忧赔款优待系数

                    if PrmCoef_DW_dict["PrmCoef.NTrafficVi"]["value"]:
                        PrmCoef_NTrafficVi = float(
                            PrmCoef_DW_dict["PrmCoef.NTrafficVi"]
                            ["value"])  # 交通违法调整系数

                    if SY_PrmCoef_NResvNum1 and PrmCoef_NTrafficVi:
                        PrmCoef_NExpectTotal = float(
                            SY_PrmCoef_NResvNum1) * float(
                                PrmCoef_NTrafficVi) * 0.85 * 0.85  # 整单期望折扣

                        # 带上整单期望折扣重新发送请求
                        DW_DATA, Base_CProdNo, Vhl_NNewPurchaseValue = get_premium_request(
                            session,
                            jqStart,
                            syStart,
                            CPlateNo,
                            searchVin,
                            insuranceType,
                            car_info,
                            PrmCoef_NExpectTotal=str(PrmCoef_NExpectTotal))
                        ret = get_premium_data(session, DW_DATA)
                    VsTax_NAggTax = None
                    if len(ret.json()['WEB_DATA']) > 0:

                        response_body_2 = json.loads(ret.text)

                        PrmCoef_DW = \
                            jsonpath.jsonpath(response_body_2, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.PrmCoef_DW')]")[0]
                        PrmCoef_DW_dataObjVoList = jsonpath.jsonpath(
                            PrmCoef_DW, "$.dataObjVoList")
                        PrmCoef_DW_dict = PrmCoef_DW_dataObjVoList[0][0][
                            'attributeVoList']

                        # 获取商业险系数

                        if PrmCoef_DW_dict["SY_PrmCoef.NTotDisc"]["value"]:
                            ratio = float(
                                PrmCoef_DW_dict["SY_PrmCoef.NTotDisc"]
                                ["value"])  # 商业险系数
                        if PrmCoef_DW_dict["JQ_PrmCoef.NTotDisc"]["value"]:
                            jq_ratio = float(
                                PrmCoef_DW_dict["JQ_PrmCoef.NTotDisc"]
                                ["value"]) / 100  # 交强险系数

                        VsTax_DW = \
                            jsonpath.jsonpath(response_body_2, "$.WEB_DATA[?(@.dwName=='prodDef.vhl.VsTax_DW')]")[0]
                        VsTax_DW_dataObjVoList = jsonpath.jsonpath(
                            VsTax_DW, "$.dataObjVoList")
                        if VsTax_DW_dataObjVoList[0]:
                            VsTax_DW_dict = VsTax_DW_dataObjVoList[0][0][
                                'attributeVoList']

                            VsTax_NAggTax = float(
                                VsTax_DW_dict["VsTax.NAggTax"]["value"])  # 车船税
                            log.info('车船税 - {0}'.format(VsTax_NAggTax))

                        Cvrg_DW = jsonpath.jsonpath(
                            response_body_2,
                            "$.WEB_DATA[?(@.dwName=='prodDef.vhl.Cvrg_DW')]"
                        )[0]
                        Cvrg_DW_dataObjVoList = jsonpath.jsonpath(
                            Cvrg_DW, "$.dataObjVoList")

                        attrs = Cvrg_DW_dataObjVoList[0]

                    else:
                        msg = ret.json()['RESULT_MSG'].replace("\n", "")

                        if '期望折扣' in msg:

                            ra = "[0-9]*\.?[0-9]+"
                            rb = re.compile(ra)

                            msg_list = re.findall(rb, msg)

                            PrmCoef_NExpectTotal = float(msg_list[0])
                            # 返回期望折扣错误重新发送请求
                            DW_DATA, Base_CProdNo, Vhl_NNewPurchaseValue = get_premium_request(
                                session,
                                jqStart,
                                syStart,
                                CPlateNo,
                                searchVin,
                                insuranceType,
                                car_info,
                                PrmCoef_NExpectTotal=str(PrmCoef_NExpectTotal))
                            ret = get_premium_data(session, DW_DATA)
                            if len(ret.json()['WEB_DATA']) > 0:
                                response_body_2 = json.loads(ret.text)

                                PrmCoef_DW = \
                                    jsonpath.jsonpath(response_body_2,
                                                      "$.WEB_DATA[?(@.dwName=='prodDef.vhl.PrmCoef_DW')]")[0]
                                PrmCoef_DW_dataObjVoList = jsonpath.jsonpath(
                                    PrmCoef_DW, "$.dataObjVoList")
                                PrmCoef_DW_dict = PrmCoef_DW_dataObjVoList[0][
                                    0]['attributeVoList']

                                # 获取商业险系数
                                if PrmCoef_DW_dict["SY_PrmCoef.NTotDisc"][
                                        "value"]:
                                    ratio = float(
                                        PrmCoef_DW_dict["SY_PrmCoef.NTotDisc"]
                                        ["value"])  # 商业险系数
                                if PrmCoef_DW_dict["JQ_PrmCoef.NTotDisc"][
                                        "value"]:
                                    jq_ratio = float(
                                        PrmCoef_DW_dict["JQ_PrmCoef.NTotDisc"]
                                        ["value"]) / 100  # 交强险系数

                                VsTax_DW = \
                                    jsonpath.jsonpath(response_body_2,
                                                      "$.WEB_DATA[?(@.dwName=='prodDef.vhl.VsTax_DW')]")[0]
                                VsTax_DW_dataObjVoList = jsonpath.jsonpath(
                                    VsTax_DW, "$.dataObjVoList")

                                if VsTax_DW_dataObjVoList[0]:
                                    VsTax_DW_dict = VsTax_DW_dataObjVoList[0][
                                        0]['attributeVoList']

                                    VsTax_NAggTax = float(
                                        VsTax_DW_dict["VsTax.NAggTax"]
                                        ["value"])  # 车船税
                                    log.info('车船税 - {0}'.format(VsTax_NAggTax))

                                Cvrg_DW = \
                                    jsonpath.jsonpath(response_body_2,
                                                      "$.WEB_DATA[?(@.dwName=='prodDef.vhl.Cvrg_DW')]")[
                                        0]
                                Cvrg_DW_dataObjVoList = jsonpath.jsonpath(
                                    Cvrg_DW, "$.dataObjVoList")

                                attrs = Cvrg_DW_dataObjVoList[0]

                            else:
                                msg = ret.json()['RESULT_MSG'].replace(
                                    "\n", "")
                                if '无法加载模板缓存' in msg:
                                    log.info(u'无法加载模板缓存, 重新请求')
                                    return get_premium(session, data)
                                log.error(msg)
                                send_mq(client, CPlateNo, msg, "2", "12",
                                        sessionId, isPhone,
                                        insuranceTypeGroupId,
                                        insuranceTypeGroup)
                                return

                        else:
                            if '无法加载模板缓存' in msg:
                                log.info(u'无法加载模板缓存, 重新请求')
                                return get_premium(session, data)
                            log.error(msg)
                            send_mq(client, CPlateNo, msg, "2", "12",
                                    sessionId, isPhone, insuranceTypeGroupId,
                                    insuranceTypeGroup)
                            return
                else:
                    msg = ret.json()['RESULT_MSG'].replace("\n", "")
                    if '无法加载模板缓存' in msg:
                        log.info(u'无法加载模板缓存, 重新请求')
                        return get_premium(session, data)
                    log.error(msg)
                    send_mq(client, CPlateNo, msg, "2", "12", sessionId,
                            isPhone, insuranceTypeGroupId, insuranceTypeGroup)
                    return

            except Exception as e:
                log.error(e)
                log.error(traceback.format_exc())
                send_mq(client, CPlateNo, "未知异常", "2", "12", sessionId,
                        isPhone, insuranceTypeGroupId, insuranceTypeGroup)
                return

            Premium = {}
            MarkPremium = {}
            hebao_premium = {}
            total_money = 0
            total_mark_money = 0

            # 计算保费
            for i, k in enumerate(attrs):
                num = int(k["attributeVoList"]["Cvrg.NSeqNo"]["value"])
                if num == 15:
                    # otherHurtPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 三者险
                    otherHurtPremium = float(
                        k["attributeVoList"]["Cvrg.NCalcAnnPrm"]
                        ["value"])  # 三者险
                    total_money += otherHurtPremium
                    log.info(str(otherHurtPremium) + u' 三者险')
                    Premium['otherHurtPremium'] = round(otherHurtPremium, 2)
                    hebao_premium['otherHurtPremium'] = otherHurtPremium

                    otherHurtBenchMarkPremium = otherHurtPremium * 0.15  # 三者险不计免赔
                    total_mark_money += otherHurtBenchMarkPremium
                    MarkPremium['otherHurtBenchMarkPremium'] = round(
                        otherHurtBenchMarkPremium, 2)

                elif num == 20:
                    # carDamagePremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]["value"]) * ratio  # 车损险应缴保费
                    carDamagePremium = float(
                        k["attributeVoList"]["Cvrg.NCalcAnnPrm"]
                        ["value"])  # 车损险应缴保费
                    total_money += carDamagePremium
                    log.info(str(carDamagePremium) + u' 车损险应缴保费')
                    Premium['carDamagePremium'] = round(carDamagePremium, 2)
                    hebao_premium['carDamagePremium'] = carDamagePremium

                    carDamageBenchMarkPremium = carDamagePremium * 0.15  # 车损险不计免赔
                    total_mark_money += carDamageBenchMarkPremium
                    MarkPremium['carDamageBenchMarkPremium'] = round(
                        carDamageBenchMarkPremium, 2)

                elif num == 13:
                    driverDutyPremium = float(
                        k["attributeVoList"]["Cvrg.NBefPrm"]
                        ["value"]) * ratio  # 车上人员险(司机)
                    total_money += driverDutyPremium
                    log.info(str(driverDutyPremium) + u' 车上人员险(司机)')
                    Premium['driverDutyPremium'] = round(driverDutyPremium, 2)
                    hebao_premium['driverDutyPremium'] = driverDutyPremium

                    driverDutyBenchMarkPremium = driverDutyPremium * 0.15  # 车上人员险(司机)不计免赔
                    total_mark_money += driverDutyBenchMarkPremium
                    MarkPremium['driverDutyBenchMarkPremium'] = round(
                        driverDutyBenchMarkPremium, 2)

                elif num == 14:
                    passengerDutyPremium = float(
                        k["attributeVoList"]["Cvrg.NBefPrm"]
                        ["value"]) * ratio  # 车上人员险(乘客)
                    total_money += passengerDutyPremium
                    log.info(str(passengerDutyPremium) + u' 车上人员险(乘客)')
                    Premium['passengerDutyPremium'] = round(
                        passengerDutyPremium, 2)
                    hebao_premium[
                        'passengerDutyPremium'] = passengerDutyPremium

                    passengerBenchMarkPremium = passengerDutyPremium * 0.15  # 车上人员险(乘客)不计免赔
                    total_mark_money += passengerBenchMarkPremium
                    MarkPremium['passengerBenchMarkPremium'] = round(
                        passengerBenchMarkPremium, 2)

                elif num == 18:
                    carTheftPremium = float(
                        k["attributeVoList"]["Cvrg.NBefPrm"]
                        ["value"]) * ratio  # 盗抢险
                    total_money += carTheftPremium
                    log.info(str(carTheftPremium) + u' 盗抢险')
                    Premium['carTheftPremium'] = round(carTheftPremium, 2)
                    hebao_premium['carTheftPremium'] = carTheftPremium

                    carTheftBenchMarkPremium = carTheftPremium * 0.20  # 盗抢险不计免赔
                    total_mark_money += carTheftBenchMarkPremium
                    MarkPremium['carTheftBenchMarkPremium'] = round(
                        carTheftBenchMarkPremium, 2)

                elif num == 19:
                    carNickPremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]
                                           ["value"]) * ratio  # 划痕险
                    total_money += carNickPremium
                    log.info(str(carNickPremium) + u' 划痕险')
                    Premium['carNickPremium'] = round(carNickPremium, 2)
                    hebao_premium['carNickPremium'] = carNickPremium

                    carNickBenchMarkPremium = carNickPremium * 0.15  # 划痕险不计免赔
                    total_mark_money += carNickBenchMarkPremium
                    MarkPremium['carNickBenchMarkPremium'] = round(
                        carNickBenchMarkPremium, 2)

                elif num == 8:
                    glassBrokenPremium = float(
                        k["attributeVoList"]["Cvrg.NBefPrm"]
                        ["value"]) * ratio  # 玻璃破碎险
                    total_money += glassBrokenPremium
                    log.info(str(glassBrokenPremium) + u' 玻璃破碎险')
                    Premium['glassBrokenPremium'] = round(
                        glassBrokenPremium, 2)
                    hebao_premium['glassBrokenPremium'] = glassBrokenPremium

                    glassBrokenMarkPremium = glassBrokenPremium * 0.20  # 玻璃破碎险不计免赔
                    total_mark_money += glassBrokenMarkPremium
                    MarkPremium['glassBrokenMarkPremium'] = round(
                        glassBrokenMarkPremium, 2)

                elif num == 5:
                    carFirePremium = float(k["attributeVoList"]["Cvrg.NBefPrm"]
                                           ["value"]) * ratio  # 自燃险
                    total_money += carFirePremium
                    log.info(str(carFirePremium) + u' 自燃险')
                    Premium['carFirePremium'] = round(carFirePremium, 2)
                    hebao_premium['carFirePremium'] = carFirePremium

                    carFireMarkPremium = carFirePremium * 0.20  # 自燃险不计免赔
                    total_mark_money += carFireMarkPremium
                    MarkPremium['carFireMarkPremium'] = round(
                        carFireMarkPremium, 2)

                elif num == 10:
                    engineWadingPremium = float(
                        k["attributeVoList"]["Cvrg.NBefPrm"]
                        ["value"]) * ratio  # 涉水险
                    total_money += engineWadingPremium
                    log.info(str(engineWadingPremium) + u' 涉水险')
                    Premium['engineWadingPremium'] = round(
                        engineWadingPremium, 2)
                    hebao_premium['engineWadingPremium'] = engineWadingPremium

                    engineWadingMarkPremium = engineWadingPremium * 0.15  # 涉水险不计免赔
                    total_mark_money += engineWadingMarkPremium
                    MarkPremium['engineWadingMarkPremium'] = round(
                        engineWadingMarkPremium, 2)

                elif num == 1:
                    compulsory_insurance = float(
                        k["attributeVoList"]["Cvrg.NBefPrm"]
                        ["value"]) * jq_ratio  # 交强险
                    log.info(str(compulsory_insurance) + u' 交强险')
                    Premium['compulsory_insurance'] = round(
                        compulsory_insurance, 2)
                    hebao_premium[
                        'compulsory_insurance'] = compulsory_insurance

                if VsTax_NAggTax:
                    Premium['NAggTax'] = round(VsTax_NAggTax, 2)
                    hebao_premium['NAggTax'] = VsTax_NAggTax

            total_premium = total_money + total_mark_money

            log.info(u'商业险应缴保费总额 - {0}'.format(total_money))
            log.info(u'应缴保费不计免赔总额 - {0}'.format(total_mark_money))
            log.info(u'应缴保费总额 - {0}'.format(total_premium))

            # hebao_premium = Premium
            hebao_premium['total_mark_premium'] = total_mark_money
            hebao_premium['total_premium'] = total_premium

            BaoE = {}

            _driverDutyPremium = insuranceType.get("driverDutyPremium", None)
            _carDamagePremium = insuranceType.get("carDamagePremium", "0")
            _otherHurtPremium = insuranceType.get("otherHurtPremium", None)
            _passengerDutyPremium = insuranceType.get("passengerDutyPremium",
                                                      None)
            _carTheftPremium = insuranceType.get("carTheftPremium", "0")
            _carFireBrokenBenchMarkPremium = insuranceType.get(
                "carFirePremium", "0")
            _engineWadingBenchMarkPremium = insuranceType.get(
                "engineWadingPremium", "0")
            _carNickPremium = insuranceType.get("carNickPremium", None)  # 划痕险

            Vhl_NNewPurchaseValue = car_info['Vhl_NNewPurchaseValue']
            seats = car_info.get('seats', 5)

            otherHurtBaoE = float(
                _otherHurtPremium.get("Amount")) if _otherHurtPremium and int(
                    _otherHurtPremium.get("isCheck"), 0) and int(
                        _otherHurtPremium.get("Amount"), 0) else None  # 三者险保额
            if otherHurtBaoE:
                BaoE['otherHurtBaoE'] = round(otherHurtBaoE, 2)

            carDamageBaoE = float(Vhl_NNewPurchaseValue) if int(
                _carDamagePremium) else None  # 车损险保额
            if carDamageBaoE:
                BaoE['carDamageBaoE'] = round(carDamageBaoE, 2)

            driverDutyBaoE = float(
                _driverDutyPremium.get("Amount")
            ) if _driverDutyPremium and int(
                _driverDutyPremium.get("isCheck"), 0) and int(
                    _driverDutyPremium.get("Amount"), 0) else None  # 驾驶人责任险
            if driverDutyBaoE:
                BaoE['driverDutyBaoE'] = round(driverDutyBaoE, 2)

            passengerDutyBaoE = float(_passengerDutyPremium.get("Amount")) * (
                seats - 1) if _passengerDutyPremium and int(
                    _passengerDutyPremium.get("isCheck"), 0) and int(
                        _passengerDutyPremium.get("Amount"),
                        0) else None  # 乘客责任险
            if passengerDutyBaoE:
                BaoE['passengerDutyBaoe'] = round(passengerDutyBaoE, 2)

            carTheftBaoE = float(Vhl_NNewPurchaseValue) if int(
                _carTheftPremium) else None  # 车盗险保额
            if carTheftBaoE:
                BaoE['carTheftBaoE'] = round(carTheftBaoE, 2)

            carNickBaoE = float(
                _carNickPremium.get("Amount")) if _carNickPremium and int(
                    _carNickPremium.get("isCheck"), 0) and int(
                        _carNickPremium.get("Amount"), 0) else None  # 划痕险保额
            if carNickBaoE:
                BaoE['carNickBaoE'] = round(carNickBaoE, 2)

            engineWadingBaoE = float(Vhl_NNewPurchaseValue) if int(
                _engineWadingBenchMarkPremium) else None  # 涉水险保额
            if engineWadingBaoE:
                BaoE['engineWadingBaoE'] = round(engineWadingBaoE, 2)

            carFireBaoE = float(Vhl_NNewPurchaseValue) if int(
                _carFireBrokenBenchMarkPremium) else None  # 自燃险保额
            if carFireBaoE:
                BaoE['carFireBaoE'] = round(carFireBaoE, 2)

            disCount = {"sy_disCount": ratio, "jq_disCount": jq_ratio}

            PremiumInfo = [Premium, BaoE, MarkPremium, disCount]

            log.info(PremiumInfo)

            soupDb(PremiumInfo, [
                utils.getlatedate(1) + ' 00:00:00',
                utils.getlatedate(365) + " 23:59:59", seats,
                insuranceTypeGroupId, insureCarId, "12"
            ])

            send_mq(client, CPlateNo, "", "1", "12", sessionId, isPhone,
                    insuranceTypeGroupId, insuranceTypeGroup)
            log.info(u"安城入库成功:%s|%s" % (CPlateNo, searchVin))

            if HEBAO_KEY and car_info.get("licenseType", "02") != "02":
                r = CRedis()
                try:
                    DW_DATA, Base_CProdNo, Vhl_NNewPurchaseValue = get_premium_request(
                        session,
                        jqStart,
                        syStart,
                        CPlateNo,
                        searchVin,
                        insuranceType,
                        car_info,
                        hebao_premium=hebao_premium)

                    ret = save_premium(session, DW_DATA)

                    WEB_DATA = ret.json()['WEB_DATA']

                    sy_appno, jq_appno = '', ''
                    for data in WEB_DATA:
                        if data['dataObjVoList']:
                            if 'SY_Base.CAppNo' in data['dataObjVoList'][0][
                                    'attributeVoList']:
                                sy_appno = data['dataObjVoList'][0][
                                    'attributeVoList']['SY_Base.CAppNo'][
                                        'value']
                            if 'JQ_Base.CAppNo' in data['dataObjVoList'][0][
                                    'attributeVoList']:
                                jq_appno = data['dataObjVoList'][0][
                                    'attributeVoList']['JQ_Base.CAppNo'][
                                        'value']

                    if sy_appno:
                        log.info(u'商业险投保单号 - {0}'.format(sy_appno))
                        ret = he_bao2(session, sy_appno)
                        RESULT_TYPE = ret.json()["RESULT_TYPE"]
                        RESULT_MSG = ret.json()["RESULT_MSG"].replace("\n", "")
                        log.info(u'核保状态 - {0} - {1}'.format(
                            RESULT_TYPE, RESULT_MSG))

                        SY_PremiumInfo = PremiumInfo
                        if 'compulsory_insurance' in SY_PremiumInfo[0]:
                            SY_PremiumInfo[0].pop('compulsory_insurance')
                        if 'jq_disCount' in SY_PremiumInfo[3]:
                            SY_PremiumInfo[3].pop('jq_disCount')

                        if RESULT_TYPE == "SUCCESS":
                            data = {
                                'appNo':
                                sy_appno,
                                'PremiumInfo':
                                SY_PremiumInfo,
                                'insuranceType':
                                insuranceType,
                                'create_date':
                                time.strftime('%Y-%m-%d %X',
                                              time.localtime(time.time())),
                                'companyId':
                                '12',
                                'Status_Code':
                                '0',
                                'CPlateNo':
                                CPlateNo,
                                'sessionId':
                                sessionId,
                                'isphone':
                                isPhone
                            }

                            mg_insert('hebaoinfo', data)
                            r.set_appno(sy_appno, '12')
                            log.info(u'商业险投保单号 - {0} - 入库成功'.format(sy_appno))
                            send_mq(client,
                                    CPlateNo,
                                    "",
                                    "1",
                                    "12",
                                    sessionId,
                                    isPhone,
                                    insuranceTypeGroupId,
                                    insuranceTypeGroup,
                                    licenseType=car_info.get(
                                        "VEHICLE_TYPE", '02'),
                                    vehicle_style=car_info.get(
                                        "VEHICLE_STYLE", "K33"))
                        else:
                            send_mq(client,
                                    CPlateNo,
                                    "",
                                    "2",
                                    "12",
                                    sessionId,
                                    isPhone,
                                    insuranceTypeGroupId,
                                    insuranceTypeGroup,
                                    licenseType=car_info.get(
                                        "VEHICLE_TYPE", '02'),
                                    vehicle_style=car_info.get(
                                        "VEHICLE_STYLE", "K33"))

                    if jq_appno:
                        log.info(u'交强险投保单号 - {0}'.format(jq_appno))
                        ret = he_bao2(session, jq_appno)
                        RESULT_TYPE = ret.json()["RESULT_TYPE"]
                        RESULT_MSG = ret.json()["RESULT_MSG"].replace("\n", "")
                        log.info(u'核保状态 - {0} - {1}'.format(
                            RESULT_TYPE, RESULT_MSG))

                        JQ_PremiumInfo = [{
                            'compulsory_insurance':
                            compulsory_insurance
                        }, {}, {}, {
                            'jq_disCount': jq_ratio
                        }]

                        if RESULT_TYPE == "SUCCESS":
                            data = {
                                'appNo':
                                jq_appno,
                                'PremiumInfo':
                                JQ_PremiumInfo,
                                'insuranceType':
                                insuranceType,
                                'create_date':
                                time.strftime('%Y-%m-%d %X',
                                              time.localtime(time.time())),
                                'companyId':
                                '12',
                                'Status_Code':
                                '0',
                                'CPlateNo':
                                CPlateNo,
                                'sessionId':
                                sessionId,
                                'isphone':
                                isPhone
                            }

                            mg_insert('hebaoinfo', data)
                            log.info(u'交强险投保单号 - {0} - 入库成功'.format(jq_appno))

                    else:
                        send_mq(client,
                                CPlateNo,
                                "",
                                "2",
                                "12",
                                sessionId,
                                isPhone,
                                insuranceTypeGroupId,
                                insuranceTypeGroup,
                                licenseType=car_info.get("VEHICLE_TYPE", '02'),
                                vehicle_style=car_info.get(
                                    "VEHICLE_STYLE", "K33"))

                except Exception as e:
                    log.error(e)
                    log.error(traceback.format_exc())
        return

    except Exception as e:
        log.error(traceback.format_exc())
        send_mq(client, CPlateNo, "未知异常", "2", "12", sessionId, isPhone,
                insuranceTypeGroupId, insuranceTypeGroup)
        return 0
Ejemplo n.º 6
0
def query_car_info(session, data, syStart, CPlateNo, searchVin):
    try:
        ret = query_car(session, CPlateNo, searchVin)

        if '车辆识别失败' in ret.text or not ret.text:

            # 交管车型查询
            try:
                result = None
                for i in range(5):
                    result = get_car(session, CPlateNo, searchVin)
                    if '录入的校验码有误' not in result.text:
                        break
                    if i == 4 and '录入的校验码有误' in result.text:
                        log.info('验证码5次识别失败')
                        return 0

                if '交管车辆查询校验信息不存在' in result.text:
                    log.info('{0},{1} - 交管车辆查询校验信息不存在'.format(
                        CPlateNo, searchVin))
                    return 0

                ra = "DATA:\['(.*?)'\]"
                rb = re.compile(ra)

                title_list = re.findall(rb, result.text)
                if not title_list:
                    log.info('{0},{1} - 交管车辆查询校验信息不存在'.format(
                        CPlateNo, searchVin))
                    return 0
                html = title_list[0]
                soup = BeautifulSoup(html, 'html.parser')
                a = soup.find('dataobj', attrs={"status": "UNCHANGED"})
                soup = BeautifulSoup(str(a), 'html.parser')
            except Exception as e:
                log.error(e)
                log.error(traceback.format_exc())
                return 0

            VEHICLE_MODEL = soup.find("attribute",
                                      attrs={
                                          "name": "VEHICLE_MODEL"
                                      }).get_text()  # 车辆型号

            VEHICLE_MODEL = VEHICLE_MODEL[:-1] + VEHICLE_MODEL[-1:].lower()

            ret = query_car_model(session, VEHICLE_MODEL)

            if '车辆识别失败' in ret.text or not ret.text:
                log.info(u'{0},{1} - 车辆识别失败'.format(CPlateNo, searchVin))
                return 0

        ra = "DATA:\['(.*?)'\]"
        rb = re.compile(ra)

        title_list = re.findall(rb, ret.text)
        if not title_list:
            session = login_ancheng()
            from request_ancheng.request_premium import get_premium
            return get_premium(session, data)

        html = title_list[0]
        soup = BeautifulSoup(html, 'html.parser')
        a = soup.find_all('dataobj', attrs={"status": "UNCHANGED"})
        a = list(a)

        c = sorted(a,
                   key=lambda x: int(
                       BeautifulSoup(str(x), 'html.parser').find(
                           "attribute", attrs={
                               "name": "VehiclePrice"
                           }).get_text()),
                   reverse=False)

        if not c:
            return 0

        d = c[0]
        car_value = int(
            BeautifulSoup(str(d), 'html.parser').find("attribute",
                                                      attrs={
                                                          "name":
                                                          "VehiclePrice"
                                                      }).get_text())
        log.info(u'车辆价格 - {0}'.format(car_value))

        soup = BeautifulSoup(str(d), 'html.parser')
    except Exception as e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0

    Vhl_CBrandNme = soup.find("attribute", attrs={
        "name": "BrandName"
    }).get_text()  # 品牌
    Cmodel_Code = soup.find("attribute", attrs={
        "name": "VehicleId"
    }).get_text()[:10]  # PK

    log.info(u'车型编码 - {0}'.format(Cmodel_Code))

    Vhl_NResvNum2 = soup.find("attribute", attrs={
        "name": "VehiclePrice"
    }).get_text()  # 车辆价格
    Vhl_CProdPlace = soup.find("attribute", attrs={
        "name": "VehicleType"
    }).get_text()  # 种类
    NewVehicleClass = soup.find("attribute", attrs={
        "name": "NewVehicleClass"
    }).get_text()  # 车辆种类 牵引车 等
    seat_01 = int(
        soup.find("attribute", attrs={
            "name": "VehicleSeat"
        }).get_text())  # 座位数
    Vhl_CModelNme = soup.find("attribute", attrs={
        "name": "VehicleName"
    }).get_text()  # 车型名称

    Vhl_CGroupNme = soup.find("attribute", attrs={
        "name": "GroupName"
    }).get_text()  # 车组名称

    code = unicode(CPlateNo)[1]

    Base_CAreaFlag = city_map.get(code, '320100')
    Base_CCountyCde = city_map_2.get(code, '320101')

    Vhl_CProdPlace = "0" if Vhl_CProdPlace == "国产" else "1"

    try:
        ret = get_vehcle_code(session, Cmodel_Code)

        ra = "###(.+?)###"
        rb = re.compile(ra)

        Vehcle_Code = re.findall(rb, ret.text)[0]

        if Vehcle_Code == 'null':
            log.info(u'无法获取行业车型编码')
            return 0

    except Exception as e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0

    # 交管车型查询
    try:
        result = None
        for i in range(5):
            result = get_car(session, CPlateNo, searchVin)
            if not '录入的校验码有误' in result.text:
                break
            if i == 4 and '录入的校验码有误' in result.text:
                log.info(u'验证码5次识别失败')
                return 0

        if '交管车辆查询校验信息不存在' in result.text:
            log.info(u'{0},{1} - 交管车辆查询校验信息不存在'.format(CPlateNo, searchVin))
            return 0

        ra = "DATA:\['(.*?)'\]"
        rb = re.compile(ra)

        title_list = re.findall(rb, result.text)
        html = title_list[0]
        soup = BeautifulSoup(html, 'html.parser')
        a = soup.find('dataobj', attrs={"status": "UNCHANGED"})
        soup = BeautifulSoup(str(a), 'html.parser')
    except Exception as e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0

    Applicant_CAppNme = soup.find("attribute", attrs={
        "name": "OWNER"
    }).get_text()  # 车主
    Insured_CInsuredNme = Applicant_CAppNme

    Applicant_CAppNme = unicode(Applicant_CAppNme)
    if len(Applicant_CAppNme) >= 5:
        Applicant_CAppNme = '测试单位'
        Applicant_CClntMrk = '3'
        Insured_CClntMrk = '3'
    else:
        Applicant_CAppNme = "测试个人"
        Applicant_CClntMrk = '1'
        Insured_CClntMrk = '1'

    Vhl_CFstRegYm = soup.find("attribute",
                              attrs={
                                  "name": "VEHICLE_REGISTER_DATE"
                              }).get_text()  # 初登日期
    Vhl_CRegVhlTyp = soup.find("attribute", attrs={
        "name": "VEHICLE_STYLE"
    }).get_text()  # 交管车辆种类
    LIMIT_LOAD_PERSON = soup.find("attribute",
                                  attrs={
                                      "name": "LIMIT_LOAD_PERSON"
                                  }).get_text()  # 座位数
    DISPLACEMENT = soup.find("attribute", attrs={
        "name": "DISPLACEMENT"
    }).get_text()  # 排量
    VEHICLE_TYPE = soup.find("attribute", attrs={
        "name": "VEHICLE_TYPE"
    }).get_text()  # 号牌种类 01 大型汽车 02 小型汽车 15 挂车
    SY_Vhl_TTransferDate = soup.find("attribute",
                                     attrs={
                                         "name": "TRANSFER_DATE"
                                     }).get_text()  # 过户日期
    PM_USE_TYPE = soup.find("attribute", attrs={
        "name": "PM_USE_TYPE"
    }).get_text()  # 使用性质 F商业 A家用
    VEHICLE_STYLE = soup.find("attribute", attrs={
        "name": "VEHICLE_STYLE"
    }).get_text()  # 车辆类型 K31 K33 、Q11货车
    HAULAGE = soup.find("attribute", attrs={
        "name": "HAULAGE"
    }).get_text()  # 牵引质量 牵引车
    LIMIT_LOAD = soup.find("attribute", attrs={
        "name": "LIMIT_LOAD"
    }).get_text()  # 核定载质量
    VEHICLE_CATEGORY = soup.find("attribute",
                                 attrs={
                                     "name": "VEHICLE_CATEGORY"
                                 }).get_text()  # 平台车辆种类(编码)
    Vhl_NPoWeight = soup.find("attribute", attrs={
        "name": "WHOLE_WEIGHT"
    }).get_text()  # 整备质量

    SY_Vhl_CVhlTransFlag = '0'
    JQ_Vhl_CVhlTransFlag = '0'

    if SY_Vhl_TTransferDate:
        SY_Vhl_CVhlTransFlag = '1'
        JQ_Vhl_CVhlTransFlag = '1'

    DISPLACEMENT = float(DISPLACEMENT) / 1000

    Vhl_NDisplacement = str(DISPLACEMENT)  # 排量

    WHOLE_WEIGHT = float(
        soup.find("attribute", attrs={
            "name": "WHOLE_WEIGHT"
        }).get_text())
    WHOLE_WEIGHT = float(WHOLE_WEIGHT) / 1000

    VsTax_NCurbWt = str(WHOLE_WEIGHT)  # 整备质量

    seats = int(LIMIT_LOAD_PERSON)
    # 车管所查询出的座位数为0 使用车辆信息中的座位数
    if seat_01 != "" and LIMIT_LOAD_PERSON == "0":
        seats = int(seat_01)

    Vhl_CFstRegYm = Vhl_CFstRegYm[:4] + '-' + Vhl_CFstRegYm[
        4:6] + '-' + Vhl_CFstRegYm[6:]
    Vhl_CEngNo = soup.find("attribute", attrs={
        "name": "ENGINE_NO"
    }).get_text()  # 发动机号

    _VEHICLE_REGISTER_DATE = soup.find("attribute",
                                       attrs={
                                           "name": "VEHICLE_REGISTER_DATE"
                                       }).get_text()  # 车辆注册时间
    VEHICLE_REGISTER_DATE = _VEHICLE_REGISTER_DATE[:4] + '-' + _VEHICLE_REGISTER_DATE[
        4:6] + '-' + _VEHICLE_REGISTER_DATE[6:]

    car_info = {}

    car_info['Vhl_CBrandNme'] = Vhl_CBrandNme
    car_info['Vhl_NResvNum2'] = Vhl_NResvNum2
    car_info['Vhl_CProdPlace'] = Vhl_CProdPlace
    car_info['Applicant_CAppNme'] = Applicant_CAppNme
    car_info['Vhl_CFstRegYm'] = Vhl_CFstRegYm
    car_info['Vhl_CRegVhlTyp'] = Vhl_CRegVhlTyp
    car_info['seats'] = seats
    car_info['Vhl_CEngNo'] = Vhl_CEngNo
    car_info['VEHICLE_REGISTER_DATE'] = VEHICLE_REGISTER_DATE
    car_info['Vehcle_Code'] = Vehcle_Code
    car_info['Cmodel_Code'] = Cmodel_Code
    car_info['Vhl_NDisplacement'] = Vhl_NDisplacement
    car_info['VsTax_NCurbWt'] = VsTax_NCurbWt
    car_info['VEHICLE_TYPE'] = VEHICLE_TYPE
    car_info['VEHICLE_CATEGORY'] = VEHICLE_CATEGORY
    car_info['PM_USE_TYPE'] = PM_USE_TYPE
    car_info['VEHICLE_STYLE'] = VEHICLE_STYLE
    car_info['HAULAGE'] = HAULAGE
    car_info['LIMIT_LOAD'] = LIMIT_LOAD
    car_info['SY_Vhl_CVhlTransFlag'] = SY_Vhl_CVhlTransFlag
    car_info['JQ_Vhl_CVhlTransFlag'] = JQ_Vhl_CVhlTransFlag
    car_info['SY_Vhl_TTransferDate'] = SY_Vhl_TTransferDate
    car_info['NewVehicleClass'] = NewVehicleClass
    car_info['Vhl_CModelNme'] = Vhl_CModelNme
    car_info['CPlateNo'] = CPlateNo
    car_info['Vhl_CGroupNme'] = Vhl_CGroupNme
    car_info['Insured_CInsuredNme'] = Insured_CInsuredNme
    car_info['Vhl_NPoWeight'] = Vhl_NPoWeight

    car_info['Base_CAreaFlag'] = Base_CAreaFlag
    car_info['Base_CCountyCde'] = Base_CCountyCde
    car_info['Applicant_CClntMrk'] = Applicant_CClntMrk
    car_info['Insured_CClntMrk'] = Insured_CClntMrk

    car_class_dict = get_car_class(car_info)
    if not car_class_dict:
        return None

    car_info['SY_Vhl_CBizMrk'] = car_class_dict['SY_Vhl_CBizMrk']
    car_info['JQ_Vhl_CBizMrk'] = car_class_dict['JQ_Vhl_CBizMrk']
    car_info['SY_Vhl_CUsageCde'] = car_class_dict['SY_Vhl_CUsageCde']
    car_info['JQ_Vhl_CUsageCde'] = car_class_dict['JQ_Vhl_CUsageCde']
    car_info['SY_Vhl_CVhlTyp'] = car_class_dict['SY_Vhl_CVhlTyp']
    car_info['JQ_Vhl_CVhlTyp'] = car_class_dict['JQ_Vhl_CVhlTyp']
    car_info['Vhl_NTonage'] = car_class_dict['Vhl_NTonage']
    car_info['is_tezhongche'] = car_class_dict['is_tezhongche']
    car_info['is_guache'] = car_class_dict['is_guache']
    car_info['SY_Vhl_CMonDespRate'] = car_class_dict['SY_Vhl_CMonDespRate']

    # 查询保额
    Vhl_NNewPurchaseValue = get_Vhl_NNewPurchaseValue(
        syStart, Vhl_CFstRegYm, car_class_dict['SY_Vhl_CMonDespRate'],
        Vhl_NResvNum2)

    log.info('保额 - {0}'.format(Vhl_NNewPurchaseValue))

    car_info['Vhl_NNewPurchaseValue'] = Vhl_NNewPurchaseValue
    r = CRedis()
    r.set_vin(searchVin, "12", json.dumps(car_info, ensure_ascii=False))

    return car_info