def test_shipping_price_4(self): """Tests an additional shipping method price with a criterion and customer price """ # create country dependent tax self.us = Country.objects.create(code="us", name="USA") self.ch = Country.objects.create(code="ch", name="Switzerland") self.request = create_request() self.request.user = AnonymousUser() self.customer = get_or_create_customer(self.request) self.ct1 = CustomerTax.objects.create(rate=10.0) cc = CountryCriterion.objects.create(content=self.ct1, operator=Criterion.IS_SELECTED) cc.value.add(self.us) self.sm1.price = 10 self.sm1.price_calculator = settings.LFS_SHIPPING_METHOD_PRICE_CALCULATORS[1][0] self.sm1.save() costs = utils.get_shipping_costs(self.request, self.sm1) self.assertEqual(costs["price_gross"], 10) self.assertEqual(costs["price_net"], 10) self.assertEqual(costs["tax"], 0) self.customer.selected_shipping_address.country = self.us self.customer.selected_shipping_address.save() costs = utils.get_shipping_costs(self.request, self.sm1) self.assertEqual(costs["price_gross"], 11) self.assertEqual(costs["price_net"], 10) self.assertEqual(costs["tax"], 1)
def address_inline(request, prefix, form): """displays the invoice address with localized fields """ template_name = "lfs/customer/" + prefix + "_address_inline.html" country_code = get_country_code(request, prefix) if country_code != '': shop = lfs.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, }))
def test_shipping_price_4(self): """Tests an additional shipping method price with a criterion and customer price """ # create country dependent tax self.us = Country.objects.create(code="us", name="USA") self.ch = Country.objects.create(code="ch", name="Switzerland") self.request = create_request() self.request.user = AnonymousUser() self.customer = get_or_create_customer(self.request) self.ct1 = CustomerTax.objects.create(rate=10.0) cc = CountryCriterion.objects.create(content=self.ct1, operator=Criterion.IS_SELECTED) cc.value.add(self.us) self.sm1.price = 10 self.sm1.price_calculator = settings.LFS_SHIPPING_METHOD_PRICE_CALCULATORS[ 1][0] self.sm1.save() costs = utils.get_shipping_costs(self.request, self.sm1) self.assertEqual(costs["price_gross"], 10) self.assertEqual(costs["price_net"], 10) self.assertEqual(costs["tax"], 0) self.customer.selected_shipping_address.country = self.us self.customer.selected_shipping_address.save() costs = utils.get_shipping_costs(self.request, self.sm1) self.assertEqual(costs["price_gross"], 11) self.assertEqual(costs["price_net"], 10) self.assertEqual(costs["tax"], 1)
def address_inline(request, prefix, form): """displays the invoice address with localized fields """ template_name = "lfs/customer/" + prefix + "_address_inline.html" country_code = get_country_code(request, prefix) if country_code != '': shop = lfs.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] save_address(request, customer, prefix) 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.company_name, "line2": customer_selected_address.street, "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, }))
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. WeightCriterion.objects.create(content=self.sm1, value=10.0, operator=GREATER_THAN) # 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 # dt2 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)
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)
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": shipping_inline(request), "payment": payment_inline(request, form), "cart": cart_inline(request)} ) return HttpResponse(result)
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)
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. WeightCriterion.objects.create(content=self.sm1, value=10.0, operator=GREATER_THAN) # Create a weigth criterion and add it to the shipping method 2. WeightCriterion.objects.create(content=self.sm2, value=10.0, operator=LESS_THAN) # 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)
def refresh_cart(request): """Refreshes the cart after some changes has been taken place: the amount of a product or shipping/payment method. """ cart = cart_utils.get_cart(request) customer = customer_utils.get_or_create_customer(request) # Update country country = request.POST.get("country") if customer.selected_shipping_address: customer.selected_shipping_address.country_id = country customer.selected_shipping_address.save() if customer.selected_invoice_address: customer.selected_invoice_address.country_id = country customer.selected_invoice_address.save() customer.selected_country_id = country # NOTE: The customer has to be saved already here in order to calculate # a possible new valid shippig method below, which coulb be triggered by # the changing of the shipping country. customer.save() # Update Amounts for item in cart.items(): amount = request.POST.get("amount-cart-item_%s" % item.id, 0) try: item.amount = int(amount) except ValueError: item.amount = 1 item.save() # IMPORTANT: We have to send the signal already here, because the valid # shipping methods might be dependent on the price. cart_changed.send(cart, request=request) # Update shipping method customer.selected_shipping_method_id = request.POST.get("shipping_method") valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request) if customer.selected_shipping_method not in valid_shipping_methods: customer.selected_shipping_method = shipping_utils.get_default_shipping_method(request) # Update payment method customer.selected_payment_method_id = request.POST.get("payment_method") # Last but not least we save the customer ... customer.save() return HttpResponse(cart_inline(request))
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)
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": shipping_inline(request), "payment": payment_inline(request, form), "cart": cart_inline(request), }) return HttpResponse(result, mimetype='application/json')
def changed_checkout(request): """ """ OnePageCheckoutForm = lfs.core.utils.import_symbol(ONE_PAGE_CHECKOUT_FORM) form = OnePageCheckoutForm() customer = customer_utils.get_or_create_customer(request) _save_customer(request, customer) _save_country(request, customer) result = json.dumps({ "shipping": shipping_inline(request), "payment": payment_inline(request, form), "cart": cart_inline(request), }) return HttpResponse(result, content_type='application/json')
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)
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)
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) cc = CountryCriterion.objects.create(content=self.ct1, operator=Criterion.IS_SELECTED) cc.value.add(self.ch) cc.value.add(self.us) self.ct2 = CustomerTax.objects.create(rate=10.0) cc = CountryCriterion.objects.create(content=self.ct2, operator=Criterion.IS_SELECTED) cc.value.add(self.ie)
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 = lfs.core.utils.get_default_shop(request) if shop.default_country is not None: country_code = shop.default_country.code return country_code
def one_page_checkout(request, checkout_form=OnePageCheckoutForm, template_name="lfs/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 = lfs.core.utils.get_default_shop() if request.user.is_anonymous() and \ shop.checkout_type == CHECKOUT_TYPE_AUTH: return HttpResponseRedirect(reverse("lfs_checkout_login")) customer = customer_utils.get_or_create_customer(request) if request.method == "POST": form = checkout_form(request.POST) if form.is_valid(): # Create or update invoice address if customer.selected_invoice_address is None: invoice_address = Address.objects.create( firstname=form.cleaned_data.get("invoice_firstname"), lastname=form.cleaned_data.get("invoice_lastname"), company_name=form.cleaned_data.get("invoice_company_name"), street=form.cleaned_data.get("invoice_street"), zip_code=form.cleaned_data.get("invoice_zip_code"), city=form.cleaned_data.get("invoice_city"), country_id=form.cleaned_data.get("invoice_country"), phone=form.cleaned_data.get("invoice_phone"), email=form.cleaned_data.get("invoice_email"), ) customer.selected_invoice_address = invoice_address else: selected_invoice_address = customer.selected_invoice_address selected_invoice_address.firstname = form.cleaned_data.get( "invoice_firstname") selected_invoice_address.lastname = form.cleaned_data.get( "invoice_lastname") selected_invoice_address.company_name = form.cleaned_data.get( "invoice_company_name") selected_invoice_address.street = form.cleaned_data.get( "invoice_street") selected_invoice_address.zip_code = form.cleaned_data.get( "invoice_zip_code") selected_invoice_address.city = form.cleaned_data.get( "invoice_city") selected_invoice_address.country_id = form.cleaned_data.get( "invoice_country") selected_invoice_address.phone = form.cleaned_data.get( "invoice_phone") selected_invoice_address.email = form.cleaned_data.get( "invoice_email") selected_invoice_address.save() # If the shipping address differs from invoice firstname we create # or update the shipping address. if not form.cleaned_data.get("no_shipping"): if customer.selected_shipping_address is None: shipping_address = Address.objects.create( firstname=form.cleaned_data.get("shipping_firstname"), lastname=form.cleaned_data.get("shipping_lastname"), company_name=form.cleaned_data.get( "shipping_company_name"), street=form.cleaned_data.get("shipping_street"), zip_code=form.cleaned_data.get("shipping_zip_code"), city=form.cleaned_data.get("shipping_city"), country_id=form.cleaned_data.get("shipping_country"), phone=form.cleaned_data.get("shipping_phone"), email=form.cleaned_data.get("shipping_email"), ) customer.selected_shipping_address = shipping_address else: selected_shipping_address = customer.selected_shipping_address selected_shipping_address.firstname = form.cleaned_data.get( "shipping_firstname") selected_shipping_address.lastname = form.cleaned_data.get( "shipping_lastname") selected_shipping_address.company_name = form.cleaned_data.get( "shipping_company_name") selected_shipping_address.street = form.cleaned_data.get( "shipping_street") selected_shipping_address.zip_code = form.cleaned_data.get( "shipping_zip_code") selected_shipping_address.city = form.cleaned_data.get( "shipping_city") selected_shipping_address.country_id = form.cleaned_data.get( "shipping_country") selected_shipping_address.phone = form.cleaned_data.get( "shipping_phone") selected_shipping_address.save() # Payment method customer.selected_payment_method_id = request.POST.get( "payment_method") # 1 = Direct Debit 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 = lfs.payment.utils.process_payment(request) payment_method = lfs.payment.utils.get_selected_payment_method( request) # Only if the payment is succesful we create the order out of the # cart. if result.get("success") == True: order = lfs.order.utils.add_order(request) # TODO: Get rid of these payment specific payment stuff. This # should be within payment utils. if payment_method.id == PAYPAL and settings.LFS_PAYPAL_REDIRECT: return HttpResponseRedirect(order.get_pay_link()) else: return HttpResponseRedirect(result.get("next-url")) else: if result.has_key("message"): form._errors[result.get("message-key")] = result.get( "message") else: # form is not valid # Create or update invoice address if customer.selected_invoice_address is None: invoice_address = Address.objects.create( firstname=form.data.get("invoice_firstname"), lastname=form.data.get("invoice_lastname"), company_name=form.data.get("invoice_company_name"), street=form.data.get("invoice_street"), zip_code=form.data.get("invoice_zip_code"), city=form.data.get("invoice_city"), country_id=form.data.get("invoice_country"), phone=form.data.get("invoice_phone"), email=form.data.get("invoice_email"), ) customer.selected_invoice_address = invoice_address else: selected_invoice_address = customer.selected_invoice_address selected_invoice_address.firstname = form.data.get( "invoice_firstname") selected_invoice_address.lastname = form.data.get( "invoice_lastname") selected_invoice_address.company_name = form.data.get( "invoice_company_name") selected_invoice_address.street = form.data.get( "invoice_street") selected_invoice_address.zip_code = form.data.get( "invoice_zip_code") selected_invoice_address.city = form.data.get("invoice_city") selected_invoice_address.country_id = form.data.get( "invoice_country") selected_invoice_address.phone = form.data.get("invoice_phone") selected_invoice_address.email = form.data.get("invoice_email") selected_invoice_address.save() # If the shipping address differs from invoice firstname we create # or update the shipping address. if not form.data.get("no_shipping"): if customer.selected_shipping_address is None: shipping_address = Address.objects.create( firstname=form.data.get("shipping_firstname"), lastname=form.data.get("shipping_lastname"), company_name=form.data.get("shipping_company_name"), street=form.data.get("shipping_street"), zip_code=form.data.get("shipping_zip_code"), city=form.data.get("shipping_city"), country_id=form.data.get("shipping_country"), phone=form.data.get("shipping_phone"), email=form.data.get("shipping_email"), ) customer.selected_shipping_address = shipping_address else: selected_shipping_address = customer.selected_shipping_address selected_shipping_address.firstname = form.data.get( "shipping_firstname") selected_shipping_address.lastname = form.data.get( "shipping_lastname") selected_shipping_address.company_name = form.data.get( "shipping_company_name") selected_shipping_address.street = form.data.get( "shipping_street") selected_shipping_address.zip_code = form.data.get( "shipping_zip_code") selected_shipping_address.city = form.data.get( "shipping_city") selected_shipping_address.country_id = form.data.get( "shipping_country") selected_shipping_address.phone = form.data.get( "shipping_phone") selected_shipping_address.save() # Payment method customer.selected_payment_method_id = request.POST.get( "payment_method") # 1 = Direct Debit if int(form.data.get("payment_method")) == 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 = {} if customer.selected_invoice_address is not None: invoice_address = customer.selected_invoice_address initial.update({ "invoice_firstname": invoice_address.firstname, "invoice_lastname": invoice_address.lastname, "invoice_street": invoice_address.street, "invoice_zip_code": invoice_address.zip_code, "invoice_city": invoice_address.city, "invoice_country": invoice_address.country_id, "invoice_phone": invoice_address.phone, "invoice_email": invoice_address.email, }) if customer.selected_shipping_address is not None: shipping_address = customer.selected_shipping_address initial.update({ "shipping_firstname": shipping_address.firstname, "shipping_lastname": shipping_address.lastname, "shipping_street": shipping_address.street, "shipping_zip_code": shipping_address.zip_code, "shipping_city": shipping_address.city, "shipping_phone": shipping_address.phone, "shipping_email": shipping_address.email, "no_shipping": False, }) # Set the addresses country to the current selected in any case. country = lfs.shipping.utils.get_selected_shipping_country(request) initial["shipping_country"] = country.id initial["invoice_country"] = country.id form = checkout_form(initial=initial) cart = cart_utils.get_cart(request) if cart is None: return HttpResponseRedirect(reverse('lfs_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 = lfs.payment.utils.get_selected_payment_method( request) valid_payment_methods = lfs.payment.utils.get_valid_payment_methods( request) valid_payment_method_ids = [m.id for m in valid_payment_methods] display_bank_account = DIRECT_DEBIT in valid_payment_method_ids display_credit_card = CREDIT_CARD in valid_payment_method_ids response = render_to_response( template_name, RequestContext( request, { "form": form, "cart_inline": cart_inline(request), "shipping_inline": shipping_inline(request), "payment_inline": payment_inline(request, form), "selected_payment_method": selected_payment_method, "display_bank_account": display_bank_account, "display_credit_card": display_credit_card, })) if form._errors: return lfs.core.utils.set_message_to(response, _(u"An error has been occured.")) else: return response
def refresh_cart(request): """ Refreshes the cart after some changes has been taken place, e.g.: the amount of a product or shipping/payment method. """ cart = cart_utils.get_cart(request) if not cart: raise Http404 customer = customer_utils.get_or_create_customer(request) # Update country country_iso = request.POST.get("country") if country_iso: selected_country = Country.objects.get(code=country_iso.lower()) customer.selected_country_id = selected_country.id if customer.selected_shipping_address: customer.selected_shipping_address.country = selected_country customer.selected_shipping_address.save() customer.selected_shipping_address.save() if customer.selected_invoice_address: customer.selected_invoice_address.country = selected_country customer.selected_invoice_address.save() customer.selected_invoice_address.save() # NOTE: The customer has to be saved already here in order to calculate # a possible new valid shippig method below, which coulb be triggered by # the changing of the shipping country. customer.save() # Update Amounts message = "" for item in cart.get_items(): amount = request.POST.get("amount-cart-item_%s" % item.id, "0.0") amount = item.product.get_clean_quantity_value(amount, allow_zero=True) if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time: amount = item.product.stock_amount if amount < 0: amount = 0 if amount == 0: message = _( u"Sorry, but '%(product)s' is not available anymore." % {"product": item.product.name}) elif amount == 1: message = _( u"Sorry, but '%(product)s' is only one time available." % {"product": item.product.name}) else: message = _( u"Sorry, but '%(product)s' is only %(amount)s times available." ) % { "product": item.product.name, "amount": amount } if item.product.get_active_packing_unit(): item.amount = item.product.get_amount_by_packages(float(amount)) else: item.amount = amount if amount == 0: item.delete() else: item.save() # IMPORTANT: We have to send the signal already here, because the valid # shipping methods might be dependent on the price. cart_changed.send(cart, request=request) # Update shipping method shipping_method = get_object_or_404(ShippingMethod, pk=request.POST.get("shipping_method")) customer.selected_shipping_method = shipping_method valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request) if customer.selected_shipping_method not in valid_shipping_methods: customer.selected_shipping_method = shipping_utils.get_default_shipping_method( request) # Update payment method payment_method = get_object_or_404(PaymentMethod, pk=request.POST.get("payment_method")) customer.selected_payment_method = payment_method # Last but not least we save the customer ... customer.save() result = json.dumps({ "html": cart_inline(request), "message": message, }, cls=LazyEncoder) return HttpResponse(result, content_type='application/json')
def add_to_cart(request, product_id=None): """ Adds the passed product with passed product_id to the cart after some validations have been taken place. The amount is taken from the query string. """ if product_id is None: product_id = request.REQUEST.get("product_id") product = lfs_get_object_or_404(Product, pk=product_id) # Only active and deliverable products can be added to the cart. if not (product.is_active() and product.is_deliverable()): raise Http404() quantity = request.POST.get("quantity", "1.0") quantity = product.get_clean_quantity_value(quantity) # Validate properties (They are added below) properties_dict = {} if product.is_configurable_product(): for key, value in request.POST.items(): if key.startswith("property-"): try: property_group_id, property_id = key.split("-")[1:] except IndexError: continue try: prop = Property.objects.get(pk=property_id) except Property.DoesNotExist: continue property_group = None if property_group_id != '0': try: property_group = PropertyGroup.objects.get( pk=property_group_id) except PropertyGroup.DoesNotExist: continue if prop.is_number_field: try: value = lfs.core.utils.atof(value) except ValueError: value = 0.0 key = '{0}_{1}'.format(property_group_id, property_id) properties_dict[key] = { 'value': unicode(value), 'property_group_id': property_group_id, 'property_id': property_id } # validate property's value if prop.is_number_field: if (value < prop.unit_min) or (value > prop.unit_max): msg = _( u"%(name)s must be between %(min)s and %(max)s %(unit)s." ) % { "name": prop.title, "min": prop.unit_min, "max": prop.unit_max, "unit": prop.unit } return lfs.core.utils.set_message_cookie( product.get_absolute_url(), msg) # calculate valid steps steps = [] x = prop.unit_min while x < prop.unit_max: steps.append("%.2f" % x) x += prop.unit_step steps.append("%.2f" % prop.unit_max) value = "%.2f" % value if value not in steps: msg = _( u"Your entered value for %(name)s (%(value)s) is not in valid step width, which is %(step)s." ) % { "name": prop.title, "value": value, "step": prop.unit_step } return lfs.core.utils.set_message_cookie( product.get_absolute_url(), msg) if product.get_active_packing_unit(): quantity = product.get_amount_by_packages(quantity) cart = cart_utils.get_or_create_cart(request) cart_item = cart.add(product, properties_dict, quantity) cart_items = [cart_item] # Check stock amount message = "" if product.manage_stock_amount and cart_item.amount > product.stock_amount and not product.order_time: if product.stock_amount == 0: message = _( u"Sorry, but '%(product)s' is not available anymore.") % { "product": product.name } elif product.stock_amount == 1: message = _( u"Sorry, but '%(product)s' is only one time available.") % { "product": product.name } else: message = _( u"Sorry, but '%(product)s' is only %(amount)s times available." ) % { "product": product.name, "amount": product.stock_amount } cart_item.amount = product.stock_amount cart_item.save() # Add selected accessories to cart for key, value in request.POST.items(): if key.startswith("accessory"): accessory_id = key.split("-")[1] try: accessory = Product.objects.get(pk=accessory_id) except ObjectDoesNotExist: continue # for product with variants add default variant if accessory.is_product_with_variants(): accessory_variant = accessory.get_default_variant() if accessory_variant: accessory = accessory_variant else: continue # Get quantity quantity = request.POST.get("quantity-%s" % accessory_id, 0) quantity = accessory.get_clean_quantity_value(quantity) cart_item = cart.add(product=accessory, amount=quantity) cart_items.append(cart_item) # Store cart items for retrieval within added_to_cart. request.session["cart_items"] = cart_items cart_changed.send(cart, request=request) # Update the customer's shipping method (if appropriate) customer = customer_utils.get_or_create_customer(request) shipping_utils.update_to_valid_shipping_method(request, customer, save=True) # Update the customer's payment method (if appropriate) payment_utils.update_to_valid_payment_method(request, customer, save=True) # Save the cart to update modification date cart.save() try: url_name = settings.LFS_AFTER_ADD_TO_CART except AttributeError: url_name = "lfs_added_to_cart" if message: return lfs.core.utils.set_message_cookie(reverse(url_name), message) else: return HttpResponseRedirect(reverse(url_name))
def login(request, template_name="lfs/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 = lfs.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() login_form = CustomerAuthenticationForm() login_form.fields["username"].label = _(u"E-Mail") RegisterForm = lfs.core.utils.import_symbol(REGISTER_FORM) register_form = RegisterForm() if request.POST.get("action") == "login": login_form = CustomerAuthenticationForm(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("lfs_shop_view") from django.contrib.auth import login login(request, login_form.get_user()) return lfs.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(): # !!!SPLICE: register_form is a form that gets validated after # submission. Data retrieval should be from # cleaned_data so that values are tagged as trusted # email = register_form.data.get("email") # password = register_form.data.get("password_1") email = register_form.cleaned_data.get("email") password = register_form.cleaned_data.get("password_1") # Create user user = User.objects.create_user( username=create_unique_username(email), email=email, password=password) # !!!SPLICE: Update user's taint here and save again. # We have to have a separate step here # because during registration, user.id has # not yet been established. As such, user # will never get tainted unless we set it here. set_current_user_id(user.pk) # UNCOMMENT FOR ROW-LEVEL TAINT # user.taints = to_int(TaintSource.current_user_taint) # CELL-LEVEL TAINT user.username_taint = to_int(TaintSource.current_user_taint) user.email_taint = to_int(TaintSource.current_user_taint) user.password_taint = to_int(TaintSource.current_user_taint) user.save() # Create customer customer = customer_utils.get_or_create_customer(request) customer.user = user customer.save() # Notify lfs.core.signals.customer_added.send(sender=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, backend='lfs.customer.auth.EmailBackend') redirect_to = request.POST.get("next") if not redirect_to or '//' in redirect_to or ' ' in redirect_to: redirect_to = reverse("lfs_shop_view") return lfs.core.utils.set_message_cookie( redirect_to, msg=_(u"You have been registered and logged in.")) # Get next_url next_url = (request.POST if request.method == 'POST' else request.GET).get("next") if next_url is None: next_url = request.META.get("HTTP_REFERER") if next_url is None: next_url = reverse("lfs_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( request, template_name, { "login_form": login_form, "login_form_errors": login_form_errors, "register_form": register_form, "next_url": next_url, })
def refresh_cart(request): """ Refreshes the cart after some changes has been taken place, e.g.: the amount of a product or shipping/payment method. """ cart = cart_utils.get_cart(request) if not cart: raise Http404 customer = customer_utils.get_or_create_customer(request) # Update country country_iso = request.POST.get("country") if country_iso: selected_country = Country.objects.get(code=country_iso.lower()) customer.selected_country_id = selected_country.id if customer.selected_shipping_address: customer.selected_shipping_address.country = selected_country customer.selected_shipping_address.save() customer.selected_shipping_address.save() if customer.selected_invoice_address: customer.selected_invoice_address.country = selected_country customer.selected_invoice_address.save() customer.selected_invoice_address.save() # NOTE: The customer has to be saved already here in order to calculate # a possible new valid shippig method below, which coulb be triggered by # the changing of the shipping country. customer.save() # Update Amounts message = "" for item in cart.get_items(): amount = request.POST.get("amount-cart-item_%s" % item.id, "0.0") amount = item.product.get_clean_quantity_value(amount, allow_zero=True) if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time: amount = item.product.stock_amount if amount < 0: amount = 0 if amount == 0: message = _(u"Sorry, but '%(product)s' is not available anymore." % {"product": item.product.name}) elif amount == 1: message = _(u"Sorry, but '%(product)s' is only one time available." % {"product": item.product.name}) else: message = _(u"Sorry, but '%(product)s' is only %(amount)s times available.") % { "product": item.product.name, "amount": amount, } if item.product.get_active_packing_unit(): item.amount = item.product.get_amount_by_packages(float(amount)) else: item.amount = amount if amount == 0: item.delete() else: item.save() # IMPORTANT: We have to send the signal already here, because the valid # shipping methods might be dependent on the price. cart_changed.send(cart, request=request) # Update shipping method shipping_method = get_object_or_404(ShippingMethod, pk=request.POST.get("shipping_method")) customer.selected_shipping_method = shipping_method valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request) if customer.selected_shipping_method not in valid_shipping_methods: customer.selected_shipping_method = shipping_utils.get_default_shipping_method(request) # Update payment method payment_method = get_object_or_404(PaymentMethod, pk=request.POST.get("payment_method")) customer.selected_payment_method = payment_method # Last but not least we save the customer ... customer.save() result = json.dumps({"html": cart_inline(request), "message": message}, cls=LazyEncoder) return HttpResponse(result, content_type="application/json")
def add_to_cart(request, product_id=None): """ Adds the passed product with passed product_id to the cart after some validations have been taken place. The amount is taken from the query string. """ if product_id is None: product_id = request.REQUEST.get("product_id") product = lfs_get_object_or_404(Product, pk=product_id) # Only active and deliverable products can be added to the cart. if not (product.is_active() and product.is_deliverable()): raise Http404() quantity = request.POST.get("quantity", "1.0") quantity = product.get_clean_quantity_value(quantity) # Validate properties (They are added below) properties_dict = {} if product.is_configurable_product(): for key, value in request.POST.items(): if key.startswith("property-"): try: property_id = key.split("-")[1] except IndexError: continue try: prop = Property.objects.get(pk=property_id) except Property.DoesNotExist: continue if prop.is_number_field: try: value = lfs.core.utils.atof(value) except ValueError: value = 0.0 properties_dict[property_id] = unicode(value) # validate property's value if prop.is_number_field: if (value < prop.unit_min) or (value > prop.unit_max): msg = _(u"%(name)s must be between %(min)s and %(max)s %(unit)s.") % { "name": prop.title, "min": prop.unit_min, "max": prop.unit_max, "unit": prop.unit, } return lfs.core.utils.set_message_cookie(product.get_absolute_url(), msg) # calculate valid steps steps = [] x = prop.unit_min while x < prop.unit_max: steps.append("%.2f" % x) x += prop.unit_step steps.append("%.2f" % prop.unit_max) value = "%.2f" % value if value not in steps: msg = _( u"Your entered value for %(name)s (%(value)s) is not in valid step width, which is %(step)s." ) % {"name": prop.title, "value": value, "step": prop.unit_step} return lfs.core.utils.set_message_cookie(product.get_absolute_url(), msg) if product.get_active_packing_unit(): quantity = product.get_amount_by_packages(quantity) cart = cart_utils.get_or_create_cart(request) cart_item = cart.add(product, properties_dict, quantity) cart_items = [cart_item] # Check stock amount message = "" if product.manage_stock_amount and cart_item.amount > product.stock_amount and not product.order_time: if product.stock_amount == 0: message = _(u"Sorry, but '%(product)s' is not available anymore.") % {"product": product.name} elif product.stock_amount == 1: message = _(u"Sorry, but '%(product)s' is only one time available.") % {"product": product.name} else: message = _(u"Sorry, but '%(product)s' is only %(amount)s times available.") % { "product": product.name, "amount": product.stock_amount, } cart_item.amount = product.stock_amount cart_item.save() # Add selected accessories to cart for key, value in request.POST.items(): if key.startswith("accessory"): accessory_id = key.split("-")[1] try: accessory = Product.objects.get(pk=accessory_id) except ObjectDoesNotExist: continue # for product with variants add default variant if accessory.is_product_with_variants(): accessory_variant = accessory.get_default_variant() if accessory_variant: accessory = accessory_variant else: continue # Get quantity quantity = request.POST.get("quantity-%s" % accessory_id, 0) quantity = accessory.get_clean_quantity_value(quantity) cart_item = cart.add(product=accessory, amount=quantity) cart_items.append(cart_item) # Store cart items for retrieval within added_to_cart. request.session["cart_items"] = cart_items cart_changed.send(cart, request=request) # Update the customer's shipping method (if appropriate) customer = customer_utils.get_or_create_customer(request) shipping_utils.update_to_valid_shipping_method(request, customer, save=True) # Update the customer's payment method (if appropriate) payment_utils.update_to_valid_payment_method(request, customer, save=True) # Save the cart to update modification date cart.save() try: url_name = settings.LFS_AFTER_ADD_TO_CART except AttributeError: url_name = "lfs_added_to_cart" if message: return lfs.core.utils.set_message_cookie(reverse(url_name), message) else: return HttpResponseRedirect(reverse(url_name))
def one_page_checkout(request, checkout_form=OnePageCheckoutForm, template_name="lfs/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 = lfs.core.utils.get_default_shop(request) if request.user.is_anonymous() and \ shop.checkout_type == CHECKOUT_TYPE_AUTH: return HttpResponseRedirect(reverse("lfs_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") if toc and form.is_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") # 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") 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 = lfs.payment.utils.process_payment(request) next_url = None if result["accepted"] == True: return HttpResponseRedirect( result.get("next-url", reverse("lfs_thank_you"))) else: if "message" in result: form._errors[result.get("message-position")] = 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") # Create or update invoice address save_address(request, customer, INVOICE_PREFIX) # 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.save() save_address(request, customer, SHIPPING_PREFIX) # 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, }) 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, "no_shipping": False, }) form = checkout_form(initial=initial) cart = cart_utils.get_cart(request) if cart is None: return HttpResponseRedirect(reverse('lfs_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 = lfs.payment.utils.get_selected_payment_method(request) valid_payment_methods = lfs.payment.utils.get_valid_payment_methods(request) valid_payment_method_ids = [m.id for m in valid_payment_methods] display_bank_account = DIRECT_DEBIT in valid_payment_method_ids display_credit_card = CREDIT_CARD in valid_payment_method_ids 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": lfs.voucher.utils.get_current_voucher_number(request), })) return response
def refresh_cart(request): """ Refreshes the cart after some changes has been taken place, e.g.: the amount of a product or shipping/payment method. """ cart = cart_utils.get_cart(request) customer = customer_utils.get_or_create_customer(request) # Update country country_iso = request.POST.get("country") if country_iso: selected_country = Country.objects.get(code=country_iso.lower()) customer.selected_country_id = selected_country.id if customer.selected_shipping_address: customer.selected_shipping_address.country = selected_country customer.selected_shipping_address.save() customer.selected_shipping_address.save() if customer.selected_invoice_address: customer.selected_invoice_address.country = selected_country customer.selected_invoice_address.save() customer.selected_invoice_address.save() # NOTE: The customer has to be saved already here in order to calculate # a possible new valid shippig method below, which coulb be triggered by # the changing of the shipping country. customer.save() # Update Amounts message = "" for item in cart.get_items(): try: value = request.POST.get("amount-cart-item_%s" % item.id, "0.0") if isinstance(value, unicode): # atof() on unicode string fails in some environments, like Czech value = value.encode("utf-8") amount = locale.atof(value) except (TypeError, ValueError): amount = 1.0 if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time: amount = item.product.stock_amount if amount < 0: amount = 0 if amount == 0: message = _(u"Sorry, but '%(product)s' is not available anymore." % {"product": item.product.name}) elif amount == 1: message = _(u"Sorry, but '%(product)s' is only one time available." % {"product": item.product.name}) else: message = _(u"Sorry, but '%(product)s' is only %(amount)s times available.") % {"product": item.product.name, "amount": amount} if item.product.active_packing_unit: item.amount = item.product.get_amount_by_packages(float(amount)) else: item.amount = amount if amount == 0: item.delete() else: item.save() # IMPORTANT: We have to send the signal already here, because the valid # shipping methods might be dependent on the price. cart_changed.send(cart, request=request) # Update shipping method customer.selected_shipping_method_id = request.POST.get("shipping_method") valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request) if customer.selected_shipping_method not in valid_shipping_methods: customer.selected_shipping_method = shipping_utils.get_default_shipping_method(request) # Update payment method customer.selected_payment_method_id = request.POST.get("payment_method") # Last but not least we save the customer ... customer.save() result = simplejson.dumps({ "html": cart_inline(request), "message": message, }, cls=LazyEncoder) return HttpResponse(result)
def login(request, template_name="lfs/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 = lfs.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() login_form = CustomerAuthenticationForm() login_form.fields["username"].label = _(u"E-Mail") RegisterForm = lfs.core.utils.import_symbol(REGISTER_FORM) register_form = RegisterForm() if request.POST.get("action") == "login": login_form = CustomerAuthenticationForm(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("lfs_shop_view") from django.contrib.auth import login login(request, login_form.get_user()) return lfs.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=create_unique_username(email), email=email, password=password) # Create customer customer = customer_utils.get_or_create_customer(request) customer.user = user customer.save() # Notify lfs.core.signals.customer_added.send(sender=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, backend='lfs.customer.auth.EmailBackend') redirect_to = request.POST.get("next") if not redirect_to or '//' in redirect_to or ' ' in redirect_to: redirect_to = reverse("lfs_shop_view") return lfs.core.utils.set_message_cookie( redirect_to, msg=_(u"You have been registered and logged in.")) # Get next_url next_url = (request.POST if request.method == 'POST' else request.GET).get("next") if next_url is None: next_url = request.META.get("HTTP_REFERER") if next_url is None: next_url = reverse("lfs_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(request, template_name, { "login_form": login_form, "login_form_errors": login_form_errors, "register_form": register_form, "next_url": next_url, })
def login(request, template_name="lfs/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 = lfs.core.utils.get_default_shop(request) try: print "%s" % request.user.username print "%s" % request.user.first_name print "%s" % request.user.is_authenticated() except: pass # 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 = "" login_form.fields["password"].label ="" register_form = RegisterForm() if request.POST.get("action") == "login": login_form = AuthenticationForm(data=request.POST) login_form.fields["username"].label ="" login_form.fields["password"].label = "" 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("lfs_shop_view") from django.contrib.auth import login login(request, login_form.get_user()) return lfs.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 lfs.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("lfs_shop_view") return lfs.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("lfs_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 supported = True try: browser = request.META['HTTP_USER_AGENT'] if ((browser.find("MSIE 8") != -1) or (browser.find("MSIE 7") != -1)): supported = False except: supported = False rs = 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, "supported": supported })) mm = ['POST','GET','OPTIONS', 'PUT', 'DELETE'] rs['Access-Control-Allow-Origin'] = 'http://ez3d_statics2.s3.amazonaws.com/' rs['Access-Control-Allow-Methods'] = ",".join( mm) print "gggggggggggg" return rs
def add_to_cart(request, product_id=None): """ Adds the passed product with passed product_id to the cart after some validations have been taken place. The amount is taken from the query string. """ if product_id is None: product_id = request.REQUEST.get("product_id") product = lfs_get_object_or_404(Product, pk=product_id) # Only active and deliverable products can be added to the cart. if not (product.is_active() and product.is_deliverable()): cart = cart_utils.get_or_create_cart(request) total_quantidade = 0 total_valor = 0 for cart_item in cart.get_items(): product = cart_item.product quantidade = str(product.get_clean_quantity(cart_item.amount)) quantidade = quantidade.replace(",", ".") quantidade = float(quantidade) total_quantidade += quantidade total_valor += float(cart_item.get_price_net(request)) if total_quantidade < 2: total_quantidade = str(total_quantidade) + '0 Item' else: total_quantidade = str(total_quantidade) + '0 Itens' total_valor = "R$ " + str(total_valor) total_valor = total_valor.replace(".", ",") total_quantidade = total_quantidade.replace(".", ",") ####################################### try: url_name = settings.LFS_AFTER_ADD_TO_CART except AttributeError: url_name = "lfs_added_to_cart" result = json.dumps( { "message": "Desculpa produto sem estoque.", "cor": "vermelho", "quantidade": str(total_quantidade), "total-cart": str(total_valor) }, cls=LazyEncoder) return HttpResponse(result, content_type='application/json') quantity = request.REQUEST.get("quantity") quantity = product.get_clean_quantity_value(quantity) # Validate properties (They are added below) properties_dict = {} if product.is_configurable_product(): for key, value in request.POST.items(): if key.startswith("property-"): try: property_group_id, property_id = key.split("-")[1:] except IndexError: continue try: prop = Property.objects.get(pk=property_id) except Property.DoesNotExist: continue property_group = None if property_group_id != '0': try: property_group = PropertyGroup.objects.get( pk=property_group_id) except PropertyGroup.DoesNotExist: continue if prop.is_number_field: try: value = lfs.core.utils.atof(value) except ValueError: value = 0.0 key = '{0}_{1}'.format(property_group_id, property_id) properties_dict[key] = { 'value': unicode(value), 'property_group_id': property_group_id, 'property_id': property_id } # validate property's value if prop.is_number_field: if (value < prop.unit_min) or (value > prop.unit_max): msg = _( u"%(name)s must be between %(min)s and %(max)s %(unit)s." ) % { "name": prop.title, "min": prop.unit_min, "max": prop.unit_max, "unit": prop.unit } return lfs.core.utils.set_message_cookie( product.get_absolute_url(), msg) # calculate valid steps steps = [] x = prop.unit_min while x < prop.unit_max: steps.append("%.2f" % x) x += prop.unit_step steps.append("%.2f" % prop.unit_max) value = "%.2f" % value if value not in steps: msg = _( u"Your entered value for %(name)s (%(value)s) is not in valid step width, which is %(step)s." ) % { "name": prop.title, "value": value, "step": prop.unit_step } return lfs.core.utils.set_message_cookie( product.get_absolute_url(), msg) if product.get_active_packing_unit(): quantity = product.get_amount_by_packages(quantity) cart = cart_utils.get_or_create_cart(request) cart_item = cart.add(product, properties_dict, quantity) cart_items = [cart_item] # Check stock amount message = _(u"%(quantidade)s %(product)s ADICIONADO") % { "product": product.name, "quantidade": quantity } cor = "verde" if product.manage_stock_amount and cart_item.amount > product.stock_amount and not product.order_time: if product.stock_amount == 0: message = _( u"Sorry, but '%(product)s' is not available anymore.") % { "product": product.name } cor = "vermelho" elif product.stock_amount == 1: message = _( u"Sorry, but '%(product)s' is only one time available.") % { "product": product.name } cor = "amarelo" else: message = _( u"Sorry, but '%(product)s' is only %(amount)s times available." ) % { "product": product.name, "amount": product.stock_amount } cor = "amarelo" cart_item.amount = product.stock_amount cart_item.save() # Add selected accessories to cart for key, value in request.POST.items(): if key.startswith("accessory"): accessory_id = key.split("-")[1] try: accessory = Product.objects.get(pk=accessory_id) except ObjectDoesNotExist: continue # for product with variants add default variant if accessory.is_product_with_variants(): accessory_variant = accessory.get_default_variant() if accessory_variant: accessory = accessory_variant else: continue # Get quantity quantity = request.POST.get("quantity-%s" % accessory_id, 0) quantity = accessory.get_clean_quantity_value(quantity) cart_item = cart.add(product=accessory, amount=quantity) cart_items.append(cart_item) # Store cart items for retrieval within added_to_cart. request.session["cart_items"] = cart_items cart_changed.send(cart, request=request) # Update the customer's shipping method (if appropriate) customer = customer_utils.get_or_create_customer(request) shipping_utils.update_to_valid_shipping_method(request, customer, save=True) # Update the customer's payment method (if appropriate) payment_utils.update_to_valid_payment_method(request, customer, save=True) # Save the cart to update modification date cart.save() ####################################### try: url_name = settings.LFS_AFTER_ADD_TO_CART except AttributeError: url_name = "lfs_added_to_cart" # Calcular totalizadores do carrinho total_quantidade = 0 total_valor = 0 for cart_item in cart.get_items(): product = cart_item.product quantidade = str(product.get_clean_quantity(cart_item.amount)) quantidade = quantidade.replace(",", ".") quantidade = float(quantidade) total_quantidade += quantidade total_valor += float(cart_item.get_price_net(request)) price = str(total_valor) if price == '0': decimal = '0' centavos = '00' else: virgula = price.find('.') decimal = price[:virgula] centavos = price[virgula:] for a in [',', '.']: decimal = decimal.replace(a, '') centavos = centavos.replace(a, '') result = json.dumps( { "html": cart_inline(request), "message": message, "cor": cor, "quantidade": str(total_quantidade), "decimal": decimal, "centavos": centavos[:2], }, cls=LazyEncoder) return HttpResponse(result, content_type='application/json')
def refresh_cart(request): """ Refreshes the cart after some changes has been taken place, e.g.: the amount of a product or shipping/payment method. """ cart = cart_utils.get_cart(request) if not cart: raise Http404 customer = customer_utils.get_or_create_customer(request) # Update country country_iso = request.POST.get("country") if country_iso: selected_country = Country.objects.get(code=country_iso.lower()) customer.selected_country_id = selected_country.id if customer.selected_shipping_address: customer.selected_shipping_address.country = selected_country customer.selected_shipping_address.save() customer.selected_shipping_address.save() if customer.selected_invoice_address: customer.selected_invoice_address.country = selected_country customer.selected_invoice_address.save() customer.selected_invoice_address.save() # NOTE: The customer has to be saved already here in order to calculate # a possible new valid shippig method below, which coulb be triggered by # the changing of the shipping country. customer.save() # Update Amounts message = '' cor = '' for item in cart.get_items(): amount = request.POST.get("amount-cart-item_%s" % item.id, "0.0") amount = item.product.get_clean_quantity_value(amount, allow_zero=True) if message == '': message = _(u"%(product)s ATUALIZADO") % {"product": 'PRODUTO'} cor = "verde" if item.product.manage_stock_amount and amount > item.product.stock_amount and not item.product.order_time: amount = item.product.stock_amount message = _(u"%(product)s ATUALIZADO") % {"product": 'PRODUTO'} cor = "verde" if amount < 0: amount = 0 message = _(u"%(product)s EXCLUIDO") % {"product": 'PRODUTO'} cor = "vermelho" if amount == 0: message = _( u"Sorry, but '%(product)s' is not available anymore.") % { "product": 'PRODUTO', "amount": amount } cor = "vermelho" elif amount == 1: message = _( u"Sorry, but '%(product)s' is only one time available." ) % { "product": 'PRODUTO', "amount": amount } cor = "amarelo" else: message = _( u"Sorry, but '%(product)s' is only %(amount)s times available." ) % { "product": 'PRODUTO', "amount": amount } cor = "amarelo" if item.product.get_active_packing_unit(): item.amount = item.product.get_amount_by_packages(float(amount)) else: item.amount = amount if amount == 0: message = _(u"%(product)s EXCLUIDO") % {"product": 'PRODUTO'} cor = "vermelho" item.delete() else: item.save() # IMPORTANT: We have to send the signal already here, because the valid # shipping methods might be dependent on the price. cart_changed.send(cart, request=request) # Update shipping method shipping_method = get_object_or_404(ShippingMethod, pk=request.POST.get("shipping_method")) customer.selected_shipping_method = shipping_method valid_shipping_methods = shipping_utils.get_valid_shipping_methods(request) if customer.selected_shipping_method not in valid_shipping_methods: customer.selected_shipping_method = shipping_utils.get_default_shipping_method( request) # Update payment method payment_method = get_object_or_404(PaymentMethod, pk=request.POST.get("payment_method")) customer.selected_payment_method = payment_method # Last but not least we save the customer ... customer.save() total_quantidade = 0 total_valor = 0 for cart_item in cart.get_items(): product = cart_item.product quantidade = str(product.get_clean_quantity(cart_item.amount)) quantidade = quantidade.replace(",", ".") quantidade = float(quantidade) total_quantidade += quantidade total_valor += float(cart_item.get_price_net(request)) price = str(total_valor) if price == '0': decimal = '0' centavos = '00' else: virgula = price.find('.') decimal = price[:virgula] centavos = price[virgula:] for a in [',', '.']: decimal = decimal.replace(a, '') centavos = centavos.replace(a, '') result = json.dumps( { "html": cart_inline(request), "message": message, "cor": cor, "quantidade": str(total_quantidade), "decimal": decimal, "centavos": centavos[:2], }, cls=LazyEncoder) return HttpResponse(result, content_type='application/json')
def add_to_cart(request, product_id=None): """Adds the amount of the product with given id to the cart. If the product is already within the cart the amount is increased. """ if product_id is None: product_id = request.REQUEST.get("product_id") product = lfs_get_object_or_404(Product, pk=product_id) # Only active and deliverable products can be added to the cart. if (product.is_active() and product.is_deliverable()) == False: raise Http404() if product.sub_type == PRODUCT_WITH_VARIANTS: variant_id = request.POST.get("variant_id") product = lfs_get_object_or_404(Product, pk=variant_id) try: quantity = float(request.POST.get("quantity", 1)) except TypeError: quantity = 1 cart = cart_utils.get_or_create_cart(request) try: cart_item = CartItem.objects.get(cart = cart, product = product) except ObjectDoesNotExist: cart_item = CartItem(cart=cart, product=product, amount=quantity) cart_item.save() else: cart_item.amount += quantity cart_item.save() cart_items = [cart_item] # Add selected accessories to cart for key, value in request.POST.items(): if key.startswith("accessory"): accessory_id = key.split("-")[1] try: accessory = Product.objects.get(pk=accessory_id) except ObjectDoesNotExist: continue # Get quantity quantity = request.POST.get("quantity-%s" % accessory_id, 0) try: quantity = float(quantity) except TypeError: quantity = 1 try: cart_item = CartItem.objects.get(cart = cart, product = accessory) except ObjectDoesNotExist: cart_item = CartItem(cart=cart, product = accessory, amount=quantity) cart_item.save() else: cart_item.amount += quantity cart_item.save() cart_items.append(cart_item) # Store cart items for retrieval within added_to_cart. request.session["cart_items"] = cart_items cart_changed.send(cart, request=request) # Update the customer's shipping method (if appropriate) customer = customer_utils.get_or_create_customer(request) shipping_utils.update_to_valid_shipping_method(request, customer, save=True) # Update the customer's shipping method (if appropriate) payment_utils.update_to_valid_payment_method(request, customer, save=True) # Save the cart to update modification date cart.save() url = reverse("lfs.cart.views.added_to_cart") return HttpResponseRedirect(url)
def add_to_cart(request, product_id=None): """Adds the amount of the product with given id to the cart. If the product is already within the cart the amount is increased. """ if product_id is None: product_id = request.REQUEST.get("product_id") product = lfs_get_object_or_404(Product, pk=product_id) # Only active and deliverable products can be added to the cart. if (product.is_active() and product.is_deliverable()) == False: raise Http404() if product.sub_type == PRODUCT_WITH_VARIANTS: variant_id = request.POST.get("variant_id") product = lfs_get_object_or_404(Product, pk=variant_id) try: quantity = float(request.POST.get("quantity", 1)) except TypeError: quantity = 1 cart = cart_utils.get_or_create_cart(request) try: cart_item = CartItem.objects.get(cart=cart, product=product) except ObjectDoesNotExist: cart_item = CartItem(cart=cart, product=product, amount=quantity) cart_item.save() else: cart_item.amount += quantity cart_item.save() cart_items = [cart_item] # Add selected accessories to cart for key, value in request.POST.items(): if key.startswith("accessory"): accessory_id = key.split("-")[1] try: accessory = Product.objects.get(pk=accessory_id) except ObjectDoesNotExist: continue # Get quantity quantity = request.POST.get("quantity-%s" % accessory_id, 0) try: quantity = float(quantity) except TypeError: quantity = 1 try: cart_item = CartItem.objects.get(cart=cart, product=accessory) except ObjectDoesNotExist: cart_item = CartItem(cart=cart, product=accessory, amount=quantity) cart_item.save() else: cart_item.amount += quantity cart_item.save() cart_items.append(cart_item) # Store cart items for retrieval within added_to_cart. request.session["cart_items"] = cart_items cart_changed.send(cart, request=request) # Update the customer's shipping method (if appropriate) customer = customer_utils.get_or_create_customer(request) shipping_utils.update_to_valid_shipping_method(request, customer, save=True) # Update the customer's shipping method (if appropriate) payment_utils.update_to_valid_payment_method(request, customer, save=True) # Save the cart to update modification date cart.save() url = reverse("lfs.cart.views.added_to_cart") return HttpResponseRedirect(url)
def login(request, template_name="lfs/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 = lfs.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() login_form = CustomerAuthenticationForm() login_form.fields["username"].label = _(u"E-Mail") register_form = RegisterForm() if request.POST.get("action") == "login": login_form = CustomerAuthenticationForm(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("lfs_shop_view") from django.contrib.auth import login login(request, login_form.get_user()) return lfs.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=create_unique_username(email), email=email, password=password) # Create customer customer = customer_utils.get_or_create_customer(request) customer.user = user # Notify lfs.core.signals.customer_added.send(sender=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("lfs_shop_view") return lfs.core.utils.set_message_cookie(redirect_to, msg=_(u"You have been registered and logged in.")) # Get next_url next_url = (request.POST if request.method == "POST" else request.GET).get("next") if next_url is None: next_url = request.META.get("HTTP_REFERER") if next_url is None: next_url = reverse("lfs_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, }, ), )
def one_page_checkout(request, checkout_form = OnePageCheckoutForm, template_name="lfs/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 = lfs.core.utils.get_default_shop() if request.user.is_anonymous() and \ shop.checkout_type == CHECKOUT_TYPE_AUTH: return HttpResponseRedirect(reverse("lfs_checkout_login")) customer = customer_utils.get_or_create_customer(request) if request.method == "POST": form = checkout_form(request.POST) if form.is_valid(): # Create or update invoice address if customer.selected_invoice_address is None: invoice_address = Address.objects.create( firstname = form.cleaned_data.get("invoice_firstname"), lastname = form.cleaned_data.get("invoice_lastname"), company_name = form.cleaned_data.get("invoice_company_name"), street = form.cleaned_data.get("invoice_street"), zip_code = form.cleaned_data.get("invoice_zip_code"), city = form.cleaned_data.get("invoice_city"), country_id = form.cleaned_data.get("invoice_country"), phone = form.cleaned_data.get("invoice_phone"), email = form.cleaned_data.get("invoice_email"), ) customer.selected_invoice_address = invoice_address else: selected_invoice_address = customer.selected_invoice_address selected_invoice_address.firstname = form.cleaned_data.get("invoice_firstname") selected_invoice_address.lastname = form.cleaned_data.get("invoice_lastname") selected_invoice_address.company_name = form.cleaned_data.get("invoice_company_name") selected_invoice_address.street = form.cleaned_data.get("invoice_street") selected_invoice_address.zip_code = form.cleaned_data.get("invoice_zip_code") selected_invoice_address.city = form.cleaned_data.get("invoice_city") selected_invoice_address.country_id = form.cleaned_data.get("invoice_country") selected_invoice_address.phone = form.cleaned_data.get("invoice_phone") selected_invoice_address.email = form.cleaned_data.get("invoice_email") selected_invoice_address.save() # If the shipping address differs from invoice firstname we create # or update the shipping address. if not form.cleaned_data.get("no_shipping"): if customer.selected_shipping_address is None: shipping_address = Address.objects.create( firstname = form.cleaned_data.get("shipping_firstname"), lastname = form.cleaned_data.get("shipping_lastname"), company_name = form.cleaned_data.get("shipping_company_name"), street = form.cleaned_data.get("shipping_street"), zip_code = form.cleaned_data.get("shipping_zip_code"), city = form.cleaned_data.get("shipping_city"), country_id = form.cleaned_data.get("shipping_country"), phone = form.cleaned_data.get("shipping_phone"), email = form.cleaned_data.get("shipping_email"), ) customer.selected_shipping_address = shipping_address else: selected_shipping_address = customer.selected_shipping_address selected_shipping_address.firstname = form.cleaned_data.get("shipping_firstname") selected_shipping_address.lastname = form.cleaned_data.get("shipping_lastname") selected_shipping_address.company_name = form.cleaned_data.get("shipping_company_name") selected_shipping_address.street = form.cleaned_data.get("shipping_street") selected_shipping_address.zip_code = form.cleaned_data.get("shipping_zip_code") selected_shipping_address.city = form.cleaned_data.get("shipping_city") selected_shipping_address.country_id = form.cleaned_data.get("shipping_country") selected_shipping_address.phone = form.cleaned_data.get("shipping_phone") selected_shipping_address.save() # Payment method customer.selected_payment_method_id = request.POST.get("payment_method") # 1 = Direct Debit 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 = lfs.payment.utils.process_payment(request) payment_method = lfs.payment.utils.get_selected_payment_method(request) # Only if the payment is succesful we create the order out of the # cart. if result.get("success") == True: order = lfs.order.utils.add_order(request) # TODO: Get rid of these payment specific payment stuff. This # should be within payment utils. if payment_method.id == PAYPAL and settings.LFS_PAYPAL_REDIRECT: return HttpResponseRedirect(order.get_pay_link()) else: return HttpResponseRedirect(result.get("next-url")) else: if result.has_key("message"): form._errors[result.get("message-key")] = result.get("message") else: # form is not valid # Create or update invoice address if customer.selected_invoice_address is None: invoice_address = Address.objects.create( firstname = form.data.get("invoice_firstname"), lastname = form.data.get("invoice_lastname"), company_name = form.data.get("invoice_company_name"), street = form.data.get("invoice_street"), zip_code = form.data.get("invoice_zip_code"), city = form.data.get("invoice_city"), country_id = form.data.get("invoice_country"), phone = form.data.get("invoice_phone"), email = form.data.get("invoice_email"), ) customer.selected_invoice_address = invoice_address else: selected_invoice_address = customer.selected_invoice_address selected_invoice_address.firstname = form.data.get("invoice_firstname") selected_invoice_address.lastname = form.data.get("invoice_lastname") selected_invoice_address.company_name = form.data.get("invoice_company_name") selected_invoice_address.street = form.data.get("invoice_street") selected_invoice_address.zip_code = form.data.get("invoice_zip_code") selected_invoice_address.city = form.data.get("invoice_city") selected_invoice_address.country_id = form.data.get("invoice_country") selected_invoice_address.phone = form.data.get("invoice_phone") selected_invoice_address.email = form.data.get("invoice_email") selected_invoice_address.save() # If the shipping address differs from invoice firstname we create # or update the shipping address. if not form.data.get("no_shipping"): if customer.selected_shipping_address is None: shipping_address = Address.objects.create( firstname = form.data.get("shipping_firstname"), lastname = form.data.get("shipping_lastname"), company_name = form.data.get("shipping_company_name"), street = form.data.get("shipping_street"), zip_code = form.data.get("shipping_zip_code"), city = form.data.get("shipping_city"), country_id = form.data.get("shipping_country"), phone = form.data.get("shipping_phone"), email = form.data.get("shipping_email"), ) customer.selected_shipping_address = shipping_address else: selected_shipping_address = customer.selected_shipping_address selected_shipping_address.firstname = form.data.get("shipping_firstname") selected_shipping_address.lastname = form.data.get("shipping_lastname") selected_shipping_address.company_name = form.data.get("shipping_company_name") selected_shipping_address.street = form.data.get("shipping_street") selected_shipping_address.zip_code = form.data.get("shipping_zip_code") selected_shipping_address.city = form.data.get("shipping_city") selected_shipping_address.country_id = form.data.get("shipping_country") selected_shipping_address.phone = form.data.get("shipping_phone") selected_shipping_address.save() # Payment method customer.selected_payment_method_id = request.POST.get("payment_method") # 1 = Direct Debit if int(form.data.get("payment_method")) == 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 = {} if customer.selected_invoice_address is not None: invoice_address = customer.selected_invoice_address initial.update({ "invoice_firstname" : invoice_address.firstname, "invoice_lastname" : invoice_address.lastname, "invoice_street" : invoice_address.street, "invoice_zip_code" : invoice_address.zip_code, "invoice_city" : invoice_address.city, "invoice_country" : invoice_address.country_id, "invoice_phone" : invoice_address.phone, "invoice_email" : invoice_address.email, }) if customer.selected_shipping_address is not None: shipping_address = customer.selected_shipping_address initial.update({ "shipping_firstname" : shipping_address.firstname, "shipping_lastname" : shipping_address.lastname, "shipping_street" : shipping_address.street, "shipping_zip_code" : shipping_address.zip_code, "shipping_city" : shipping_address.city, "shipping_phone" : shipping_address.phone, "shipping_email" : shipping_address.email, "no_shipping" : False, }) # Set the addresses country to the current selected in any case. country = lfs.shipping.utils.get_selected_shipping_country(request) initial["shipping_country"] = country.id initial["invoice_country"] = country.id form = checkout_form(initial=initial) cart = cart_utils.get_cart(request) if cart is None: return HttpResponseRedirect(reverse('lfs_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 = lfs.payment.utils.get_selected_payment_method(request) valid_payment_methods = lfs.payment.utils.get_valid_payment_methods(request) valid_payment_method_ids = [m.id for m in valid_payment_methods] display_bank_account = DIRECT_DEBIT in valid_payment_method_ids display_credit_card = CREDIT_CARD in valid_payment_method_ids response = render_to_response(template_name, RequestContext(request, { "form" : form, "cart_inline" : cart_inline(request), "shipping_inline" : shipping_inline(request), "payment_inline" : payment_inline(request, form), "selected_payment_method" : selected_payment_method, "display_bank_account" : display_bank_account, "display_credit_card" : display_credit_card, })) if form._errors: return lfs.core.utils.set_message_to(response, _(u"An error has been occured.")) else: return response