def _result_insert(fee_resp, renewal_data_dt): log = Logger() insureCarId = renewal_data_dt.get('insureCarId', '') CPlateNo = renewal_data_dt.get('plateNumber', '') client = renewal_data_dt.get('client', '') isPhone = renewal_data_dt['isPhone'] sessionId = renewal_data_dt.get('sessionId', '') insuranceType = renewal_data_dt.get("insuranceType", {}) if isinstance(insuranceType, list): insureTypeGroupId = insuranceType[0].get("insuranceTypeGroupId", "") insuranceTypeGroup = insuranceType[0].get("insuranceTypeGroup", "") else: insureTypeGroupId = insuranceType.get("insuranceTypeGroupId", "") insuranceTypeGroup = insuranceType.get("insuranceTypeGroup", "") if isinstance(fee_resp, dict): data = [] data.append(fee_resp['c01beginTime']) data.append(fee_resp['c01endTime']) data.append(fee_resp['vehicleSeats']) data.append(insureTypeGroupId) data.append(insureCarId) data.append("1") # log.info("平安开始入库 %s" % CPlateNo) soupDb(fee_resp['fee'], data) log.info("平安入库成功 %s ", CPlateNo) send_mq(client, CPlateNo, "", "1", "1", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) else: if isinstance(fee_resp, list): fee_resp = json.dumps(fee_resp, encoding=False) log.error(fee_resp) else: log.error(fee_resp) send_mq(client, CPlateNo, fee_resp, "2", "1", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup)
def startCicc(loginRes, data): session = loginRes[0] userId = loginRes[1] modelName = data['vehicleBrand'].encode('utf-8') chassisNo = data['vinNo'].encode('utf-8') motorNo = data['engineNo'].encode('utf-8') enrollDate = data['firstRegister'].encode('utf-8') licenseNo = data['plateNumber'].encode('utf-8') driverName = data['custName'].encode('utf-8') driverIDNumber = data['identitCard'].encode('utf-8') INSURE_CAR_ID = data['insureCarId'] client = data['client'] sessionId = data['sessionId'] isPhone = data['isPhone'] insuranceType = data['insuranceType'] #保险组合类型 groupId = insuranceType['insuranceTypeGroupId'] insuranceTypeGroup = insuranceType['insuranceTypeGroup'] carModelRes = getCarModel.getCarModel(session, modelName, chassisNo, motorNo, enrollDate, licenseNo) carModelRes = carModelRes.replace('null', '""') carModelRes = carModelRes.replace("'", '"') carModelResJson = ast.literal_eval(carModelRes) jsCheckCode = carModelResJson['result']['items'][0]['jsCheckCode'] # codeStr = request_cicc.util.pic2Str(base64.b64decode(jsCheckCode)) jsCheckNo = carModelResJson['result']['items'][0]['jsCheckNo'] carModel = getCarModel.selectMinPriceModel(carModelRes) vcodeRes = getCarModel.postSelectCarModel(session, modelName, chassisNo, motorNo, enrollDate, licenseNo, carModel, jsCheckCode, "1111", jsCheckNo) log.info(u"大地 ,%s,第一次上报验证码完成" % licenseNo) # codeStr = request_cicc.util.pic2Str(base64.b64decode(vcodeRes['result']['jsCheckCode'])) codeStr = "1111" try: enrollDate = vcodeRes['result']['jsEnrollDate'] except: enrollDate = data['firstRegister'].encode('utf-8') log.info(enrollDate) endDate = data.get('preInsureEndDate', '') priumeDic = calculatePost.calculatePremium(insuranceType, session, userId, driverName, driverIDNumber, licenseNo, chassisNo, motorNo, enrollDate, codeStr, modelName, carModel['replacementValue'], vcodeRes, endDate) log.info(u"大地 ,%s,第二次上报验证码完成" % licenseNo) result = priumeDic['result'][0] calculateErrMeg = result.get('insuranceApplication.calculateErrMeg', None) while calculateErrMeg is not None: endDate = "" if "车主名称与交管信息不一致" in calculateErrMeg: log.error(u"大地重复投保 %s ,返回信息 %s " % (licenseNo, calculateErrMeg)) str2 = calculateErrMeg.split(":") str2 = str2[2].split(';') driverName = str2[0] if "保单发生重复投保" in calculateErrMeg: str1 = "\d{4}-\d{2}-\d{2}" datelist = re.findall(str1, calculateErrMeg, re.S) log.error(u"大地重复投保 %s ,返回信息 %s " % (licenseNo, calculateErrMeg)) if len(datelist) == 2: endDate = compare_date(datelist[0], datelist[1]) priumeDic = calculatePost.calculatePremium( insuranceType, session, userId, driverName, driverIDNumber, licenseNo, chassisNo, motorNo, enrollDate, codeStr, modelName, carModel['replacementValue'], vcodeRes, endDate) result = priumeDic['result'][0] calculateErrMeg = result.get('insuranceApplication.calculateErrMeg', None) if calculateErrMeg is not None: if (not "车主名称与交管信息不一致" in calculateErrMeg) and ( not "保单发生重复投保" in calculateErrMeg): send_mq(client, licenseNo, "车主名称与交管信息不一致 or 保单发生重复投保 ", "2", "5", sessionId, isPhone, groupId, insuranceTypeGroup) log.error(u"%s %s" % (licenseNo, calculateErrMeg)) break try: PremiumInfo = translate.getPriumeInf(priumeDic, vcodeRes['result']['seatCount']) send_mq(client, licenseNo, "", "1", "5", sessionId, isPhone, groupId, insuranceTypeGroup) except: print traceback.format_exc() out = priumeDic['result'][0].get( 'insuranceApplication.calculateErrMeg', "") send_mq(client, licenseNo, out, "2", "5", sessionId, isPhone, groupId, insuranceTypeGroup) log.error(u"大地爬取失败 %s " % licenseNo) return out tomorrow = dtime.date.today() + dtime.timedelta(1) startDate = tomorrow.strftime("%Y-%m-%d") endDate = str(tomorrow.year + 1) + '-' + str(tomorrow.month) + '-' + str( tomorrow.day) data = [ startDate, endDate, vcodeRes['result']['seatCount'], groupId, INSURE_CAR_ID, "5" ] #data=[开始时间,结束时间,座位数,组合id,车辆id,公司id] soupDb(PremiumInfo, data) log.info(u"大地入库成功 %s " % licenseNo) # if __name__=="__main__": # startCicc()
def newPrimue(licenseNo, frameNo, req_session, insuranceType, insure_id, group_id, endDate=""): checkResult = get_checkAnwser(licenseNo, frameNo, req_session) DMV_res = checkResult['DMV_res'] DMV_carinfo_res = checkResult['DMV_carinfo_res'] checkCode = DMV_res['data'][0]['checkCode'] checkNo = DMV_res['data'][0]['checkNo'] checkAnswer = checkResult['checkAnswer'] # 通过车架号获取行业的modelCode modelCode_url = "http://10.134.136.112:8000/prpall/business/queryVehicleByPrefillVIN.do?vinNo=" + frameNo + "&licenseNo=" + urllib.quote( licenseNo.encode('gb2312')) + "&engineNo=&enrollDate=" modelCode_res = req_session.post(modelCode_url, verify=False).json() # 通过modelCode查询车型列表 carType_list_url = "http://10.134.136.112:8000/prpall/vehicle/vehicleQuery.do?brandName=" + modelCode_res[ 'msg'] + "&modelCode=" carType_list__res = req_session.post(carType_list_url, verify=False).json() enrollDate = str( time.strftime( "%Y-%m-%d", time.localtime( int(DMV_carinfo_res['data'][0]['enrollDate']['time']) / 1000))) tomorrow = datetime.date.today() + datetime.timedelta(1) today = datetime.date.today() pmCarOwner = DMV_carinfo_res['data'][0]['carOwner'] exhaustScale = DMV_carinfo_res['data'][0]['displacement'] engineNo = DMV_carinfo_res['data'][0]['engineNo'] brandName = carType_list__res['data'][0]['vehicleName'] purchasePriceOld = carType_list__res['data'][0]['priceTr'] modelCode = carType_list__res['data'][0]['vehicleId'] dateDic = { 'startDate': str(tomorrow), 'endDate': str( datetime.datetime.strptime( (str(today.year + 1) + '-' + str(today.month) + '-' + str(today.day)), "%Y-%m-%d").date()), 'today': str(today), 'enrollDate': enrollDate } if endDate != "": endDate = datetime.datetime.strptime(endDate, "%Y-%m-%d").date() dateDic['startDate'] = str(endDate) endDate = datetime.datetime.strptime( (str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)), "%Y-%m-%d").date() + datetime.timedelta(-1) dateDic['endDate'] = str(endDate) useYears = calc_user_years(dateDic['startDate'], enrollDate) calAclDic = { "enrollDate": enrollDate, 'ciEndDate': dateDic['endDate'], 'licenseNo': licenseNo, 'pmCarOwner': pmCarOwner, 'exhaustScale': exhaustScale, 'today': dateDic['today'], 'engineNo': engineNo, 'brandName': brandName, 'purchasePriceOld': purchasePriceOld, 'checkAnswer': checkAnswer, 'ciStartDate': dateDic['startDate'], 'checkNo': checkNo, 'prpCitemCar_useYears': useYears, ###需要计算一下 'frameNo': frameNo, 'modelCode': modelCode, 'operationTimeStamp': str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")), # 需要重新获取下 'checkCode': checkCode, 'seatCount': DMV_carinfo_res['data'][0]['seatCount'] } acl_price = caclAcl(calAclDic, req_session) calAclDic['aclPrice'] = acl_price price_res = caclPremium(calAclDic, insuranceType, req_session) while ((price_res['data'][0].get('errMessage', "") is not None) and (price_res['data'][0].get('errMessage', "") != "") or ("0" in price_res.get('msg', ""))): if "0" in price_res.get('msg', ""): carAlis = price_res['msg'].split("\n")[4].split(" ")[1] data = "pageNo_=1&riskCode=DAA&totalRecords_=&pageSize_=10&taxFlag=0&comCode=32012105&pm_vehicle_switch=1&carShipTaxPlatFormFlag=&TCVehicleVO.searchCode=&TCVehicleVO.vehicleAlias=" + urllib.quote( carAlis.encode('gb2312') ) + "&TCVehicleVO.vehicleId=&TCVehicleVO.brandId=&TCVehicleVO.brandName=&TCVehicleVO.vehicleName=SVW7167QSD&brandName=" + modelCode_res[ 'msg'] + "&pageSizeSelect=10"ationFlag=" url = "http://10.134.136.112:8000/prpall/vehicle/vehicleQuery.do?pageSize=10&pageNo=1" res = req_session.post(url, data=data, verify=False).json() if len(res['data']) == 0: log.error(price_res.get('msg', "")) return price_res.get('msg', "") else: acl_price_url = 'http://10.134.136.112:8000/prpall/business/calActualValue.do' useYears = calc_user_years(dateDic['startDate'], enrollDate) exhaustScale = res['data'][0]['vehicleQuality'] brandName = res['data'][0]['vehicleName'] purchasePriceOld = res['data'][0]['priceTr'] modelCode = res['data'][0]['vehicleId'] calAclDic = { "enrollDate": enrollDate, 'ciEndDate': dateDic['endDate'], 'licenseNo': licenseNo, 'pmCarOwner': pmCarOwner, 'exhaustScale': exhaustScale, 'today': dateDic['today'], 'engineNo': engineNo, 'brandName': brandName, 'purchasePriceOld': purchasePriceOld, 'checkAnswer': checkAnswer, 'ciStartDate': dateDic['startDate'], 'checkNo': checkNo, 'prpCitemCar_useYears': useYears, ###需要计算一下 'frameNo': frameNo, 'modelCode': modelCode, 'operationTimeStamp': str(datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")), # 需要重新获取下 'checkCode': checkCode, 'seatCount': DMV_carinfo_res['data'][0]['seatCount'] } acl_price = caclAcl(calAclDic, req_session) calAclDic['aclPrice'] = acl_price price_res = caclPremium(calAclDic, insuranceType, req_session) if price_res['data'][0]['errMessage'] != "": log.info(price_res['data'][0]['errMessage']) if (price_res['data'][0].get('errMessage', "") is not None) and ( price_res['data'][0].get('errMessage', "") != ""): if ("9308" in price_res['data'][0]['errMessage'].encode('utf-8')) or ( ('重复投保' in price_res['data'][0]['errMessage'])): str1 = "\d{4}-\d{2}-\d{2}" datelist = re.findall(str1, price_res['data'][0]['errMessage'], re.S) if len(datelist) == 2: endDate = compare_date(datelist[0], datelist[1]) dayGap = compare_time40(str(endDate)) if dayGap >= 40: log.error("重复投保,上期保单超过40天") return price_res['data'][0]['errMessage'].encode( 'utf-8') else: dateDic['startDate'] = str(endDate) endDate = datetime.datetime.strptime( (str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)), "%Y-%m-%d").date() + datetime.timedelta(-1) dateDic['endDate'] = str(endDate) useYears = calc_user_years(dateDic['startDate'], enrollDate) calAclDic = { "enrollDate": enrollDate, 'ciEndDate': dateDic['endDate'], 'licenseNo': licenseNo, 'pmCarOwner': pmCarOwner, 'exhaustScale': exhaustScale, 'today': dateDic['today'], 'engineNo': engineNo, 'brandName': brandName, 'purchasePriceOld': purchasePriceOld, 'checkAnswer': checkAnswer, 'ciStartDate': dateDic['startDate'], 'checkNo': checkNo, 'prpCitemCar_useYears': useYears, ###需要计算一下 'frameNo': frameNo, 'modelCode': modelCode, 'operationTimeStamp': str(datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")), # 需要重新获取下 'checkCode': checkCode, 'seatCount': DMV_carinfo_res['data'][0]['seatCount'] } acl_price = caclAcl(calAclDic, req_session) calAclDic['aclPrice'] = acl_price price_res = caclPremium(calAclDic, insuranceType, req_session) if price_res['data'][0][ 'errMessage'] != "" and price_res['data'][0][ 'errMessage'] is not None: return price_res['data'][0]['errMessage'] log.error(price_res['data'][0]['errMessage']) log.error("开始解析保费信息") PremiumInfo = readJson( price_res['data'][0]['biInsuredemandVoList'][0]['prpCitemKinds'], price_res['data'][0].get('ciInsureVOList', "")) log.info(PremiumInfo) # data=[开始时间,结束时间,座位数,组合id,车辆id,公司id] company_id = '2' data_list = [ dateDic['startDate'], dateDic['endDate'], DMV_carinfo_res['data'][0]['seatCount'], group_id, insure_id, company_id ] soupDb(PremiumInfo, data_list)
def flow_main(loginRes, data): try: req_session = loginRes[0] userId = loginRes[1] redis_dt = r.get_vin(data['vinNo'], "5") if redis_dt is not None: try: log.info(u"%s,可以从redis中获取信息" % data['vinNo']) dt = eval(redis_dt) #log.info(dt) dt['insuranceType'] = data['insuranceType'] dt['req_session'] = req_session log.info(dt['endDate']) dt['endDate'] = datetime.strptime(dt['endDate'], "%Y-%m-%d").date() client = data['client'] sessionId = data['sessionId'] isPhone = data['isPhone'] insuranceType = dt['insuranceType'] # 保险组合类型 if isinstance(insuranceType, list): insuranceTypes = insuranceType for insuranceType in insuranceTypes: try: dt['insuranceType'] = insuranceType groupId = insuranceType['insuranceTypeGroupId'] insuranceTypeGroup = insuranceType[ 'insuranceTypeGroup'] INSURE_CAR_ID = data['insureCarId'] premuim_dic = calculate_premium(dt) premuim_result = jsonpath(premuim_dic, "$.result") if premuim_result: calculateErrMeg = premuim_result[0][0].get( 'insuranceApplication.calculateErrMeg', None) if calculateErrMeg is not None: send_mq(client, dt['licenseNo'], calculateErrMeg, "2", "5", sessionId, isPhone, groupId, insuranceTypeGroup) return calculateErrMeg PremiumInfo = translate.getPriumeInf( premuim_dic, dt['insuranceType']) dataDic = { 'startData': str(dt['endDate']), 'endData': str( datetime.strptime( (str(dt['endDate'].year + 1) + '-' + str(dt['endDate'].month) + '-' + str(dt['endDate'].day)), "%Y-%m-%d").date()) } data = [ dataDic['startData'], dataDic['endData'], dt['seatCount'], groupId, INSURE_CAR_ID, "5" ] soupDb(PremiumInfo, data) log.info(u"大地入库成功,%s" % dt['licenseNo']) send_mq(client, dt['licenseNo'], "", "1", "5", sessionId, isPhone, groupId, insuranceTypeGroup) except Exception, e: log.info(u"%s,根据redis获取的信息查询保费时报正在重试正常流程" % data['vinNo']) log.error(traceback.format_exc()) return return u"大地入库成功,%s" % dt['licenseNo'] groupId = insuranceType['insuranceTypeGroupId'] insuranceTypeGroup = insuranceType['insuranceTypeGroup'] INSURE_CAR_ID = data['insureCarId'] premuim_dic = calculate_premium(dt) premuim_result = jsonpath(premuim_dic, "$.result") if premuim_result: calculateErrMeg = premuim_result[0][0].get( 'insuranceApplication.calculateErrMeg', None) if calculateErrMeg is not None: send_mq(client, dt['licenseNo'], calculateErrMeg, "2", "5", sessionId, isPhone, groupId, insuranceTypeGroup) return calculateErrMeg PremiumInfo = translate.getPriumeInf(premuim_dic, dt['insuranceType']) dataDic = { 'startData': str(dt['endDate']), 'endData': str( datetime.strptime((str(dt['endDate'].year + 1) + '-' + str(dt['endDate'].month) + '-' + str(dt['endDate'].day)), "%Y-%m-%d").date()) } data = [ dataDic['startData'], dataDic['endData'], dt['seatCount'], groupId, INSURE_CAR_ID, "5" ] soupDb(PremiumInfo, data) log.info(u"大地入库成功,%s" % dt['licenseNo']) send_mq(client, dt['licenseNo'], "", "1", "5", sessionId, isPhone, groupId, insuranceTypeGroup) return u"大地入库成功,%s" % dt['licenseNo'] except Exception, e: log.info(u"%s,根据redis获取的信息查询保费时报正在重试正常流程" % data['vinNo']) log.error(traceback.format_exc())
data = [ dataDic['startData'], dataDic['endData'], dt['seatCount'], groupId, INSURE_CAR_ID, "5" ] log.info(PremiumInfo) dt['endDate'] = str(dt['endDate']) dt.pop('req_session') dt.pop('client') r.set_vin(dt['vinNo'], "5", json.dumps(dt, ensure_ascii=False)) dt['req_session'] = req_session dt['client'] = client dt['endDate'] = datetime.strptime( dt['endDate'], "%Y-%m-%d").date() soupDb(PremiumInfo, data) log.info(u"大地入库成功,%s" % dt['licenseNo']) send_mq(client, dt['licenseNo'], "", "1", "5", sessionId, isPhone, groupId, insuranceTypeGroup) if insuranceTypeList != "": for insuranceType in insuranceTypeList: try: dt['insuranceType'] = insuranceType groupId = insuranceType[ 'insuranceTypeGroupId'] insuranceTypeGroup = insuranceType[ 'insuranceTypeGroup'] premuim_dic = calculate_premium(dt) premuim_result = jsonpath( premuim_dic, "$.result")
def get_pingan_redis_body(sessionoop, dtjson): try: searchVin = dtjson.get("vinNo", "") if searchVin == "": return 0 r = CRedis() alldata = r.get_vin(searchVin, "1") if alldata is None: return 0 # 发送请求 切换域名session log.info(u"从redis中查询出信息") toibcswriter_url = "https://icore-pts.pingan.com.cn/ebusiness/auto/newness/toibcswriter.do?transmitId=apply" headers = se.headers headers[ 'Referer'] = "https://icore-pts.pingan.com.cn/ebusiness/frames/main_02.jsp" toibcswriter_resp = sessionoop.get(url=toibcswriter_url, headers=headers, verify=False) toibcswriter_body = toibcswriter_resp.text dt_toibcswriter = parse_toibcswriter(toibcswriter_body) cypherText = dt_toibcswriter['cypherText'] timestamp = dt_toibcswriter['timestamp'] # 切换域名请求 获取cookies 为下面使用 icorepnbs_request = requests.session() icorepnbs_request.headers.update(se.headers) systemTransfer_url = "https://icorepnbs.pingan.com.cn/icore_pnbs/do/usermanage/systemTransfer" systemTransfer_data = { "channelSourceCode": "G", "partnerWorkNetCode": "", "operablePartnerWorknetList": "210697215001", "agentCode": "10690047", "BrandDetailName": "", "umCode": "STDJNDS-00001", "businessSourceDetailCode": "3", "saleAgentName": "耿越", "transitSystemSource": "ICORE-PTS", "saleAgentCode": "2100003024", "cypherText": cypherText, "isUseCyberArk": "Y", "channelSourceDetailCode": "F", "dealerCodes": "", "userName": "******", "businessCertificateNumText": "", "timestamp": timestamp, "transferId": "apply", "brokerCode": "", "dataSource": "ICORE-PTS", "departmentCode": "21069", "brandDetail": "", "businessSourceCode": "2", "agentSalerNameText": "", "relationQueryFlag": "Y", "departmentCodeList": "", "systemId": "ICORE-PTS", "partnerType": "0", "empBusinessCertificateNumText": "" } headers = se.headers headers[ 'Referer'] = "https://icore-pts.pingan.com.cn/ebusiness/auto/newness/toibcswriter.do?transmitId=apply" headers['Content-Type'] = "application/x-www-form-urlencoded" headers['Cache-Control'] = "max-age=0" icorepnbs_request.post(url=systemTransfer_url, data=systemTransfer_data, headers=headers, verify=False) insuranceType = dtjson.get("insuranceType", {}) insuranceTypeGroupId = insuranceType.get("insuranceTypeGroupId", "") insuranceTypeGroup = insuranceType.get("insuranceTypeGroup", "") insureCarId = dtjson['insureCarId'] CPlateNo = dtjson.get("plateNumber", "") client = dtjson['client'] sessionId = dtjson['sessionId'] isPhone = dtjson['isPhone'] alldata = eval(alldata) alldata['insuranceType'] = insuranceType fee_resp = get_fee(icorepnbs_request, alldata) if isinstance(fee_resp, dict): data = [] data.append(fee_resp['c01beginTime']) data.append(fee_resp['c01endTime']) data.append(fee_resp['vehicleSeats']) data.append(insuranceTypeGroupId) data.append(insureCarId) data.append("1") log.info("平安开始入库 %s", CPlateNo) soupDb(fee_resp['fee'], data) log.info("平安入库成功 %s ", CPlateNo) send_mq(client, CPlateNo, "", "1", "1", sessionId, isPhone, insuranceTypeGroupId, insuranceTypeGroup) return 1 if isinstance(fee_resp, list): fee_resp = json.dumps(fee_resp, encoding=False) log.error(fee_resp) return 0 log.error(fee_resp) # send_mq(client,CPlateNo,fee_resp,"2","1",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup) return 0 except Exception as e: log.error(traceback.format_exc()) log.error(e) return 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
def xd_request_premium(renewal_data_dt): try: alldata = {} # licenseNoBC = '苏EE9N06'.encode('gbk') # FrameNo = 'LSVAG2186B2299594' # 车架号 insureCarId = renewal_data_dt.get('insureCarId', '') CPlateNo = renewal_data_dt.get('plateNumber', '') licenseNoBC = CPlateNo.encode('gbk') searchVin = renewal_data_dt.get('vinNo', '') FrameNo = searchVin client = renewal_data_dt.get('client', '') isPhone = renewal_data_dt['isPhone'] sessionId = renewal_data_dt.get('sessionId', '') insuranceType = renewal_data_dt.get("insuranceType", {}) if isinstance(insuranceType, list): insureTypeGroupId = insuranceType[0].get("insuranceTypeGroupId", "") insuranceTypeGroup = insuranceType[0].get("insuranceTypeGroup", "") else: insureTypeGroupId = insuranceType.get("insuranceTypeGroupId", "") insuranceTypeGroup = insuranceType.get("insuranceTypeGroup", "") permium_dict = {} # session = get_session("14") # if session is None: session = xd_login() sy_insuranceEndTime = renewal_data_dt.get("insuranceTime", {}).get( "syStart", getlatedate(1)) jq_insuranceEndTime = renewal_data_dt.get("insuranceTime", {}).get( "jqStart", getlatedate(1)) permium_dict['insuranceType'] = insuranceType permium_dict['jq_insuranceEndTime'] = jq_insuranceEndTime permium_dict['sy_insuranceEndTime'] = sy_insuranceEndTime # vin查询 car_vin_ret = get_car_vin(licenseNoBC, FrameNo, session) carVinInfo = parse_vin_car(car_vin_ret) if not isinstance(carVinInfo, dict): send_mq(client, CPlateNo, "获取车辆型号失败", "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return permium_dict['carVinInfo'] = carVinInfo # 获取车管所信息 vehicle = get_car_info(licenseNoBC, FrameNo, session) if not isinstance(vehicle, dict): send_mq(client, CPlateNo, "获取车管所信息失败%s" % licenseNoBC, "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return permium_dict['vehicle'] = vehicle # 判断车辆种类 syName = carVinInfo['syName'] mainCarKindCodeBC = get_main_cartype(carVinInfo['brandNameBC']) # 如果带挂 说明是挂车 if "挂" in CPlateNo: mainCarKindCodeBC = "G" if mainCarKindCodeBC == "BG": mainCarKindCodeBC = "H" if mainCarKindCodeBC is None: # 非客车 # 如果还是None 取车辆名称型号 判断特种车 mainCarKindCodeBC = get_specical_car_type( carVinInfo['brandNameBC']) if isinstance(mainCarKindCodeBC, dict): if mainCarKindCodeBC['type'] == "货车": mainCarKindCodeBC = "H" elif mainCarKindCodeBC['type'] == "挂车": mainCarKindCodeBC = "G" if mainCarKindCodeBC is None: # 如果还是None 取vin查询返回的商业险名称 if "吨" in syName: mainCarKindCodeBC = "H" if "特" in syName: if "一" in syName: mainCarKindCodeBC = "T1" elif "二" in syName: mainCarKindCodeBC = "T2" elif "三" in syName: mainCarKindCodeBC = "T3" elif "四" in syName: mainCarKindCodeBC = "T4" else: mainCarKindCodeBC = "H" else: mainCarKindCodeBC = "A" permium_dict['carVinInfo']['mainCarKindCodeBC'] = mainCarKindCodeBC if mainCarKindCodeBC == "A": # 如果大类是客车 那么子类也为客车,使用性质为家庭自用carKindCodeBC permium_dict['carVinInfo']['mainCarKindCodeBC'] = "A0" # 种类为A0 permium_dict['carVinInfo']['useNatureCodeBC'] = "8A" if mainCarKindCodeBC == "G": # permium_dict['carVinInfo']['mainCarKindCodeBC'] = "G0" # permium_dict['carVinInfo']['useNatureCodeBC'] = "9D" if mainCarKindCodeBC == "H": if "XXY" in carVinInfo['brandNameBC']: # 厢式货车 permium_dict['carVinInfo']['carKindCodeBC'] = "H3" elif get_main_cartype(carVinInfo['brandNameBC']) == "BG": permium_dict['carVinInfo']['carKindCodeBC'] = "H5" # else: permium_dict['carVinInfo']['carKindCodeBC'] = "H0" # # 使用性质 permium_dict['carVinInfo']['useNatureCodeBC'] = "9D" # carTypeCodeBC判断车辆类型 carTypeCodeBC = "1" myCarTypeCodeBC = "1" if len(syName) != 0: codelist = get_car_type(syName) carTypeCodeBC = codelist[2] myCarTypeCodeBC = codelist[3] permium_dict['vehicle']['carTypeCodeBC'] = carTypeCodeBC permium_dict['vehicle']['myCarTypeCodeBC'] = myCarTypeCodeBC # 判断交强险与商业险选项 # 获取车辆实际价格以及纯风险保费 actualValue = get_car_value(permium_dict, session, sy_insuranceEndTime) if not isinstance(actualValue, dict): send_mq(client, CPlateNo, "获取车辆协商价格以及纯风险保费失败%s" % licenseNoBC, "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return permium_dict['actualValue'] = actualValue # 计算车辆实际使用年限 userYear = calc_user_years(sy_insuranceEndTime, vehicle['enrollDateBC']) permium_dict['actualValue']['useYears'] = userYear chose_flag = choose_jq_sy(permium_dict['insuranceType']) JQ = {} if chose_flag == "2" or chose_flag == "3": # 只选了交强险 JQ = get_jq_data(session, permium_dict) if not isinstance(JQ, dict): send_mq(client, CPlateNo, "交强险重复投保%s" % licenseNoBC, "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return permium_dict['JQ'] = JQ if chose_flag == "2": jq_insert = [{ "compulsory_insurance": JQ['compulsory_insurance'], "NAggTax": JQ['NAggTax'] }, {}, {}, { "jq_disCount": JQ['jq_disCount'] }] soupDb(jq_insert, [ getlatedate(1) + ' 00:00:00', getlatedate(365) + " 23:59:59", vehicle['seatCountBC'], insureTypeGroupId, insureCarId, "14" ]) # 发送成功队列 send_mq(client, CPlateNo, "", "1", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) log.info(u"信达入库成功:%s|%s" % (CPlateNo, searchVin)) return if chose_flag == "1" or chose_flag == "3": # 请求系数以及等 SubmitBI = get_InputSubmitBI(session, permium_dict) if not isinstance(SubmitBI, dict): send_mq(client, CPlateNo, SubmitBI, "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return permium_dict['SubmitBI'] = SubmitBI Rules = get_ValidateRulesBI(session, permium_dict) if not isinstance(Rules, dict): send_mq(client, CPlateNo, SubmitBI, "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return permium_dict['Rules'] = Rules # 计算修改费率 get_bi_rate(permium_dict) # 请求保费请求 查询码 premium_data = get_premium_data(session, permium_dict) permium_dict['premium'] = premium_data SY = xd_parse_get_premuim(permium_dict) permium_dict['sy_premuim'] = SY # 发送保单暂存 permium_dict['tempSaveFlag'] = "1" tmp_out = get_save_tmp_premium(session, permium_dict) if not isinstance(tmp_out, dict): send_mq(client, CPlateNo, tmp_out, "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return permium_dict['tmpBICI'] = tmp_out permium_dict['tempSaveFlag'] = "0" riskLevelFlag = get_riskLevelFlag(session, permium_dict) if not isinstance(riskLevelFlag, dict): send_mq(client, CPlateNo, riskLevelFlag, "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return permium_dict['riskLevel'] = riskLevelFlag sav_premium(session, permium_dict) # if chose_flag == "1": soupDb(SY, [ getlatedate(1) + ' 00:00:00', getlatedate(365) + " 23:59:59", vehicle['seatCountBC'], insureTypeGroupId, insureCarId, "14" ]) send_mq(client, CPlateNo, "", "1", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) log.info(u"信达入库成功:%s|%s" % (CPlateNo, searchVin)) return elif chose_flag == "3": # 交强险加商业险 入库返回 SY[0]['compulsory_insurance'] = JQ['compulsory_insurance'] SY[0]['NAggTax'] = JQ['NAggTax'] SY[3]['jq_disCount'] = JQ['jq_disCount'] log.info(SY) soupDb(SY, [ getlatedate(1) + ' 00:00:00', getlatedate(365) + " 23:59:59", vehicle['seatCountBC'], insureTypeGroupId, insureCarId, "14" ]) send_mq(client, CPlateNo, "", "1", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) log.info(u"信达入库成功:%s|%s" % (CPlateNo, searchVin)) except Exception as e: import traceback log.error(traceback.format_exc()) log.error(e) send_mq(client, CPlateNo, "未知异常 %s " % e, "2", "14", sessionId, isPhone, insureTypeGroupId, insuranceTypeGroup) return 0
def standard_main(renewal_data_dt, endDate=""): try: r = redisUtil.CRedis() log.error("start") srssion = get_session('2') sessBase = srssion req_session = pickle.loads(codecs.decode(sessBase.encode(), "base64")) req_session.mount('https://', MyAdapter()) insuranceTypeList = "" insure_id = renewal_data_dt['insureCarId'] client = renewal_data_dt.get('client', None) if isinstance(renewal_data_dt['insuranceType'], dict): insuranceType = renewal_data_dt['insuranceType'] group_id = insuranceType['insuranceTypeGroupId'] elif isinstance(renewal_data_dt['insuranceType'], list): insuranceTypeList = renewal_data_dt['insuranceType'] insuranceType = insuranceTypeList[0] group_id = insuranceType['insuranceTypeGroupId'] redis_dt = r.get_vin(renewal_data_dt['vinNo'], "2") if redis_dt is not None: try: log.info(u'人保可以从redis中获取信息') dt = eval(redis_dt) get_checkcode_url = "http://10.134.136.112:8000/prpall/business/" \ "queryVehiclePMCheck.do?comCode=32012105&frameNo=" \ + dt['vinNo'] + "&licenseNo=" req_session.post(url=get_checkcode_url, verify=False).json() if insuranceTypeList == "": price_res = caclPremium(dt, insuranceType, req_session) if price_res['data'][0].get('errMessage') is not None: log.error(price_res['data'][0].get('errMessage')) log.error(u"开始解析保费信息") PremiumInfo = readJson( price_res['data'][0]['biInsuredemandVoList'][0] ['prpCitemKinds'], price_res['data'][0].get('ciInsureVOList', None)) if PremiumInfo: log.info(PremiumInfo) # data=[开始时间,结束时间,座位数,组合id,车辆id,公司id] data_list = [ dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'], group_id, insure_id, '2' ] soupDb(PremiumInfo, data_list) log.info(u'人保入库成功') return None else: log.error(u"未知错误") return price_res['data'][0].get('errMessage', '未知错误') else: for insuranceType in insuranceTypeList: try: insure_id = renewal_data_dt['insureCarId'] group_id = insuranceType['insuranceTypeGroupId'] price_res = caclPremium(dt, insuranceType, req_session) if price_res['data'][0].get( 'errMessage') is not None: log.error( price_res['data'][0].get('errMessage')) log.error(u"开始解析保费信息") PremiumInfo = readJson( price_res['data'][0]['biInsuredemandVoList'][0] ['prpCitemKinds'], price_res['data'][0].get( 'ciInsureVOList', None)) if PremiumInfo: log.info(PremiumInfo) # data=[开始时间,结束时间,座位数,组合id,车辆id,公司id] data_list = [ dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'], group_id, insure_id, '2' ] soupDb(PremiumInfo, data_list) log.info(u'人保入库成功') send_mq( client, dt['licenseNo'], "", "1", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) # return None else: log.error(u"未知错误") log.info(u"开始发送消息") send_mq( client, dt['licenseNo'], price_res['data'][0].get( 'errMessage', '未知错误'), "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) except Exception, e: log.error(traceback.format_exc()) send_mq( client, dt['licenseNo'], "未知错误", "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) return None except: log.error(traceback.format_exc()) if client is not None: log.info(u"开始发送消息") send_mq(client, dt['licenseNo'], "未知错误", "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) return "未知错误" dt = dt_init() licenseType = renewal_data_dt.get('licenseType', "02") if licenseType == '01': dt['licenseType'] = licenseType dt['LicenseTypeDes'] = "大型汽车号牌" dt['licenseColorCode'] = "04" dt['LicenseColorCodeDes'] = "黄" dt['carKindCode'] = "B01" dt['CarKindCodeDes'] = "货车" dt['useNatureCode'] = "120" dt['clauseType'] = "F43" dt['tonCount'] = '10000' elif licenseType == "02": dt['licenseType'] = licenseType dt['LicenseTypeDes'] = "小型汽车号牌" dt['licenseColorCode'] = "01" dt['LicenseColorCodeDes'] = "蓝" dt['carKindCode'] = "A01" dt['CarKindCodeDes'] = "客车" dt['useNatureCode'] = "211" dt['clauseType'] = "F42" dt['tonCount'] = "0" sy_jq_date = jq_sy_time(renewal_data_dt) syStart = sy_jq_date.get('syStart', timeUtil.getlatedate(1)) jqStart = sy_jq_date.get('jqStart', timeUtil.getlatedate(1)) dt['ciStartDate'] = syStart endDate = datetime.datetime.strptime(syStart, "%Y-%m-%d").date() dt['ciEndDate'] = str( datetime.datetime.strptime((str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)), "%Y-%m-%d").date() + datetime.timedelta(-1)) dt['syStart'] = syStart dt['syEnd'] = str( datetime.datetime.strptime((str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)), "%Y-%m-%d").date() + datetime.timedelta(-1)) dt['jqStart'] = jqStart jqEndDate = datetime.datetime.strptime(jqStart, "%Y-%m-%d").date() dt['jqEnd'] = str( datetime.datetime.strptime( (str(jqEndDate.year + 1) + '-' + str(jqEndDate.month) + '-' + str(jqEndDate.day)), "%Y-%m-%d").date() + datetime.timedelta(-1)) # if endDate == "": # tomorrow = datetime.date.today() + datetime.timedelta(1) # today = datetime.date.today() # dt['ciStartDate'] = str(tomorrow) # dt['ciEndDate'] = str( # datetime.datetime.strptime((str(today.year + 1) + '-' + str(today.month) + '-' + str(today.day)), # "%Y-%m-%d").date()) # else: # endDate = datetime.datetime.strptime(endDate, "%Y-%m-%d").date() # dt['ciStartDate'] = str(endDate) # endDate = datetime.datetime.strptime( # (str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)), # "%Y-%m-%d").date() + datetime.timedelta(-1) # dt['ciEndDate'] = str(endDate) dt['vinNo'] = renewal_data_dt.get('vinNo', '') dt['licenseNo'] = renewal_data_dt.get('plateNumber', '') get_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMCheck.do?comCode=32012105&frameNo=" + \ dt['vinNo'] + "&licenseNo=" get_checkcode_res = req_session.post(url=get_checkcode_url, verify=False).json() checkcode_res = jsonpath(get_checkcode_res, "$.data") dt['checkNo'] = checkcode_res[0][0]['checkNo'] dt['checkCode'] = checkcode_res[0][0]['checkCode'] # dt['checkAnswer'] = request_cicc.util.pic2Str(base64.b64decode(dt['checkCode'])) dt['checkAnswer'] = dama("3", dt['checkCode']) post_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMConfirm.do?comCode=32012105&checkNo=" + \ dt['checkNo'] + "&checkCode=" + dt['checkAnswer'] post_checkcode_res = req_session.post(url=post_checkcode_url, verify=False).json() post_checkcode_res = jsonpath(post_checkcode_res, "$.data") log.info(u'开始打码') count = 0 log.info(post_checkcode_res[0][0].get('errMessage', '')) while post_checkcode_res[0][0].get('errMessage', '') is not None: if '未匹配到交管车辆信息' in post_checkcode_res[0][0].get('errMessage', ''): log.error("未匹配到交管车辆信息") # 返回错误信息 if client is not None: log.info(u"开始发送消息") send_mq(client, dt['licenseNo'], post_checkcode_res[0][0].get('errMessage', ''), "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) return post_checkcode_res[0][0].get('errMessage', '') if '录入的校验码有误' in post_checkcode_res[0][0].get('errMessage', ''): dama("99", dt['checkCode']) log.error(u"验证码有误,错误的验证码为,%s" % dt['checkAnswer']) get_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMCheck.do?comCode=32012105&frameNo=" + \ dt['vinNo'] + "&licenseNo=" get_checkcode_res = req_session.post(url=get_checkcode_url, verify=False).json() checkcode_res = jsonpath(get_checkcode_res, "$.data") dt['checkNo'] = checkcode_res[0][0]['checkNo'] dt['checkCode'] = checkcode_res[0][0]['checkCode'] # dt['checkAnswer'] = request_cicc.util.pic2Str(base64.b64decode(dt['checkCode'])) dt['checkAnswer'] = dama("3", dt['checkCode']) post_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMConfirm.do?comCode=32012105&checkNo=" + \ dt['checkNo'] + "&checkCode=" + dt['checkAnswer'] post_checkcode_res = req_session.post(url=post_checkcode_url, verify=False).json() post_checkcode_res = jsonpath(post_checkcode_res, "$.data") if count > 4: # 验证码重发超限 if client is not None: log.info(u"开始发送消息") send_mq(client, dt['licenseNo'], "查询失败,稍后重试", "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) return "查询失败,稍后重试" count = count + 1 if post_checkcode_res[0][0].get('errMessage', '') is None: log.info(u'打码成功') dt['modelCode'] = post_checkcode_res[0][0]['modelCode'] car_info_url = "http://10.134.136.112:8000/prpall/vehicle/vehicleQuery.do?brandName=" + dt[ 'modelCode'] + "&modelCode=" car_info_res = req_session.post(url=car_info_url, verify=False).json() car_info_list = jsonpath(car_info_res, "$.data") if car_info_list: if len(car_info_list[0]) == 0: log.info(u"正在重新尝试获取车辆型号") dt['modelCode'] = dt['modelCode'][:-1] + dt['modelCode'][ -1].lower() log.info(dt['modelCode']) car_info_url = "http://10.134.136.112:8000/prpall/vehicle/vehicleQuery.do?brandName=" + dt[ 'modelCode'] + "&modelCode=" car_info_res = req_session.post(url=car_info_url, verify=False).json() car_info_list = jsonpath(car_info_res, "$.data") # cic_car_info = get_car_model(dt['vinNo']) # if cic_car_info is not None: # dt['gCIndustryModelName'] = cic_car_info['gCIndustryModelName'] # car_info_url = "http://10.134.136.112:8000/prpall/vehicle/vehicleQuery.do?brandName=" + dt['gCIndustryModelName'] + "&modelCode=" # car_info_res = req_session.post(url=car_info_url, verify=False).json() # car_info_list = jsonpath(car_info_res, "$.data") if len(car_info_list[0]) > 0: log.info(u'获取车型成功,正在选取最低价车型') car_info_list = car_info_list[0] car_info_list.sort(key=lambda obj: obj.get('priceT')) car_info = car_info_list[0] if post_checkcode_res[0][0].get('enrollDate', None) is not None: dt['enrollDate'] = str( time.strftime( "%Y-%m-%d", time.localtime( int(post_checkcode_res[0][0]['enrollDate'] ['time']) / 1000))) dt['licenseNo'] = post_checkcode_res[0][0]['id'][ 'licenseNo'] dt['pmCarOwner'] = post_checkcode_res[0][0]['carOwner'] if licenseType == '01': dt['exhaustScale'] = post_checkcode_res[0][0][ 'displacement'] dt['carLotEquQuality'] = float( car_info['vehicleQuality']) * 1000 if post_checkcode_res[0][0].get('tonCount', '0') == '0': dt['tonCount'] = post_checkcode_res[0][0].get( 'tonCount', '0') else: dt['tonCount'] = post_checkcode_res[0][0].get( 'haulage', '0') else: dt['exhaustScale'] = car_info['vehicleExhaust'] dt['engineNo'] = post_checkcode_res[0][0]['engineNo'] dt['brandName'] = car_info['vehicleName'] dt['purchasePriceOld'] = str(car_info['priceTr']) log.info(u'新车购置价格是:%s' % dt['purchasePriceOld']) dt['frameNo'] = dt['vinNo'] dt['modelCode'] = car_info['vehicleId'] dt['seatCount'] = car_info['vehicleSeat'] useYears = calc_user_years(dt['syStart'], dt['enrollDate']) dt['prpCitemCar_useYears'] = useYears acl_price = caclAcl(dt, req_session) dt['aclPrice'] = acl_price price_res = caclPremium(dt, insuranceType, req_session) log.info(price_res['data'][0].get('errMessage')) while price_res['data'][0].get('errMessage') is not None: if '重复投保' in price_res['data'][0].get('errMessage'): str1 = "\d{4}-\d{2}-\d{2}" datelist = re.findall( str1, price_res['data'][0]['errMessage'], re.S) if len(datelist) == 2: endDate = compare_date(datelist[0], datelist[1]) dayGap = compare_time40(str(endDate)) if dayGap >= 40: log.error(u"重复投保,上期保单超过40天") if client is not None: log.info(u"开始发送消息") send_mq( client, dt['licenseNo'], price_res['data'][0]['errMessage'], "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get( "insuranceTypeGroupId", "9999"), insuranceType.get( "insuranceTypeGroup", "0")) return price_res['data'][0]['errMessage'] else: dt['syStart'] = dt['jqStart'] = str( endDate) endDate = datetime.datetime.strptime( (str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)), "%Y-%m-%d").date( ) + datetime.timedelta(-1) dt['syEnd'] = dt['jqEnd'] = str(endDate) useYears = calc_user_years( dt['syStart'], dt['enrollDate']) dt['prpCitemCar_useYears'] = useYears acl_price = caclAcl(dt, req_session) dt['aclPrice'] = acl_price price_res = caclPremium( dt, insuranceType, req_session) else: log.error(u"重复投保") if client is not None: log.info(u"开始发送消息") send_mq( client, dt['licenseNo'], price_res['data'][0]['errMessage'], "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get( "insuranceTypeGroupId", "9999"), insuranceType.get( "insuranceTypeGroup", "0")) return price_res['data'][0]['errMessage'] log.info(price_res['data'][0]['biInsuredemandVoList'] [0].get('ciInsureDemandRepets')) if len(price_res['data'][0]['biInsuredemandVoList'][0].get( 'ciInsureDemandRepets')) > 0: endDate = datetime.datetime.strptime( time.strftime( "%Y-%m-%d", time.localtime( int(price_res['data'][0] ['biInsuredemandVoList'][0].get( 'ciInsureDemandRepets')[0] ['endDate']['time'] / 1000))), "%Y-%m-%d").date() print endDate, type(endDate) dayGap = compare_time40(str(endDate)) if dayGap >= 40: log.error(u"重复投保,上期保单超过40天") if client is not None: log.info(u"开始发送消息") send_mq( client, dt['licenseNo'], price_res['data'][0]['errMessage'], "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) return price_res['data'][0]['errMessage'] else: dt['syStart'] = dt['jqStart'] = str(endDate) endDate = datetime.datetime.strptime( (str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)), "%Y-%m-%d").date() + datetime.timedelta(-1) dt['syEnd'] = dt['jqEnd'] = str(endDate) useYears = calc_user_years(dt['syStart'], dt['enrollDate']) dt['prpCitemCar_useYears'] = useYears acl_price = caclAcl(dt, req_session) dt['aclPrice'] = acl_price price_res = caclPremium(dt, insuranceType, req_session) log.error(u"开始解析保费信息") PremiumInfo = readJson( price_res['data'][0]['biInsuredemandVoList'][0] ['prpCitemKinds'], price_res['data'][0].get('ciInsureVOList', None)) if PremiumInfo: log.info(PremiumInfo) # data=[开始时间,结束时间,座位数,组合id,车辆id,公司id] data_list = [ dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'], group_id, insure_id, '2' ] soupDb(PremiumInfo, data_list) dt['ciEndDate'] = str(dt['ciEndDate']) r.set_vin(dt['vinNo'], "2", json.dumps(dt, ensure_ascii=False)) log.info(u'人保入库成功') if insuranceTypeList != "": insuranceTypeList = insuranceTypeList[1:] for insuranceType in insuranceTypeList: try: insure_id = renewal_data_dt['insureCarId'] group_id = insuranceType[ 'insuranceTypeGroupId'] price_res = caclPremium( dt, insuranceType, req_session) if price_res['data'][0].get( 'errMessage') is not None: log.error(price_res['data'][0].get( 'errMessage')) log.error(u"开始解析保费信息") PremiumInfo = readJson( price_res['data'][0] ['biInsuredemandVoList'][0] ['prpCitemKinds'], price_res['data'][0].get( 'ciInsureVOList', None)) if PremiumInfo: log.info(PremiumInfo) # data=[开始时间,结束时间,座位数,组合id,车辆id,公司id] data_list = [ dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'], group_id, insure_id, '2' ] soupDb(PremiumInfo, data_list) log.info(u'人保入库成功') log.info(u"开始发送消息") send_mq( client, dt['licenseNo'], "", "1", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get( "insuranceTypeGroupId", "9999"), insuranceType.get( "insuranceTypeGroup", "0")) # return None else: log.error(u"未知错误") log.info(u"开始发送消息") send_mq( client, dt['licenseNo'], price_res['data'][0].get( 'errMessage', '未知错误'), "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get( "insuranceTypeGroupId", "9999"), insuranceType.get( "insuranceTypeGroup", "0")) except Exception, e: log.error(traceback.format_exc()) log.info(u"开始发送消息") send_mq( client, dt['licenseNo'], "未知错误", "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get( "insuranceTypeGroupId", "9999"), insuranceType.get( "insuranceTypeGroup", "0")) return None else: return "未知错误" else: log.error(u'无法获取车型') if client is not None: send_mq( client, dt['licenseNo'], '无法获取车型', "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) return ('无法获取车型') except Exception, e: log.error(traceback.format_exc()) if client is not None: send_mq(client, dt['licenseNo'], '未知错误', "2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"), insuranceType.get("insuranceTypeGroup", "0")) return "未知错误"