Exemplo n.º 1
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 muecke.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
Exemplo n.º 2
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 muecke.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
Exemplo n.º 3
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 muecke.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
Exemplo n.º 4
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 muecke.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
Exemplo n.º 5
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 muecke.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
Exemplo n.º 6
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 muecke.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
Exemplo n.º 7
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 = muecke_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))
Exemplo n.º 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.
    """
    try:
        quantity = float(quantity)
    except TypeError:
        quantity = 1

    product = muecke_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))
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
0
def delete_cart_item(request, cart_item_id):
    """
    Deletes the cart item with the given id.
    """
    muecke_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))
Exemplo n.º 12
0
def delete_cart_item(request, cart_item_id):
    """
    Deletes the cart item with the given id.
    """
    muecke_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))
Exemplo n.º 13
0
def checkout_dispatcher(request):
    """Dispatcher to display the correct checkout form
    """
    shop = muecke.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("muecke_checkout"))
    else:
        return HttpResponseRedirect(reverse("muecke_checkout_login"))
Exemplo n.º 14
0
def checkout_dispatcher(request):
    """Dispatcher to display the correct checkout form
    """
    shop = muecke.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("muecke_checkout"))
    else:
        return HttpResponseRedirect(reverse("muecke_checkout_login"))
Exemplo n.º 15
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()
Exemplo n.º 16
0
def cart_inline(request, template_name="muecke/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 = muecke.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"] + payment_costs["price"]
    cart_tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"]

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

    # Voucher
    voucher_number = muecke.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:
        muecke.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)
        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_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_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,
        "discounts": discounts,
        "display_voucher": display_voucher,
        "voucher_number": voucher_number,
        "voucher_value": voucher_value,
        "voucher_tax": voucher_tax,
        "voucher_number": muecke.voucher.utils.get_current_voucher_number(request),
        "voucher_message": voucher_message,
    }))
Exemplo n.º 17
0
def one_page_checkout(request,
                      checkout_form=OnePageCheckoutForm,
                      template_name="muecke/checkout/one_page_checkout.html"):
    """One page checkout form.
    """
    # If the user is not authenticated and the if only authenticate checkout
    # allowed we rediret to authentication page.
    shop = muecke.core.utils.get_default_shop(request)
    if request.user.is_anonymous() and \
       shop.checkout_type == CHECKOUT_TYPE_AUTH:
        return HttpResponseRedirect(reverse("muecke_checkout_login"))

    customer = customer_utils.get_or_create_customer(request)
    if request.method == "POST":
        form = checkout_form(request.POST)
        toc = True

        if shop.confirm_toc:
            if "confirm_toc" not in request.POST:
                toc = False
                if form.errors is None:
                    form.errors = {}
                form.errors["confirm_toc"] = _(
                    u"Please confirm our terms and conditions")

        # Validate invoice address
        prefix = "invoice"
        country_iso = request.POST.get(prefix + "-country",
                                       shop.default_country.code)
        form_class = form_factory(country_iso)
        invoice_form = form_class(request.POST, prefix=prefix)

        # Validate shipping address
        valid_shipping_form = True
        if not request.POST.get("no_shipping"):
            prefix = "shipping"
            country_iso = request.POST.get(prefix + "-country",
                                           shop.default_country.code)
            form_class = form_factory(country_iso)
            shipping_form = form_class(request.POST, prefix=prefix)
            valid_shipping_form = shipping_form.is_valid()

        if form.is_valid() and invoice_form.is_valid(
        ) and valid_shipping_form and toc:
            # save invoice details
            customer.selected_invoice_address.firstname = request.POST.get(
                "invoice_firstname")
            customer.selected_invoice_address.lastname = request.POST.get(
                "invoice_lastname")
            customer.selected_invoice_address.phone = request.POST.get(
                "invoice_phone")
            customer.selected_invoice_address.email = request.POST.get(
                "invoice_email")
            customer.selected_invoice_address.company_name = request.POST.get(
                "invoice_company_name")

            # Create or update invoice address
            valid_invoice_address = save_address(request, customer,
                                                 INVOICE_PREFIX)
            if valid_invoice_address == False:
                form._errors.setdefault(
                    NON_FIELD_ERRORS,
                    ErrorList([_(u"Invalid invoice address")]))
            else:
                # If the shipping address differs from invoice firstname we create
                # or update the shipping address.
                valid_shipping_address = True
                if not form.cleaned_data.get("no_shipping"):
                    # save shipping details
                    customer.selected_shipping_address.firstname = request.POST.get(
                        "shipping_firstname")
                    customer.selected_shipping_address.lastname = request.POST.get(
                        "shipping_lastname")
                    customer.selected_shipping_address.phone = request.POST.get(
                        "shipping_phone")
                    customer.selected_shipping_address.email = request.POST.get(
                        "shipping_email")
                    customer.selected_shipping_address.company_name = request.POST.get(
                        "shipping_company_name")

                    valid_shipping_address = save_address(
                        request, customer, SHIPPING_PREFIX)

                if valid_shipping_address == False:
                    form._errors.setdefault(
                        NON_FIELD_ERRORS,
                        ErrorList([_(u"Invalid shipping address")]))
                else:
                    # Payment method
                    customer.selected_payment_method_id = request.POST.get(
                        "payment_method")

                    if int(form.data.get("payment_method")) == DIRECT_DEBIT:
                        bank_account = BankAccount.objects.create(
                            account_number=form.cleaned_data.get(
                                "account_number"),
                            bank_identification_code=form.cleaned_data.get(
                                "bank_identification_code"),
                            bank_name=form.cleaned_data.get("bank_name"),
                            depositor=form.cleaned_data.get("depositor"),
                        )

                        customer.selected_bank_account = bank_account

                    # Save the selected information to the customer
                    customer.save()

                    # process the payment method ...
                    result = muecke.payment.utils.process_payment(request)

                    if result["accepted"]:
                        return HttpResponseRedirect(
                            result.get("next_url",
                                       reverse("muecke_thank_you")))
                    else:
                        if "message" in result:
                            form._errors[result.get(
                                "message_location")] = result.get("message")
        else:  # form is not valid
            # save invoice details
            customer.selected_invoice_address.firstname = request.POST.get(
                "invoice_firstname")
            customer.selected_invoice_address.lastname = request.POST.get(
                "invoice_lastname")
            customer.selected_invoice_address.phone = request.POST.get(
                "invoice_phone")
            customer.selected_invoice_address.email = request.POST.get(
                "invoice_email")
            customer.selected_invoice_address.company_name = request.POST.get(
                "invoice_company_name")

            # If the shipping address differs from invoice firstname we create
            # or update the shipping address.
            if not form.data.get("no_shipping"):
                # save shipping details
                customer.selected_shipping_address.firstname = request.POST.get(
                    "shipping_firstname")
                customer.selected_shipping_address.lastname = request.POST.get(
                    "shipping_lastname")
                customer.selected_shipping_address.phone = request.POST.get(
                    "shipping_phone")
                customer.selected_shipping_address.email = request.POST.get(
                    "shipping_email")
                customer.selected_shipping_address.company_name = request.POST.get(
                    "shipping_company_name")
                customer.save()

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

            # 1 = Direct Debit
            if customer.selected_payment_method_id:
                if int(customer.selected_payment_method_id) == DIRECT_DEBIT:
                    bank_account = BankAccount.objects.create(
                        account_number=form.data.get("account_number"),
                        bank_identification_code=form.data.get(
                            "bank_identification_code"),
                        bank_name=form.data.get("bank_name"),
                        depositor=form.data.get("depositor"),
                    )

                    customer.selected_bank_account = bank_account

            # Save the selected information to the customer
            customer.save()

    else:
        # If there are addresses intialize the form.
        initial = {}
        invoice_address = customer.selected_invoice_address
        initial.update({
            "invoice_firstname": invoice_address.firstname,
            "invoice_lastname": invoice_address.lastname,
            "invoice_phone": invoice_address.phone,
            "invoice_email": invoice_address.email,
            "invoice_country": invoice_address.country,
            "invoice_company_name": invoice_address.company_name,
        })
        shipping_address = customer.selected_shipping_address
        initial.update({
            "shipping_firstname": shipping_address.firstname,
            "shipping_lastname": shipping_address.lastname,
            "shipping_phone": shipping_address.phone,
            "shipping_email": shipping_address.email,
            "shipping_company_name": shipping_address.company_name,
            "no_shipping": True,
        })
        form = checkout_form(initial=initial)
    cart = cart_utils.get_cart(request)
    if cart is None:
        return HttpResponseRedirect(reverse('muecke_cart'))

    # Payment
    try:
        selected_payment_method_id = request.POST.get("payment_method")
        selected_payment_method = PaymentMethod.objects.get(
            pk=selected_payment_method_id)
    except PaymentMethod.DoesNotExist:
        selected_payment_method = muecke.payment.utils.get_selected_payment_method(
            request)

    valid_payment_methods = muecke.payment.utils.get_valid_payment_methods(
        request)
    valid_payment_method_ids = [m.id for m in valid_payment_methods]

    display_bank_account = any([
        pm.type == muecke.payment.settings.PM_BANK
        for pm in valid_payment_methods
    ])
    display_credit_card = any([
        pm.type == muecke.payment.settings.PM_CREDIT_CARD
        for pm in valid_payment_methods
    ])

    response = render_to_response(
        template_name,
        RequestContext(
            request, {
                "form":
                form,
                "cart_inline":
                cart_inline(request),
                "shipping_inline":
                shipping_inline(request),
                "invoice_address_inline":
                address_inline(request, INVOICE_PREFIX, form),
                "shipping_address_inline":
                address_inline(request, SHIPPING_PREFIX, form),
                "payment_inline":
                payment_inline(request, form),
                "selected_payment_method":
                selected_payment_method,
                "display_bank_account":
                display_bank_account,
                "display_credit_card":
                display_credit_card,
                "voucher_number":
                muecke.voucher.utils.get_current_voucher_number(request),
                "settings":
                settings,
            }))

    return response
Exemplo n.º 18
0
def cart_inline(request,
                template_name="muecke/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 = muecke.shipping.utils.get_selected_shipping_method(
        request)
    shipping_costs = muecke.shipping.utils.get_shipping_costs(
        request, selected_shipping_method)

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

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

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

    # Voucher
    try:
        voucher_number = muecke.voucher.utils.get_current_voucher_number(
            request)
        voucher = Voucher.objects.get(number=voucher_number)
    except Voucher.DoesNotExist:
        display_voucher = False
        voucher_value = 0
        voucher_tax = 0
        voucher_message = MESSAGES[6]
    else:
        muecke.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)
        else:
            display_voucher = False
            voucher_value = 0
            voucher_tax = 0

    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,
                "display_voucher": display_voucher,
                "discounts": discounts,
                "voucher_value": voucher_value,
                "voucher_tax": voucher_tax,
                "shipping_price": shipping_costs["price"],
                "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,
            }))
Exemplo n.º 19
0
def one_page_checkout(request, checkout_form=OnePageCheckoutForm,
    template_name="muecke/checkout/one_page_checkout.html"):
    """One page checkout form.
    """
    # If the user is not authenticated and the if only authenticate checkout
    # allowed we rediret to authentication page.
    shop = muecke.core.utils.get_default_shop(request)
    if request.user.is_anonymous() and \
       shop.checkout_type == CHECKOUT_TYPE_AUTH:
        return HttpResponseRedirect(reverse("muecke_checkout_login"))

    customer = customer_utils.get_or_create_customer(request)
    if request.method == "POST":
        form = checkout_form(request.POST)
        toc = True

        if shop.confirm_toc:
            if "confirm_toc" not in request.POST:
                toc = False
                if form.errors is None:
                    form.errors = {}
                form.errors["confirm_toc"] = _(u"Please confirm our terms and conditions")

        # Validate invoice address
        prefix="invoice"
        country_iso = request.POST.get(prefix + "-country", shop.default_country.code)
        form_class = form_factory(country_iso)
        invoice_form = form_class(request.POST, prefix=prefix)

        # Validate shipping address
        valid_shipping_form = True
        if not request.POST.get("no_shipping"):
            prefix="shipping"
            country_iso = request.POST.get(prefix + "-country", shop.default_country.code)
            form_class = form_factory(country_iso)
            shipping_form = form_class(request.POST, prefix=prefix)
            valid_shipping_form = shipping_form.is_valid()

        if form.is_valid() and invoice_form.is_valid() and valid_shipping_form and toc:
            # save invoice details
            customer.selected_invoice_address.firstname = request.POST.get("invoice_firstname")
            customer.selected_invoice_address.lastname = request.POST.get("invoice_lastname")
            customer.selected_invoice_address.phone = request.POST.get("invoice_phone")
            customer.selected_invoice_address.email = request.POST.get("invoice_email")
            customer.selected_invoice_address.company_name = request.POST.get("invoice_company_name")

            # Create or update invoice address
            valid_invoice_address = save_address(request, customer, INVOICE_PREFIX)
            if valid_invoice_address == False:
                form._errors.setdefault(NON_FIELD_ERRORS, ErrorList([_(u"Invalid invoice address")]))
            else:
                # If the shipping address differs from invoice firstname we create
                # or update the shipping address.
                valid_shipping_address = True
                if not form.cleaned_data.get("no_shipping"):
                    # save shipping details
                    customer.selected_shipping_address.firstname = request.POST.get("shipping_firstname")
                    customer.selected_shipping_address.lastname = request.POST.get("shipping_lastname")
                    customer.selected_shipping_address.phone = request.POST.get("shipping_phone")
                    customer.selected_shipping_address.email = request.POST.get("shipping_email")
                    customer.selected_shipping_address.company_name = request.POST.get("shipping_company_name")

                    valid_shipping_address = save_address(request, customer, SHIPPING_PREFIX)

                if valid_shipping_address == False:
                    form._errors.setdefault(NON_FIELD_ERRORS, ErrorList([_(u"Invalid shipping address")]))
                else:
                    # Payment method
                    customer.selected_payment_method_id = request.POST.get("payment_method")

                    if int(form.data.get("payment_method")) == DIRECT_DEBIT:
                        bank_account = BankAccount.objects.create(
                            account_number=form.cleaned_data.get("account_number"),
                            bank_identification_code=form.cleaned_data.get("bank_identification_code"),
                            bank_name=form.cleaned_data.get("bank_name"),
                            depositor=form.cleaned_data.get("depositor"),
                        )

                        customer.selected_bank_account = bank_account

                    # Save the selected information to the customer
                    customer.save()

                    # process the payment method ...
                    result = muecke.payment.utils.process_payment(request)

                    if result["accepted"]:
                        return HttpResponseRedirect(result.get("next_url", reverse("muecke_thank_you")))
                    else:
                        if "message" in result:
                            form._errors[result.get("message_location")] = result.get("message")
        else:  # form is not valid
            # save invoice details
            customer.selected_invoice_address.firstname = request.POST.get("invoice_firstname")
            customer.selected_invoice_address.lastname = request.POST.get("invoice_lastname")
            customer.selected_invoice_address.phone = request.POST.get("invoice_phone")
            customer.selected_invoice_address.email = request.POST.get("invoice_email")
            customer.selected_invoice_address.company_name = request.POST.get("invoice_company_name")

            # If the shipping address differs from invoice firstname we create
            # or update the shipping address.
            if not form.data.get("no_shipping"):
                # save shipping details
                customer.selected_shipping_address.firstname = request.POST.get("shipping_firstname")
                customer.selected_shipping_address.lastname = request.POST.get("shipping_lastname")
                customer.selected_shipping_address.phone = request.POST.get("shipping_phone")
                customer.selected_shipping_address.email = request.POST.get("shipping_email")
                customer.selected_shipping_address.company_name = request.POST.get("shipping_company_name")
                customer.save()

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

            # 1 = Direct Debit
            if customer.selected_payment_method_id:
                if int(customer.selected_payment_method_id) == DIRECT_DEBIT:
                    bank_account = BankAccount.objects.create(
                        account_number=form.data.get("account_number"),
                        bank_identification_code=form.data.get("bank_identification_code"),
                        bank_name=form.data.get("bank_name"),
                        depositor=form.data.get("depositor"),
                    )

                    customer.selected_bank_account = bank_account

            # Save the selected information to the customer
            customer.save()

    else:
        # If there are addresses intialize the form.
        initial = {}
        invoice_address = customer.selected_invoice_address
        initial.update({
            "invoice_firstname": invoice_address.firstname,
            "invoice_lastname": invoice_address.lastname,
            "invoice_phone": invoice_address.phone,
            "invoice_email": invoice_address.email,
            "invoice_country": invoice_address.country,
            "invoice_company_name": invoice_address.company_name,
        })
        shipping_address = customer.selected_shipping_address
        initial.update({
            "shipping_firstname": shipping_address.firstname,
            "shipping_lastname": shipping_address.lastname,
            "shipping_phone": shipping_address.phone,
            "shipping_email": shipping_address.email,
            "shipping_company_name": shipping_address.company_name,
            "no_shipping": True,
        })
        form = checkout_form(initial=initial)
    cart = cart_utils.get_cart(request)
    if cart is None:
        return HttpResponseRedirect(reverse('muecke_cart'))

    # Payment
    try:
        selected_payment_method_id = request.POST.get("payment_method")
        selected_payment_method = PaymentMethod.objects.get(pk=selected_payment_method_id)
    except PaymentMethod.DoesNotExist:
        selected_payment_method = muecke.payment.utils.get_selected_payment_method(request)

    valid_payment_methods = muecke.payment.utils.get_valid_payment_methods(request)
    valid_payment_method_ids = [m.id for m in valid_payment_methods]

    display_bank_account = any([pm.type == muecke.payment.settings.PM_BANK for pm in valid_payment_methods])
    display_credit_card = any([pm.type == muecke.payment.settings.PM_CREDIT_CARD for pm in valid_payment_methods])

    response = render_to_response(template_name, RequestContext(request, {
        "form": form,
        "cart_inline": cart_inline(request),
        "shipping_inline": shipping_inline(request),
        "invoice_address_inline": address_inline(request, INVOICE_PREFIX, form),
        "shipping_address_inline": address_inline(request, SHIPPING_PREFIX, form),
        "payment_inline": payment_inline(request, form),
        "selected_payment_method": selected_payment_method,
        "display_bank_account": display_bank_account,
        "display_credit_card": display_credit_card,
        "voucher_number": muecke.voucher.utils.get_current_voucher_number(request),
        "settings": settings,
    }))

    return response
Exemplo n.º 20
0
def cart_inline(request, template_name="muecke/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 = muecke.shipping.utils.get_selected_shipping_method(request)
    shipping_costs = muecke.shipping.utils.get_shipping_costs(request, selected_shipping_method)

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

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

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

    # Voucher
    try:
        voucher_number = muecke.voucher.utils.get_current_voucher_number(request)
        voucher = Voucher.objects.get(number=voucher_number)
    except Voucher.DoesNotExist:
        display_voucher = False
        voucher_value = 0
        voucher_tax = 0
        voucher_message = MESSAGES[6]
    else:
        muecke.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)
        else:
            display_voucher = False
            voucher_value = 0
            voucher_tax = 0

    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,
        "display_voucher": display_voucher,
        "discounts": discounts,
        "voucher_value": voucher_value,
        "voucher_tax": voucher_tax,
        "shipping_price": shipping_costs["price"],
        "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,
    }))
Exemplo n.º 21
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 = muecke.discounts.utils.get_valid_discounts(request)
    for discount in discounts:
        price = price - discount["price_gross"]
        tax = tax - discount["tax"]

    # Add voucher if one exists
    try:
        voucher_number = muecke.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_net"],
            price_gross=-discount["price_gross"],
            tax=-discount["tax"],
            product_sku=discount["sku"],
            product_name=discount["name"],
            product_amount=1,
            product_price_net=-discount["price_net"],
            product_price_gross=-discount["price_gross"],
            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
Exemplo n.º 22
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.get_active_packing_unit():
            item.amount = muecke.catalog.utils.calculate_real_amount(
                item.product, float(amount))
        else:
            item.amount = amount

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

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

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

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

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

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

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

    return HttpResponse(result)
Exemplo n.º 23
0
def cart_inline(request, template_name="muecke/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 = muecke.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"] + payment_costs["price"]
    cart_tax = cart.get_tax(
        request) + shipping_costs["tax"] + payment_costs["tax"]

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

    # Voucher
    voucher_number = muecke.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:
        muecke.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)
        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_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_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,
                "discounts":
                discounts,
                "display_voucher":
                display_voucher,
                "voucher_number":
                voucher_number,
                "voucher_value":
                voucher_value,
                "voucher_tax":
                voucher_tax,
                "voucher_number":
                muecke.voucher.utils.get_current_voucher_number(request),
                "voucher_message":
                voucher_message,
            }))
Exemplo n.º 24
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 = muecke.discounts.utils.get_valid_discounts(request)
    for discount in discounts:
        price = price - discount["price_gross"]
        tax = tax - discount["tax"]

    # Add voucher if one exists
    try:
        voucher_number = muecke.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_net"],
            price_gross=-discount["price_gross"],
            tax=-discount["tax"],
            product_sku=discount["sku"],
            product_name=discount["name"],
            product_amount=1,
            product_price_net=-discount["price_net"],
            product_price_gross=-discount["price_gross"],
            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
Exemplo n.º 25
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.get_active_packing_unit():
            item.amount = muecke.catalog.utils.calculate_real_amount(item.product, 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)