Пример #1
0
def ConvertUrl():
    """
    将大图转换为qmm.la下的短链
    """
    with dbpool.get_connection_exception('qf_mchnt') as db:
        mchnt_fields = ['id', 'pic_url_bigger']
        activity_datas = db.select('mchnt_activityrecord', fields=mchnt_fields)

    update_list = []
    for d in activity_datas:
        url = d.get('pic_url_bigger')
        act_id = d.get('id')
        if 'qmm.la' in url:
            continue
        else:
            #short_url = shorten_url(url, host="qmm.la")
            short_url = shorten_url(url)
            if "qmm.la" in short_url:
                update_list.append({'url': short_url, 'id': act_id})

    if update_list:  # 更新数据
        log.warn("starting update url..., datas={}".format(update_list))
        with dbpool.get_connection_exception('qf_mchnt') as db2:
            for data in update_list:
                update_v = {"pic_url_bigger": data.get('url')}
                where = {"id": data.get('id')}
                db2.update('mchnt_activityrecord', update_v, where)
    else:
        log.info("no url need update")
Пример #2
0
def GenPic():
    with dbpool.get_connection_exception('qf_mchnt') as db:
        where = {"status": "1", "pic_url_bigger": ""}
        datas = db.select('mchnt_activityrecord', where=where)

    if not datas:
        log.info('no datas need gen pic')
        return

    activity_info = {}
    log.info("need gen pics data is = {}".format(datas))

    for d in datas:
        shop_name = d.get('shop_name', '')
        activity_id = d.get('activityid')

        if not shop_name:
            log.info('NOTGENPIC: data={0}'.format(d))
            continue

        try:
            pic_url = real_genpic_upload(activity_id, shop_name)
        except:
            log.info("GENPIC ERROR:{}".format(traceback.format_exc()))
            pic_url = ''
        if pic_url:
            update_value = {"pic_url_bigger": pic_url}
            update_where = {
                "mchntid": d.get('mchntid'),
                'activityid': d.get('activityid')
            }
            with dbpool.get_connection_exception('qf_mchnt') as db:
                db.update('mchnt_activityrecord',
                          update_value,
                          where=update_where)
Пример #3
0
def get_mchnt_mccstr(mcc=None, lang=None, langconf=None):
    """根据mcc获取对应的中文mcc"""
    mcc_str = ''
    if not mcc:
        return mcc_str
    if not is_valid_int(mcc):
        return mcc_str
    mcc = int(mcc)
    with get_connection_exception('qf_mis') as db:
        ret = db.select_one('tools_mcc', where={'id': mcc, 'mcc_display': 1})
    if not ret:
        with get_connection_exception('qf_mis') as db:
            ret = db.select_one('tools_mcca',
                                where={
                                    'id': mcc,
                                    'mcca_display': 1
                                })
        if ret:
            mcc_str = ret['mcca_name']
    else:
        mcc_str = ret['mcc_name']
    if lang == 'en':
        for i in PRIMARY_MCC:
            if mcc_str == i['name']:
                mcc = i['id']
        for i in getattr(langconf, 'PRIMARY_MCC'):
            if mcc == i['id']:
                mcc_str = i['name']

    return mcc_str
Пример #4
0
    def build_args(self):
        d = self.req.input()
        self.valid_args()

        values = {}
        for i in self.valid_list:
            arg_name = i[0]
            arg_value = d[arg_name]
            if arg_name in self.valid_int_list:
                if not is_valid_int(arg_value):
                    raise ParamError('{}参数有误'.format(i[1]))
                arg_value = int(arg_value)
            if arg_name == 'status':
                if arg_value not in TagDef.TAG_STATUS:
                    raise ParamError('状态值不合法')
            if arg_name == 'cate_code':
                pass
            if arg_name == 'cate_name':
                with get_connection_exception('qf_user') as db:
                    where = {'cate_name': arg_value}
                    ret = db.select('user_category',where=where)
                    if ret:
                        raise ParamError('该标签已存在,请重新输入')
            if arg_name == 'cate_codes':
                arg_value = [i.strip() for i in arg_value.split(',')]
            if arg_name == 'userids':
                userids = arg_value.split(',')
                for userid in userids:
                    if not is_valid_int(userid):
                        raise ParamError('输入商户ID请使用英文分隔符')
                arg_value = [int(i) for i in userids]
                if not arg_value:
                    raise ParamError('未输入有效商户ID')
            values[arg_name] = arg_value
        for i in self.manual_list:
            arg_name = i[0]
            arg_value = d.get(arg_name)
            if not arg_value: continue
            if arg_name in self.valid_int_list:
                if not is_valid_int(arg_value):
                    raise ParamError('{}参数有误'.format(i[1]))
                arg_value = int(arg_value)
            if arg_name == 'remark':
                if get_str_len(arg_value) > getattr(config, 'REMARK_LEN', 100):
                    raise ParamError('标签解释长度不可超过100个字符')
            # code 放在valid_list中,已经存在
            if arg_name == 'cate_name':
                where = {'cate_name': arg_value}
                if values.get('cate_code'):
                    where['cate_code'] = ('!=', values.get('cate_code'))
                with get_connection_exception('qf_user') as db:
                    ret = db.select_one('user_category',
                            fields = 'count(*) as total',
                            where = where)
                    if ret and ret.get('total') != 0:
                        raise ParamError('名称重复')
            values[arg_name] = arg_value
        log.debug(values)
        return values
Пример #5
0
    def GET(self):
        userid = self.user.userid

        uinfo = get_userinfo(userid)
        mobile = uinfo.get("mobile", '')

        imgurl_res = get_imgurl_res(userid)

        all_imgnames = ("licensephoto", "authcertphoto", "idcardfront",
                        "idcardback", 'authbankcardfront')
        res = {"mobile": mobile, "userid": userid}
        for i in imgurl_res:
            res.update(
                {i["name"]: {
                     "imgurl": i["imgurl"],
                     "state": IMG_NOT_UPLOAD
                 }})

        with get_connection_exception("qf_mis") as conn:
            rows = conn.select("mis_upgrade_voucher",
                               where={
                                   "user_id": userid,
                                   "name": ("in", all_imgnames)
                               },
                               fields="name, state")

        if rows:
            for i in rows:
                res[i["name"]].update({"state": i["state"]})

        with get_connection_exception("qf_core") as conn:
            row = conn.select_one("extra_mchinfo",
                                  where={"userid": userid},
                                  fields="is_supplied, wechat_no")

            if row:

                # 暂时让这个值都等于 没有补过
                # res['all_supplied'] = ALREADY_SUPPLIED if row['is_supplied'] else NO_SUPPLIED
                res['all_supplied'] = NO_SUPPLIED
                res['wechat_no'] = row['wechat_no']
            else:
                res['all_supplied'] = NO_SUPPLIED
                res['wechat_no'] = ''

        with get_connection_exception("qf_mis") as conn:
            row = conn.select_one("apply",
                                  fields="licensenumber, name, usertype",
                                  where={"user": userid})
            res["licensenumber"] = row[
                "licensenumber"] if row and row["licensenumber"] else ""
            res["name"] = row['name'] if row else ""
            res["user_type"] = row["usertype"] if row else 0

        return self.write(success(data=res))
Пример #6
0
def update_order(p):
    '''更新订单信息'''
    # 查询订单
    with get_connection_exception('qf_mchnt') as db:
        order = db.select_one('paying_order',
                              where={'id': int(p.get('out_trade_no') or 0)})
        if not order:
            raise ParamError('订单不存在')

    # 订单状态
    # 支付成功
    if p['cancel'] == '0' and p['respcd'] == '0000':
        status = ORDER_STATUS['done']
    # 未支付
    elif p['cancel'] == '0' and p['respcd'] in ('1143', '1145'):
        status = ORDER_STATUS['undo']
    # 支付失败
    else:
        status = ORDER_STATUS['fail']

    # 更新订单
    with get_connection_exception('qf_mchnt') as db:
        where = {
            'id': int(p.get('out_trade_no') or 0),
            'status': ('in', (ORDER_STATUS['undo'], ORDER_STATUS['fail']))
        }
        where['status'] = ORDER_STATUS['undo']
        data = {
            'utime': int(time.time()),
            'out_sn': p['syssn'],
            'status': status
        }
        updated = db.update('paying_order', data, where)

    # 若更新payding_order且订单状态为已支付,
    # 则更新商户付费有效期
    if updated and status == ORDER_STATUS['done']:
        if order['goods_code'] == 'message':
            log.info('begin send message')
            send_message(order)
        else:
            update_mchnt(order)

    return {
        'syssn': p['syssn'],
        'txamt': p['txamt'],
        'status': status,
        'txdtm': order['ctime']
    }
Пример #7
0
 def _create(self, p):
     field = [
         'userid', 'title', 'content', 'start_time', 'expire_time', 'bg_url'
     ]
     d = {i: p[i] for i in field}
     d['ctime'] = d['utime'] = int(time.time())
     d['status'] = 1  # 启用
     d['id'] = create_id()
     d['type'] = MemDefine.ACTV_TYPE_PROMO
     try:
         with get_connection_exception('qf_mchnt') as db:
             db.insert('member_actv', d)
     except:
         log.warn('insert member actv error:%s' % traceback.format_exc())
         raise DBError('创建活动失败')
     else:
         with get_connection('qf_mchnt') as db:
             db.update('member_actv',
                       values={'status': MemDefine.ACTV_STATUS_OFF},
                       where={
                           'status': MemDefine.ACTV_STATUS_ON,
                           'expire_time': ('>=', int(time.time())),
                           'id': ('!=', d['id']),
                           'userid': d['userid'],
                           'type': MemDefine.ACTV_TYPE_PROMO,
                       })
     return d['id']
Пример #8
0
 def tag_user(self):
     self.valid_list = [
         ('cate_codes', '标签'), ('userids' ,'商户ID'), ('status', '状态')
     ]
     values = self.build_args()
     with get_connection_exception('qf_user') as db:
         cate_map_list = db.select(
             fields = ['cate_code', 'cate_name', 'remark'],
             table = 'user_category',
             where = {'userid': TagDef.VIRTUAL_USER_ID}
         )
         cate_map = {i['cate_code']: (i['cate_name'], i['remark'])
                 for i in cate_map_list}
     categories = []
     for userid in values['userids']:
         for cate_code in values['cate_codes']:
             tmp = UserCate(
                 code = cate_code,
                 name = unicode_to_utf8(cate_map.get(cate_code, ('', ''))[0]),
                 status = values['status'],
                 ctime = datetime.datetime.now().strftime(DATETIME_FMT),
                 remark = unicode_to_utf8(cate_map.get(cate_code, ('', ''))[1]),
             )
             categories.append(tmp)
     ret = thrift_callex(config.APOLLO_SERVERS, ApolloServer, 'setUsersCategory',
             list(values['userids']), categories)
     if ret != 0:
         raise ParamError('内部错误')
     return self.write(success({}))
Пример #9
0
    def card_actv(self):
        '''
        获取大商户和自己创建的集点活动
        '''
        def _get_where():
            now = int(time.time())
            r = {
                'userid': self.get_userid_condition(),
                'status': ACTV_STATUS_NORMAL
            }
            r["expire_time"] = (">", now)
            r['start_time'] = ('<=', now)

            return r

        where = _get_where()
        with get_connection_exception('qf_mchnt') as db:
            actvs = db.select_one(
                table='card_actv',
                fields=('id, start_time, expire_time, exchange_num, '
                        'total_pt, status, goods_amt, goods_name, '
                        'obtain_amt, obtain_limit, exchange_pt'),
                where=where,
                other='order by ctime desc')

        return actvs
Пример #10
0
def get_qd_of_org(org_uid):
    ret = []

    if not org_uid:
        return ret

    with get_connection_exception('qf_org') as db:
        one = []
        one = db.select(
            table='qd_user',
            fields='qd_uid',
            where={
                'level': 2,
                'parent': org_uid,
                'status': 0
            },
        )
        one_uids = [i['qd_uid'] for i in one]
        if not one_uids:
            return ret

        two = []
        two = db.select(
            table='qd_user',
            fields='qd_uid',
            where={
                'level': 3,
                'parent': ('in', one_uids),
                'status': 0
            },
        )
        two_uids = [i['qd_uid'] for i in two]
        one_uids.extend(two_uids)
        ret = one_uids
    return ret
Пример #11
0
    def GET(self):
        userid = self.req.input().get('userid')
        if not is_valid_int(userid):
            raise ParamError('userid为空')

        customer_id = self.req.input().get('customer_id')
        if not is_valid_int(customer_id):
            raise ParamError('商户id为空')

        cardno = None
        with get_connection_exception('qf_mchnt') as db:
            member = db.select_one(
                'member',
                where= {
                    'userid': userid,
                    'customer_id': customer_id
                }
            )

        if member:
            cardno = member['id']

        else:
            self.be_member(userid, customer_id, MemDefine.MEMBER_SRC_CARD)
            cardno = getattr(self, '_cardno', '')

        return self.write(success({'cardno': cardno}))
Пример #12
0
    def _create_order(self, d):
        # 订单信息
        fields = ('userid', 'goods_code', 'txamt', 'total_amt', 'price_code',
                  'promo_code', 'goods_name')
        order = {i: d[i] for i in fields}
        order['id'] = getid()
        order['out_sn'] = 0
        order['ext'] = order['promo_code'][:2]
        order['promo_code'] = order['promo_code'][2:]
        order['status'] = ORDER_STATUS['undo']
        order['ctime'] = order['utime'] = int(time.time())
        # 插入paying_order
        with get_connection_exception('qf_mchnt') as db:
            db.insert('paying_order', order)

        # 返回值
        r = {}
        r['goods_name'] = d['goods_name']
        r['txamt'] = d['txamt']
        r['txcurrcd'] = 'CNY'
        r['txdtm'] = time.strftime(DATETIME_FMT)
        r['out_trade_no'] = order['id']
        r['udid'] = 'mchnt_api'
        r['appcode'] = config.QT2_APP_CODE
        r['sign'] = RechargeUtil.make_sign(r)
        return r
Пример #13
0
    def _query(self, d):
        def _query_qt2():
            '''从qt2查询订单信息'''
            p = {'syssn': d['out_sn']}
            headers = {
                'X-QF-APPCODE': config.QT2_APP_CODE,
                'X-QF-SIGN': RechargeUtil.make_sign(p)
            }
            try:
                client = HttpClient(config.QT2_SERVER)
                r = json.loads(
                    client.get('/trade/v1/query', params=p, headers=headers))
                if r['respcd'] == '0000' and r['data']:
                    return r['data'][0]
            except:
                log.warn('qt2 query error:%s' % traceback.format_exc())
            raise ThirdError('获取订单信息失败')

        with get_connection_exception('qf_mchnt') as db:
            pwhere = {'out_sn': d['out_sn'], 'status': ORDER_STATUS['done']}
            info = db.select_one('paying_order', where=pwhere)
            if info:
                return {
                    'syssn': info['out_sn'],
                    'txamt': info['txamt'],
                    'status': info['status'],
                    'txdtm': info['ctime']
                }

        return update_order(_query_qt2())
Пример #14
0
    def check_allow_query(self, aid):
        '''验证能否查看集点活动

        能查看的情况
        1. 自己创建的活动
        2. 自己参与的活动
        3. 自己子商户的活动

        '''
        userid = self.user.userid

        # 子商户可以查看大商户活动
        with get_connection_exception('qf_mchnt') as db:
            actv = db.select_one('card_actv', where={'id': aid})
            if not actv:
                raise ParamError('活动不存在')

        if actv['userid'] != int(userid):
            # 参与活动能查看
            try:
                mchnt_id_list = json.loads(actv['mchnt_id_list'])
            except:
                mchnt_id_list = []
            if str(userid) in mchnt_id_list:
                return actv

            # 活动创建商户的大商户能查看
            re_relates = apcli_ex('getUserReverseRelation', actv['userid'],
                                  'merchant') or []
            userids = [i.userid for i in re_relates]
            if int(userid) not in userids:
                raise ParamError('活动不存在')

        return actv
Пример #15
0
    def check_allow_change(self, aid):
        '''验证能否修改集点活动

        Params:
            aid: 集点活动id
        Returns:
            返回活动信息
        '''
        userid = self.user.userid
        cate = self.get_cate()

        actv = None
        with get_connection_exception('qf_mchnt') as db:
            actv = db.select_one('card_actv', where={'id': aid})
        if not actv:
            raise ParamError('活动不存在')

        if actv['userid'] != int(userid):
            # 判断登录角色
            cate = self.get_cate()
            if cate in ('merchant', 'submerchant'):
                raise ParamError('子商户不能修改大商户创建的活动')

            # 活动的大商户是否是登录商户
            re_relates = apcli_ex('getUserReverseRelation', actv['userid'],
                                  'merchant') or []
            userids = [i.userid for i in re_relates]
            if int(userid) not in userids:
                raise ParamError('活动不存在')

        now = datetime.datetime.now()
        if actv['expire_time'] < now:
            raise ParamError('活动已停止')

        return actv
Пример #16
0
def GeneratePicLocation(name="big"):
    if name == "big":
        config_data = {
            "offset_x": 1188,
            "offset_y": 985,
            "max_text_width": 3130,
            "image_name": "big_shujia.jpg",
            "font_name": "SimHei.ttf",
            "font_size": 155,
            "fill_color": '#faf7e6'
        }
        values = {"bigimg_location": json.dumps(config_data)}
    else:
        config_data = {
            "offset_x": 169,
            "offset_y": 138,
            "max_text_width": 437,
            "image_name": "small_shujia.jpg",
            "font_name": "SimHei.ttf",
            "font_size": 26,
            "fill_color": '#faf7e6'
        }
        values = {"smallimg_location": json.dumps(config_data)}

    with dbpool.get_connection_exception('qf_mchnt') as db:
        db.update('mchnt_activity', values, where={"activityid": 3})
Пример #17
0
    def _trans_input(self):
        d = {k: v.strip() for k, v in self.req.input().iteritems()}
        r = {}
        r['id'] = d.get('id') or ''

        # actv info
        with get_connection_exception('qf_mchnt') as db:
            info = db.select_one('card_actv', where={'id': r['id']})
        if not info:
            raise ParamError('活动不存在')
        info['start_time'] = int(time.mktime(info['start_time'].timetuple()))
        expire_time = d.get('expire_time', info['expire_time'])
        if not is_valid_date(expire_time):
            raise ParamError('活动截止时间格式不对')
        r['expire_time'] = str_to_tstamp(expire_time, DATE_FMT) + 86399
        #if r['expire_time'] < info['start_time']:
        #raise ParamError('修改活动的截止日期不能小于起始日期')

        r['obtain_amt'] = int(d.get('obtain_amt', info['obtain_amt']) or 0)
        if r['obtain_amt'] <= 0:
            raise ParamError('集点条件大于0元')

        r['goods_name'] = remove_emoji(d.get('goods_name', info['goods_name']))
        if not 1 <= str_len(r['goods_name']) <= 8:
            raise ParamError('商品名长度是1至8位')

        r['goods_amt'] = int(d.get('goods_amt', info['goods_amt']) or 0)
        if r['goods_amt'] <= 0:
            raise ParamError('商品价格应大于0')

        r['content'] = (info['content']
                        or '') + (d.get('content') or '%smis修改' %
                                  (time.strftime(DATETIME_FMT)))

        return r
Пример #18
0
    def get_customer(actid, **cf):
        '''获取消费者信息'''
        customer_num, info = 0, []
        try:
            # 查询消费者
            where  = {'activity_id':actid, 'status':COUPON_STATUS_USE}
            limit, offset =  cf.get('limit', 5) , cf.get('offset', 0)
            with get_connection_exception('qf_marketing') as db:
                cps = db.select('coupon_bind', fields = 'distinct customer_id', where= where,
                    other = 'order by create_time desc limit %s, %s' % (offset, limit))
            cids, info = [i['customer_id'] for i in cps], []

            # 查询总共有多少消费者
            customer_num = db.select_one('coupon_bind', where = where, fields = 'count(distinct customer_id) as num')['num']

            # 查询消费者信息
            if cids:
                spec = json.dumps({"user_id":cids})
                r = thrift_callex(config.OPENUSER_SERVER, OpenUser, 'get_profiles', config.OPENUSER_APPID, spec)
                r = {str(i.user_id):i for i in r}
                # 处理返回值
                for i in cids:
                    if i in r:
                        info.append({'id':i, 'avatar':r[i].avatar or config.HJ_AVATAR, 'nickname':r[i].nickname})
                    else:
                        info.append({'id':i, 'avatar':config.HJ_AVATAR, 'nickname':i})
        except:
            log.warn('get openuser_info error:%s' % traceback.format_exc())
            if cf.get('raise_ex', ''):
                raise ThirdError('获取消费者信息失败')

        return customer_num, info
Пример #19
0
    def exchange(self, actv, member, code_info):
        now = int(time.time())
        with get_connection_exception('qf_mchnt') as db:
            # 更新会员集点
            db.update('member_pt',
                      values={
                          'cur_pt': DBFunc('cur_pt-%d' % actv['exchange_pt']),
                          'exchange_num': DBFunc('exchange_num+1'),
                          'last_exdtm': now,
                          'utime': now
                      },
                      where={'id': member['id']})

            # 更新exchange_record
            db.update('exchange_record',
                      values={
                          'status': CODE_STATUS_EXCHANGED,
                          'utime': now,
                          'userid': self.user.userid
                      },
                      where={'id': code_info['id']})

            # 更新card_actv表
            db.update('card_actv',
                      values={
                          'exchange_num': DBFunc('exchange_num+1'),
                          'utime': now
                      },
                      where={'id': actv['id']})
Пример #20
0
    def be_member(self, userid, customer_id, src=MemDefine.MEMBER_SRC_WX):
        ''' 成为会员

        如果是新会员将返回1, 否则返回0

        '''
        now = int(time.time())
        try:
            with get_connection_exception('qf_mchnt') as db:
                cardno = getid()
                db.insert('member',
                          values={
                              'id': cardno,
                              'userid': userid,
                              'customer_id': customer_id,
                              'num': 0,
                              'txamt': 0,
                              'last_txdtm': 0,
                              'ctime': now,
                              'utime': now
                          })
                self._cardno = cardno

                db.insert('member_tag',
                          values={
                              'id': getid(),
                              'userid': userid,
                              'customer_id': customer_id,
                              'src': src,
                              'ctime': now,
                              'utime': now
                          })
        except:
            return 0
        return 1
Пример #21
0
    def get_coupon_use_info(self, userid):
        _result = dict(max_count=config.NOTIFY_MAX_COUNT_MONTH,
                       used_count=0,
                       used_coupon=False)
        with get_connection_exception('qf_marketing') as conn:
            # 检测是否已经创建过
            where = dict(
                mchnt_id=userid,
                type=3,
            )
            result = conn.select_one('activity', where=where)
            if result is not None:
                _result['used_coupon'] = True

            # 检测已经使用次数
            timeline = datetime.date.today()
            timeline = timeline.replace(day=1)
            where = dict(mchnt_id=userid,
                         type=3,
                         status=('in', [1, 2]),
                         start_time=('>=',
                                     util.convert_date_to_timestamp(timeline)))
            result = conn.select_one('activity',
                                     where=where,
                                     fields="count(1) as used_count")
            if result is not None:
                _result['used_count'] = result['used_count']

        return _result
Пример #22
0
def add_free(userid, goods_code=None, service_code='card_actv'):
    '''
    给userid开通免费体验
    '''
    goods = get_goods(goods_code, service_code)
    if not goods.get('free'):
        raise ParamError('该服务暂不支持免费体验')
    free = goods['free']

    try:
        now = int(time.time())
        expire_time = str_timestamp(time.strftime(DATE_FMT),
                                    DATE_FMT) + (free + 1) * 24 * 3600 - 1
        recharge_id = getid()
        with get_connection_exception('qf_mchnt') as db:
            db.insert(
                'recharge', {
                    'id': recharge_id,
                    'userid': userid,
                    'ctime': now,
                    'utime': now,
                    'goods_code': goods['code'],
                    'status': 1,
                    'expire_time': expire_time
                })
        return recharge_id
    except:
        log.warn('create activity error: %s' % traceback.format_exc())
        raise DBError('开通免费体验失败')
Пример #23
0
    def get_summary(cls, user_id):
        retval = dict(member_count=0,
                      inactive_member_count=0,
                      active_member_count=0,
                      period="30天")

        current_timestamp = time.time()
        basetime = current_timestamp - (30 * 24 * 3600)

        with get_connection_exception('qf_mchnt') as conn:
            result = conn.select_one('member',
                                     where=dict(userid=user_id),
                                     fields='count(1) as member_count')
            if result['member_count']:
                retval['member_count'] = result['member_count']
                pass

            args = dict(userid=user_id, last_txdtm=(">", basetime))
            result = conn.select_one('member',
                                     where=args,
                                     fields='count(1) as active_member_count')

            if result['active_member_count']:
                retval['active_member_count'] = result['active_member_count']
                pass

            retval['inactive_member_count'] = max(
                0, retval['member_count'] - retval['active_member_count'])
            pass

        return retval
Пример #24
0
    def POST(self):
        params = self.req.input()
        userid = int(self.user.userid)

        new_username = params.get('new_username', '').strip()
        if not new_username:
            raise ParamError('新账号不能为空')

        # 验证grant_code
        grant_code = params.get('grant_code') or ''
        self.check_grant_code(userid, grant_code)

        # 验证verify_code
        verify_code = params.get('verify_code') or ''
        if not check_smscode(verify_code, new_username, mode=1):
            raise ParamError('验证信息错误')

        # 验证新账号是否被占用
        with get_connection_exception('qf_core') as db:
            new_user = db.select_one('auth_user',
                                     where={'username': new_username})
        if new_user:
            raise ParamError('新账号已经被占用')

        # apollo接口修改username
        try:
            apcli_ex('changeUsername', userid, new_username)
        except ApolloException as e:
            raise ThirdError(e.respmsg)

        # 将现有设备踢下线
        kick_user(userid, mode='all')

        return success({})
Пример #25
0
    def card_list(self, d):
        with get_connection_exception('qf_mchnt') as db:
            where = {
                'mp.customer_id': d['customer_id'],
                'ca.expire_time': ('>', int(time.time()))
            }
            if d.get('groupid') and not userid_cache[d['groupid']]:
                return [], 0

            if d['mchnt_id']:
                link_ids = apcli.userids_by_linkid(int(d['mchnt_id']),
                                                   'merchant') or []
                link_ids = {i.userid for i in link_ids}
                link_ids.add(d['mchnt_id'])
                where['ca.userid'] = ('in', link_ids)

            elif d.get('groupid') and userid_cache[d['groupid']]:
                where['ca.userid'] = ('in', userid_cache[d['groupid']])

            on = {'mp.activity_id': 'ca.id'}
            fields = ['mp.' + i for i in ('cur_pt', 'id', 'activity_id')]
            fields += [
                'ca.' + i for i in ('obtain_amt', 'obtain_limit', 'start_time',
                                    'expire_time', 'exchange_pt', 'goods_amt',
                                    'goods_name', 'status', 'userid')
            ]
            r = db.select_join('member_pt mp',
                               'card_actv ca',
                               on=on,
                               where=where,
                               fields=fields,
                               other=('order by mp.cur_pt desc '
                                      'limit {} offset {}'.format(
                                          d['limit'], d['offset']))) or []

            total_num = db.select_join_one('member_pt mp',
                                           'card_actv ca',
                                           on=on,
                                           where=where,
                                           fields='count(1) as num')['num']
            if not r: return r, total_num

        # 用户信息
        userids = [i['userid'] for i in r]
        users = apcli_ex('findUserBriefsByIds', userids)
        users = {i.uid: i.__dict__ for i in users}
        for i in r:
            t = users.get(i['userid']) or {}
            i['id'] = str(i['id'])
            i['activity_id'] = str(i['activity_id'])
            i['shopname'] = t.get('shopname') or ''
            i['addr'] = t.get('address') or ''
            i['diff_exchange'] = max(
                i['exchange_pt'] - i['cur_pt'] % i['exchange_pt'], 0)
            i['exchange'] = i['cur_pt'] / i['exchange_pt']
            i['start_time'] = str_to_tstamp(str(i['start_time']))
            i['expire_time'] = str_to_tstamp(str(i['expire_time']))

        return r, total_num
Пример #26
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('密码验证失败')
Пример #27
0
    def POST(self):
        param = self._trans_input()

        with get_connection_exception('qmm_wx') as db:
            where = {'id' : param['actv_id']}
            db.update('market_activity', param['data'], where=where)

        return self.write(success({}))
Пример #28
0
    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']}))
Пример #29
0
 def _del(self, p):
     try:
         with get_connection_exception('qf_mchnt') as db:
             data = {'status': 3, 'utime': int(time.time())}
             db.update('member_actv', data, where={'id': p['id']})
     except:
         log.warn('del member actv error:%s' % traceback.format_exc())
         raise DBError('更新活动失败')
     return self.write(success({'id': p['id']}))
Пример #30
0
 def edit_mpconf(self):
     '''修改配置'''
     values = self.build_args()
     where = {'id': values.pop('id')}
     try:
         with get_connection_exception('qf_solar') as db:
             db.update('app_conf', values=values, where=where)
     except:
         raise ParamError('保存失败,该配置已存在')
     return self.write(success({}))