Esempio n. 1
0
def card_create(request):
    '''创建礼包卡
    '''
    msg = ''
    card_count = int(request.REQUEST.get('card_count','0'))
    batch_id = int(request.REQUEST.get('batch_id','0'))
    record = int(request.REQUEST.get('record','0'))

    card_size = 2000
    if card_count < card_size:
        card_size = card_count
        
    if card_count - record < card_size:
        card_size = card_count - record
    
    is_finish = 0
    
    if card_count == record:
        is_finish = 1    
   
    if batch_id > 0 and card_count > 0 and card_size > 0 and is_finish == 0:
        try:
            card_batch = CardBatch.objects.using('card').get(id = batch_id)
            key = card_batch.key
            #card = Card()
            card_table_name = Card.get_card_table_name(key)
            Card._meta.db_table = Card.get_card_table_name(key)
            card = Card()      
            card.batch_id = batch_id     
            
            conn = connections['card']
            cursor = conn.cursor()              
            if card_batch:
                insert_sql = []
                add_time = datetime.datetime.now()
                number_cache_list = []
                for i in range(0,card_size):
                    while True:
                        number = Card.get_card_number(key)
                        if number not in number_cache_list:
                            number_cache_list.append(number)
                            break
                    count_sql = "SELECT COUNT(*) FROM `%s` c WHERE c.`number` = '%s' "%(card_table_name,number)
                    cursor.execute(count_sql)
                    count = cursor.fetchone()
                    repeat_count = int(count[0])   
                    if repeat_count == 0:          
                        insert_sql.append("('%s','%s','%s',0,0)"%(batch_id,number,add_time))
                        i = i + 1
                cursor.execute('INSERT INTO `%s`(`batch_id`,`number`,`add_time`,`status`,`use_count`) VALUES  %s'%(card_table_name, ','.join(insert_sql)))
                cursor.close()
                card_batch.total_count = card_batch.total_count + i
                card_batch.save(using='card')
                record = record + i
        except Exception, e:
            print('create card number error:', e)
            traceback.print_exc()
            msg = '%s'%e
Esempio n. 2
0
def card_list(request):
    msg = ''
    batch_id = int(request.REQUEST.get('batch_id', '0'))
    page_num = int(request.REQUEST.get('page_num', '1'))    
    if page_num < 1:
        page_num = 1 
    page_num = int(request.REQUEST.get('page_num', '1'))
    page_size = 50
    list_data = []    
    search_type = int(request.REQUEST.get('search_type','0'))
    status = request.REQUEST.get('status','')
    
    sdate = request.REQUEST.get('start_date','')
    edate = request.REQUEST.get('end_date','')
    
    search_val = request.REQUEST.get('search_val','')
    query = ['1=1']
    total_record = 0
    card_batch = None
    list_server = get_server_list()
    server_id = int(request.REQUEST.get('server_id','0'))
    if batch_id > 0:
        query.append(" and batch_id = '%s'"%batch_id)
        try:
            card_batch = CardBatch.objects.using('card').get(id = batch_id)
            key = card_batch.key
            Card._meta.db_table = Card.get_card_table_name(key)
            if search_type != 0 and search_val !='':
                if search_type == 1:
                    query.append(" and number = '%s'"%search_val)
                elif search_type == 2:
                    query.append(" and player_id = '%s'"%search_val)
#                elif search_type == 3:
#                    query.append(" and password = '******'"%search_val)                    
            if server_id != 0:
                query.append(" and server_id = %d "%server_id)
            if status != '':
                try:
                    status = int(status)
                    query.append(" and status = %d "%status)
                except:
                    pass
            if sdate != '' and edate != '':
                query.append(" AND DATE(`use_time`) >= '%s' AND DATE(`use_time`) <= '%s'"%(sdate,edate))
            total_record = Card.objects.using('card').extra(where=[''.join(query)]).count()
            if total_record > 0:
                list_data = Card.objects.using('card').extra(where=[''.join(query)]).order_by('-id')[(page_num - 1) * page_size:page_num * page_size]
                for item in list_data:
                    item.server = ''
                    if item.server_id:
                        the_server = Server.objects.get(id = item.server_id)
                        if the_server:
                            item.server = the_server.name
        except Exception, e:
            print('create card number error:', e)   
            msg = '%s'%e        
Esempio n. 3
0
def card_del(request):
    model_id = int(request.REQUEST.get('id','0'))
    batch_id = int(request.REQUEST.get('batch_id','0'))
    if model_id > 0 and batch_id > 0:
        try:
            card_batch = CardBatch.objects.using('card').get(id = batch_id)
            key = card_batch.key
            Card._meta.db_table = Card.get_card_table_name(key)
            the_card = Card.objects.using('card').get(id=model_id)
            the_card.status = -1
            the_card.save(using='card')
            
        except Exception, e:
            print('update error:', e)
Esempio n. 4
0
def show(request, batch_name=''):
    '''礼包卡号显示
    '''
    batch_name = batch_name.strip()
    card_result = ''
    server_id = int(request.REQUEST.get('server_id', '') or 0)
    is_ajax = request.REQUEST.get('is_ajax', False)
    key_name = request.REQUEST.get('key_name', '')
    password_key = request.REQUEST.get(key_name, '')
    cb = request.REQUEST.get('cb', '') or request.REQUEST.get(
        'callback', '') or request.REQUEST.get('jsonpcallback', '')
    server_ids = []
    is_error = True

    _r = {"code": -1, "msg": ""}

    try:

        if not batch_name:
            raise CardShowError('礼包名名为空!')

        the_card_batch = CardBatch.objects.using('card').filter(
            name=batch_name)[:1]

        if len(the_card_batch) == 0:
            raise CardShowError('没有 %s 礼包!' % batch_name)

        import pdb
        pdb.set_trace()
        the_card_batch = the_card_batch[0]
        if the_card_batch.show == 0:
            raise CardShowError('%s 礼包被禁用 !' % batch_name)

        if int(time.time()) - request.session.get('card_time', 0) > 1800:
            request.session['card_code'] = 0

        card_code = request.session.get('card_code', 0)
        if card_code:
            _r['code'] = 0
            raise CardShowError(card_code)

        card_limit_count = the_card_batch.card_limit_count
        current_unixtime = int(time.time())
        start_time = int(time.mktime(the_card_batch.start_time.timetuple()))
        end_time = int(time.mktime(the_card_batch.end_time.timetuple()))

        if not (current_unixtime > start_time and current_unixtime < end_time):
            raise CardShowError('%s 礼包不在可用时间内 !' % batch_name)

        list_server = the_card_batch.server
        if list_server:
            list_server = [int(i) for i in list_server.split(',')]
            if server_id not in list_server:
                raise CardShowError('%s 礼包不在可用服务器内!' % batch_name)
        try:
            key = the_card_batch.key
            the_conn_str = DATABASES['card']
            the_conn = MySQLdb.connect(host=the_conn_str['HOST'],
                                       user=the_conn_str['USER'],
                                       passwd=the_conn_str['PASSWORD'],
                                       port=int(the_conn_str['PORT']),
                                       db=the_conn_str['NAME'],
                                       charset='utf8')
            the_conn.autocommit(1)
            cursor = None
            card_table_name = Card.get_card_table_name(key)
            cursor = the_conn.cursor()
            sql = "LOCK TABLE %s WRITE" % card_table_name
            cursor.execute(sql)
            sql = "SELECT `number`,`id` FROM %s WHERE  `status`=0  AND `batch_id` = %d LIMIT 1" % (
                card_table_name, the_card_batch.id)
            cursor.execute(sql)
            print sql
            data = cursor.fetchone()

            if not data:
                raise CardShowError('卡号已经全部领取完毕')
            card_code = data[0]
            sql = "UPDATE %s SET  `status`=1 WHERE `id` = %d " % (
                card_table_name, int(data[1]))
            cursor.execute(sql)
            request.session['card_code'] = card_code
            request.session['card_time'] = int(time.time())
            _r['msg'] = data[0]
            _r['code'] = 0
        except CardShowError, e:
            raise CardShowError(str(e))
        except Exception, e:
            traceback.print_exc()
            raise CardShowError(str(e))
Esempio n. 5
0
    validate_card = ''
    print 'card_no', card_no
    print 'server_id', server_id
    print 'player_id', player_id
    print 'channel_id', channel_id
    print 'level', level
    try:
        if server_id != '' and card_no != '' and player_id != '' and re.match(
                '^\d+$', server_id):
            key = card_no[0:3]
            validate_card = Card.check_card(card_no)
            print 'validate_card', validate_card
            if validate_card and CardBatch.check_card_key(key):
                player_id = int(player_id)

                Card._meta.db_table = Card.get_card_table_name(key)
                the_card = Card.objects.using('card').extra(where=[
                    "number = '%s' and (status <> -1 ) or status IS NULL " %
                    card_no
                ])

                if the_card:
                    the_card = the_card[0]
                    the_card.use_count = the_card.get_use_count()
                    batch_id = the_card.batch.id
                    card_batch = CardBatch.objects.using('card').get(
                        id=batch_id)

                    card_limit_count = card_batch.card_limit_count
                    # _r['name'] = card_batch.name
                    if the_card.use_count >= card_limit_count:
Esempio n. 6
0
            model.card_limit_count = card_limit_count
            model.channels = ','.join(channel_list)
            model.create_user = create_user
            try:
                _ = json.loads(other_condition)
                model.other_condition = other_condition
            except:
                msg = '条件解析错误!'

            model.remark = remark
            if model.code == '' or model.code == None or model.code == 'None':
                model.code = generate_password(2, 3, 3)
            model.save(using='card')
            if model.id > 0 and model_id == 0:
                try:
                    sql = "CREATE TABLE IF NOT EXISTS `%s` LIKE `card_0`" % Card.get_card_table_name(
                        key)
                    conn = connections['card']
                    cursor = conn.cursor()
                    cursor.execute(sql)
                    cursor.close()
                except Exception, e:
                    print 'create table `card_%s` error' % Card.get_card_table_name(
                        key)
                    msg = '礼包卡类标识已经存在!%s' % e
        except Exception, e:
            print 'save batch error', e
            msg = '%s' % e
    parg = {}
    parg['err_msg'] = msg
    parg['next_url'] = '/card/batch/?status=1'
    is_dialog = request.REQUEST.get('is_dialog', '')
Esempio n. 7
0
def export_card(request): 
    page_size = 500
    is_chl = int(request.REQUEST.get('is_chl','0'))
    clear_export_old_file = int(request.REQUEST.get('clear_export_old_file', '0'))
    page_num = int(request.REQUEST.get('page_num', '1'))    
    batch_id = int(request.REQUEST.get('batch_id','0'))
    card_status = int(request.REQUEST.get('card_status','0'))
    start_date = request.REQUEST.get('start_date','')
    end_date = request.REQUEST.get('end_date','')
    export = int(request.REQUEST.get('export','2'))
    if page_num < 1:
        page_num = 1  
    fields = ''    
    #处理 导出文件
    if batch_id > 0 and export > 0: 
        try:
            select_sql = ''
            where_sql = ''
            card_data = []
            card_batch = CardBatch.objects.using('card').get(id = batch_id)
            key = card_batch.key     
            card_table =  Card.get_card_table_name(key)
            from settings import DATABASES
            import MySQLdb
            the_conn_str = DATABASES['card']
            port = int(the_conn_str.get('PORT',3306))
            conn = MySQLdb.connect(host=the_conn_str['HOST'],user=the_conn_str['USER'],passwd=the_conn_str['PASSWORD'], port=port, db=the_conn_str['NAME'],charset='utf8') 
            #conn = connections['card']
            cursor = conn.cursor()
            fields = [u'卡号',u'使用状态']
            if card_status == 3:
                select_sql = ",IF(c.`status`=0,'未使用',IF(c.`status`=1,'已领取',IF(c.`status` = 2,'已使用','删除')))"
                where_sql = ''
            elif card_status == 0:
                where_sql = ' AND c.`status` = 0'
                select_sql = ",'未使用' "                    
            elif card_status == 1:
                where_sql = ' AND c.`status` = 1'
                select_sql = ",'已领取' "
            elif card_status == 2:
                where_sql = ' AND c.`status` = 2'
                select_sql = ",'已使用',c.`use_count`, c.`use_time`,c.`player_id`, c.`server_id` "
                fields = [u'卡号','使用状态',u'使用次数',u'使用时间', u'角色ID', u'服务器']
                
            if start_date != '' and end_date != '':
                if card_status == 2:
                    where_sql += " AND c.`use_time` >= '%s' AND c.`use_time` <= '%s'"%(start_date,end_date)
                else:
                    where_sql += " AND c.`add_time` >= '%s' AND c.`add_time` <= '%s'"%(start_date,end_date)
                
            sql = "SELECT c.`number` %s FROM `%s` c WHERE 1=1 %s ORDER BY c.`id` "%(select_sql,card_table,where_sql)
            count_sql = "SELECT COUNT(*) FROM (%s) a" % sql
            cursor.execute(count_sql)
            count = cursor.fetchone()
            total_record = int(count[0])  
            file_name = [] 
            export_key = '%s_%s' % (card_batch.name,request.admin.id)
            card_export = CardExport(export_key,export)

            file_name.append('%s' % key)
            file_name = ''.join(file_name)
            if total_record > 0:  
                sql = "%s LIMIT %s,%s"%(sql,(page_num - 1) * page_size,page_size) 
                cursor.execute(sql)
                card_data = cursor.fetchall()
                
                if card_status == 2:
                    new_data = []
                    for item in card_data:
                        item = list(item)
                        if item[4]:
                            the_server = Server.objects.get(id = int(item[4]))
                            if the_server:
                                item[4] = the_server.name
                        new_data.append(item)
                    card_data = new_data
                try:
                    is_finish = False
                    de = total_record / page_size
                    if total_record % page_size >= 1:
                        total_page =  de + 1 
                    else:
                        total_page =  de
                    if page_num+1 > total_page:
                        is_finish = True                    
                    if is_chl == 1 and card_status == 0 and is_finish:
                        min_max_sql = "SELECT MIN(c.`id`), MAX(c.`id`) FROM `%s` c WHERE 1 = 1 %s "%(card_table,where_sql)
                        cursor.execute(min_max_sql)
                        min_max = cursor.fetchone()
                        if min_max[0] != None and min_max[1] != None:
                            min_val = int(min_max[0])             
                            max_val = int(min_max[1])
                            update_sql = "UPDATE `%s` SET `status` = 1 WHERE `id` >= %d AND `id` <= %d AND `status` = 0"%(card_table, min_val, max_val)
                            cursor.execute(update_sql)
                            conn.commit()
                except Exception,e:
                    print 'commit error',e 
        except Exception,e:
            traceback.print_exc()
            print 'export card error',e

        response = HttpResponse(json.dumps(card_export.gene_file(file_name,card_data, fields=fields, page_num=page_num, page_size=page_size, total_record=total_record)) )             
        return response