def add_item_to_cart(request, item_pk, quantity=1, checkout=False): cart = Cart(request) item = get_object_or_404(Item, pk=item_pk) # checking input data, validate it and raise error if something # goes unusual, without any data post for time measure resons threshold = item.category.threshold try: quantity = int(quantity) except TypeError: raise Http404("Go fsck yourself") if int(quantity) < threshold: msg = _("You can not order less of item quantity then " "given threshold" ) return {'success': False, 'errors': unicode(msg)} if int(quantity) % threshold != 0: msg = _( "Quantity should be proportional to its item category threshold, " "you can not add items without it" ) return {'success': False, 'errors': unicode(msg)} ct = ContentType.objects.get( app_label=Item._meta.app_label, model=Item._meta.module_name) try: cart.add(item, item.get_cost(), quantity) except ItemAlreadyExists: cart_item = cart.cart.item_set.get(object_id=item_pk, content_type=ct) if checkout: cart_item.quantity = quantity else: cart_item.quantity += quantity cart_item.save() return {'redirect': 'catalog:cart'} return {'redirect': request.META.get('HTTP_REFERER', '/')}
def order_repeat(request, pk): order = get_object_or_404(Order, pk=pk) containers = order.order_container_order_set.all() cart = Cart(request) if cart.cart.item_set.count() != 0: messages.error( request, _("You can not repeat order if there's something " "in the cart, please cleanse it") ) # return redirect(request.META.get('HTTP_REFERER', '/')) return redirect(reverse('catalog:service-page', args=(order.container.owner.pk,))) for container in containers: model_class = container.content_type.model_class() item = get_object_or_None( model_class.whole_objects, pk=container.object_id ) if item.is_deleted: messages.warning( request, _("Item '%s' does not exist anymore, sorry") % \ item.title ) else: cart.add(item, item.get_cost(), container.quantity) # return redirect(request.META.get('HTTP_REFERER', '/')) return redirect(reverse('catalog:service-page', args=(order.container.owner.pk,)))
def test_successful_purchase_with_coupon(self): customer = mommy.make('payments.Customer') self.request.POST.update({'coupon': 'allthethings'}) form = CheckoutForm(self.request.POST) self.assertTrue(form.is_valid()) subscription = mommy.make('godjango_cart.Subscription', plan="monthly") cart = TheCart(self.request) cart.add(subscription, 9.00, 1) self.mock.StubOutWithMock(self.view, 'get_form_kwargs') self.mock.StubOutWithMock(views.CartMixin, 'get_cart') self.mock.StubOutWithMock(views.CustomerMixin, 'get_customer') self.mock.StubOutWithMock(customer, 'can_charge') self.mock.StubOutWithMock(customer, 'subscribe') self.view.get_form_kwargs().AndReturn( {'data': { 'coupon': 'allthethings' }}) views.CartMixin.get_cart().AndReturn(cart) views.CustomerMixin.get_customer().AndReturn(customer) customer.can_charge().AndReturn(True) customer.subscribe('monthly', coupon='allthethings') self.mock.ReplayAll() response = self.view.form_valid(form) self.mock.VerifyAll() self.assertEqual(response.status_code, 302)
def subscribe(request): cart = Cart(request) if cart.count() < 1: sub = Subscription.objects.get(plan="monthly") cart.add(sub, sub.price, 1) return redirect("checkout")
def test_add_with_quantity_to_existing_item(self): '''Adding an item with a quantity increases the quantity of an existing item.''' cart = Cart() cart.add('apple', 2) cart.add('apple', 3) self.assertEqual(cart.get_item('apple').quantity, 5)
def test_successful_purchase_with_coupon(self): customer = mommy.make('payments.Customer') self.request.POST.update({'coupon': 'allthethings'}) form = CheckoutForm(self.request.POST) self.assertTrue(form.is_valid()) subscription = mommy.make('godjango_cart.Subscription', plan="monthly") cart = TheCart(self.request) cart.add(subscription, 9.00, 1) self.mock.StubOutWithMock(self.view, 'get_form_kwargs') self.mock.StubOutWithMock(views.CartMixin, 'get_cart') self.mock.StubOutWithMock(views.CustomerMixin, 'get_customer') self.mock.StubOutWithMock(customer, 'can_charge') self.mock.StubOutWithMock(customer, 'subscribe') self.view.get_form_kwargs().AndReturn( {'data': {'coupon': 'allthethings'}}) views.CartMixin.get_cart().AndReturn(cart) views.CustomerMixin.get_customer().AndReturn(customer) customer.can_charge().AndReturn(True) customer.subscribe('monthly', coupon='allthethings') self.mock.ReplayAll() response = self.view.form_valid(form) self.mock.VerifyAll() self.assertEqual(response.status_code, 302)
def add_to_cart(request, product_id, quantity): product = Product.objects.get(id=product_id) cart = Cart(request) #print("Cart made") #print(request.session[CART_ID]) #data = {'product': product} cart.add(product, product.price, quantity)
def test_add_two_same_item(self): '''Adding more than one of the same item does not create duplicate CartItems.''' cart = Cart() cart.add('apple') cart.add('apple') self.assertEqual(len(cart), 1)
def add_to_cart_via_post(request): dictionary = baseDict(request) update_dict_for_main_page_redirect(dictionary, request) quantity = request.POST.get('quantity') if int(quantity) <= 0: # stop if the amount added is not positive dictionary.update({ "error_message" : "The quantity you added is %s, please put a positive number !" % quantity, 'nodes' : Category.objects.all(), }) # return render_to_response('index.html', dictionary, context_instance = RequestContext(request)) return render_to_response("products.html", dictionary, context_instance = RequestContext(request)) # otherwise fetch the product and add it's amount to the cart product_slug = request.POST.get('slug') product = Product.objects.get(slug=product_slug) if (int(product.quantity) - int(quantity)) < 0: dictionary.update({ 'error_message' : '%s has %d items left in stock !' % (product.title, product.quantity), 'nodes' : Category.objects.all(), }) return render_to_response("products.html", dictionary, context_instance = RequestContext(request)) cart = Cart(request) cart.add(product, product.price, quantity) # return render_to_response('index.html', dictionary, context_instance = RequestContext(request)) return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def add_to_cart(request): print "add to cart\n" product = Product.objects.get(id=request.POST["product_id"]) cart = Cart(request) cart.add(product) request.basket_number = cart.getItemCount() return render_to_response('basket.html', dict(cart=cart, total_price=cart.getTotalPrice(), products=Product.objects.all()), context_instance=RequestContext(request))
def test_get_total_multiple_items_multiple_quantity(self): '''Correct total for multiple items with multiple quantities in cart.''' cart = Cart(self._create_product_store()) cart.add('apple', 2) cart.add('strawberries', 3) self.assertEqual(cart.get_total(), Decimal('6.30'))
def add_to_cart(request): quantity = 1 supply_id = request.GET.get('id', None) if (supply_id): user_id = "anon" if request.user.id: user_id = request.user.id supply = Supply.objects.get(id=supply_id) cart = Cart(request) cart.add(supply, supply.price, quantity) analytics.track(user_id, 'Added to cart', { 'supply_id' : supply.id, "supply_name" : supply.name }) if request.session.get('email', '') == '': return redirect('cart.views.get_email') return redirect('cart.views.view_cart')
def test_email_change_while_checkingout(self, UpdateMock, SubscribeMock, ChargeMock): Customer.objects.create( user=self.user, stripe_id=1 ) request = self.factory.post( '/cart/checkout/', { 'stripeToken':'xxxxxxxxxx', 'email': '*****@*****.**' } ) request.user = self.user request.session = {} cart = TheCart(request) sub = Subscription.objects.get(plan='monthly') cart.add(sub, sub.price, 1) self.assertEqual(request.user.email, '*****@*****.**') response = views.checkout(request) self.assertEqual(response.status_code, 302) user = User.objects.get(pk=1) self.assertEqual(request.user.email, '*****@*****.**')
def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Art, id=product_id) update = request.POST['update'] in ['True'] quantity = int(request.POST['quantity']) cart.add(product=product, quantity=quantity, update_quantity=update) return redirect('cart_detail')
def test_get_total_multiple_items_multiple_quantity(self): '''Correct total for multiple items with multiple quantities in cart.''' cart = Cart(self._create_product_store()) cart.add('apple', 2) cart.add('kitkat', 3) self.assertEqual(cart.get_total(), float('6.30'))
def add_to_cart(request, product_id, quantity): product = Product.objects.get(custom_id=product_id) cart = Cart(request) cart.add(product, product.price, quantity) print "ADD: %s - %s" % (product_id, quantity) # return render(request, 'index.html', {'cart' : cart}) #return render(request, 'cart.html', {'cart' : cart}) return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def test_add_two_same_item_increases_quantity(self): '''Adding an item that is already in the cart increases its quantity.''' cart = Cart() cart.add('apple') cart.add('apple') cartitem = cart.get_item('apple') self.assertEqual(cartitem.quantity, 2)
def add_to_cart(request): id = ClientJob.objects.aggregate(Max('job_no')) maxid =id['job_no__max'] product = TestTotal.objects.get(job_no=maxid) #unit = TestTotal.objects.values_list('unit_price',flat=True).filter(job_no=maxid) #unit_price = unit cart = Cart(request) cart.add(product, product.unit_price)
def test_get_item(self): '''cart.get_item() returns expected CartItem.''' cart = Cart() cart.add('apple') cart.add('kitkat') returned_cart_item = cart.get_item('apple') self.assertTrue(type(returned_cart_item) is CartItem) self.assertEqual(returned_cart_item.product, 'apple')
def test_get_total_with_one_offer(self): '''Cart get_total returns correct value with a bogof offer applied.''' product_store = self._create_product_store() bogof_kitkat = MultiBuyOffer('kitkat', 1, 1) cart = Cart(product_store) cart.add('kitkat', 2) cart.add('apple') self.assertEqual(cart.get_total(offers=[bogof_kitkat]), float('0.85'))
def test_get_item(self): '''cart.get_item() returns expected CartItem.''' cart = Cart() cart.add('apple') cart.add('orange') returned_cart_item = cart.get_item('apple') self.assertTrue(type(returned_cart_item) is CartItem) self.assertEqual(returned_cart_item.product, 'apple')
def add(request): if(request.is_ajax() and request.POST): video = get_object_or_404(Video, pk=request.POST['video_pk']) cart = Cart(request) cart.add(video, video.price, 1) return HttpResponse("{'success':true}", mimetype="application/json") else: raise Http404
def add_to_cart(request, product_id, quantity): product = Product.objects.get(id=product_id) cart = Cart(request) try: cart.add(product, product.get_price(), quantity) except: pass return HttpResponseRedirect(reverse('cart_detail'))
def combined_offer(self): cart = Cart() cart.add('Biscuits',8) cart.add('Baked Beans',4) multibuy_apples = BuyGetOffer('Biscuits', 5, 2) percentdiscount = PercentageDiscountOffer('Baked Beans',0.15) self.assertEqual( cart.get_total(offers=[multibuy_apples,percentdiscount]), Decimal(10.566))
def test_get_total_with_one_offer(self): '''Cart get_total returns correct value with a bogof offer applied.''' product_store = self._create_product_store() bogof_strawberries = MultiBuyOffer('strawberries', 1, 1) cart = Cart(product_store) cart.add('strawberries', 2) cart.add('apple') self.assertEqual(cart.get_total(offers=[bogof_strawberries]), Decimal('2.15'))
def test_get_total_with_one_offer(self): '''Cart get_total returns correct value with a bogof offer applied.''' product_store = self._create_product_store() bogof_strawberries = MultiBuyOffer('strawberries', 1, 1) cart = Cart(product_store) cart.add('strawberries', 2) cart.add('apple') self.assertEqual( cart.get_total(offers=[bogof_strawberries]), Decimal('2.15'))
def add_to_cart(request, product_id): if request.is_ajax(): your_price = calculate_your_price(request, product_id) part = Part.objects.get(id=product_id) # import pdb; pdb.set_trace() cart = Cart(request) cart.add(part, your_price, part.surcharge, 1) return HttpResponse('part added to cart.') else: return HttpResponseRedirect('/')
def add(request, pk): product = or404(Product, pk=pk) cart = Cart(request) try: cart.add(product, product.unit_price, 1) except ItemAlreadyExists: # Update cart item quantity if product already exists in the cart cart_item(cart.cart, product.pk).update(quantity=F('quantity') + 1) return items(request)
def cart_add(request, product_id): cart = Cart(request) producto = get_object_or_404(Producto, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=producto, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail')
def add_to_cart(request): if request.method == 'POST': my_key = request.POST.get('key') my_qty = request.POST.get('qty') my_price = request.POST.get('price') item = Item.objects.get(id=my_key) cart = Cart(request) cart.add(item,my_price,my_qty) data = {'status':'success'} response = HttpResponse(json.dumps(data),mimetype="application/json") return response
def test_two_with_one_dependent(self): '''Two target product in the presence of one dependent product triggers discount.''' product_store = self._create_product_store() mars_snickers_20_discount = DependentDiscountOffer( 'mars bar', 'snickers bar', Decimal('0.2')) cart = Cart(product_store) mars_cartitem = cart.add('mars bar', 2) cart.add('snickers bar') self.assertEqual(mars_snickers_20_discount.calculate_line_total( mars_cartitem, product_store, cart), Decimal('1.17'))
def test_get_total_with_dependent_discount_offer(self): '''Cart get_total returns correct value with a dependent discount offer applied.''' product_store = self._create_product_store() strawberries_apple_20_discount = DependentDiscountOffer( 'strawberries', 'apple', Decimal('0.2')) cart = Cart(product_store) cart.add('strawberries', 2) cart.add('apple') self.assertEqual( cart.get_total(offers=[strawberries_apple_20_discount]), Decimal('3.75'))
def test_two_with_one_dependent(self): '''Two target product in the presence of one dependent product triggers discount.''' product_store = self._create_product_store() mars_snickers_20_discount = DependentDiscountOffer( 'mars bar', 'snickers bar', Decimal('0.2')) cart = Cart(product_store) mars_cartitem = cart.add('mars bar', 2) cart.add('snickers bar') self.assertEqual( mars_snickers_20_discount.calculate_line_total( mars_cartitem, product_store, cart), Decimal('1.17'))
def add_to_cart_async(request): # Get cart object cart = Cart(request) # Decode json request parameters data = json.loads(request.body) product = Goodie.objects.get(pk=data['id']) price = product.price quantity = data['quantity'] cart.add(product, price, quantity) return JsonResponse({"status": "added"})
def test_get_total_with_dependent_discount_offer(self): '''Cart get_total returns correct value with a dependent discount offer applied.''' product_store = self._create_product_store() kitkat_apple_20_discount = DependentDiscountOffer( 'kitkat', 'apple', float('0.2')) cart = Cart(product_store) cart.add('kitkat', 2) cart.add('apple') self.assertEqual( round(cart.get_total(offers=[kitkat_apple_20_discount]), 2), float('1.41'))
def test_get_total_with_two_offers_on_same_target(self): '''Cart get_total returns cheapest total when two offers are applicable for the same target.''' product_store = self._create_product_store() bogof_strawberries = MultiBuyOffer('strawberries', 1, 1) strawberries_apple_20_discount = DependentDiscountOffer( 'strawberries', 'apple', Decimal('0.2')) cart = Cart(product_store) cart.add('strawberries', 2) cart.add('apple') self.assertEqual(cart.get_total( offers=[bogof_strawberries, strawberries_apple_20_discount]), Decimal('2.15'))
def add_to_cart(request): product_id = request.POST['product_id'] qty = request.POST['qty'] product = Product.objects.get(id=product_id) cart = Cart(request) if in_cart(cart, product_id): cart.remove(product) cart.add(product, product.price, qty) else: cart.add(product, product.price) mykwrgs = get_kwrgs(request) return render(request, 'shop/cart.html', mykwrgs)
def test_cart_test(self): c = Cart() c.add((1, 1, 1)) self.assertEqual(c[0][0], 1) c.append((2, 2, 2)) self.assertEqual(c[1][0], 2) self.assertEqual(c.total(), 2) self.assertEqual(c.total_items(), 3) c.delete(0) self.assertEqual(c.total(), 1) self.assertEqual(c[0][0], 2) self.assertEqual(c.total_items(), 2)
def test_cart_test(self): c = Cart() c.add((1,1,1)) self.assertEqual(c[0][0], 1) c.append((2,2,2)) self.assertEqual(c[1][0], 2) self.assertEqual(c.total(), 2) self.assertEqual(c.total_items(), 3) c.delete(0) self.assertEqual(c.total(), 1) self.assertEqual(c[0][0], 2) self.assertEqual(c.total_items(), 2)
def test_remove_from_cart(self): self.assertEqual(0, Cart.objects.count()) cart = TheCart(self.request) cart.add(self.video, self.video.price, 1) view = views.CartRemoveView() view.request = self.request response = view.post(self.request) self.assertEqual(200, response.status_code) cart = Cart.objects.all()[0] self.assertEqual(0, cart.item_set.count())
def test_two_with_one_dependent(self): '''Two target product in the presence of one dependent product triggers discount.''' product_store = self._create_product_store() mars_snickers_20_discount = DependentDiscountOffer( 'ice cream', 'dairy milk', float('0.2')) cart = Cart(product_store) mars_cartitem = cart.add('ice cream', 2) cart.add('dairy milk') self.assertEqual( round( mars_snickers_20_discount.calculate_line_total( mars_cartitem, product_store, cart), 2), float('6.28'))
def test_get_total_with_two_offers_on_same_target(self): '''Cart get_total returns cheapest total when two offers are applicable for the same target.''' product_store = self._create_product_store() bogof_kitkat = MultiBuyOffer('kitkat', 1, 1) kitkat_apple_20_discount = DependentDiscountOffer( 'kitkat', 'apple', float('0.2')) cart = Cart(product_store) cart.add('kitkat', 2) cart.add('apple') self.assertEqual( cart.get_total(offers=[bogof_kitkat, kitkat_apple_20_discount]), float('0.85'))
def generateCartWithItems(self, request): fixture = AutoFixture(Category) category = fixture.create(1) fixture = AutoFixture(Product) products = fixture.create(5) # 5 products quantity = 3 # added 3 times, thus 5*3=15 products[0].title="kartofi" products[1].title="makaroni" cart = Cart(request) for product in products: cart.add(product, product.price, quantity) return cart
def test_get_total_with_two_offers_on_same_target(self): '''Cart get_total returns cheapest total when two offers are applicable for the same target.''' product_store = self._create_product_store() bogof_strawberries = MultiBuyOffer('strawberries', 1, 1) strawberries_apple_20_discount = DependentDiscountOffer( 'strawberries', 'apple', Decimal('0.2')) cart = Cart(product_store) cart.add('strawberries', 2) cart.add('apple') self.assertEqual( cart.get_total( offers=[bogof_strawberries, strawberries_apple_20_discount]), Decimal('2.15'))
class Chef(object): def __init__(self, name): self.name = name self.cart = Cart(self) self.kitch = MyKitch(self) def get_recieved_orders(self): pass def add_to_cart(self, item): self.cart.add(self, item) def place_order(self): pass
def add_to_cart(request): quantity = request.POST.get('quantity') menu_id = request.POST.get('menu_id') menu_item = MenuItem.objects.get(id=menu_id) cart = Cart(request) cart.add(menu_item, menu_item.unit_price, quantity) total = cart.summary() data = { "quantity": quantity, "total": str(total), "name": menu_item, "price": str(menu_item.unit_price), } return HttpResponse(json.dumps(data))
def test_save(self): post = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 2, 'form-0-quantity': 5, 'form-1-quantity': 5} cart = Cart() cart.add(stock_product, 10) cart.add(digital_product, 100) form = ReplaceCartLineFormSet(post, cart=cart) self.assertTrue(form.is_valid()) form.save() product_quantity = cart.get_line(stock_product).quantity self.assertEqual(product_quantity, 5, '%s is the bad quantity value' % (product_quantity,))
def add_to_cart(request): try: sel_prod_id = request.POST['prod_id'] except: return render(request, 'index.html', { 'err_msg': 'Product selecting error.' }) product = get_object_or_404(Product, pk=sel_prod_id) cart = Cart(request) cur_q = cart.get_current_quantity(product) if cur_q == 0: cart.add(product, product.price) else: cart.update(product, product.price, cur_q + 1) return redirect(reverse('shop:cart'))
def test_buy_get_offer(self): #Calculate the price while there is buy 3 get 2 offer with quantity 3 cart = Cart() cartitem=cart.add('Biscuits',3) multibuy_apples=BuyGetOffer('Biscuits', 3, 2) self.assertEqual(multibuy_apples.calculate_line_total( cartitem), Decimal('3.6'))
def test_percentage_discount_offer(self): #calculate the price while there is 25% offer in product cart = Cart() cartitem=cart.add('Baked Beans',4) percentdiscount = PercentageDiscountOffer('Baked Beans',0.15) self.assertEqual( cart.get_total(offers=[percentdiscount]), Decimal(3.366))
def test_save(self): post = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 2, 'form-0-quantity': 5, 'form-1-quantity': 5 } cart = Cart() cart.add(stock_product, 10) cart.add(digital_product, 100) form = ReplaceCartLineFormSet(post, cart=cart) self.assertTrue(form.is_valid()) form.save() product_quantity = cart.get_line(stock_product).quantity self.assertEqual(product_quantity, 5, '%s is the bad quantity value' % (product_quantity, ))
def test_buy_get_offer(self): #Calculate the price while there is buy 3 get 2 offer with quantity 6 cart = Cart() cartitem=cart.add('Biscuits',6) multibuy_apples=BuyGetOffer('Biscuits', 3, 2) self.assertEqual( cart.get_total(offers=[multibuy_apples]), Decimal(4.8))