Ejemplo n.º 1
0
class Apply(BaseHandler):
    '''
    生意王上传
    '''

    STATE_PATTERN = r'^(1|2|3|4)$'

    _validator_fields = [
        Field('wx_pub', T_STR, default=''),
        Field('mobile', T_STR, default=''),
        Field('license_state', T_REG, match=STATE_PATTERN, default=1),
    ]

    @with_validator()
    @check_login
    @raise_excp('上传信息失败')
    def POST(self):
        data = self.validator.data
        data['ctime'] = data['utime'] = int(time.time())
        data['id'] = getid()
        data['userid'] = self.user.userid
        data['state'] = 1
        if not data['mobile']:
            user = apcli.user_by_id(data['userid']) or {}
            data['mobile'] = user.get('mobile') or ''

        with get_connection('qf_mchnt') as db:
            db.insert('bk_apply', data)

        return self.write(success({}))
Ejemplo n.º 2
0
class AddTag(MemBase):
    '''
    获取消费详细信息
    '''

    TAG_PATTERN = r'^(coupon|card|prepaid|sale|diancan|submit)$'

    _validator_fields = [
        Field('customer_id', T_INT, isnull=False),
        Field('userid', T_INT, isnull=False),
        Field('tag', T_STR, isnull=False),
        Field('src', T_INT, default=4),
    ]

    _base_err = '更新消费者tag失败'

    @check(['check_ip', 'validator'])
    def POST(self):
        data = self.validator.data
        userid = data['userid']
        customer_id = data['customer_id']
        src = data['src']
        self.add_tag(userid, customer_id, data['tag'], src)

        return self.write(success({}))
Ejemplo n.º 3
0
class Shops(MemBase):
    '''
    获取适用的门店列表
    '''

    _base_err = '获取门店列表失败'

    _validator_fields = [
        Field('page', T_INT, default=0),
        Field('pagesize', T_INT, default=10),
    ]

    @with_validator()
    @raise_excp(_base_err)
    def GET(self):
        userid = hids.decode(self.req.input().get('userid'))
        if not userid:
            raise ParamError('商户userid为空')
        userid = userid[0]

        data = self.validator.data

        limit = data['pagesize']
        offset = data['page'] * data['pagesize']

        ret = {}
        ret['shops'] = self.get_shops(userid, offset, limit)
        ret['shop_num'] = self._shop_num

        return self.write(success(ret))
Ejemplo n.º 4
0
class Manage(BaseHandler):
    '''
    操作会员特权
    '''
    STATUS_PATTERN = r'(1|3)'

    _validator_fields = [
        Field('id', T_INT, isnull=False),
        Field('status', T_REG, match=STATUS_PATTERN, default=None),
        Field('content', T_STR, default=''),
    ]

    def edit(self):
        data = self.validator.data

        values= {i:data[i] for i in ('status', 'content') if data[i]}
        if values:
            with get_connection('qf_mchnt') as db:
                db.update(
                        'member_actv',
                        values= values,
                        where= {
                            'userid': int(self.user.userid),
                            'id': int(self.validator.data['id'])
                        })

        return self.write(success({}))

    @check(['login', 'check_perm'])
    @with_validator()
    @raise_excp('操作特权失败')
    def POST(self, mode):
        func = getattr(self, mode, None)
        if callable(func):
            return func()
Ejemplo n.º 5
0
class Change(BaseHandler):
    '''
    修改用户信息
    '''

    _validator_fields = [
        Field('opuid', T_INT, isnull=False),
        Field('mobile', T_REG, match=SIMPLE_MOBILE_PATTERN, default=None),
        Field('password', T_REG, match=PASSWORD_PATTERN, default=None),
        Field('opname', T_STR, default=None),
        Field('status', T_INT, default=None),
    ]

    _base_err = '修改收银员失败'

    @check('validator')
    def POST(self):
        userid = self.get_userid_login_or_ip()

        d = self.validator.data
        update_data = {}
        if d['status'] not in [None, 0, 1]:
            raise ParamError('状态非法')

        with get_connection_exception('qf_core') as db:
            opuser = db.select_one(table='opuser',
                                   where={
                                       'userid': int(userid),
                                       'opuid': int(d['opuid'])
                                   }) or {}
        if not opuser:
            raise UserError('操作员不存在')

        fields = ['mobile', 'status', 'opname', 'password']
        for field in fields:
            if d[field] is not None:
                if field == 'password':
                    if not check_password(d['password'], opuser['password']):
                        update_data[field] = enc_password(d['password'])
                elif d[field] != unicode_to_utf8(opuser[field]):
                    update_data[field] = d[field]

        if not update_data:
            return success({})

        with get_connection('qf_core') as db:
            db.update('opuser',
                      update_data,
                      where={
                          'userid': userid,
                          'opuid': int(d['opuid'])
                      })

        # 如果更新了状态,则剔除操作员
        if update_data.get('status') == 0 or update_data.get('password'):
            kick_user(userid, int(d['opuid']), mode='opuser')

        return success({})
Ejemplo n.º 6
0
class ToBigMchnt(BaseHandler):
    '''
    成为大商户
    会进行限制
    '''
    fields = [
        Field('username', T_REG, match=MOBILE_PATTERN, isnull=False),
        Field('password', T_REG, match='^\S{6,20}$', isnull=False),
        Field('shopname', isnull=False),
    ]

    def _trans_input(self):
        d = {k: v.strip() for k, v in self.req.input().iteritems()}
        r = {i: d[i] for i in ['username', 'password', 'shopname']}
        user = check_user(d.get('username'))
        if user['is_signup']:
            raise ParamError('该用户已经注册,请更换手机号')

        r['shopname'] = remove_emoji(r['shopname'])
        if not r['shopname']:
            raise ParamError('店名不能为空')

        return r

    def _get_UserProfile(self, d):
        '''用户信息'''
        def get_UserCate():
            return UserCate(code='bigmerchant', name='大商户')

        def get_User():
            p = {}
            p['mobile'] = d['username']  # 用户名
            p['password'] = d['password']  # 密码
            p['shopname'] = d['shopname']  # 店铺名
            p['userCates'] = [get_UserCate()]
            return User(**p)

        return UserProfile(user=get_User())

    @check_ip()
    @check_validator()
    def POST(self):
        try:
            # 转换输入
            d = self._trans_input()

            # 当商户已经注册时,提示错误
            userid, respmsg = apocli.signup(self._get_UserProfile(d),
                                            allow_exist=False)
            if not userid:
                raise ThirdError(respmsg)
            return self.write(success({}))
        except MchntException, e:
            log.warn('ToBigMchnt error: %s' % e)
            return self.write(error(e.errcode, respmsg=e.errmsg))
        except:
Ejemplo n.º 7
0
class AddOpuser(BaseHandler):
    '''
    添加操作员
    '''
    _validator_fields = [
        Field('opuid', T_STR),
        Field('mobile', T_REG, match=SIMPLE_MOBILE_PATTERN),
        Field('password', T_REG, match=PASSWORD_PATTERN, isnull=False),
        Field('opname', T_STR, isnull=False),
    ]

    def check_opuid(self, userid):
        '''
        检查传入的opuid是否已经存在
        '''
        data = self.validator.data

        if not is_valid_int(data['opuid'] or 0):
            raise ParamError('opuid 错误')

        max_opuid = int(UserUtil.get_max_opuid(int(userid)) or 0)
        if not data['opuid']:
            opuid = max_opuid + 1

        else:
            if max_opuid and int(data['opuid']) <= max_opuid:
                raise ParamError('收银员编号:{}已经存在'.format(data['opuid']))
            opuid = int(data['opuid'])

        return opuid

    _base_err = '添加收银员失败'

    @check('validator')
    def POST(self):
        userid = self.get_userid_login_or_ip()

        now = time.strftime(DATETIME_FMT)
        d = self.validator.data
        opuid = int(self.check_opuid(int(userid)))

        data = {}
        data['opname'] = d['opname']
        data['mobile'] = d['mobile']
        data['opuid'] = int(opuid)
        data['userid'] = userid
        data['password'] = enc_password(d['password'])
        data['status'] = 1
        data['create_time'] = now
        data['last_login'] = now
        data['modify_time'] = now

        with get_connection_exception('qf_core') as db:
            db.insert('opuser', data)

        return self.write(success({'opuid': opuid}))
Ejemplo n.º 8
0
class DataList(BaseHandler):
    '''
    数据报告列表报告
    '''

    _validator_fields = [
        Field('page', T_INT, default=0),
        Field('pagesize', T_INT, default=20),
    ]

    @check_login
    @with_validator()
    @raise_excp('获取数据失败')
    def GET(self):
        d = self.validator.data
        datas = None
        with get_connection('qf_mchnt') as db:
            datas = db.select(
                     table= 'actv_effect',
                     where= {
                         'userid' : self.user.userid,
                     },
                     other= ('order by ctime desc limit {limit} offset {offset}'.format(
                        offset = d['page'] * d['pagesize'], limit = d['pagesize'])),
                     fields= 'id, ctime, type, content'
                    ) or []

        actv_effect = config.ACTV_EFFECT
        default_img_url = getattr(config, 'DATA_DEFAULT_IMG_URL', '')
        default_desc_fmt = getattr(config, 'DATA_DEFAULT_DESC_FMT', '')
        default_info_url = getattr(config, 'DATA_DEFAULT_INFO_URL', '')
        ret = []
        for data in datas:
            if data['type'] not in actv_effect:
                continue

            desc_fmt = actv_effect[data['type']].get('_desc_fmt', default_desc_fmt)
            info_url = actv_effect[data['type']].get('_info_fmt', default_info_url)
            param = data['content']
            try:
                actv = json.loads(param)['datas']
                actv = {k: unicode_to_utf8_ex(v) for k, v in actv.iteritems()}
                ret.append({
                    'ctime': tstamp_to_str(data['ctime']),
                    'img_url': actv_effect[data['type']].get('_img_url',
                                                             default_img_url),
                    'type': data['type'],
                    'id': data['id'],
                    'desc': desc_fmt.format(**actv),
                    'info_url': info_url.format(data['id'])
                })
            except:
                log.debug(traceback.format_exc())

        return self.write(success({'datas': ret}))
Ejemplo n.º 9
0
class Preview(BaseHandler):
    '''
    支付预览页面
    '''

    _validator_fields = [
        Field('goods_code', T_STR),
        Field('promo_code', T_STR),
        Field('price_code', T_STR, default='12month'),
    ]

    @check_login
    @with_validator()
    @raise_excp('获取付费预览失败')
    def GET(self):
        userid = int(self.user.userid)

        # 验证信息
        info = RechargeUtil.check_recharge_info(userid, **self.validator.data)
        upgoods = info['goods']

        # 获取当前支付信息
        code = self.validator.data['goods_code']
        cur_amt, cur_expire = RechargeUtil.get_cur_payinfo(userid, code)
        add_conf = {upgoods['price']['alidity']['unit']: upgoods['price']['alidity']['key']}
        expire_time = future(cur_expire, **add_conf)

        # 付费服务信息
        goods_info = copy.deepcopy(upgoods)
        goods_info['price'] = {i:goods_info['price'][i]
                                   for i in ['code', 'goods_name', 'amt']}
        goods_info['services'] = [{i: service.get(i, '') for i in ['title', 'icon_url', 'info_url']}
                                   for service in goods_info['services']]
        goods_info['pg_name'] = '{}权益'.format(goods_info['name'])

        fields = ['services', 'color', 'pg_name', 'code', 'logo_url', 'price', 'desc']
        goods_info = {field:goods_info[field] for field in fields}
        goods_amt = goods_info['price']['amt']


        promo_amt = info.get('promo_amt', 0)
        promo_amt = min(promo_amt, goods_amt - 1)
        ret = {}
        ret['goods_info'] = goods_info
        ret['promo_amt'] = promo_amt
        ret['cur_amt'] = (cur_amt if (promo_amt + cur_amt) < goods_amt
                          else (goods_amt - promo_amt - 1))
        ret['txamt'] = max(goods_amt - promo_amt - cur_amt, 1)
        ret['expire_time'] = expire_time

        return self.write(success(ret))
Ejemplo n.º 10
0
class TabBadge(BaseHandler):
    '''
    导航栏标记
    '''

    _validator_fields = [
        Field('msg_stamp', T_INT, default=0),
        Field('data_stamp', T_INT, default=0),
    ]

    def _get_data_badges(self):
        timestamp = self.validator.data['data_stamp']
        if not timestamp: return 0

        badges = 0
        with get_connection('qf_mchnt') as db:
            badges = db.select_one(table='actv_effect',
                                   fields='count(1) as num',
                                   where={
                                       'userid': int(self.user.userid),
                                       'ctime': ('>', timestamp),
                                   })['num']

        return badges

    def _get_msg_badges(self):
        timestamp = self.validator.data['msg_stamp']
        if not timestamp: return 0
        badges = 0

        try:
            badges = ms_redis_pool.zcount(
                'merch_msg_{}_me'.format(self.user.userid), timestamp + 1,
                '+inf')
        except:
            log.warn(traceback.format_exc())

        return badges

    @check_login
    @with_validator()
    @raise_excp('获取标记失败')
    def GET(self):
        ret = {}
        ret['data_badges'] = self._get_data_badges()
        ret['msg_badges'] = self._get_msg_badges()

        ret['total'] = sum(ret.values())

        return self.write(success(ret))
Ejemplo n.º 11
0
class ChangePerm(BaseHandler):
    '''
    修改用户权限
    '''

    _validator_fields = [
        Field('opuid', T_INT, isnull=False),
        Field('type', T_STR, default=None),
        Field('status', T_INT, default=None),
    ]

    _base_err = '修改用户权限失败'

    @check(['login', 'validator'])
    def POST(self):
        '''
        修改用户权限
        '''
        d = self.validator.data
        userid = int(self.user.userid)

        if not d['opuid']:
            raise ParamError('参数错误')
        if d['status'] is not None and d['status'] not in [0, 1]:
            raise ParamError('状态非法')
        if d['type'] is None:
            type = 'refund'
        else:
            type = d['type']

        # 更新数据
        where = {'userid': userid, 'opuid': int(d['opuid'])}
        perms = {}
        with get_connection('qf_core') as db:
            opuser = db.select_one(table='opuser',
                                   fields=['perms'],
                                   where=where)
            if opuser:
                try:
                    perms = json.loads(opuser['perms'])
                    perms[type] = d['status']
                except:
                    perms[type] = d['status']
                finally:
                    db.update('opuser', {'perms': json.dumps(perms)}, where)

                return self.write(success({}))
            else:
                return self.write(error(QFRET.PARAMERR, respmsg='操作员信息不存在'))
Ejemplo n.º 12
0
class Head(BaseHandler):
    '''
    会员管理列表头部
    '''

    FILTER_PATTERN = r'^(all|lose|card|prepaid|submit)$'

    _validator_fields = [
        Field('filter_key', T_REG, match=FILTER_PATTERN, default='all'),
    ]

    @check_login
    @with_validator()
    @raise_excp('获取数据失败')
    def GET(self):
        userid = self.user.userid

        mode = self.validator.data['filter_key']
        ret = {}
        summary = {}
        summary['total_num'] = summary['td_num'] = 0
        with get_connection('qf_mchnt') as db:
            where = {'userid': userid}
            if mode in ('all', 'lose'):
                # 总数
                if mode == 'lose':
                    where['last_txdtm'] = ('<=',
                            future(days=-60, fmt_type='timestamp'))
                summary['total_num']= db.select_one(
                        table= 'member',
                        where= where,
                        fields= 'count(1) as num')['num']

            elif mode in ('card', 'prepaid', 'submit'):
                summary['total_num'] = db.select_one(
                        'member_tag',
                        where= {
                            'userid': userid,
                            mode: ('>=', 1)
                        },
                        fields= 'count(1) as num')['num']


            summary['td_num']= db.select_one(
                    table= 'member',
                    where= {
                        'userid': userid,
                        'ctime': ('>', get_day_begin_ts())
                    },
                    fields= 'count(1) as num')['num']
        ret['summary'] = summary

        for k in ('filters', 'sorts', 'flags'):
            ret[k] = get_qd_conf_value(mode='member_'+k, key='service',
                                       groupid=self.get_groupid())
        ret['filters'] = ret['filters'] or config.MEMBER_FILTERS
        ret['sorts'] = ret['sorts'] or config.MEMBER_SORTS
        ret['flags'] = ret['flags'] or config.MEMBER_FLAGS

        return self.write(success(ret))
Ejemplo n.º 13
0
class Info(CardBase):
    '''
    会员集点活动详细信息
    '''

    _validator_fields = [
        Field('id', T_INT, isnull=False),
    ]

    _base_err = '获取活动信息失败'

    @check(['ip_or_login', 'validator'])
    def GET(self):
        actv = self.check_allow_query(self.validator.data['id'])

        fields = [
            'id', 'start_time', 'expire_time', 'exchange_num', 'total_pt',
            'status', 'goods_amt', 'goods_name', 'obtain_amt', 'obtain_limit',
            'exchange_pt', 'statement', 'mchnt_id_list'
        ]
        actv_info = {field:actv[field] for field in fields}
        actv_info['id'] = str(actv_info['id'])
        actv_info['state'] = self.get_state(str(actv_info['expire_time']))
        actv_info['big_create'] = int(actv['userid'] != int(self.user.userid))
        actv['promotion_url'] = get_qd_conf_value(
            self.user.userid, 'card', groupid=self.get_groupid()
        )
        actv_info.update(self.get_customers(actv))

        return success(actv_info)
Ejemplo n.º 14
0
class AddInvoice(BaseHandler):
    '''
    添加发票信息
    '''

    _validator_fields = [
        Field('userid', isnull=False),
        Field('title', isnull=False),
        Field('taxNumber', isnull=False),
        Field('companyAddress', isnull=False),
        Field('telephone', isnull=False),
        Field('bankName', isnull=False),
        Field('bankAccount', isnull=False),
    ]

    # @check('validator')
    @with_customer
    def POST(self):
        try:

            if not self.customer.is_login():
                return self.write(
                    error(QFRET.LOGINERR,
                          resperr="user not login",
                          respmsg="用户未登陆"))
            params = self.req.input()
            userid = params.get('userid', '')
            try:
                userid = hids.decode(userid)[0]
            except:
                raise ParamError("商户id错误")
            customer_id = self.customer.customer_id
            title = params.get('title', '')
            tax_no = params.get('taxNumber', '')

            address = params.get('companyAddress', '')
            phone = params.get('telephone', '')
            bank_name = params.get('bankName', '')
            bank_num = params.get('bankAccount', '')

            now = int(time.time())
            values = {'utime': now, 'ctime': now}

            values['userid'] = userid
            values['customer_id'] = customer_id
            values['title'] = title
            values['tax_no'] = tax_no
            values['address'] = address
            values['telephone'] = phone
            values['bank_name'] = bank_name
            values['bank_num'] = bank_num
            with get_connection('qf_mchnt') as db:
                db.insert('invoices', values=values)

            return self.write(success({}))

        except:
            log.warn('error :%s' % traceback.format_exc())
            return self.write(error(QFRET.SERVERERR, respmsg='内部错误'))
Ejemplo n.º 15
0
class Apply_info(BaseHandler):
    '''
    获取审核信息
    '''

    _validator_fields = [
        Field('mode', T_STR),
    ]

    @check_login
    @with_validator()
    @raise_excp('获取审核信息失败')
    def GET(self):
        data = self.validator.data
        values = {k: v for k, v in data.iteritems() if v is not None}

        if not values:
            return self.write(success({}))
        userid = int(self.user.userid)
        user = apcli_ex('findUserBriefById', userid)
        if not user:
            user = UserBrief(city='', uid=userid, province='')

        userids = []
        with get_connection('qf_mis') as db:
            userids = db.select(
                table='merchant_change_apply',
                where={
                    'userid': ('in', [int(userid)]),
                    'changetype': ('in', [int(2)])
                },
                fields='userid,applyjson,status,createtime,modifytime,auditmemo'
            )
        ret = userids

        if ret:
            ret = ret[0]
        else:
            return self.write(success({'status': 3}))

        _applyjson = json.loads(ret['applyjson'])

        log.info("userid :%s", userid)

        if ret['status'] == 2:
            ret['status'] = 1

        return self.write(
            success({
                'change': _applyjson['change_apply']['nickname'],
                'auditmemo': ret['auditmemo'],
                'createtime': ret['createtime'],
                'audittime': ret['modifytime'],
                'status': ret['status']
            }))
Ejemplo n.º 16
0
class Customer(BaseHandler):
    '''
    获取消费者详细信息
    '''

    _validator_fields = [
        Field('activity_id', T_INT, isnull=False),
        Field('page', T_INT, default=0),
        Field('pagesize', T_INT, default=10),
    ]

    @check_login
    @with_validator()
    @raise_excp('查询活动消费者信息失败')
    def GET(self):
        userid = int(self.user.userid)
        data = self.validator.data
        actv = None
        with get_connection('qf_marketing') as db:
            big_uid = self.get_big_uid()
            userids = (userid, big_uid) if big_uid else (userid, )
            actv = db.select_one(table='activity',
                                 where={
                                     'create_mchnt_id': ('in', userids),
                                     'id': data['activity_id'],
                                     'src': ACTIVITY_SRC
                                 },
                                 fields='id')
        if not actv:
            raise ParamError('未查询到该活动')

        num, info = CouponUtil.get_customer(actid=actv['id'],
                                            limit=data['pagesize'],
                                            offset=data['pagesize'] *
                                            data['page'],
                                            raise_ex=True)

        return self.write(success({
            'customer_num': num,
            'customer_info': info
        }))
Ejemplo n.º 17
0
class Cards(MemBase):
    '''
    会员卡列表
    '''

    _base_err = '获取数据失败'

    _validator_fields = [
        Field('page', T_INT, default=0),
        Field('pagesize', T_INT, default=10),
    ]

    @with_validator()
    @raise_excp(_base_err)
    def GET(self):
        data = self.validator.data
        groupid = self.req.input().get('groupid')

        customer_id = self.get_cid()
        limit = data['pagesize']
        offset = data['page'] * data['pagesize']

        return self.write(
            success(self.get_cards(customer_id, groupid, offset, limit)))
Ejemplo n.º 18
0
class Remove(BaseHandler):
    '''
    删除红包活动
    '''

    _validator_fields = [
        Field('coupon_id', T_INT, isnull=False),
    ]

    @check(['login'])
    @with_validator()
    @raise_excp('终止红包推广活动失败')
    def POST(self):
        actv = None
        with get_connection('qf_marketing') as db:
            actv = db.select_one(
                    table= 'activity',
                    where= {
                        'id': self.validator.data['coupon_id'],
                    },
                    fields= 'id, create_mchnt_id, status, create_time')
        if not actv:
            raise ParamError('活动不存在')

        if actv['create_mchnt_id'] != str(self.user.userid):
            if actv['create_mchnt_id'] == str(self.get_big_uid()):
                raise ParamError('此活动为总账户创建,你无法执行修改~')
            raise ParamError('暂无修改此活动的权限')

        # 已经进行的活动不能删除
        now = datetime.datetime.now()
        notify_datetime = get_notify_datetime(actv['create_time'])
        if not now < notify_datetime:
                raise ParamError('不能删除已经进行的红包推广活动!')

        if actv['status'] != 3:
            try:
                act = Activity(id=actv['id'], status=3,
                               src='qpos')
                thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing,
                              'activity_change', act)
            except:
                log.warn(traceback.format_exc())
                raise ThirdError('关闭活动失败')

        return self.write(success({}))
Ejemplo n.º 19
0
class Create(BaseHandler):
    '''
    创建特权活动
    '''

    _validator_fields = [
        Field('content', T_STR, is_null = False),
    ]

    @check(['login', 'check_perm'])
    @with_validator()
    @raise_excp('创建活动失败')
    def POST(self):
        userid = int(self.user.userid)
        actv = None
        with get_connection('qf_mchnt') as db:
            actv = db.select_one(
                    'member_actv',
                    where= {
                        'userid': userid,
                        'type': MemDefine.ACTV_TYPE_PRIVI
                    })
        if actv:
            raise ParamError('已经创建过特权活动了.')


        content = self.validator.data['content']
        content = remove_emoji(content)
        if str_len(content) > 80:
            raise ParamError('活动内容不超过80字')

        now = int(time.time())
        data = {}
        data['id'] = getid()
        data['title'] = ''
        data['content'] = content
        data['userid'] = userid
        data['status'] = MemDefine.ACTV_STATUS_ON
        data['ctime'] = data['utime'] =  now
        data['start_time'] = now
        data['expire_time'] = now + 20 * 365 * 24 * 3600
        data['type'] = MemDefine.ACTV_TYPE_PRIVI
        with get_connection('qf_mchnt') as db:
            db.insert('member_actv', data)

        return self.write(success({}))
Ejemplo n.º 20
0
class Display(BaseHandler):
    '''
    特权预览页
    '''

    _validator_fields = [
        Field('mode', T_STR, default='rule'),
    ]

    @check_login
    @with_validator()
    def GET(self):
        privilege = config.ACTV_TIPS.get('privilege') or {}
        mode = self.validator.data['mode']

        display = privilege.get(mode) or []

        return self.write(success(display))
Ejemplo n.º 21
0
class Change(BaseHandler):
    '''
    修改活动列表
    目前只允许关闭活动
    '''

    _validator_fields = [
        Field('id', T_INT, isnull=False),
    ]

    @check(['login', 'check_perm'])
    @with_validator()
    @raise_excp('修改活动失败')
    def POST(self):
        actv = None
        with get_connection('qf_marketing') as db:
            actv = db.select_one(table='activity',
                                 where={
                                     'id': self.validator.data['id'],
                                     'src': ACTIVITY_SRC
                                 },
                                 fields='id, create_mchnt_id, status')
        if not actv:
            raise ParamError('活动不存在')

        if actv['create_mchnt_id'] != str(self.user.userid):
            if actv['create_mchnt_id'] == str(self.get_big_uid()):
                raise ParamError('此活动为总账户创建,你无法执行修改~')
            raise ParamError('暂无修改此活动的权限')

        if actv['status'] != COUPON_RULE_STATUS_CLOSE:
            try:
                act = Activity(id=actv['id'],
                               status=COUPON_RULE_STATUS_CLOSE,
                               src=ACTIVITY_SRC)
                thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing,
                              'activity_change', act)
            except:
                log.warn(traceback.format_exc())
                raise ThirdError('关闭活动失败')

        return self.write(success({}))
Ejemplo n.º 22
0
class DebitBackList(BaseHandler):
    '''
    获取操作员退款权限列表
    '''

    _validator_fields = [
        Field('mode', T_STR, default='page'),
        Field('page', T_INT, default=0),
        Field('pagesize', T_INT, default=10),
        Field('userid', T_STR, default=None),
    ]

    _base_err = '获取操作员列表失败'

    @check(['login', 'validator'])
    def GET(self):
        ret = {}
        tmp = []
        d = self.validator.data

        mode = d['mode']
        page = d['page']
        pagesize = d['pagesize']
        userid = d.get('userid')

        if not userid:
            userid = int(self.user.userid)
        else:
            userid_tuple = hids.decode(userid)
            if userid_tuple:
                userid = userid_tuple[0]
            else:
                if not userid.isdigit():
                    raise ParamError('用户编号不存在')

        log.debug('decoded userid={}'.format(userid))

        # 操作员登录,返回空列表
        if 'opuid' in self.user.ses:
            ret['opusers'] = []
            return self.write(success(ret))

        # 判断分页显示或者全部显示,根据status筛选
        other = 'order by create_time desc limit {limit} offset {offset}'.format(
            limit=pagesize, offset=pagesize * page)
        if mode == 'all':
            other = 'order by create_time desc'

        where = {'userid': userid}

        # 获取商户下操作员
        opusers = []
        with get_connection('qf_core') as db:
            opusers = db.select(table='opuser',
                                where=where,
                                fields='opname, opuid, perms',
                                other=other)
        for opuser in opusers:
            result = {}
            source_opuid = opuser['opuid']
            prefix = (4 - len(str(source_opuid))) * '0'
            result['opuid'] = prefix + str(source_opuid)
            try:
                perms = json.loads(opuser['perms'])
                refund = perms.get('refund', 0)
            except:
                refund = 0
            result['refund'] = refund
            result['opname'] = opuser['opname']
            tmp.append(result)
        ret['opusers'] = tmp

        return self.write(success(ret))
Ejemplo n.º 23
0
class ChangeAccountHandler(BaseHandler):
    '''
    更改账户接口
    '''
    fields = [
        Field('banktype', isnull=False),
        Field('bankuser', isnull=False),
        Field('bankaccount', isnull=False),
        Field('headbankname', isnull=False),
        Field('bankname', isnull=False),
        Field('bankprovince', isnull=False),
        Field('bankcity', isnull=False)
    ]

    @check('login')
    def POST(self):
        try:
            params = self.req.inputjson()
            banktype = params.get('banktype', '')
            bankuser = params.get('bankuser', '')
            bankaccount = params.get('bankaccount', '')
            headbankname = params.get('headbankname', '')
            bankname = params.get('bankname', '')
            brchbank_code = params.get('brchbank_code', '')
            bankprovince = params.get('bankprovince', '')
            bankcity = params.get('bankcity', '')
            img_name = params.get('img_name', '')
            img_type = params.get('img_type', '')
            userid = int(self.user.userid)
            value = {
                'userid': userid,
                'banktype': banktype,
                'bankuser': bankuser,
                'bankaccount': bankaccount,
                'headbankname': headbankname,
                'brchbank_code': brchbank_code,
                'bankname': bankname,
                'bankprovince': bankprovince,
                'bankcity': bankcity,
                'applyuser': userid,
                'applytype': 5,
                'modifytime': datetime.now(),
                'create_time': datetime.now(),
                'status': UserDefine.BANK_APPLY_WAIT,
                'sync_tl_status': UserDefine.BANK_SYNC_NO
            }
            value['operatorgroup'] = json.dumps(config.OPERATE_GROUP)

            with get_connection('qf_mis') as db:
                db.insert('bankchange_apply', value)
                where = {'userid': userid}
                if img_name:
                    apy = db.select_one(
                        'bankchange_apply',
                        where=where,
                        other='order by modifytime desc') or {}
                    id = apy.get('id', 0)
                    if img_type == '1':
                        img_type = 'BANK_CARD'
                    if img_type == '2':
                        img_type = 'OPEN_LICENSE'
                    db.insert('bankchange_apply_img',
                              values={
                                  'change_apply_id': int(id),
                                  'img': img_name,
                                  'img_type': img_type,
                                  'created': datetime.now(),
                                  'updated': datetime.now()
                              })

            return self.write(success({'message': '申请提交成功,请耐心等待审核结果'}))
        except:
            log.warn('error :%s' % traceback.format_exc())
            return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误"))
Ejemplo n.º 24
0
class EffectList(BaseHandler):
    '''
     会员通知红包列表
    '''

    _validator_fields = [
        Field('page', T_INT, default=0),
        Field('pagesize', T_INT, default=10),
    ]

    def get_coupon_data_report(self, userid):
        reports = {}
        big_uid = self.get_big_uid()
        for i in (big_uid, userid):
            if not i:
                continue
            try:
                result = thrift_callex(config.PROMOTION_COUPON_REPORT_SERVERS,
                                       couprecall, "couprec", str(i))

                result = json.loads(result)
                reports.update({int(d['actv_id']): d for d in result})
            except Exception as e:
                log.warn(str(e))

        return reports

    def get_coupon_info(self, userid, actv_ids):
        if not actv_ids:
            return {}

        result = {i: {'id': i, 'used_coupon_count':0,
                       'payment_count':0, 'inactive_member_count': 0}
                  for i in actv_ids }

        data_report = self.get_coupon_data_report(userid)

        for actv_id, report in data_report.iteritems():
            if int(actv_id) not in actv_ids:
                continue

            actv = result[actv_id]
            actv['used_coupon_count'] = report['tx_cnt']
            actv['payment_count'] = report['tx_amt']
            actv['inactive_member_count'] = report['recall_cnt']

        return result

    def get_stats(self, userid, actv_ids):
        stats = None
        with get_connection('qf_marketing') as db:
            stats= db.select(
                    'record',
                    where= {
                        'activity_id': ('in', actv_ids)
                    },
                    fields= ('activity_id, sum(total_amt) payment_count',
                             'count(1) used_coupon_count'),
                    other= 'group by activity_id')
        return {i['activity_id']: i for i in stats or []}

    def get_coupon_rules(self, ruleids):
        rules = []
        with get_connection('qf_marketing') as db:
            rules = db.select('coupon_rule',
                              where={'id': ('in', ruleids)},
                              fields='id, amt_min')
        return {i['id']:i for i in rules or [] }

    def get_big_actvids(self):
        big_uid = self.get_big_uid()
        if not big_uid:
            return []

        actvids = actvs = None
        userid = self.user.userid
        with get_connection('qf_marketing') as db:
            actvs = db.select_join(
                    table1= 'activity a', table2= 'coupon_rule_mchnt crm',
                    on= {'a.obtain_xx_id': 'crm.coupon_rule_id'},
                    where= {
                        'a.create_mchnt_id': str(big_uid),
                        'a.type': 3,
                        'a.status': ('in', (1, 2)),
                        'a.mchnt_id': DBFunc('0 and locate(\'"{}"\', '
                                'crm.mchnt_id_list)'.format(userid))
                    },
                    fields= 'a.id')
            actvids = [actv['id'] for actv in actvs ]

        return actvids

    def get_effect_list(self, userid):
        result = []
        data = self.validator.data

        big_actvids = self.get_big_actvids()
        actvs = None
        with get_connection('qf_marketing') as db:
            where = '(create_mchnt_id={userid} {bigids}) '.format(
                    userid= userid,
                    bigids= ('' if not big_actvids else
                        ' or id in ({})'.format(
                            ','.join(str(int(i))for i in big_actvids))
                    ))
            where += 'and type=3 and status in (1,2)'
            sql = ('select * from activity where {where} {other}'.format(
                    where= where,
                    other=('order by id desc limit %d offset %d' %
                           (data['pagesize'], data['page']*data['pagesize']))))

            actvs = db.query(sql)

        if not actvs:
            return []

        actv_ids = [actv['id'] for actv in actvs]
        # 红包信息
        coupon_infos = self.get_coupon_info(userid, actv_ids)
        # 统计信息
        stats = self.get_stats(userid, actv_ids)
        # coupon rule
        rules = self.get_coupon_rules([i['obtain_xx_id'] for i in actvs])

        result = []
        now = datetime.datetime.now()
        for actv in actvs:
            aid = actv['id']
            if actv['obtain_xx_id'] not in rules or aid not in coupon_infos:
                continue
            info = coupon_infos[aid]
            stat = stats.get(aid) or {}
            info.update(stat)

            info['notify_time'] = get_notify_datetime(actv['create_time'])
            if now < info['notify_time']:
                info['status'] = 0
            elif now >= info['notify_time'] and now<=actv['expire_time']:
                info['status'] = 1
            else:
                info['status'] = 2

            info['coupon_count'] = (actv['used_num'] or
                                    (actv['total_amt']/rules[actv['obtain_xx_id']]['amt_min']))

            # 大商户创建的标记
            info['big_create'] = int(actv['create_mchnt_id'] != str(userid))

            result.append(info)

        return result

    @check_login
    @with_validator()
    @raise_excp('获取活动列表失败')
    def GET(self):
        userid = int(self.user.userid)

        coupon_list = self.get_effect_list(userid)
        allow_create = check_allow_create(userid)

        return self.write(success({
            'coupon_list': coupon_list,
            'allow_create': allow_create
        }))
Ejemplo n.º 25
0
class Advice(UserBase):
    '''
    好近建议
    '''

    # mode模式
    # random: 随机返回好近建议
    # normal: 正常返回好近建议
    MODE_PATTERN = r'^(normal|random)$'

    _validator_fields = [
        Field('mode', T_REG, match=MODE_PATTERN, default='random'),
        Field('index', T_INT, default=0),
    ]

    def eval_advice(self, datas_from, data):
        ret = []
        default = config.DEFAULT_ADVICE
        fields = ['title', 'color', 'desc', 'link', 'button_desc']
        for index, advice in enumerate(config.ADVICES):
            if advice.get('from') != datas_from:
                continue

            try:
                if eval(advice.get('limit', 'True'), {'data': data}):
                    result = {
                        i: advice.get(i, default.get(i, '')).format(**data)
                        for i in fields
                    }
                    result['index'] = index
                    ret.append(result)
                    self._result[index] = result
            except:
                pass

        return ret

    def _datas(self, userid):
        '''从数据组拉取数据'''
        datas = {}
        try:
            datas = json.loads(
                thrift_callex(config.DATAS_SERVERS, activiquer, 'activiq',
                              'advice', str(userid)))[0]
            log.debug('datas:%s' % datas)
            for i in ('newc_7d_rank_p', 'activec_30d_rank_p',
                      'lossc_60d_rank_p'):
                if i in datas:
                    datas[i] *= 100
        except:
            pass
            #log.debug(traceback.format_exc())

        return self.eval_advice('datas', datas)

    def _vip(self, userid):
        '''获取商户充值信息'''
        mchnt_info = adjust_payinfo_ex(userid,
                                       service_code='card_actv',
                                       groupid=self.get_groupid())
        log.debug('mchnt_info:%s' % mchnt_info)
        return self.eval_advice('vip', mchnt_info)

    def _sale(self, userid):
        '''特卖'''
        sales, today = [], time.strftime(DATE_FMT)
        where = {
            'audit_status': ('in', (SpecialDefine.AUDIT_STATUS_PLACED,
                                    SpecialDefine.AUDIT_STATUS_SUCCESS)),
            'status':
            ('in', (SpecialDefine.STATUS_PLACED, SpecialDefine.STATUS_NORMAL,
                    SpecialDefine.STATUS_TEST)),
            'redeem_start_date': ('<=', today),
            'redeem_end_date': ('>=', today),
            'atype':
            SpecialDefine.ATYPE_SALE,
            'buyable_start_date': ('<=', today),
            'buyable_end_date': ('>=', today),
            'quantity': ('>', '0'),
            'qf_uid':
            userid
        }
        fields = 'qf_uid, id, title, buyable_start_date, create_time, quantity, daily_quantity'
        with get_connection('qmm_wx') as db:
            sales = db.select('market_activity', where=where, fields=fields)

        if not sales: return None

        ret = []
        for sale in sales:
            # 购买数量
            sale['total_count'] = sale['daily_quantity'] or sale[
                'quantity']  # 总数量
            sale['quantity_p'] = sale['total_count'] * 100 / sale[
                'quantity']  # 百分比

            ret.extend(self.eval_advice('sales', sale))
        return ret

    def get_advice_seqs(self):
        advice_num = len(config.ADVICES)
        mode = self.validator.data['mode']
        seqs = get_qd_conf_value(mode='advice_sequence',
                                 key='service',
                                 groupid=self.get_groupid(),
                                 default=range(advice_num))
        advice_num = len(seqs)
        if mode == 'random':
            random.shuffle(seqs)
        elif mode == 'normal':
            index = (self.validator.data['index'] % advice_num) + 1
            seqs = seqs[index:] + seqs[:index]

        return seqs

    _base_err = '获取建议失败'

    @check(['validator', 'login'])
    def GET(self):
        # 如果是大商户或者操作员, 暂不展示
        user_cate = self.get_user_cate()
        if user_cate in ('bigmerchant', 'opuser'):
            return success({})

        self._runned_funcs = set()
        self._result = {}

        userid = int(self.user.userid)

        advice = {}
        seqs = self.get_advice_seqs()
        log.debug(seqs)
        for index in seqs:
            advice_conf = config.ADVICES[index]
            func_name = '_' + advice_conf.get('from', '')
            if func_name not in self._runned_funcs:
                func = getattr(self, func_name, None)
                if callable(func):
                    func(userid)
                self._runned_funcs.add(func_name)

            if index in self._result:
                advice = self._result[index]
                break

        return success(advice)
Ejemplo n.º 26
0
class Create(BaseHandler):
    '''
    创建活动
    成功返回活动id
    '''

    _validator_fields = [
        Field('title', isnull=False),
        Field('obtain_limit_amt', T_INT, isnull=False),
        Field('use_limit_amt', T_INT, isnull=False),
        Field('coupon_lifetime', T_INT, isnull=False),
        Field('start_time', isnull=False),
        Field('expire_time', isnull=False),
    ]

    def _trans_input(self):
        data = {k: v.strip() for k, v in self.req.input().iteritems()}
        userid = int(self.user.userid)

        # 验证商户付费状态
        if getattr(config, 'COUPON_CHECK_PAYINFO', True):
            mchnt = get_payinfo_ex(userid,
                                   service_code='coupon',
                                   groupid=self.get_groupid())
            if not mchnt:
                raise ParamError('你的会员服务尚未开通,请联系业务员开通后再进行设置。')
            elif str(mchnt['expire_time']) <= time.strftime(DATETIME_FMT):
                raise ParamError('只有续费才能创建哦')

        fields = ('amt', 'num', 'obtain_limit_amt', 'use_limit_amt',
                  'coupon_lifetime', 'amt_min', 'amt_max', 'total_amt')
        for i in fields:
            data[i] = int(data.get(i) or 0)

        # 去除表情符
        data['title'] = remove_emoji(data['title'])
        if not (1 <= str_len(data['title']) <= 12):
            raise ParamError('活动名称长度是1至12位')
        # 固定金额, 需要处理下
        if data['num']:
            data['total_amt'] = data['num'] * data['amt']
            data['amt_min'] = data['amt_max'] = data['amt']
        # 红包金额小于100
        if data['amt_max'] > 10000:
            raise ParamError('红包金额应小于100')
        # 红包最小金额小于最大金额
        if data['amt_min'] > data['amt_max']:
            raise ParamError('红包奖励最大金额应该大于最小金额')
        # 红包奖励金额
        if not data['amt_max']:
            raise ParamError('红包奖励金额应该大于0')
        # 红包预算
        if not (0 < data['total_amt'] < 1000000):
            raise ParamError('红包预算应该大于0小于10000元')
        # 使用金额和红包金额
        if data['use_limit_amt'] < data['amt_max']:
            raise ParamError('红包使用金额大于等于红包金额')
        # 有效时间
        if not all(
                map(is_valid_date, [data['start_time'], data['expire_time']])):
            raise ParamError('时间格式不对')
        # 红包有效期
        if data['coupon_lifetime'] <= 0:
            raise ParamError('优惠劵的有效时间大于0')
        # 红包截止日期
        if data['start_time'] > data['expire_time']:
            raise ParamError('活动开始时间大于截止时间')

        data['type'] = covert(data.get('type', ''), int, 20)
        data['coupon_offset'] = covert(data.get('coupon_offset', ''), int, 0)
        data['start_time'] = str_to_tstamp(data['start_time'], DATE_FMT)
        data['expire_time'] = str_to_tstamp(data['expire_time'],
                                            DATE_FMT) + (24 * 60 * 60 - 1)
        data['userid'] = str(userid)

        return data

    def _create_coupon(self, data):
        c = {}
        c['status'] = 2
        c['src'] = ACTIVITY_SRC
        c['mchnt_id'] = data['userid']
        c['title'] = data['title']
        c['amt_max'], c['amt_min'] = data['amt_max'], data['amt_min']
        c['start_time'], c['expire_time'] = data['start_time'], data[
            'expire_time']
        c['use_rule'] = json.dumps([['amt', '>=', data['use_limit_amt']]])
        c['profile'] = CouponRuleProfile(
            **{
                'mchnt_limit': 2,
                'effect_type': 2,
                'effect_offset': data['coupon_offset'],
                'effect_len': data['coupon_lifetime']
            })

        try:
            coupon = CouponRule(**c)
            cid = thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing,
                                'coupon_rule_create', coupon)
        except:
            log.warn('create coupon error: %s' % traceback.format_exc())
            raise ThirdError('调用创建红包接口失败')

        return cid

    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})

    def _create_activity(self, cid, data):
        try:
            a = {}
            a['status'] = 2
            a['src'] = ACTIVITY_SRC
            a['type'] = ACTIVITY_TYPE_PAYMENT
            a['mchnt_id'] = data['userid']
            a['total_amt'] = data['total_amt']
            a['xx_type'] = ACTIVITY_SHARE_TYPE_COUPON
            obtain_rule, share_rule = [], []
            # 消费返劵
            if data['type'] == 20:
                a['sponsor_xx_id'] = cid
                a['sponsor_award_num'] = 1
                obtain_rule = [["amt", ">=", data['obtain_limit_amt']],
                               ["num_type", "=", 1], ["obtain_num", "<=", 1]]
            # 消费分享劵
            else:
                a['obtain_xx_id'] = a['sponsor_xx_id'] = cid
                a['sponsor_award_num'] = 1
                a['obtain_num'] = config.OBTAIN_NUM
                a['ext'] = self._get_act_ext(data)
                obtain_rule = [["amt", ">=", data['obtain_limit_amt']]]
                share_rule = [
                    ["amt", ">=", data['obtain_limit_amt']],
                ]
            a['title'] = data['title']
            a['start_time'], a['expire_time'] = data['start_time'], data[
                'expire_time']
            a['rule'] = json.dumps({
                "obtain_rule": obtain_rule,
                'share': share_rule
            })
            r = thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing,
                              'activity_create', Activity(**a))
            return r
        except:
            log.warn('create activity error: %s' % traceback.format_exc())
            raise ThirdError('调用活动接口失败')

    @check_login_ex(prelogin_lock, postlogin_lock)
    @check(['check_perm'])
    @with_validator()
    @raise_excp('创建活动失败')
    def POST(self):
        # 转化input参数
        data = self._trans_input()
        # 创建优惠劵
        cid = self._create_coupon(data)
        # 创建活动
        aid = self._create_activity(cid, data)
        return self.write(success({'id': aid}))
Ejemplo n.º 27
0
class Create(CardBase):
    '''
    创建会员集点活动
    '''

    _validator_fields = [
        Field('goods_name', T_STR, isnull=False),
        Field('goods_amt', T_INT, default=0),
        Field('start_time', T_STR),
        Field('expire_time', T_STR),
        Field('exchange_pt', T_INT, default=0),
        Field('obtain_amt', T_INT, default=0),
        Field('obtain_limit', T_INT, default=1),
    ]

    _base_err = '创建集点活动失败'

    def allow_create(self, userid):
        cate = self.get_cate()
        # 大商户允许创建多个集点活动
        if cate == 'bigmerchant':
            return True

        with get_connection_exception('qf_mchnt') as db:
            num = db.select_one('card_actv',
                    where= {
                        'expire_time': ('>', int(time.time())),
                        'userid': self.get_userid_condition(),
                    },
                    fields='count(1) as num')['num']
            if num:
                raise ParamError('已经有进行中的活动')

    @check(['ip_or_login', 'check_perm', 'user_lock', 'validator'])
    def POST(self):
        userid = int(self.user.userid)

        # 商户付费状态
        groupid = self.get_groupid()
        mchnt = get_payinfo_ex(userid,
                service_code='card_actv', groupid=groupid)
        if not mchnt:
            add_free_ex(userid, service_code='card_actv', groupid=groupid)
        elif str(mchnt['expire_time']) <= time.strftime(DATETIME_FMT):
            if mchnt['status'] == MCHNT_STATUS_FREE:
                raise ParamError('免费体验已经到期了哦')
            if mchnt['status'] == MCHNT_STATUS_NORMAL:
                raise ParamError('付费已经到期了哦')

        # 能否创建集点活动
        self.allow_create(userid)

        actv = self.validator.data

        # 适用门店
        d = self.req.input()
        actv['mchnt_id_list'] = self.get_mchnt_id_list(
                d.get('mchnt_id_list', '').strip().split(','))
        actv['userid'] = userid
        actv['goods_name'] = remove_emoji(actv.get('goods_name'))
        if not 1 <= str_len(actv['goods_name']) <= 8:
            raise ParamError('商品名长度是1至8位')

        if actv['goods_amt'] <= 0:
            raise ParamError('商品价格应大于0')

        actv['start_time'] = actv.get('start_time') or time.strftime(DT_FMT)
        if not(is_valid_date(actv['start_time']) and
               is_valid_date(actv['expire_time'])):
            raise ParamError('活动时间格式不合法')
        if actv['start_time'] > actv['expire_time']:
            raise ParamError('开始时间应该小于结束时间')
        actv['start_time'] = str_to_tstamp(actv['start_time'], DT_FMT)
        actv['expire_time'] = str_to_tstamp(actv['expire_time'], DT_FMT) + 86399

        if actv['exchange_pt'] not in range(1, 11):
            raise ParamError('暂不只支持该兑换集点的活动')

        if actv['obtain_amt'] <= 0:
            raise ParamError('集点条件大于0')

        if actv['obtain_limit'] < 0:
            raise ParamError('一次交易获取的最多集点应该大于0')

        actv['id'] = getid()
        actv['ctime'] = actv['utime'] = int(time.time())
        actv['status'] = ACTV_STATUS_NORMAL

        with get_connection_exception('qf_mchnt') as db:
            db.insert('card_actv', actv)

        return self.write(success({'id': actv['id']}))
Ejemplo n.º 28
0
class Info(BaseHandler):
    '''
    获取活动详细信息
    '''

    _validator_fields = [
        Field('id', T_INT, isnull=False),
    ]

    def get_info(self, mchnt_id):
        '''获取活动信息'''
        def _actinfo():
            r = None
            actid = self.validator.data['id']
            with get_connection('qf_marketing') as db:
                big_uid = self.get_big_uid(mchnt_id)
                userids = (mchnt_id, big_uid) if big_uid else (mchnt_id, )
                r = db.select_one(
                    table='activity',
                    where={
                        'id': actid,
                        'create_mchnt_id': ('in', userids),
                        'src': ACTIVITY_SRC,
                        'type': ACTIVITY_TYPE_PAYMENT
                    },
                    fields=[
                        'id', 'mchnt_id', 'type', 'title', 'total_amt',
                        'obtain_num', 'obtain_xx_id', 'status', 'used_amt',
                        'rule', 'sponsor_award_num', 'sponsor_xx_id',
                        'start_time', 'expire_time', 'create_time',
                        'create_mchnt_id'
                    ])
            if not r:
                raise ParamError('该活动不存在')

            r['type'] = 21 if r['obtain_xx_id'] else 20
            # 活动obtain_limit_amt
            if r['type'] == 20:
                rule = rule_json2dic(r.pop('rule', ''), 'obtain_rule')
                r['obtain_limit_amt'] = rule.get('amt', 0)
            else:
                rule = rule_json2dic(r.pop('rule', ''), 'share')
                r['obtain_limit_amt'] = rule.get('amt', 0)

            # 活动状态 1:进行中 2:已结束
            r['state'] = CouponUtil.get_actv_state(r)

            # 活动统计
            stat = CouponUtil.get_actv_stats(actid)
            r.update(stat)

            # 如果是消费分享劵会加上奖励的券
            if r['type'] == 21:
                r['obtain_num'] += r['award_num']
                r['obtain_amt'] += r['award_amt']

            # 消费者信息
            r['customer_num'], r['customer_info'] = CouponUtil.get_customer(
                actid)
            r['pv'] = CouponUtil.get_actv_pv(actid)

            # 大商户创建标记
            r['big_create'] = int(r['create_mchnt_id'] != str(mchnt_id))

            return r

        def _couponinfo(couponid):
            with get_connection('qf_marketing') as db:
                fields = [
                    'id', 'title', 'amt_max', 'amt_min', 'status',
                    'start_time', 'expire_time', 'use_rule', 'profile'
                ]
                r = db.select_one('coupon_rule',
                                  where={'id': couponid},
                                  fields=fields)
            # if coupon rule not exists
            if not r:
                raise ParamError('该活动规则不存在')

            use_rule, profile = r.pop('use_rule'), r.pop('profile')
            rule = rule_json2dic(use_rule, 'rule')
            profile = json2dic(profile)
            r.update({
                'use_limit_amt': rule.get('amt', 0),
                'mchnt_limit': profile.get('mchnt_limit', 1),
                'effect_offset': profile.get('effect_offset', 1),
                'effect_type': profile.get('effect_type', 1),
                'effect_len': profile.get('effect_len', 7)
            })
            return r

        try:
            r = _actinfo()
            k = 'sponsor_coupon_info' if r[
                'type'] == 20 else 'obtain_coupon_info'
            r[k] = _couponinfo(r['sponsor_xx_id'] or r['obtain_xx_id'])
            r['num'] = r['total_amt'] / max(r[k]['amt_min'], r[k]['amt_max'],
                                            1)
            return r
        except MchntException:
            raise
        except:
            log.warn('query activity ifno error: %s' % traceback.format_exc())
            raise DBError('查询活动详细信息失败')

    @check_login
    @with_validator()
    @raise_excp('查询活动信息失败')
    def GET(self):
        userid = int(self.user.userid)

        # 获取活动信息
        r = self.get_info(userid)
        r['now'] = time.strftime(DATETIME_FMT)
        r['promotion_url'] = get_qd_conf_value(userid,
                                               'coupon',
                                               groupid=self.get_groupid())

        return self.write(success(r))
Ejemplo n.º 29
0
class List(BaseHandler):
    '''
    获取活动列表
    '''

    STATE_PATTERN = r'(1|2)'

    _validator_fields = [
        Field('state', T_REG, match=STATE_PATTERN, isnull=False),
        Field('page', T_INT, default=0),
        Field('pagesize', T_INT, default=10),
    ]

    def get_big_actvids(self):
        big_uid = self.get_big_uid()
        if not big_uid:
            return []

        actvids = actvs = None
        userid = self.user.userid
        with get_connection('qf_marketing') as db:
            actvs = db.select_join(table1='activity a',
                                   table2='activity_mchnt am',
                                   on={'a.id': 'am.activity_id'},
                                   where={
                                       'a.create_mchnt_id':
                                       str(big_uid),
                                       'a.type':
                                       ACTIVITY_TYPE_PAYMENT,
                                       'a.status': ('in', (1, 2)),
                                       'a.mchnt_id':
                                       DBFunc(
                                           '0 and locate(\'"{}"\', '
                                           'am.mchnt_id_list)'.format(userid))
                                   },
                                   fields='a.id')
            actvids = [actv['id'] for actv in actvs]

        self._bigids = actvids or []
        return actvids

    def get_actvs(self, userid):
        '''
        获取活动列表
        '''
        def get_where():
            now = int(time.time())

            big_actvids = self.get_big_actvids()
            where = '(create_mchnt_id={userid} {bigids}) '.format(
                userid=userid,
                bigids=('' if not big_actvids else ' or id in ({})'.format(
                    ','.join(str(int(i)) for i in big_actvids))))
            where += ('and src="{src}" and type={type} '.format(
                src=ACTIVITY_SRC, type=ACTIVITY_TYPE_PAYMENT))
            # 启用的
            if self.validator.data['state'] == '1':
                where += ('and expire_time>={now} and status=2 and '
                          'used_amt<total_amt'.format(now=now))
            # 关闭的
            else:
                where += ('and ((expire_time<{now}) or (used_amt>=total_amt) '
                          'or (status=3))'.format(now=now))
            return where

        data = self.validator.data
        actvs = None
        with get_connection('qf_marketing') as db:
            sql = ('select {fields} from activity where {where} '
                   'order by create_time desc limit {limit} '
                   'offset {offset}'.format(
                       fields=('id, mchnt_id, type, title, total_amt, '
                               'obtain_xx_id, obtain_num, sponsor_award_num, '
                               'sponsor_xx_id, rule, start_time, expire_time, '
                               'create_time, create_mchnt_id'),
                       where=get_where(),
                       limit=data['pagesize'],
                       offset=data['pagesize'] * data['page']))
            actvs = db.query(sql)
        if not actvs:
            return []

        cids = {i['sponsor_xx_id'] or i['obtain_xx_id'] for i in actvs}
        coupons = {}
        if cids:
            if cids:
                cps = None
                with get_connection('qf_marketing') as db:
                    cps = db.select(table='coupon_rule',
                                    fields='id, amt_max, amt_min',
                                    where={'id': ('in', cids)})
                for cp in cps:
                    coupons[cp['id']] = {
                        'coupon_amt_max': cp['amt_max'],
                        'coupon_amt_min': cp['amt_min']
                    }

        # 获取统计信息
        actids = [i['id'] for i in actvs]
        stats = CouponUtil.get_actv_stats(actids)

        # 整理数据
        promotion_url = get_qd_conf_value(userid,
                                          'coupon',
                                          groupid=self.get_groupid())
        for act in actvs:
            # 加入优惠劵信息
            act.update(coupons.get(act['sponsor_xx_id']
                                   or act['obtain_xx_id']))
            # 活动rule
            act['num'] = act['total_amt'] / max(act['coupon_amt_min'],
                                                act['coupon_amt_max'], 1)

            # 活动统计
            act.update(stats.get(act['id']))
            # 活动类型
            act['type'] = 21 if act['obtain_xx_id'] else 20
            # 物料信息
            act['promotion_url'] = promotion_url

            # 活动obtain_limit_amt
            if act['type'] == 20:
                rule = rule_json2dic(act.pop('rule', ''), 'obtain_rule')
                act['obtain_limit_amt'] = rule.get('amt', 0)
            else:
                rule = rule_json2dic(act.pop('rule', ''), 'share')
                act['obtain_limit_amt'] = rule.get('amt', 0)
                act['obtain_num'] += act['award_num']
                act['obtain_amt'] += act['award_amt']

            # 大商户创建的标记
            act['big_create'] = int(act['create_mchnt_id'] != str(userid))

        return actvs

    def get_actv_num(self, userid):
        '''
        获取活动数量
        '''
        share_num = sponsor_num = 0
        with get_connection('qf_marketing') as db:
            nums = db.select('activity',
                             where={
                                 'create_mchnt_id': userid,
                                 'src': ACTIVITY_SRC,
                                 'type': ACTIVITY_TYPE_PAYMENT
                             },
                             fields='obtain_xx_id , count(1) as num',
                             other='group by (obtain_xx_id > 0)')
            for num in nums:
                if num['obtain_xx_id'] > 0:
                    share_num = num['num']
                else:
                    sponsor_num = num['num']
        return share_num, sponsor_num

    @check_login
    @with_validator()
    @raise_excp('获取数据失败')
    def GET(self):
        userid = int(self.user.userid)

        # 获取活动列表
        actvs = self.get_actvs(userid)

        # 获取当前正在进行的活动
        share_num, sponsor_num = self.get_actv_num(userid)

        return self.write(
            success({
                'left_warn_day': 7,
                'activities': actvs,
                'now': time.strftime(DATETIME_FMT),
                'act_num': share_num + sponsor_num,
                'share_act_num': share_num,
                'sponsor_act_num': sponsor_num
            }))
Ejemplo n.º 30
0
class List(BaseHandler):
    '''
    获取操作员列表
    '''

    _validator_fields = [
        Field('mode', T_STR, default='page'),
        Field('page', T_INT, default=0),
        Field('pagesize', T_INT, default=10),
        Field('status', T_STR),
        Field('userid', T_STR, default=None),
    ]

    _base_err = '获取操作员列表失败'

    def get_mchnt_info(self, userid):
        mchnt_info = {}
        with get_connection('qf_core') as db:
            mchnt_info = db.select_one(table='auth_user',
                                       fields=['state as status', 'mobile'],
                                       where={'id': userid})

        if not mchnt_info:
            raise ParamError('主账号信息不存在')

        opname = get_constant('门店主账户', self.get_language())
        mchnt_info['opuid'] = '0000'
        mchnt_info['opname'] = opname

        return mchnt_info

    @check(['login', 'validator'])
    def GET(self):
        ret = {}
        tmp = []
        d = self.validator.data

        mode = d['mode']
        page = d['page']
        pagesize = d['pagesize']
        userid = d.get('userid')

        if not userid:
            userid = int(self.user.userid)
        else:
            try:
                userid = int(userid)
            except:
                raise ParamError('userid参数错误')

        log.debug('userid={}'.format(userid))

        # 判断分页显示或者全部显示,根据status筛选
        other = 'order by create_time desc limit {limit} offset {offset}'.format(
            limit=pagesize, offset=pagesize * page)
        if mode == 'all':
            other = 'order by create_time desc'
            tmp.append(self.get_mchnt_info(userid))

        where = {'userid': userid}
        if d['status'] != '':
            where['status'] = int(d['status'])

        # 获取商户下操作员
        opusers = []
        with get_connection('qf_core') as db:
            opusers = db.select(table='opuser',
                                where=where,
                                fields='opname, mobile, status, opuid, perms',
                                other=other)

        for opuser in opusers:
            source_opuid = opuser['opuid']
            prefix = (4 - len(str(source_opuid))) * '0'
            opuser['opuid'] = prefix + str(source_opuid)
            try:
                perms = json.loads(opuser['perms'])
                refund = perms.get('refund', 0)
            except:
                refund = 0
            opuser['refund'] = refund
            tmp.append(opuser)
        ret['opusers'] = tmp

        return self.write(success(ret))