Exemple #1
0
    def test_shipping_price_3(self):
        """Tests an additional shipping method price with a criterion.
        """
        # Add a shipping method price
        smp = ShippingMethodPrice.objects.create(shipping_method=self.sm1, price=5)

        # Add a criterion the to the price
        c = CartPriceCriterion.objects.create(price=10.0, operator=GREATER_THAN)
        co = CriteriaObjects.objects.create(criterion=c, content=smp)

        # The cart price is less than 10, hence the price is not valid and the
        # shipping price is the default price of the shipping method , which is
        # 1, see above.
        costs = utils.get_shipping_costs(self.request, self.sm1)
        self.assertEqual(costs["price"], 1)

        # No we add some items to the cart
        cart = cart_utils.get_or_create_cart(self.request)
        CartItem.objects.create(cart=cart, product=self.p1, amount=2)
        update_cart_cache(cart)

        # The cart price is now greater than 10, hence the price valid and the
        # shipping price is the price of the yet valid additional price.
        costs = utils.get_shipping_costs(self.request, self.sm1)
        self.assertEqual(costs["price"], 5)
Exemple #2
0
def add_to_cart(request, product_id=None):
    """
    Adds the passed product with passed product_id to the cart after
    some validations have been taken place. The amount is taken from the query
    string.
    """
    if product_id is None:
        product_id = request.REQUEST.get("product_id")

    product = muecke_get_object_or_404(Product, pk=product_id)

    # Only active and deliverable products can be added to the cart.
    if (product.is_active() and product.is_deliverable()) == False:
        raise Http404()

    try:
        value = request.POST.get("quantity", "1.0")
        if isinstance(value, unicode):
            # atof() on unicode string fails in some environments, like Czech
            value = value.encode("utf-8")
        quantity = locale.atof(value)
    except (TypeError, ValueError):
        quantity = 1.0

    # Validate properties (They are added below)
    properties_dict = {}
    if product.is_configurable_product():
        for key, value in request.POST.items():
            if key.startswith("property-"):
                try:
                    property_id = key.split("-")[1]
                except IndexError:
                    continue
                try:
                    property = Property.objects.get(pk=property_id)
                except Property.DoesNotExist:
                    continue

                if property.is_number_field:
                    try:
                        value = muecke.core.utils.atof(value)
                    except ValueError:
                        value = locale.atof("0.0")

                properties_dict[property_id] = unicode(value)

                # validate property's value
                if property.is_number_field:

                    if (value < property.unit_min) or (value > property.unit_max):
                        msg = _(u"%(name)s must be between %(min)s and %(max)s %(unit)s.") % {"name": property.title, "min": property.unit_min, "max": property.unit_max, "unit": property.unit}
                        return muecke.core.utils.set_message_cookie(
                            product.get_absolute_url(), msg)

                    # calculate valid steps
                    steps = []
                    x = property.unit_min
                    while x < property.unit_max:
                        steps.append("%.2f" % x)
                        x = x + property.unit_step
                    steps.append("%.2f" % property.unit_max)

                    value = "%.2f" % value
                    if value not in steps:
                        msg = _(u"Your entered value for %(name)s (%(value)s) is not in valid step width, which is %(step)s.") % {"name": property.title, "value": value, "step": property.unit_step}
                        return muecke.core.utils.set_message_cookie(
                            product.get_absolute_url(), msg)

    if product.get_active_packing_unit():
        quantity = muecke.catalog.utils.calculate_real_amount(product, quantity)

    cart = cart_utils.get_or_create_cart(request)

    cart_item = cart.add(product, properties_dict, quantity)
    cart_items = [cart_item]

    # Check stock amount
    message = ""
    if product.manage_stock_amount and cart_item.amount > product.stock_amount and not product.order_time:
        if product.stock_amount == 0:
            message = _(u"Sorry, but '%(product)s' is not available anymore." % {"product": product.name})
        elif product.stock_amount == 1:
            message = _(u"Sorry, but '%(product)s' is only one time available." % {"product": product.name})
        else:
            message = _(u"Sorry, but '%(product)s' is only %(amount)s times available.") % {"product": product.name, "amount": product.stock_amount}
        cart_item.amount = product.stock_amount
        cart_item.save()

    # Add selected accessories to cart
    for key, value in request.POST.items():
        if key.startswith("accessory"):
            accessory_id = key.split("-")[1]
            try:
                accessory = Product.objects.get(pk=accessory_id)
            except ObjectDoesNotExist:
                continue

            # Get quantity
            quantity = request.POST.get("quantity-%s" % accessory_id, 0)
            try:
                quantity = float(quantity)
            except TypeError:
                quantity = 1

            cart_item = cart.add(product=accessory, amount=quantity)
            cart_items.append(cart_item)

    # Store cart items for retrieval within added_to_cart.
    request.session["cart_items"] = cart_items
    cart_changed.send(cart, request=request)

    # Update the customer's shipping method (if appropriate)
    customer = customer_utils.get_or_create_customer(request)
    shipping_utils.update_to_valid_shipping_method(request, customer, save=True)

    # Update the customer's payment method (if appropriate)
    payment_utils.update_to_valid_payment_method(request, customer, save=True)

    # Save the cart to update modification date
    cart.save()

    try:
        url_name = settings.LFS_AFTER_ADD_TO_CART
    except AttributeError:
        url_name = "muecke.cart.views.added_to_cart"

    if message:
        return muecke.core.utils.set_message_cookie(reverse(url_name), message)
    else:
        return HttpResponseRedirect(reverse(url_name))
Exemple #3
0
def add_to_cart(request, product_id=None):
    """
    Adds the passed product with passed product_id to the cart after
    some validations have been taken place. The amount is taken from the query
    string.
    """
    if product_id is None:
        product_id = request.REQUEST.get("product_id")

    product = muecke_get_object_or_404(Product, pk=product_id)

    # Only active and deliverable products can be added to the cart.
    if (product.is_active() and product.is_deliverable()) == False:
        raise Http404()

    try:
        value = request.POST.get("quantity", "1.0")
        if isinstance(value, unicode):
            # atof() on unicode string fails in some environments, like Czech
            value = value.encode("utf-8")
        quantity = locale.atof(value)
    except (TypeError, ValueError):
        quantity = 1.0

    # Validate properties (They are added below)
    properties_dict = {}
    if product.is_configurable_product():
        for key, value in request.POST.items():
            if key.startswith("property-"):
                try:
                    property_id = key.split("-")[1]
                except IndexError:
                    continue
                try:
                    property = Property.objects.get(pk=property_id)
                except Property.DoesNotExist:
                    continue

                if property.is_number_field:
                    try:
                        value = muecke.core.utils.atof(value)
                    except ValueError:
                        value = locale.atof("0.0")

                properties_dict[property_id] = unicode(value)

                # validate property's value
                if property.is_number_field:

                    if (value < property.unit_min) or (value >
                                                       property.unit_max):
                        msg = _(
                            u"%(name)s must be between %(min)s and %(max)s %(unit)s."
                        ) % {
                            "name": property.title,
                            "min": property.unit_min,
                            "max": property.unit_max,
                            "unit": property.unit
                        }
                        return muecke.core.utils.set_message_cookie(
                            product.get_absolute_url(), msg)

                    # calculate valid steps
                    steps = []
                    x = property.unit_min
                    while x < property.unit_max:
                        steps.append("%.2f" % x)
                        x = x + property.unit_step
                    steps.append("%.2f" % property.unit_max)

                    value = "%.2f" % value
                    if value not in steps:
                        msg = _(
                            u"Your entered value for %(name)s (%(value)s) is not in valid step width, which is %(step)s."
                        ) % {
                            "name": property.title,
                            "value": value,
                            "step": property.unit_step
                        }
                        return muecke.core.utils.set_message_cookie(
                            product.get_absolute_url(), msg)

    if product.get_active_packing_unit():
        quantity = muecke.catalog.utils.calculate_real_amount(
            product, quantity)

    cart = cart_utils.get_or_create_cart(request)

    cart_item = cart.add(product, properties_dict, quantity)
    cart_items = [cart_item]

    # Check stock amount
    message = ""
    if product.manage_stock_amount and cart_item.amount > product.stock_amount and not product.order_time:
        if product.stock_amount == 0:
            message = _(u"Sorry, but '%(product)s' is not available anymore." %
                        {"product": product.name})
        elif product.stock_amount == 1:
            message = _(
                u"Sorry, but '%(product)s' is only one time available." %
                {"product": product.name})
        else:
            message = _(
                u"Sorry, but '%(product)s' is only %(amount)s times available."
            ) % {
                "product": product.name,
                "amount": product.stock_amount
            }
        cart_item.amount = product.stock_amount
        cart_item.save()

    # Add selected accessories to cart
    for key, value in request.POST.items():
        if key.startswith("accessory"):
            accessory_id = key.split("-")[1]
            try:
                accessory = Product.objects.get(pk=accessory_id)
            except ObjectDoesNotExist:
                continue

            # Get quantity
            quantity = request.POST.get("quantity-%s" % accessory_id, 0)
            try:
                quantity = float(quantity)
            except TypeError:
                quantity = 1

            cart_item = cart.add(product=accessory, amount=quantity)
            cart_items.append(cart_item)

    # Store cart items for retrieval within added_to_cart.
    request.session["cart_items"] = cart_items
    cart_changed.send(cart, request=request)

    # Update the customer's shipping method (if appropriate)
    customer = customer_utils.get_or_create_customer(request)
    shipping_utils.update_to_valid_shipping_method(request,
                                                   customer,
                                                   save=True)

    # Update the customer's payment method (if appropriate)
    payment_utils.update_to_valid_payment_method(request, customer, save=True)

    # Save the cart to update modification date
    cart.save()

    try:
        url_name = settings.LFS_AFTER_ADD_TO_CART
    except AttributeError:
        url_name = "muecke.cart.views.added_to_cart"

    if message:
        return muecke.core.utils.set_message_cookie(reverse(url_name), message)
    else:
        return HttpResponseRedirect(reverse(url_name))