Beispiel #1
0
def address_inline(request, prefix, form):
    """displays the invoice address with localized fields
    """
    template_name = "muecke/customer/" + prefix + "_address_inline.html"
    country_code = get_country_code(request, prefix)
    if country_code != '':
        shop = muecke.core.utils.get_default_shop(request)
        countries = None
        if prefix == INVOICE_PREFIX:
            countries = shop.invoice_countries.all()
        else:
            countries = shop.shipping_countries.all()
        customer = customer_utils.get_or_create_customer(request)
        address_form_class = form_factory(country_code)
        if request.method == 'POST':
            if POSTAL_ADDRESS_L10N == True:
                address_form = address_form_class(prefix=prefix, data=request.POST,)
            else:
                address_form = PostalAddressForm(prefix=prefix, data=request.POST,)
            if countries is not None:
                address_form.fields["country"].choices = [(c.code.upper(), c.name) for c in countries]
        else:
            # If there are addresses intialize the form.
            initial = {}
            customer_selected_address = None
            if hasattr(customer, 'selected_' + prefix + '_address'):
                customer_selected_address = getattr(customer, 'selected_' + prefix + '_address')
            if customer_selected_address is not None:
                initial.update({
                    "line1": customer_selected_address.line1,
                    "line2": customer_selected_address.line2,
                    "city" : customer_selected_address.city,
                    "state": customer_selected_address.state,
                    "code": customer_selected_address.zip_code,
                    "country": customer_selected_address.country.code.upper(),
                })
                address_form = address_form_class(prefix=prefix, initial=initial)
            else:
                address_form = address_form_class(prefix=prefix)
                address_form.fields["country"].initial = country_code
            if countries is not None:
                address_form.fields["country"].choices = [(c.code.upper(), c.name) for c in countries]

    # Removes fields from address form if requested via settings.
    for i in range(1, 6):
        address_settings = getattr(settings, "POSTAL_ADDRESS_LINE%s" % i, None)
        try:
            if address_settings and address_settings[2] == False:
                del address_form.fields["line%s" % i]
        except IndexError:
            pass

    # if request via ajax don't display validity errors
    if request.is_ajax():
        address_form._errors = {}
    return render_to_string(template_name, RequestContext(request, {
        "address_form": address_form,
        "form": form,
        "settings": settings,
    }))
Beispiel #2
0
    def test_get_product_delivery_time_2(self):
        """Tests the product delivery time for the *cart view*.
        """
        request = create_request()
        request.user = AnonymousUser()

        customer = customer_utils.get_or_create_customer(request)
        customer.selected_shipping_method = self.sm1
        customer.save()

        dt = utils.get_product_delivery_time(request, self.p1, for_cart=True)
        self.assertEqual(dt.min, self.dt1.min)
        self.assertEqual(dt.max, self.dt1.max)
        self.assertEqual(dt.unit, self.dt1.unit)

        dt = utils.get_product_delivery_time(request, self.p2, for_cart=True)
        self.assertEqual(dt.min, self.dt1.min)
        self.assertEqual(dt.max, self.dt1.max)
        self.assertEqual(dt.unit, self.dt1.unit)

        customer.selected_shipping_method = self.sm2
        customer.save()

        # As the customer has now selected sm2 explicitely the delivery method
        # for the products is dt2 although the default shipping method is
        # sm1.
        dt = utils.get_product_delivery_time(request, self.p1, for_cart=True)
        self.assertEqual(dt.min, self.dt2.min)
        self.assertEqual(dt.max, self.dt2.max)
        self.assertEqual(dt.unit, self.dt2.unit)

        # For product 2 sm1 is valid, hence we should get dt1
        dt = utils.get_product_delivery_time(request, self.p2, for_cart=True)
        self.assertEqual(dt.min, self.dt2.min)
        self.assertEqual(dt.max, self.dt2.max)
        self.assertEqual(dt.unit, self.dt2.unit)

        # Create a weigth criterion and add it to the shipping method 1. That
        # means sm1 is not valid anymore for p1.
        c = WeightCriterion.objects.create(weight=10.0, operator=GREATER_THAN)
        co = CriteriaObjects(criterion=c, content=self.sm1)
        co.save()

        # And even if the customer select sm1 explicitely ...
        customer.selected_shipping_method = self.sm1
        customer.save()

        # ... the shipping method for p1 is sm2 and hence the delivery time is
        # dt1
        dt = utils.get_product_delivery_time(request, self.p1, for_cart=True)
        self.assertEqual(dt.min, self.dt2.min)
        self.assertEqual(dt.max, self.dt2.max)
        self.assertEqual(dt.unit, self.dt2.unit)
Beispiel #3
0
    def test_get_product_delivery_time_1(self):
        """Tests the product delivery time for the *product view*.
        """
        request = create_request()
        request.user = AnonymousUser()

        customer = customer_utils.get_or_create_customer(request)
        customer.selected_shipping_method = self.sm1
        customer.save()

        # We select a explicitely shipping method for the customer. For the
        # product view this shouldn't make a difference. It should always the
        # first valid shipping method be taken to display the delivery time.
        customer.selected_shipping_method = self.sm2
        customer.save()

        # Create a weigth criterion and add it to the shipping method 1.
        c = WeightCriterion.objects.create(weight=10.0, operator=GREATER_THAN)
        co = CriteriaObjects(criterion=c, content=self.sm1)
        co.save()

        # Create a weigth criterion and add it to the shipping method 2.
        c = WeightCriterion.objects.create(weight=10.0, operator=LESS_THAN)
        co = CriteriaObjects(criterion=c, content=self.sm2)
        co.save()

        # Now we ask for the delivery time for product 1. As sm1 is not valid
        # (p1 has an weight of 6.0) we should get the delivery time from sm2,
        # which is dt2
        dt = utils.get_product_delivery_time(request, self.p1)
        self.assertEqual(dt.min, self.dt2.min)
        self.assertEqual(dt.max, self.dt2.max)
        self.assertEqual(dt.unit, self.dt2.unit)

        # For product 2 sm1 is valid (p2 has an weight of 11.0), hence we should
        # get dt1.
        dt = utils.get_product_delivery_time(request, self.p2)
        self.assertEqual(dt.min, self.dt1.min)
        self.assertEqual(dt.max, self.dt1.max)
        self.assertEqual(dt.unit, self.dt1.unit)

        # Now we switch to manual delivery time
        self.p1.manual_delivery_time = True
        self.p1.delivery_time = self.dt3
        self.p1.save()

        dt = utils.get_product_delivery_time(request, self.p1)
        self.assertEqual(dt.min, self.dt3.min)
        self.assertEqual(dt.max, self.dt3.max)
        self.assertEqual(dt.unit, self.dt3.unit)
Beispiel #4
0
def changed_checkout(request):
    """
    """
    form = OnePageCheckoutForm()
    customer = customer_utils.get_or_create_customer(request)
    _save_customer(request, customer)
    _save_country(request, customer)

    result = simplejson.dumps({
        SHIPPING_PREFIX: shipping_inline(request),
        "payment": payment_inline(request, form),
        "cart": cart_inline(request),
    })

    return HttpResponse(result)
Beispiel #5
0
def changed_checkout(request):
    """
    """
    form = OnePageCheckoutForm()
    customer = customer_utils.get_or_create_customer(request)
    _save_customer(request, customer)
    _save_country(request, customer)

    result = simplejson.dumps({
        SHIPPING_PREFIX: shipping_inline(request),
        "payment": payment_inline(request, form),
        "cart": cart_inline(request),
    })

    return HttpResponse(result)
Beispiel #6
0
    def setUp(self):
        self.us = Country.objects.create(code="us", name="USA")
        self.ch = Country.objects.create(code="ch", name="Switzerland")
        self.de = Country.objects.create(code="de", name="Germany")
        self.ie = Country.objects.create(code="ie", name="Ireland")

        self.product = Product.objects.create(name="P1", slug="p1", price=100.0)

        self.request = create_request()
        self.request.user = AnonymousUser()
        self.customer = get_or_create_customer(self.request)

        self.ct1 = CustomerTax.objects.create(rate = 20.0)
        self.ct1.countries.add(self.ch)
        self.ct1.countries.add(self.us)

        self.ct2 = CustomerTax.objects.create(rate = 10.0)
        self.ct2.countries.add(self.ie)
Beispiel #7
0
    def setUp(self):
        self.us = Country.objects.create(code="us", name="USA")
        self.ch = Country.objects.create(code="ch", name="Switzerland")
        self.de = Country.objects.create(code="de", name="Germany")
        self.ie = Country.objects.create(code="ie", name="Ireland")

        self.product = Product.objects.create(name="P1",
                                              slug="p1",
                                              price=100.0)

        self.request = create_request()
        self.request.user = AnonymousUser()
        self.customer = get_or_create_customer(self.request)

        self.ct1 = CustomerTax.objects.create(rate=20.0)
        self.ct1.countries.add(self.ch)
        self.ct1.countries.add(self.us)

        self.ct2 = CustomerTax.objects.create(rate=10.0)
        self.ct2.countries.add(self.ie)
Beispiel #8
0
def get_country_code(request, prefix):
    # get country_code from the request
    country_code = request.POST.get(prefix + '-country', '')

    # get country code from customer
    if country_code == '':
        customer = customer_utils.get_or_create_customer(request)
        if prefix == INVOICE_PREFIX:
            if customer.selected_invoice_address is not None:
                if customer.selected_invoice_address.country is not None:
                    country_code = customer.selected_invoice_address.country.code
        elif prefix == SHIPPING_PREFIX:
            if customer.selected_shipping_address is not None:
                if customer.selected_shipping_address.country is not None:
                    country_code = customer.selected_shipping_address.country.code

    # get country code from shop
    if country_code == '':
        shop = muecke.core.utils.get_default_shop(request)
        if shop.default_country is not None:
            country_code = shop.default_country.code
    return country_code
Beispiel #9
0
def get_country_code(request, prefix):
    # get country_code from the request
    country_code = request.POST.get(prefix + '-country', '')

    # get country code from customer
    if country_code == '':
        customer = customer_utils.get_or_create_customer(request)
        if prefix == INVOICE_PREFIX:
            if customer.selected_invoice_address is not None:
                if customer.selected_invoice_address.country is not None:
                    country_code = customer.selected_invoice_address.country.code
        elif prefix == SHIPPING_PREFIX:
            if customer.selected_shipping_address is not None:
                if customer.selected_shipping_address.country is not None:
                    country_code = customer.selected_shipping_address.country.code

    # get country code from shop
    if country_code == '':
        shop = muecke.core.utils.get_default_shop(request)
        if shop.default_country is not None:
            country_code = shop.default_country.code
    return country_code
Beispiel #10
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)
Beispiel #11
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
Beispiel #12
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
Beispiel #13
0
def refresh_cart(request):
    """
    Refreshes the cart after some changes has been taken place, e.g.: the
    amount of a product or shipping/payment method.
    """
    cart = cart_utils.get_cart(request)
    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)
Beispiel #14
0
def add_to_cart(request, product_id=None):
    """
    Adds the passed product with passed product_id to the cart after
    some validations have been taken place. The amount is taken from the query
    string.
    """
    if product_id is None:
        product_id = request.REQUEST.get("product_id")

    product = muecke_get_object_or_404(Product, pk=product_id)

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

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

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

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

                properties_dict[property_id] = unicode(value)

                # validate property's value
                if property.is_number_field:

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

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

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

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

    cart = cart_utils.get_or_create_cart(request)

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

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

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

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

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

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

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

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

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

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

    if message:
        return muecke.core.utils.set_message_cookie(reverse(url_name), message)
    else:
        return HttpResponseRedirect(reverse(url_name))
Beispiel #15
0
def login(request, template_name="muecke/customer/login.html"):
    """Custom view to login or register/login a user.

    The reason to use a custom login method are:

      * validate checkout type
      * integration of register and login form

    It uses Django's standard AuthenticationForm, though.
    """
    shop = muecke.core.utils.get_default_shop(request)

    # If only anonymous checkout is allowed this view doesn't exists :)
    # if shop.checkout_type == CHECKOUT_TYPE_ANON:
    #     raise Http404()

    # Using Djangos default AuthenticationForm
    login_form = AuthenticationForm()
    login_form.fields["username"].label = _(u"E-Mail")
    register_form = RegisterForm()

    if request.POST.get("action") == "login":
        login_form = AuthenticationForm(data=request.POST)
        login_form.fields["username"].label = _(u"E-Mail")

        if login_form.is_valid():
            redirect_to = request.POST.get("next")
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = reverse("muecke_shop_view")

            from django.contrib.auth import login
            login(request, login_form.get_user())

            return muecke.core.utils.set_message_cookie(
                redirect_to, msg=_(u"You have been logged in."))

    elif request.POST.get("action") == "register":
        register_form = RegisterForm(data=request.POST)
        if register_form.is_valid():

            email = register_form.data.get("email")
            password = register_form.data.get("password_1")

            # Create user
            user = User.objects.create_user(
                username=email, email=email, password=password)

            # Create customer
            customer = customer_utils.get_or_create_customer(request)
            customer.user = user

            # Notify
            muecke.core.signals.customer_added.send(user)

            # Log in user
            from django.contrib.auth import authenticate
            user = authenticate(username=email, password=password)

            from django.contrib.auth import login
            login(request, user)

            redirect_to = request.POST.get("next")
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = reverse("muecke_shop_view")

            return muecke.core.utils.set_message_cookie(
                redirect_to, msg=_(u"You have been registered and logged in."))

    # Get next_url
    next_url = request.REQUEST.get("next")
    if next_url is None:
        next_url = request.META.get("HTTP_REFERER")
    if next_url is None:
        next_url = reverse("muecke_shop_view")

    # Get just the path of the url. See django.contrib.auth.views.login for more
    next_url = urlparse(next_url)
    next_url = next_url[2]

    try:
        login_form_errors = login_form.errors["__all__"]
    except KeyError:
        login_form_errors = None

    return render_to_response(template_name, RequestContext(request, {
        "login_form": login_form,
        "login_form_errors": login_form_errors,
        "register_form": register_form,
        "next_url": next_url,
    }))
Beispiel #16
0
def add_to_cart(request, product_id=None):
    """
    Adds the passed product with passed product_id to the cart after
    some validations have been taken place. The amount is taken from the query
    string.
    """
    if product_id is None:
        product_id = request.REQUEST.get("product_id")

    product = muecke_get_object_or_404(Product, pk=product_id)

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

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

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

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

                properties_dict[property_id] = unicode(value)

                # validate property's value
                if property.is_number_field:

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

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

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

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

    cart = cart_utils.get_or_create_cart(request)

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

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

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

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

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

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

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

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

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

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

    if message:
        return muecke.core.utils.set_message_cookie(reverse(url_name), message)
    else:
        return HttpResponseRedirect(reverse(url_name))
Beispiel #17
0
def address_inline(request, prefix, form):
    """displays the invoice address with localized fields
    """
    template_name = "muecke/customer/" + prefix + "_address_inline.html"
    country_code = get_country_code(request, prefix)
    if country_code != '':
        shop = muecke.core.utils.get_default_shop(request)
        countries = None
        if prefix == INVOICE_PREFIX:
            countries = shop.invoice_countries.all()
        else:
            countries = shop.shipping_countries.all()
        customer = customer_utils.get_or_create_customer(request)
        address_form_class = form_factory(country_code)
        if request.method == 'POST':
            if POSTAL_ADDRESS_L10N == True:
                address_form = address_form_class(
                    prefix=prefix,
                    data=request.POST,
                )
            else:
                address_form = PostalAddressForm(
                    prefix=prefix,
                    data=request.POST,
                )
            if countries is not None:
                address_form.fields["country"].choices = [
                    (c.code.upper(), c.name) for c in countries
                ]
        else:
            # If there are addresses intialize the form.
            initial = {}
            customer_selected_address = None
            if hasattr(customer, 'selected_' + prefix + '_address'):
                customer_selected_address = getattr(
                    customer, 'selected_' + prefix + '_address')
            if customer_selected_address is not None:
                initial.update({
                    "line1":
                    customer_selected_address.line1,
                    "line2":
                    customer_selected_address.line2,
                    "city":
                    customer_selected_address.city,
                    "state":
                    customer_selected_address.state,
                    "code":
                    customer_selected_address.zip_code,
                    "country":
                    customer_selected_address.country.code.upper(),
                })
                address_form = address_form_class(prefix=prefix,
                                                  initial=initial)
            else:
                address_form = address_form_class(prefix=prefix)
                address_form.fields["country"].initial = country_code
            if countries is not None:
                address_form.fields["country"].choices = [
                    (c.code.upper(), c.name) for c in countries
                ]

    # Removes fields from address form if requested via settings.
    for i in range(1, 6):
        address_settings = getattr(settings, "POSTAL_ADDRESS_LINE%s" % i, None)
        try:
            if address_settings and address_settings[2] == False:
                del address_form.fields["line%s" % i]
        except IndexError:
            pass

    # if request via ajax don't display validity errors
    if request.is_ajax():
        address_form._errors = {}
    return render_to_string(
        template_name,
        RequestContext(request, {
            "address_form": address_form,
            "form": form,
            "settings": settings,
        }))
Beispiel #18
0
def login(request, template_name="muecke/customer/login.html"):
    """Custom view to login or register/login a user.

    The reason to use a custom login method are:

      * validate checkout type
      * integration of register and login form

    It uses Django's standard AuthenticationForm, though.
    """
    shop = muecke.core.utils.get_default_shop(request)

    # If only anonymous checkout is allowed this view doesn't exists :)
    # if shop.checkout_type == CHECKOUT_TYPE_ANON:
    #     raise Http404()

    # Using Djangos default AuthenticationForm
    login_form = AuthenticationForm()
    login_form.fields["username"].label = _(u"E-Mail")
    register_form = RegisterForm()

    if request.POST.get("action") == "login":
        login_form = AuthenticationForm(data=request.POST)
        login_form.fields["username"].label = _(u"E-Mail")

        if login_form.is_valid():
            redirect_to = request.POST.get("next")
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = reverse("muecke_shop_view")

            from django.contrib.auth import login
            login(request, login_form.get_user())

            return muecke.core.utils.set_message_cookie(
                redirect_to, msg=_(u"You have been logged in."))

    elif request.POST.get("action") == "register":
        register_form = RegisterForm(data=request.POST)
        if register_form.is_valid():

            email = register_form.data.get("email")
            password = register_form.data.get("password_1")

            # Create user
            user = User.objects.create_user(username=email,
                                            email=email,
                                            password=password)

            # Create customer
            customer = customer_utils.get_or_create_customer(request)
            customer.user = user

            # Notify
            muecke.core.signals.customer_added.send(user)

            # Log in user
            from django.contrib.auth import authenticate
            user = authenticate(username=email, password=password)

            from django.contrib.auth import login
            login(request, user)

            redirect_to = request.POST.get("next")
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = reverse("muecke_shop_view")

            return muecke.core.utils.set_message_cookie(
                redirect_to, msg=_(u"You have been registered and logged in."))

    # Get next_url
    next_url = request.REQUEST.get("next")
    if next_url is None:
        next_url = request.META.get("HTTP_REFERER")
    if next_url is None:
        next_url = reverse("muecke_shop_view")

    # Get just the path of the url. See django.contrib.auth.views.login for more
    next_url = urlparse(next_url)
    next_url = next_url[2]

    try:
        login_form_errors = login_form.errors["__all__"]
    except KeyError:
        login_form_errors = None

    return render_to_response(
        template_name,
        RequestContext(
            request, {
                "login_form": login_form,
                "login_form_errors": login_form_errors,
                "register_form": register_form,
                "next_url": next_url,
            }))