Beispiel #1
0
    def update_ext(self, data):
        user_ext = UserExt(uid=int(self.user.userid))
        user_ext.head_img = data.get('head_img')
        user_ext.logo_url = data.get('logo_url')
        user_ext.contact = data.get('telephone', '')

        apcli('bindUserExt', user_ext)
Beispiel #2
0
    def get_big_uid(self):
        params = self.req.input()
        src = self.get_src()
        log.debug('src:%s' % src)

        # 验证登录
        if not self.check_login():
            raise SessionError('用户未登录')

        if src == 'salesman':
            if not is_valid_int(params.get('big_uid')):
                raise ParamError('参数错误')
            sm_uid = self.user.userid
            cates = apcli('getUserCategory', int(sm_uid), '') or []
            cates = [i.code for i in cates]
            if 'saleman' not in cates and 'qudao' not in cates:
                raise ParamError('该用户非业务员')

            big_cates = apcli('getUserCategory', int(params['big_uid']),
                              '') or []
            big_cates = [i.code for i in big_cates]
            if 'bigmerchant' not in big_cates:
                raise ParamError('非大商户')

            return int(params['big_uid'])

        else:
            if self.get_cate() != 'bigmerchant':
                raise ParamError('非大商户')
            return int(self.user.userid)
Beispiel #3
0
    def POST(self):
        params = self.req.input()
        shopid = params.get("shopid", '')
        newpwd = params.get("newpwd", '')
        if not shopid or not newpwd:
            raise ParamError("参数错误")

        # 验证是否是当前商户的子商户
        userid = self.user.userid
        cate = self.get_cate()
        if cate == "bigmerchant":
            subids = get_linkids(userid)
            shopid = int(shopid)
            if shopid not in subids:
                raise ParamError("非大商户的子商户")

            try:
                apcli("changePwd", uid=shopid, password=newpwd)

                kick_user(int(shopid), mode = 'not_opuser')
                return self.write(success(data={"result": "success"}))
            except:
                log.debug(traceback.format_exc())
                return self.write(success(data={"result": "fail"}))
        else:
            raise ParamError("角色错误")
Beispiel #4
0
    def POST(self):
        userid = int(self.user.userid)
        params = self.req.inputjson()
        password = params.get('password', '')
        mode = params.get('mode', '')

        if not password:
            raise ParamError('密码为空')

        # 支持收银员切换
        if mode == 'opuser':
            opuid = params.get('opuid', '')
        else:
            opuid = self.user.ses.data.get('opuid', '')

        # 验证管理员密码
        if mode == 'manage':
            with get_connection_exception('qf_core') as conn:
                row = conn.select_one(
                    'extra_mchinfo', where={'userid': userid},
                    fields='manage_password'
                )
            if not row or not row['manage_password']:
                raise DBError('未设置过管理密码')
            else:
                if not check_password(password, row['manage_password']):
                    return success(data={'result': 'fail'})
                else:
                    return success(data={'result': 'success'})

        # 验证普通密码
        # 先判断是否opuid有值, 没有opuid属性说明是主账号
        if opuid:
            with get_connection('qf_core') as db:
                opuser = db.select_one(
                    'opuser', fields='password',
                    where={
                        'userid': userid,
                        'opuid': int(opuid),
                        'status': VALID_OPUSER_STATUS
                    }
                )
            if not opuser:
                raise DBError('该操作员不存在')

            if not check_password(password, opuser['password']):
                return success(data={'result': 'fail'})
            else:
                return success(data={'result': 'success'})

        else:
            try:
                apcli('checkByUid', userid, password)
                return success(data={'result': 'success'})
            except ApolloException as e:
                if e.respcd == '1008':
                    return success(data={'result': 'fail'})
                else:
                    raise DBError('密码验证失败')
Beispiel #5
0
def add_user_ext(userid, data):
    contact = data['ext_contact'] if 'ext_contact' in data else data.get(
        'landline', '') or data.get('telephone')
    user_ext = UserExt(uid=int(userid),
                       shoptype_id=data.get('shoptype_id'),
                       contact=contact,
                       head_img=data.get('head_img'),
                       logo_url=data.get('logo_url'),
                       ext=json.dumps(data.get('user_ext') or {}))
    if is_valid_int(data.get('regionid')):
        user_ext.regionid = int(data['regionid'])
    apcli('bindUserExt', user_ext)
Beispiel #6
0
def get_userinfo(userid):
    '''获取店铺信息

    通过apollo.findUserBriefsByIds获取商户的信息

    Params:
        userids: 商户userid,
            若userid为list或者tuple返回字典
            否则, 返回直接返回商户信息

    Raises:
        仅当apollo报错时会抛出错误
    '''
    if isinstance(userid, (list, tuple)):
        mode = 'mul'
        userids = [int(i) for i in userid]
    else:
        mode = 'one'
        userids = [int(userid)]

    try:
        userinfos = apcli('findUserBriefsByIds', userids) or []
    except:
        raise ThirdError('获取商户信息失败')

    userinfos = {i.uid: i.__dict__ for i in userinfos}

    return userinfos.get(int(userid)) if mode == 'one' else userinfos
Beispiel #7
0
    def get_link_ids(self, userid=None):
        '''获取大商户的子商户id列表'''
        cate = self.get_cate(userid)
        if cate != 'bigmerchant':
            return []

        link_ids = None
        try:
            if not userid:
                return self.user.ses.data['link_ids']
        except:
            pass

        try:
            userid = userid or self.user.userid
        except:
            userid = None

        if userid:
            try:
                relats = apcli(
                    'getUserRelation', int(userid),
                    'merchant'
                ) or []
                link_ids = [i.userid for i in relats]

                self.user.ses.data['link_ids'] = link_ids
            except:
                return link_ids

        return link_ids
Beispiel #8
0
    def get_perms(self, userid=None, reload=False):
        self._new_get_perms = False
        try:
            if not reload and not self._new_get_perms:
                return self.user.ses.data['perms']
        except:
            pass

        try:
            self._new_get_perms = True
            userid = int(userid or self.user.userid)
            perms = apcli('get_user_permissions', userid)
            perms = [
                p.code for p in perms or []
                if p.group.startswith(PermDef.PERM_ROLE_GROUP)
            ]
        except:
            perms = []

        try:
            self.user.ses.data['perms'] = perms
        except:
            pass

        return perms
Beispiel #9
0
    def GET(self):
        userid = int(self.user.userid)

        ret = {}
        userinfo = apcli('findUserByid', userid).__dict__
        ret['shopinfo'] = {}
        ret['shopinfo']['shopname'] = userinfo.get('shopname')
        ret['shopinfo']['city'] = userinfo.get('city')
        ret['shopinfo']['province'] = userinfo.get('province')
        ret['shopinfo']['telephone'] = userinfo.get('telephone')
        ret['shopinfo']['address'] = userinfo.get('address')

        # 同步审核后的商户名称
        apply_info = {}
        with get_connection('qf_mis') as db:
            apply_info = db.select_one(table='merchant_change_apply',
                                       where={
                                           'userid': userid,
                                           'changetype': 2,
                                           'status': 3
                                       },
                                       fields='applyjson',
                                       other='order by modifytime desc')

        val = {}
        if apply_info:
            apply_dict = json.loads(apply_info['applyjson'])
            val['shopname'] = unicode_to_utf8(
                apply_dict['change_apply']['nickname'])
            if val['shopname'] != ret['shopinfo']['shopname']:
                apcli_ex('updateUser', int(userinfo['uid']), User(**val))
                ret['shopinfo']['shopname'] = val['shopname']

        return success(ret)
Beispiel #10
0
    def get_big_uid(self, userid=None):
        '''
        获取商户的大商户id
        '''
        big_uid = None
        try:
            if not userid:
                return self.user.ses.data['big_uid']
        except:
            pass

        try:
            userid = userid or self.user.userid
        except:
            userid = None

        if userid:
            try:
                relate = apcli('getUserReverseRelation',
                               int(userid), 'merchant')
                big_uid = relate[0].userid if relate else 0

                self.user.ses.data['big_uid'] = big_uid
            except:
                return big_uid

        return big_uid
Beispiel #11
0
def apcli_ex(func, *args, **kw):
    ret = None
    try:
        ret = apcli(func, *args, **kw)
    except:
        log.debug(traceback.format_exc())

    return ret
Beispiel #12
0
def ap_client(func, *args, **kw):
    try:
        return apcli(func, *args, **kw)
    except ApolloException as e:
        raise ThirdError(e.respmsg)
    except:
        log.warn(traceback.format_exc())
        raise ThirdError('第三方服务错误')
Beispiel #13
0
def get_user_bank_info(userid):

    try:
        bank_info = apcli('userprofile_by_id', userid)['bankInfo'] or {}
    except:
        raise ThirdError('获取商户详细信息失败')

    return bank_info
Beispiel #14
0
def get_user_detail_info(userid):

    try:
        detail_info = apcli('findUserByid', userid) or {}
    except:
        raise ThirdError('获取商户详细信息失败')

    detail_info = detail_info.__dict__
    return detail_info
Beispiel #15
0
def get_linkids(userid):
    '''
    获取子商户
    '''
    try:
        relates = apcli('getUserRelation', int(userid), 'merchant')
        linkids = [i.userid for i in relates]
    except:
        raise ThirdError('获取子商户列表失败')

    return linkids
Beispiel #16
0
 def get_dzero_users(self, userids):
     '''通过user_service的code来判断d0'''
     ret = []
     if not userids:
         return ret
     users_service = apcli('getAllUserServices', userids)
     for k, v in users_service.iteritems():
         codes = [service.code for service in v if service.status == 1]
         if 'balance' in codes:
             log.debug('userid={},codes={}'.format(k, codes))
             ret.append(k)
     return ret
Beispiel #17
0
def get_big_uid(userid, data):
    # 大商户userid
    big_uid = -1
    try:
        relate = apcli('getUserReverseRelation', int(userid), 'merchant')
        if relate:
            big_uid = relate[0].userid
    except:
        log.warn(traceback.format_exc())
        return data

    return big_uid
Beispiel #18
0
    def POST(self):
        self.req.inputjson()['password'] = '******'
        data = self.validator.data

        change_user = data['username'] or data['mobile']

        # 重置密码
        if data['mode'] == 'reset':
            if not data['code']:
                raise ParamError('验证码不能为空')

            if not change_user:
                raise ParamError('修改账号不能为空')
            # 验证验证码
            if not check_smscode(data['code'], change_user, 1):
                raise ParamError('验证码错误')

            userid = self.get_userid(change_user)

        # 修改密码
        else:
            if self.check_login():
                if data['src'] == 'big-submchnt':
                    userid = self.get_userid(change_user)
                    self.check_link(int(self.user.userid), userid)
                else:
                    userid = int(self.user.userid)
            else:
                raise SessionError('商户未登录')

        # 调用apollo修改密码
        apcli('changePwd', userid, data['password'])

        # 剔除所有正在登陆的商户
        kick_user(userid, mode='not_opuser')

        # 将商户从名单剔除
        self.kick_sign_tag(userid)

        return self.write(success({}))
Beispiel #19
0
    def _get_act_ext(self, data):
        user = None
        try:
            user = apcli('findUserBriefById', int(data['userid']))
        except:
            log.warn(traceback.format_exc())
        userinfo = (user or UserBrief()).__dict__
        share = Share()
        share.title = config.SHARE_ACT_DEFAULT_CONF['title'].format(**userinfo)
        share.desc = config.SHARE_ACT_DEFAULT_CONF['desc']
        share.icon_url = config.SHARE_ACT_DEFAULT_CONF['icon_url']

        return ActivityExt(**{'share': share})
Beispiel #20
0
    def check_customer(self, mobile):
        '''
        消费者补充会员休息
        '''
        enuserid = self.req.input().get('enuserid')
        if enuserid:
            try:
                userid = hids.decode(enuserid)[0]
            except:
                if not is_valid_int(enuserid):
                    return
                userid = int(enuserid)

            user = apcli('findUserBriefById', userid)
            if user:
                self._groupid = user.groupid
Beispiel #21
0
    def GET(self):

        params = self.req.input()
        userid = params.get("userid", '')
        usertype = params.get("usertype", '')
        try:
            usertype = int(usertype)
        except:
            raise ParamError("usertype参数错误")
        if usertype not in UserDefine.SIGNUP_USERTYPES:
            raise ParamError("usertype参数错误")
        if not userid:
            raise ParamError("userid参数错误")

        # 验证传入的userid是否属于当前业务员
        curr_uid = self.user.userid

        qd_info = get_qd_mchnt(userid)
        if qd_info:
            slsm_uid = qd_info.slsm_uid
            if slsm_uid != int(curr_uid):
                return self.write(error(QFRET.DBERR, respmsg="商户id参数与当前操作员无绑定关系"))

        cate = self.get_cate(userid=userid)
        if cate == "bigmerchant":
            sub_uids = get_linkids(userid)

            if not sub_uids:
                return self.write(success(data={}))
            else:

                # 先筛选出状态为审核通过的商户 最新商户信息从审核通过商户中选取
                with get_connection('qf_mis') as db:
                    rows = db.select('apply', where={'user': ('in', sub_uids), 'state': APPLY_STATE.get("pass")}, fields='user')
                if rows:
                    sub_uids = [i['user'] for i in rows]
                else:
                    return self.write(success(data={}))

                ret = dict()

                # 查询出最新的userid, name和legalname
                with get_connection("qf_core") as db:
                    rows = db.select("profile", where={"userid": ("in", sub_uids), "user_type": usertype},
                                     fields="userid, name, legalperson, user_type", other="order by jointime desc")
                    if len(rows) <= 0:
                        return self.write(success(data={}))
                    latest_uid = rows[0]['userid']

                    usertype = int(rows[0]['user_type'])
                    name = rows[0]['name']
                    legal_name = rows[0]['legalperson']

                    if usertype == UserDefine.SIGNUP_USERTYPE_TINY:
                        ret['name'] = name
                    else:
                        ret['name'] = legal_name

                try:
                    detail_info = apcli('userprofile_by_id', latest_uid)
                except:
                    log.debug(traceback.format_exc())
                    raise ThirdError("获取商户详情失败")
                user_info = detail_info['user']
                bank_info = detail_info['bankInfo']

                ret['banktype'] = bank_info['banktype']
                ret['bankuser'] = bank_info['bankuser']
                ret['bankaccount'] = bank_info['bankaccount']
                ret['bankmobile'] = bank_info['bankmobile']
                ret['bankProvince'] = bank_info['bankProvince']
                bank_city = bank_info.get('bankCity', '')
                head_bankname = bank_info.get('headbankname', '')
                ret['bankCity'] = bank_city
                ret['headbankname'] = head_bankname
                with get_connection_exception('qf_mis') as db:
                    r = db.select_one('tools_areacity', where={'city_name': bank_city}, fields='city_no, city_name') or {}
                    head_bank = db.select_one('tools_bank', where={'bank_name': head_bankname, 'bank_display': 1},
                                              fields='bank_name, bank_no') or {}
                ret['city_id'] = r.get('city_no', '')
                ret['headbankid'] = head_bank.get('bank_no', '')
                ret['bankcode'] = bank_info.get('bankcode', '')
                ret['bankname'] = bank_info['bankname']

                ret['idnumber'] = user_info['idnumber']
                ret['address'] = user_info['address']


                user_ext = apcli_ex('getUserExt', int(latest_uid))
                ret['shoptype_id'] = ''
                if user_ext:
                    ret['shoptype_id'] = user_ext.shoptype_id

                # 身份证有效期, 照片,
                cert_names = ["idcardfront", "idcardback", "idcardinhand", "licensephoto"]

                # 常量对应
                cert_imgurl = {"idcardfront": 'idcardfront_url', "idcardback": 'idcardback_url',
                               "idcardinhand": "idcardinhand_url", "licensephoto": "license_photo_url"}

                all_img_info = get_img_info(latest_uid, cert_names)

                for i in all_img_info:
                    ret.update({cert_imgurl[i['name']]: i['imgurl']})

                with get_connection('qf_mis') as db:
                    db_ret = db.select('apply', fields="idstatdate, idenddate",
                                       where={"user": latest_uid}, other="limit 1")
                    if db_ret:
                        ret.update(db_ret[0])
                    else:
                        ret.update({
                            "idstatdate": "",  # 身份证起始时间
                            "idenddate": "",  # 身份证结束时间
                        })
                return self.write(success(data=ret))

        else:
            raise ParamError("角色错误")
Beispiel #22
0
    def get_user_services(self, pos='all', addon=None, limit=None):
        '''
        获取用户功能列表
        参数:
            pos all:全部功能 home_page:首页 head: 头部
            addon 功能多加载的数据
            limit 限制数量
        '''
        userid = int(self.user.userid)
        language = self.get_language()

        # 获取用户的信息
        user = apcli('findUserBriefById', userid)
        if not user:
            raise ThirdError('商户不存在')
        user = user.__dict__
        self._user = user

        # 获取用户的登录角色
        user_cate = self.get_user_cate()

        # 获取渠道配置
        qd_conf = get_qd_conf()

        # 用户服务列表
        groupid = user['groupid']
        default_services = get_qd_conf_value(userid,
                                             'default',
                                             'service',
                                             groupid=groupid,
                                             default=config.DEFAULT_SERVICES,
                                             qd_confs=qd_conf)
        user_service = apcli.user_service(userid)
        self._user_service = {i['code']
                              for i in user_service} | set(default_services)

        # 根据版本号和平台获取服务列表
        version, platform = get_app_info(
            self.req.environ.get('HTTP_USER_AGENT', ''))
        log.info('user_agent:%s version:%s  platform:%s userid:%s' %
                 (self.req.environ.get('HTTP_USER_AGENT',
                                       ''), version, platform, userid))
        sys_services = get_qd_conf_value(userid,
                                         'services',
                                         'service',
                                         groupid=groupid,
                                         default=config.SYSTEM_SERVICES,
                                         qd_confs=qd_conf)
        must_addon = [
            'recharge_link', 'group_link', 'condition', 'dis_groupids',
            'nodis_groupids', 'dis_service', 'dis_condition', 'show_cate'
        ]
        addon = (addon or []) + must_addon
        services = get_services(version,
                                platform,
                                addon=addon,
                                sys_services=sys_services)

        # 调整返回值
        ret = []
        payinfo = None
        user_open_service = {i['code'] for i in user_service}
        for service in services:
            # 若不满足条件, 直接跳过
            if service['code'] not in self._user_service:
                continue

            # 指定角色才展示
            show_cates = service.pop('show_cate') or [
                'merchant', 'submerchant'
            ]
            if user_cate not in show_cates:
                continue

            # 显示位置判断
            tpos = service.pop('pos') or ['all']
            if pos not in tpos:
                continue

            dis_condition = service.pop('dis_condition', None)
            if dis_condition:
                try:
                    if not eval(
                            dis_condition,
                        {
                            'user': user,
                            'user_open': service['code'] in user_open_service
                        }):
                        continue
                except:
                    log.warn(traceback.format_exc())
                    continue

            # 条件
            condition = service.pop('condition', None)

            # 渠道link
            group_link = service.pop('group_link', None)  # 渠道link

            # 根据grouid配置是否展示
            dis_groupids = service.pop('dis_groupids') or config.QF_GROUPIDS
            nodis_groupids = service.pop(
                'nodis_groupids') or config.QF_GROUPIDS

            # 付费后的链接
            recharge_link = service.pop('recharge_link', None)

            # 余额提现链接
            dis_service = service.pop('dis_service', '')

            # 根据条件判断
            if condition:
                # 如果指定服务存在将不展示
                if ('dis_service' in condition
                        and dis_service in self._user_service):
                    continue

                # 根据渠道判断
                # 白牌渠道不展示
                if 'group_dis' in condition:
                    if groupid in qd_conf:
                        continue

                # 根据渠道id来控制展示
                if 'group_control' in condition:
                    if groupid not in dis_groupids:
                        continue

                # 根据渠道id来控制展示
                if 'nogroup_control' in condition:
                    if groupid in nodis_groupids:
                        continue

                # 白牌渠道link
                if 'group_link' in condition:
                    if groupid in qd_conf:
                        service['link'] = group_link

                # 开通点餐服务
                if 'diancan_service' in condition:
                    if payinfo is None:
                        payinfo = get_mchnt_paying(userid, code='diancan')
                    if payinfo and str(payinfo['expire_time']) > time.strftime(
                            DATETIME_FMT):
                        service['link'] = recharge_link

            # 链接带上参数
            service['link'] = service['link'].format(**user)

            # name根据语言可控制
            if 'name' in service:
                service['name'] = get_constant(service['name'], language)

            ret.append(service)

        return ret[:limit]