예제 #1
0
def clone(id):
    cart = Cart.query.get_or_404(id)
    foods = cart.foods.all()

    # clone cart
    cart_copy = Cart()
    cart_copy.user = current_user

    for food in foods:
        food_copy = FoodItem(name=food.name,
                             img_url=food.img_url,
                             nf_calories=food.nf_calories,
                             nf_total_fat=food.nf_total_fat,
                             nf_saturated_fat=food.nf_saturated_fat,
                             nf_cholesterol=food.nf_cholesterol,
                             nf_sodium=food.nf_sodium,
                             nf_total_carbohydrate=food.nf_total_carbohydrate,
                             nf_dietary_fiber=food.nf_dietary_fiber,
                             nf_sugars=food.nf_sugars,
                             nf_protein=food.nf_protein,
                             serving_unit=food.serving_unit,
                             serving_qty=food.serving_qty)
        food_copy.cart = cart_copy
        db.session.add(food_copy)

    cart_copy.update_nutrients()
    db.session.add(cart_copy)
    db.session.commit()

    flash('Cart Has Been Cloned And Added To Your Carts')
    return redirect(url_for('carts.cart', id=cart_copy.id))
예제 #2
0
 def setUp(self):
     '''
     Set up method that will run before every Test
     '''
     self.user_ = User(username = '******',password = '******', email = '*****@*****.**')
       
     self.new_cart = Cart(product='vegan pizza',size="large",user = self.user_Stan,amount="1000")
예제 #3
0
def add_to_cart(request):
    user = request.user
    product_id = request.GET.get('prod_id')
    product = Product.objects.get(id=product_id)
    data_for_cart = Cart(user=user, product=product)
    data_for_cart.save()
    return redirect('/show-cart')
예제 #4
0
class CartTest(unittest.TestCase):
    '''
    Test Class to test the behaviour of the  class
    '''
          
    def setUp(self):
        '''
        Set up method that will run before every Test
        '''
        self.user_ = User(username = '******',password = '******', email = '*****@*****.**')
          
        self.new_cart = Cart(product='vegan pizza',size="large",user = self.user_Stan,amount="1000")
   
    def tearDown(self):
        Cart.query.delete()
        User.query.delete()
        
    def test_instance(self):
        self.assertTrue(isinstance(self.new_cart, Cart))
  
    
    # We then check if the values of variables are correctly being placed.
    def test_check_instance_variables(self):
        
        self.assertEquals(self.new_cart.product,'vegan pizza')
        self.assertEquals(self.new_cart.price,"food for vegans")
        self.assertEquals(self.new_cart.size,"large")
        self.assertEquals(self.new_cart.amount,"1000")
        self.assertEquals(self.new_cart.user,self.user_Stan)
        
    def test_save_product(self):
        self.new_cart.save_cart()
        self.assertTrue(len(Cart.query.all())>0)
        
예제 #5
0
def add_to_cart(request):
    product_id = request.POST.get('product_id')
    if request.user.is_authenticated == False:
        return redirect(f'/login/?redirect_to=/products/{product_id}/')

    product = Product.objects.get(pk=product_id)
    carts = Cart.objects.filter(
        user_id=request.user.id).order_by('-created_on')
    if carts.exists():
        cart = carts[0]
    else:
        cart = Cart(user_id=request.user.id)
        cart.save()
    cartItems = cart.cartitem_set.filter(product_id=product_id)
    if cartItems.exists():
        cartItem = cartItems[0]
        cartItem.quantity = cartItem.quantity + 1
        cartItem.total = product.unit_price * cartItem.quantity
    else:
        cartItem = CartItem(cart=cart,
                            product=product,
                            quantity=1,
                            unit_price=product.unit_price,
                            total=product.unit_price * 1)
    cartItem.save()
    return redirect(product_detail, id=product_id)
예제 #6
0
def cart(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except DoesNotExist:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)

    template = 'cart.html'
    if request.method == 'POST':
        new_order = Order()
        new_order.user = request.user
        new_order.total = cart.cart_total
        new_order.save()
        for item in cart.items.all():
            cart.items.remove(item)
            cart.save()
        return render(request, template)

    new_cart_total = 0
    for item in cart.items.all():
        new_cart_total += item.item_total

    cart.cart_total = new_cart_total
    cart.save()
    context = {
        'cart': cart
    }
    return render(request, template, context)
예제 #7
0
def cart_session(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(pk=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)
    return cart
예제 #8
0
def get_cart(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=int(cart_id))
        request.session['count'] = cart.items.count()
        return cart
    except:
        cart = Cart()
        cart.save()
        request.session['cart_id'] = cart.id
        cart = Cart.objects.get(id=cart.id)
        return cart
예제 #9
0
def add_to_cart(id, product_id):
    print(f"dfgsdfgsfh {id} {product_id} sfdgsdfg")
    form = CartForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        print(f"ARE WE IN THE IF? ARE WE VALIDATING?")
        new_cart_item = Cart(user_id=id, product_id=product_id)
        print(f"NEW_CART:{new_cart_item}")
        db.session.add(new_cart_item)
        db.session.commit()
        return new_cart_item.to_dict()
        # return new_cart_item
    return "okie dokey"
def add_item():
    form = ItemForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        new_cart = Cart(user_id=form.user_id.data,
                        item_id=form.item_id.data,
                        quantity=form.quantity.data,
                        preferences=form.preferences.data)
        db.session.add(new_cart)
        db.session.commit()
        return new_cart.to_dict()
    else:
        return {"errors": "invalid submission"}
예제 #11
0
def checkout_view(request):
    try:
        cart_id = request.session[
            'cart_id']  # Получение значения сессии при помощи ключа(то есть, 'cart_id').
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id  # Передача значения в сессию
        cart = Cart.objects.get(id=cart_id)
    context = {'cart': cart}
    return render(request, 'app/checkout.html', context)
예제 #12
0
def order_create_view(request):
    try:
        cart_id = request.session[
            'cart_id']  # Получение значения сессии при помощи ключа(то есть, 'cart_id').
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id  # Передача значения в сессию
        cart = Cart.objects.get(id=cart_id)
    form = OrderForm(request.POST or None)
    context = {'form': form, 'cart': cart}
    return render(request, 'app/order.html', context)
예제 #13
0
def extractAndPersistKartDetailsUsingSubquery(productId):
    user = User.query.filter(User.email == session['email']).first()
    userId = user.id

    subqury = Cart.query.filter(Cart.userid == userId).filter(Cart.productid == productId).subquery()
    qry = db.session.query(Cart.quantity).select_entity_from(subqury).all()

    if len(qry) == 0:
        cart = Cart(userid=userId, productid=productId, quantity=1)
    else:
        cart = Cart(userid=userId, productid=productId, quantity=qry[0][0] + 1)

    db.session.merge(cart)
    db.session.flush()
    db.session.commit()
예제 #14
0
def add():
    try:
        # get headers first
        name = request.headers.get('name')
        price = request.headers.get('price')
        description = request.headers.get('description')
        image_url = request.headers.get('image_url')
        product_id = request.headers.get('product_id')

        # different combinations of data will be provided 
        # depending on whether a product is being added to the inventory or an item is being added to the cart
        # must follow either of these patterns
        if product_id and not name and not price and not description and not image_url:
            cart = Cart(product_id=product_id)
            
            db.session.add(cart)
            db.session.commit()
            
            return jsonify({ 'success': 'Added item to cart' })
        elif name and price and description and image_url and not product_id:
            product = Product(name=name, price=price, description=description, image_url=image_url)
            
            db.session.add(product)
            db.session.commit()
            
            return jsonify({ 'success': 'Added product to inventory' })
        else:
            return jsonify({ 'error': 'Error #001: Invalid parameters' })
    except:
        return jsonify({ 'error': 'Error #002: Could not add item/product' })
예제 #15
0
def addToCart(product_id, from_page):
    if current_user.is_anonymous:
        return redirect(url_for('login'))
    cart = Cart(user_id=current_user.id, product_id=product_id)
    db.session.add(cart)
    db.session.commit()
    return redirect(url_for('cart'))
예제 #16
0
def add_to_cart(item_id):
    #item_id = request.args.get('item_id')
    cart_item = Cart(user_id=current_user.id, item_id=item_id)
    db.session.add(cart_item)
    db.session.commit()
    flash(u'Pozycja dodana do koszyka!', 'success')
    return redirect(url_for('item.index', item_id=item_id))
예제 #17
0
def AddToCart(ProductID):
    # 1. Get current User's ID to add product in particular user's cart.
    # 2. Get ProductID as a parameter.
    # 3. Add new entry in Cart table with above UserID and ProductID.
    # 4. Commit database after above entry.
    uid = current_user.get_id()
    CartObject = Cart(user_id=uid, product_id=ProductID)
    db.session.add(CartObject)
    db.session.commit()

    print("ProductID: ", ProductID)
    # For now: OPTION 1
    # 5. call GetPredictedProducts() and calculate runtime r1
    # 6. call GetSimilarProducts() and calculate runtime r2
    # 7. call GetComplementaryProducts() and calculate runtime r3
    # 8. call GetRecipeRecommendations() and calculate runtime r4
    # 9. Display result on terminal along with runtime (r1+r2, r1+r3, r1+r4)

    # Ideally, one of the function will be called out of step 6, 7, 8
    # according to the tab selected by the user in recommendatioin part of the page
    # and view will be updated with the new recommendations

    NextBuyProducts = GetPredictedProducts()

    return redirect('/Home')
예제 #18
0
def addBookCart(bookid):
    if request.method == 'POST':
        cart = Cart(current_user.id, bookid)
        db.session.add(cart)
        db.session.commit()
        flash('Book Successfully Added to cart', 'success')
    return redirect(url_for('cart'))
예제 #19
0
 def post(self,request,*args,**kwargs):
     form = self.form_class(request.POST)
     if form.is_valid():
         form.save()
         user = get_object_or_404(User, username = form.cleaned_data.get('username'))
         # Create the cart for the user
         cart = Cart(user = user)
         cart.save()
         # Add the user's email to the news letters
         try:
             get_object_or_404(NewsLetters,email = form.cleaned_data.get('email'))
         except NewsLetters.DoesNotExist:
             news_letters = NewsLetters(email = form.cleaned_data.get('username'))
             news_letters.save()
         messages.success(request,f'You account has been succesfully created, you can sign in now.')
         return HttpResponseRedirect(reverse('user:signin'))
     return render(request,self.template_name,{'form':form})
예제 #20
0
def add_to_cart():
    form = CartForm()
    print(request.get_json())
    # Get the csrf_token from the request cookie and put it into the
    # form manually to validate_on_submit can be used
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        cart = Cart(
            user_id=form.user_id.data,
            listing_id=form.listing_id.data,
            quantity=form.quantity.data,
        )
    db.session.add(cart)
    # print("added")
    db.session.commit()
    return cart.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}, 401
예제 #21
0
def extractAndPersistKartDetailsUsingSubquery(productId, quantity):
    number_of_items = quantity
    userId = session['user_id']

    subqury = Cart.query.filter(Cart.productid == productId).subquery()
    qry = db.session.query(Cart.quantity).select_entity_from(subqury).all()

    if len(qry) == 0:
        cart = Cart(userid=userId, productid=productId,
                    quantity=number_of_items)
    else:
        cart = Cart(userid=userId, productid=productId,
                    quantity=(qry[0][0] + number_of_items))

    db.session.merge(cart)
    db.session.flush()
    db.session.commit()
예제 #22
0
def addcart(request):
    token = request.session.get('token')

    goodsid = request.GET.get('goodsid')

    data = {}

    if token:
        user = User.objects.get(token=token)

        goods = Goods.objects.get(pk=goodsid)

        carts = Cart.objects.filter(user=user).filter(goods=goods)

        if carts.exists():
            cart = carts.first()
            cart.number = cart.number + 1
            cart.save()

        else:
            cart = Cart()
            cart.user = user
            cart.goods = goods
            cart.number = 1
            cart.save()
        return JsonResponse({
            'msg': '{},添加购物车成功'.format(goods.productlongname),
            'number': cart.number,
            'status': 1
        })

    else:
        data['msg'] = '请登录后操作!'
        data['status'] = -1
        return JsonResponse(data)
예제 #23
0
파일: views.py 프로젝트: q894257739/mixin
def addcart(request):
    goodsid = request.GET.get('goodsid')
    token = request.session.get('token')
    userid = cache.get(token)

    if userid:
        user = User.objects.get(pk=userid)
        goods = Goods.objects.get(id=goodsid)
        carts = Cart.objects.filter(user=user).filter(goods=goods)
        if carts.exists():
            cart = carts.first()
            cart.number = cart.number + 1
            cart.save()
        else:
            cart = Cart()
            cart.user = user
            cart.goods = goods
            cart.number = 1
            cart.save()

        response_data = {'msg': '成功添加商品', 'status': 1, 'number': cart.number}

    else:
        response_data = {'msg': '未登录', 'status': -1}

    return JsonResponse(response_data)
예제 #24
0
def addcart(request):
    #获取token
    token = request.session.get('token')
    #响应数据
    response_data = {}
    # 缓存
    if token:
        userid = cache.get(token)
        if userid:
            user = User.objects.get(pk=userid)
            goodsid = request.GET.get('goodsid')
            goods = Goods.objects.get(pk=goodsid)
            carts = Cart.objects.filter(user=user).filter(goods=goods)
            if carts.exists():
                cart = carts.first()
                cart.number = cart.number + 1
                cart.save()
            else:
                cart = Cart()
                cart.user = user
                cart.goods = goods
                cart.number = 1
                cart.save()
            response_data['status'] = 1
            response_data['number'] = cart.number
            response_data['msg'] = '添加{} 购物车成功,数量为:{}'.format(
                cart.goods.productlongname, cart.number)
            return JsonResponse(response_data)
    response_data['status'] = -1
    response_data['msg'] = '请登录后操作'
    return JsonResponse(response_data)
예제 #25
0
def addcart(request):

    token = request.session.get('token')

    # 响应数据
    response_data = {}

    if token:
        userid = cache.get(token)

        if userid:  # 已经登录
            user = User.objects.get(pk=userid)
            goodsid = request.GET.get('goodsid')
            goods = Goods.objects.get(pk=goodsid)
            number = request.GET.get('number')
            print(number)
            # 商品不存在: 添加新记录
            # 商品存在: 修改number
            carts = Cart.objects.filter(user=user).filter(goods=goods)
            cart = Cart()
            cart.user = user
            cart.goods = goods
            cart.number = number
            cart.save()

            response_data = '添加 {} 购物车成功: {}'.format(cart.goods, cart.number)

            return JsonResponse(response_data)
예제 #26
0
def add_cart(request):
    token = request.session.get('token')
    userid = cache.get(token)

    goodsid = request.GET.get('goodsid')

    number = int(request.GET.get('number'))
    print(number)

    if userid:

        user = User.objects.get(pk=userid)

        goods = Goods.objects.get(pk=goodsid)

        cart = Cart.objects.filter(user=user).filter(goods=goods)

        if cart.exists():
            cart = cart.first()
            cart.number = cart.number + number

            cart.save()
        else:
            cart = Cart()
            cart.user = user
            cart.goods = goods
            cart.number = number
            cart.save()

        return JsonResponse({'msg': '{}-添加购物车成功,数量为-{}'.format(cart.goods.name, cart.number), 'status': 1})
    else:
        return JsonResponse({'msg': '请先登录,后操作', 'status': 0})
예제 #27
0
파일: views.py 프로젝트: HelloCXD/axf
def addcart(request):
    goodsid = request.GET.get('goodsid')
    token = request.session.get('token')

    responseData = {'msg': '添加购物车成功', 'status': 1}

    if token:  # 已登录
        user = User.objects.get(token=token)
        goods = Goods.objects.get(pk=goodsid)

        # 判断商品是否在购物车中
        carts = Cart.objects.filter(user=user).filter(goods=goods)
        if carts.exists():
            cart = carts.first()
            cart.number = cart.number + 1
            cart.save()
            responseData['number'] = cart.number
        else:
            cart = Cart()
            cart.user = user
            cart.goods = goods
            cart.number = 1
            cart.save()

            responseData['number'] = cart.number

        return JsonResponse(responseData)
    else:  # 未登录
        responseData['msg'] = '请登录后操作'
        responseData['status'] = -1
        return JsonResponse(responseData)
예제 #28
0
def addgoods(request):
    token = request.session.get('token')
    response_data = {}
    if token:
        userid = cache.get(token)
        if userid:
            user = User.objects.get(pk=userid)
            goodsid = request.GET.get('goodsid')
            goodsnum = int(request.GET.get('goodsNum'))
            goods = GOODs.objects.get(pk=goodsid)
            # 判断需要添加的商品是否已经存在
            carts = Cart.objects.filter(user=user).filter(goods=goods)

            if carts.exists():
                cart = carts.first()
                cart.number += goodsnum
                cart.save()
            else:
                cart = Cart()
                cart.user = user
                cart.goods = goods
                cart.number = goodsnum
                cart.save()

            response_data['status'] = 1
            response_data['number'] = cart.number
            response_data['msg'] = '添加{}购物车成功:{}'.format(
                cart.goods.productlongname, cart.number)
            return JsonResponse(response_data)

    response_data['status'] = -1
    response_data['msg'] = '请登录后操作'
    return JsonResponse(response_data)
예제 #29
0
def quicklybuy(request):
    token = request.session.get('token')
    response_data = {}
    if token:
        userid = cache.get(token)
        if userid:  # 已经登录
            user = User.objects.get(pk=userid)
            goodsid = request.GET.get('goodsid')
            num = int(request.GET.get('number1'))
            goods = Goods.objects.get(pk=goodsid)
            carts = Cart.objects.filter(user=user).filter(goods=goods)
            if carts.exists():
                cart = carts.first()
                cart.number = cart.number + num
                cart.save()
            else:
                cart = Cart()
                cart.user = user
                cart.goods = goods
                cart.number = num
                cart.save()

            response_data['status'] = 1
            response_data['number'] = cart.number
            response_data['msg'] = '添加 {} 购物车成功: {}'.format(cart.goods.productname, cart.number)
            return JsonResponse(response_data)
    response_data['status'] = -1
    response_data['msg'] = '请登录后操作'
    return JsonResponse(response_data)
예제 #30
0
def addtocart(request):
    username = request.session.get('username')
    data = {'status': '200', 'msg': 'ok'}
    # ajax请求的,则返回的也是返回到ajax,判断用户是否登录
    if not username:
        data['status'] = '302'
        data['msg'] = '用户未登录'
        return JsonResponse(data)
    # 获取到商品的id
    goodsid = request.GET.get('goodsid')
    # 找到对应的商品
    goods = MarketGoods.objects.filter(pk=goodsid).first()
    user = User.objects.filter(u_name=username).first()
    # 从购物车里检索这个商品,如果有的话,数量加1,如果没有就新建一个
    cart_item = Cart.objects.filter(c_user=user).filter(c_goods=goods).filter(
        c_belong=False).first()
    if not cart_item:
        cart_item = Cart()
    else:
        cart_item.c_num = cart_item.c_num + 1
    cart_item.c_goods = goods
    cart_item.c_user = user
    cart_item.save()
    data['c_num'] = cart_item.c_num
    return JsonResponse(data)
예제 #31
0
def process_order(request):
    print "placing order"

    try:
        phone_number = request.POST.get("phone_number")
        user_name = request.POST.get("userName")
        email = request.POST.get("email")
        app_version = request.POST.get("app_version")
        device_id = request.POST.get("device_id")
        app_id = request.POST.get("app_id")
        bring_change_of = int(request.POST.get("bring_change_of", "0"))
        address_str = request.POST.get("address")
        landmark = request.POST.get("landmark")
        location_show = request.POST.get("location_show")
        location_id = request.POST.get("location_id")
        api_key = request.POST.get("api_key")
        products = request.POST.get("products")
        tomorrow = request.POST.get("tomorrow")
        delivery_time = request.POST.get("delivery_time")
        # print request
        coupon_id = int(request.POST.get("coupon_id", "0"))

        coupon = None

        print "coupon"
        print phone_number
        user = User.objects.get(username=phone_number)
        if user:
            user.email = email
            user.first_name = user_name.title()
            user.save()
            user_profile = user.userprofile
            user_profile.app_version = app_version
            user_profile.app_id = app_id
            user_profile.device_id = device_id
            user_profile.save()
            if user.api_key.key != api_key:
                print "api key is not valid"
                data = simplejson.dumps({"status": "Not Valid Request"})
                return HttpResponse(data, content_type="application/json", status=403)
        else:
            print "User not found"
            data = simplejson.dumps({"status": "Not Valid Request"})
            return HttpResponse(data, content_type="application/json", status=403)

        print "user obj created"
        print coupon_id

        if coupon_id > 0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count += 1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon, user=user)
            print user
            if prev_order:
                if prev_order[0].status != 1:
                    print "coupon invalidation1"
                    coupon = None
            print coupon
        print "check for coupon"
        location = Location.objects.get(pk=location_id)
        address = Address.objects.filter(user=user, address=address_str, landmark=landmark)
        if address:
            address = address[0]
            address.location = location
            address.save()
        else:
            address = Address(
                user=user, address=address_str, landmark=landmark, location_show=location_show, location=location
            )
            address.save()
        print "address done"

        # print products
        products = products.split(",")
        product_ids = map(lambda x: x.split("::")[0], products)
        product_qns = map(lambda x: x.split("::")[1], products)
        print product_ids
        print product_qns
        order = Order(user=user, total_amount=0, address=address, status=3)
        if tomorrow == "1":
            print delivery_time
            if dt.datetime.now().hour > 20:
                order.delivery_time = dt.datetime.strptime(
                    str((dt.datetime.now() + dt.timedelta(days=1)).date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
            else:
                order.delivery_time = dt.datetime.strptime(
                    str(dt.datetime.now().date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
        else:
            order.delivery_time = dt.datetime.now() + dt.timedelta(hours=1)
        if bring_change_of:
            order.change_requested = bring_change_of
        order.save()
        invoice = Invoice(order=order, product_json="")
        invoice.save()
        print "order obj saved"
        total_amount = 0
        index = 0

        ordered_services = {}
        products_json = []
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append(
                {
                    "spid": prd.id,
                    "pid": prd.product.product.id,
                    "name": prd.product.product.name,
                    "price": prd.price,
                    "discount": prd.discount,
                    "qn": product_qns[index],
                    "size_id": prd.product.size.id,
                }
            )
            service = prd.product.product.category.service
            if "offer" in service.name.lower():
                OfferDeviceId(device_id=device_id).save()
                OfferProductOrderMapping(
                    device_id=device_id, order=order, offer_product=prd.offerproductmapping_set.all()[0]
                ).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)] = 0
            total_amount += int(product_qns[index]) * (prd.price - prd.discount)
            ordered_services[str(service.id)] += int(product_qns[index]) * (prd.price - prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order, store=store)
            if cart:
                cart = cart[0]
            else:
                cart = Cart(order=order, store=store)
                cart.save()

            OrderedProduct(product=prd, cart=cart, quantity=product_qns[index]).save()
            index += 1
        products_json = simplejson.dumps(products_json)
        invoice.product_json = products_json
        invoice.save()

        service_amount_ordered = []
        for key in ordered_services:
            service_amount_ordered.append(str(key) + ":" + str(ordered_services[key]))
        service_amount_ordered = ";;".join(service_amount_ordered)
        print total_amount

        final_amount = total_amount

        if coupon:
            if total_amount >= coupon.min_total:
                order.coupon_applied = coupon
                print "found coupon"
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(
                    coupon, user, location_id, int(app_version), final_amount, service_amount_ordered
                )["discount"]
                print "discount" + str(discount)
                final_amount -= discount

        print "passed coupon part"

        delivery_charges = {}
        for key in ordered_services:
            service = Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service, location=location)
            if lsm:
                lsm = lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True, is_active=True, lsm=lsm)
                print "done"
                if stl:
                    stl = stl[0]
                    if key not in delivery_charges:
                        delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": stl.delivery_min_amount}
                    if ordered_services[key] < stl.delivery_min_amount:
                        final_amount += -stl.delivery_charges
                        total_amount += stl.delivery_charges
                        delivery_charges[key]["delivery_charges"] = stl.delivery_charges
                else:
                    delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}
            else:
                delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}

        print "passed delivery part"

        order.total_amount = total_amount
        order.final_amount = final_amount
        order.delivery_charges = simplejson.dumps(delivery_charges)
        order.save()
        OrderActivity(order=order, user=order.user, actions=0, comment=" ").save()

        data = simplejson.dumps({"status": "done"})
        return HttpResponse(data, content_type="application/json", status=201)
    except Exception as process_order_function_error:
        print "process_order: " + str(process_order_function_error)
        data = simplejson.dumps({"status": "Server Error"})
        send_mail(
            "Order placing Error " + str(process_order_function_error),
            str(request) + "\n\n\n" + str(simplejson.dumps(request.POST)),
            "*****@*****.**",
            ["*****@*****.**"],
            fail_silently=False,
        )
        return HttpResponse(data, content_type="application/json", status=500)
예제 #32
0
    def obj_create(self, bundle, request=None, **kwargs):
        # data={'status':'cant place order'}
        # return HttpResponse(data, content_type='application/json')
        print bundle.data
        phone_number =  bundle.data['phone_number']
        userName =  bundle.data['userName']
        email =  bundle.data['email']
        app_version =  bundle.data['app_version']
        device_id =  bundle.data['device_id']
        app_id =  bundle.data['app_id']
        bring_change_of =  int(bundle.data['bring_change_of'])

        address_str = bundle.data['address']
        landmark = bundle.data['landmark']
        location_show = bundle.data['location_show']
        location_id = bundle.data['location_id']
        coupon_id =""
        try:
            coupon_id = int(bundle.data['coupon_id'])
        except:
            pass

        coupon=None

        print 'coupon'
        print phone_number
        user = User.objects.filter(username=phone_number)
        print user
        print '----'
        if user:
            user=user[0]
            user.email = email
            user.first_name=userName.title()
            user.save()
            print 'user saved'
            userProfile =UserProfile.objects.filter(user=user)
            print 'userprofile'
            print userProfile
            print '----'
            if userProfile:
                userProfile = userProfile[0]
                userProfile.app_version=app_version
                userProfile.app_id=app_id
                userProfile.device_id=device_id
                userProfile.save()
            else:
                UserProfile(user=user,contact=int(phone_number),app_id=app_id,app_version=app_version,device_id=device_id).save()
        else:
            user=User.objects.create_user(phone_number,email,phone_number)
            user.first_name=userName.title()
            user.save()
            UserProfile(user=user,contact=int(phone_number),app_id=app_id,app_version=app_version,device_id=device_id).save()
        print 'user obj created'
        print coupon_id
        if coupon_id>0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count+=1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon,user=user)
            print user
            if prev_order:
                if prev_order[0].status!=1:
                    print 'coupon invalidation1'
                    coupon=None
            print coupon
        print 'check for coupon'
        location = Location.objects.get(pk=location_id)
        address  = Address.objects.filter(user =user ,address=address_str,landmark=landmark)
        if address:
            address=address[0]
        else:
            address  = Address(user =user ,address=address_str,landmark=landmark,location_show=location_show,location=location )
            address.save()
        print 'address done'
        products = bundle.data['products']
        # print products
        products = products.split(',')
        product_ids = map(lambda x:x.split('::')[0],products)
        product_qns = map(lambda x:x.split('::')[1],products)
        print product_ids
        print product_qns
        order = Order(user = user,total_amount=0,address=address,status=3)
        order.delivery_time=dt.datetime.now()+dt.timedelta(hours=1)
        order.save()
        print 'order obj saved'
        total_amount = 0
        index=0

        ordered_services={}
        products_json=[]
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append({'spid':prd.id,'pid':prd.product.product.id,'name':prd.product.product.name,'price':prd.price,'discount':prd.discount,'qn':product_qns[index],'size_id':prd.product.size.id})
            service = prd.product.product.category.service
            if 'offer' in service.name.lower():
                OfferProductOrderMapping(device_id=device_id,order=order,offer_product=prd.offerproductmapping_set.all()[0]).save()
                OfferDeviceId(device_id=device_id).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)]= 0
            total_amount+= int(product_qns[index])*(prd.price- prd.discount)
            ordered_services[str(service.id)]+= int(product_qns[index])*(prd.price- prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order,store=store)
            if cart:
                cart=cart[0]
            else:
                cart = Cart(order=order,store=store)
                cart.save()

            OrderedProduct(product=prd,cart=cart,quantity=product_qns[index]).save()
            index+=1
        service_amount_ordered=[]
        for key in ordered_services:
            service_amount_ordered.append(str(key)+":"+str(ordered_services[key]))
        service_amount_ordered=';;'.join(service_amount_ordered)
        print total_amount

        final_amount=total_amount
        if coupon:
            if total_amount>=coupon.min_total:
                order.coupon_applied=coupon
                print 'found coupon'
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(coupon,user,location_id,int(app_version),final_amount,service_amount_ordered)['discount']
                print "discount" + str(discount)
                final_amount-=discount
        print "passed coupon part"
        delivery_charges = 0
        delivery_charges_to_save_in_order={}
        for key in ordered_services:
            service=Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service,location=location)
            if lsm:
                lsm=lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True,is_active=True,lsm=lsm)
                print 'done'
                if stl:
                    stl=stl[0]
                    # print 'done1'
                    if key not in delivery_charges_to_save_in_order:
                        # print 'done10'
                        delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':stl.delivery_min_amount}
                        # print 'done11'
                    if ordered_services[key]<stl.delivery_min_amount:
                        # print 'done20'
                        final_amount+=-stl.delivery_charges
                        total_amount+=stl.delivery_charges
                        # print 'done21'
                        delivery_charges_to_save_in_order[key]['delivery_charges']=stl.delivery_charges
                        # print 'done22'
                else:
                    delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':0}
            else:
                delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':0}
        print "passed delivery part"
        order.total_amount=total_amount
        order.final_amount=final_amount
        if bring_change_of:
            order.change_requested=bring_change_of
        order.delivery_charges = simplejson.dumps(delivery_charges_to_save_in_order)
        order.save()
        products_json=simplejson.dumps(products_json)
        Invoice(order=order,product_json=products_json).save()
        bundle.obj=order
        OrderActivity(order=order,user=order.user,actions=0,comment=" ").save()
        print bundle
        return bundle