Esempio n. 1
0
    def _downDetail(self, base_info):
        if not base_info:
            return False
        try:
            jxl_record = OpenJxlStat().getById(base_info.jxlstat_id)
            if not jxl_record:
                print("暂无通讯详单数据")
                return False

            detail_url = jxl_record.get('detail_url')
            detail_data = OpenJxlStat().getDetail(detail_url)
            calls = detail_data['raw_data']['members']['transactions'][0][
                'calls']
            pd_detail = pd.DataFrame(calls)
            if len(pd_detail) == 0:
                print("暂无详单数据")
                return False
            detail_list = []
            #detail_list = ['13716248789', '18888820817', '18911224494', '13716248789']
            for phone in pd_detail.other_cell_phone:
                detail_list.append(phone)
            return detail_list
        except KeyError as error:
            print(error)
            return False
        except Exception as error:
            print(error)
            return False
Esempio n. 2
0
    def mulrundetail1(self,id):
        jxlData = OpenJxlStat().getData(id)
        if jxlData is None:
            print("there is nothing data to deal with")
        # 获取聚信立报告并分析
        try:
            phone = jxlData.phone
            if not str(phone).isdigit():
                print("the phone must be a number: %s" % phone)

            detailData = OpenJxlStat().getByPhone(phone)
            if detailData is None:
                print("the phone does not exist in jxlstat : %s" % phone)

            # 2.获取通话详情信息
            url = detailData.get('detail_url')
            detail_data = OpenJxlStat().getDetail(url)
            if detail_data is None:
                print("json_url:%s can't get detail_data" % (url))

            # 3. 分析详单
            analisis_res = DetailAnalysis(detail_data)._analysis()
            if analisis_res is None:
                print("mobile:%s can't get analisis_res" % (phone))
            # 4. 详单数据入库
            print(analisis_res)
        except Exception as e:
            logger.error("analysis fail: %s" % e)
            return False
Esempio n. 3
0
    def runMatch(self):
        # 1. 用户
        self.dbUser = YiUser().get(self.user_id)
        if self.dbUser is None:
            logger.error("user_id:%s db中没有纪录" % self.user_id)
            raise Exception(1002, "没有纪录")

        # 2. 获取通讯录对象
        self.__address()
        self.address_phone = self.oAddress.getDistinctPhone(
        ) if self.oAddress else []
        # 3. 获取通话详单对象
        record = OpenJxlStat().getByPhone(self.dbUser.mobile)
        if record:
            self.__detail(record.get('detail_url'))
        self.detail_phone = self.oDetail.getDistinctPhone(
        ) if self.oDetail else []
        # 4. 二级关系
        oMultiMatch = MultiMatch(self.dbUser.mobile, self.detail_phone,
                                 self.address_phone)
        multi_match_res = oMultiMatch.run()
        dict_data = {}
        dict_data['multi_match'] = multi_match_res
        dict_data = self.__mergeData(self.aid, self.user_id, self.request_id,
                                     self.loan_id, dict_data)
        return dict_data
Esempio n. 4
0
    def runwsm(self, start_time=None, end_time=None):
        last_day = datetime.now() + timedelta(days=-1)
        if start_time is None:
            start_time = last_day.strftime('%Y-%m-%d 00:00:00')

        if end_time is None:
            end_time = last_day.strftime('%Y-%m-%d 23:59:59')
        #getmobiles
        users_info = YiUserRemitList().getMobiles(start_time, end_time)
        if users_info is None:
            logger.error("users_info:no data to dealwith")
            return False

        #获取开放平台聚信立信息
        for user in users_info:
            try:
                # 1. get detail_datas
                Jxl_datas = OpenJxlStat().getByPhone(user.mobile)
                if Jxl_datas is None:
                    logger.error("mobile:%s  can't get Jxl_datas" %
                                 (user.mobile))
                    continue

                url = Jxl_datas.get('detail_url')
                detail_datas = OpenJxlStat().getDetail(url)
                if detail_datas is None:
                    logger.error("json_url:%s  can't get detail_data" % (url))
                    continue

                # 2. get contacts_mobile and relatives_phone
                mobile_phone = YiFavoriteContact().getByUserId(user.user_id)
                if mobile_phone is None:
                    logger.error("user_id:%s  can't get mobile_phone" %
                                 (user.user_id))
                    continue
                dict_contact_phone = {
                    'mobile': mobile_phone.mobile,
                    'phone': mobile_phone.phone
                }

                # 3. analysis  detail_data
                analysis_datas = Detail(detail_datas).runWsm(
                    dict_contact_phone)
                n = 0
                for key, value in analysis_datas.items():
                    # 4. save analysis_data
                    add_res = AfWsm().addWsm(value, user)
            except Exception as e:
                logger.error("user.mobile:%s is fail: %s" % (user.mobile, e))
        return True
Esempio n. 5
0
 def __get_detail_phone(self, phone):
     '''
     详单相关
     '''
     json_data = None
     detail_phone = []
     if phone:
         record = OpenJxlStat().getByPhone(phone)
         if record:
             json_data = OpenJxlStat().getDetail(record.get('detail_url'))
     if json_data:
         try:
             oDetail = Detail(json_data)
             detail_phone = oDetail.getDistinctPhone()
         except Exception as e:
             logger.error("phone:%s jxl detail is fail: %s" % (phone, e))
     return detail_phone
Esempio n. 6
0
 def __detail(self, url):
     # 获取通话详单处理对象
     try:
         json_data = OpenJxlStat().getDetail(url)
         if json_data:    
             self.oDetail = Detail(json_data)
     except Exception as e:
         logger.error("user_id:%s jxl detail is fail: %s" % (self.user_id, e))
         self.oDetail = None
Esempio n. 7
0
 def __saveBase(self):
     if int(self.operator.get('type')) == 1:
         req_id = 0 if self.operator.get(
             'data') is None else self.operator.get('data')
         self.jxl_record = OpenJxlStat().getByRequestId(req_id)
         self.jxlstat_id = self.jxl_record.get(
             'jxlstat_id') if self.jxl_record is not None else 0
     afBase = AfBase()
     afBase.request_id = self.request_id
     afBase.aid = self.aid
     afBase.user_id = self.user_id
     afBase.loan_id = self.loan_id
     afBase.jxlstat_id = self.jxlstat_id
     afBase.match_status = 0
     afBase.create_time = datetime.now()
     afBase.modify_time = datetime.now()
     afBase.save()
     self.base_id = afBase.id
Esempio n. 8
0
    def __getEndId(self, start_id):
        end_id = int(start_id)+10
        max_id = OpenJxlStat().getMaxId()
        if end_id > max_id:
            end_id = max_id

        f = open('./util/detailId.txt', 'w')
        f.write(str(end_id))
        f.close()
        return end_id
Esempio n. 9
0
    def __analysis(self):
        # 分析数据
        # 1. 用户, 亲属 , 好友认证
        self.dbUser = YiUser().get(self.user_id)
        if self.dbUser is None:
            logger.error("user_id:%s db中没有纪录" % self.user_id)
            raise Exception(1002, "没有纪录")

        self.dbYiFriends = YiFriend().getByUserId(self.user_id)

        # 2. 初始化通讯录和报告
        self.dbYiAddressList = AddressList().getByUserPhoneDict(self.dbUser.mobile)
        try:
            # 通讯录追加
            self._addMailNumberLabel(self.dbUser.mobile)
        except Exception as e:
            logger.info("number_label: 通讯录错误:%s" % e)

        #学信、社保、公积金维度的数据信息验证
        try:
            thirdPartyInfo().runData(self.dbUser)
        except Exception as e:
            logger.info("第三方接口: 学信、社保、公积错误:%s" % e)

        self.jxl_record = OpenJxlStat().getById(self.jxlstat_id)
        logger.info("number_label: user_id:%s" % self.user_id)
        # 3. 调用OperatorAnalysis
        operatorObj = OperatorAnalysis()
        operator_data = operatorObj.getOperatorData(self.dbYiAddressList,self.jxl_record)
        if operatorObj is not None:
            self.oDetail = operatorObj.oDetail
            self.oAddress = operatorObj.oAddress

        # 4. 跟业务模型数据交叉合并
        # 亲属联系人与是否逾期
        self.dbContact = YiFavoriteContact().getByUserId(self.user_id)
        relatives = {}
        if self.dbContact is not None:
            relatives['phone'] = self.dbContact.phone
            relatives['mobile'] = self.dbContact.mobile

        self.contact_due_data = relatives_is_overdue(relatives)
        if self.oAddress is not None:
            self.address_vscontact = self.oAddress.vsContact(relatives)
            self.address_vsuser = self.oAddress.vsUser(self.dbUser.mobile)
            self.address_vsloan = Addrloan(self.oAddress.pd_address).run()
        # 5. 与detail联合匹配
        if self.oDetail is not None:
            self.__detailVs()

        # 6. 黑名单
        self.black_data = self.__blackNum()
        return operator_data
Esempio n. 10
0
    def _rundetail(self,id):
        # logger.error('child pid %s:', os.getpid())
        #获取开放平台聚信立信息
        jxlData = OpenJxlStat().getData(id)
        if jxlData is None:
            print("there is nothing data to deal with")
            return None
        #获取聚信立报告并分析
        try:
            phone = jxlData.phone
            if not str(phone).isdigit():
                logger.error("the phone must be a number: %s" % phone)
                return False

            detailData = OpenJxlStat().getByPhone(phone)
            if detailData is None:
                logger.error("the phone does not exist in jxlstat : %s" % phone)
                return False

            #2.获取通话详情信息
            url = detailData.get('detail_url')
            detail_data = OpenJxlStat().getDetail(url)
            if detail_data is None:
                logger.error("json_url:%s can't get detail_data" % (url))
                return False

            #3. 分析详单
            analisis_res = DetailAnalysis(detail_data)._analysis()
            if analisis_res is None:
                logger.error("mobile:%s can't get analisis_res" % (phone))
                return False
            #4. 详单数据入库
            # print(analisis_res)
            save_res = DetailList().saveDetailList(analisis_res,jxlData)
            re_save_res = ReverseDetailList().saveDetailList(analisis_res, jxlData)
            return True
        except Exception as e:
            logger.error("analysis fail: %s" % e)
            return False
Esempio n. 11
0
 def run(self):
     #通过手机号获取jxl_stat
     self.jxl_record = OpenJxlStat().getByPhone(self.user_phone)
     if self.jxl_record is None:
         self.jxlstat_id = 0
         self.report_type = {"report_type": 0}
     else:
         self.jxlstat_id = self.jxl_record.get("jxlstat_id")
         self.report_type = {"report_type": self.jxl_record.get("source")}
     # 插入请求AfTagBase
     self.__saveAfTagBase()
     #插入请求表
     self.base_id, oBase = self.__saveApiBase()
     if self.base_id == 0:
         return None
     try:
         # 1.分析
         # 运营商报告数据
         operator_data = self.__analysis()
         # 入库数据
         dict_data = self.__getResult(operator_data)
         # 整合结果
         dict_data_param = copy.deepcopy(dict_data)
         db_dict_data = self.__mergeData(dict_data_param)
         # 2.入库
         oApiDbAgent = ApiDbAgent()
         res = oApiDbAgent.api_import_db(db_dict_data)
         # 3.修改请求表状态
         oBase.changeStatus(2)
         # 4.拼接返回数据
         return_data = self.__formatData(dict_data)
         return return_data
     except Exception as e:
         logger.error("代码异常, StrategyId:%d , 异常信息: %s" %
                      (self.credit_id, e))
         oBase.changeFail()
         return None
Esempio n. 12
0
    def run_strategy(self):
        strategyData = self.__getInitStrateryData()
        if strategyData is None:
            return None

        for oStrategy in strategyData:
            # 获取请求业务端数据
            try:
                oCredit = CreditRequest().getByStReqId(oStrategy.id)
                creditData = oCredit.credit_data
                creditData = json.loads(creditData)
            except Exception as e:
                logger.error("请求参数获取失败, StrategyId:" + str(oStrategy.id) + ", 异常信息: %s" % (e))
                continue

            aid = creditData.get('aid', None)
            phone = creditData.get('mobile', None)
            contain = self.__getContainByAid(aid)
            # 判断聚信立报告是否取得
            if oStrategy.version < 20:
                record = OpenJxlStat().getByPhone(phone)
                if record is None:
                    res = oStrategy.finished(0)
                    logger.error("未取得聚信立报告, 稍后执行")
                    continue
            # 拼接请求参数
            requestArgs = {
                'aid': aid,
                'credit_id': oStrategy.id,
                'identity': creditData.get('identity', None),
                'phone': phone,
                'realname': creditData.get('realname', None),
                'contain': contain,
                'contact': creditData.get('relation', None),
            }
            oRequest = dict2object(requestArgs)
            # 调用数据分析方法
            try:
                obj = OperatorLogic(oRequest)
                dict_data = obj.run()
                if dict_data is None:
                    logger.error("数据解析失败, StrategyId:" + str(oStrategy.id))
                else:
                    res = oStrategy.finished(2)
                    logger.error("数据解析成功, StrategyId:" + str(oStrategy.id))
            except Exception as e:
                logger.error("代码异常, StrategyId:" + str(oStrategy.id) + ", 异常信息: %s" % (e))

        return True
Esempio n. 13
0
class OperatorLogic():
    def __init__(self, data):
        self.credit_id = data.credit_id
        self.aid = data.aid
        self.contain = data.contain
        self.realname = data.realname
        self.user_phone = data.phone
        self.identity = data.identity
        self.contact = data.contact
        self.__init_obj()
        self.__init_dict()
        self.base_id = 0
        self.jxlstat_id = 0
        self.detail_phone = None

    def __init_obj(self):
        # analysis类
        self.oAddress = None
        self.oDetail = None

    def __init_dict(self):
        # 字典各项分析结果
        self.report_type = {}
        self.loan = {}
        self.address_vscontact = {}
        self.address_vsuser = {}
        self.detail_vsaddress = {}
        self.detail_vscontact = {}
        self.loan_total_all = {}
        self.address_tag = {}
        self.detail_tag = {}
        self.other_data = {}

    def run(self):
        #通过手机号获取jxl_stat
        self.jxl_record = OpenJxlStat().getByPhone(self.user_phone)
        if self.jxl_record is None:
            self.jxlstat_id = 0
            self.report_type = {"report_type": 0}
        else:
            self.jxlstat_id = self.jxl_record.get("jxlstat_id")
            self.report_type = {"report_type": self.jxl_record.get("source")}
        # 插入请求AfTagBase
        self.__saveAfTagBase()
        #插入请求表
        self.base_id, oBase = self.__saveApiBase()
        if self.base_id == 0:
            return None
        try:
            # 1.分析
            # 运营商报告数据
            operator_data = self.__analysis()
            # 入库数据
            dict_data = self.__getResult(operator_data)
            # 整合结果
            dict_data_param = copy.deepcopy(dict_data)
            db_dict_data = self.__mergeData(dict_data_param)
            # 2.入库
            oApiDbAgent = ApiDbAgent()
            res = oApiDbAgent.api_import_db(db_dict_data)
            # 3.修改请求表状态
            oBase.changeStatus(2)
            # 4.拼接返回数据
            return_data = self.__formatData(dict_data)
            return return_data
        except Exception as e:
            logger.error("代码异常, StrategyId:%d , 异常信息: %s" %
                         (self.credit_id, e))
            oBase.changeFail()
            return None

    def __analysis(self):
        # 1.初始化通讯录
        addrList = AddressList().getByUserPhoneDict(self.user_phone)
        # 2.通讯录号码标签
        number_label = NumberLabelApi()
        if len(addrList) > 0:
            self.address_tag = number_label.getAddressTag(
                self.user_phone, addrList)

        user_id = self.__getUserId()
        # 3.学信、社保、公积金维度的数据信息验证
        third_party_dict = {
            "aid": self.aid,
            "user_id": user_id,
            "identity_code": self.identity,
            "realname": self.realname
        }
        self.other_data = thirdPartyApi(third_party_dict).run()

        # 4.调用OperatorAnalysis
        operatorObj = OperatorAnalysisApi()
        operator_data = operatorObj.getOperatorData(addrList, self.jxl_record)
        if operatorObj is not None:
            self.oDetail = operatorObj.oDetail
            self.oAddress = operatorObj.oAddress
            self.detail_phone = operatorObj.detail_phone
        '''
        #=============不需要返回start==========
        # 4. 跟业务模型数据交叉合并
        # 亲属联系人与是否逾期(需要与一亿元交互)  返回字段是{'com_r_overdue': 0, 'com_c_overdue': 0}
        relatives = {}
        if self.contact != '':
            relatives = json.loads(self.contact)
            relatives['phone'] = relatives.get("phone")
            relatives['mobile'] = relatives.get("mobile")
        self.contact_due_data = relatives_is_overdue(relatives)
        logger.info("bbbbb=%s" % self.contact_due_data)
        # self.dbContact = YiFavoriteContact().getByUserId(self.user_id)
        # relatives = {}
        # if self.dbContact is not None:
        #     relatives['phone'] = self.dbContact.phone
        #     relatives['mobile'] = self.dbContact.mobile
        #
        # self.contact_due_data = relatives_is_overdue(relatives)
        # =============不需要返回end==========
        '''

        relatives = {}
        if self.contact != '':
            relatives = json.loads(self.contact)
            relatives['phone'] = relatives.get("phone")
            relatives['mobile'] = relatives.get("mobile")
        pd_address = None
        if self.oAddress is not None:
            self.address_vscontact = self.oAddress.vsContact(relatives)
            self.address_vsuser = self.oAddress.vsUser(self.user_phone)
            pd_address = self.oAddress.pd_address
        self.loan, self.loan_total_all = LoanLogic(pd_address, self.user_phone,
                                                   self.contact,
                                                   self.contain).run()

        # 6.详单tag
        if self.detail_phone:
            try:
                calls = self.detail_phone['raw_data']['members'][
                    'transactions'][0]['calls']
                pd_detail = pd.DataFrame(calls)
                other_cell_phone = list(pd_detail['other_cell_phone'])
                self.detail_tag = number_label.getDetailTag(
                    self.user_phone, other_cell_phone)
            except Exception as e:
                logger.error("号码标签vs详单异常: %s" % (e))
        # 7.与detail联合匹配
        if self.oDetail is not None:
            self.__detailVs()

        return operator_data

    def __getResult(self, operator_data):
        # 整合结果集
        # 1 通讯录数据
        dict_data = {}
        address_data = DictMerge()
        address_data.set(operator_data.get('address'))
        address_data.set(self.address_vscontact)
        address_data.set(self.address_vsuser)
        dict_data['address'] = address_data.get()

        loan_data = DictMerge()
        loan_data.set(self.loan)
        dict_data['loan'] = loan_data.get()

        summary_data = DictMerge()
        summary_data.set(self.loan_total_all)
        dict_data['summary_data'] = summary_data.get()

        detail_tag_data = DictMerge()
        detail_tag_data.set(self.detail_tag)
        dict_data['detail_tag'] = detail_tag_data.get()

        address_tag_data = DictMerge()
        address_tag_data.set(self.address_tag)
        dict_data['address_tag'] = address_tag_data.get()

        ss_report_data = DictMerge()
        ss_report_data.set(operator_data.get('ss_report'))
        dict_data['ss_report'] = ss_report_data.get()

        mh_report_data = DictMerge()
        mh_report_data.set(operator_data.get('mh_report'))
        dict_data['mh_report'] = mh_report_data.get()

        report_data = DictMerge()
        report_data.set(operator_data.get('report'))
        dict_data['report'] = report_data.get()

        detail_data = DictMerge()
        detail_data.set(operator_data.get('detail'))
        detail_data.set(self.detail_vsaddress)
        dict_data['detail'] = detail_data.get()

        detail_other_data = DictMerge()
        detail_other_data.set(operator_data.get('detail_other'))
        dict_data['detail_other'] = detail_other_data.get()

        contact_data = DictMerge()
        contact_data.set(self.detail_vscontact)
        #contact_data.set(self.contact_due_data)
        dict_data['contact'] = contact_data.get()

        other_data = DictMerge()
        other_data.set(self.other_data)
        dict_data['other_data'] = other_data.get()

        return dict_data

    def __mergeData(self, dict_data):
        def mergeBase(dict_data):
            ''' 合并 base_id '''
            if dict_data is None:
                return {}
            if len(dict_data) == 0:
                return {}
            dict_data['base_id'] = self.base_id
            dict_data['create_time'] = datetime.now().strftime(
                '%Y-%m-%d %H:%M:%S')
            return dict_data

        for key, value in dict_data.items():
            if key == "loan":
                for k, v in value.items():
                    value[k] = mergeBase(value[k])
            else:
                dict_data[key] = mergeBase(dict_data[key])
        return dict_data

    def __detailVs(self):
        # 1 vs 亲属
        self.detail_vscontact = self.__detailVsContact(self.oDetail)
        # 2 vs address
        if self.oAddress is not None:
            #返回{'vs_phone_match': 0, 'vs_connect_match': 0, 'vs_duration_match': 0, 'vs_valid_match': 0}
            self.detail_vsaddress = self.oDetail.vsAddressApi(
                self.oAddress.pd_address)

    def __detailVsContact(self, oDetail):
        # 2 vs 亲属,常用联系人
        dict_contact = {}
        if self.contact != '':
            relatives = json.loads(self.contact)
            dict_contact['phone'] = relatives.get("phone")
            dict_contact['mobile'] = relatives.get("mobile")
        detail_vscontact = oDetail.vsContact(dict_contact)
        return detail_vscontact

    # 保存请求数据
    def __saveApiBase(self):
        oBase = ApiBase()
        oBase.credit_id = self.credit_id
        oBase.aid = self.aid
        oBase.contain = self.contain
        oBase.realname = self.realname
        oBase.mobile = self.user_phone
        oBase.identity = self.identity
        oBase.contact = self.contact
        oBase.jxlstat_id = self.jxlstat_id
        oBase.report_type = self.report_type.get('report_type', 0)
        oBase.status = 0
        oBase.create_time = datetime.now()
        oBase.modify_time = datetime.now()
        base_id = oBase.save()
        return base_id, oBase

    # 保存标签表数据
    def __saveAfTagBase(self):
        try:
            tagData = {
                'aid': self.aid,
                'base_id': self.credit_id,
                'user_id': 0,
                'phone': self.user_phone,
                'tag_status': 0,
                'create_time': datetime.now(),
                'modify_time': datetime.now()
            }
            return AfTagBase().addData(tagData)
        except Exception as e:
            logger.error("credit_id:%d save tag_base is fail: %s" %
                         (self.credit_id, e))

    def __formatData(self, dict_data):
        data = {}
        data.update(dict_data.get("address"))
        data.update(dict_data.get("ss_report"))
        data.update(dict_data.get("mh_report"))
        data.update(dict_data.get("report"))
        data.update(dict_data.get("detail"))
        data.update(dict_data.get("detail_other"))
        data.update(dict_data.get("contact"))
        data.update(dict_data.get("detail_tag"))
        data.update(dict_data.get("other_data"))
        data.update(self.report_type)
        data['loan'] = self.loan
        data['summary_data'] = self.loan_total_all
        return data

    def __getUserId(self):
        aid = int(self.aid)
        if aid == 1:
            from module.yiyiyuan.model.yi_user import YiUser as User
        elif aid == 16:
            from module.huakashop.model.shop_loan_user import ShopLoanUser as User
        elif aid == 17:
            from module.yigeyinew.model.shop_loan_user import ShopLoanUser as User
        else:
            return 0
        oUser = User().getByMobile(self.user_phone)
        if oUser is None:
            return 0
        return oUser.user_id
Esempio n. 14
0
    def runbase(self):
        strategy_data = self._getStrategy()
        if strategy_data is None:
            print("there is nothing data to deal with")
            return None

        for db_strategy in strategy_data:
            try:
                # get user_info
                oYiUser = YiUser().getByUserId(db_strategy.user_id)
                record = None
                if oYiUser is not None:
                    record = OpenJxlStat().getByPhone(oYiUser.mobile)
                # get jxl_stat
                jxlstat_id = 0 if record is None else record.get('jxlstat_id')
                if db_strategy.version < 20:
                    if jxlstat_id == 0:
                        res = db_strategy.finished(0)
                        continue
                # save af_base
                baseInfo  = {
                    'request_id':db_strategy.req_id,
                    'aid':db_strategy.aid,
                    'user_id':db_strategy.user_id,
                    'loan_id':db_strategy.loan_id,
                    'jxlstat_id':jxlstat_id,
                    'match_status':0,
                    'create_time':datetime.now(),
                    'modify_time':datetime.now()
                }
                afbase_id = AfBase().addBaseData(baseInfo)
                print(afbase_id)
                try:
                    #增加中间表
                    relation_id = AfRelationBase().saveData(afbase_id, db_strategy.id)
                    print(relation_id)
                except Exception as e:
                    print(e)
                #get last ID

                # save af_jac_base
                jacbaseinfo = {
                    'aid': db_strategy.aid,
                    'jac_match_id':0,
                    'request_id': db_strategy.req_id,
                    'base_id' : afbase_id,
                    'user_id' : db_strategy.user_id,
                    'loan_id' : db_strategy.loan_id,
                    'mobile' : 0 if oYiUser is None else oYiUser.mobile,
                    'jac_status' : 0,
                    'base_status' : 0,
                    'create_time' : datetime.now(),
                    'modify_time' : datetime.now()
                }
                afjacbase = AfJacBase().addData(jacbaseinfo)
                print(afjacbase)

                # save af_tag_base
                tagbaseinfo = {
                    'aid': db_strategy.aid,
                    'base_id': afbase_id,
                    'user_id': db_strategy.user_id,
                    'phone': 0 if oYiUser is None else oYiUser.mobile,
                    'tag_status': 0,
                    'create_time': datetime.now(),
                    'modify_time': datetime.now()
                }
                aftagbase = AfTagBase().addData(tagbaseinfo)
                print(aftagbase)
            except Exception as e:
                print(e)
                logger.error("af_base save fail %s" %e)

        return True
Esempio n. 15
0
class PodloanAnalysis(object):
    def __init__(self, data):
        self.request_id = data.request_id
        self.aid = data.aid
        self.user_id = data.user_id
        self.loan_id = data.loan_id
        self.user_phone = data.phone

        self.jxl_record = {}
        self.address_info = {}
        self.contact_due_data = {}
        self.relatives = self.__relation(data.relation)
        self.operator = self.__load_json(data.operator)
        self.address_list = self.__load_json(data.address)

        self.base_id = 0
        self.jxlstat_id = 0
        self.source = 0
        self.__init_obj()
        self.__init_dict()

    def __init_obj(self):
        # analysis类
        self.oAddress = None
        self.oDetail = None

    def __init_dict(self):
        # 字典各项分析结果
        self.address_vscontact = {}
        self.address_vsuser = {}
        self.address_vsloan = {}
        self.detail_vscontact = {}
        self.detail_vsaddress = {}

    def run(self):
        # 分析,整合, 保存
        operator_data = self.__analysis()
        dict_data = self.__getResult(operator_data)
        return dict_data

    def __getResult(self, operator_data):
        # 整合结果集
        # 1 通讯录数据
        dict_data = {}
        address_data = DictMerge()
        address_data.set(operator_data.get('address'))
        address_data.set(self.address_vscontact)
        address_data.set(self.address_vsuser)
        dict_data['address'] = address_data.get()
        dict_data['addr_loan'] = self.address_vsloan

        ss_report_data = DictMerge()
        ss_report_data.set(operator_data.get('ss_report'))
        dict_data['ss_report'] = ss_report_data.get()

        report_data = DictMerge()
        report_data.set(operator_data.get('report'))
        dict_data['report'] = report_data.get()

        detail_data = DictMerge()
        detail_data.set(operator_data.get('detail'))
        detail_data.set(self.detail_vsaddress)
        dict_data['detail'] = detail_data.get()

        detail_other_data = DictMerge()
        detail_other_data.set(operator_data.get('detail_other'))
        dict_data['detail_other'] = detail_other_data.get()

        contact_data = DictMerge()
        contact_data.set(self.detail_vscontact)
        contact_data.set(self.contact_due_data)
        dict_data['contact'] = contact_data.get()

        # 5 整合结果
        dict_data = self.__mergeData(self.user_id, self.request_id, self.aid,
                                     dict_data)
        return dict_data

    def __mergeData(self, user_id, request_id, aid, dict_data):
        def mergeUser(dict_data):
            ''' 合并 user_id '''
            if dict_data is None:
                return {}
            if len(dict_data) == 0:
                return {}
            dict_data['user_id'] = user_id
            dict_data['request_id'] = request_id
            dict_data['aid'] = aid
            dict_data['create_time'] = datetime.now()
            return dict_data

        for k in dict_data:
            dict_data[k] = mergeUser(dict_data[k])
        return dict_data

    def __analysis(self):
        # 1.写入请求base
        self.__saveBase()

        # 2. 获取通讯录数据
        self.address_record = self.__get_address_record()

        # 3. 调用OperatorAnalysis
        operatorObj = OperatorAnalysis()
        operator_data = operatorObj.getOperatorData(self.address_record,
                                                    self.jxl_record)

        if operatorObj is not None:
            self.oDetail = operatorObj.oDetail
            self.oAddress = operatorObj.oAddress
        #4. 跟业务模型数据交叉合并
        # 亲属联系人与是否逾期
        self.contact_due_data = relatives_is_overdue(self.relatives)

        if self.oAddress is not None:
            self.address_vscontact = self.oAddress.vsContact(self.relatives)
            self.address_vsuser = self.oAddress.vsUser(self.user_phone)
            self.address_vsloan = Addrloan(self.oAddress.pd_address).run()

        # 4. 与detail联合匹配
        if self.oDetail is not None:
            self.__detailVs()
        return operator_data

    def __saveBase(self):
        if int(self.operator.get('type')) == 1:
            req_id = 0 if self.operator.get(
                'data') is None else self.operator.get('data')
            self.jxl_record = OpenJxlStat().getByRequestId(req_id)
            self.jxlstat_id = self.jxl_record.get(
                'jxlstat_id') if self.jxl_record is not None else 0
        afBase = AfBase()
        afBase.request_id = self.request_id
        afBase.aid = self.aid
        afBase.user_id = self.user_id
        afBase.loan_id = self.loan_id
        afBase.jxlstat_id = self.jxlstat_id
        afBase.match_status = 0
        afBase.create_time = datetime.now()
        afBase.modify_time = datetime.now()
        afBase.save()
        self.base_id = afBase.id

    def __get_address_record(self):
        '''
        通讯录数据获取
        '''
        address_info = {}
        try:
            if (int(self.address_list.get('type')) == 2):
                sign = createSignByMd5({'user_id': self.user_id})
                data = {'user_id': self.user_id, 'sign': sign}
                r = requests.post(self.address_list.get('data'), data=data)
                if r.status_code != 200:
                    logger.error("request_id:%s aid:%s get address is fail" %
                                 (self.request_id, self.aid))
                resp_info = json.loads(r.text)
                if resp_info.get('rsp_code') != '0000':
                    logger.error(
                        "request_id:%s aid:%s get address is fail %s" %
                        (self.request_id, self.aid, resp_info.get('rsp_msg')))
                address_info = resp_info.get('phone_book')  # 通讯录数据
        except Exception as e:
            logger.error("url:%s get address is fail" % e)
        return address_info

    def __detailVs(self):
        # 1 vs 亲属
        self.detail_vscontact = self.__detailVsContact(self.relatives)
        # 2 vs address
        if self.oAddress is not None:
            self.detail_vsaddress = self.oDetail.vsAddress(
                self.oAddress.pd_address)
            return self.detail_vsaddress

    def __detailVsContact(self, relatives):
        # 2 vs 亲属,常用联系人
        if relatives is None:
            return None

        detail_vscontact = self.oDetail.vsContact(relatives)
        return detail_vscontact

    def __relation(self, relation_json):
        res = {}
        try:
            relations = json.loads(relation_json)
            for relation in relations:
                if relation.get('phone') is None and relation.get(
                        'relation', 0) in [1, 2, 5, 6]:
                    res['phone'] = relation.get('mobile')
                else:
                    res['mobile'] = relation.get('mobile')
        except Exception as e:
            logger.error('load relation_json is fail : %s' % e)
        return res

    def __load_json(self, json_data):
        json_obj = {}
        try:
            json_obj = json.loads(json_data)
        except Exception as e:
            logger.error('load json is fail : %s' % e)
        return json_obj