示例#1
0
def add_to_cart(request):
    """
    Add product to cart
    """
    product_id = int(request.POST['product_id'])

    # Checking if user already has cart in session
    # otherwise create a new cart for the user
    if 'cart_id' in request.session:
        cart_id = int(request.session['cart_id'])
        cart = Cart.get_cart(cart_id)
    else:
        cart = Cart.get_cart()
        request.session['cart_id'] = cart.id

    try:
        quantity = int(request.POST['quantity'])
        if quantity > 0:
            cart.add_item(product_id, quantity, request.user)
        else:
            raise ValueError()
    except ValueError:
        return HttpResponseBadRequest('Product quantity is not correct, please enter one or more products in numbers.')

    if request.is_ajax():

        return render(request, 'sales/cart_basket.html', {'cart': cart})

    #return HttpResponseRedirect(reverse('sales_checkout_cart'))
    return render(request, 'sales/cart_basket.html', {'cart': cart})
示例#2
0
def add2Cart(request, cuisineID):
    # FIXME: 如果餐厅在“打烊”状态,应该无法添加到购物车,返回错误
    cart = request.session.get('cart', None)
    if cart is None:
        cart = Cart()
    res = {'size':cart.add(int(cuisineID))}
    request.session['cart'] = cart
    return HttpResponse(json.dumps(res))
示例#3
0
文件: views.py 项目: onlyanyz/mysite
def add_to_cart(request,id):
    product=Product.objects.get(id=id)
    cart=request.session.get("cart",None)
    if not cart:
        cart=Cart()
        request.session["cart"]=cart
    cart.add_product(product)
    request.session["cart"]=cart
    # return view_cart(request)
    return HttpResponseRedirect("/depotapp/cart/view/")
示例#4
0
 def _create_cart_in_database(self, creation_date=datetime.datetime.now(), 
         checked_out=False):
     """
         Helper function so I don't repeat myself
     """
     cart = Cart()
     cart.creation_date = creation_date
     cart.checked_out = False
     cart.save()
     return cart
示例#5
0
 def on_post(self, req, resp, userId):
     try:
         cart = Cart(userId=userId)
         carts = Cart.objects(userId=userId)
         if len(carts) == 0:
             cartResp = cart.save()
             ResponseUtil.makeBody(resp, cartResp.to_json())
         else:
             ResponseUtil.makeBody(resp, carts[0].to_json())
     except Exception as e:
         ResponseUtil.error(e, resp)
示例#6
0
文件: tests.py 项目: n3n/django-cart
 def test_update_cart(self):
     user = self._create_user_in_database()
     cart = Cart(self.request)
     cart.new(self.request)
     cart.add(product=user, quantity=3, unit_price=100)
     cart.update(product=user, quantity=2, unit_price=200)
     self.assertEquals(cart.summary(), 400)
     self.assertEquals(cart.count(), 2)
示例#7
0
文件: tests.py 项目: n3n/django-cart
 def test_add_cart_quantity_equals_zero(self):
     user = self._create_user_in_database()
     cart = Cart(self.request)
     cart.new(self.request)
     cart.add(product=user, quantity=1, unit_price=100)
     self.assertEquals(cart.item_count(), 1)
     cart.add(product=user, quantity=-1, unit_price=100)
     self.assertEquals(cart.item_count(), 0)
示例#8
0
def get_cart(request):
    if 'cart_hash' in request.session:
        cart_hash = request.session['cart_hash']
        try:
            return Cart.objects.get(hash=cart_hash)
        except Cart.DoesNotExist:
            pass
    cart = Cart()
    cart.hash = random_str(25)
    cart.save()
    request.session['cart_hash'] = cart.hash
    return cart
示例#9
0
def create_cart(request):
    """
    Creates a cart for the current session and/or user.
    """
    if not request.session.exists(request.session.session_key):
        request.session.create()
    cart = Cart(session=request.session.session_key)
    if request.user.is_authenticated():
        cart.user = request.user

    cart.save()
    return cart
示例#10
0
文件: app.py 项目: jpsca/monolith
def cart_remove():
    product_id = request.args.get("product_id", type=int)
    product = Product.first(id=product_id)
    if not product:
        return ""
    Cart.remove(product)

    return render_update(
        "cart/remove.html",
        counter=Cart.count(),
        cart_items=Cart.get_all(),
    )
示例#11
0
def insertcart(request):
    x = request.GET["pid"]
    qt = request.GET["qt"]
    user = User.objects.get(id=request.session.get("_auth_user_id"))
    un = str(user.username)
    pr = Product.objects.get(pid=x)
    a = int(str(x))
    b = int(str(qt))
    c = un
    d = float(pr.pcost)
    e = int(str(qt)) * float(pr.pcost)
    ct = Cart(username=c, pid=a, units=b, unitprice=d, tuprice=e)
    ct.save()
    return render(request, 'insertcart.html')
示例#12
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()
示例#13
0
def add_cart():
    try:
        request_data = request.get_json()
        u_id = request_data["u_id"]
        g_id = request_data["goods_id"]
    except:
        return jsonify({
            'status': 400,
            'msg': '请求参数错误'
        })
    try:
        cart = db.session.query(Cart).filter(Cart.u_id == u_id, Cart.goods_id == g_id)
        if cart.count() == 0:
            g_num = 1
            is_select = False
            new_cart = Cart(u_id=u_id, goods_id=g_id, c_goods_num=g_num, c_is_selected=is_select)
            db.session.add(new_cart)
            db.session.commit()
        else:
            current_cart = cart.first()
            current_cart.c_goods_num += 1
            db.session.commit()
        return jsonify({
            'status': 200,
            'msg': '添加购物车成功'
        })
    except:
        return jsonify({
            'status': 300,
            'msg': "添加购物车失败"
        })
示例#14
0
def addcart():
    data = request.form
    product = Product.query.filter_by(id=int(data['product_id'])).first()
    product_price = int(data['quantity']) * product.price
    cart = Cart(user_id=current_user.id,
                product_id=int(data['product_id']),
                quantity=int(data['quantity']),
                price=product_price)
    if cart.quantity < 0:
        return {}

    product = Cart.query.filter_by(product_id=cart.product_id,
                                   user_id=current_user.id).first()
    if product:
        product.quantity += cart.quantity
        product.price += product_price

        db.session.commit()
        return {}

    if cart.quantity != 0:
        db.session.add(cart)
        db.session.commit()

    return {}
示例#15
0
def addCart():
    #返回参数结构
    responseData = {"status": 0, "message": '', "result": {}}
    goodsId = request.form.get("goodsId")
    goodsPrice = request.form.get("goodsPrice")
    goodsNumber = request.form.get("goodsNumber")
    goodsStyle = request.form.get("goodsStyle")
    goodsSize = request.form.get("goodsSize")
    userId = '1111'
    if not (goodsId and goodsPrice and goodsNumber and goodsStyle
            and goodsSize):
        responseData["status"] = 1
        responseData["message"] = "缺少必要的业务参数!"
    else:
        goods = Cart(goodsId=goodsId,
                     goodsPrice=goodsPrice,
                     goodsNumber=goodsNumber,
                     goodsStyle=goodsStyle,
                     goodsSize=goodsSize,
                     userId=userId)
        db.session.add(goods)
        db.session.commit()
        responseData["status"] = 0
        responseData["message"] = "加入购物车成功!"

    # 返回数据
    return jsonify(responseData)
示例#16
0
def start(bot, update, user_data):
    uid = update.message.from_user.id
    bot.sendChatAction(uid, action=typing)
    # btrack(update.message, event_name="start-test-inline")
    # if the user is admin
    if uid == owner_id:
        text = texts.welcome_admin
        keyboard = main_kbd_admin
        next_state = "MAIN_MENU_A"
    # if the user is an ordinary user (is not admin)
    else:
        # if user is not saved in user_data dict
        if 'user' not in user_data: # useless if statement? now we don't save user in the dict
            # and the user is not saved in DB
            if session.query(User.tuid).filter_by(tuid=uid).scalar() is None:
                # we should save the user in user_data dict
                from_user = update.message.from_user
                user = User(tuid=uid, first_name=from_user.first_name, last_name=from_user.last_name)
                # also save the user in DB
                session.add(user)
                session.commit()
            # create an empty cart for the user
            user_data["cart"] = Cart()
            user_data["prev_delivery_addr"] = []
            # welcome, pathetic user
            text = texts.welcome_user
        # if user is saved in user_data dict we have nothing to do but to welcome him again
        else:
            text = texts.welcome_again_user
        keyboard = main_kbd_user
        next_state = "MAIN_MENU_U"
    return ans(text=text, keyboard=keyboard, next_state=next_state)(bot, update)
示例#17
0
def cart(book_name):
    global user_name
    book_id = Book.get_id_by_username(book_name)
    author = Book.get_author_by_username(book_name)
    price = Book.get_price_by_username(book_name)
    genre = Book.get_genre_by_username(book_name)
    edition = Book.get_edition_by_username(book_name)
    Session = sessionmaker(bind=engine)
    session = Session()
    customer_id = Customer.get_id_by_username(user_name)

    temp = 0
    cart = session.query(Cart).filter(Cart.customer_id == customer_id).all()
    for book in cart:
        print(book.book_id)
        if book.book_id == book_id:
            temp += 1
    if temp > 0:
        flash('This book is already in your cart!!')
        return redirect(url_for('search'))
    cart = Cart(customer_id=customer_id, book_id=book_id, book_name=book_name, author=author,
                price=price, genre=genre, book_edition=edition)
    session.add(cart)
    session.commit()
    res = session.query(Cart).filter(Cart.customer_id == customer_id).all()
    session.flush()
    session.close()
    return render_template('shopping_cart.html', res=res, user_logged=user_logged, user_name=user_name)
示例#18
0
def pay(bot, update, args):
    try:
        cart_id = args[0]
        cart = Cart.update(paid=True).where(Cart.id == cart_id)
        cart.execute()
        cart = Cart.select().where(Cart.id == cart_id)[0]
        bot.send_message(
            chat_id=update.message.chat_id,
            text='Thank you for shopping with us! '
            'Your Payment in amount of {} LC confirmed.'
            '\nIf you need help, please use /guidance'.format(cart.amount),
        )
    except IndexError:
        bot.send_message(chat_id=update.message.chat_id,
                         text='Please use proper format: '
                         '/pay Your Cart # ')
示例#19
0
def index(page=1):
    if request.method == 'GET':
        goods = Goods.query.filter().paginate(page, config.POSTS_PER_PAGE,
                                              False)
        return render_template('index.html', goods=goods)
    elif request.method == 'POST':
        user_account = session.get('user_account')
        if user_account:
            user = Users.query.filter(Users.account == user_account).first()
            user_id = user.id
            good_id = request.form.get('good_id')
            check_exist = Cart.query.filter(Cart.user_id == user_id).filter(
                Cart.goods_id == good_id).first()
            if check_exist:
                check_exist.goods_num = check_exist.goods_num + 1
                db.session.commit()
            else:
                new_cart = Cart(user_id=user_id, goods_id=good_id, goods_num=1)
                db.session.add(new_cart)
                db.session.commit()
            goods = Goods.query.filter().paginate(page, config.POSTS_PER_PAGE,
                                                  False)
            return render_template('index.html',
                                   goods=goods,
                                   status=1,
                                   color='success',
                                   alert='Add to cart successfully!')
        else:
            return redirect(url_for('login'))

    goods = Goods.query.filter().paginate(page, config.POSTS_PER_PAGE, False)
    return render_template('index.html', goods=goods)
示例#20
0
文件: bot.py 项目: hidercorp/stor
def order_confirm(bot, update, user_data):
    uid = update.message.from_user.id
    answer = update.message.text
    keyboard = main_kbd_user
    next_state = "MAIN_MENU_U"
    # delivery:
    if "delivery_addr" in user_data:
        dtime = correct_time(answer)
        if not dtime:
            text = texts.wrong_time_format
            keyboard = None
            next_state = None
        else:
            user_data["delivery_time"] = dtime
            addr = user_data["delivery_addr"]
            ddate = user_data["delivery_date"]
            # dtime = user_data["delivery_time"]
            cart = user_data["cart"]
            order_json = cart.json_repr()
            new_order = Order(addr=addr,
                              ddate=ddate,
                              dtime=dtime,
                              order=order_json)
            user = session.query(User).filter_by(tuid=uid).scalar()
            user.uorders.append(new_order)
            session.commit()
            # TODO: save delivery_addr and suggest it next time
            user_data["prev_delivery_addr"].append(addr)
            user_data["cart"] = Cart()
            del user_data["delivery_addr"]
            del user_data["delivery_date"]
            del user_data["delivery_time"]
            text = texts.delivery_confirmation % (addr, ddate, dtime,
                                                  cart.total)
    # pickup:
    else:
        pickup_point = answer
        cart = user_data["cart"]
        order_json = cart.json_repr()
        new_order = Order(pickup=pickup_point, order=order_json)
        user = session.query(User).filter_by(tuid=uid).scalar()
        user.uorders.append(new_order)
        session.commit()
        text = texts.pickup_confirmation % (answer, cart.total)
        user_data["cart"] = Cart()
    return ans(text=text, keyboard=keyboard, next_state=next_state)(bot,
                                                                    update)
示例#21
0
def get_cart_products(username):
    try:
        u = User.select().where(User.username == username).get()
        data = [[c.product.name, c.product.category.name, c.product.price]
                for c in Cart.select().where(Cart.user == u.id)]
        return data
    except peewee.DoesNotExist:
        return None
示例#22
0
文件: views.py 项目: onlyanyz/mysite
def view_cart(request):
    cart = request.session.get("cart", None)
    if not cart:
        cart = Cart()
        request.session["cart"] = cart
    return render_to_response("view_cart.html",
                              locals(),
                              context_instance=RequestContext(request))
示例#23
0
 def on_get(self, req, resp, userId):
     try:
         carts = Cart.objects(userId=userId)
         if len(carts) == 0:
             ResponseUtil.makeResponse(404, resp)
             return
         else:
             ResponseUtil.makeBody(resp, carts[0].to_json())
     except Exception as e:
         ResponseUtil.error(e, resp)
示例#24
0
def addToCart():
    user = User.query.get(request.data['id'])
    data = request.json
    newProductInCart = Cart(user_id=user.id,
                            product_id=data['product_id'],
                            product_details_id=data['product_details_id'],
                            quantity=data['quantity'])
    db.session.add(newProductInCart)
    db.session.commit()
    return jsonify({'message': 'item has been added to the cart'})
示例#25
0
文件: views.py 项目: palletorsson/vb
def show_product(request, article_slug):
    a = get_object_or_404(Article, slug=article_slug)

    if request.method == 'POST':
        data= request.POST.copy()
        form = CartForm(request, data)

        if form.is_valid():
            #add to cart and redirect to cart page
            Cart.add_to_cart(request)
            # if test cookie worked, get rid of it
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
                url = urlresolvers.reverse('show_cart')
                return HttpResponseRedirect(url)
            else:
                form = CartForm(request=request, label_suffix=':')

            request.session.set_test_cookie()
            return render_to_response("variation/detail.html", locals(), context_instance=RequestContext(request))
示例#26
0
    def create(qty, product_id, username, cart_number) -> dict:
        """ Create Cart """
        result: dict = {}
        try:
            data_stock = Stock.query.filter_by(product_id=product_id).first()
            if (data_stock is not None and data_stock.stock > 0):
                if ((data_stock.stock - qty) >= 0):
                    data = Cart(qty, product_id, username, 'Stock Available',
                                cart_number)
                    data.save()
                    result = {
                        'product_id': data.product_id,
                        'qty': data.qty,
                        'username': data.username,
                        'date_created': str(data.date_created),
                    }
                else:
                    result = {'message': 'Stock is not Enough'}
            else:
                result = {'message': 'Stock Unavailable'}
        except IntegrityError:
            Cart.rollback()
            raise ResourceExists('file_name already exists')

        return result
示例#27
0
def remove_cart():
	# Appease the preflight
	if(request.method == "OPTIONS"):
		return

	# Grab the cart from the db
	cart = Cart.cart_by_area(request.json["area"])

	# Delete the thing!
	cart.key.delete()

	# Assume a successful update.
	return
def list_item_of_user(id_user):
    cart = Cart.query.filter(Cart.id_user == id_user).all()
    if (cart != []):
        id_cart = cart[0].id
    else:
        newcart = Cart(id_user=id_user)
        db.session.add(newcart)
        db.session.commit()
        id_cart = Cart.query.filter(Cart.id_user == id_user).first().id

    list_item = CartItem.query.filter(CartItem.id_cart == id_cart).all()

    return id_cart, list_item
示例#29
0
def add(request, slug):
    product_add = Product.objects.get(slug=slug)
    request.session.set_expiry(60)
    try:
        active = request.session['cart']
    except:
        request.session['cart'] = 'Empty'
    if request.session['cart'] != 'Empty':
        cart = request.session['cart']
        update_cart = Cart.objects.get(id=cart)
        update_cart.products.add(product_add)
        update_cart.save()
        request.session['total_items'] = len(update_cart.products.all())

    else:
        new_cart = Cart()
        new_cart.save()
        new_cart.products.add(product_add)
        request.session['cart'] = new_cart.id
        request.session['total_items'] = len(new_cart.products.all())

    return HttpResponseRedirect("/products/%s" % (slug))
示例#30
0
def add_to_cart():
    id = request.form['id'] if request.form['id'] else None
    qty = request.form['qty'] if request.form['qty'] else None

    if not id or not qty or not is_number(id) or not is_number(qty):
        return "NG"

    product = Product.query.filter_by(id=id).first()
    if not product:
        return "NG"

    existing = Cart.query.filter_by(user_id=current_user.id, product_id=id).first()
    if existing:
        existing.quantity += int(qty)
        cart = existing
    else:
        cart = Cart()
        cart.add_to_cart(current_user.id, id, qty)
    db.session.add(cart)
    db.session.commit()

    return "OK"
示例#31
0
def get_cart_location():
	# Appease the preflight
	if(request.method == "OPTIONS"):
		return

	# Grab the cart fomr the db
	cart = Cart.cart_by_area(request.json["area"])

	# Create the json object from the cart.
	location_json = json.dumps(cart.to_dict())

	# Return the mofo
	return location_json
示例#32
0
def set_cart_location():
	# Appease the preflight
	if(request.method == "OPTIONS"):
		return

	# Grab the cart from the db
	cart = Cart.cart_by_area(request.json["area"])

	# Create the json object from the cart.
	cart.update_location(request.json["location"]["lat"], request.json["location"]["lon"])

	# Assume a successful update.
	return
示例#33
0
def add(name):
    user = user_session.current_user()
    try:
        username, _ = user_session.read_current_user()
        user = User.select().where(User.username == username).get()
        product = Product.select().where(Product.name == name).get()

        cart = Cart.create(user=user, product=product)
        cart.save()

        return f'Product {product.name} added to cart!'

    except peewee.DoesNotExist:
        return f'Product {name} not available'
def list_item_of_user_name_book(id_user):
    cart = Cart.query.filter(Cart.id_user == id_user).all()
    if (cart != []):
        id_cart = cart[0].id
    else:
        newcart = Cart(id_user=id_user)
        db.session.add(newcart)
        db.session.commit()
        id_cart = Cart.query.filter(Cart.id_user == id_user).first().id

    list_item = CartItem.query.filter(CartItem.id_cart == id_cart).join(
        Book, Book.id == CartItem.idBook).add_column(Book.name).all()

    return id_cart, list_item
示例#35
0
    def test_add_to_cart(self):
        # Создаем нулевое кол-во продуктов в корзине для пользователя.
        # Создание происходит при просмотре инфо продукта
        product_in_cart, created = Cart.get_or_create(owner_id=update.message.from_user.id, product_id=1)
        self.assertTrue(created, 'Продукт не создан в корзине')

        # тестовый объект магазина
        store = Store()
        store.user = update.message.from_user
        store.current_product = Mock()
        store.current_product.id = 1

        update.callback_query = Mock()

        product_to_add = 5
        for count in range(1, product_to_add+1):
            store.cart_put_one(update, context)
            product_in_cart.amount += 1
            product_in_cart.save()

        # Проверка кол-ва после добавления
        product_in_cart = Cart.get(owner_id=update.message.from_user.id, product_id=1)
        self.assertEqual(product_to_add, product_in_cart.amount, 'Неверно работает добавление продукта')
示例#36
0
def order_confirm(bot, update, user_data):
    answer = update.message.text
    # delivery:
    if "delivery_addr" in user_data:
        user_data["delivery_time"] = answer
        addr = user_data["delivery_addr"]
        ddate = user_data["delivery_date"]
        dtime = user_data["delivery_time"]
        cart = user_data["cart"]
        order_json = cart.json_repr()
        new_order = Order(addr=addr,
                          ddate=ddate,
                          dtime=dtime,
                          order=order_json)
        user = user_data['user']
        user.uorders.append(new_order)
        session.commit()
        # TODO: save delivery_addr and suggest it next time
        user_data["prev_delivery_addr"].append(addr)
        user_data["cart"] = Cart()
        del user_data["delivery_addr"]
        del user_data["delivery_date"]
        del user_data["delivery_time"]
        text = texts.delivery_confirmation % (addr, ddate, dtime, cart.total)
    # pickup:
    else:
        pickup_point = answer
        cart = user_data["cart"]
        order_json = cart.json_repr()
        new_order = Order(pickup=pickup_point, order=order_json)
        user = user_data['user']
        user.uorders.append(new_order)
        session.commit()
        text = texts.pickup_confirmation % (answer, cart.total)
        user_data["cart"] = Cart()
    ans(text=text, keyboard=main_kbd_user)(bot, update)
    return "MAIN_MENU_U"
def insert_into_cart(user_id, product_id, quantity):
    stock = db_session.query(Product).filter_by(id=product_id).first()
    available_stock = stock.count
    if available_stock > int(quantity):
        pro = db_session.query(Cart).filter_by(user_id=user_id,
                                               product_id=product_id).first()
        if pro != None:
            return "result"
        else:
            item = Cart(user_id=user_id, product_id=product_id, count=quantity)
            db_session.add(item)
            db_session.commit()
            return True
    else:
        return False
示例#38
0
def buy(bot, update, args):
    # Function to calculate total amount of certain cart
    try:
        cart_id = args[0]
        cart = Cart.select().where(Cart.id == cart_id)[0]
        bot.send_message(
            chat_id=update.message.chat_id,
            text='Dear {}, total amount of Your Cart # {} is {} LC. '
            '\nIf you want to pay, please use /pay'
            '\nIf you want to continue shopping, please use /guidance'.format(
                cart.customer, cart_id, cart.amount))
    except IndexError:
        bot.send_message(chat_id=update.message.chat_id,
                         text='Please use proper format: '
                         '/buy Your Cart # ')
示例#39
0
 def on_get(self, req, resp, userId, couponId):
     try:
         couponResult = Coupon.objects(id=couponId)
         cartResult = Cart.objects(userId=userId)
         if len(couponResult) == 0 or len(cartResult) == 0:
             ResponseUtil.makeResponse(409, resp)
             return
         coupon = couponResult[0]
         cart = cartResult[0]
         ResponseUtil.makeJson(resp, {
             'cart': cart.to_json(),
             'coupon': coupon.to_json()
         })
     except Exception as e:
         ResponseUtil.error(e, resp)
示例#40
0
    def test_clear_cart(self):
        # тестовый объект магазина
        store = Store()
        store.user = update.message.from_user
        store.current_product = Mock()
        store.current_product.id = 1

        expected_products = [(1, 3), (2, 2), (3, 1)]

        # Наполняем корзину
        for product_id, product_count in expected_products:
            Cart.create(owner_id=store.user.id, product_id=product_id, amount=product_count)

        # Проверяем корректность наполнения
        cart_content = Cart.select().where(Cart.owner_id == store.user.id)
        for expected, in_cart in zip(expected_products, cart_content):
            self.assertEqual(expected, (in_cart.product_id.id, in_cart.amount), 'Что-то не так при пополнении корзины')

        store.cart_remove_all(update, context)

        # проверяем, что корзина очищена
        cart_after_cleaning = Cart.select().where(Cart.owner_id == store.user.id)
        for record in cart_after_cleaning:
            self.assertEqual(record.amount, 0, 'Продукт не удален из корзины')
示例#41
0
 def _create_cart_in_database(self, creation_date=datetime.datetime.now(), 
         checked_out=False):
     """
         Helper function so I don't repeat myself
     """
     cart = Cart()
     cart.creation_date = creation_date
     cart.checked_out = False
     cart.save()
     return cart
示例#42
0
def insert_into_cart(product_id, quantity, user_id):
    available_stock = session.query(Item).filter_by(id=product_id).first()
    available_quantity = available_stock.quantity
    if available_quantity < int(quantity):
        return False
    else:
        avail = session.query(Cart).filter_by(user_id=user_id,
                                              item_id=product_id).first()
        if avail != None:
            return "No"
        else:
            product = Cart(user_id=user_id,
                           item_id=product_id,
                           desired_quantity=quantity)
        session.add(product)
        session.commit()
        return True
示例#43
0
    def fetch_cart(jwt, customer_id):

        totals = []
        cart = []

        query = Cart.query.join(
            Product, Cart.product_id == Product.id
        ).with_entities(
            Cart.amount,
            Cart.customer_id,
            Cart.id,
            Cart.product_id,
            Product.name.label("product_name"),
            Product.short_description,
            Product.image_link,
            Cart.product_price
        ).filter(
            Cart.customer_id == customer_id
        ).order_by(
            Cart.id
        ).all()

        cart = Cart.format(query)

        totals_query = Cart.query.with_entities(
            func.sum(Cart.amount * Cart.product_price).label("product_total")
        ).filter_by(
            customer_id=customer_id
        )

        for el in totals_query:
            totals.append({
                'discount': 0,  # todo
                'final_price': el.product_total,
            })

        if len(cart) == 0:
            abort(404)

        return jsonify({
            'success': True,
            'products': cart,
            'totals': totals,
            'total_products': len(cart)
        })
示例#44
0
def add_to_cart(request, num=1):
    if request.method == "POST":
        food_id = request.POST['foodId']
        food = Food.objects.get(id=food_id)
        cart_session = request.session.get('cart', None)
        # Lineitem save in cart
        # session is empty
        if not cart_session:
            # 购物车中不存在物品的情况
            cart = Cart()
            li = LineItem()
            li.food = food
            li.unite_price = food.price
            li.quantity = num
            li.save()
            cart.add_product(li, num)
        else:
            cart = pickle_load(cart_session)

            has_food = False
            for li in cart.items:
                if li.food.id == food.id:
                    li.quantity += num
                    has_food = True
                    cart.total_price += food.price * num
            if not has_food:
                li = LineItem()
                li.food = food
                li.unite_price = food.price
                li.quantity = num
                li.save()
                cart.add_product(li, num)
        cart.total_price = round(cart.total_price, 2)
        data = pickle_dump(cart)
        request.session['cart'] = data
        return HttpResponse(cart.total_price)
    else:
        logger.error('Get Request to add_to_cart')
        return HttpResponse('request method err')
#!/usr/local/bin/python
import urllib2
import json
from models import Cart

carts = Cart()
carts.remove_all()
host = 'http://data.cityofnewyork.us/resource/xfyi-uyt5.json'
for i in range(0, 7000, 1000):
    query = 'permit_type_description=MOBILE+FOOD+UNIT&$offset=%d' % i
    request = host + '?' + query
    data = urllib2.urlopen(host + '?' + query)

    results = json.loads(data.read())
    data.close()
    for r in results:
        if not r.has_key('longitude_wgs84'):
            r['longitude_wgs84'] = 'UNKNOWN'
        if not r.has_key('latitude_wgs84'):
            r['latitude_wgs84'] = 'UNKNOWN'
        if not r.has_key('street'):
            r['street'] = 'UNKNOWN'
        if not r.has_key('address'):
            r['address'] = 'UNKNOWN'
        if not r.has_key('zip_code'):
            r['zip_code'] = 'UNKNOWN'
        if not r.has_key('borough'):
            r['borough'] = 'UNKNOWN'
        if not r.has_key('license_permit_holder'):
            r['license_permit_holder'] = 'UNKNOWN'
示例#46
0
文件: views.py 项目: hnejadi/cart-api
 def post_save(self, obj, created=False):
     if created:
         cart = Cart(user=obj)
         cart.save()
示例#47
0
 def new(self, request):
     cart = CartModel()
     cart.save()
     request.session[CART_ID] = cart.id
     return cart
示例#48
0
def cart_count(request):
    cart_id = Cart.get_cart_id(request)
    return {'cart_count': Purchase.objects.filter(cart_id=cart_id).count() if cart_id else 0}
示例#49
0
def remove_from_cart(request, decal_id):
    decal = Decal.objects.get(id=decal_id)
    cart = Cart(request)
    cart.remove(decal)
示例#50
0
def add_to_cart(request, decal_id, quantity):
    decal = Decal.objects.get(id=decal_id)
    cart = Cart(request)
    cart.add(decal, decal.price, quantity)