Exemple #1
0
    def test_standard_product(self):
        client = Client()
        self.assertEqual(Cart.objects.count(), 0)

        # add item to cart as anonymous user
        response = client.post(reverse('lfs_add_to_cart'), {
            'product_id': self.p0.id,
            'quantity': 1
        },
                               follow=True)

        self.assertEqual(Cart.objects.count(), 1)
        request = response.context['request']

        cart = get_cart(request)
        self.assertFalse(cart is None)

        # 1. login admin
        # log in not using client.login as this will fail due to use of
        # HttpRequest without middlewares applied (no request.user)
        client.post(reverse('lfs_login'),
                    dict(username='******', password='******', action='login'),
                    follow=True)

        # verify if cart items for logged in user were copied from anonymous cart
        response = client.get(reverse('lfs_cart'))
        request = response.context['request']
        cart = get_cart(request)
        self.assertFalse(cart is None)
        self.assertEqual(int(cart.get_items()[0].amount), 1)

        # logout
        client.logout()

        # add items to the cart again - as anonymous
        response = client.post(reverse('lfs_add_to_cart'), {
            'product_id': self.p0.id,
            'quantity': 2
        },
                               follow=True)
        request = response.context['request']
        cart = get_cart(request)
        self.assertFalse(cart is None)
        self.assertEqual(int(cart.get_items()[0].amount), 2)

        # 2. login admin
        client.post(
            reverse('lfs_login'),
            dict(username='******', password='******', action='login'),
        )

        # verify cart - items should be summed up
        response = client.get(reverse('lfs_cart'))

        request = response.context['request']
        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 3)
Exemple #2
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the width is taken from the product otherwise from
        the cart.
        """
        if product is not None:
            max_width = product.get_width()
        else:
            from lfs.cart import utils as cart_utils
            cart = cart_utils.get_cart(request)
            if cart is None:
                return False

            max_width = 0
            for item in cart.items():
                if max_width < item.product.get_width():
                    max_width = item.product.get_width()

        if self.operator == LESS_THAN and (max_width < self.width):
            return True
        if self.operator == LESS_THAN_EQUAL and (max_width <= self.width):
            return True
        if self.operator == GREATER_THAN and (max_width > self.width):
            return True
        if self.operator == GREATER_THAN_EQUAL and (max_width >= self.width):
            return True
        if self.operator == EQUAL and (max_width == self.width):
            return True

        return False
Exemple #3
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the price is taken from the product otherwise from
        the cart.
        """
        if product is not None:
            cart_price = product.get_price()
        else:
            from lfs.cart import utils as cart_utils
            cart = cart_utils.get_cart(request)

            if cart is None:
                return False

            cart_price = cart_utils.get_cart_price(request, cart)

        if self.operator == LESS_THAN and (cart_price < self.price):
            return True
        if self.operator == LESS_THAN_EQUAL and (cart_price <= self.price):
            return True
        if self.operator == GREATER_THAN and (cart_price > self.price):
            return True
        if self.operator == GREATER_THAN_EQUAL and (cart_price >= self.price):
            return True
        if self.operator == EQUAL and (cart_price == self.price):
            return True

        return False
Exemple #4
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))
Exemple #5
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the price is taken from the product otherwise from
        the cart.
        """
        if product is not None:
            cart_price = product.get_price(request)
        else:
            from lfs.cart import utils as cart_utils
            cart = cart_utils.get_cart(request)

            if cart is None:
                return False

            cart_price = cart.get_price_gross(request)

        if self.operator == LESS_THAN and (cart_price < self.price):
            return True
        if self.operator == LESS_THAN_EQUAL and (cart_price <= self.price):
            return True
        if self.operator == GREATER_THAN and (cart_price > self.price):
            return True
        if self.operator == GREATER_THAN_EQUAL and (cart_price >= self.price):
            return True
        if self.operator == EQUAL and (cart_price == self.price):
            return True

        return False
Exemple #6
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the width is taken from the product otherwise from
        the cart.
        """
        if product is not None:
            max_width = product.get_width()
        else:
            from lfs.cart import utils as cart_utils
            cart = cart_utils.get_cart(request)
            if cart is None:
                return False

            max_width = 0
            for item in cart.get_items():
                if max_width < item.product.get_width():
                    max_width = item.product.get_width()

        if self.operator == LESS_THAN and (max_width < self.width):
            return True
        if self.operator == LESS_THAN_EQUAL and (max_width <= self.width):
            return True
        if self.operator == GREATER_THAN and (max_width > self.width):
            return True
        if self.operator == GREATER_THAN_EQUAL and (max_width >= self.width):
            return True
        if self.operator == EQUAL and (max_width == self.width):
            return True

        return False
Exemple #7
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the weight is taken from the product otherwise from
        the cart.
        """
        if product is not None:
            cart_weight = product.get_weight()
        else:
            from lfs.cart import utils as cart_utils
            cart = cart_utils.get_cart(request)

            if cart is None:
                return False

            cart_weight = 0
            for item in cart.get_items():
                cart_weight += (item.product.get_weight() * item.amount)

        if self.operator == LESS_THAN and (cart_weight < self.weight):
            return True
        if self.operator == LESS_THAN_EQUAL and (cart_weight <= self.weight):
            return True
        if self.operator == GREATER_THAN and (cart_weight > self.weight):
            return True
        if self.operator == GREATER_THAN_EQUAL and (cart_weight >=
                                                    self.weight):
            return True
        if self.operator == EQUAL and (cart_weight == self.weight):
            return True

        return False
Exemple #8
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))
Exemple #9
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the length is taken from the product otherwise from
        the cart.
        """
        from lfs.cart import utils as cart_utils

        cart = cart_utils.get_cart(request)
        if cart is None:
            return False

        if product is not None:
            cart_length = product.length
        else:
            cart_length = 0
            for item in cart.items():
                cart_length += item.product.length * item.amount

        if self.operator == LESS_THAN and (cart_length < self.length):
            return True
        if self.operator == LESS_THAN_EQUAL and (cart_length <= self.length):
            return True
        if self.operator == GREATER_THAN and (cart_length > self.length):
            return True
        if self.operator == GREATER_THAN_EQUAL and (cart_length >= self.length):
            return True
        if self.operator == EQUAL and (cart_length == self.length):
            return True

        return False
Exemple #10
0
def cart_inline(request, template_name="lfs/checkout/checkout_cart_inline.html"):
    """Displays the cart items of the checkout page.

    Factored out to be reusable for the starting request (which renders the
    whole checkout page and subsequent ajax requests which refresh the
    cart items.
    """
    cart = cart_utils.get_cart(request)

    # Shipping
    selected_shipping_method = lfs.shipping.utils.get_selected_shipping_method(request)
    shipping_costs = lfs.shipping.utils.get_shipping_costs(request, selected_shipping_method)

    # Payment
    selected_payment_method = lfs.payment.utils.get_selected_payment_method(request)
    payment_costs = lfs.payment.utils.get_payment_costs(request, selected_payment_method)

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

    return render_to_string(template_name, RequestContext(request, {
        "cart" : cart,
        "cart_price" : cart_price,
        "cart_tax" : cart_tax,
        "shipping_price" : shipping_costs["price"],
        "payment_price" : payment_costs["price"],
        "selected_shipping_method" : selected_shipping_method,
        "selected_payment_method" : selected_payment_method,
    }))
Exemple #11
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the length is taken from the product otherwise from
        the cart.
        """
        from lfs.cart import utils as cart_utils
        cart = cart_utils.get_cart(request)
        if cart is None:
            return False

        if product is not None:
            cart_length = product.length
        else:
            cart_length = 0
            for item in cart.items():
                cart_length += (item.product.length * item.amount)

        if self.operator == LESS_THAN and (cart_length < self.length):
            return True
        if self.operator == LESS_THAN_EQUAL and (cart_length <= self.length):
            return True
        if self.operator == GREATER_THAN and (cart_length > self.length):
            return True
        if self.operator == GREATER_THAN_EQUAL and (cart_length >= self.length):
            return True
        if self.operator == EQUAL and (cart_length == self.length):
            return True

        return False
Exemple #12
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))
Exemple #13
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the weight is taken from the product otherwise from
        the cart.
        """
        if product is not None:
            cart_weight = product.get_weight()
        else:
            from lfs.cart import utils as cart_utils
            cart = cart_utils.get_cart(request)

            if cart is None:
                return False

            cart_weight = 0
            for item in cart.items():
                cart_weight += (item.product.get_weight() * item.amount)

        if self.operator == LESS_THAN and (cart_weight < self.weight):
            return True
        if self.operator == LESS_THAN_EQUAL and (cart_weight <= self.weight):
            return True
        if self.operator == GREATER_THAN and (cart_weight > self.weight):
            return True
        if self.operator == GREATER_THAN_EQUAL and (cart_weight >= self.weight):
            return True
        if self.operator == EQUAL and (cart_weight == self.weight):
            return True

        return False
Exemple #14
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))
Exemple #15
0
 def is_valid(self, request, product=None):
     cart = get_cart(request)
     if not cart or not cart.items():
         return False
     amount = 0
     for item in cart.items():
         amount += item.amount
     return self.test_value(amount)
Exemple #16
0
    def test_standard_product(self):
        session = SessionStore()
        rf = RequestFactory()

        request = rf.post("/", {"product_id": self.p0.id, "quantity": 1})
        request.session = session
        request.user = AnonymousUser()

        cart = get_cart(request)
        self.assertEqual(cart, None)

        add_to_cart(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)

        # 1l login admin
        request = rf.get("/")
        request.session = session
        request.user = self.admin

        cart = get_cart(request)
        self.assertEqual(cart, None)

        update_cart_after_login(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)

        # logout
        session = SessionStore()
        request = rf.post("/", {"product_id": self.p0.id, "quantity": 2})
        request.session = session
        request.user = AnonymousUser()

        cart = get_cart(request)
        self.assertEqual(cart, None)

        add_to_cart(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 2)

        # 2. login admin
        request = rf.get("/")
        request.session = session
        request.user = self.admin

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)

        update_cart_after_login(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 3)
Exemple #17
0
    def test_standard_product(self):
        session = SessionStore()
        rf = RequestFactory()

        request = rf.post("/", {"product_id": self.p0.id, "quantity": 1})
        request.session = session
        request.user = AnonymousUser()

        cart = get_cart(request)
        self.assertEqual(cart, None)

        add_to_cart(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)

        # 1l login admin
        request = rf.get("/")
        request.session = session
        request.user = self.admin

        cart = get_cart(request)
        self.assertEqual(cart, None)

        update_cart_after_login(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)

        # logout
        session = SessionStore()
        request = rf.post("/", {"product_id": self.p0.id, "quantity": 2})
        request.session = session
        request.user = AnonymousUser()

        cart = get_cart(request)
        self.assertEqual(cart, None)

        add_to_cart(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 2)

        # 2. login admin
        request = rf.get("/")
        request.session = session
        request.user = self.admin

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)

        update_cart_after_login(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 3)
Exemple #18
0
    def test_add_order(self):
        """Tests the general adding of an order via the add_order method
        """
        order = add_order(self.request)

        self.assertEqual(order.state, SUBMITTED)
        self.assertEqual("%.2f" % order.price, "9.80")
        self.assertEqual("%.2f" % order.tax, "1.56")

        self.assertEqual(order.shipping_method.name, "Standard")
        self.assertEqual(order.shipping_price, 1.0)
        self.assertEqual("%.2f" % order.shipping_tax, "0.16")

        self.assertEqual(order.payment_method.name, "Direct Debit")
        self.assertEqual(order.payment_price, 0.0)
        self.assertEqual(order.payment_tax, 0.0)

        self.assertEqual(order.shipping_firstname, "John")
        self.assertEqual(order.shipping_lastname, "Doe")
        self.assertEqual(order.shipping_line1, "Street 42")
        self.assertEqual(order.shipping_line2, None)
        self.assertEqual(order.shipping_city, "Gotham City")
        self.assertEqual(order.shipping_code, "2342")
        self.assertEqual(order.shipping_phone, "555-111111")
        self.assertEqual(order.shipping_company_name, "Doe Ltd.")

        self.assertEqual(order.invoice_firstname, "Jane")
        self.assertEqual(order.invoice_lastname, "Doe")
        self.assertEqual(order.invoice_line1, "Street 43")
        self.assertEqual(order.invoice_line2, None)
        self.assertEqual(order.invoice_city, "Smallville")
        self.assertEqual(order.invoice_code, "2443")
        self.assertEqual(order.invoice_phone, "666-111111")
        self.assertEqual(order.invoice_company_name, "Doe Ltd.")

        # Items
        self.assertEqual(len(order.items.all()), 2)

        item = order.items.all().order_by('id')[0]
        self.assertEqual(item.product_amount, 2)
        self.assertEqual(item.product_sku, "sku-1")
        self.assertEqual(item.product_name, "Product 1")
        self.assertEqual("%.2f" % item.product_price_gross, "1.10")
        self.assertEqual("%.2f" % item.product_price_net, "0.92")
        self.assertEqual("%.2f" % item.product_tax, "0.18")

        item = order.items.all().order_by('id')[1]
        self.assertEqual(item.product_amount, 3)
        self.assertEqual(item.product_sku, "sku-2")
        self.assertEqual(item.product_name, "Product 2")
        self.assertEqual("%.2f" % item.product_price_gross, "2.20")
        self.assertEqual("%.2f" % item.product_price_net, "1.85")
        self.assertEqual("%.2f" % item.product_tax, "0.35")

        # The cart should be deleted after the order has been created
        cart = cart_utils.get_cart(self.request)
        self.assertEqual(cart, None)
Exemple #19
0
    def test_add_order(self):
        """Tests the general adding of an order via the add_order method
        """
        order = add_order(self.request)

        self.assertEqual(order.state, SUBMITTED)
        self.assertEqual("%.2f" % order.price, "9.80")
        self.assertEqual("%.2f" % order.tax, "1.56")

        self.assertEqual(order.shipping_method.name, "Standard")
        self.assertEqual(order.shipping_price, 1.0)
        self.assertEqual("%.2f" % order.shipping_tax, "0.16")

        self.assertEqual(order.payment_method.name, "Direct Debit")
        self.assertEqual(order.payment_price, 0.0)
        self.assertEqual(order.payment_tax, 0.0)

        self.assertEqual(order.shipping_firstname, "John")
        self.assertEqual(order.shipping_lastname, "Doe")
        self.assertEqual(order.shipping_line1, "Street 42")
        self.assertEqual(order.shipping_line2, None)
        self.assertEqual(order.shipping_city, "Gotham City")
        self.assertEqual(order.shipping_code, "2342")
        self.assertEqual(order.shipping_phone, "555-111111")
        self.assertEqual(order.shipping_company_name, "Doe Ltd.")

        self.assertEqual(order.invoice_firstname, "Jane")
        self.assertEqual(order.invoice_lastname, "Doe")
        self.assertEqual(order.invoice_line1, "Street 43")
        self.assertEqual(order.invoice_line2, None)
        self.assertEqual(order.invoice_city, "Smallville")
        self.assertEqual(order.invoice_code, "2443")
        self.assertEqual(order.invoice_phone, "666-111111")
        self.assertEqual(order.invoice_company_name, "Doe Ltd.")

        # Items
        self.assertEqual(len(order.items.all()), 2)

        item = order.items.all().order_by('id')[0]
        self.assertEqual(item.product_amount, 2)
        self.assertEqual(item.product_sku, "sku-1")
        self.assertEqual(item.product_name, "Product 1")
        self.assertEqual("%.2f" % item.product_price_gross, "1.10")
        self.assertEqual("%.2f" % item.product_price_net, "0.92")
        self.assertEqual("%.2f" % item.product_tax, "0.18")

        item = order.items.all().order_by('id')[1]
        self.assertEqual(item.product_amount, 3)
        self.assertEqual(item.product_sku, "sku-2")
        self.assertEqual(item.product_name, "Product 2")
        self.assertEqual("%.2f" % item.product_price_gross, "2.20")
        self.assertEqual("%.2f" % item.product_price_net, "1.85")
        self.assertEqual("%.2f" % item.product_tax, "0.35")

        # The cart should be deleted after the order has been created
        cart = cart_utils.get_cart(self.request)
        self.assertEqual(cart, None)
Exemple #20
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))
Exemple #21
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))
Exemple #22
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')
    def _get_quote(self):
        ups_cfg = self._ups_config()

        credentials = {
            'username': ups_cfg.username,
            'password': ups_cfg.password,
            'access_license': ups_cfg.access_license,
            'shipper_number': ups_cfg.shipper_number,
        }

        shipper = Address(
            name=ups_cfg.shipper_name,
            address=ups_cfg.shipper_address,
            city=ups_cfg.shipper_city,
            state=ups_cfg.shipper_state,
            zip=ups_cfg.shipper_zipcode,
            country=ups_cfg.shipper_country.code
        )

        customer = get_customer(self.request)
        ship_address = customer.get_selected_shipping_address()
        recipient = Address(
            name=' '.join([ship_address.firstname or '', ship_address.lastname or '']),
            address=' '.join([ship_address.line1 or '', ship_address.line2 or '']),
            city=ship_address.city,
            state=ship_address.state,
            zip=ship_address.zip_code,
            country=ship_address.country.code
        )

        cart = get_cart(self.request)

        #weight, length, width, height
        product_info = [0, 0, 0, 0]
        for line_item in cart.get_items():
            product_info[0] += line_item.product.weight * line_item.amount
            product_info[1] += line_item.product.length * line_item.amount
            product_info[2] += line_item.product.width * line_item.amount
            product_info[3] += line_item.product.height * line_item.amount

        #import pdb; pdb.set_trace()
        quote = 0.0
        if all(product_info):
            packages = [Package(*product_info)]
            ups = UPSClient(credentials)
            response = ups.rate(
                packages=packages,
                packaging_type=ups_cfg.default_packaging_type,
                shipper=shipper,
                recipient=recipient
            )
            quote = float(response['info'][0]['cost'])

        return quote
Exemple #24
0
def cart_inline(request, template_name="lfs/cart/cart_inline.html"):
    """The actual content of the cart. This is factored out to be reused within
    'normal' and ajax requests.
    """
    cart = cart_utils.get_cart(request)
    shopping_url = lfs.cart.utils.get_go_on_shopping_url(request)
    if cart is None:
        return render_to_string(template_name, RequestContext(request, {"shopping_url": shopping_url}))

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

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

    shipping_costs = shipping_utils.get_shipping_costs(request, selected_shipping_method)

    payment_costs = payment_utils.get_payment_costs(request, selected_payment_method)

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

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

    max_delivery_time = cart_utils.get_cart_max_delivery_time(request, cart)

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

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

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

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

    shipping_costs = shipping_utils.get_shipping_costs(request,
        selected_shipping_method)

    payment_costs = payment_utils.get_payment_costs(request,
        selected_payment_method)

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

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

    max_delivery_time = cart_utils.get_cart_max_delivery_time(request, cart)

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

    return render_to_string(template_name, RequestContext(request, {
        "cart" : cart,
        "max_delivery_date" : max_delivery_date,
        "cart_price" : cart_price,
        "cart_tax" : cart_tax,
        "shipping_methods" : shipping_utils.get_valid_shipping_methods(request),
        "selected_shipping_method" : selected_shipping_method,
        "shipping_price" : shipping_costs["price"],
        "payment_methods" : payment_utils.get_valid_payment_methods(request),
        "selected_payment_method" : selected_payment_method,
        "payment_price" : payment_costs["price"],
        "countries" : countries,
        "selected_country" : selected_country,
        "max_delivery_time" : max_delivery_time,
        "shopping_url" : shopping_url,
    }))
Exemple #26
0
    def _get_quote(self):
        ups_cfg = self._ups_config()

        credentials = {
            'username': ups_cfg.username,
            'password': ups_cfg.password,
            'access_license': ups_cfg.access_license,
            'shipper_number': ups_cfg.shipper_number,
        }

        shipper = Address(name=ups_cfg.shipper_name,
                          address=ups_cfg.shipper_address,
                          city=ups_cfg.shipper_city,
                          state=ups_cfg.shipper_state,
                          zip=ups_cfg.shipper_zipcode,
                          country=ups_cfg.shipper_country.code)

        customer = get_customer(self.request)
        ship_address = customer.get_selected_shipping_address()
        recipient = Address(name=' '.join(
            [ship_address.firstname or '', ship_address.lastname or '']),
                            address=' '.join([
                                ship_address.line1 or '', ship_address.line2
                                or ''
                            ]),
                            city=ship_address.city,
                            state=ship_address.state,
                            zip=ship_address.zip_code,
                            country=ship_address.country.code)

        cart = get_cart(self.request)

        #weight, length, width, height
        product_info = [0, 0, 0, 0]
        for line_item in cart.get_items():
            product_info[0] += line_item.product.weight * line_item.amount
            product_info[1] += line_item.product.length * line_item.amount
            product_info[2] += line_item.product.width * line_item.amount
            product_info[3] += line_item.product.height * line_item.amount

        #import pdb; pdb.set_trace()
        quote = 0.0
        if all(product_info):
            packages = [Package(*product_info)]
            ups = UPSClient(credentials)
            response = ups.rate(packages=packages,
                                packaging_type=ups_cfg.default_packaging_type,
                                shipper=shipper,
                                recipient=recipient)
            quote = float(response['info'][0]['cost'])

        return quote
Exemple #27
0
def checkout_dispatcher(request):
    """Dispatcher to display the correct checkout form
    """
    shop = lfs.core.utils.get_default_shop(request)
    cart = cart_utils.get_cart(request)

    if cart is None or not cart.get_items():
        return empty_page_checkout(request)

    if request.user.is_authenticated() or shop.checkout_type == CHECKOUT_TYPE_ANON:
        return HttpResponseRedirect(reverse("lfs_checkout"))
    else:
        return HttpResponseRedirect(reverse("lfs_checkout_login"))
Exemple #28
0
    def is_valid(self, request, product=None):

        if product:
            return self.test_value(product.weight)

        cart = get_cart(request)
        if not cart or not cart.items():
            return False

        max_weight = cart.items()\
                         .aggregate(max_weight=Max('product__weight'))
        max_weight = max_weight['max_weight']
        return self.test_value(max_weight)
Exemple #29
0
def checkout_dispatcher(request):
    """Dispatcher to display the correct checkout form
    """
    shop = lfs.core.utils.get_default_shop(request)
    cart = cart_utils.get_cart(request)

    if cart is None or not cart.get_items():
        return empty_page_checkout(request)

    if request.user.is_authenticated() or \
       shop.checkout_type == CHECKOUT_TYPE_ANON:
        return HttpResponseRedirect(reverse("lfs_checkout"))
    else:
        return HttpResponseRedirect(reverse("lfs_checkout_login"))
Exemple #30
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))
Exemple #31
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))
Exemple #32
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))
Exemple #33
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))
Exemple #34
0
    def _compute_price(self):
        #Get the zip_code
        customer = get_customer(self.request)
        ship_address = customer.selected_shipping_address
        zip_code = ship_address.zip_code

        #Lookup the zone based on the ZIP Code and weight
        if zip_code:
            zone = get_zone(int(zip_code))
        else:
            zone = 8
        cart = get_cart(self.request)
        weight = 0
        for item in cart.get_items():
            weight += item.product.weight * item.amount
        return get_price(zone, weight)
Exemple #35
0
def process_payment(request):
    """
    Processes the payment depending on the selected payment method. Returns a
    dictionary with the success state, the next url and a optional error
    message.
    """
    from lfs.core.utils import import_symbol
    from lfs.order.utils import add_order
    from lfs.cart.utils import get_cart
    payment_method = get_selected_payment_method(request)

    if payment_method.module:
        payment_class = import_symbol(payment_method.module)
        payment_instance = payment_class(request)

        create_order_time = payment_instance.get_create_order_time()
        if create_order_time == PM_ORDER_IMMEDIATELY:
            order = add_order(request)
            if order is None:
                return {'accepted': True, 'next_url': reverse("lfs_shop_view")}
            payment_instance.order = order
            result = payment_instance.process()
            if result.get("order_state"):
                order.state = result.get("order_state")
                order.save()
            order_submitted.send(sender=order, request=request)
        else:
            cart = get_cart(request)
            payment_instance.cart = cart
            result = payment_instance.process()

        if result["accepted"]:
            if create_order_time == PM_ORDER_ACCEPTED:
                order = add_order(request)
                if result.get("order_state"):
                    order.state = result.get("order_state")
                    order.save()
                order_submitted.send(sender=order, request=request)
        return result
    else:
        order = add_order(request)
        order_submitted.send(sender=order, request=request)
        return {
            "accepted": True,
            "next_url": reverse("lfs_thank_you"),
        }
Exemple #36
0
def process_payment(request):
    """
    Processes the payment depending on the selected payment method. Returns a
    dictionary with the success state, the next url and a optional error
    message.
    """
    from lfs.core.utils import import_symbol
    from lfs.order.utils import add_order
    from lfs.cart.utils import get_cart
    payment_method = get_selected_payment_method(request)

    if payment_method.module:
        payment_class = import_symbol(payment_method.module)
        payment_instance = payment_class(request)

        create_order_time = payment_instance.get_create_order_time()
        if create_order_time == PM_ORDER_IMMEDIATELY:
            order = add_order(request)
            if order is None:
                return {'accepted': True, 'next_url': reverse("lfs_shop_view")}
            payment_instance.order = order
            result = payment_instance.process()
            if result.get("order_state"):
                order.state = result.get("order_state")
                order.save()
            order_submitted.send(sender=order, request=request)
        else:
            cart = get_cart(request)
            payment_instance.cart = cart
            result = payment_instance.process()

        if result["accepted"]:
            if create_order_time == PM_ORDER_ACCEPTED:
                order = add_order(request)
                if result.get("order_state"):
                    order.state = result.get("order_state")
                    order.save()
                order_submitted.send(sender=order, request=request)
        return result
    else:
        order = add_order(request)
        order_submitted.send(sender=order, request=request)
        return {
            "accepted": True,
            "next_url": reverse("lfs_thank_you"),
        }
Exemple #37
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.
        """
        if product:
            result = product.manual_delivery_time
        else:
            cart = get_cart(request)
            if cart is None or not cart.items().exists():
                return False

            result = any(item.product.manual_delivery_time
                         for item in cart.items())

        if self.operator == IS:
            return result
        else:
            return not result
Exemple #38
0
    def is_valid(self, request, product=None):

        if product is not None:
            products = [product]
        else:
            cart = get_cart(request)
            if cart is None or not cart.items().exists():
                return False
            product_ids = list(cart.items().values_list('product', flat=True))
            products = Product.objects.filter(id__in=product_ids)

        profit = 0.
        for product in products:
            price = product.get_price()
            d_price = product.localproduct.get_best_distributor_price()
            profit += (price - d_price)

        return self.test_value(profit)
Exemple #39
0
    def setUp(self):
        """
        """
        self.client.login(username="******", password="******")

        self.user = User.objects.get(username="******")
        self.request = DummyRequest(user=self.user)

        # Create delivery times
        self.dt1 = DeliveryTime.objects.create(min=3,
                                               max=4,
                                               unit=DELIVERY_TIME_UNIT_DAYS)
        self.dt2 = DeliveryTime.objects.create(min=1,
                                               max=2,
                                               unit=DELIVERY_TIME_UNIT_DAYS)
        self.dt3 = DeliveryTime.objects.create(min=5,
                                               max=6,
                                               unit=DELIVERY_TIME_UNIT_DAYS)

        self.sm1 = ShippingMethod.objects.create(name="Standard",
                                                 active=True,
                                                 price=1,
                                                 delivery_time=self.dt1,
                                                 priority=1)
        self.sm2 = ShippingMethod.objects.create(name="Express",
                                                 active=True,
                                                 delivery_time=self.dt2,
                                                 priority=2)

        self.p1 = Product.objects.create(name="Product 1",
                                         slug="p1",
                                         price=9,
                                         weight=6.0,
                                         active=True)
        self.p2 = Product.objects.create(name="Product 2",
                                         slug="p2",
                                         price=11,
                                         weight=12.0,
                                         active=True)

        # Delete the cart for every test method.
        cart = cart_utils.get_cart(self.request)
        if cart:
            cart.delete()
Exemple #40
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.
        """
        if product:
            result = product in self.products.all()
        else:
            cart = get_cart(request)
            if cart is None or not cart.items().exists():
                return False

            products = set(item.product for item in cart.items()
                           if item.product)

            result = bool(products.intersection(self.products.all()))

        if self.operator == IS:
            return result
        else:
            return not result
Exemple #41
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.
        """
        if product:
            result = product.get_for_sale()
        else:
            cart = get_cart(request)
            if cart is None or not cart.items().exists():
                return False

            result = False
            for item in cart.items():
                if item.product.get_for_sale():
                    result = True

        if self.operator == IS:
            return result
        else:
            return not result
Exemple #42
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the combined length and girth is taken from the
        product otherwise from the cart.
        """
        if product is not None:
            clag = (2 * product.get_width()) + (
                2 * product.get_height()) + product.get_length()
        else:
            from lfs.cart import utils as cart_utils
            cart = cart_utils.get_cart(request)
            if cart is None:
                return False

            cart_clag = 0
            max_width = 0
            max_length = 0
            total_height = 0
            for item in cart.get_items():
                if max_length < item.product.get_length():
                    max_length = item.product.get_length()

                if max_width < item.product.get_width():
                    max_width = item.product.get_width()

                total_height += item.product.get_height()

            clag = (2 * max_width) + (2 * total_height) + max_length

        if self.operator == LESS_THAN and (clag < self.clag):
            return True
        if self.operator == LESS_THAN_EQUAL and (clag <= self.clag):
            return True
        if self.operator == GREATER_THAN and (clag > self.clag):
            return True
        if self.operator == GREATER_THAN_EQUAL and (clag >= self.clag):
            return True
        if self.operator == EQUAL and (clag == self.clag):
            return True

        return False
Exemple #43
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.

        If product is given the combined length and girth is taken from the
        product otherwise from the cart.
        """
        if product is not None:
            clag = (2 * product.width) + (2 * product.height) + product.length
        else:
            from lfs.cart import utils as cart_utils

            cart = cart_utils.get_cart(request)
            if cart is None:
                return False

            cart_clag = 0
            max_width = 0
            max_length = 0
            total_height = 0
            for item in cart.items():
                if max_length < item.product.length:
                    max_length = item.product.length

                if max_width < item.product.width:
                    max_width = item.product.width

                total_height += item.product.height

            clag = (2 * max_width) + (2 * total_height) + max_length

        if self.operator == LESS_THAN and (clag < self.clag):
            return True
        if self.operator == LESS_THAN_EQUAL and (clag <= self.clag):
            return True
        if self.operator == GREATER_THAN and (clag > self.clag):
            return True
        if self.operator == GREATER_THAN_EQUAL and (clag >= self.clag):
            return True
        if self.operator == EQUAL and (clag == self.clag):
            return True

        return False
Exemple #44
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.
        """
        if product:
            mnf = product.get_manufacturer()
            result = mnf in self.manufacturers.all()
        else:
            cart = get_cart(request)
            if cart is None or not cart.items().exists():
                return False

            manufacturers = set()
            for item in cart.items():
                manufacturers.add(item.product.get_manufacturer())

            result = bool(manufacturers.intersection(self.manufacturers.all()))

        if self.operator == IS:
            return result
        else:
            return not result
Exemple #45
0
def cart_inline(request,
                template_name="lfs/checkout/checkout_cart_inline.html"):
    """Displays the cart items of the checkout page.

    Factored out to be reusable for the starting request (which renders the
    whole checkout page and subsequent ajax requests which refresh the
    cart items.
    """
    cart = cart_utils.get_cart(request)

    # Shipping
    selected_shipping_method = lfs.shipping.utils.get_selected_shipping_method(
        request)
    shipping_costs = lfs.shipping.utils.get_shipping_costs(
        request, selected_shipping_method)

    # Payment
    selected_payment_method = lfs.payment.utils.get_selected_payment_method(
        request)
    payment_costs = lfs.payment.utils.get_payment_costs(
        request, selected_payment_method)

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

    return render_to_string(
        template_name,
        RequestContext(
            request, {
                "cart": cart,
                "cart_price": cart_price,
                "cart_tax": cart_tax,
                "shipping_price": shipping_costs["price"],
                "payment_price": payment_costs["price"],
                "selected_shipping_method": selected_shipping_method,
                "selected_payment_method": selected_payment_method,
            }))
Exemple #46
0
def tabs(context, obj=None):
    """
    """
    print "AA %s" % "AAAA"
    if obj is None:
        obj = context.get("product") or context.get("category")

    request = context.get("request")
    cart = cart_utils.get_cart(request)
    if cart == None:
        num_cart_items = 0
    else:
        num_cart_items = len(cart.get_items())
        
    tabs = Action.objects.filter(active=True , group=1)
#    if isinstance(obj, (Product, Category)):
#        print "AA %s" % "BBBB"
#        top_category = lfs.catalog.utils.get_current_top_category(request, obj)
#        if top_category:
#            for tab in tabs:
#                if top_category.get_absolute_url().find(tab.link) != -1:
#                    tab.selected = True
#                    break
#    else:
    for tab in tabs:
        urlStr = tab.link.replace("%7B","{")
        urlStr = urlStr.replace("%7D","}")
        urlStr = urlStr.replace("%22",'"')
        
        print "AA %s" % urlStr
        print "CC %s" % request.path
        if request.path.find(urlStr) != -1:
            tab.selected = True
            break
        
    return {
        "tabs": tabs,
        "num_cart_items": num_cart_items,
        "STATIC_URL": context.get("STATIC_URL"),
    }
Exemple #47
0
def get_cart_items_for_paypal(request):
    cart = cart_utils.get_cart(request)
    cart_items = []
    for cart_item in cart.get_items():
        product = cart_item.product
        ouritem = product.get_item()
        quantity = product.get_clean_quantity(cart_item.amount)
        cart_items.append({
            #"obj": cart_item,
            "quantity": quantity,
            #"product": product,
            "product_price_per_item" : product.get_price_formatted(),
            "product_price_net": cart_item.get_price_net(request),
            "product_price_gross": cart_item.get_price_gross(request),
            "product_tax": cart_item.get_tax(request),
            "product_name": product.name,
            "image_url" : product.get_item_image()
        })
    result = simplejson.dumps({
        "items": cart_items
    }, cls=LazyEncoder)

    return HttpResponse(result)   
Exemple #48
0
    def is_valid(self, request, product=None):
        """Returns True if the criterion is valid.
        """
        #content_object = self.criteria_objects.filter()[0].content
        result = True
        cart = get_cart(request)
        if cart is None or not cart.items().exists():
            return False
        compositions = CompositionCategory.objects.filter(criterion=self)

        for composition in compositions:
            amount = 0
            for item in cart.items().filter(
                                product__categories=composition.category):
                amount += item.amount
            if amount < composition.amount:
                result = False
                break

        if self.operator == IS:
            return result
        else:
            return not result
Exemple #49
0
    def setUp(self):
        """
        """
        self.client.login(username="******", password="******")

        self.user = User.objects.get(username="******")
        self.request = DummyRequest(user=self.user)

        # Create delivery times
        self.dt1 = DeliveryTime.objects.create(min=3, max=4, unit=DELIVERY_TIME_UNIT_DAYS)
        self.dt2 = DeliveryTime.objects.create(min=1, max=2, unit=DELIVERY_TIME_UNIT_DAYS)
        self.dt3 = DeliveryTime.objects.create(min=5, max=6, unit=DELIVERY_TIME_UNIT_DAYS)

        self.sm1 = ShippingMethod.objects.create(name="Standard", active=True, price=1, delivery_time=self.dt1, priority=1)
        self.sm2 = ShippingMethod.objects.create(name="Express", active=True, delivery_time=self.dt2, priority=2)

        self.p1 = Product.objects.create(name="Product 1", slug="p1", price=9, weight=6.0, active=True)
        self.p2 = Product.objects.create(name="Product 2", slug="p2", price=11, weight=12.0, active=True)

        # Delete the cart for every test method.
        cart = cart_utils.get_cart(self.request)
        if cart:
            cart.delete()
Exemple #50
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))
Exemple #51
0
    def test_configurable_product(self):
        rf = RequestFactory()
        session = SessionStore()

        request = rf.post(
            "/", {
                "product_id": self.p1.id,
                "quantity": 1,
                "property-%s" % self.pp1.id: "A"
            })
        request.session = session
        request.user = AnonymousUser()

        cart = get_cart(request)
        self.assertEqual(cart, None)

        add_to_cart(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)

        request = rf.post(
            "/", {
                "product_id": self.p1.id,
                "quantity": 10,
                "property-%s" % self.pp1.id: "B"
            })
        request.session = session
        request.user = AnonymousUser()
        add_to_cart(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)
        self.assertEqual(int(cart.get_items()[1].amount), 10)

        # 1. login admin
        request = rf.get("/")
        request.session = session
        request.user = self.admin

        cart = get_cart(request)
        self.assertEqual(cart, None)

        update_cart_after_login(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)
        self.assertEqual(int(cart.get_items()[1].amount), 10)

        # logout
        session = SessionStore()

        request = rf.post(
            "/", {
                "product_id": self.p1.id,
                "quantity": 2,
                "property-%s" % self.pp1.id: "A"
            })
        request.session = session
        request.user = AnonymousUser()

        cart = get_cart(request)
        self.assertEqual(cart, None)

        add_to_cart(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 2)

        request = rf.post(
            "/", {
                "product_id": self.p1.id,
                "quantity": 20,
                "property-%s" % self.pp1.id: "B"
            })
        request.session = session
        request.user = AnonymousUser()
        add_to_cart(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 2)
        self.assertEqual(int(cart.get_items()[1].amount), 20)

        # 2. login admin
        request = rf.get("/")
        request.session = session
        request.user = self.admin

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 1)
        self.assertEqual(int(cart.get_items()[1].amount), 10)

        update_cart_after_login(request)

        cart = get_cart(request)
        self.assertEqual(int(cart.get_items()[0].amount), 3)
        self.assertEqual(int(cart.get_items()[1].amount), 30)
Exemple #52
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')
Exemple #53
0
def cart_inline(request, template_name="lfs/cart/cart_inline.html"):
    """
    The actual content of the cart.

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

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

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

    shipping_costs = shipping_utils.get_shipping_costs(
        request, selected_shipping_method)

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

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

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

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

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

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

    return render_to_string(
        template_name,
        RequestContext(
            request, {
                "cart":
                cart,
                "cart_items":
                cart_items,
                "cart_price":
                cart_price,
                "cart_tax":
                cart_tax,
                "shipping_methods":
                shipping_utils.get_valid_shipping_methods(request),
                "selected_shipping_method":
                selected_shipping_method,
                "shipping_costs":
                shipping_costs,
                "payment_methods":
                payment_utils.get_valid_payment_methods(request),
                "selected_payment_method":
                selected_payment_method,
                "payment_price":
                payment_costs["price"],
                "countries":
                countries,
                "selected_country":
                selected_country,
                "max_delivery_time":
                max_delivery_time,
                "shopping_url":
                shopping_url,
                "discounts":
                discounts,
                "display_voucher":
                display_voucher,
                "voucher_number":
                voucher_number,
                "voucher_value":
                voucher_value,
                "voucher_tax":
                voucher_tax,
                "voucher_message":
                voucher_message,
            }))
Exemple #54
0
def add_order(request):
    """Adds an order based on current cart for the current customer.

    It assumes that the customer is prepared with all needed information. This
    is within the responsibility of the checkout form.
    """
    customer = customer_utils.get_customer(request)
    order = None

    invoice_address = customer.selected_invoice_address
    if request.POST.get("no_shipping"):
        shipping_address = customer.selected_invoice_address
    else:
        shipping_address = customer.selected_shipping_address

    cart = cart_utils.get_cart(request)
    if cart is None:
        return order

    shipping_method = shipping_utils.get_selected_shipping_method(request)
    shipping_costs = shipping_utils.get_shipping_costs(request,
                                                       shipping_method)

    payment_method = payment_utils.get_selected_payment_method(request)
    payment_costs = payment_utils.get_payment_costs(request, payment_method)

    # Set email dependend on login state. An anonymous customer doesn't  have a
    # django user account, so we set the name of the invoice address to the
    # customer name.

    # Note: After this has been processed the order's customer email has an
    # email in any case. That means you can use it to send emails to the
    # customer.
    if request.user.is_authenticated():
        user = request.user
        customer_email = user.email
    else:
        user = None
        customer_email = customer.selected_invoice_address.email

    # Calculate the totals
    price = cart.get_price_gross(
        request) + shipping_costs["price"] + payment_costs["price"]
    tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"]

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

    # Add voucher if one exists
    try:
        voucher_number = lfs.voucher.utils.get_current_voucher_number(request)
        voucher = Voucher.objects.get(number=voucher_number)
    except Voucher.DoesNotExist:
        voucher = None
    else:
        is_voucher_effective, voucher_message = voucher.is_effective(
            request, cart)
        if is_voucher_effective:
            voucher_number = voucher.number
            voucher_price = voucher.get_price_gross(request, cart)
            voucher_tax = voucher.get_tax(request, cart)

            price -= voucher_price
            tax -= voucher_tax
        else:
            voucher = None

    order = Order.objects.create(
        user=user,
        session=request.session.session_key,
        price=price,
        tax=tax,
        customer_firstname=customer.selected_invoice_address.firstname,
        customer_lastname=customer.selected_invoice_address.lastname,
        customer_email=customer_email,
        shipping_method=shipping_method,
        shipping_price=shipping_costs["price"],
        shipping_tax=shipping_costs["tax"],
        payment_method=payment_method,
        payment_price=payment_costs["price"],
        payment_tax=payment_costs["tax"],
        invoice_firstname=customer.selected_invoice_address.firstname,
        invoice_lastname=customer.selected_invoice_address.lastname,
        invoice_company_name=customer.selected_invoice_address.company_name,
        invoice_line1=invoice_address.line1,
        invoice_line2=invoice_address.line2,
        invoice_city=invoice_address.city,
        invoice_state=invoice_address.state,
        invoice_code=invoice_address.zip_code,
        invoice_country=Country.objects.get(code=invoice_address.country.code),
        invoice_phone=customer.selected_invoice_address.phone,
        shipping_firstname=shipping_address.firstname,
        shipping_lastname=shipping_address.lastname,
        shipping_company_name=shipping_address.company_name,
        shipping_line1=shipping_address.line1,
        shipping_line2=shipping_address.line2,
        shipping_city=shipping_address.city,
        shipping_state=shipping_address.state,
        shipping_code=shipping_address.zip_code,
        shipping_country=Country.objects.get(
            code=shipping_address.country.code),
        shipping_phone=shipping_address.phone,
        message=request.POST.get("message", ""),
    )

    requested_delivery_date = request.POST.get("requested_delivery_date", None)
    if requested_delivery_date is not None:
        order.requested_delivery_date = requested_delivery_date
        order.save()

    if voucher:
        voucher.mark_as_used()
        order.voucher_number = voucher_number
        order.voucher_price = voucher_price
        order.voucher_tax = voucher_tax
        order.save()

    # Copy bank account if one exists
    if customer.selected_bank_account:
        bank_account = customer.selected_bank_account
        order.account_number = bank_account.account_number
        order.bank_identification_code = bank_account.bank_identification_code
        order.bank_name = bank_account.bank_name
        order.depositor = bank_account.depositor

    order.save()

    # Copy cart items
    for cart_item in cart.get_items():
        order_item = OrderItem.objects.create(
            order=order,
            price_net=cart_item.get_price_net(request),
            price_gross=cart_item.get_price_gross(request),
            tax=cart_item.get_tax(request),
            product=cart_item.product,
            product_sku=cart_item.product.sku,
            product_name=cart_item.product.get_name(),
            product_amount=cart_item.amount,
            product_price_net=cart_item.product.get_price_net(request),
            product_price_gross=cart_item.get_product_price_gross(request),
            product_tax=cart_item.product.get_tax(request),
        )

        cart_item.product.decrease_stock_amount(cart_item.amount)

        # Copy properties to order
        if cart_item.product.is_configurable_product():
            for cpv in cart_item.properties.all():
                OrderItemPropertyValue.objects.create(order_item=order_item,
                                                      property=cpv.property,
                                                      value=cpv.value)

    for discount in discounts:
        OrderItem.objects.create(
            order=order,
            price_net=-(discount["price"] - discount["tax"]),
            price_gross=-discount["price"],
            tax=-discount["tax"],
            product_sku=discount["sku"],
            product_name=discount["name"],
            product_amount=1,
            product_price_net=-(discount["price"] - discount["tax"]),
            product_price_gross=-discount["price"],
            product_tax=-discount["tax"],
        )

    # Send signal before cart is deleted.
    order_created.send({"order": order, "cart": cart, "request": request})

    cart.delete()

    # Note: Save order for later use in thank you page. The order will be
    # removed from the session if the thank you page has been called.
    request.session["order"] = order

    ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR)
    try:
        order_numbers = ong.objects.get(id="order_number")
    except ong.DoesNotExist:
        order_numbers = ong.objects.create(id="order_number")

    try:
        order_numbers.init(request, order)
    except AttributeError:
        pass

    order.number = order_numbers.get_next()
    order.save()

    return order
Exemple #55
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)
Exemple #56
0
def cart_inline(request, template_name="lfs/cart/cart_inline.html"):
    """
    The actual content of the cart.

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

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

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

    shipping_costs = shipping_utils.get_shipping_costs(request, selected_shipping_method)

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

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

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

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

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

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

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

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

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

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

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

    return render_to_string(template_name, request=request, context={
        "cart": cart,
        "cart_items": cart_items,
        "cart_price": cart_price,
        "cart_tax": cart_tax,
        "shipping_methods": shipping_utils.get_valid_shipping_methods(request),
        "selected_shipping_method": selected_shipping_method,
        "shipping_costs": shipping_costs,
        "payment_methods": payment_utils.get_valid_payment_methods(request),
        "selected_payment_method": selected_payment_method,
        "payment_price": payment_costs["price"],
        "countries": countries,
        "selected_country": selected_country,
        "max_delivery_time": max_delivery_time,
        "shopping_url": shopping_url,
        "discounts": discounts,
        "display_voucher": use_voucher,
        "voucher_number": voucher_data['voucher_number'],
        "voucher_value": voucher_data['voucher_value'],
        "voucher_tax": voucher_data['voucher_tax'],
        "voucher_message": voucher_data['voucher_message'],
    })
Exemple #57
0
    def test_add_order(self):
        """Tests the general adding of an order via the add_order method
        """
        # check we have 2 addresses before the order
        self.assertEqual(4, Address.objects.count())

        order = add_order(self.request)

        # adding an order should deep copy our addresses above
        self.assertEqual(6, Address.objects.count())

        self.assertEqual(order.state, SUBMITTED)
        self.assertEqual("%.2f" % order.price, "9.80")
        self.assertEqual("%.2f" % order.tax, "1.56")

        self.assertEqual(order.shipping_method.name, "Standard")
        self.assertEqual(order.shipping_price, 1.0)
        self.assertEqual("%.2f" % order.shipping_tax, "0.16")

        self.assertEqual(order.payment_method.name, "Direct Debit")
        self.assertEqual(order.payment_price, 0.0)
        self.assertEqual(order.payment_tax, 0.0)

        self.assertEqual(order.shipping_address.firstname, "John")
        self.assertEqual(order.shipping_address.lastname, "Doe")
        self.assertEqual(order.shipping_address.line1, "Street 42")
        self.assertEqual(order.shipping_address.line2, None)
        self.assertEqual(order.shipping_address.city, "Gotham City")
        self.assertEqual(order.shipping_address.zip_code, "2342")
        self.assertEqual(order.shipping_address.phone, "555-111111")
        self.assertEqual(order.shipping_address.company_name, "Doe Ltd.")

        self.assertEqual(order.invoice_address.firstname, "Jane")
        self.assertEqual(order.invoice_address.lastname, "Doe")
        self.assertEqual(order.invoice_address.line1, "Street 43")
        self.assertEqual(order.invoice_address.line2, None)
        self.assertEqual(order.invoice_address.city, "Smallville")
        self.assertEqual(order.invoice_address.zip_code, "2443")
        self.assertEqual(order.invoice_address.phone, "666-111111")
        self.assertEqual(order.invoice_address.company_name, "Doe Ltd.")

        # Items
        self.assertEqual(len(order.items.all()), 2)

        item = order.items.all().order_by('id')[0]
        self.assertEqual(item.product_amount, 2)
        self.assertEqual(item.product_sku, "sku-1")
        self.assertEqual(item.product_name, "Product 1")
        self.assertEqual("%.2f" % item.product_price_gross, "1.10")
        self.assertEqual("%.2f" % item.product_price_net, "0.92")
        self.assertEqual("%.2f" % item.product_tax, "0.18")

        item = order.items.all().order_by('id')[1]
        self.assertEqual(item.product_amount, 3)
        self.assertEqual(item.product_sku, "sku-2")
        self.assertEqual(item.product_name, "Product 2")
        self.assertEqual("%.2f" % item.product_price_gross, "2.20")
        self.assertEqual("%.2f" % item.product_price_net, "1.85")
        self.assertEqual("%.2f" % item.product_tax, "0.35")

        # The cart should be deleted after the order has been created
        cart = cart_utils.get_cart(self.request)
        self.assertEqual(cart, None)

        # delivery time should of the selected shipping method should be saved with order
        self.assertTrue(order.delivery_time is not None)
Exemple #58
0
def cart_inline(request,
                template_name="lfs/checkout/checkout_cart_inline.html"):
    """Displays the cart items of the checkout page.

    Factored out to be reusable for the starting request (which renders the
    whole checkout page and subsequent ajax requests which refresh the
    cart items.
    """
    cart = cart_utils.get_cart(request)

    # Shipping
    selected_shipping_method = lfs.shipping.utils.get_selected_shipping_method(
        request)
    shipping_costs = lfs.shipping.utils.get_shipping_costs(
        request, selected_shipping_method)

    # Payment
    selected_payment_method = lfs.payment.utils.get_selected_payment_method(
        request)
    payment_costs = lfs.payment.utils.get_payment_costs(
        request, selected_payment_method)

    # Cart costs
    cart_price = 0
    cart_tax = 0
    if cart is not None:
        cart_price = cart.get_price_gross(
            request) + shipping_costs["price_gross"] + payment_costs["price"]
        cart_tax = cart.get_tax(
            request) + shipping_costs["tax"] + payment_costs["tax"]

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

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

    if cart_price < 0:
        cart_price = 0
    if cart_tax < 0:
        cart_tax = 0

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

    return render_to_string(
        template_name,
        RequestContext(
            request, {
                "cart": cart,
                "cart_items": cart_items,
                "cart_price": cart_price,
                "cart_tax": cart_tax,
                "display_voucher": display_voucher,
                "discounts": discounts,
                "voucher_value": voucher_value,
                "voucher_tax": voucher_tax,
                "shipping_costs": shipping_costs,
                "payment_price": payment_costs["price"],
                "selected_shipping_method": selected_shipping_method,
                "selected_payment_method": selected_payment_method,
                "voucher_number": voucher_number,
                "voucher_message": voucher_message,
            }))