예제 #1
0
파일: tests.py 프로젝트: abingham/youblob
    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)
예제 #2
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
        CartPriceCriterion.objects.create(content=smp,
                                          value=10.0,
                                          operator=GREATER_THAN)

        # 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_gross"], 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_gross"], 5)
예제 #3
0
파일: views.py 프로젝트: Rishfact/website-1
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 = lfs_get_object_or_404(Product, pk=product_id)

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

    quantity = request.POST.get("quantity", "1.0")
    quantity = product.get_clean_quantity_value(quantity)

    # 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_group_id, property_id = key.split("-")[1:]
                except IndexError:
                    continue

                try:
                    prop = Property.objects.get(pk=property_id)
                except Property.DoesNotExist:
                    continue

                property_group = None
                if property_group_id != '0':
                    try:
                        property_group = PropertyGroup.objects.get(
                            pk=property_group_id)
                    except PropertyGroup.DoesNotExist:
                        continue

                if prop.is_number_field:
                    try:
                        value = lfs.core.utils.atof(value)
                    except ValueError:
                        value = 0.0

                key = '{0}_{1}'.format(property_group_id, property_id)
                properties_dict[key] = {
                    'value': unicode(value),
                    'property_group_id': property_group_id,
                    'property_id': property_id
                }

                # validate property's value
                if prop.is_number_field:

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

                    # calculate valid steps
                    steps = []
                    x = prop.unit_min
                    while x < prop.unit_max:
                        steps.append("%.2f" % x)
                        x += prop.unit_step
                    steps.append("%.2f" % prop.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": prop.title,
                            "value": value,
                            "step": prop.unit_step
                        }
                        return lfs.core.utils.set_message_cookie(
                            product.get_absolute_url(), msg)

    if product.get_active_packing_unit():
        quantity = product.get_amount_by_packages(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

            # for product with variants add default variant
            if accessory.is_product_with_variants():
                accessory_variant = accessory.get_default_variant()
                if accessory_variant:
                    accessory = accessory_variant
                else:
                    continue

            # Get quantity
            quantity = request.POST.get("quantity-%s" % accessory_id, 0)
            quantity = accessory.get_clean_quantity_value(quantity)

            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 = "lfs_added_to_cart"

    if message:
        return lfs.core.utils.set_message_cookie(reverse(url_name), message)
    else:
        return HttpResponseRedirect(reverse(url_name))
예제 #4
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 = lfs_get_object_or_404(Product, pk=product_id)

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

    quantity = request.POST.get("quantity", "1.0")
    quantity = product.get_clean_quantity_value(quantity)

    # 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:
                    prop = Property.objects.get(pk=property_id)
                except Property.DoesNotExist:
                    continue

                if prop.is_number_field:
                    try:
                        value = lfs.core.utils.atof(value)
                    except ValueError:
                        value = 0.0

                properties_dict[property_id] = unicode(value)

                # validate property's value
                if prop.is_number_field:

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

                    # calculate valid steps
                    steps = []
                    x = prop.unit_min
                    while x < prop.unit_max:
                        steps.append("%.2f" % x)
                        x += prop.unit_step
                    steps.append("%.2f" % prop.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": prop.title, "value": value, "step": prop.unit_step}
                        return lfs.core.utils.set_message_cookie(product.get_absolute_url(), msg)

    if product.get_active_packing_unit():
        quantity = product.get_amount_by_packages(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

            # for product with variants add default variant
            if accessory.is_product_with_variants():
                accessory_variant = accessory.get_default_variant()
                if accessory_variant:
                    accessory = accessory_variant
                else:
                    continue

            # Get quantity
            quantity = request.POST.get("quantity-%s" % accessory_id, 0)
            quantity = accessory.get_clean_quantity_value(quantity)

            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 = "lfs_added_to_cart"

    if message:
        return lfs.core.utils.set_message_cookie(reverse(url_name), message)
    else:
        return HttpResponseRedirect(reverse(url_name))
예제 #5
0
파일: views.py 프로젝트: potar/lfs
def add_to_cart(request, product_id=None):
    """Adds the amount of the product with given id to the cart. If the product
    is already within the cart the amount is increased.
    """
    if product_id is None:
        product_id = request.REQUEST.get("product_id")

    product = lfs_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()
    
    if product.sub_type == PRODUCT_WITH_VARIANTS:
        variant_id = request.POST.get("variant_id")
        product = lfs_get_object_or_404(Product, pk=variant_id)

    try:
        quantity = float(request.POST.get("quantity", 1))
    except TypeError:
        quantity = 1

    cart = cart_utils.get_or_create_cart(request)

    try:
        cart_item = CartItem.objects.get(cart = cart, product = product)
    except ObjectDoesNotExist:
        cart_item = CartItem(cart=cart, product=product, amount=quantity)
        cart_item.save()
    else:
        cart_item.amount += quantity
        cart_item.save()

    cart_items = [cart_item]

    # 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

            try:
                cart_item = CartItem.objects.get(cart = cart, product = accessory)
            except ObjectDoesNotExist:
                cart_item = CartItem(cart=cart, product = accessory, amount=quantity)
                cart_item.save()
            else:
                cart_item.amount += quantity
                cart_item.save()

            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 shipping method (if appropriate)
    payment_utils.update_to_valid_payment_method(request, customer, save=True)

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

    url = reverse("lfs.cart.views.added_to_cart")
    return HttpResponseRedirect(url)
예제 #6
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 = lfs_get_object_or_404(Product, pk=product_id)

    # Only active and deliverable products can be added to the cart.
    if not (product.is_active() and product.is_deliverable()):
        cart = cart_utils.get_or_create_cart(request)
        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))

        if total_quantidade < 2:
            total_quantidade = str(total_quantidade) + '0 Item'
        else:
            total_quantidade = str(total_quantidade) + '0 Itens'
        total_valor = "R$ " + str(total_valor)

        total_valor = total_valor.replace(".", ",")
        total_quantidade = total_quantidade.replace(".", ",")

        #######################################
        try:
            url_name = settings.LFS_AFTER_ADD_TO_CART
        except AttributeError:
            url_name = "lfs_added_to_cart"
        result = json.dumps(
            {
                "message": "Desculpa produto sem estoque.",
                "cor": "vermelho",
                "quantidade": str(total_quantidade),
                "total-cart": str(total_valor)
            },
            cls=LazyEncoder)

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

    quantity = request.REQUEST.get("quantity")
    quantity = product.get_clean_quantity_value(quantity)

    # 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_group_id, property_id = key.split("-")[1:]
                except IndexError:
                    continue

                try:
                    prop = Property.objects.get(pk=property_id)
                except Property.DoesNotExist:
                    continue

                property_group = None
                if property_group_id != '0':
                    try:
                        property_group = PropertyGroup.objects.get(
                            pk=property_group_id)
                    except PropertyGroup.DoesNotExist:
                        continue

                if prop.is_number_field:
                    try:
                        value = lfs.core.utils.atof(value)
                    except ValueError:
                        value = 0.0

                key = '{0}_{1}'.format(property_group_id, property_id)
                properties_dict[key] = {
                    'value': unicode(value),
                    'property_group_id': property_group_id,
                    'property_id': property_id
                }

                # validate property's value
                if prop.is_number_field:

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

                    # calculate valid steps
                    steps = []
                    x = prop.unit_min
                    while x < prop.unit_max:
                        steps.append("%.2f" % x)
                        x += prop.unit_step
                    steps.append("%.2f" % prop.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": prop.title,
                            "value": value,
                            "step": prop.unit_step
                        }
                        return lfs.core.utils.set_message_cookie(
                            product.get_absolute_url(), msg)

    if product.get_active_packing_unit():
        quantity = product.get_amount_by_packages(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 = _(u"%(quantidade)s %(product)s ADICIONADO") % {
        "product": product.name,
        "quantidade": quantity
    }
    cor = "verde"
    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
                }
            cor = "vermelho"
        elif product.stock_amount == 1:
            message = _(
                u"Sorry, but '%(product)s' is only one time available.") % {
                    "product": product.name
                }
            cor = "amarelo"
        else:
            message = _(
                u"Sorry, but '%(product)s' is only %(amount)s times available."
            ) % {
                "product": product.name,
                "amount": product.stock_amount
            }
            cor = "amarelo"
        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

            # for product with variants add default variant
            if accessory.is_product_with_variants():
                accessory_variant = accessory.get_default_variant()
                if accessory_variant:
                    accessory = accessory_variant
                else:
                    continue

            # Get quantity
            quantity = request.POST.get("quantity-%s" % accessory_id, 0)
            quantity = accessory.get_clean_quantity_value(quantity)

            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 = "lfs_added_to_cart"

    # Calcular totalizadores do carrinho

    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')
예제 #7
0
파일: views.py 프로젝트: pombredanne/lfs
def add_to_cart(request, product_id=None):
    """Adds the amount of the product with given id to the cart. If the product
    is already within the cart the amount is increased.
    """
    if product_id is None:
        product_id = request.REQUEST.get("product_id")

    product = lfs_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()

    if product.sub_type == PRODUCT_WITH_VARIANTS:
        variant_id = request.POST.get("variant_id")
        product = lfs_get_object_or_404(Product, pk=variant_id)

    try:
        quantity = float(request.POST.get("quantity", 1))
    except TypeError:
        quantity = 1

    cart = cart_utils.get_or_create_cart(request)

    try:
        cart_item = CartItem.objects.get(cart=cart, product=product)
    except ObjectDoesNotExist:
        cart_item = CartItem(cart=cart, product=product, amount=quantity)
        cart_item.save()
    else:
        cart_item.amount += quantity
        cart_item.save()

    cart_items = [cart_item]

    # 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

            try:
                cart_item = CartItem.objects.get(cart=cart, product=accessory)
            except ObjectDoesNotExist:
                cart_item = CartItem(cart=cart, product=accessory, amount=quantity)
                cart_item.save()
            else:
                cart_item.amount += quantity
                cart_item.save()

            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 shipping method (if appropriate)
    payment_utils.update_to_valid_payment_method(request, customer, save=True)

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

    url = reverse("lfs.cart.views.added_to_cart")
    return HttpResponseRedirect(url)