Ejemplo n.º 1
0
    def create(cart_id, product_id, quantity):
        """ Create a new cart """
        cart_item = CartItem(cart_id=cart_id,
                             product_id=product_id,
                             quantity=quantity)

        return cart_item.save()
Ejemplo n.º 2
0
def add_to_cart(request):
    postdata = request.POST.copy()
    # Получаю название заказанного продукта
    model_id = postdata.get('model_id','')
    quantity = 1
    product_in_cart = False
    # Получаю заказанный продукт
    p = get_object_or_404(Model, id=model_id)
    # Если клиент уже есть в базе
    if CartItem.objects.filter(cart_id = _cart_id(request)):
        # Получаю все продукты в корзине
        cart = CartItem.objects.get(cart_id = _cart_id(request))
        cart_products = CartProduct.objects.filter(cartitem=cart.id)
        # Проверяю есть ли такой продукт уже в корзине
        for cart_item in cart_products:
            if cart_item.product_id == p.id:
                # Если уже есть то обновляю количество
                ttt = CartProduct.objects.get(cartitem=cart,product=p.id)
                ttt.augment_quantity(quantity)
                product_in_cart = True
        # Если нету то добавляю
        if not product_in_cart:
            cart = CartItem.objects.get(cart_id = _cart_id(request))
            cp = CartProduct(cartitem = cart, product = p)
            cp.save()
    # Если клиента нету в базе то создаю его
    else:
        ci = CartItem()
        ci.cart_id = _cart_id(request)
        ci.save()

        # И добавляю его заказ в корзину
        cart = CartItem.objects.get(cart_id = _cart_id(request))
        cp = CartProduct(cartitem = cart, product = p)
        cp.save()
Ejemplo n.º 3
0
def add_to_cart(request, id):
    product = get_object_or_404(Product, pk=id)
    cartItem = CartItem(
        user=request.user,
        product=product,
        quantity=1
    )
    cartItem.save()
    return redirect(reverse('cart'))
Ejemplo n.º 4
0
def create_user():
    for Model in (Role, User, UserRoles, Item, Customer, Cart, CartItem):
        Model.drop_table(fail_silently=True)
        Model.create_table(fail_silently=True)
    user_datastore.create_user(
        email='*****@*****.**',
        password='******'
    )
    item1 = Item(name='notebook', stock=300, price=500)
    item1.save()
    item2 = Item(name='TV', stock=250, price=200)
    item2.save()
    item3 = Item(name='flash', stock=950, price=10)
    item3.save()
    item4 = Item(name='smartphone', stock=455, price=150)
    item4.save()
    item5 = Item(name='camera', stock=50, price=550)
    item5.save()
    customer = Customer(name='John', birthday=date(1990, 1, 15))
    customer.save()
    cart1 = Cart(customer=customer.id)
    cart1.save()
    cartitem = CartItem(cart=cart1, item=item1, quantity=3)
    cartitem.save()
    customer = Customer(name='Olivier', birthday=date(1995, 2, 22))
    customer.save()
    cart2 = Cart(customer=customer.id)
    cart2.save()
    cartitem = CartItem(cart=cart2, item=item5, quantity=45)
    cartitem.save()
Ejemplo n.º 5
0
def add_to_cart(request, id):
    add_donation = get_object_or_404(donation, pk=id)
    quantity = int(request.POST.get('quantity'))
    try:
        cartItem = CartItem.objects.get(user=request.user,
                                        donation=add_donation)
        cartItem.quantity += quantity
    except CartItem.DoesNotExist:
        cartItem = CartItem(
            user=request.user,
            donation=add_donation,
            quantity=quantity,
        )
    cartItem.save()
    return redirect(reverse('cart_user'))
Ejemplo n.º 6
0
def add_to_cart(request, id):
    product = get_object_or_404(Product, pk=id)
    quantity = int(request.POST.get('quantity'))

    try:
        cartItem = CartItem.objects.get(user=request.user, product=product)
        cartItem.quantity += quantity
    except CartItem.DoesNotExist:

        cartItem = CartItem(
            user=request.user,
            product=product,
            quantity=quantity
        )
    cartItem.save()
    return redirect(reverse('cart'))
Ejemplo n.º 7
0
 def post(self):
     status_code = 200
     parser = reqparse.RequestParser()
     parser.add_argument("user_email")
     parser.add_argument("mobile")
     parser.add_argument("restaurant_id")
     parser.add_argument("spend_hour")
     parser.add_argument('table', action='append')
     parser.add_argument('selected_item', action='append')
     args = parser.parse_args()
     user_exist = User.query.filter_by(email=args['user_email'], user_type='customer').all()
     if not user_exist:
         user = User(password='******', email=args['user_email'], user_type='customer')
         db.session.add(user)
     try:
         order_obj = Order(user_email=args['user_email'], mobile=args['mobile'], restaurant_id=args['restaurant_id'],
                           spend_hour=args['spend_hour'], active=True)
         for table_id in args.table:
             table_obj = Table.query.get(int(table_id))
             order_obj.order_tables.append(table_obj)
         db.session.add(order_obj)
         db.session.commit()
         # Add Menu Items
         for item in args.selected_item:
             item = json.loads(item)
             cart_item_obj = CartItem(order_id=order_obj.id, menu_id=item['item_id'], count=item['item_count'])
             db.session.add(cart_item_obj)
         db.session.commit()
         result = {'Item Name': order_obj.id}
     except:
         status_code = 404
         result = {'message': 'There is some error'}
     return result, status_code
Ejemplo n.º 8
0
def new_cart(request, product_ids=[]):
    """
    Initiate a purchase using the selected product and processing options.
    """    
    assert(len(product_ids))
    CartItem.objects.filter(session_key=request.session.session_key).delete()   
    item_count = 1
    for prodid in product_ids: 
        item = CartItem(
            number = item_count,
            session_key = request.session.session_key,
            product = Product.objects.get(pk=prodid),
            quantity = 1
        )
        item.save()
        item_count += 1
Ejemplo n.º 9
0
def add_to_cart(request):
    postdata = request.POST.copy()

    # get product slug from post data, return blank if empty
    product_slug = postdata.get('product_slug', '')
    # get quantity added, return 1 if empty
    quantity = postdata.get('quantity', 1)
    # fetch the product or return a missing page error
    p = get_object_or_404(Product, slug=product_slug)
    # get products in cart
    cart_products = get_cart_items(request)
    product_in_cart = False

    # check to see if item is already in cart
    for cart_item in cart_products:
        if cart_item.product.id == p.id:
            # update the quantity if found
            cart_item.augment_quantity(quantity)
            product_in_cart = True

    if not product_in_cart:
        # create and save a new cart item
        ci = CartItem()
        ci.product = p
        ci.quantity = quantity
        ci.cart_id = _cart_id(request)
        ci.save()
Ejemplo n.º 10
0
Archivo: views.py Proyecto: madrize/ecs
def add_to_cart(request, failed_url="/", cart_url="/shopping-cart/"):
    """
    Adds an item to cart
    """

    if request.method == "POST":
        # form posted, get form info
        data = request.POST.copy()
        quantity = data.get('quantity', '')
        product_slug = data.get('product_slug', '')
        p = get_object_or_404(Product, slug=product_slug)
        # add item to cart
        try:
            item = CartItem.objects.get(item=p)
        except:
            item = None
        # if this product isnt already in the cart...
        if item is None:
            # create new Cart Item object
            item = CartItem(owner=request.user, item=p, quantity=quantity)
            item.save()
        else:
            # increase the quantity
            item.quantity = item.quantity + int(quantity)
            item.save()
    else:
        # form isnt valid
        return HttpResponseRedirect(failed_url)

    # done !
    # redirect to user's cart
    return HttpResponseRedirect(cart_url)
Ejemplo n.º 11
0
def add_to_cart(request, product=None):
    """
    function that takes a POST request and adds a product instance to the current customer's shopping cart
    """
    post_data = request.POST.copy()
    # quantity = post_data.get('quantity', 1)  # get quantity added, return 1 if empty
    quantity = 1
    if not product:
        product_slug = post_data.get(
            'product_slug',
            '')  # get product slug from post data, return blank if empty
        product = get_object_or_404(
            Product, slug=product_slug
        )  # fetch the product or return a missing page error
    cart_products = get_cart_items(request)  # get products in cart
    product_in_cart = False
    # check to see if item is already in cart
    for cart_item in cart_products:
        if cart_item.product.id == product.id:
            cart_item.augment_quantity(
                quantity)  # update the quantity if found
            product_in_cart = True
            break
    if not product_in_cart:
        ci = CartItem()  # create and save a new cart item
        ci.product = product
        ci.quantity = quantity
        ci.cart_id = _cart_id(request)
        ci.save()
Ejemplo n.º 12
0
def add_to_cart(request):
	postdata = request.POST.copy()

	# get product slug from post data, return blank if empty
	product_slug = postdata.get('product_slug', '')

	#get quantity added, return 1 is empty
	quantity = postdata.get('quantity', 1)

	# fetch the product or return a missing page error
	p = get_object_or_404(Product, slug = product_slug)

	#get products in cart
	cart_products = get_cart_items(request)
	product_in_cart = False

	for cart_item in cart_products:
		if cart_item.product.id == p.id:
			# update the quantity if found
			cart_item.augment_quantity(quantity)
			product_in_cart = True
	if not product_in_cart:
		# create and save a new cart item
		ci = CartItem()
		ci.product = p
		ci.quantity = quantity
		ci.cart_id = _cart_id(request)
		ci.user = request.user
		ci.save()
Ejemplo n.º 13
0
def save_cart():
    if request.method == 'POST' and current_user.is_authenticated:
        json_data = request.get_json()
        current_user.cart = [
            CartItem(product=key, quantity=value)
            for key, value in json_data.items()
        ]
        current_user.save()
    return 'success'
Ejemplo n.º 14
0
def cart(bot, update, args):
    # Function to review all products and quantity by Cart id #
    try:
        cart_id = args[0]
        cartitems = (CartItem.select().join(Cart).where(Cart.id == cart_id))
        cartitems = ', '.join([str(cartitem) for cartitem in cartitems])
        quantities = (CartItem.select().join(Cart).where(Cart.id == cart_id))
        quantities = ', '.join(
            [str(quantity.quantity) for quantity in quantities])
        bot.send_message(
            chat_id=update.message.chat_id,
            text='Your Cart includes the following products: {} '
            'in quantities: {} respectively. '
            '\nIf you want to continue shopping, please use /guidance'
            '\nIf you want to know Your Cart Amount, please use /buy'.format(
                cartitems, quantities))
    except IndexError:
        bot.send_message(chat_id=update.message.chat_id,
                         text='Please use proper format: '
                         '/cart Your Cart # ')
Ejemplo n.º 15
0
 def add(self, stock_item, unit_price, quantity=1):
     try:
         cart_item = CartItem.objects.get(cart=self.cart,
                                          stock_item=stock_item)
         cart_item.quantity = quantity
         cart_item.save()
     except CartItem.DoesNotExist:
         cart_item = CartItem()
         cart_item.cart = self.cart
         cart_item.stock_item = stock_item
         cart_item.unit_price = unit_price
         cart_item.quantity = quantity
         cart_item.save()
Ejemplo n.º 16
0
def add_to_cart(request):
    postdata = request.POST.copy()
    try:
        flavor_id = int(postdata.get('flavor_id', False))
        volume_id = int(postdata.get('volume_id', False))
        conc_id = int(postdata.get('conc_id', False))
        assert volume_id and (volume_id in request.volumes_data.keys()
                              ), "You are not allowed to access this page"
    except (ValueError, TypeError) as e:
        raise Http404("Sorry! Failed to add product to cart")
    except AssertionError as e:
        raise Http404(e)
    # get quantity added , return 1 if empty
    quantity = int(postdata.get('quantity', 1))
    #fetch the product or return a missing page error
    p = get_object_or_404(ProductVariant,
                          vol_id=volume_id,
                          conc_id=conc_id,
                          flavor_id=flavor_id,
                          active=True,
                          product_tmpl_id__type="product")
    # get products in cart
    cart_products = get_cart_items(request)
    # Check to see if item already in cart
    product_in_cart = False
    available_qty = get_products_availability(p.id)[str(p.id)]
    added = False
    cart_quantity = 0
    for cart_item in cart_products:
        if cart_item.product_id == p.id:
            #upddate the quantity if found
            product_in_cart = True
            cart_quantity = cart_item.quantity + quantity
            if cart_quantity <= available_qty.get('virtual_available', 0):
                cart_item.augment_quantity(quantity)
                added = True

    if not product_in_cart:
        cart_quantity = quantity
        if cart_quantity <= available_qty.get('virtual_available', 0):
            #create and save a new cart item
            ci = CartItem()
            ci.product_id = p.id
            ci.quantity = quantity
            ci.cart_id = _cart_id(request)
            if request.user.is_authenticated:
                ci.user_id = request.user
            ci.save()
            added = True

    return available_qty, cart_quantity, added
Ejemplo n.º 17
0
Archivo: views.py Proyecto: madrize/ecs
def add_to_cart(request,
                failed_url="/",
                cart_url="/shopping-cart/"):
    """
    Adds an item to cart
    """
    
    if request.method == "POST":
        # form posted, get form info
        data = request.POST.copy()
        quantity = data.get('quantity','')
        product_slug = data.get('product_slug','')
        p = get_object_or_404(Product,slug=product_slug)
        # add item to cart
        try:
            item = CartItem.objects.get(item=p)
        except:
            item = None
        # if this product isnt already in the cart...
        if item is None:
            # create new Cart Item object
            item = CartItem(owner=request.user, item=p, quantity=quantity)
            item.save()
        else:
            # increase the quantity
            item.quantity = item.quantity + int(quantity)
            item.save()
    else:
        # form isnt valid
        return HttpResponseRedirect(failed_url)
    
    # done !
    # redirect to user's cart
    return HttpResponseRedirect(cart_url)
Ejemplo n.º 18
0
def add_to_cart(request):
    """ function that takes a POST request and adds a product instance to the current customer's shopping cart """
    post_data = request.POST.copy()
    # get product slug from post data, return blank if empty
    #product_slug = post_data.get('product_slug','')
    # get quantity added, return 1 if empty
    quantity = post_data.get('quantity',1)
    product_id = post_data.get('product_id', 0)
    product = get_object_or_404(Product, pk = product_id)
    # fetch the product or return a missing page error
    cart_products = get_cart_items(request)
    product_in_cart = False
    # check to see if item is already in cart
    for cart_item in cart_products:
        if cart_item.product.id == product.id:
            # update the quantity if found
            cart_item.augment_quantity(quantity)
            product_in_cart = True
    if not product_in_cart:
        # create and save a new cart item
        ci = CartItem()
        ci.product = product
        ci.quantity = quantity
        ci.cart_id = _cart_id(request)
        ci.save()
Ejemplo n.º 19
0
def add(bot, update, args):
    # Function to add to certain Cart # product and quantity
    try:
        if len(args) == 3:
            cart_id = args[0]
            cart = Cart.select().where(Cart.id == cart_id)[0]
            item_name = args[1]
            item = Item.select().where(Item.name == item_name)[0]
            quantity = args[2]
            cart_item = CartItem(cart=cart, item=item, quantity=quantity)
            cart_item.save()
            bot.send_message(
                chat_id=update.message.chat_id,
                text='{}, thanks for shopping with us! '
                'Product: {} in quantity of: {} added to Your Cart {}.'
                '\nIf you need help, please use /guidance'.format(
                    cart.customer, cart_item.item, cart_item.quantity,
                    cart_id))
    except IndexError:
        bot.send_message(chat_id=update.message.chat_id,
                         text='Please use proper format: '
                         '/add Your Cart # Product name Quantity ')
Ejemplo n.º 20
0
 def add(self, stock_item, unit_price, quantity=1):
     try:
         cart_item = CartItem.objects.get(cart=self.cart, stock_item=stock_item)
         cart_item.quantity = quantity
         cart_item.save()
     except CartItem.DoesNotExist:
         cart_item = CartItem()
         cart_item.cart = self.cart
         cart_item.stock_item = stock_item
         cart_item.unit_price = unit_price
         cart_item.quantity = quantity
         cart_item.save()
Ejemplo n.º 21
0
    def testQuantity(self):
        # test that quantity must be greater than zero
        for quantity in [0, -1, -18]:
            with self.assertRaises(ValidationError) as cm:
                create_cart_item(quantity=quantity)
            self.assertIn("Ensure this value is greater than or equal to 1", str(cm.exception))

        # test that quantity defaults to 1
        product = create_product()
        ci = CartItem(product=product, cart_id=CartItem.generate_cart_id())
        self.assertEqual(1, ci.quantity)

        # test that the quantity cannot be nulled out
        with self.assertRaises(ValidationError) as cm:
            create_cart_item(quantity=None)
        self.assertIn("This field cannot be null", str(cm.exception))
Ejemplo n.º 22
0
def add_to_cart(request):
    postdata = request.POST.copy()
    product_slug = postdata.get('product_slug', '')
    quantity = postdata.get('quantity', 1)
    p = get_object_or_404(Product, slug=product_slug)
    cart_products = get_cart_items(request)
    product_in_cart = False
    for cart_item in cart_products:
        if cart_item.product.id == p.id:
            cart_item.augment_quantity(quantity)
            product_in_cart = True
    if not product_in_cart:
        ci = CartItem()
        ci.product = p
        ci.quantity = quantity
        ci.cart_id = _cart_id(request)
        ci.save()
Ejemplo n.º 23
0
Archivo: cart.py Proyecto: deusesx/VDom
def add_to_cart(request):
    postdata = request.POST.copy()
    product_slug = postdata.get('product_slug', '')
    quantity = postdata.get('quantity', 1)
    p = get_object_or_404(Product, slug=product_slug)
    cart_products = get_cart_items(request)
    product_in_cart = False
    for cart_item in cart_products:
        if cart_item.product.id == p.id:
            cart_item.augment_quantity(quantity)
            product_in_cart = True
    if not product_in_cart:
        ci = CartItem()
        ci.product = p
        ci.quantity = quantity
        ci.cart_id = _cart_id(request)
        ci.save()
Ejemplo n.º 24
0
    def testCartId(self):
        # def test that every character that can go into a cart-id can be saved to the database field
        for char in CartItem.CART_ID_CHARS:
            cart_id = char
            ci = create_cart_item(cart_id=cart_id)
            self.assertEqual(cart_id, ci.cart_id)

        # test that the cart id cannot be none, and has no default
        with self.assertRaises(ValidationError) as cm:
            ci = CartItem(cart_id=None, product=create_product(), quantity=2)
            ci.full_clean()
        self.assertIn("This field cannot be null", str(cm.exception))

        with self.assertRaises(ValidationError) as cm:
            ci = CartItem(product=create_product(), quantity=2)
            ci.full_clean()
        self.assertIn("This field cannot be blank", str(cm.exception))
Ejemplo n.º 25
0
def create_cart_item(**kwargs):
    cart_id = kwargs.pop('cart_id', None)

    if not cart_id:
        cart_id = CartItem.generate_cart_id()

    product = kwargs.pop('product', None)

    if not product:
        product = create_product()

    quantity = kwargs.pop('quantity', 1)
    if len(kwargs) > 0:
        raise Exception("Extra keyword args in create_cart_item: %s" % kwargs)

    ci = CartItem(cart_id=cart_id, product=product, quantity=quantity)
    ci.full_clean()
    ci.save()
    return ci
Ejemplo n.º 26
0
def add_to_cart(request):
    postdata = request.POST.copy()
    # product_slug = postdata.get('product_slug', '')
    quantity = postdata.get('quantity', 1)
    id = postdata.get('product_id')
    # p = get_object_or_404(Product, slug = product_slug)
    p = get_object_or_404(Product, id=id)
    cart_products = get_cart_items(request)
    product_in_cart = False
    for cart_item in cart_products:
        if cart_item.product.id == p.id:
            cart_item.augment_quantity(quantity)
            product_in_cart=True
            return JsonResponse({'product in cart':product_in_cart})
    if not product_in_cart:
        ci = CartItem()
        ci.product = p
        ci.quantity = quantity
        ci.cart_id = _cart_id(request)
        ci.save()
        return JsonResponse({'product in cart': product_in_cart, 'cart_id': ci.cart_id})
Ejemplo n.º 27
0
def cart():
    if request.method == 'POST':
        token = request.form.get('token', '')
        post_id = request.form.get('postId', '')
        user_found = User.get_by_token(token)
        if user_found:
            post_found = Post.get_valid_by_id(post_id)
            if post_found:
                if int(post_id) not in [
                        item.post_id for item in user_found.cart
                ]:
                    """接收参数post_id为字符串,sql查询时会自动转为数字,但在比较时需要转为数字"""
                    # noinspection PyBroadException
                    try:
                        cart_item_ = CartItem(openid=user_found.openid,
                                              post_id=post_id)
                        db.session.add(cart_item_)
                        db.session.commit()
                    except Exception:
                        abort(500)
                    else:
                        return jsonify({'cartItemId': cart_item_.id}), 201
                else:
                    return jsonify({'errMsg': 'Item exists'}), 400
            else:
                return jsonify({'errMsg': 'Invalid postId'}), 404
        else:
            return jsonify({'errMsg': 'Invalid token'}), 403

    elif request.method == 'GET':
        token = request.args.get('token', '')
        if token:
            user_found = User.get_by_token(token)
            if user_found:  # 根据token查找到用户
                cart_items = CartItem.get_by_openid(
                    openid=user_found.openid)  # 按添加顺序倒序
                # cart_items = user_found.cart
                cart_list = list()
                if cart_items:
                    for item in cart_items:
                        cart_item = item.get_cart_item_info()
                        cart_list.append(cart_item)

                    return jsonify({
                        'msg': 'Request: ok',
                        'cartList': cart_list
                    })
                else:
                    return jsonify({'msg': 'Request: ok'}), 204
            else:  # token过期(多端登录)或用户不存在(bug)
                return jsonify({'errMsg': 'Overdue token'}), 403
        else:
            return jsonify({'errMsg': 'Need token'}), 400

    elif request.method == 'DELETE':
        token = request.form.get('token', '')
        delete_list = request.form.get('deleteList', '')
        # logger.info(delete_list)
        if delete_list:
            delete_list = delete_list.split(',')  # 参数为字符串,拆分得到字符数组
            # noinspection PyBroadException
            try:
                for item_id in delete_list:
                    cart_item = CartItem.get_by_id(item_id=item_id)
                    if cart_item:
                        if token == cart_item.user.token:
                            db.session.delete(cart_item)
                            db.session.commit()
                        else:
                            return jsonify({'errMsg': 'Invalid token'}), 403
                    else:
                        return jsonify({'errMsg': 'CartItem not found'}), 204
            except Exception:
                abort(500)
            else:
                return jsonify({'msg': 'Delete: ok'})
        else:
            return jsonify({'errMsg': 'Need cart item id'}), 400
Ejemplo n.º 28
0
 def testGenerateCartId(self):
     for i in xrange(500):
         cart_id = CartItem.generate_cart_id()
         self.assertIsNotNone(cart_id)
         self.assertEqual(50, len(cart_id))