Exemplo n.º 1
0
    def test_valid_shipping_methods_1(self):
        """Tests valid shipping methods.
        """        
        # Add the a user criterion with the current user to the shipping method. 
        c = UserCriterion.objects.create()
        c.users = (self.user, )
        c.save()
        
        co = CriteriaObjects.objects.create(criterion=c, content=self.sm1)
        
        # And its still valid. 
        sms = utils.get_valid_shipping_methods(self.request)
        self.assertEqual(len(sms), 2)
        
        # Tests that the correct shipping methods are returned
        sm_names = [sm.name for sm in sms]
        self.failUnless("Standard" in sm_names)
        self.failUnless("Express" in sm_names)
        
        # We now ``logout``
        self.request.user = None
        
        # And the shipping method is not valid any more.
        sms = utils.get_valid_shipping_methods(self.request)        
        self.assertEqual(len(sms), 1)

        # Tests that the correct shipping methods are returned        
        sm_names = [sm.name for sm in sms]                        
        self.failUnless("Express" in sm_names)
Exemplo n.º 2
0
    def test_valid_shipping_methods_1(self):
        """Tests valid shipping methods.
        """
        # Add the a user criterion with the current user to the shipping method.
        c = UserCriterion.objects.create()
        c.users = (self.user, )
        c.save()

        co = CriteriaObjects.objects.create(criterion=c, content=self.sm1)

        # And its still valid.
        sms = utils.get_valid_shipping_methods(self.request)
        self.assertEqual(len(sms), 2)

        # Tests that the correct shipping methods are returned
        sm_names = [sm.name for sm in sms]
        self.failUnless("Standard" in sm_names)
        self.failUnless("Express" in sm_names)

        # We now ``logout``
        self.request.user = None

        # And the shipping method is not valid any more.
        sms = utils.get_valid_shipping_methods(self.request)
        self.assertEqual(len(sms), 1)

        # Tests that the correct shipping methods are returned
        sm_names = [sm.name for sm in sms]
        self.failUnless("Express" in sm_names)
Exemplo n.º 3
0
    def test_valid_shipping_methods_2(self):
        """Tests valid shipping methods. Test with a cart price criterion.
        """
        user = User.objects.get(username="******")
        request = DummyRequest(user=user)

        # Create a cart price criterion and add it to the shipping method 1
        c = CartPriceCriterion.objects.create(price=10.0, operator=GREATER_THAN)
        co = CriteriaObjects(criterion=c, content=self.sm1)
        co.save()

        # Cart price is 0.0 sms1 is not valid
        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 1)

        # Add some products to the cart
        cart = cart_utils.create_cart(request)

        # Cart price is still under 10 - sms1 is not valid
        CartItem.objects.create(cart=cart, product=self.p1, amount=1)
        update_cart_cache(cart)

        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 1)

        # Cart price is greater than 10.0 now - sms1 is valid
        CartItem.objects.create(cart=cart, product=self.p2, amount=1)
        update_cart_cache(cart)

        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 2)
Exemplo n.º 4
0
    def test_valid_shipping_methods_2(self):
        """Tests valid shipping methods. Test with a cart price criterion.
        """
        user = User.objects.get(username="******")
        request = DummyRequest(user=user)

        # Create a cart price criterion and add it to the shipping method 1
        CartPriceCriterion.objects.create(content=self.sm1,
                                          value=10.0,
                                          operator=GREATER_THAN)

        # Cart price is 0.0 sms1 is not valid
        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 1)

        # Add some products to the cart
        cart = cart_utils.create_cart(request)

        # Cart price is still under 10 - sms1 is not valid
        CartItem.objects.create(cart=cart, product=self.p1, amount=1)
        update_cart_cache(cart)

        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 1)

        # Cart price is greater than 10.0 now - sms1 is valid
        CartItem.objects.create(cart=cart, product=self.p2, amount=1)
        update_cart_cache(cart)

        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 2)
Exemplo n.º 5
0
    def test_valid_shipping_methods_2(self):
        """Tests valid shipping methods. Test with a cart price criterion.
        """
        self.client.post(
            reverse('lfs_login'),
            dict(
                username='******',
                password='******',
                action='login'
            ),
            follow=True
        )

        response = self.client.get(
            reverse('lfs_cart')
        )
        request = response.context['request']

        # Create a cart price criterion and add it to the shipping method 1
        CartPriceCriterion.objects.create(content=self.sm1, value=10.0, operator=GREATER_THAN)

        # Cart price is 0.0 sms1 is not valid
        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 1)

        # Add some products to the cart
        cart = cart_utils.create_cart(request)

        # Cart price is still under 10 - sms1 is not valid
        CartItem.objects.create(cart=cart, product=self.p1, amount=1)
        update_cart_cache(cart)

        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 1)

        # Cart price is greater than 10.0 now - sms1 is valid
        CartItem.objects.create(cart=cart, product=self.p2, amount=1)
        update_cart_cache(cart)

        sms = utils.get_valid_shipping_methods(request)
        self.assertEqual(len(sms), 2)
Exemplo n.º 6
0
def cart_inline(request, template_name="lfs/cart/cart_inline.html"):
    """The actual content of the cart. This is factored out to be reused within
    'normal' and ajax requests.
    """
    cart = cart_utils.get_cart(request)
    shopping_url = lfs.cart.utils.get_go_on_shopping_url(request)
    if cart is None:
        return render_to_string(template_name, RequestContext(request, {"shopping_url": shopping_url}))

    shop = core_utils.get_default_shop()
    countries = shop.countries.all()
    selected_country = shipping_utils.get_selected_shipping_country(request)

    # Get default shipping method, so that we have a one in any case.
    selected_shipping_method = shipping_utils.get_selected_shipping_method(request)
    selected_payment_method = payment_utils.get_selected_payment_method(request)

    shipping_costs = shipping_utils.get_shipping_costs(request, selected_shipping_method)

    payment_costs = payment_utils.get_payment_costs(request, selected_payment_method)

    cart_costs = cart_utils.get_cart_costs(request, cart)
    cart_price = cart_costs["price"] + shipping_costs["price"] + payment_costs["price"]

    cart_tax = cart_costs["tax"] + shipping_costs["tax"] + payment_costs["tax"]

    max_delivery_time = cart_utils.get_cart_max_delivery_time(request, cart)

    # Calc delivery date for cart (which is the maximum of all cart items)
    max_delivery_date = cart_utils.get_cart_max_delivery_time(request, cart)

    return render_to_string(
        template_name,
        RequestContext(
            request,
            {
                "cart": cart,
                "max_delivery_date": max_delivery_date,
                "cart_price": cart_price,
                "cart_tax": cart_tax,
                "shipping_methods": shipping_utils.get_valid_shipping_methods(request),
                "selected_shipping_method": selected_shipping_method,
                "shipping_price": shipping_costs["price"],
                "payment_methods": payment_utils.get_valid_payment_methods(request),
                "selected_payment_method": selected_payment_method,
                "payment_price": payment_costs["price"],
                "countries": countries,
                "selected_country": selected_country,
                "max_delivery_time": max_delivery_time,
                "shopping_url": shopping_url,
            },
        ),
    )
Exemplo n.º 7
0
Arquivo: views.py Projeto: potar/lfs
def cart_inline(request, template_name="lfs/cart/cart_inline.html"):
    """The actual content of the cart. This is factored out to be reused within
    'normal' and ajax requests.
    """
    cart = cart_utils.get_cart(request)
    shopping_url = lfs.cart.utils.get_go_on_shopping_url(request)
    if cart is None:
        return render_to_string(template_name, RequestContext(request, {
            "shopping_url" : shopping_url,
        }))

    shop = core_utils.get_default_shop()
    countries = shop.countries.all()
    selected_country = shipping_utils.get_selected_shipping_country(request)

    # Get default shipping method, so that we have a one in any case.
    selected_shipping_method = shipping_utils.get_selected_shipping_method(request)
    selected_payment_method = payment_utils.get_selected_payment_method(request)

    shipping_costs = shipping_utils.get_shipping_costs(request,
        selected_shipping_method)

    payment_costs = payment_utils.get_payment_costs(request,
        selected_payment_method)

    cart_costs = cart_utils.get_cart_costs(request, cart)
    cart_price = \
        cart_costs["price"] + shipping_costs["price"] + payment_costs["price"]

    cart_tax = \
        cart_costs["tax"] + shipping_costs["tax"] + payment_costs["tax"]

    max_delivery_time = cart_utils.get_cart_max_delivery_time(request, cart)

    # Calc delivery date for cart (which is the maximum of all cart items)
    max_delivery_date = cart_utils.get_cart_max_delivery_time(request, cart)

    return render_to_string(template_name, RequestContext(request, {
        "cart" : cart,
        "max_delivery_date" : max_delivery_date,
        "cart_price" : cart_price,
        "cart_tax" : cart_tax,
        "shipping_methods" : shipping_utils.get_valid_shipping_methods(request),
        "selected_shipping_method" : selected_shipping_method,
        "shipping_price" : shipping_costs["price"],
        "payment_methods" : payment_utils.get_valid_payment_methods(request),
        "selected_payment_method" : selected_payment_method,
        "payment_price" : payment_costs["price"],
        "countries" : countries,
        "selected_country" : selected_country,
        "max_delivery_time" : max_delivery_time,
        "shopping_url" : shopping_url,
    }))
Exemplo n.º 8
0
    def test_valid_shipping_methods_1(self):
        """Tests valid shipping methods.
        """
        # And its still valid.
        sms = utils.get_valid_shipping_methods(self.request)
        self.assertEqual(len(sms), 2)

        # Tests that the correct shipping methods are returned
        sm_names = [sm.name for sm in sms]
        self.failUnless("Standard" in sm_names)
        self.failUnless("Express" in sm_names)

        # We now ``logout``
        self.request.user = None

        # And the shipping method is not valid any more.
        sms = utils.get_valid_shipping_methods(self.request)
        self.assertEqual(len(sms), 2)

        # Tests that the correct shipping methods are returned
        sm_names = [sm.name for sm in sms]
        self.failUnless("Express" in sm_names)
Exemplo n.º 9
0
    def test_valid_shipping_methods_1(self):
        """Tests valid shipping methods.
        """
        # And its still valid.
        sms = utils.get_valid_shipping_methods(self.request)
        self.assertEqual(len(sms), 2)

        # Tests that the correct shipping methods are returned
        sm_names = [sm.name for sm in sms]
        self.failUnless("Standard" in sm_names)
        self.failUnless("Express" in sm_names)

        # We now ``logout``
        self.request.user = None

        # And the shipping method is not valid any more.
        sms = utils.get_valid_shipping_methods(self.request)
        self.assertEqual(len(sms), 2)

        # Tests that the correct shipping methods are returned
        sm_names = [sm.name for sm in sms]
        self.failUnless("Express" in sm_names)
Exemplo n.º 10
0
def refresh_cart(request):
    """Refreshes the cart after some changes has been taken place: the amount
    of a product or shipping/payment method.
    """
    cart = cart_utils.get_cart(request)
    customer = customer_utils.get_or_create_customer(request)

    # Update country
    country = request.POST.get("country")
    if customer.selected_shipping_address:
        customer.selected_shipping_address.country_id = country
        customer.selected_shipping_address.save()
    if customer.selected_invoice_address:
        customer.selected_invoice_address.country_id = country
        customer.selected_invoice_address.save()
    customer.selected_country_id = country

    # NOTE: The customer has to be saved already here in order to calculate
    # a possible new valid shippig method below, which coulb be triggered by
    # the changing of the shipping country.
    customer.save()

    # Update Amounts
    for item in cart.items():
        amount = request.POST.get("amount-cart-item_%s" % item.id, 0)
        try:
            item.amount = int(amount)
        except ValueError:
            item.amount = 1
        item.save()

    # IMPORTANT: We have to send the signal already here, because the valid
    # shipping methods might be dependent on the price.
    cart_changed.send(cart, request=request)

    # Update shipping method
    customer.selected_shipping_method_id = request.POST.get("shipping_method")

    valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request)
    if customer.selected_shipping_method not in valid_shipping_methods:
        customer.selected_shipping_method = shipping_utils.get_default_shipping_method(request)

    # Update payment method
    customer.selected_payment_method_id = request.POST.get("payment_method")

    # Last but not least we save the customer ...
    customer.save()

    return HttpResponse(cart_inline(request))
Exemplo n.º 11
0
Arquivo: views.py Projeto: potar/lfs
def refresh_cart(request):
    """Refreshes the cart after some changes has been taken place: the amount
    of a product or shipping/payment method.
    """
    cart = cart_utils.get_cart(request)
    customer = customer_utils.get_or_create_customer(request)

    # Update country
    country = request.POST.get("country")
    if customer.selected_shipping_address:
        customer.selected_shipping_address.country_id = country
        customer.selected_shipping_address.save()
    if customer.selected_invoice_address:
        customer.selected_invoice_address.country_id = country
        customer.selected_invoice_address.save()
    customer.selected_country_id = country

    # NOTE: The customer has to be saved already here in order to calculate
    # a possible new valid shippig method below, which coulb be triggered by
    # the changing of the shipping country.
    customer.save()

    # Update Amounts
    for item in cart.items():
        amount = request.POST.get("amount-cart-item_%s" % item.id, 0)
        try:
            item.amount = int(amount)
        except ValueError:
            item.amount = 1
        item.save()

    # IMPORTANT: We have to send the signal already here, because the valid
    # shipping methods might be dependent on the price.
    cart_changed.send(cart, request=request)

    # Update shipping method
    customer.selected_shipping_method_id = request.POST.get("shipping_method")

    valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request)
    if customer.selected_shipping_method not in valid_shipping_methods:
        customer.selected_shipping_method = shipping_utils.get_default_shipping_method(request)

    # Update payment method
    customer.selected_payment_method_id = request.POST.get("payment_method")

    # Last but not least we save the customer ...
    customer.save()

    return HttpResponse(cart_inline(request))
Exemplo n.º 12
0
def cart_inline(request, template_name="lfs/cart/cart_inline.html"):
    """
    The actual content of the cart.

    This is factored out to be reused within 'normal' and ajax requests.
    """
    cart = cart_utils.get_cart(request)
    shopping_url = lfs.cart.utils.get_go_on_shopping_url(request)
    if cart is None:
        return render_to_string(
            template_name,
            RequestContext(request, {
                "shopping_url": shopping_url,
            }))

    shop = core_utils.get_default_shop(request)
    countries = shop.shipping_countries.all()
    selected_country = shipping_utils.get_selected_shipping_country(request)

    # Get default shipping method, so that we have a one in any case.
    selected_shipping_method = shipping_utils.get_selected_shipping_method(
        request)
    selected_payment_method = payment_utils.get_selected_payment_method(
        request)

    shipping_costs = shipping_utils.get_shipping_costs(
        request, selected_shipping_method)

    # Payment
    payment_costs = payment_utils.get_payment_costs(request,
                                                    selected_payment_method)

    # Cart costs
    cart_price = cart.get_price_gross(
        request) + shipping_costs["price_gross"] + payment_costs["price"]
    cart_tax = cart.get_tax(
        request) + shipping_costs["tax"] + payment_costs["tax"]

    # Discounts
    discounts = lfs.discounts.utils.get_valid_discounts(request)
    for discount in discounts:
        cart_price = cart_price - discount["price_gross"]
        cart_tax = cart_tax - discount["tax"]

    # Voucher
    voucher_number = lfs.voucher.utils.get_current_voucher_number(request)
    try:
        voucher = Voucher.objects.get(number=voucher_number)
    except Voucher.DoesNotExist:
        display_voucher = False
        voucher_value = 0
        voucher_tax = 0
        voucher_message = MESSAGES[6]
    else:
        lfs.voucher.utils.set_current_voucher_number(request, voucher_number)
        is_voucher_effective, voucher_message = voucher.is_effective(
            request, cart)
        if is_voucher_effective:
            display_voucher = True
            voucher_value = voucher.get_price_gross(request, cart)
            cart_price = cart_price - voucher_value
            voucher_tax = voucher.get_tax(request, cart)
            cart_tax = cart_tax - voucher_tax
        else:
            display_voucher = False
            voucher_value = 0
            voucher_tax = 0

    # Calc delivery time for cart (which is the maximum of all cart items)
    max_delivery_time = cart.get_delivery_time(request)

    cart_items = []
    for cart_item in cart.get_items():
        product = cart_item.product
        quantity = product.get_clean_quantity(cart_item.amount)
        cart_items.append({
            "obj":
            cart_item,
            "quantity":
            quantity,
            "product":
            product,
            "product_price_net":
            cart_item.get_price_net(request),
            "product_price_gross":
            cart_item.get_price_gross(request),
            "product_tax":
            cart_item.get_tax(request),
        })

    return render_to_string(
        template_name,
        RequestContext(
            request, {
                "cart":
                cart,
                "cart_items":
                cart_items,
                "cart_price":
                cart_price,
                "cart_tax":
                cart_tax,
                "shipping_methods":
                shipping_utils.get_valid_shipping_methods(request),
                "selected_shipping_method":
                selected_shipping_method,
                "shipping_costs":
                shipping_costs,
                "payment_methods":
                payment_utils.get_valid_payment_methods(request),
                "selected_payment_method":
                selected_payment_method,
                "payment_price":
                payment_costs["price"],
                "countries":
                countries,
                "selected_country":
                selected_country,
                "max_delivery_time":
                max_delivery_time,
                "shopping_url":
                shopping_url,
                "discounts":
                discounts,
                "display_voucher":
                display_voucher,
                "voucher_number":
                voucher_number,
                "voucher_value":
                voucher_value,
                "voucher_tax":
                voucher_tax,
                "voucher_message":
                voucher_message,
            }))
Exemplo n.º 13
0
def refresh_cart(request):
    """
    Refreshes the cart after some changes has been taken place, e.g.: the
    amount of a product or shipping/payment method.
    """
    cart = cart_utils.get_cart(request)
    if not cart:
        raise Http404
    customer = customer_utils.get_or_create_customer(request)

    # Update country
    country_iso = request.POST.get("country")
    if country_iso:
        selected_country = Country.objects.get(code=country_iso.lower())
        customer.selected_country_id = selected_country.id
        if customer.selected_shipping_address:
            customer.selected_shipping_address.country = selected_country
            customer.selected_shipping_address.save()
            customer.selected_shipping_address.save()
        if customer.selected_invoice_address:
            customer.selected_invoice_address.country = selected_country
            customer.selected_invoice_address.save()
            customer.selected_invoice_address.save()
        # NOTE: The customer has to be saved already here in order to calculate
        # a possible new valid shippig method below, which coulb be triggered by
        # the changing of the shipping country.
        customer.save()

    # Update Amounts
    message = ""
    for item in cart.get_items():
        amount = request.POST.get("amount-cart-item_%s" % item.id, "0.0")
        amount = item.product.get_clean_quantity_value(amount, allow_zero=True)

        if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time:
            amount = item.product.stock_amount
            if amount < 0:
                amount = 0

            if amount == 0:
                message = _(
                    u"Sorry, but '%(product)s' is not available anymore." %
                    {"product": item.product.name})
            elif amount == 1:
                message = _(
                    u"Sorry, but '%(product)s' is only one time available." %
                    {"product": item.product.name})
            else:
                message = _(
                    u"Sorry, but '%(product)s' is only %(amount)s times available."
                ) % {
                    "product": item.product.name,
                    "amount": amount
                }

        if item.product.get_active_packing_unit():
            item.amount = item.product.get_amount_by_packages(float(amount))
        else:
            item.amount = amount

        if amount == 0:
            item.delete()
        else:
            item.save()

    # IMPORTANT: We have to send the signal already here, because the valid
    # shipping methods might be dependent on the price.
    cart_changed.send(cart, request=request)

    # Update shipping method
    shipping_method = get_object_or_404(ShippingMethod,
                                        pk=request.POST.get("shipping_method"))
    customer.selected_shipping_method = shipping_method

    valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request)
    if customer.selected_shipping_method not in valid_shipping_methods:
        customer.selected_shipping_method = shipping_utils.get_default_shipping_method(
            request)

    # Update payment method
    payment_method = get_object_or_404(PaymentMethod,
                                       pk=request.POST.get("payment_method"))
    customer.selected_payment_method = payment_method

    # Last but not least we save the customer ...
    customer.save()

    result = json.dumps({
        "html": cart_inline(request),
        "message": message,
    },
                        cls=LazyEncoder)

    return HttpResponse(result, content_type='application/json')
Exemplo n.º 14
0
def cart_inline(request, template_name="lfs/cart/cart_inline.html"):
    """
    The actual content of the cart.

    This is factored out to be reused within 'normal' and ajax requests.
    """
    cart = cart_utils.get_cart(request)
    shopping_url = lfs.cart.utils.get_go_on_shopping_url(request)
    if cart is None:
        return render_to_string(template_name, RequestContext(request, {"shopping_url": shopping_url}))

    shop = core_utils.get_default_shop(request)
    countries = shop.shipping_countries.all()
    selected_country = shipping_utils.get_selected_shipping_country(request)

    # Get default shipping method, so that we have a one in any case.
    selected_shipping_method = shipping_utils.get_selected_shipping_method(request)
    selected_payment_method = payment_utils.get_selected_payment_method(request)

    shipping_costs = shipping_utils.get_shipping_costs(request, selected_shipping_method)

    # Payment
    payment_costs = payment_utils.get_payment_costs(request, selected_payment_method)

    # Cart costs
    cart_price = cart.get_price_gross(request) + shipping_costs["price_gross"] + payment_costs["price"]
    cart_tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"]

    # Discounts
    discounts = lfs.discounts.utils.get_valid_discounts(request)
    for discount in discounts:
        cart_price = cart_price - discount["price_gross"]
        cart_tax = cart_tax - discount["tax"]

    # Voucher
    voucher_number = lfs.voucher.utils.get_current_voucher_number(request)
    try:
        voucher = Voucher.objects.get(number=voucher_number)
    except Voucher.DoesNotExist:
        display_voucher = False
        voucher_value = 0
        voucher_tax = 0
        voucher_message = MESSAGES[6]
    else:
        lfs.voucher.utils.set_current_voucher_number(request, voucher_number)
        is_voucher_effective, voucher_message = voucher.is_effective(request, cart)
        if is_voucher_effective:
            display_voucher = True
            voucher_value = voucher.get_price_gross(request, cart)
            cart_price = cart_price - voucher_value
            voucher_tax = voucher.get_tax(request, cart)
            cart_tax = cart_tax - voucher_tax
        else:
            display_voucher = False
            voucher_value = 0
            voucher_tax = 0

    # Calc delivery time for cart (which is the maximum of all cart items)
    max_delivery_time = cart.get_delivery_time(request)

    cart_items = []
    for cart_item in cart.get_items():
        product = cart_item.product
        quantity = product.get_clean_quantity(cart_item.amount)
        cart_items.append(
            {
                "obj": cart_item,
                "quantity": quantity,
                "product": product,
                "product_price_net": cart_item.get_price_net(request),
                "product_price_gross": cart_item.get_price_gross(request),
                "product_tax": cart_item.get_tax(request),
            }
        )

    return render_to_string(
        template_name,
        RequestContext(
            request,
            {
                "cart": cart,
                "cart_items": cart_items,
                "cart_price": cart_price,
                "cart_tax": cart_tax,
                "shipping_methods": shipping_utils.get_valid_shipping_methods(request),
                "selected_shipping_method": selected_shipping_method,
                "shipping_costs": shipping_costs,
                "payment_methods": payment_utils.get_valid_payment_methods(request),
                "selected_payment_method": selected_payment_method,
                "payment_price": payment_costs["price"],
                "countries": countries,
                "selected_country": selected_country,
                "max_delivery_time": max_delivery_time,
                "shopping_url": shopping_url,
                "discounts": discounts,
                "display_voucher": display_voucher,
                "voucher_number": voucher_number,
                "voucher_value": voucher_value,
                "voucher_tax": voucher_tax,
                "voucher_message": voucher_message,
            },
        ),
    )
Exemplo n.º 15
0
def refresh_cart(request):
    """
    Refreshes the cart after some changes has been taken place, e.g.: the
    amount of a product or shipping/payment method.
    """
    cart = cart_utils.get_cart(request)
    if not cart:
        raise Http404
    customer = customer_utils.get_or_create_customer(request)

    # Update country
    country_iso = request.POST.get("country")
    if country_iso:
        selected_country = Country.objects.get(code=country_iso.lower())
        customer.selected_country_id = selected_country.id
        if customer.selected_shipping_address:
            customer.selected_shipping_address.country = selected_country
            customer.selected_shipping_address.save()
            customer.selected_shipping_address.save()
        if customer.selected_invoice_address:
            customer.selected_invoice_address.country = selected_country
            customer.selected_invoice_address.save()
            customer.selected_invoice_address.save()
        # NOTE: The customer has to be saved already here in order to calculate
        # a possible new valid shippig method below, which coulb be triggered by
        # the changing of the shipping country.
        customer.save()

    # Update Amounts
    message = ""
    for item in cart.get_items():
        amount = request.POST.get("amount-cart-item_%s" % item.id, "0.0")
        amount = item.product.get_clean_quantity_value(amount, allow_zero=True)

        if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time:
            amount = item.product.stock_amount
            if amount < 0:
                amount = 0

            if amount == 0:
                message = _(u"Sorry, but '%(product)s' is not available anymore." % {"product": item.product.name})
            elif amount == 1:
                message = _(u"Sorry, but '%(product)s' is only one time available." % {"product": item.product.name})
            else:
                message = _(u"Sorry, but '%(product)s' is only %(amount)s times available.") % {
                    "product": item.product.name,
                    "amount": amount,
                }

        if item.product.get_active_packing_unit():
            item.amount = item.product.get_amount_by_packages(float(amount))
        else:
            item.amount = amount

        if amount == 0:
            item.delete()
        else:
            item.save()

    # IMPORTANT: We have to send the signal already here, because the valid
    # shipping methods might be dependent on the price.
    cart_changed.send(cart, request=request)

    # Update shipping method
    shipping_method = get_object_or_404(ShippingMethod, pk=request.POST.get("shipping_method"))
    customer.selected_shipping_method = shipping_method

    valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request)
    if customer.selected_shipping_method not in valid_shipping_methods:
        customer.selected_shipping_method = shipping_utils.get_default_shipping_method(request)

    # Update payment method
    payment_method = get_object_or_404(PaymentMethod, pk=request.POST.get("payment_method"))
    customer.selected_payment_method = payment_method

    # Last but not least we save the customer ...
    customer.save()

    result = json.dumps({"html": cart_inline(request), "message": message}, cls=LazyEncoder)

    return HttpResponse(result, content_type="application/json")
Exemplo n.º 16
0
def refresh_cart(request):
    """
    Refreshes the cart after some changes has been taken place, e.g.: the
    amount of a product or shipping/payment method.
    """
    cart = cart_utils.get_cart(request)
    customer = customer_utils.get_or_create_customer(request)

    # Update country
    country_iso = request.POST.get("country")
    if country_iso:
        selected_country = Country.objects.get(code=country_iso.lower())
        customer.selected_country_id = selected_country.id
        if customer.selected_shipping_address:
            customer.selected_shipping_address.country = selected_country
            customer.selected_shipping_address.save()
            customer.selected_shipping_address.save()
        if customer.selected_invoice_address:
            customer.selected_invoice_address.country = selected_country
            customer.selected_invoice_address.save()
            customer.selected_invoice_address.save()
        # NOTE: The customer has to be saved already here in order to calculate
        # a possible new valid shippig method below, which coulb be triggered by
        # the changing of the shipping country.
        customer.save()

    # Update Amounts
    message = ""
    for item in cart.get_items():
        try:
            value = request.POST.get("amount-cart-item_%s" % item.id, "0.0")
            if isinstance(value, unicode):
                # atof() on unicode string fails in some environments, like Czech
                value = value.encode("utf-8")
            amount = locale.atof(value)
        except (TypeError, ValueError):
            amount = 1.0

        if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time:
            amount = item.product.stock_amount
            if amount < 0:
                amount = 0

            if amount == 0:
                message = _(u"Sorry, but '%(product)s' is not available anymore." % {"product": item.product.name})
            elif amount == 1:
                message = _(u"Sorry, but '%(product)s' is only one time available." % {"product": item.product.name})
            else:
                message = _(u"Sorry, but '%(product)s' is only %(amount)s times available.") % {"product": item.product.name, "amount": amount}


        if item.product.active_packing_unit:
            item.amount = item.product.get_amount_by_packages(float(amount))
        else:
            item.amount = amount

        if amount == 0:
            item.delete()
        else:
            item.save()

    # IMPORTANT: We have to send the signal already here, because the valid
    # shipping methods might be dependent on the price.
    cart_changed.send(cart, request=request)

    # Update shipping method
    customer.selected_shipping_method_id = request.POST.get("shipping_method")

    valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request)
    if customer.selected_shipping_method not in valid_shipping_methods:
        customer.selected_shipping_method = shipping_utils.get_default_shipping_method(request)

    # Update payment method
    customer.selected_payment_method_id = request.POST.get("payment_method")

    # Last but not least we save the customer ...
    customer.save()

    result = simplejson.dumps({
        "html": cart_inline(request),
        "message": message,
    }, cls=LazyEncoder)

    return HttpResponse(result)
Exemplo n.º 17
0
def cart_inline(request, template_name="lfs/cart/cart_inline.html"):
    """
    The actual content of the cart.

    This is factored out to be reused within 'normal' and ajax requests.
    """
    cart = cart_utils.get_cart(request)
    shopping_url = lfs.cart.utils.get_go_on_shopping_url(request)
    if cart is None:
        return render_to_string(template_name, request=request, context={
            "shopping_url": shopping_url,
        })

    shop = core_utils.get_default_shop(request)
    countries = shop.shipping_countries.all()
    selected_country = shipping_utils.get_selected_shipping_country(request)

    # Get default shipping method, so that we have a one in any case.
    selected_shipping_method = shipping_utils.get_selected_shipping_method(request)
    selected_payment_method = payment_utils.get_selected_payment_method(request)

    shipping_costs = shipping_utils.get_shipping_costs(request, selected_shipping_method)

    # Payment
    payment_costs = payment_utils.get_payment_costs(request, selected_payment_method)

    # Cart costs
    cart_price = cart.get_price_gross(request) + shipping_costs["price_gross"] + payment_costs["price"]
    cart_tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"]

    # get voucher data (if voucher exists)
    voucher_data = lfs.voucher.utils.get_voucher_data(request, cart)

    # get discounts data
    discounts_data = lfs.discounts.utils.get_discounts_data(request)

    # calculate total value of discounts and voucher that sum up
    summed_up_value = discounts_data['summed_up_value']
    if voucher_data['sums_up']:
        summed_up_value += voucher_data['voucher_value']

    # initialize discounts with summed up discounts
    use_voucher = voucher_data['voucher'] is not None
    discounts = discounts_data['summed_up_discounts']
    if voucher_data['voucher_value'] > summed_up_value or discounts_data['max_value'] > summed_up_value:
        # use not summed up value
        if voucher_data['voucher_value'] > discounts_data['max_value']:
            # use voucher only
            discounts = []
        else:
            # use discount only
            discounts = discounts_data['max_discounts']
            use_voucher = False

    for discount in discounts:
        cart_price -= discount["price_gross"]
        cart_tax -= discount["tax"]

    if use_voucher:
        cart_price -= voucher_data['voucher_value']
        cart_tax -= voucher_data['voucher_tax']

    cart_price = max(0, cart_price)
    cart_tax = max(0, cart_tax)

    # Calc delivery time for cart (which is the maximum of all cart items)
    max_delivery_time = cart.get_delivery_time(request)

    cart_items = []
    for cart_item in cart.get_items():
        product = cart_item.product
        quantity = product.get_clean_quantity(cart_item.amount)
        cart_items.append({
            "obj": cart_item,
            "quantity": quantity,
            "product": product,
            "product_price_net": cart_item.get_price_net(request),
            "product_price_gross": cart_item.get_price_gross(request),
            "product_tax": cart_item.get_tax(request),
        })

    return render_to_string(template_name, request=request, context={
        "cart": cart,
        "cart_items": cart_items,
        "cart_price": cart_price,
        "cart_tax": cart_tax,
        "shipping_methods": shipping_utils.get_valid_shipping_methods(request),
        "selected_shipping_method": selected_shipping_method,
        "shipping_costs": shipping_costs,
        "payment_methods": payment_utils.get_valid_payment_methods(request),
        "selected_payment_method": selected_payment_method,
        "payment_price": payment_costs["price"],
        "countries": countries,
        "selected_country": selected_country,
        "max_delivery_time": max_delivery_time,
        "shopping_url": shopping_url,
        "discounts": discounts,
        "display_voucher": use_voucher,
        "voucher_number": voucher_data['voucher_number'],
        "voucher_value": voucher_data['voucher_value'],
        "voucher_tax": voucher_data['voucher_tax'],
        "voucher_message": voucher_data['voucher_message'],
    })
Exemplo n.º 18
0
def refresh_cart(request):
    """
    Refreshes the cart after some changes has been taken place, e.g.: the
    amount of a product or shipping/payment method.
    """
    cart = cart_utils.get_cart(request)
    if not cart:
        raise Http404
    customer = customer_utils.get_or_create_customer(request)

    # Update country
    country_iso = request.POST.get("country")
    if country_iso:
        selected_country = Country.objects.get(code=country_iso.lower())
        customer.selected_country_id = selected_country.id
        if customer.selected_shipping_address:
            customer.selected_shipping_address.country = selected_country
            customer.selected_shipping_address.save()
            customer.selected_shipping_address.save()
        if customer.selected_invoice_address:
            customer.selected_invoice_address.country = selected_country
            customer.selected_invoice_address.save()
            customer.selected_invoice_address.save()
        # NOTE: The customer has to be saved already here in order to calculate
        # a possible new valid shippig method below, which coulb be triggered by
        # the changing of the shipping country.
        customer.save()

    # Update Amounts
    message = ''
    cor = ''
    for item in cart.get_items():
        amount = request.POST.get("amount-cart-item_%s" % item.id, "0.0")
        amount = item.product.get_clean_quantity_value(amount, allow_zero=True)
        if message == '':
            message = _(u"%(product)s ATUALIZADO") % {"product": 'PRODUTO'}
            cor = "verde"
        if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time:
            amount = item.product.stock_amount
            message = _(u"%(product)s ATUALIZADO") % {"product": 'PRODUTO'}
            cor = "verde"
            if amount < 0:
                amount = 0
                message = _(u"%(product)s EXCLUIDO") % {"product": 'PRODUTO'}
                cor = "vermelho"

            if amount == 0:
                message = _(
                    u"Sorry, but '%(product)s' is not available anymore.") % {
                        "product": 'PRODUTO',
                        "amount": amount
                    }
                cor = "vermelho"
            elif amount == 1:
                message = _(
                    u"Sorry, but '%(product)s' is only one time available."
                ) % {
                    "product": 'PRODUTO',
                    "amount": amount
                }
                cor = "amarelo"
            else:
                message = _(
                    u"Sorry, but '%(product)s' is only %(amount)s times available."
                ) % {
                    "product": 'PRODUTO',
                    "amount": amount
                }
                cor = "amarelo"
        if item.product.get_active_packing_unit():
            item.amount = item.product.get_amount_by_packages(float(amount))
        else:
            item.amount = amount

        if amount == 0:
            message = _(u"%(product)s EXCLUIDO") % {"product": 'PRODUTO'}
            cor = "vermelho"
            item.delete()
        else:
            item.save()

    # IMPORTANT: We have to send the signal already here, because the valid
    # shipping methods might be dependent on the price.
    cart_changed.send(cart, request=request)

    # Update shipping method
    shipping_method = get_object_or_404(ShippingMethod,
                                        pk=request.POST.get("shipping_method"))
    customer.selected_shipping_method = shipping_method

    valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request)
    if customer.selected_shipping_method not in valid_shipping_methods:
        customer.selected_shipping_method = shipping_utils.get_default_shipping_method(
            request)

    # Update payment method
    payment_method = get_object_or_404(PaymentMethod,
                                       pk=request.POST.get("payment_method"))
    customer.selected_payment_method = payment_method

    # Last but not least we save the customer ...
    customer.save()

    total_quantidade = 0
    total_valor = 0
    for cart_item in cart.get_items():
        product = cart_item.product
        quantidade = str(product.get_clean_quantity(cart_item.amount))
        quantidade = quantidade.replace(",", ".")
        quantidade = float(quantidade)
        total_quantidade += quantidade
        total_valor += float(cart_item.get_price_net(request))

    price = str(total_valor)

    if price == '0':
        decimal = '0'
        centavos = '00'
    else:
        virgula = price.find('.')
        decimal = price[:virgula]
        centavos = price[virgula:]
        for a in [',', '.']:
            decimal = decimal.replace(a, '')
            centavos = centavos.replace(a, '')

    result = json.dumps(
        {
            "html": cart_inline(request),
            "message": message,
            "cor": cor,
            "quantidade": str(total_quantidade),
            "decimal": decimal,
            "centavos": centavos[:2],
        },
        cls=LazyEncoder)

    return HttpResponse(result, content_type='application/json')