Exemple #1
0
    def clean_discount(self):
        discount = self.cleaned_data['discount'] or None
        if discount:
            if discount > self.request.user.bonus_score:
                raise forms.ValidationError(
                    _("You can not spend more bonus points than you have")
                )
            cart = Cart(self.request)
            price = cart.get_total_price()
            threshold = settings.DEFAULT_BONUS_PAY_THRESHOLD_AMOUNT
            exchange = settings.DEFAULT_EXCHANGE_RATE

            msg = _(
                """Maxium discount you can get
                is '%(percent)s' of '%(amount)s is %(max)s'""") % {
                'percent': str(threshold * 100) + '%',
                'amount': price,
                'max': str(round(price * Decimal(str(threshold))))
            }
            if Decimal(str(discount * exchange)) > (price * Decimal(str(threshold))):
                raise forms.ValidationError(msg)
            if discount < 0:
                raise forms.ValidationError(
                    _("You can not proceed negative values for discount")
                )
        return discount
Exemple #2
0
    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, '*****@*****.**')
Exemple #3
0
def checkout(request):
    template_name='cart/checkout.html'
    pp_urls=None
    model=None
    '''
    Renders a form ready to be submit to paypal. Passes PAYPAL_URL, which is
    taken from settings. Also passes total, which is the total amount
    of all the cart items
    '''
    if request.user.is_authenticated():
        cart_id=request.session.get('CART-ID')
#        print cart_id, request.user
        cartModel = models.Cart.objects.get(id=cart_id)
        cartModel.user=request.user
        cartModel.save()
#        cartModel=models.Cart.objects.get(user=request.user)
        cart=Cart(request)
        items = Item.objects.filter(cart=cartModel)
        if model:
            ct = ContentType.objects.get_for_model(model)
            items = items.filter(content_type=ct)
        form = CheckoutForm(items, pp_urls)
        total = cart.total()
    #    for item in items:
    #        total += item.amount
        return render_to_response(template_name,{
                "form":form,
                "PAYPAL_URL": settings.PAYPAL_URL,
                "total": total,
                },context_instance=RequestContext(request))
    else:
        print "An user is not registered"
Exemple #4
0
def index(request):
    context = get_common_context(request)
    
    cart = Cart(request)
    cart.clear()   
    
    return render_to_response('common/default.html', context, context_instance=RequestContext(request))
Exemple #5
0
def thankyou(request):
    context = get_common_context(request)
    
    cart = Cart(request)
    cart.clear()   
    
    return render_to_response('common/thankyou.html', context, context_instance=RequestContext(request))
Exemple #6
0
def search_library(query):
    """Search the music library for tracks and carts.

    :param query: search term
    """
    results = []

    try:
        res = requests.get(URL_STUDIOSEARCH, params={"query": query})
        results_res = res.json()

        for cart_res in results_res["carts"]:
            filename = LIBRARY_PREFIX + "carts/" + cart_res["filename"]

            cart = Cart(cart_res["cartID"], cart_res["title"], cart_res["issuer"], cart_res["type"], filename)
            if cart.is_playable():
                results.append(cart)

        for track_res in results_res["tracks"]:
            filename = LIBRARY_PREFIX + track_res["file_name"]
            track_id = track_res["album_code"] + "-" + track_res["track_num"]

            track = Cart(track_id, track_res["track_name"], track_res["artist_name"], track_res["rotation"], filename)
            if track.is_playable():
                results.append(track)
    except requests.exceptions.ConnectionError:
        print "Error: Could not fetch search results."

    return results
Exemple #7
0
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)
Exemple #8
0
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,)))
Exemple #9
0
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', '/')}
Exemple #10
0
def checkout(request):
    template_name='cart/checkout.html'
    pp_urls=None
    model=None
    '''
    Renders a form ready to be submit to paypal. Passes PAYPAL_URL, which is
    taken from settings. Also passes total, which is the total amount
    of all the cart items
    '''
#    cart=Cart.objects.get(user=request.user)
    cartModel=models.Cart.objects.get(user=request.user)
#    cartModel.user=request.user
    print 'test'
    print 'username is'+ request.user.username + request.user.id
#    print cartModel.id
    cart=Cart(request)
    items = Item.objects.filter(cart=cart)
    if model:
        ct = ContentType.objects.get_for_model(model)
        items = items.filter(content_type=ct)
    form = CheckoutForm(items, pp_urls)
    total = cart.total()
#    for item in items:
#        total += item.amount
    return render_to_response(template_name,{
            "form":form,
            "PAYPAL_URL": settings.PAYPAL_URL,
            "total": total,
            },context_instance=RequestContext(request))
Exemple #11
0
def remove_from_cart(request):
    product_id = request.POST['product_id']
    kw = get_kwrgs(request)
    product = Product.objects.get(id=product_id)
    cart = Cart(request)
    cart.remove(product)
    return render(request, 'shop/cart.html', kw)
Exemple #12
0
def get_carts():
    """Load a dictionary of cart arrays for each cart type."""
    carts = {
        0: [],
        1: [],
        2: [],
        3: []
    }

    try:
        for cart_type in carts:
            res = requests.get(URL_CARTLOAD, params={"type": cart_type})
            carts_res = res.json()

            for cart_res in carts_res:
                # TODO: move pathname building to Cart constructor
                filename = LIBRARY_PREFIX + "carts/" + cart_res["filename"]

                cart = Cart(cart_res["cartID"], cart_res["title"], cart_res["issuer"], cart_res["type"], filename)

                if cart.is_playable():
                    carts[cart_type].append(cart)

    except requests.exceptions.ConnectionError:
        print time.asctime() + " :=: Error: Could not fetch carts."

    return carts
Exemple #13
0
    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)
Exemple #14
0
def delete_cart(request, id):
    cart = Cart(request)
    cart.delete(id)
    if request.META.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest':
        return HttpResponse(cart.serialize())
    else:
        return redirect(reverse('show_cart'))
Exemple #15
0
    def clean(self):
        # deliver_date, deliver_time
        dd = self.cleaned_data.get('deliver_date', None)
        dt = self.cleaned_data.get('deliver_time', None)

        cart = Cart(self.request)
        total_price = cart.get_total_price()
        item_ct = get_model_content_type(Item)
        item = cart.cart.item_set.filter(content_type=item_ct)

        minimal_cost = item[0].product.container.owner.minimal_cost if len(item) else 0
        if total_price < minimal_cost and total_price > 0:
            msg = _("Minimal cost for order is '%s' for this service, "
            "you should get more items to process") % minimal_cost
            self._errors['name'] = ErrorList([msg])

        if all((dd, dt)):
            now = datetime.now()
            offset = now + timedelta(minutes=30)
            st = datetime(dd.year, dd.month, dd.day, dt.hour, dt.minute, dt.second)
            if st <= offset:
                msg = _("You can not order in the past")
                self._errors['deliver_date'] = ErrorList([msg])

        return self.cleaned_data
Exemple #16
0
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")
Exemple #17
0
def cart_checkout(request, template='events/cart_checkout.html'):
    context = {}
    cart = CartManager(request)
    if request.method == 'POST':
        try:
            stripe.api_key = settings.STRIPE_PRIVATE_KEY
            # get the credit card details submitted by the form
            token = request.POST['stripeToken']
            # create the charge on Stripe's servers - this will charge the user's card
            charge = stripe.Charge.create(
                amount=int(cart.summary()*100), # amount in cents
                currency="usd",
                card=token,
                description=request.user.email
            )
            if charge.get('paid'):
                subject = _(u'[Django Events] Your purchase has been accepted.')
                message = 'You bought:\n'
                for ticket_order in cart:
                    message += '%s * %s for %s\n' % (ticket_order.quantity,
                                                     ticket_order.ticket.name,
                                                     ticket_order.ticket.event.name)
                send_mail(subject, message, '*****@*****.**',
                          [request.user.email], fail_silently=True)
                cart.check_out()
                return HttpResponse('TRUE')
            return HttpResponse('FALSE')
        except:
            import traceback
            traceback.print_exc()
Exemple #18
0
def cart(request):
    _cart = Cart(request)
    items = len(list(_cart.cart.item_set.all()))
    item_ct = get_model_content_type(Item)
    addon_ct = get_model_content_type(Addon)

    products = _cart.cart.item_set.filter(content_type=item_ct)
    addons = _cart.cart.item_set.filter(content_type=addon_ct)
    total_price = _cart.get_total_price()
    bonus_max = round(total_price * Decimal(str(0.1 / settings.DEFAULT_EXCHANGE_RATE)))
    service = None
    deliver_cost = None

    if products:
        # item could be deleted so careful
        try:
            service = products.all()[0].product.container.owner
            deliver_cost = service.get_deliver_cost(total_price)
        except ObjectDoesNotExist:
            _cart.cart.item_set.all().delete()
    context = {
        "cart": _cart,
        "kart": {
            "total_price": _cart.get_total_price(),
            "products": products,
            "cart_items": items or None,
            "addons": addons,
            "bonus_max": int(bonus_max),
            "service": service,
            "deliver_cost": int(deliver_cost) if deliver_cost is not None else None,
        },
    }

    return context
Exemple #19
0
def order_cart(request):
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            subject = u'Заказ с сайта'
            recipients = []
            try:
                recipients.extend(emails_list(request.settings.email))
            except:
                recipients.append(settings.ADMINS[0][1])
            cart = Cart(request, init=True)
            letter_context = form.cleaned_data
            letter_context.update({'site': request.settings.project})
            order_text = render_to_string('order_info.txt', {'cart': cart})
            letter_content = render_to_string('order_letter.txt', letter_context)
            letter_content += order_text
            send_mail(subject, letter_content, letter_context['email'] or recipients[0], recipients)
            success_message = u"""
            Благодарим за то, что Вы воспользовались услугами нашего Интернет-магазина.
            Ваша заявка принята в обработку и наш менеджер свяжется с Вами в ближайшее время для уточнения деталей.
            Мы будем благодарны Вам, если Вы оставите на нашем сайте свой отзыв о работе нашего  Интернет-магазина.
            """
            messages.add_message(request, messages.SUCCESS, success_message)
            cart.delete_all()
            return HttpResponseRedirect('')
    else:
        form = OrderForm()
    return render_to_response('cart_order.html', {'form': form},
        context_instance=RequestContext(request))   
Exemple #20
0
 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)
Exemple #21
0
 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)
Exemple #22
0
def clear_cart(request):
    if request.is_ajax():
        cart = Cart(request)
        cart.clear()
        return HttpResponse('cart was destroyed.')
    else:
        return HttpResponseRedirect('/')
Exemple #23
0
def submit_single(request, shipping, items, final_amount, coupon_amount):
	print('submit_single:', shipping.contact)

	item = items[0]
	order = item.product
	order.shipping = shipping
	order.status = 'OR'
	order.amount = float(order.amount) - (coupon_amount / 100.0);
	order.coupon = request.POST.get('coupon_code', '')

	order.save()

	mail_order_confirmation(shipping.contact, order.meshu, order)

	# send a mail to ifttt that creates an svg in our dropbox for processing
	mail_ordered_svg(order)

	current_cart = Cart(request)
	current_cart.clear()

	return render(request, 'meshu/notification/ordered.html', {
		'view': 'paid',
		'order': order,
		'meshu': order.meshu
	})
Exemple #24
0
def make_order(request):
    cart = Cart(request)
    user = request.user
    order = None
    if not user.is_authenticated():
        order = Order(client_name=u'Не зарегистрирован, ' + request.POST["name"], client_phone=request.POST["phone"], order_status=OrderStatus.objects.get(status='Принят'))
        order.order_info = "\n".join([item.product.brand + " " + str(item.count) for item in cart])
        order.save()
        for item in cart:
            item.order = order
            item.code = item.product.code
            item.brand = item.product.brand
            item.price_1 = item.product.price_with_currency
            item.price_2 = item.get_price_with_discount()
            item.supplier = item.product.supplier
            item.save()
    else:
        for item in cart:
            item.user = user
            item.code = item.product.code
            item.brand = item.product.brand
            item.price_1 = item.product.price_with_currency
            item.price_2 = item.get_price_with_discount()
            item.supplier = item.product.supplier
            item.save()
    cart.cart.checked_out = True
    cart.cart.save()
    cart.change_id(request)
    cart = Cart(request)
    request.basket_number = 0
    return HttpResponseRedirect("/basket")
Exemple #25
0
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))
Exemple #26
0
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')
Exemple #27
0
def ajax_eliminaritem(request):
	product_id=request.POST["item_id"]
 	product = Producto.objects.get(id=product_id)
 	cart = Cart(request)
 	cart.remove(product)
 	total_carrito =cart.total_cart
 	return HttpResponse(total_carrito)
Exemple #28
0
def get_cart(request):

    cart = Cart(request)

    if request.user.is_authenticated():
        try:
            customer = Customer.objects.get(user=request.user)
        except:
            customer = None
    else:
        customer = None

    if request.method == 'POST':
        form = CustomerForm(request.POST, instance=customer)
        order_form = OrderForm(request.POST)
        if form.is_valid():

            # SAVE CUSTOMER
            new_customer = form.save(commit=False)
            if request.user.is_authenticated():
                new_customer.user = request.user
            new_customer.save()

            if order_form.is_valid():

                # SAVE ORDER
                new_order = order_form.save(commit=False)
                new_order.customer = new_customer

                new_order.cust_name = new_customer.name
                new_order.cust_email = new_customer.email
                new_order.cust_phone = new_customer.phone
                new_order.cust_city = new_customer.city
                new_order.cust_postcode = new_customer.postcode
                new_order.cust_address = new_customer.address

                new_order.summary = cart.summary()
                new_order.save()
                new_order.number = new_order.get_number(new_order.id)
                new_order.save()

                # SAVE CART TO ORDER DETAIL
                for item in cart:
                    new_item = OrderDetail()
                    new_item.order = new_order
                    new_item.product = item.product
                    new_item.price = item.unit_price
                    new_item.quantity = item.quantity
                    new_item.total_price = item.total_price
                    new_item.save()
                cart.clear()

                return direct_to_template(request, 'fshop/order_thanks.html',{'object':new_order})

    else:
        form = CustomerForm(instance=customer)
        order_form = OrderForm()

    return direct_to_template(request, 'fshop/cart_detail.html', {'cart':cart, 'form':form, 'order_form':order_form})
Exemple #29
0
    def save(self, commit=True):
        """ if not commit, please add items manual """
        instance = self.instance
        cart = Cart(self.request)
        discount = self.cleaned_data['discount'] or 0
        exchange = settings.DEFAULT_EXCHANGE_RATE
        total_price = cart.get_total_price()

        instance.cost = total_price  # - Decimal(str(discount * exchange))
        instance.discount = Decimal(str(discount * exchange))

        new_user = None
        if all((self.cleaned_data['is_register'], self.cleaned_data['email'])):
            new_user = User.objects.create(
                email=self.cleaned_data['email'],
                username=self.cleaned_data['email'],
                phone=self.cleaned_data['phone']
            )
            new_password = uuid1().hex[:6]
            new_user.set_password(new_password)
            new_user.save()

            email = new_user.email
            link = settings.SITE_URL + '/login'
            login = new_user.username

            send_mail(
                subject=unicode(_(u"Регистрация на uzevezu.ru")),
                message=unicode(settings.ORDER_REGISTER_MESSAGE % {
                    'password': new_password,
                    'login': login,
                    'link': link
                }),
                from_email=settings.EMAIL_FROM,
                recipient_list=[email, ],
                fail_silently=True
            )
        if self.request.user.is_authenticated() or new_user:
            instance.client = new_user or self.request.user
        super(OrderForm, self).save(commit)

        is_authenticated = reduce(
            lambda x,y: getattr(x, y) if hasattr(x, y) else None,
            [self.request, 'user', 'is_authenticated']
        )
        if not is_authenticated():
            # send sms
            sms = SMSLogger.objects.create(
                provider='disms',
                phone=self.cleaned_data['phone'],
                text=settings.ANONYMOUS_ORDER_MESSAGE
            )
            sms.send_message()
            sms.save()
            return self.instance

        # reloading bonus score
        self.request.user.reload_bonus_score(rebuild=True)
        return self.instance
Exemple #30
0
def remove_from_cart(request, product_id):
#    form = my_form(request.GET)
#    if form.is_valid():
    product = Product.objects.get(id=product_id)
    cart = Cart(request)
    cart.remove(product)
    return render_to_response('cart/cart.html', dict(cart=Cart(request)),
                                  context_instance=RequestContext(request))
Exemple #31
0
def remove_from_cart(request, product_slug):
	dictionary = baseDict(request)
	update_dict_for_main_page_redirect(dictionary, request)

	product = Product.objects.get(slug=product_slug) # fetch the product we want to remove
	cart = Cart(request) # fetch the cart
	cart.remove(product) # remove the item

	return render_to_response('cart.html', dictionary, context_instance = RequestContext(request))
Exemple #32
0
def remove():
    product = db(db.product.id == request.args(0)).select().first()
    cart = Cart()
    try:
        # If the order is not found, an exception will be raised.
        cart.DecreaseAmount(product.id)
    except OrderError as e:
        return e
    return locals()
Exemple #33
0
def remove_from_cart(request, menu_name, table_name, product_name):
    product = Product.objects.get(name=product_name)
    cart = Cart(request)
    cart.remove(product)
    return HttpResponseRedirect(
        reverse('select_table',
                kwargs={
                    'menu_name': menu_name,
                    'table_name': table_name
                }))
Exemple #34
0
    def __init__(self, sys_clk, with_sdram):
        self.sys_clk = sys_clk * 1e6
        self.with_sdram = with_sdram

        self.cart = Cart(sys_clk)
        self.cpu = SERV()
        self.sdram = SDRAMController(self.sys_clk)
        #self.uart = UART(int(self.sys_clk//115200))
        self.buffer = Memory(width=16, depth=256)

        self.wb_uart = WishboneUART(int(self.sys_clk // 115200))
Exemple #35
0
class CartTest(unittest.TestCase):
    def setUp(self):
        self.menu = Menu('pokeS', 'Available', 12.06, 1, 'Contains Raw fishes')
        self.cart = Cart(self.menu, 1)

    def test_Quantity(self):
        self.assertEqual(self.cart.getQuantity(), 1)

    def test_Menu(self):
        menu = self.cart.getMenu()
        self.assertEqual(str(menu), 'pokeS')
    def check_complex(self, t):
        # GIVEN
        cart = Cart()

        # WHEN
        for i in t['input']:
            cart.process_request(i, True)

        print(cart.generate_invoice(True))
        # THEN
        self.assertEqual(cart.bill, t['expected'])
Exemple #37
0
def remove_from_cart(request, product_id):
    print "Rremove from cart: %s" % (product_id)
    product = Product.objects.get(custom_id=product_id)
    cart = Cart(request)
    product_removed = cart.remove(product)
    url = reverse("index")
    if product_removed:
        request.session['status'] = "%s removed from Cart!" % product.name
    else:
        request.session['status'] = "%s not in Cart!" % product.name
    return HttpResponseRedirect(url)
Exemple #38
0
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')
Exemple #39
0
 def test_one_without_dependent(self):
     '''One target product in the absence of its dependent product doesn't
     trigger 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')
     self.assertEqual(
         mars_snickers_20_discount.calculate_line_total(
             mars_cartitem, product_store, cart), Decimal('0.65'))
 def __init__(self):
     self.transactionNum = 0
     self.inventory = Inventory()
     self.cart = Cart()
     self.todayDate = date.today()
     self._customerOption = ""
     self._menuOption = 0
     self._transactionOption = 0
     self._addInput = []
     self._cashAmount = 0.0
     self._rmvOption = 0
Exemple #41
0
 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'))
Exemple #42
0
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"})
Exemple #43
0
 def test_one_without_dependent(self):
     '''One target product in the absence of its dependent product doesn't
     trigger 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')
     self.assertEqual(
         round(
             mars_snickers_20_discount.calculate_line_total(
                 mars_cartitem, product_store, cart), 2), float('3.49'))
Exemple #44
0
def add_to_cart(request, product_id, quantity):
    print "Add to cart: %s - %s" % (product_id, quantity)
    product = Product.objects.get(custom_id=product_id)
    cart = Cart(request)
    product_added = cart.add(product, product.price, quantity)
    url = reverse("index")
    if product_added == 1:
        request.session['status'] = "%s added to Cart!" % product.name
    else:
        request.session[
            'status'] = "%s quantity updated in Cart!" % product.name
    return HttpResponseRedirect(url)
Exemple #45
0
def order_cart(request):
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            subject = u'Заказ с сайта'
            recipients = []
            try:
                recipients.extend(emails_list(request.settings.email))
            except:
                recipients.append(settings.ADMINS[0][1])
            cart = Cart(request, init=True)
            # Order insertion
            if cart.objects:
                order = Order.objects.create(
                    fio=form.cleaned_data['fio'],
                    address='',
                    phones=form.cleaned_data['phones'],
                    email=form.cleaned_data['email'],
                    comment=form.cleaned_data['comment'])
                for item in cart.objects:
                    order.items.create(label=item.label,
                                       amount=item.amount,
                                       price=item.price)
            subject = u'Поступил заказ с сайта %s' % settings.PROJECT_TITLE
            letter_context = form.cleaned_data
            letter_context.update({
                'site': settings.PROJECT_TITLE,
                'cart': cart,
                'subject': subject
            })

            text_content = render_to_string('letters/order_text.txt',
                                            letter_context)
            html_content = render_to_string('letters/order_html.html',
                                            letter_context)

            msg = EmailMultiAlternatives(subject, text_content, recipients[0],
                                         recipients)
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            cart.delete_all()
            success_message = request.infoblock.get(
                'order_send_message', u"""
            Благодарим за то, что Вы воспользовались услугами нашего Интернет-магазина.
            Ваша заявка принята в обработку, и наш менеджер свяжется с Вами в ближайшее время для уточнения деталей.
            """)
            messages.add_message(request, messages.SUCCESS, success_message)
            return redirect(reverse('message_list'))
    else:
        form = OrderForm()
    return render_to_response('cart_order.html', {'form': form},
                              context_instance=RequestContext(request))
Exemple #46
0
 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'))
Exemple #47
0
    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())
Exemple #48
0
	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
Exemple #49
0
 def __init__(self, aggregatedData):
     self.cart = Cart(aggregatedData)
     self.bonusPanel = BonusPanel(aggregatedData)
     self.updated = Event()
     self.selected = Event()
     self.__aData = aggregatedData
     self.__currentType = CUSTOMIZATION_TYPE.CAMOUFLAGE
     self.__currentIdx = 0
     self.__data = None
     self.__initialData = None
     self.__updateSlotsData(False)
     self.__aData.updated += self.__updateSlotsData
     return
Exemple #50
0
def checkout(request):
    #-------------请求参数-------------
    #-------必填参数---------
    #请与贵网站订单系统中的唯一订单号匹配
    out_trade_no = baseutil.time_hash()

    #订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里
    subject = alipay_settings.subject
    #订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述里
    body = alipay_settings.body
    cart = Cart(request)
    for item in cart:
        body = "%s%sx%d+" % (body, item.product.name, item.quantity)
    body = body[:-1]
    #订单总金额,显示在支付宝收银台里的“应付总额里
    #以后添加促销策略,就在这里修改实际应付金额。在页面中传值过来容易被firebug等手动改变
    #记得测试完改回total_fee = cart.total_fee
    #total_fee = 0.01 #测试时使用
    total_fee = cart.total_fee
    #------end of 必填参数------

    #///////扩展功能参数——其他///
    show_url = alipay_settings.show_url
    #-----------endof请求参数----------

    #/////商户自己的业务逻辑/////#
    cart = Cart(request)
    #关闭cart购物车,防止付款之前购物车内内容改变
    cart.cart.checked_out = True
    cart.cart.save()
    #记录transaction
    now = datetime.datetime.now()
    Transaction.objects.create(out_trade_no=out_trade_no,
                               user=request.user,
                               cart=cart.cart,
                               payed_fee=0,
                               trade_time=now)

    #把请求参数打包成数组
    sParaTemp = {}
    sParaTemp["payment_type"] = "1"
    sParaTemp["show_url"] = show_url
    sParaTemp["out_trade_no"] = out_trade_no
    sParaTemp["subject"] = subject
    sParaTemp["body"] = body
    sParaTemp["total_fee"] = total_fee
    #构造即时到帐接口表单提交HTML数据,无需修改
    alipay = Service()
    strHtml = alipay.Create_direct_pay_by_user(sParaTemp)
    return render_to_response("usercenter/checkout.html", {'content': strHtml})
Exemple #51
0
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
Exemple #52
0
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 testPlusMinusButtons(self):
     #Adds an item to target.com's shopping cart. Calls the Cart class increment function to add one additional quanity of that item to shopping cart.
     #Test the change in target.com's shopping cart item# value for correctness--expects 2. Calls the Cart class decrement function to subtract one
     #  additional quanity of that item same item from shopping cart. Again, test target.com's shopping cart item# value for correctness--expects 1
     #Added sleep statments before each count_item() and assert call to keep the tests consistent with Target's bad load times
     self.setUp()
     driver.get("http://www.target.com/p/gopro-hero-chdha-301/-/A-16399081")
     WebDriverWait(
         driver, 15
     ).until(lambda driver: driver.find_element_by_xpath(
         "/html/body/div[2]/div[4]/div/aside/div[2]/div[4]/div[3]/div/div/div[1]/div/button"
     )).click()
     WebDriverWait(
         driver, 15
     ).until(lambda driver: driver.find_element_by_xpath(
         "/html/body/div[2]/div[4]/div/div[5]/div[2]/div[2]/div/div[2]/div/div[1]/div[4]/button"
     )).click()
     cart = Cart(driver)
     cart.increment_item(1, 2)
     time.sleep(5)
     countTest = cart.count_items()
     self.assertEqual(2, countTest)
     cart.decrement_item(1, 2)
     time.sleep(5)
     countTest = cart.count_items()
     self.assertEqual(1, countTest)
Exemple #54
0
    def setUp(self):
        self.order = Order()
        self.menu1 = Menu('pokeS', 'Available', 12.06, 1,
                          'Contains Raw fishes')
        self.menu2 = Menu('pokeM', 'Available', 14.26, 1,
                          'Contains Raw fishes')
        self.menu3 = Menu('pokeL', 'Available', 16.46, 1,
                          'Contains Raw fishes')

        self.cart1 = Cart(self.menu1, 1)
        self.cart2 = Cart(self.menu2, 3)
        self.cart3 = Cart(self.menu3, 2)

        self.order.addMenu(self.cart1)
        self.order.addMenu(self.cart2)
        self.order.addMenu(self.cart3)
Exemple #55
0
 def world(self, n, m):
     # mounting pts:   x  y  z  θ
     w = World(*[(0, i * self.dy, 0, 0) for i in range(0, n)])
     # cmpts:
     for i in range(0, n):
         Cart("Cart" + str(i), w, i)
     return w
Exemple #56
0
class ReplaceCartLineFormTest(TestCase):
    def setUp(self):
        self.cart = Cart()

    def test_quantity(self):
        'Is ReplaceCartLineForm works with correct quantity value'
        form = ReplaceCartLineForm({'quantity': 5},
                                   cart=self.cart,
                                   product=stock_product)
        self.assertTrue(form.is_valid())
        form.save()
        form = ReplaceCartLineForm({'quantity': 5},
                                   cart=self.cart,
                                   product=stock_product)
        self.assertTrue(form.is_valid())
        form.save()
        product_quantity = self.cart.get_line(stock_product).quantity
        self.assertEqual(product_quantity, 5,
                         '%s is the bad quantity value' % (product_quantity, ))

    def test_too_big_quantity(self):
        'Is ReplaceCartLineForm works with to big quantity value'
        form = ReplaceCartLineForm({'quantity': 15},
                                   cart=self.cart,
                                   product=stock_product)
        self.assertFalse(form.is_valid())
Exemple #57
0
 def test_raise_error(self): #test to verify if the error is risen if the page wasn't right
   
   with self.assertRaises(ValueError):
     driver.get("http://facebook.com") #wrong page
     Cart(driver)
     driver.get("https://www-secure.target.com/co-cart") #goes back to cart in case this is not the last test executed
     time.sleep(3)
Exemple #58
0
def check_out(request, menu_name, table_name):
    """
    Second checkout setup for selecting sides and configurations
    :param request:
    :return:
    """
    #
    # do lookups to marry configurations and sides
    #  into order_items
    #
    # order_items to be rendered into form in template
    order_items = []
    cart = Cart(request)
    j = 0
    for i in cart:
        e = Entree.objects.get(name=i.product.name)
        sides = e.sides.split()
        configs = e.configurations.split()
        io = {
            'index': j,
            'name': e.name,
            'quantity': i.quantity,
            'price': e.price,
            'sides': sides,
            'configs': configs
        }
        order_items.append(io)
        j += 1
    return render(request,
                  'orders/check_out.html', {
                      'menu_name': menu_name,
                      'table_name': table_name,
                      'order_items': order_items,
                  },
                  context_instance=RequestContext(request))
Exemple #59
0
def on_FileReader_load(e):
    arrayBuffer = e.target.result
    file = e.target.file['name']
    rom = __new__(Uint8Array(arrayBuffer, 0, arrayBuffer.length))
    c = Cart(file, rom)
    document.getElementById('cartName').innerText = file
    s = System(c)
Exemple #60
0
def clear_cart(request, menu_name, table_name):

    cart = Cart(request)
    # cart.clear() does not work

    for i in cart:
        entree = Entree.objects.get(name=i.product.name)

        cart.remove(entree)

    return HttpResponseRedirect(
        reverse('select_table',
                kwargs={
                    'menu_name': menu_name,
                    'table_name': table_name
                }))