Esempio n. 1
0
def add_accessory_to_cart(request, product_id, quantity=1):
    """
    Adds the product with passed product_id as an accessory to the cart and
    updates the added-to-cart view.
    """
    try:
        quantity = float(quantity)
    except TypeError:
        quantity = 1

    product = lfs_get_object_or_404(Product, pk=product_id)

    session_cart_items = request.session.get("cart_items", [])
    cart = cart_utils.get_cart(request)
    cart_item = cart.add(product=product, amount=quantity)

    # Update session
    if cart_item not in session_cart_items:
        session_cart_items.append(cart_item)
    else:
        for session_cart_item in session_cart_items:
            if cart_item.product == session_cart_item.product:
                session_cart_item.amount += quantity

    request.session["cart_items"] = session_cart_items

    cart_changed.send(cart, request=request)
    return HttpResponse(added_to_cart_items(request))
Esempio n. 2
0
def add_accessory_to_cart(request, product_id, quantity=1):
    """
    Adds the product with passed product_id as an accessory to the cart and
    updates the added-to-cart view.
    """
    product = lfs_get_object_or_404(Product, pk=product_id)
    # for product with variants add default variant
    if product.is_product_with_variants():
        variant = product.get_default_variant()
        if variant:
            product = variant
        else:
            return HttpResponse(added_to_cart_items(request))

    quantity = product.get_clean_quantity_value(quantity)

    session_cart_items = request.session.get("cart_items", [])
    cart = cart_utils.get_cart(request)
    cart_item = cart.add(product=product, amount=quantity)

    # Update session
    if cart_item not in session_cart_items:
        session_cart_items.append(cart_item)
    else:
        for session_cart_item in session_cart_items:
            if cart_item.product == session_cart_item.product:
                session_cart_item.amount += quantity

    request.session["cart_items"] = session_cart_items

    cart_changed.send(cart, request=request)
    return HttpResponse(added_to_cart_items(request))
Esempio n. 3
0
def add_accessory_to_cart(request, product_id, quantity=1):
    """
    Adds the product with passed product_id as an accessory to the cart and
    updates the added-to-cart view.
    """
    product = lfs_get_object_or_404(Product, pk=product_id)
    # for product with variants add default variant
    if product.is_product_with_variants():
        variant = product.get_default_variant()
        if variant:
            product = variant
        else:
            return HttpResponse(added_to_cart_items(request))

    quantity = product.get_clean_quantity_value(quantity)

    session_cart_items = request.session.get("cart_items", [])
    cart = cart_utils.get_cart(request)
    cart_item = cart.add(product=product, amount=quantity)

    # Update session
    if cart_item not in session_cart_items:
        session_cart_items.append(cart_item)
    else:
        for session_cart_item in session_cart_items:
            if cart_item.product == session_cart_item.product:
                session_cart_item.amount += quantity

    request.session["cart_items"] = session_cart_items

    cart_changed.send(cart, request=request)
    return HttpResponse(added_to_cart_items(request))
Esempio n. 4
0
def add_accessory_to_cart(request, product_id, quantity=1):
    """Adds an accessory to the cart and updates the added-to-cart view.
    """
    try:
        quantity = float(quantity)
    except TypeError:
        quantity = 1

    product = lfs_get_object_or_404(Product, pk=product_id)

    session_cart_items = request.session.get("cart_items", [])
    cart = cart_utils.get_cart(request)

    # Add product to cart
    try:
        cart_item = CartItem.objects.get(cart=cart, product=product)
    except ObjectDoesNotExist:
        cart_item = CartItem.objects.create(cart=cart, product=product, amount=quantity)
        session_cart_items.append(cart_item)
    else:
        cart_item.amount += quantity
        cart_item.save()

        if cart_item not in session_cart_items:
            session_cart_items.append(cart_item)
        else:
            # Update save cart item within session
            for session_cart_item in session_cart_items:
                if cart_item.product == session_cart_item.product:
                    session_cart_item.amount += quantity

    request.session["cart_items"] = session_cart_items

    cart_changed.send(cart, request=request)
    return HttpResponse(added_to_cart_items(request))
Esempio n. 5
0
def delete_cart_item(request, cart_item_id):
    """Deletes the cart item with the given id.
    """
    lfs_get_object_or_404(CartItem, pk=cart_item_id).delete()

    cart = cart_utils.get_cart(request)
    cart_changed.send(cart, request=request)

    return HttpResponse(cart_inline(request))
Esempio n. 6
0
File: views.py Progetto: potar/lfs
def delete_cart_item(request, cart_item_id):
    """Deletes the cart item with the given id.
    """
    lfs_get_object_or_404(CartItem, pk=cart_item_id).delete()

    cart = cart_utils.get_cart(request)
    cart_changed.send(cart, request=request)

    return HttpResponse(cart_inline(request))
Esempio n. 7
0
def delete_cart_item(request, cart_item_id):
    """
    Deletes the cart item with the given id.
    """

    cart = cart_utils.get_cart(request)
    if not cart:
        raise Http404

    item = lfs_get_object_or_404(CartItem, pk=cart_item_id)
    if item.cart.id != cart.id:
        raise Http404
    item.delete()

    message = _(u"%(product)s EXCLUIDO") % {"product": item.product.name}
    cor = "vermelho"

    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)

    cart_changed.send(cart, request=request)

    return HttpResponse(result, content_type='application/json')
Esempio n. 8
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))
Esempio n. 9
0
File: views.py Progetto: 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))
Esempio n. 10
0
def delete_cart_item(request, cart_item_id):
    """
    Deletes the cart item with the given id.
    """
    cart = cart_utils.get_cart(request)
    if not cart:
        raise Http404

    item = lfs_get_object_or_404(CartItem, pk=cart_item_id)
    if item.cart.id != cart.id:
        raise Http404
    item.delete()

    cart_changed.send(cart, request=request)

    return HttpResponse(cart_inline(request))
Esempio n. 11
0
def delete_cart_item(request, cart_item_id):
    """
    Deletes the cart item with the given id.
    """
    cart = cart_utils.get_cart(request)
    if not cart:
        raise Http404

    item = lfs_get_object_or_404(CartItem, pk=cart_item_id)
    if item.cart.id != cart.id:
        raise Http404
    item.delete()

    cart_changed.send(cart, request=request)

    return HttpResponse(cart_inline(request))
Esempio n. 12
0
File: views.py Progetto: potar/lfs
def add_accessory_to_cart(request, product_id, quantity=1):
    """Adds an accessory to the cart and updates the added-to-cart view.
    """
    try:
        quantity = float(quantity)
    except TypeError:
        quantity = 1

    product = lfs_get_object_or_404(Product, pk=product_id)

    session_cart_items = request.session.get("cart_items", [])
    cart = cart_utils.get_cart(request)

    # Add product to cart
    try:
        cart_item = CartItem.objects.get(cart=cart, product=product)
    except ObjectDoesNotExist:
        cart_item = CartItem.objects.create(
            cart=cart, product=product, amount=quantity)
        session_cart_items.append(cart_item)
    else:
        cart_item.amount += quantity
        cart_item.save()

        if cart_item not in session_cart_items:
            session_cart_items.append(cart_item)
        else:
            # Update save cart item within session
            for session_cart_item in session_cart_items:
                if cart_item.product == session_cart_item.product:
                    session_cart_item.amount += quantity

    request.session["cart_items"] = session_cart_items

    cart_changed.send(cart, request=request)
    return HttpResponse(added_to_cart_items(request))
Esempio 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')
Esempio n. 14
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_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))
Esempio n. 15
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')
Esempio 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)
    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")
Esempio n. 17
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))
Esempio 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')
Esempio n. 19
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)
Esempio n. 20
0
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)
Esempio n. 21
0
File: views.py Progetto: 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)