Exemple #1
0
 def export_product(modeladmin, request, queryset):
     response, writer = write_csv("products")
     writer.writerow(['SKU','Title','Category','Created','Dispaly date','URL to product','Price','RMB Cost',
         'Currency','SearchTerms','Status','Description','Brief','Filter Attributes','Source',
         'Factory','Offline_factory','Admin','Attributes'])
     for query in queryset:
         row = [
             str(query.sku),
             str(query.name),
             str(query.category),
             str(query.created),
             str(query.display_date),
             query.get_absolute_url(),
             str(query.price),
             str(query.total_cost),
             str('US'),
             str(query.keywords),
             query.get_status_display(),
             str(query.description),
             str(query.brief),
             str(query.filter_attributes),
             str(query.source),
             str(query.factory),
             str(query.offline_factory),
             str(query.admin),
             str(query.attributes),
         ]
         writer.writerow(row)
     return response
Exemple #2
0
def celebrity_export(request):
    data = {}
    #红人列表导出:
    if request.POST.get('type') == 'export_celebrits':
        try:
            from_time = eparse(request.POST.get('from_time'),
                               offset=" 00:00:00")
            to_time = eparse(request.POST.get('to_time'), offset=" 23:59:59")
        except Exception, e:
            print e

        response, writer = write_csv('celebrits')
        writer.writerow([
            'id', 'name', 'email', 'country', 'gender', 'birthday', 'level',
            'admin', 'created', 'is able', 'Blogs'
        ])

        celebrits = Celebrits.objects.filter(created__gte=from_time,
                                             created__lt=to_time)

        for celebrit in celebrits:
            admin = ''
            user = User.objects.filter(id=celebrit.admin_id).first()
            if user:
                admin = user.username

            gender = 'Woman'
            if celebrit.sex == 1:
                gender = 'Man'

            blogs = ''
            celebrityblogs = CelebrityBlogs.objects.filter(
                celebrity_id=celebrit.id)
            for celebrityblog in celebrityblogs:
                blogs += celebrityblog.url + ' , '

            row = [
                str(celebrit.id),
                str(celebrit.name),
                str(celebrit.email),
                str(celebrit.country),
                str(gender),
                str(celebrit.birthday),
                str(celebrit.level),
                str(admin),
                str(celebrit.created),
                str(celebrit.is_able),
                str(blogs),
            ]
            writer.writerow(row)
        return response
Exemple #3
0
    def export_category(modeladmin, request, queryset):
        response, writer = write_csv('category')
        writer.writerow(['Name','Link','On_menu','Parent_Catalog'])

        for query in queryset:
            link = str(query.link)
            id = str(query.id)
            absolute_link = settings.BASE_URL+ link + '-c-' + id

            parent_catalog = ''
            if query.parent_id:
                categorys = Category.objects.filter(id=query.parent_id)
                for category in categorys:
                    parent_catalog += category.name+'; '

            row = [
                str(query.name),
                str(absolute_link),
                str(query.on_menu),
                str(parent_catalog),
            ]
            writer.writerow(row)
        return response
Exemple #4
0
def add_spromotion_memcache_data(request):
    context = {}
    if request.POST.get('type') == 'sku_memcache_add':
        print '------'
        print 111
        skus = request.POST.get('skus', '').strip().split('\r\n')
        print skus
        if skus[0]:
            ids = Product.objects.filter(sku__in=skus, deleted=0).values_list('id')
            expired_time = int(time.time())
            for i in ids:
                spromotions = Spromotions.objects.filter(expired__gte=expired_time, product_id=i[0]). \
                    values('id', 'product_id', 'price', 'type', 'created', 'expired')

                for obj in spromotions:
                    if int(obj['price']) > 0:
                        cache_one = {}
                        cache_one['price'] = obj['price']
                        cache_one['created'] = time.mktime(obj['created'].timetuple())
                        cache_one['expired'] = time.mktime(obj['expired'].timetuple())

                        cache_key = 'spromotion_' + str(i[0])
                        cache = memcache.Client([settings.MEMCACHE_URL])
                        cache_data = {}
                        cache_data[obj['type']] = cache_one
                        cache_data = phpserialize.dumps(cache_data)
                        print cache.set(cache_key, cache_data)
                messages.success(request, u'缓存设置成功')

        else:
            messages.error(request, u'sku不能为空')

    elif request.POST.get('type') == 'do_promotion_insert':
        msg = ''
        reader = csv.reader(StringIO.StringIO(request.FILES['file'].read()))
        header = next(reader)
        std_header = [
            "SKU","Price","Catalog","Expired Time","Type"
        ]
        field_header = [
            "sku", 'price', 'catalog',"expired", "type"
        ]

        # 由于bom头的问题, 就不比较第一列的header了
        if header[1:] != std_header[1:]:
            messages.error(request, u"请使用正确的模板, 并另存为utf-8格式")
            return redirect('handle')

        types = {}
        types['vip'] = 0
        types['daily'] = 1
        types['cost']= 2
        types['outlet'] = 3
        types['special'] = 4
        types['activity'] = 5
        types['flash_sale'] = 6
        types['top_seller'] = 7
        types['bomb'] = -1

        for i, row in enumerate(reader, 2):
            res = dict(zip(field_header, row))

            order_dict = {}
            pro_id = Product.objects.filter(sku=res['sku']).values('id','price')
            order_dict['product_id'] = int(pro_id[0]['id'])
            order_dict['price'] = res['price']
            if(float(pro_id[0]['price']) < float(order_dict['price'])):
                pass
            else:
                order_dict['catalog'] = ''
                order_dict['price'] = float(res['price'])
                times = time_stamp6(res['expired'])
                order_dict['expired'] = times
                res['type'] = res['type'].lower()
                if res['type'] in types.keys():
                    order_dict['type'] = types[res['type']] or 1

                order_dict['admin'] = int(request.user.id)
                if order_dict['type'] == 0:
                    has = Spromotions.objects.filter(type=0,product_id=order_dict['product_id']).first()
                else:
                    has = Spromotions.objects.filter(product_id=order_dict['product_id']).exclude(type=0).first()

                if not has:
                    c = Spromotions.objects.create(price=order_dict['price'],
                                          type=order_dict['type'],
                                          # expired=order_dict['expired'],
                                          admin_id=order_dict['admin'],
                                          product_id=order_dict['product_id']
                                         )
                    if c:
                        sql = "UPDATE carts_spromotions SET expired="+str(order_dict['expired'])+" WHERE id="+str(c.id)
                        cursor = connection.cursor()
                        cursor.execute(sql)

                    cache_key ='spromotion_' + str(order_dict['product_id'])
                    cache= memcache.Client([settings.MEMCACHE_URL])
                    cache_data = {}
                    cache_data[order_dict['type']] = order_dict
                    cache_data =  phpserialize.dumps(cache_data)
                    print cache.set(cache_key,cache_data)
                else:
                    promo = Spromotions.objects.get(product_id=order_dict['product_id'])
                    promo.price=order_dict['price']
                    promo.type=order_dict['type']
                    # promo.expired=order_dict['expired']
                    promo.admin_id=order_dict['admin']
                    promo.product_id=order_dict['product_id']
                    c = promo.save()
                    if promo:
                        sql = "UPDATE carts_spromotions SET expired="+str(order_dict['expired'])+" WHERE id="+str(promo.id)
                        cursor = connection.cursor()
                        cursor.execute(sql)

                    cache_key ='spromotion_' + str(order_dict['product_id'])
                    cache= memcache.Client([settings.MEMCACHE_URL])
                    cache_data = {}
                    cache_data[order_dict['type']] = order_dict
                    cache_data =  phpserialize.dumps(cache_data)
                    print cache.set(cache_key,cache_data)
        messages.success(request, u'缓存设置成功')
    elif request.POST.get('type') == 'export_special_expired':
        response, writer = write_csv("special_expired_product")
        writer.writerow(["sku", "Orig_Price","Sale_Price","Created_Time", "Expired_Time", "Admin"])
        t = nowtime()
        queryset=Spromotions.objects.filter(expired__lt=t,product__status=1,product__visibility=1)
        for query in queryset:
            row = [
                str(query.product.sku),
                str(query.product.price),
                str(query.price),
                str(query.created),
                str(query.expired),
                str(),
            ]
            writer.writerow(row)
        return response
    
    #新品促销分类产品关联
    elif request.POST.get('type') == 'new_relate':
        #关联类型
        relate_type = request.POST.get('new_relate_selete','')
        if relate_type == 'one_week':
            relate_type = 1
        else:
            relate_type = 2
        #调用前台接口
        relate_type = demjson.encode(relate_type)

        url = settings.BASE_URL+'adminapi/new_relate'
        # url = 'http://local.oldchoies.com/adminapi/new_relate'
        req = urllib2.Request(url)
        response = urllib2.urlopen(req,urllib.urlencode({'relate_type':relate_type}))
       

        '''
        now = time.time()
        nowtime = now - (now % 86400) + time.timezone
        #关联一周数据操作
        if relate_type == 'one_week':
            #前一周时间
            lasttime = int(nowtime) - 7*86400
        else:
            #前两周时间
            lasttime = int(nowtime) - 14*86400
        #新品分类
        category = Category.objects.filter(link='new-product').first()
        #当前一周内上新的产品
        products = Product.objects.filter(visibility=1,display_date__gte=lasttime,display_date__lt=nowtime).all()
        #把该时间段内的新品关联到新品分类中
        for product in products:
            #更新产品分类关联表(手动创建的表)
            query, is_created = CategoryProduct.objects.get_or_create(category_id=category.id,product_id=product.id,deleted=0)
        '''

        messages.success(request, u"Relate "+relate_type+" new product Success!")


    #新品促销分类产品删除
    elif request.POST.get('type') == 'new_delete':
        category = Category.objects.filter(link='new-product').first()
        if category:
            #删除产品分类关联表(手动创建的表)
            result1 = CategoryProduct.objects.filter(category_id=category.id).delete()

            if result1:
                messages.success(request,u'Delete new product Success!')
                return redirect('cart_promition_data')
            else:
               messages.error(request ,u'Delete new product Failed!')
            return redirect('cart_promition_data') 
        else:
            messages.error(request ,u'无新品促销分类')
            return redirect('cart_promition_data')

    elif request.POST.get('type') == 'export_coupons_order':
        data = request.POST.get('coupons')
        print '---',data
        coupon = Coupons.objects.filter(code=data).first()
        if coupon:
            orders = Order.objects.filter(coupon_code=coupon.code).all()
            if orders:
                response, writer = write_csv("coupons_orders")
                writer.writerow(["Ordernum", "Amount", "Currency", "Created", "Payment_status"])
                for order in orders:
                    row = [
                        str(order.ordernum),
                        str(order.amount),
                        str(order.currency),
                        str(order.created),
                        str(order.payment_status),
                    ]
                    writer.writerow(row)
                return response
            else:
                messages.error(request,u'折扣号尚未使用')
        else:
            messages.error(request,u'折扣号不存在')
    else:
        context = {}
    return render(request, 'cart_handle.html', context)
Exemple #5
0
            ]
            writer.writerow(row)
        return response

    #红人订单产品导出:
    elif request.POST.get('type') == 'export_celebrity_order_products':
        try:
            from_time = eparse(request.POST.get('from_time'),
                               offset=" 00:00:00")
            from_time = time_stamp(from_time)
            to_time = eparse(request.POST.get('to_time'), offset=" 23:59:59")
            to_time = time_stamp(to_time)
        except Exception, e:
            print e

        response, writer = write_csv('celebrits_order_products')
        writer.writerow([
            'Email', 'Name', 'Created', 'Ordernum', 'Verify_date', 'SKU',
            'Price', 'Admin'
        ])

        query = "SELECT c.email,c.name,o.created,o.ordernum,o.verify_date,i.sku,i.product_id,c.admin_id FROM celebrities_celebrits c,orders_order o,orders_orderitem i WHERE c.customer_id=o.customer_id AND o.id=i.order_id AND (o.payment_status='success' or o.payment_status='verify_pass') AND i.status != 'cancel' AND o.created >=" + str(
            from_time) + " AND o.created <" + str(
                to_time) + " ORDER BY o.created"
        # query = "select id,name ,email from celebrities_celebrits where id < 10"
        cursor = connection.cursor()
        cursor.execute(query)
        res = cursor.fetchall()
        for i in res:
            created = ''
            if i[2]:
Exemple #6
0
def customer_points(request):
    data = {}
    # print '---', request.user.id
    if request.POST.get('type') == 'points':
        emails = request.POST.get('customer_points', '').strip().split('\r\n')
        points = request.POST.get('points', '')
        record = request.POST.get('record', '')
        user_id = request.user.id
        #验证是否为纯数字
        if points.isdigit():
            points = int(points)
            #积分不能为0
            if points:
                for email in emails:
                    res = validateEmail(email)
                    if res:

                        arr = Customers.objects.filter(email=email,
                                                       deleted=0).get()
                        if arr:
                            Point_Records.objects.create(customer_id=arr.id,
                                                         amount=points,
                                                         type=record,
                                                         admin_id=user_id,
                                                         status='activated')
                            if arr.points:
                                points = arr.points + points
                            else:
                                points = points
                            Customers.objects.filter(id=arr.id).update(
                                points=points)
                            messages.success(request, u"操作成功")
                        else:
                            messages.error(request, u"用户%s不存在 " % email)

                    else:
                        messages.error(request, u"email格式不正确,请核对:%s" % email)
            else:
                messages.error(request, u"积分不能为0")
        else:
            messages.error(request, u"积分内容输入不正确,请核对")
    elif request.POST.get('type') == 'admin':
        emails = request.POST.get('email', '').strip().split('\r\n')
        admin = request.POST.get('admin', '')
        admin_validate = validateEmail(admin)
        if admin_validate:
            try:
                arr = User.objects.filter(email=admin).get()
            except User.DoesNotExist:
                messages.error(request, u"负责人%s不存在 " % admin)
            else:
                for email in emails:
                    email_validate = validateEmail(email)
                    if email_validate:
                        Customers.objects.filter(
                            email=email,
                            deleted=0).update(users_admin_id=arr.id)
                        messages.success(request, u"操作成功 ")
                    else:
                        messages.error(request, u"用户%s不存在 " % email)
        else:
            messages.error(request, u"请核对admin邮箱 ")
    elif request.POST.get('type') == 'email':
        emails = request.POST.get('email', '').strip().split('\r\n')
        print '-----'
        for email in emails:
            email_validate = validateEmail(email)
            if email_validate:
                try:
                    query = Customers.objects.filter(email=email).get()

                except Customers.DoesNotExist:
                    #email不存在
                    Customers.objects.create(email=email, deleted=0, flag=4)
                    messages.success(request, u"操作成功")
                else:
                    #email存在
                    if query:
                        #deleted=1
                        if query.deleted:
                            messages.error(
                                request,
                                u"注意:用户%s曾经被删除过,现在未对其进行任何操作 !!" % email)
                        #deleted=0
                        else:
                            messages.error(request, u"用户%s已存在 " % email)

            else:
                messages.error(request, u"请核对输入的email %s " % email)

    #按照积分数范围/是否fb注册导出用户
    elif request.POST.get('type') == 'export_point_customers':
        """时间不输入默认为当天 """
        try:
            from_time = eparse(request.POST.get('from_time'),
                               offset=" 00:00:00")
            from_time = time_stamp(from_time)
            to_time = eparse(request.POST.get('to_time'), offset=" 23:59:59")
            to_time = time_stamp(to_time)
            print from_time
            print to_time
        except Exception, e:
            messages.error(request, u'请输入正常的时间格式')

        point_from = request.POST.get('point_from', '0')
        if point_from:
            point_from = int(point_from)
        else:
            point_from = 0
        point_to = request.POST.get('point_to', '0')
        if point_to:
            point_to = int(point_to)
        else:
            point_to = 1000000

        submit = request.POST.get('submit', 'Export')
        is_facebook = int(request.POST.get('is_facebook', '0'))

        print is_facebook
        if is_facebook == 1:
            customers = Customers.objects.filter(created__gte=from_time,
                                                 created__lt=to_time,
                                                 points__gte=point_from,
                                                 points__lt=point_to,
                                                 is_facebook=1)
            print customers
        else:
            customers = Customers.objects.filter(created__gte=from_time,
                                                 created__lt=to_time,
                                                 points__gte=point_from,
                                                 points__lt=point_to)
            print customers

        if submit == 'Export':
            response, writer = write_csv('customers')
            writer.writerow(
                ['created', 'email', 'firstname', 'points', 'country'])

            for customer in customers:
                country = ''
                if customer.country:
                    country = customer.country
                else:
                    address = Address.objects.filter(
                        customer_id=customer.id).first()
                    if address:
                        country = address.country
                row = [
                    str(customer.created),
                    str(customer.email),
                    str(customer.firstname),
                    str(customer.points),
                    str(country),
                ]
                writer.writerow(row)
            return response

        else:
            response, writer = write_csv('customers')
            writer.writerow(['email', 'created', 'ip_country'])
            for customer in customers:
                row = [
                    str(customer.email),
                    str(customer.created),
                    str(customer.ip_country),
                ]
                writer.writerow(row)
            return response
Exemple #7
0
            from_time = eparse(request.POST.get('from_time'),
                               offset=" 00:00:00")
            from_time = time_stamp(from_time)
            to_time = eparse(request.POST.get('to_time'), offset=" 23:59:59")
            to_time = time_stamp(to_time)
            print from_time
            print to_time
        except Exception, e:
            messages.error(request, u'请输入正常的时间格式')

        select_type = request.POST.get('select_type', 'register')
        country_code = request.POST.get('country_code', '')

        print select_type
        if select_type == 'register':
            response, writer = write_csv('Register_customers')
            writer.writerow(['email', 'country', 'created', 'orders'])

            if country_code:
                customers = Customers.objects.filter(
                    created__gte=from_time,
                    created__lt=to_time,
                    country=country_code,
                    flag__in=[0, 3]).order_by('id')
            else:
                customers = Customers.objects.filter(
                    created__gte=from_time,
                    created__lt=to_time,
                    flag__in=[0, 3]).order_by('id')

            for customer in customers: