Exemple #1
0
    def push_entry_get_deviceid(self, data):
        '''
        获取deviceid
        ios: device_token
        andriod: clientid
        '''
        ret = ''
        if self.platform == 'ios':
            if data.get('device_token'):
                ret = data['device_token']

            elif self.user.ses.get('push_device_token'):
                ret = self.user.ses.get('push_device_token')

            if ret:
                # 保留device_token
                self.user.ses.data['push_device_token'] = ret

        elif self.platform == 'android':
            if data.get('clientid'):
                ret = data['clientid']

            elif self.user.ses.get('push_clientid'):
                ret = self.user.ses.get('push_clientid')

            elif ('msgpush' in and_bind_platform and data.get('deviceid')
                  and data.get('apptype')):

                with get_connection('push_data') as db:
                    getui = db.select_one(table='getui_bind',
                                          where={
                                              'deviceid': data['deviceid'],
                                              'apptype': data['apptype']
                                          },
                                          fields='clientid')
                    if getui:
                        ret = getui['clientid']
            if ret:
                # 保留clientid
                self.user.ses.data['push_clientid'] = ret

        return ret
Exemple #2
0
    def get_user_count(self, cate_codes):

        ret = {}
        if not cate_codes:
            return ret
        where = {}
        where['cate_code'] = ('in', cate_codes)
        where['status'] = TagDef.TAG_VALID
        where['userid'] = ('!=', TagDef.VIRTUAL_USER_ID)
        with get_connection('qf_user') as db:
            count = db.select(
                table = 'user_category',
                fields = 'cate_code, count(*) as count',
                where = where,
                other = 'group by cate_code'
            )
            log.debug('count={}'.format(count))
            if count:
                ret = {i['cate_code']: i['count'] for i in count}
        return ret
Exemple #3
0
    def GET(self):

        params = self.req.input()
        pid = params.get('pid', '')
        if not pid:
            raise ParamError('pid不能为空')

        try:
            int(pid)
        except:
            raise ParamError('pid格式错误')

        try:
            with get_connection('qf_mis') as conn:
                rows = conn.select('lst_area', fields='area_id, full_name, name', where={'status': 1, 'parent_id': pid})
                rows = sorted(rows, key=_itemgetter('area_id'))
            return self.write(success(data=rows))
        except:
            log.warn(traceback.format_exc())
            raise DBError('查询区域失败')
Exemple #4
0
 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
Exemple #5
0
    def GET(self, userid=None):

        # 微信通道实名商户
        wx_oauth_mchnt, chnlbind = 0, {}
        with get_connection('qf_core') as db:
            chnlbind = db.select_one('chnlbind',
                                     where={
                                         'userid': ('in', (0, userid)),
                                         'available': 1,
                                         'tradetype': UserDefine.CHNLBIND_TYPE
                                     },
                                     other='order by priority',
                                     fields='key3, mchntid, chnlid, termid')
            # 微信通道下实名商户为微信特约商户
            if (chnlbind['chnlid'] == config.WX_CHNLID
                    and chnlbind['key3'] != 'wxeb6e671f5571abce'):
                wx_oauth_mchnt = 1

        # T1或者D1
        settle_type = UserDefine.SETTLE_TYPE_T1
        bigmchntids = set(get_bigmchntid() or [])
        if not chnlbind or not bigmchntids:
            settle_type = UserDefine.SETTLE_TYPE_T1
        elif (chnlbind['chnlid'] in config.D1_CHNLIDS and '{}_{}'.format(
                chnlbind['mchntid'], chnlbind['termid']) not in bigmchntids):
            settle_type = UserDefine.SETTLE_TYPE_D1
        else:
            settle_type = UserDefine.SETTLE_TYPE_T1

        # period
        # 若是t1需要获取账期
        period = {}
        if settle_type == UserDefine.SETTLE_TYPE_T1:
            td = time.strftime(DATE_FMT)
            period = UserUtil.get_periods(td) or {}

        return success({
            'wx_oauth_mchnt': wx_oauth_mchnt,
            'settle_type': settle_type,
            'period': period
        })
Exemple #6
0
def get_area_cities(country_code):
    with get_connection('qf_org') as db:

        records_area = db.select(
            'tools_area',
            where={
                'country': country_code,
                'area_display': 1
            },
            fields=('id areaid, area_name areaname, area_no'),
        )
        if records_area:
            records_areacity = db.select(
                'tools_areacity',
                where={
                    'area_id': ('in', [i['areaid'] for i in records_area]),
                    'city_display': 1
                },
                fields=('id cityid, city_name cityname, city_no, area_id'),
            )
    rtn_val = {}
    for area in records_area or []:
        if area.get('areaid') not in rtn_val:
            rtn_val[area.get('areaid')] = {
                'areaid': area.get('areaid'),
                'areaname': area.get('areaname'),
                'area_no': area.get('area_no'),
                'cities': []
            }
        for areacity in records_areacity or []:
            if area.get('areaid') == areacity.get('area_id'):
                rtn_val[area.get('areaid')]['cities'].append({
                    'cityid':
                    areacity.get('cityid'),
                    'cityname':
                    areacity.get('cityname'),
                    'city_no':
                    areacity.get('city_no')
                })

    return rtn_val
Exemple #7
0
    def check_op(self, userid, password, opuid):
        opuser = None
        with get_connection('qf_core') as db:
            opuser = db.select_one('opuser',
                                   fields='password, opname, opuid',
                                   where={
                                       'userid': userid,
                                       'opuid': int(opuid),
                                       'status': 1
                                   })
        if not opuser:
            raise UserError('该操作员不存在')

        if not check_password(password, opuser['password']):
            self.password_error(userid, password, opuid)
            raise UserError('账号或密码有误,请重新输入')

        return {
            'opname': opuser['opname'] or '',
            'opuid': str(opuser['opuid']).rjust(4, '0')
        }
Exemple #8
0
    def msgpush_bind(self, data):
        if self.sdk != 'getui':
            return

        with get_connection('push_data') as db:
            where = {'deviceid': data['deviceid'], 'apptype': data['apptype']}
            if db.select('getui_bind', where=where):
                update_fields = [
                    'openid', 'mobile', 'appver', 'clientid', 'usertag',
                    'userid', 'update_time'
                ]
                update_data = {i: data[i] for i in update_fields if data[i]}
                update_data['is_logout'] = data['is_logout']
                update_data['token_status'] = data['token_status']
                db.update(table='getui_bind', values=update_data, where=where)

            else:
                db.insert(
                    table='getui_bind',
                    values=data,
                )
Exemple #9
0
def all_tags(display='code_list'):
    '''取出所有的标签'''

    all_codes = [] if display == 'code_list' else {}
    where = {'userid': TagDef.VIRTUAL_USER_ID}
    with get_connection('qf_user') as db:
        all_codes = db.select(table='user_category',
                              fields='cate_code, cate_name, remark',
                              where=where)
        if all_codes:
            if display == 'code_list':
                all_codes = [i['cate_code'] for i in all_codes]
            elif display == 'code_map':
                all_codes_map = {}
                for i in all_codes:
                    all_codes_map[i['cate_code']] = {
                        'cate_name': i['cate_name'],
                        'remark': i['remark']
                    }
                all_codes = all_codes_map
    return all_codes
Exemple #10
0
    def get_recharge_info(userid, groupid=None):
        '''获取商户付费信息'''
        # 商户付费情况
        mchnt_info = adjust_payinfo_ex(userid,
                                       service_code='card_actv',
                                       groupid=groupid)

        # 付费过期
        if mchnt_info['status'] and mchnt_info['overdue']:
            num = 0
            with get_connection('qf_mchnt') as db:
                num = db.select_one('member',
                                    where={'userid': userid},
                                    fields='count(*) as num')['num']
            # 过期提示
            mchnt_info['note'] = ('抱歉,您的会员服务已到期,会员功能将无法继续使用,正常收款不受影响。'
                                  '为保证{num}已有会员的体验,建议尽快续费哦~'.format(
                                      num='%d位' % num if num else ''))
            mchnt_info['num'] = num

        return mchnt_info
Exemple #11
0
    def GET(self):
        userid = int(self.req.input().get('userid').strip())
        r = None
        with get_connection('qf_mchnt') as db:
            now = int(time.time())
            r = db.select_one('card_actv',
                              where={
                                  'userid': self.get_userid_condition(userid),
                                  'expire_time': ('>', now),
                                  'start_time': ('<', now)
                              },
                              fields=[
                                  'exchange_pt', 'goods_name', 'goods_amt',
                                  'obtain_amt', 'status', 'obtain_limit'
                              ],
                              other='order by ctime desc') or {}

        if not r:
            return error(QFRET.NODATA)

        return success(r)
Exemple #12
0
    def GET(self):
        d = self._trans_input()
        ret = {'notify_list' : [], 'total_count' : 0}

        userids = []
        with get_connection('qf_mchnt') as db:
            consumed_shops = db.select(
                        table = 'member',
                        where = {
                            'customer_id' : d['customer_id']
                        }, fields='userid') or []

            userids = [i['userid'] for i in consumed_shops]

        if userids:
            all_sales = SpecialApi.get_all_sales() or []
            consumed_sales = [sale for sale in all_sales if sale['qf_uid'] in userids]
            ret['notify_list'] = SpecialApi.tidy_sales(consumed_sales,
                    mode = 'consumed', lng = d['lng'], lat = d['lat'])
            ret['total_count'] = len(ret['notify_list'])

        return self.write(success(ret))
Exemple #13
0
    def is_new_card(userid, customer_id, src):
        '''将用户设置为新用户'''
        is_new = 0

        TIME_LIMIT = 24 * 3600
        with get_connection('qf_mchnt') as db:
            member = db.select_one('member',
                                   where={
                                       'customer_id': customer_id,
                                       'userid': userid,
                                   },
                                   fields='id, ctime') or []

            key = '_mchnt_api_is_new_{}_{}_{}__'.format(
                userid, customer_id, src)
            now = int(time.time())
            if (not member or (now - member['ctime'] < TIME_LIMIT
                               and not redis_pool.get(key))):
                is_new = 1
                redis_pool.set(key, 1, TIME_LIMIT)

        return is_new
Exemple #14
0
    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
Exemple #15
0
    def GET(self):
        d = self.req.input()
        q = d.get('q', '')
        if len(q) < 5:
            return  self.write(success({'records': []}))
        elif len(q) > 9:
            q = q[:6]

        cardbins = None
        with get_connection('qf_core') as db:
            cardbins = db.select(
                     table= 'cardbin',
                     where= {'cardbin': ('like', '{}%'.format(q))},
                     fields= ('distinct cardbin, bankid headbankid,'
                              ' bankname headbankname, cardtp'))
        if not cardbins:
            return self.write(success({'records': []}))

        hdbanks = get_head_banks()
        tags = set()
        records = []
        for cardbin in cardbins:
            tag = '%s%s' % (cardbin['headbankname'], cardbin['cardtp'])
            if tag in tags:
                continue
            tags.add(tag)

            for hdbank in hdbanks:
                if cardbin['headbankname'] in hdbank['headbankname']:
                    records.append({
                        'headbankname': hdbank['headbankname'],
                        'headbankid': hdbank['headbankid'],
                        'cardtype': card_type.get(int(cardbin['cardtp']),
                                                  '未识别的卡种'),
                        'csphone': hdbank['csphone'] or '',
                        'iscommon': hdbank['iscommon']
                     })
        return self.write(success({'records': records}))
Exemple #16
0
def check_allow_create(userid):
    num = 0
    allow_create = True
    where = {
        'create_mchnt_id': userid,
        'type': 3,
        'status': ('in', [1, 2]),
    }
    td_ts = get_day_begin_ts()
    notify_ts = td_ts + 11 * 3600
    if int(time.time()) > notify_ts:
        where['create_time'] = ('>=', td_ts)
    else:
        where['create_time'] = ('>', td_ts - 24 * 3600)
    with get_connection('qf_marketing') as db:
        num = db.select_one(
                table= 'activity',
                where= where,
                fields= 'count(1) as num')['num']
    if num >= 1:
        allow_create = False

    return allow_create
Exemple #17
0
def test():
    from qfcommon.base import logger, dbpool
    logger.install('stdout')
    DATABASE = {'test': # connection name, used for getting connection from pool
                {'engine':'mysql',   # db type, eg: mysql, sqlite
                 'db':'test',        # db name
                 'host':'127.0.0.1', # db host
                 'port':3306,        # db port
                 'user':'******',      # db user
                 'passwd':'123456',  # db password
                 'charset':'utf8',   # db charset
                 'conn':2}          # db connections in pool
           }

    dbpool.install(DATABASE)

    with dbpool.get_connection('test') as conn:
        for i in range(0, 10):
            myid = new_id64(conn=conn)
            print time.time(), time.localtime()[:]
            print myid,
            unpack_id64(myid)
            print unpack_time_id64(myid)
Exemple #18
0
    def _get_city(self, provinceid):
        '''由provinceid获取市'''
        if not provinceid or not is_valid_int(provinceid):
            return ''

        city = None
        with get_connection('qf_mis') as db:
            city = db.select_join_one('tools_areacity tac',
                                      'tools_area ta',
                                      on={'tac.area_id': 'ta.id'},
                                      where={
                                          'area_display':
                                          1,
                                          'city_display':
                                          1,
                                          'ta.area_no':
                                          int(provinceid[:2]),
                                          'tac.city_no':
                                          ('in', (provinceid[:2],
                                                  provinceid[:4], provinceid))
                                      },
                                      fields='city_name')
        city = (city or {}).get('city_name', '')
        return unicode_to_utf8_ex(city)
Exemple #19
0
        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
Exemple #20
0
    def GET(self):
        d = self.req.input()
        userid = int(self.user.userid)

        # opuid设置
        opuid = d.get('opuid', '')
        if not opuid:
            raise ParamError('获取收银员编号错误')

        # 查询操作员信息
        opuser_info = {}
        with get_connection('qf_core') as db:
            opuser_info = db.select_one(table='opuser',
                                        where={
                                            'userid': userid,
                                            'opuid': int(opuid),
                                        },
                                        fields='opname, status, mobile')
        if not opuser_info:
            raise ParamError('未能查询到该收银员')

        opuser_info['opuid'] = opuid

        return self.write(success(opuser_info))
Exemple #21
0
    def get_cates(self):
        self.manual_list = [('status', '状态')]
        self.valid_list = []
        values = self.build_args()

        where = {
            'status': ('in', TagDef.TAG_STATUS),
            'userid': TagDef.VIRTUAL_USER_ID
        }
        if values.get('status'):
            where['status'] = values.get('status')


        cate_dict = {}
        with get_connection('qf_user') as db:
            ret = db.select(
                table = 'user_category',
                fields = 'cate_code, cate_name, status',
                where = where,
            )
            if ret:
                for i in ret:
                    cate_dict[i['cate_code']] = i['cate_name']
        return self.write(success({'cate_dict': cate_dict}))
Exemple #22
0
    def get_org_uid(self, userid=None):
        '''获取商户机构uid'''
        if not userid:
            try:
                return self.user.ses.data['groupid']
            except:
                pass

        admin = None
        with get_connection('qf_org') as db:
            userid = userid or self.user.userid
            admin = db.select_one('org_admin',
                                  where={'userid': userid},
                                  fields='qd_uid')

        if not admin:
            raise ParamError('org不存在')

        try:
            self.user.ses['org_uid'] = admin['qd_uid']
        except:
            pass

        return admin['qd_uid']
Exemple #23
0
    def GET(self):
        d = self._trans_input()
        # 获取活动报名详细信息
        r = None
        with get_connection('qf_mchnt') as db:
            r = db.select_one(
                table='official_actv',
                where={
                    'id': d['aid'],
                    'status': 1
                },
                fields=(
                    'cast(id as char) as id, title, rule, bg_url, content,'
                    'start_time, expire_time, poster_url, poster_content, ext'
                ))
        if not r:
            raise ParamError('该活动不存在')

        r['rule'] = r['rule'].split('\n')
        r['poster_content'] = r['poster_content'].split('\n')
        r['start_time'] = r['start_time'].strftime(DATE_FMT)
        r['expire_time'] = r['expire_time'].strftime(DATE_FMT)

        return self.write(success(r))
Exemple #24
0
    def tidy_codes(self, codes, customer, actv):
        cur_num = customer['cur_pt'] / actv['exchange_pt']
        codes_num = len(codes)

        # 若兑换卡数相同
        if cur_num == codes_num:
            return codes

        now = int(time.time())
        # 当前卡数大于实际卡数
        if cur_num < codes_num:
            cancel_num = codes_num - cur_num
            cancel_codes = [codes[i]['id'] for i in range(cancel_num)]
            with get_connection('qf_mchnt') as db:
                db.update(table='exchange_record',
                          values={
                              'utime': now,
                              'status': CODE_STATUS_CANCEL
                          },
                          where={'id': ('in', cancel_codes)})
            return codes[cancel_num:]

        # 实际卡数大于当前卡数
        with get_connection('qf_mchnt') as db:
            records = db.select(table='exchange_record',
                                fields='code, status',
                                where={'activity_id': actv['id']})
        allcodes = defaultdict(set)
        # allcodes:
        # 0: 所有code 1: 已兑换 2:创建优惠码 3:已撤销
        for i in records or []:
            allcodes[0].add(i['code'])
            allcodes[i['status']].add(i['code'])

        add_num = cur_num - codes_num
        choose, allchoose = [], set(range(1, 10000))
        if 9999 - len(allcodes[0]) > add_num:
            choose = random.sample(list(allchoose - allcodes[0]), add_num)
        else:
            try:
                choose = random.sample(
                    list(allchoose - allcodes[CODE_STATUS_CREATE]), add_num)
            except:
                log.error('兑换码不够,error:%s' % traceback.format_exc())

        data = []
        for code in choose:
            data.append({
                'id': getid(),
                'code': code,
                'userid': actv['userid'],
                'ctime': now,
                'utime': now,
                'customer_id': customer['customer_id'],
                'activity_id': actv['id'],
                'status': CODE_STATUS_CREATE
            })
        if data:
            codes.extend(data)
            with get_connection('qf_mchnt') as db:
                db.insert_list('exchange_record', data)

        return codes
Exemple #25
0
def start():
    now = int(time.time())
    userids = []
    userids.append({"appid": "wxeb6e671f5571abce", "nickname": u"好近"})

    today = datetime.date.today()
    yesterday = today - datetime.timedelta(days=1)
    bfore_yesterday = today - datetime.timedelta(days=2)

    client = ThriftClient(config.WX_SERVER, QFMP, framed=False)
    client.raise_except = True
    open_ids = []

    b_30 = today - datetime.timedelta(days=60)

    tlist = []

    newfans = []
    with get_connection('qf_mis') as db:
        sql = "select channelid,channelname from channel_crm where channelid = 20395 "
        newfans = db.query(sql)

    print newfans
    exit(-1)

    # newfans = []
    # with get_connection('open_user') as db:
    #     sql = "select count(1) as newfan, userid as uid,appid,`chnluserid` as mchnt_id from `subscribe` where ctime between '2018-06-14 00:00:00' and '2018-06-14 23:59:59' and userid in (2104049) group by userid,appid,chnluserid "
    #     newfans = db.query(sql)
    #
    # print newfans
    # exit(-1)

    # r = Urllib2Client().get("http://192.20.20.12:8097/findChnlInfo")
    # r_j = json.loads(r)
    # ls = r_j['data']
    #
    # for xy in ls:
    #     tlist.append(xy['chnlTypeCode'])
    #
    # tlist = set(tlist)
    # print tlist  2235043

    # qudao_list = []
    # with get_connection('qf_core') as db:
    #
    #     #sql = "update profile set user_state = 1 where userid = 2235043  "
    #     sql = "select userid,idenddate from profile where userid = 2235826  "
    #
    #     # sql = "update apply set usertype = 1 where user in (1322810,1659877,1680586,2118907,2125555,2128594,2138725,2199637,2217508,2218048,2222098,2224777,2224822,2224864);"
    #     qudao_list = db.query(sql)
    #
    # print qudao_list
    #
    # exit(-1)

    # qudao_list = []
    # with get_connection('qf_audit') as db:
    #     sql = "select userid,ext,id from salesman_event where ext like '%\"oldusertype\": null%'  "
    #     #sql = "update apply set usertype = 1 where user in (1322810,1659877,1680586,2118907,2125555,2128594,2138725,2199637,2217508,2218048,2222098,2224777,2224822,2224864);"
    #     qudao_list = db.query(sql)
    #
    # print qudao_list

    deals = []
    with get_connection('qf_solar') as db:
        _sql = "select * from `mchnt_list` where  ctime between 20180613 and 20180613   and uid in (1987190)"
        deals = db.query(_sql)
    print deals

    exit(-1)

    # _data = client.call('access_token','wx2af0f30b8b10de0a')
    # _token = _data.access_token
    #
    # print _token
    # exit(-1)

    #获取微信数据
    # for xy in userids:
    #
    #     _data = client.call('access_token',xy['appid'])
    #     _token = _data.access_token
    #
    #     #总粉丝数
    #     r = Urllib2Client().get("https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=" % _token)
    #     r_j = json.loads(r)
    #     xy['allfan'] = r_j["total"]
    #     open_ids = r_j['data']['openid']
    #
    #     #新增粉丝数
    #     _params = {"begin_date":str(yesterday).replace("-",''),"end_date":str(yesterday).replace("-",'')}
    #     r = Urllib2Client().post_json("https://api.weixin.qq.com/datacube/getusersummary?access_token=%s" % _token, _params,escape=False )
    #     r_j = json.loads(r)
    #     print r_j
    #     newfan = 0
    #     if r_j['list'][-1]:
    #         newfan = r_j['list'][-1]["new_user"]
    #
    #     xy['newfan'] = newfan
    # print userids
    #exit(-1)

    # #查看来源
    #
    # for jc in open_ids:
    #
    #     r = Urllib2Client().get("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN" % (_token,str(jc)))
    #     r_j = json.loads(r)
    #     print r_j["subscribe_scene"]  2230180

    #获取交易笔数

    # deals = []
    # with get_connection('qf_audit') as db:
    #     _sql = "select userid,ext,state,type from `salesman_event` where type =2 and userid = 2192593  "
    #     deals = db.query(_sql)
    #
    # print deals
    # exit(-1)
    #
    # newfans = []
    # with get_connection('qf_solar') as db:
    #     #sql = "select count(1) as newfan, userid as uid,appid,`chnluserid` as mchnt_id from `subscribe` where DATE_FORMAT(ctime,'%%Y-%%m-%%d') = '2018-06-11'  group by userid,appid,chnluserid limit 10"
    #     #sql = "select * from salesman_event where userid = 2230180 and type = 1 "
    #     sql = "select chnlcode from app_rule   "
    #     newfans = db.query(sql)
    #
    # print newfans
    # exit(-1)
    #
    #
    # with get_connection('open_user') as db:
    #     #sql = "select count(1) as newfan, userid as uid,appid,`chnluserid` as mchnt_id from `subscribe` where DATE_FORMAT(ctime,'%%Y-%%m-%%d') = '2018-06-11'  group by userid,appid,chnluserid limit 10"
    #     sql = "select * from `subscribe` where chnluserid != '' order by userid desc limit 2"
    #     newfans = db.query(sql)
    #
    # print newfans
    # exit(-1)

    # deals = []
    # with get_connection('qf_solar') as db:
    #     _sql = "select * from `mchnt_list` where   ctime between 20180610 and 20180610   and uid in (1572440)"
    #     deals = db.query(_sql)
    #
    # print deals
    # exit(-1)

    # 获取交易笔数
    # deals = []
    # with get_connection('qf_solar') as db:
    #     _sql = "select count(DISTINCT `mchnt_id`) from `mchnt_list` where   id != 0  and ctime between 20180412 and 20180523 "
    #     deals = db.query(_sql)
    #
    # print deals
    # exit(-1)

    # deals = []
    # with get_connection('qf_audit') as db:
    #     _sql = "select userid,ext,state from `salesman_event` where userid = 1587465  "
    #     deals = db.query(_sql)
    #
    # print deals
    # exit(-1)1668004

    #slist = [1322810,1659877,1680586,2118907,2125555,2128594,2138725,2199637,2217508,2218048,2222098,2224777,2224822,2224864]
    slist = [2224858, 1709404, 2224648, 2075924, 2224402, 2209915, 2200336]

    # for xy in slist:
    #
    #
    #     with get_connection('qf_mis') as db:
    #         sql = "select userid,name,imgname from mis_voucher_history where userid =  %s and name = 'shopphoto' order by id desc limit 1 " % xy
    #         qudao_list = db.query(sql)
    #
    #     print qudao_list
    #
    #
    #     with get_connection('qf_mis') as db:
    #         sql = "update mis_upgrade_voucher set imgname = '%s' where user_id =  %s and name = 'shopphoto' " % (qudao_list[0]['imgname'],qudao_list[0]['userid'])
    #         db.query(sql)
    #
    # exit(-1)

    #
    # qudao_list = []
    # with get_connection('qf_audit') as db:
    #     sql = "select userid,ext,id from salesman_event where ext like '%\"oldusertype\": null%'"
    #     #sql = "update apply set usertype = 1 where user in (1322810,1659877,1680586,2118907,2125555,2128594,2138725,2199637,2217508,2218048,2222098,2224777,2224822,2224864);"
    #     qudao_list = db.query(sql)
    #
    # for xy in qudao_list:
    #     _ext = json.loads(xy['ext'])
    #     del _ext['oldusertype']
    #     _ext = json.dumps(_ext,ensure_ascii=False)
    #     _sql = "update salesman_event set ext = '%s' where id = %s " % (_ext,xy['id'])
    #     db.query(_sql)
    #
    # print qudao_list
    # exit(-1)
    #
    # deals = []
    # with get_connection('qf_trade') as db:
    #     sql = "select count(1) as deal,userid as uid,chnluserid as mchnt_id,chnlid from `%s` where sysdtm between '2018-05-31 00:00:00' and '2018-05-31 23:59:59'  and `status` = 1 and `busicd` in ('800201','800207','800208') and chnluserid = '226801000004003759372'  " % (
    #     'record_201805')
    #     print sql
    #     deals = db.query(sql)
    #
    #
    #
    # print deals
    # exit(-1)

    # deals = []
    # with get_connection('qf_mis') as db:
    #     _sql = "select user,ext,state from `salesman_event` where userid = 1587465  "
    #     deals = db.query(_sql)
    #
    # print deals
    # exit(-1)
    #
    # #2108593
    #
    #
    # with get_connection('qf_mis') as db:
    #     _sql = "select user_id,`name`,imgname from  `mis_upgrade_voucher` where user_id in (2170012) and name in ('checkstand_alipay','checkstand_weixin','checkin_weixin','checkin_alipay','licensephoto','goodsphoto','shopphoto')"
    #     img_list = db.query(_sql)
    #
    # def replace_img(imgname, userid):
    #     ret = 'http://pic.qfpay.com/userprofile/%d/%d/%s' % (int(userid) / 10000, int(userid), imgname)
    #     return ret
    #
    # dict_img = {'checkstand_alipay': '收银台照片_支付宝蓝海', 'checkstand_weixin': '收银台照片_微信绿洲'
    #     , 'checkin_weixin': '餐饮平台入驻照_微信绿洲', 'checkin_alipay': '餐饮平台入驻照_支付宝蓝海', 'goodsphoto': '店铺内景照片'
    #     , 'shopphoto': '店铺外景照片', 'licensephoto': '营业执照'}
    #
    # CUR_PATH = '../static/common/zip'
    #
    # for xy in img_list:
    #     img_src = replace_img(xy['imgname'], xy['user_id'])
    #     print img_src
    #     try:
    #         urllib.urlretrieve(img_src, "%s/%s_%s.jpg" % (CUR_PATH, str(xy['user_id']), dict_img[xy['name']]))
    #     except Exception, e:
    #         print e
    #         log.debug(str(e))
    # exit(-1)

    # deals = []
    # with get_connection('qf_mis') as db:
    #     _sql = "select user_id,`name`,imgname from  `mis_upgrade_voucher` where user_id in (2170012) and name in ('checkstand_alipay','checkstand_weixin','checkin_weixin','checkin_alipay','licensephoto','goodsphoto','shopphoto')"
    #     deals = db.query(_sql)
    #
    # print deals
    # exit(-1)
    #
    # deals = []
    # with get_connection('qf_core') as db:
    #     _sql = "select userid,feeratio from account where userid in (2206156) "
    #     deals = db.query(_sql)
    #
    # print deals
    # exit(-1)

    # deals = []
    # with get_connection('qf_audit') as db:
    #     _sql = "update `salesman_event` set state = 2,memo = '测试失败' where userid in (1993892,2086667)  "
    #     deals = db.query(_sql)
    #
    # print deals
    # exit(-1)

    #print yesterday

    # 获取交易笔数
    # deals = []
    # with get_connection('qf_mis') as db:
    #     _sql = "select user_id,detail from mis_oplog where admin_id = 320293 and action_time between '2018-04-25 00:00:00' and '2018-04-25 23:59:59'"
    #     deals = db.query(_sql)
    #
    # for xy in deals:
    #     _str = "%s|%s" % (xy['user_id'],xy['detail'])
    #     w = file('/home/qfpay/solar/1/bin/scripts/jobs.txt','a')
    #     w.write("%s\n" % _str)
    #     w.close()
    #
    # print deals

    # newfans = []
    # with get_connection('open_user') as db:
    #     sql = "select count(1) as newfan, userid as uid,appid,customer_id from `subscribe` where DATE_FORMAT(ctime,'%%Y-%%m-%%d') = '%s' and userid = 2086718 group by userid,appid,customer_id " % (
    #     yesterday)
    #     newfans = db.query(sql)
    #
    # print newfans

    #select `uid`,`id` from `mchnt_list` where   id != 0  and ctime between 20180411 and 20180411   and uid in (451869)

    # deals = []
    # with get_connection('qf_weifutong') as db:
    #      _sql = "select userid as uid,MAX(`ctime`) as stime  from `amchnl_bind` where userid = 2070263 and `state` = 1 group by userid order by stime desc "
    #      deals = db.query(_sql)

    #
    #  deals = []
    # with get_connection('open_user') as db:
    #     sql = "select count(1) as deal,userid as uid,ctime as dtime,`appid` from `open_user`.`subscribe` where ctime between '%s 00:00:00' and '%s 23:59:59' and userid = 2070263  group by userid order by ctime desc" % (
    #     b_30, yesterday)
    #     deals = db.query(sql)
    #
    # print deals

    #
    #  userids = []
    # with get_connection('wxmp_customer') as db:
    #     _sql = " select appid,nick_name from `mp_conf` where status = 1 and nick_name = '' "
    #     userids = db.query(_sql)
    # print userids  800100090148461

    # userids = [{'appid':'wxeb6e671f5571abce','name':u'好近'}]
    #
    # deals = []
    # with get_connection('qf_trade') as db:
    #     sql = "select count(1) as deal,userid as uid,chnluserid as mchnt_id,chnlid,`busicd`,`paydtm` from `%s` where  DATE_FORMAT(paydtm,'%%Y-%%m-%%d') = '2018-05-08'  and `status` = 1  and `busicd` in ('800201','800207','800208') group by mchnt_id " % (
    #     "record_201805")
    #     print sql
    #     deals = db.query(sql)
    #
    # _mchids = ""
    # for xy in deals:
    #     _mchids += "'%s'," % str(xy['mchnt_id'])
    # _mchids = _mchids.rstrip(",")
    #
    # newfans = []
    # with get_connection('qf_weifutong') as db:
    #     sql = "select `mchnt_id`,`subscribe_appid` as appid from `amchnl_bind` where  state = 1 and subscribe_appid != '' and mchnt_id in (%s)  group by  `mchnt_id`,`subscribe_appid` " % (
    #     _mchids)
    #     newfans = db.query(sql)
    #
    # for xy in userids:
    #     xy['mchnt_id'] = []
    #     for jx in newfans:
    #         if xy['appid'] == jx['appid']:
    #             xy['mchnt_id'].append(jx['mchnt_id'])
    #
    # for xy in userids:
    #     _shop = 0
    #     _deal = 0
    #
    #     _shop = len(xy['mchnt_id'])
    #
    #     for jx in deals:
    #         for jc in xy['mchnt_id']:
    #             if str(jc) == str(jx['mchnt_id']):
    #                 _deal += int(jx['deal'])
    #     xy['deal'] = _deal
    #     xy['shop'] = _shop
    #
    # print userids
    #
    #
    # exit(-1)

    #
    #  deals = []
    # with get_connection('qf_weifutong') as db:
    #      _sql = "select userid,mchnt_id from `amchnl_bind` where mchnt_id = '800100090148461' and `state` = 1 "
    #      deals = db.query(_sql)
    #
    # print deals

    # newfans = []
    # with get_connection('open_user') as db:
    #     sql = "select count(*) as newfan,userid as uid from (select * from (select openid,appid,userid from `subscribe` where DATE_FORMAT(ctime,'%%Y-%%m-%%d') = '%s' and userid = %s group by userid,appid) a WHERE NOT EXISTS  (select appid,userid from `subscribe` where DATE_FORMAT(ctime,'%%Y-%%m-%%d') <= '%s' and userid = %s group by userid,appid  ) ) c " % (
    #     yesterday,1336107, bfore_yesterday,1336107)
    #     print sql
    #     newfans = db.query(sql)
    # print newfans

    #1722811

    # newfans = []
    # with get_connection('qf_core') as db:
    #     sql = "select code,name from `channel`"
    #     newfans = db.query(sql)
    # print newfans

    # deals1 = []
    #
    # with get_connection('qf_weifutong') as db:
    #      _sql = "select `subscribe_appid`,`ctime` from `amchnl_bind` where `state` = 1 and userid = 2070263 order by ctime desc "
    #      deals1 = db.query(_sql)
    #
    # print deals1

    # ops = ''
    # for xy in open_ids:
    #     ops += "'%s'," % xy
    # ops = ops.rstrip(",")
    #
    # deals_openid = []
    # with get_connection('open_user') as db:
    #     _sql = "select openid,userid,appid from `subscribe` where DATE_FORMAT(ctime,'%%Y-%%m-%%d') = '%s' and openid in (%s) group by openid " % (str(yesterday),str(ops))
    #     deals_openid = db.query(_sql)
    exit(-1)

    for xy in userids:
        _shop = 0
        _deal = 0
        for jx in deals:
            if xy['appid'] == jx['appid']:
                _shop = int(jx['shop'])
                _deal = int(jx['deal'])
        if _deal == 0:
            _fan = "0%"
        else:
            _fan = "%s%%" % str(round(int(xy['newfan']) / int(_deal), 4))

        xy['shop'] = _shop
        xy['deal'] = _deal
        xy['fan'] = _fan
                    cuser = gcc['cancel_user']

            auser = newfan - cuser

            xy['newfan'] = newfan
            xy['cuser'] = cuser
            xy['auser'] = auser
        except Exception, e:
            print e
            xy['allfan'] = 0
            xy['newfan'] = 0
            xy['cuser'] = 0
            xy['auser'] = 0

    deals = []
    with get_connection('qf_trade') as db:
        sql = "select count(1) as deal,chnluserid as mchnt_id from `%s` where  DATE_FORMAT(paydtm,'%%Y-%%m-%%d') = '%s'  and `status` = 1 and `busicd` in ('800201','800207','800208') group by mchnt_id " % (
            _table_name, yesterday)
        deals = db.query(sql)

    _mchids = ""
    for xy in deals:
        _mchids += "'%s'," % str(xy['mchnt_id'])
    _mchids = _mchids.rstrip(",")

    newfans = []
    with get_connection('qf_weifutong') as db:
        sql = "select `mchnt_id`,`subscribe_appid` as appid from `amchnl_bind` where  state = 1 and subscribe_appid != '' and mchnt_id in (%s)  group by  `mchnt_id`,`subscribe_appid` " % (
            _mchids)
        newfans = db.query(sql)
Exemple #27
0
    def tabs(self):

        values = {"ios_tabs":  [
          {
         "icon": "http://near.m1img.com/op_upload/105/150348111759.png",
         "icon_selected": "http://near.m1img.com/op_upload/105/150348106883.png",
         "link": "nearmcht://view-home-module",
         "name": "首页",
         "color": "#000000",
         "color_selected": "#FF8100",
         },
         {
         "icon": "http://near.m1img.com/op_upload/105/150348115347.png",
         "icon_selected": "http://near.m1img.com/op_upload/105/150348114341.png",
         "link": "nearmcht://view-more-module",
         "name": "更多",
         "color": "#000000",
         "color_selected": "#FF8100",

         },
       {
         "icon": "http://near.m1img.com/op_upload/105/150348117955.png",
         "icon_selected": "http://near.m1img.com/op_upload/105/150348117035.png",
         "link": "nearmcht://view-message-module",
         "name": "消息",
         "color": "#000000",
         "color_selected": "#FF8100",
         },
        {
         "icon": "http://near.m1img.com/op_upload/105/150348120002.png",
         "icon_selected": "http://near.m1img.com/op_upload/105/150348118983.png",
         "link": "nearmcht://view-mine-module",
         "name": "我的",
         "color": "#000000",
         "color_selected": "#FF8100",
         }
      ],
            "and_tabs":  [
          {
         "icon": "http://near.m1img.com/op_upload/105/150348111759.png",
         "icon_selected": "http://near.m1img.com/op_upload/105/150348106883.png",
         "link": "nearmcht://view-home-module",
         "name": "首页",
         "color": "#000000",
         "color_selected": "#FF8100",
         },
         {
         "icon": "http://near.m1img.com/op_upload/105/150348115347.png",
         "icon_selected": "http://near.m1img.com/op_upload/105/150348114341.png",
         "link": "nearmcht://view-more-module",
         "name": "更多",
         "color": "#000000",
         "color_selected": "#FF8100",

         },
       {
         "icon": "http://near.m1img.com/op_upload/105/150348117955.png",
         "icon_selected": "http://near.m1img.com/op_upload/105/150348117035.png",
         "link": "nearmcht://view-message-module",
         "name": "消息",
         "color": "#000000",
         "color_selected": "#FF8100",
         },
        {
         "icon": "http://near.m1img.com/op_upload/105/150348120002.png",
         "icon_selected": "http://near.m1img.com/op_upload/105/150348118983.png",
         "link": "nearmcht://view-mine-module",
         "name": "我的",
         "color": "#000000",
         "color_selected": "#FF8100",
         }
      ]
        }

        with get_connection('qf_mis') as db:
            qdconfs = db.select(
                    table='qd_conf',
                    where={'qd_uid' : 0},
                    fields=('service'))
            vals = json.loads(qdconfs[0]['service'])
            vals.update(values)
            db.update('qd_conf', {'service': json.dumps(vals)}, where={'qd_uid': 0})
Exemple #28
0
    def _get_audit_info(self, userid):
        def get_audit_memo(memo):
            try:
                data = json.loads(memo)['data']
                ret = sorted(data, key=lambda d: d['time'])[-1]['memo']
            except:
                return None
            return ret

        result = {}
        show_button = True
        with get_connection('qf_mis') as db:
            where = {
                'userid': userid,
                'modifytime': ('>=', config.BANK_APPLY_ONLINE_TIME)
            }
            apy = db.select_one('bankchange_apply',
                                where=where,
                                other='order by id desc') or {}
        with get_connection('qf_settle') as db:
            debit_pay = db.select_one('debit_paychnl',
                                      where={'userid': userid},
                                      other='order by id desc') or {}

        tips = config.BANK_UPDATE_TIPS
        # 获取审核信息
        with get_connection('qf_mis') as db:
            audit_state = db.select_one(
                'apply', where={'user': userid}, fields='user, state') or {}
        if audit_state:
            state = audit_state.get('state', '')
            if state != APPLY_STATE.get("pass"):
                result['show_button'] = False
                return result
        # 未提交过信息
        if not apy:
            result['show_button'] = show_button
            #退票处理
            if debit_pay.get('status', '') == 3:
                result['title'] = tips['debit_back']['title']
                result['subtitle'] = tips['debit_back']['subtitle']
                result['remit_back'] = 1
            return result

        if (apy['status'] == UserDefine.BANK_APPLY_SUCC
                and apy['sync_tl_status'] == UserDefine.BANK_SYNC_SUCC):
            # 审核通过
            result['state'] = UserDefine.BANK_APPLY_STATE_SUCC
            success = {
                'title':
                tips['success']['title'],
                'subtitle':
                tips['success']['subtitle'].format(
                    apy['modifytime'].strftime('%Y年%m月%d日'))
            }
            result.update(success)
            result['content'] = []
            result['show_button'] = show_button
            return result

        apy['bankaccount'] = apy['bankaccount'][-4:]
        # 审核关闭 或者 银行反馈失败
        if (apy['status'] == UserDefine.BANK_APPLY_CLOSED
                or apy['sync_tl_status'] == UserDefine.BANK_SYNC_FAIL):
            result['state'] = UserDefine.BANK_APPLY_STATE_FAIL
            result['show_button'] = show_button
            memo = get_audit_memo(apy['operatorinfo'])
            sync_memo = apy.get('sync_memo', '')
            result['title'] = tips['auditing']['title'].format(**apy)
            result['subtitle'] = tips['auditing']['subtitle']
            info = [{
                'name':
                tips['submit'],
                'time':
                apy['create_time'].strftime('%Y年%m月%d日 %H:%M:%S')
                if apy['create_time'] else ''
            }]
            #state 1.审核中 2.审核成功 3.审核失败
            #风控审核失败
            if apy['status'] == UserDefine.BANK_APPLY_CLOSED:
                info.append({
                    'name': tips['risk_audit'],
                    'time': '',
                    'state': 3,
                    'memo': memo,
                    'st_title': tips['audit_fail']
                })
                info.append({
                    'name': tips['bank_change'],
                    'time': '',
                    'memo': tips['audit_memo2']
                })
                result['process'] = 2

            #风控审核通过
            if apy['status'] == UserDefine.BANK_APPLY_SUCC:
                info.append({
                    'name': tips['risk_audit'],
                    'time': '',
                    'state': 2,
                    'memo': '',
                    'st_title': tips['audit_success']
                })
                result['process'] = 3
                #银行变更中, 银行卡未同步
                if apy['sync_tl_status'] == UserDefine.BANK_SYNC_NO:
                    #银行信息同步中,时间和memo无法获取
                    info.append({
                        'name': tips['bank_change'],
                        'time': '',
                        'state': 1,
                        'memo': tips['audit_memo1'],
                        'st_title': tips['sync_ing']
                    })
                #银行同步失败
                else:
                    info.append({
                        'name': tips['bank_change'],
                        'time': '',
                        'state': 3,
                        'memo': sync_memo,
                        'st_title': tips['sync_fail']
                    })

            result['content'] = info

        # 审核中
        else:
            result['state'] = UserDefine.BANK_APPLY_STATE_ING
            result['title'] = tips['auditing']['title'].format(**apy)
            result['subtitle'] = tips['auditing']['subtitle']
            result['show_button'] = False
            info = [{
                'name':
                tips['submit'],
                'time':
                apy['create_time'].strftime('%Y年%m月%d日 %H:%M:%S')
                if apy['create_time'] else ''
            }]
            #风控审核成功
            if apy['status'] == UserDefine.BANK_APPLY_SUCC:
                info.append({
                    'name': tips['risk_audit'],
                    'time': '',
                    'state': 2,
                    'memo': '',
                    'st_title': tips['audit_success']
                })
                info.append({
                    'name': tips['bank_change'],
                    'time': '',
                    'state': 1,
                    'memo': tips['audit_memo1'],
                    'st_title': tips['sync_ing']
                })
                result['process'] = 3
            #风控审核中
            else:
                info.append({
                    'name': tips['risk_audit'],
                    'time': '',
                    'state': 1,
                    'memo': tips['audit_memo1'],
                    'st_title': tips['audit_ing']
                })
                info.append({
                    'name': tips['bank_change'],
                    'time': '',
                    'memo': tips['audit_memo2']
                })
                result['process'] = 2

            result['content'] = info
        #商户提交了申请,且被银行退票时,优先展示审核状态
        if not result:
            result['show_button'] = show_button
            #退票处理
            if debit_pay.get('status', '') == 3:
                result['title'] = tips['debit_back']['title']
                result['subtitle'] = tips['debit_back']['subtitle']
                result['remit_back'] = 1

        return result
Exemple #29
0
    def GET(self):
        if 'id' not in self.req.input():
            raise ParamError('活动不存在')
        actv_id = self.req.input()['id'].strip()
        userid = int(self.user.userid)

        actv = {}
        with get_connection('qf_mchnt') as db:
            actv = db.select_one('actv_effect',
                            where = {
                                'id' : actv_id,
                                'userid' : userid
                            }) or {}
        if not actv:
            raise ParamError('活动不存在')

        if actv['type'] not in UserDefine.ACTV_EFFECTS:
            raise ParamError('活动类型错误')

        # 活动结案报告
        params = json.loads(actv['content'])
        effect = copy.deepcopy(config.ACTV_EFFECT[actv['type']])

        # 整理输出
        result = {}
        for key, val in effect.iteritems():
            if key in ('datas', 'effect'):
                param = params.get(key) or {}
                param = {k:(v/100.0 if k.endswith('amt') else v) for k,v in param.iteritems()}
                result[key] = []
                for item in val:
                    try:
                        item['desc'] = item['desc'].format(**param)
                        result[key].append(item)
                    except:
                        #log.debug(traceback.format_exc())
                        pass
            elif key == 'rank':
                try:
                    result['rank'] = val.format(**params['rank'])
                except:
                    result['rank'] = ''
            elif not key.startswith('_'):
                result[key] = val

        # 活动信息
        datas = params.get('datas') or {}
        if datas:
            if actv['type'] == UserDefine.ACTV_EFFECT_SALE:
                datas['start_time'] = datas['create_time']
                datas['expire_time'] =datas['redeem_end_date'] + ' 00:00:00'

            try:
                result['actv_info'] = {
                    'expire_time' : str_to_tstamp(datas['expire_time'], DATETIME_FMT),
                    'start_time' : str_to_tstamp(datas['start_time'], DATETIME_FMT),
                    'actv_name' : datas.get('title', '')
                }
                if actv['type'] == UserDefine.ACTV_EFFECT_CARD:
                    result['actv_info']['actv_name'] = u'兑换{}活动'.format(params['datas']['goods_name'])
            except:
                log.debug(traceback.format_exc())

        return self.write(success(result))
Exemple #30
0
    def gen_ret(self, coupons):
        '''整理输出'''
        if not coupons: return []

        cr_ids = [
            i['coupon_rule_id'] for i in coupons if not i['use_mchnt_id']
        ]
        use_mchnt_dict = {}
        if cr_ids:
            with get_connection('qf_marketing') as db:
                use_mchnts = db.select(
                    'coupon_rule_mchnt',
                    where={'coupon_rule_id': ('in', cr_ids)},
                    fields='coupon_rule_id,  mchnt_id_list')
                for i in use_mchnts:
                    try:
                        t = json.loads(i['mchnt_id_list'])
                        if t:
                            use_mchnt_dict[i['coupon_rule_id']] = (len(t),
                                                                   t[0])
                    except:
                        log.warn(traceback.format_exc())

        # 需要查询店铺信息
        mchnt_ids = [
            coupon['use_mchnt_id'] for coupon in coupons
            if coupon['use_mchnt_id']
        ]
        for mode, userid in use_mchnt_dict.values():
            if mode == 1:
                mchnt_ids.append(userid)

        users = {}
        if mchnt_ids:
            users = apcli_ex('findUserBriefsByIds',
                             list({int(i)
                                   for i in mchnt_ids}))
            users = {user.uid: user.__dict__ for user in users or []}

        today = time.strftime(DT_FMT)
        for coupon in coupons:
            use_rule = coupon.pop('use_rule', '')
            coupon_rule_id = coupon.pop('coupon_rule_id', '')
            create_mchnt_id = coupon.pop('create_mchnt_id', '')

            coupon['id'] = str(coupon['id'])
            coupon['use_amt'] = get_use_amt(use_rule)

            if create_mchnt_id:
                coupon['platform'] = 0
            else:
                coupon['platform'] = 1

            userid = None
            if coupon['use_mchnt_id']:
                userid = int(coupon['use_mchnt_id'])

            elif coupon_rule_id in use_mchnt_dict:
                multi, u_userid = use_mchnt_dict[coupon_rule_id]
                if multi == 1:
                    userid = int(u_userid)
                else:
                    coupon['multi'] = multi

            else:
                coupon['multi'] = 1

            if userid:
                coupon['multi'] = 0
                user = users.get(int(userid), {})
                coupon['addr'] = user.get('address', '')
                coupon['shopname'] = user.get('shopname', '')
            coupon['coupon_type'] = get_coupon_type(coupon['type'])
            try:
                coupon['expire_day'] = str_diffdays(
                    today,
                    str(coupon['expire_time'])[:10]) + 1
            except:
                coupon['expire_day'] = 0

        return coupons