def save_criteria(self, request): """ Saves all passed criteria (via request.POST) to the object. """ # First we delete all existing criteria objects for the given object. for co in self.get_criteria(): co.delete() # Then we add all passed criteria to the object. for key, model in request.POST.items(): if key.startswith("type"): try: id = key.split("-")[1] except KeyError: continue # Get the values for the criterion operator = request.POST.get("operator-%s" % id) position = request.POST.get("position-%s" % id) criterion_class = import_symbol(model) criterion = criterion_class.objects.create(content=self, operator=operator, position=position) if criterion.get_value_type() == criterion.MULTIPLE_SELECT: value = request.POST.getlist("value-%s" % id) else: value = request.POST.get("value-%s" % id) criterion.update(value)
def save_criteria(self, request): """ Saves all passed criteria (via request.POST) to the object. """ # First we delete all existing criteria objects for the given object. for co in self.get_criteria(): co.delete() # Then we add all passed criteria to the object. for key, model in request.POST.items(): if key.startswith("type"): try: id = key.split("-")[1] except KeyError: continue # Get the values for the criterion operator = request.POST.get("operator-%s" % id) position = request.POST.get("position-%s" % id) criterion_class = import_symbol(model) criterion = criterion_class.objects.create(content=self, operator=operator, position=position) if criterion.get_value_type() == criterion.MULTIPLE_SELECT: value = request.POST.getlist("value-%s" % id) else: value = request.POST.get("value-%s" % id) criterion.update(value) content_type = ContentType.objects.get_for_model(self) cache_key = u"criteria_for_model_{}_{}".format(self.pk, content_type.pk) cache.delete(cache_key)
def add_criterion(request): """ Adds a new criterion form. """ try: default_criterion = settings.LFS_CRITERIA[0] default_criterion = import_symbol(default_criterion[0]) result = default_criterion().render(request, 10) except: result = "" default_criterion = settings.LFS_CRITERIA[0] default_criterion = import_symbol(default_criterion[0]) result = default_criterion().render(request, 10) return HttpResponse(result)
def save_order_numbers_tab(request): """Saves the order number tab of the default shop. """ shop = lfs.core.utils.get_default_shop() ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) order_number = ong.objects.get(id="order_number") form = order_number.get_form(instance=order_number, data=request.POST) if form.is_valid(): form.save() shop_changed.send(shop) message = _(u"Order numbers has been saved.") else: message = _(u"Please correct the indicated errors.") result = simplejson.dumps( { "html": [["#order_numbers", order_numbers_tab(request, shop, form)]], "message": message, }, cls=LazyEncoder) return HttpResponse(result)
def save_criteria(request, object): """ Saves the criteria for the given object. The criteria are passed via request body. """ logger.info("Decprecated: lfs.criteria.utils.save_criteria: this function is deprecated. Please use the Criteria class instead.") # First we delete all existing criteria objects for the given object. for co in get_criteria(object): co.delete() # Then we add all passed criteria to the object. for key, model in request.POST.items(): if key.startswith("type"): try: id = key.split("-")[1] except KeyError: continue # Get the values for the criterion operator = request.POST.get("operator-%s" % id) position = request.POST.get("position-%s" % id) criterion_class = import_symbol(model) criterion = criterion_class.objects.create(content=object, operator=operator, position=position) if criterion.get_value_type() == criterion.MULTIPLE_SELECT: value = request.POST.getlist("value-%s" % id) else: value = request.POST.get("value-%s" % id) criterion.update(value)
def save_criteria(request, object): """ Saves the criteria for the given object. The criteria are passed via request body. """ logger.info( "Decprecated: lfs.criteria.utils.save_criteria: this function is deprecated. Please use the Criteria class instead." ) # First we delete all existing criteria objects for the given object. for co in get_criteria(object): co.delete() # Then we add all passed criteria to the object. for key, model in request.POST.items(): if key.startswith("type"): try: id = key.split("-")[1] except KeyError: continue # Get the values for the criterion operator = request.POST.get("operator-%s" % id) position = request.POST.get("position-%s" % id) criterion_class = import_symbol(model) criterion = criterion_class.objects.create(content=object, operator=operator, position=position) if criterion.get_value_type() == criterion.MULTIPLE_SELECT: value = request.POST.getlist("value-%s" % id) else: value = request.POST.get("value-%s" % id) criterion.update(value)
def environment(request, template_name="manage/information/environment.html"): """Displays miscellaneous information about the evnironment. """ apps = [] for app in settings.INSTALLED_APPS: if app in ["lfs"] or \ app.startswith("lfs.") or \ app.startswith("django."): continue try: version = import_symbol("%s.__version__" % app) except AttributeError: version = "N/A" apps.append({ "name": app, "version": version, }) apps.sort(lambda a, b: cmp(a["name"], b["name"])) return render_to_response( template_name, RequestContext( request, { "lfs_version": lfs_version, "lfs_theme_version": lfs_theme_version, "apps": apps, }))
def environment(request, template_name="manage/information/environment.html"): """Displays miscellaneous information about the evnironment. """ apps = [] for app in settings.INSTALLED_APPS: if app in ["lfs"] or \ app.startswith("lfs.") or \ app.startswith("django."): continue try: version = import_symbol("%s.__version__" % app) except AttributeError: version = "N/A" apps.append({ "name": app, "version": version, }) apps.sort(lambda a, b: cmp(a["name"], b["name"])) return render_to_response(template_name, RequestContext(request, { "lfs_version": lfs_version, "lfs_theme_version": lfs_theme_version, "apps": apps, }))
def get_price_gross(self, request): """ Returns the default price of the shipping method. """ if self.price_calculator: price_class = import_symbol(self.price_calculator) return price_class(request, self).get_price_gross() else: return self.price
def get_tax(self, request): """ Returns the absolute tax of the shipping method. """ if self.price_calculator: price_class = import_symbol(self.price_calculator) return price_class(request, self).get_tax() else: return self.tax.rate
def get_price(self, request): """Returns the gross price of the shipping method. This method is DEPRECATED. """ if self.price_calculator: price_class = import_symbol(self.price_calculator) return price_class(request, self).get_price() else: return self.price
def get_tax(self, request): """ Returns the absolute tax of the shipping method. """ if self.price_calculator: price_class = import_symbol(self.price_calculator) return price_class(request, self).get_tax() else: # TODO: this should be tax not tax rate return 0.0
def change_criterion_form(request): """ Changes the changed criterion form to the given type (via request body) form. This is called via an AJAX request. The result is injected into the right DOM node. """ type = request.POST.get("type", "price") criterion = import_symbol(type) # create dummy criterion result = criterion(pk=1).render(request, 10) return HttpResponse(result)
def process_payment(request): """ Processes the payment depending on the selected payment method. Returns a dictionary with the success state, the next url and a optional error message. """ from lfs.core.utils import import_symbol from lfs.order.utils import add_order from lfs.cart.utils import get_cart payment_method = get_selected_payment_method(request) if payment_method.module: payment_class = import_symbol(payment_method.module) payment_instance = payment_class(request) create_order_time = payment_instance.get_create_order_time() if create_order_time == PM_ORDER_IMMEDIATELY: order = add_order(request) if order is None: return {'accepted': True, 'next_url': reverse("lfs_shop_view")} payment_instance.order = order result = payment_instance.process() if result.get("order_state"): order.state = result.get("order_state") order.save() order_submitted.send(sender=order, request=request) else: cart = get_cart(request) payment_instance.cart = cart result = payment_instance.process() if result["accepted"]: if create_order_time == PM_ORDER_ACCEPTED: order = add_order(request) if result.get("order_state"): order.state = result.get("order_state") order.save() order_submitted.send(sender=order, request=request) return result else: order = add_order(request) order_submitted.send(sender=order, request=request) return { "accepted": True, "next_url": reverse("lfs_thank_you"), }
def get_pay_link(request, payment_method, order): """ Creates a pay link for the passed payment_method and order. This can be used to display the link within the order mail and/or the thank you page after a customer has payed. """ from lfs.core.utils import import_symbol logger.info("Decprecated: lfs.payment.utils.get_pay_link: this function is deprecated. Please use Order.get_pay_link instead.") if payment_method.module: payment_class = import_symbol(payment_method.module) payment_instance = payment_class(request=request, order=order) try: return payment_instance.get_pay_link() except AttributeError: return "" else: return ""
def save_order_numbers_tab(request): """Saves the order number tab of the default shop. """ shop = lfs.core.utils.get_default_shop() ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) order_number = ong.objects.get(id="order_number") form = order_number.get_form(instance=order_number, data=request.POST) if form.is_valid(): form.save() shop_changed.send(shop) message = _(u"Order numbers has been saved.") else: message = _(u"Please correct the indicated errors.") result = simplejson.dumps( {"html": [["#order_numbers", order_numbers_tab(request, shop, form)]], "message": message}, cls=LazyEncoder ) return HttpResponse(result)
def create_order(form_data, request): client = form_data['client'] order = Order.objects.create( user=client.user, invoice_line2=form_data['reference'], message=form_data['message'], session=request.session.session_key, # tax=form_data['product_price_gross'] * form_data['product_tax'], customer_firstname=client.name, customer_lastname='', customer_email=client.user.email, invoice_firstname=client.name, invoice_lastname='', invoice_company_name=client.name, invoice_line1='{street} {nr}'.format(street=client.street, nr=client.street_nr), # invoice_line2='', used for the invoice reference invoice_city=client.city, invoice_state='', invoice_code=client.zip, invoice_country=Country.objects.get(code='nl'), invoice_phone='', ) ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) try: order_numbers = ong.objects.get(id="order_number") except ong.DoesNotExist: order_numbers = ong.objects.create(id="order_number") try: order_numbers.init(request, order) except AttributeError: pass order.number = order_numbers.get_next() return order
def add_order(request): """Adds an order based on current cart for the current customer. It assumes that the customer is prepared with all needed information. This is within the responsibility of the checkout form. """ customer = customer_utils.get_customer(request) order = None invoice_address = customer.selected_invoice_address if request.POST.get("no_shipping"): shipping_address = customer.selected_invoice_address else: shipping_address = customer.selected_shipping_address cart = cart_utils.get_cart(request) if cart is None: return order shipping_method = shipping_utils.get_selected_shipping_method(request) shipping_costs = shipping_utils.get_shipping_costs(request, shipping_method) payment_method = payment_utils.get_selected_payment_method(request) payment_costs = payment_utils.get_payment_costs(request, payment_method) # Set email dependend on login state. An anonymous customer doesn't have a # django user account, so we set the name of the invoice address to the # customer name. # Note: After this has been processed the order's customer email has an # email in any case. That means you can use it to send emails to the # customer. if request.user.is_authenticated(): user = request.user customer_email = user.email else: user = None customer_email = customer.selected_invoice_address.email # Calculate the totals price = cart.get_price_gross( request) + shipping_costs["price"] + payment_costs["price"] tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"] # Discounts discounts = lfs.discounts.utils.get_valid_discounts(request) for discount in discounts: price = price - discount["price"] tax = tax - discount["tax"] # Add voucher if one exists try: voucher_number = lfs.voucher.utils.get_current_voucher_number(request) voucher = Voucher.objects.get(number=voucher_number) except Voucher.DoesNotExist: voucher = None else: is_voucher_effective, voucher_message = voucher.is_effective( request, cart) if is_voucher_effective: voucher_number = voucher.number voucher_price = voucher.get_price_gross(request, cart) voucher_tax = voucher.get_tax(request, cart) price -= voucher_price tax -= voucher_tax else: voucher = None order = Order.objects.create( user=user, session=request.session.session_key, price=price, tax=tax, customer_firstname=customer.selected_invoice_address.firstname, customer_lastname=customer.selected_invoice_address.lastname, customer_email=customer_email, shipping_method=shipping_method, shipping_price=shipping_costs["price"], shipping_tax=shipping_costs["tax"], payment_method=payment_method, payment_price=payment_costs["price"], payment_tax=payment_costs["tax"], invoice_firstname=customer.selected_invoice_address.firstname, invoice_lastname=customer.selected_invoice_address.lastname, invoice_company_name=customer.selected_invoice_address.company_name, invoice_line1=invoice_address.line1, invoice_line2=invoice_address.line2, invoice_city=invoice_address.city, invoice_state=invoice_address.state, invoice_code=invoice_address.zip_code, invoice_country=Country.objects.get(code=invoice_address.country.code), invoice_phone=customer.selected_invoice_address.phone, shipping_firstname=shipping_address.firstname, shipping_lastname=shipping_address.lastname, shipping_company_name=shipping_address.company_name, shipping_line1=shipping_address.line1, shipping_line2=shipping_address.line2, shipping_city=shipping_address.city, shipping_state=shipping_address.state, shipping_code=shipping_address.zip_code, shipping_country=Country.objects.get( code=shipping_address.country.code), shipping_phone=shipping_address.phone, message=request.POST.get("message", ""), ) requested_delivery_date = request.POST.get("requested_delivery_date", None) if requested_delivery_date is not None: order.requested_delivery_date = requested_delivery_date order.save() if voucher: voucher.mark_as_used() order.voucher_number = voucher_number order.voucher_price = voucher_price order.voucher_tax = voucher_tax order.save() # Copy bank account if one exists if customer.selected_bank_account: bank_account = customer.selected_bank_account order.account_number = bank_account.account_number order.bank_identification_code = bank_account.bank_identification_code order.bank_name = bank_account.bank_name order.depositor = bank_account.depositor order.save() # Copy cart items for cart_item in cart.get_items(): order_item = OrderItem.objects.create( order=order, price_net=cart_item.get_price_net(request), price_gross=cart_item.get_price_gross(request), tax=cart_item.get_tax(request), product=cart_item.product, product_sku=cart_item.product.sku, product_name=cart_item.product.get_name(), product_amount=cart_item.amount, product_price_net=cart_item.product.get_price_net(request), product_price_gross=cart_item.get_product_price_gross(request), product_tax=cart_item.product.get_tax(request), ) cart_item.product.decrease_stock_amount(cart_item.amount) # Copy properties to order if cart_item.product.is_configurable_product(): for cpv in cart_item.properties.all(): OrderItemPropertyValue.objects.create(order_item=order_item, property=cpv.property, value=cpv.value) for discount in discounts: OrderItem.objects.create( order=order, price_net=-(discount["price"] - discount["tax"]), price_gross=-discount["price"], tax=-discount["tax"], product_sku=discount["sku"], product_name=discount["name"], product_amount=1, product_price_net=-(discount["price"] - discount["tax"]), product_price_gross=-discount["price"], product_tax=-discount["tax"], ) # Send signal before cart is deleted. order_created.send({"order": order, "cart": cart, "request": request}) cart.delete() # Note: Save order for later use in thank you page. The order will be # removed from the session if the thank you page has been called. request.session["order"] = order ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) try: order_numbers = ong.objects.get(id="order_number") except ong.DoesNotExist: order_numbers = ong.objects.create(id="order_number") try: order_numbers.init(request, order) except AttributeError: pass order.number = order_numbers.get_next() order.save() return order
def handle(self, *args, **options): from lfs.core.models import ActionGroup from lfs.core.models import Action from lfs.core.models import Application from lfs.core.models import Country from lfs.core.models import Shop from lfs.core.utils import import_symbol from portlets.models import Slot from portlets.models import PortletAssignment from lfs.portlet.models import CartPortlet from lfs.portlet.models import CategoriesPortlet from lfs.portlet.models import PagesPortlet from lfs.payment.models import PaymentMethod from lfs.payment.settings import PM_BANK from lfs.page.models import Page from lfs.shipping.models import ShippingMethod from lfs_additional_categories.models import AdditionalFilterPortlet from lfs.catalog.models import Category #Clear Country.objects.all().delete() Shop.objects.all().delete() ActionGroup.objects.all().delete() Action.objects.all().delete() Category.objects.all().delete() CartPortlet.objects.all().delete() CategoriesPortlet.objects.all().delete() PagesPortlet.objects.all().delete() AdditionalFilterPortlet.objects.all().delete() PortletAssignment.objects.all().delete() PaymentMethod.objects.all().delete() ShippingMethod.objects.all().delete() Page.objects.all().delete() Application.objects.all().delete() # Country russia = Country.objects.create(code="ru", name=u"Россия") # Shop shop = Shop.objects.create(name="LFS", shop_owner="John Doe", from_email="*****@*****.**", notification_emails="*****@*****.**", description=SHOP_DESCRIPTION, default_country=russia) shop.invoice_countries.add(russia) shop.shipping_countries.add(russia) # Actions tabs = ActionGroup.objects.create(name="Tabs") footer = ActionGroup.objects.create(name="Footer") Action.objects.create(group=tabs, title=u"Контакты", link="/contact", active=True, position=1) # Action.objects.create(group=footer, title=u"Соглашение об использовании", link="/page/terms-and-conditions", active=True, position=1) # Action.objects.create(group=footer, title="Imprint", link="/page/imprint", active=True, position=2) #Catalog category = Category.objects.create(name=u"Товары", slug="all", level=1, template=1) # Portlets left_slot = Slot.objects.create(name="Left") right_slot = Slot.objects.create(name="Right") centre_slot = Slot.objects.create(name="Centre") cart_portlet = CartPortlet.objects.create(title=u"Корзина") PortletAssignment.objects.create(slot=right_slot, content=shop, portlet=cart_portlet) categories_portlet = CategoriesPortlet.objects.create(title=u"Товары") PortletAssignment.objects.create(slot=left_slot, content=shop, portlet=categories_portlet) # pages_portlet = PagesPortlet.objects.create(title=u"Информация") # PortletAssignment.objects.create(slot=left_slot, content=shop, portlet=pages_portlet) additional_filter_portlet = AdditionalFilterPortlet.objects.create(title=u"Товары по модели", default_category=category) PortletAssignment.objects.create(slot=centre_slot, content=shop, portlet=additional_filter_portlet) # Payment methods pm = PaymentMethod.objects.create(name=u"Банковская карта", priority=1, active=1, deletable=0, type=PM_BANK) pm.id=1; pm.save() pm = PaymentMethod.objects.create(name=u"Оплата наличными при получении товара", priority=2, active=1, deletable=0) pm.id=2; pm.save() #pm = PaymentMethod.objects.create(name=u"PayPal", priority=3, active=1, deletable=0) #pm.id=3; pm.save() pm = PaymentMethod.objects.create(name=u"Предоплата", priority=4, active=1, deletable=0) pm.id=3; pm.save() # Shipping methods ShippingMethod.objects.create(name=u"Обычная доставка", priority=1, active=1) # Pages p = Page.objects.create(title=u"Главная страница", slug="", active=1, exclude_from_navigation=1) p.id = 1; p.save() # p = Page.objects.create(title=u"Соглашение об использовании", slug="terms-and-conditions", active=1, # body=u"Введите текст соглашения об использовании.") # p.id = 2; p.save() # p = Page.objects.create(title="Imprint", slug="imprint", active=1, body="Enter your imprint here.") # p.id = 3; p.save() # Order Numbers ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) ong.objects.all().delete() ong.objects.create(id="order_number") # Application object Application.objects.create(version="0.7")
def add_order(request): """Adds an order based on current cart for the current customer. It assumes that the customer is prepared with all needed information. This is within the responsibility of the checkout form. """ customer = customer_utils.get_customer(request) order = None not_required_address = getattr(settings, 'LFS_CHECKOUT_NOT_REQUIRED_ADDRESS', 'shipping') invoice_address = customer.selected_invoice_address shipping_address = customer.selected_shipping_address if not_required_address == 'shipping': if request.POST.get("no_shipping"): shipping_address = customer.selected_invoice_address else: shipping_address = customer.selected_shipping_address else: if request.POST.get("no_invoice"): invoice_address = customer.selected_shipping_address else: invoice_address = customer.selected_invoice_address cart = cart_utils.get_cart(request) if cart is None: return order shipping_method = shipping_utils.get_selected_shipping_method(request) shipping_costs = shipping_utils.get_shipping_costs(request, shipping_method) payment_method = payment_utils.get_selected_payment_method(request) payment_costs = payment_utils.get_payment_costs(request, payment_method) # Set email dependend on login state. An anonymous customer doesn't have a # django user account, so we set the name of the invoice address to the # customer name. # Note: After this has been processed the order's customer email has an # email in any case. That means you can use it to send emails to the # customer. if request.user.is_authenticated(): user = request.user customer_email = user.email else: user = None customer_email = customer.selected_invoice_address.email # Calculate the totals price = cart.get_price_gross( request) + shipping_costs["price_gross"] + payment_costs["price"] tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"] # get voucher data (if voucher exists) voucher_data = get_voucher_data(request, cart) # get discounts data discounts_data = lfs.discounts.utils.get_discounts_data(request) # calculate total value of discounts and voucher that sum up summed_up_value = discounts_data['summed_up_value'] if voucher_data['sums_up']: summed_up_value += voucher_data['voucher_value'] # initialize discounts with summed up discounts use_voucher = voucher_data['voucher'] is not None discounts = discounts_data['summed_up_discounts'] if voucher_data['voucher_value'] > summed_up_value or discounts_data[ 'max_value'] > summed_up_value: # use not summed up value if voucher_data['voucher_value'] > discounts_data['max_value']: # use voucher only discounts = [] else: # use discount only discounts = discounts_data['max_discounts'] use_voucher = False for discount in discounts: price -= discount["price_gross"] tax -= discount["tax"] if use_voucher: price -= voucher_data['voucher_value'] tax -= voucher_data['voucher_tax'] if price < 0: price = 0 if tax < 0: tax = 0 # Copy addresses invoice_address = deepcopy(invoice_address) invoice_address.id = None invoice_address.pk = None invoice_address.save() shipping_address = deepcopy(shipping_address) shipping_address.id = None shipping_address.pk = None shipping_address.save() order = Order.objects.create( user=user, session=request.session.session_key, price=price, tax=tax, customer_firstname=customer.selected_invoice_address.firstname, customer_lastname=customer.selected_invoice_address.lastname, customer_email=customer_email, shipping_method=shipping_method, shipping_price=shipping_costs["price_gross"], shipping_tax=shipping_costs["tax"], payment_method=payment_method, payment_price=payment_costs["price"], payment_tax=payment_costs["tax"], invoice_address=invoice_address, shipping_address=shipping_address, message=request.POST.get("message", ""), ) delivery_time = cart.get_delivery_time(request) if delivery_time: OrderDeliveryTime.objects.create(order=order, min=delivery_time.min, max=delivery_time.max, unit=delivery_time.unit) invoice_address.order = order invoice_address.save() shipping_address.order = order shipping_address.save() requested_delivery_date = request.POST.get("requested_delivery_date", None) if requested_delivery_date is not None: order.requested_delivery_date = requested_delivery_date order.save() if use_voucher: voucher_data['voucher'].mark_as_used() order.voucher_number = voucher_data['voucher_number'] order.voucher_price = voucher_data['voucher_value'] order.voucher_tax = voucher_data['voucher_tax'] order.save() # Copy bank account if one exists if customer.selected_bank_account: bank_account = customer.selected_bank_account order.account_number = bank_account.account_number order.bank_identification_code = bank_account.bank_identification_code order.bank_name = bank_account.bank_name order.depositor = bank_account.depositor order.save() # Copy cart items for cart_item in cart.get_items(): if cart_item.amount == 0: continue order_item = OrderItem.objects.create( order=order, price_net=cart_item.get_price_net(request), price_gross=cart_item.get_price_gross(request), tax=cart_item.get_tax(request), product=cart_item.product, product_sku=cart_item.product.sku, product_name=cart_item.product.get_name(), product_amount=cart_item.amount, product_price_net=cart_item.product.get_price_net(request), product_price_gross=cart_item.get_product_price_gross(request), product_tax=cart_item.product.get_tax(request), ) cart_item.product.decrease_stock_amount(cart_item.amount) # Copy properties to order if cart_item.product.is_configurable_product(): for cpv in cart_item.properties.all(): OrderItemPropertyValue.objects.create(order_item=order_item, property=cpv.property, value=cpv.value) for discount in discounts: OrderItem.objects.create( order=order, price_net=-discount["price_net"], price_gross=-discount["price_gross"], tax=-discount["tax"], product_sku=discount["sku"], product_name=discount["name"], product_amount=1, product_price_net=-discount["price_net"], product_price_gross=-discount["price_gross"], product_tax=-discount["tax"], ) # Re-initialize selected addresses to be equal to default addresses for next order customer.sync_default_to_selected_addresses() customer.save() # Send signal before cart is deleted. order_created.send(order, cart=cart, request=request) cart.delete() # Note: Save order for later use in thank you page. The order will be # removed from the session if the thank you page has been called. request.session["order"] = order ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) try: order_numbers = ong.objects.get(id="order_number") except ong.DoesNotExist: order_numbers = ong.objects.create(id="order_number") try: order_numbers.init(request, order) except AttributeError: pass order.number = order_numbers.get_next() order.save() return order
def add_order(request): """Adds an order based on current cart for the current customer. It assumes that the customer is prepared with all needed information. This is within the responsibility of the checkout form. """ customer = customer_utils.get_customer(request) order = None not_required_address = getattr(settings, 'LFS_CHECKOUT_NOT_REQUIRED_ADDRESS', 'shipping') invoice_address = customer.selected_invoice_address shipping_address = customer.selected_shipping_address if not_required_address == 'shipping': if request.POST.get("no_shipping"): shipping_address = customer.selected_invoice_address else: shipping_address = customer.selected_shipping_address else: if request.POST.get("no_invoice"): invoice_address = customer.selected_shipping_address else: invoice_address = customer.selected_invoice_address cart = cart_utils.get_cart(request) if cart is None: return order shipping_method = shipping_utils.get_selected_shipping_method(request) shipping_costs = shipping_utils.get_shipping_costs(request, shipping_method) payment_method = payment_utils.get_selected_payment_method(request) payment_costs = payment_utils.get_payment_costs(request, payment_method) # Set email dependend on login state. An anonymous customer doesn't have a # django user account, so we set the name of the invoice address to the # customer name. # Note: After this has been processed the order's customer email has an # email in any case. That means you can use it to send emails to the # customer. if request.user.is_authenticated(): user = request.user customer_email = user.email else: user = None customer_email = customer.selected_invoice_address.email # Calculate the totals price = cart.get_price_gross(request) + shipping_costs["price_gross"] + payment_costs["price"] tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"] # get voucher data (if voucher exists) voucher_data = get_voucher_data(request, cart) # get discounts data discounts_data = lfs.discounts.utils.get_discounts_data(request) # calculate total value of discounts and voucher that sum up summed_up_value = discounts_data['summed_up_value'] if voucher_data['sums_up']: summed_up_value += voucher_data['voucher_value'] # initialize discounts with summed up discounts use_voucher = voucher_data['voucher'] is not None discounts = discounts_data['summed_up_discounts'] if voucher_data['voucher_value'] > summed_up_value or discounts_data['max_value'] > summed_up_value: # use not summed up value if voucher_data['voucher_value'] > discounts_data['max_value']: # use voucher only discounts = [] else: # use discount only discounts = discounts_data['max_discounts'] use_voucher = False for discount in discounts: price -= discount["price_gross"] tax -= discount["tax"] if use_voucher: price -= voucher_data['voucher_value'] tax -= voucher_data['voucher_tax'] if price < 0: price = 0 if tax < 0: tax = 0 # Copy addresses invoice_address = deepcopy(invoice_address) invoice_address.id = None invoice_address.pk = None invoice_address.save() shipping_address = deepcopy(shipping_address) shipping_address.id = None shipping_address.pk = None shipping_address.save() order = Order.objects.create( user=user, session=request.session.session_key, price=price, tax=tax, customer_firstname=customer.selected_invoice_address.firstname, customer_lastname=customer.selected_invoice_address.lastname, customer_email=customer_email, shipping_method=shipping_method, shipping_price=shipping_costs["price_gross"], shipping_tax=shipping_costs["tax"], payment_method=payment_method, payment_price=payment_costs["price"], payment_tax=payment_costs["tax"], invoice_address=invoice_address, shipping_address=shipping_address, message=request.POST.get("message", ""), ) delivery_time = cart.get_delivery_time(request) if delivery_time: OrderDeliveryTime.objects.create(order=order, min=delivery_time.min, max=delivery_time.max, unit=delivery_time.unit) invoice_address.order = order invoice_address.save() shipping_address.order = order shipping_address.save() requested_delivery_date = request.POST.get("requested_delivery_date", None) if requested_delivery_date is not None: order.requested_delivery_date = requested_delivery_date order.save() if use_voucher: voucher_data['voucher'].mark_as_used() order.voucher_number = voucher_data['voucher_number'] order.voucher_price = voucher_data['voucher_value'] order.voucher_tax = voucher_data['voucher_tax'] order.save() # Copy bank account if one exists if customer.selected_bank_account: bank_account = customer.selected_bank_account order.account_number = bank_account.account_number order.bank_identification_code = bank_account.bank_identification_code order.bank_name = bank_account.bank_name order.depositor = bank_account.depositor order.save() # Copy cart items for cart_item in cart.get_items(): if cart_item.amount == 0: continue order_item = OrderItem.objects.create( order=order, price_net=cart_item.get_price_net(request), price_gross=cart_item.get_price_gross(request), tax=cart_item.get_tax(request), product=cart_item.product, product_sku=cart_item.product.sku, product_name=cart_item.product.get_name(), product_amount=cart_item.amount, product_price_net=cart_item.product.get_price_net(request), product_price_gross=cart_item.get_product_price_gross(request), product_tax=cart_item.product.get_tax(request), ) cart_item.product.decrease_stock_amount(cart_item.amount) # Copy properties to order if cart_item.product.is_configurable_product(): for cpv in cart_item.properties.all(): OrderItemPropertyValue.objects.create( order_item=order_item, property=cpv.property, value=cpv.value) for discount in discounts: OrderItem.objects.create( order=order, price_net=-discount["price_net"], price_gross=-discount["price_gross"], tax=-discount["tax"], product_sku=discount["sku"], product_name=discount["name"], product_amount=1, product_price_net=-discount["price_net"], product_price_gross=-discount["price_gross"], product_tax=-discount["tax"], ) # Re-initialize selected addresses to be equal to default addresses for next order customer.sync_default_to_selected_addresses() customer.save() # Send signal before cart is deleted. order_created.send(order, cart=cart, request=request) cart.delete() # Note: Save order for later use in thank you page. The order will be # removed from the session if the thank you page has been called. request.session["order"] = order ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) try: order_numbers = ong.objects.get(id="order_number") except ong.DoesNotExist: order_numbers = ong.objects.create(id="order_number") try: order_numbers.init(request, order) except AttributeError: pass order.number = order_numbers.get_next() order.save() return order
def handle(self, *args, **options): from lfs.core.models import ActionGroup from lfs.core.models import Action from lfs.core.models import Application from lfs.core.models import Country from lfs.core.models import Shop from lfs.core.utils import import_symbol from portlets.models import Slot from portlets.models import PortletAssignment from lfs.portlet.models import CartPortlet from lfs.portlet.models import CategoriesPortlet from lfs.portlet.models import PagesPortlet from lfs.payment.models import PaymentMethod from lfs.payment.settings import PM_BANK from lfs.page.models import Page from lfs.shipping.models import ShippingMethod # Country usa = Country.objects.create(code="us", name="USA") # Shop shop = Shop.objects.create(name="LFS", shop_owner="John Doe", from_email="*****@*****.**", notification_emails="*****@*****.**", description=SHOP_DESCRIPTION, default_country=usa) shop.invoice_countries.add(usa) shop.shipping_countries.add(usa) # Actions tabs = ActionGroup.objects.create(name="Tabs") footer = ActionGroup.objects.create(name="Footer") Action.objects.create(group=tabs, title="Contact", link="/contact", active=True, position=1) Action.objects.create(group=footer, title="Terms and Conditions", link="/page/terms-and-conditions", active=True, position=1) Action.objects.create(group=footer, title="Imprint", link="/page/imprint", active=True, position=2) # Portlets left_slot = Slot.objects.create(name="Left") right_slot = Slot.objects.create(name="Right") cart_portlet = CartPortlet.objects.create(title="Cart") PortletAssignment.objects.create(slot=right_slot, content=shop, portlet=cart_portlet) categories_portlet = CategoriesPortlet.objects.create( title="Categories") PortletAssignment.objects.create(slot=left_slot, content=shop, portlet=categories_portlet) pages_portlet = PagesPortlet.objects.create(title="Information") PortletAssignment.objects.create(slot=left_slot, content=shop, portlet=pages_portlet) # Payment methods pm = PaymentMethod.objects.create(name="Direct debit", priority=1, active=1, deletable=0, type=PM_BANK) pm.id = 1 pm.save() pm = PaymentMethod.objects.create(name="Cash on delivery", priority=2, active=1, deletable=0) pm.id = 2 pm.save() pm = PaymentMethod.objects.create(name="PayPal", priority=3, active=1, deletable=0) pm.id = 3 pm.save() pm = PaymentMethod.objects.create(name="Prepayment", priority=4, active=1, deletable=0) pm.id = 4 pm.save() # Shipping methods ShippingMethod.objects.create(name="Standard", priority=1, active=1) # Pages p = Page.objects.create(title="Root", slug="", active=1, exclude_from_navigation=1) p.id = 1 p.save() p = Page.objects.create(title="Terms and Conditions", slug="terms-and-conditions", active=1, body="Enter your terms and conditions here.") p.id = 2 p.save() p = Page.objects.create(title="Imprint", slug="imprint", active=1, body="Enter your imprint here.") p.id = 3 p.save() # Order Numbers ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) ong.objects.create(id="order_number") # Application object Application.objects.create(version="0.7")
def handle(self, *args, **options): from lfs.catalog.models import DeliveryTime from lfs.catalog.settings import DELIVERY_TIME_UNIT_DAYS from lfs.core.models import ActionGroup from lfs.core.models import Action from lfs.core.models import Application from lfs.core.models import Country from lfs.core.models import Shop from lfs.core.utils import import_symbol from portlets.models import Slot from portlets.models import PortletAssignment from lfs.portlet.models import CartPortlet from lfs.portlet.models import CategoriesPortlet from lfs.portlet.models import PagesPortlet from lfs.payment.models import PaymentMethod from lfs.payment.settings import PM_BANK from lfs.page.models import Page from lfs.shipping.models import ShippingMethod # Country usa = Country.objects.create(code="us", name="USA") # Default delivery time delivery_time = DeliveryTime.objects.create(min=1, max=2, unit=DELIVERY_TIME_UNIT_DAYS) # Shop shop = Shop.objects.create(name="LFS", shop_owner="John Doe", from_email="*****@*****.**", notification_emails="*****@*****.**", description=SHOP_DESCRIPTION, default_country=usa, delivery_time=delivery_time) shop.invoice_countries.add(usa) shop.shipping_countries.add(usa) # Actions tabs = ActionGroup.objects.create(name="Tabs") footer = ActionGroup.objects.create(name="Footer") Action.objects.create(group=tabs, title="Contact", link="/contact", active=True, position=1) Action.objects.create(group=footer, title="Terms and Conditions", link="/page/terms-and-conditions", active=True, position=1) Action.objects.create(group=footer, title="Imprint", link="/page/imprint", active=True, position=2) # Portlets left_slot = Slot.objects.create(name="Left") right_slot = Slot.objects.create(name="Right") cart_portlet = CartPortlet.objects.create(title="Cart") PortletAssignment.objects.create(slot=right_slot, content=shop, portlet=cart_portlet) categories_portlet = CategoriesPortlet.objects.create(title="Categories") PortletAssignment.objects.create(slot=left_slot, content=shop, portlet=categories_portlet) pages_portlet = PagesPortlet.objects.create(title="Information") PortletAssignment.objects.create(slot=left_slot, content=shop, portlet=pages_portlet) # Payment methods pm = PaymentMethod.objects.create(name="Direct debit", priority=1, active=1, deletable=0, type=PM_BANK) pm.id = 1 pm.save() pm = PaymentMethod.objects.create(name="Cash on delivery", priority=2, active=1, deletable=0) pm.id = 2 pm.save() pm = PaymentMethod.objects.create(name="PayPal", priority=3, active=1, deletable=0, module="lfs_paypal.PayPalProcessor") pm.id = 3 pm.save() pm = PaymentMethod.objects.create(name="Prepayment", priority=4, active=1, deletable=0) pm.id = 4 pm.save() # Shipping methods ShippingMethod.objects.create(name="Standard", priority=1, active=1) # Pages p = Page.objects.create(title="Root", slug="", active=1, exclude_from_navigation=1) p.id = 1 p.save() p = Page.objects.create(title="Terms and Conditions", slug="terms-and-conditions", active=1, body="Enter your terms and conditions here.") p.id = 2 p.save() p = Page.objects.create(title="Imprint", slug="imprint", active=1, body="Enter your imprint here.") p.id = 3 p.save() # Order Numbers ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) ong.objects.create(id="order_number") # Application object Application.objects.create(version="0.7")
def add_order(request): """Adds an order based on current cart for the current customer. It assumes that the customer is prepared with all needed information. This is within the responsibility of the checkout form. """ customer = customer_utils.get_customer(request) order = None invoice_address = customer.selected_invoice_address if request.POST.get("no_shipping"): shipping_address = customer.selected_invoice_address else: shipping_address = customer.selected_shipping_address cart = cart_utils.get_cart(request) if cart is None: return order shipping_method = shipping_utils.get_selected_shipping_method(request) shipping_costs = shipping_utils.get_shipping_costs(request, shipping_method) payment_method = payment_utils.get_selected_payment_method(request) payment_costs = payment_utils.get_payment_costs(request, payment_method) # Set email dependend on login state. An anonymous customer doesn't have a # django user account, so we set the name of the invoice address to the # customer name. # Note: After this has been processed the order's customer email has an # email in any case. That means you can use it to send emails to the # customer. if request.user.is_authenticated(): user = request.user customer_email = user.email else: user = None customer_email = customer.selected_invoice_address.email # Calculate the totals price = cart.get_price_gross(request) + shipping_costs["price_gross"] + payment_costs["price"] tax = cart.get_tax(request) + shipping_costs["tax"] + payment_costs["tax"] # Discounts discounts = lfs.discounts.utils.get_valid_discounts(request) for discount in discounts: price = price - discount["price_gross"] tax = tax - discount["tax"] # Add voucher if one exists is_voucher_effective = False try: voucher_number = lfs.voucher.utils.get_current_voucher_number(request) voucher = Voucher.objects.get(number=voucher_number) except Voucher.DoesNotExist: voucher = None else: is_voucher_effective, voucher_message = voucher.is_effective(request, cart) if is_voucher_effective: voucher_number = voucher.number voucher_price = voucher.get_price_gross(request, cart) voucher_tax = voucher.get_tax(request, cart) price -= voucher_price tax -= voucher_tax else: voucher = None if price < 0: price = 0 if tax < 0: tax = 0 # Copy addresses invoice_address = deepcopy(invoice_address) invoice_address.id = None invoice_address.save() shipping_address = deepcopy(shipping_address) shipping_address.id = None shipping_address.save() order = Order.objects.create( user=user, session=request.session.session_key, price=price, tax=tax, customer_firstname=customer.selected_invoice_address.firstname, customer_lastname=customer.selected_invoice_address.lastname, customer_email=customer_email, shipping_method=shipping_method, shipping_price=shipping_costs["price_gross"], shipping_tax=shipping_costs["tax"], payment_method=payment_method, payment_price=payment_costs["price"], payment_tax=payment_costs["tax"], invoice_address=invoice_address, shipping_address=shipping_address, message=request.POST.get("message", ""), ) invoice_address.order = order invoice_address.save() shipping_address.order = order shipping_address.save() requested_delivery_date = request.POST.get("requested_delivery_date", None) if requested_delivery_date is not None: order.requested_delivery_date = requested_delivery_date order.save() if is_voucher_effective: voucher.mark_as_used() order.voucher_number = voucher_number order.voucher_price = voucher_price order.voucher_tax = voucher_tax order.save() # Copy bank account if one exists if customer.selected_bank_account: bank_account = customer.selected_bank_account order.account_number = bank_account.account_number order.bank_identification_code = bank_account.bank_identification_code order.bank_name = bank_account.bank_name order.depositor = bank_account.depositor order.save() # Copy cart items for cart_item in cart.get_items(): if cart_item.amount == 0: continue order_item = OrderItem.objects.create( order=order, price_net=cart_item.get_price_net(request), price_gross=cart_item.get_price_gross(request), tax=cart_item.get_tax(request), product=cart_item.product, product_sku=cart_item.product.sku, product_name=cart_item.product.get_name(), product_amount=cart_item.amount, product_price_net=cart_item.product.get_price_net(request), product_price_gross=cart_item.get_product_price_gross(request), product_tax=cart_item.product.get_tax(request), ) cart_item.product.decrease_stock_amount(cart_item.amount) # Copy properties to order if cart_item.product.is_configurable_product(): for cpv in cart_item.properties.all(): OrderItemPropertyValue.objects.create( order_item=order_item, property=cpv.property, value=cpv.value) for discount in discounts: OrderItem.objects.create( order=order, price_net=-discount["price_net"], price_gross=-discount["price_gross"], tax=-discount["tax"], product_sku=discount["sku"], product_name=discount["name"], product_amount=1, product_price_net=-discount["price_net"], product_price_gross=-discount["price_gross"], product_tax=-discount["tax"], ) # Send signal before cart is deleted. order_created.send({"order": order, "cart": cart, "request": request}) cart.delete() # Note: Save order for later use in thank you page. The order will be # removed from the session if the thank you page has been called. request.session["order"] = order ong = import_symbol(settings.LFS_ORDER_NUMBER_GENERATOR) try: order_numbers = ong.objects.get(id="order_number") except ong.DoesNotExist: order_numbers = ong.objects.create(id="order_number") try: order_numbers.init(request, order) except AttributeError: pass order.number = order_numbers.get_next() order.save() return order
class Address(BaseAddress): """ The default address of LFS which is used as invoice and shipping address. This can be replaced by an own model. """ values_before_postal = ("firstname+", "lastname+", "company_name") values_after_postal = ("phone", "email") company_name = models.CharField(_("Company name"), max_length=50, blank=True, null=True) reference_name = models.CharField(_(u'Reference Name'), max_length=100, blank=True, null=True) phone = models.CharField(_("Phone"), blank=True, null=True, max_length=20) email = models.EmailField(_("E-Mail"), blank=True, null=True) def __unicode__(self): return u'%s %s (%s)' % (self.firstname, self.lastname, self.company_name) address_model = import_symbol(ADDRESS_MODEL) class AddressBook(models.Model): customer = models.ForeignKey(Customer, related_name="address_book") address = models.ForeignKey(address_model, related_name="address_book", verbose_name=_("Customer saved addresses")) def __unicode__(self): return "%s book: %s %s" % (self.customer.user.first_name, self.address.full_name, self.address.line1)