def set_discount(self): """ Assigns the session variables for the discount. """ discount = getattr(self, "_discount", None) def clear_session(*names): for name in names: try: del self._request.session[name] except KeyError: pass if discount is not None: # Clear out any previously defined discount code # session vars. clear_session("free_shipping", "discount_code", "discount_total") total = self._request.cart.calculate_discount(discount) if discount.free_shipping: set_shipping(self._request, _("Free shipping"), 0) else: # A previously entered discount code providing free # shipping may have been entered prior to this # discount code beign entered, so clear out any # previously set shipping vars. clear_session("shipping_type", "shipping_total") self._request.session["free_shipping"] = discount.free_shipping self._request.session["discount_code"] = discount.code self._request.session["discount_total"] = total
def set_discount(self): """ Assigns the session variables for the discount. """ discounts = getattr(self, "_discount", None) # member_discount = getattr(self, "member_discount", None) if discounts is not None: total = Decimal("0") names = ("free_shipping", "discount_codes", "discount_total") clear_session(self._request, *names) for discount in discounts: # Clear out any previously defined discount code # session vars. total += self._request.cart.calculate_discount(discount) if discount.free_shipping: set_shipping(self._request, _("Free shipping"), 0) self._request.session["free_shipping"] = discount.free_shipping else: # A previously entered discount code providing free # shipping may have been entered prior to this # discount code beign entered, so clear out any # previously set shipping vars. clear_session(self._request, "shipping_type", "shipping_total") self._request.session["discount_codes"] = discount.code self._request.session["discount_total"] = str(total)
def update_cart(request): if request.is_ajax() and request.method == "POST": sub = {} grand = 0 form = request.POST cart_formset = CartItemFormSet(request.POST, instance=request.cart) cart = cart_formset[0].instance.cart valid = cart_formset.is_valid() if valid: cart_formset.save() sub = [float(f.instance.total_price) for f in cart_formset] subtotal = float(cart.total_price()) discount = get_discount_on_update(request) grand = "{0:.2f}".format(subtotal - discount) total_qty = int(cart.total_quantity()) if total_qty == 0: set_shipping(request, "Shipping", 0) return HttpResponse(json.dumps({'sub':sub, 'subtotal' : subtotal, 'grand':grand, 'total_qty':total_qty, 'discount_total':discount}), content_type='application/json') else: error = cart_formset.errors[0]['quantity'][0] cart_formset = CartItemFormSet(instance=request.cart) messages.info(request, _(error)) #cart_formset._errors = errors return HttpResponse(json.dumps({'error': error}), content_type='application/json') else: return HttpResponse('Sth went wrong.')
def correios_billship_handler(request, order_form): """ Default billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ logger.debug("integration.checkout.correios_billship_handler()") if not request.session.get("free_shipping"): settings.use_editable() # http://www.correios.com.br/webservices/default.cfm # http://www.correios.com.br/webServices/PDF/SCPP_manual_implementacao_calculo_remoto_de_precos_e_prazos.pdf client = Client("http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx?wsdl") """ 40010 = SEDEX """ origin_cep = settings.CEP_ORIGIN data = order_form.cleaned_data dest_cep = data["billing_detail_postcode"] logger.debug("cep de %s para %s" % (origin_cep,dest_cep) ) # Propriedades fixas apenas para testar por enquanto result = client.service.CalcPreco("","",40010, origin_cep, dest_cep , "1.0",1, 50.0, 50.0, 50.0, 50.0, "N", 0 , "N") price = Decimal(result.Servicos[0][0].Valor.replace(",",".")) logger.debug("preço %s" % price) set_shipping(request, _("SEDEX"), price)
def get_carrier(request): if request.is_ajax() and request.method == 'POST': if not request.POST.get("free_shipping"): carrier = request.POST['carrier'] shipping_type = request.POST['shipping_type'] shipping_total = float(carrier.split()[3][1:]) settings.use_editable() set_shipping(request, shipping_type, shipping_total) recalculate_cart(request) else: shipping_type = 'Regular Shipping' shipping_total = 0.0 set_shipping(request, shipping_type, shipping_total) subtotal = float(request.cart.total_price()) discount = float(request.session.get('discount_total', '0.00')) total = subtotal - discount + shipping_total total = "{0:.2f}".format(total) #resp = render_to_string('shop/cart.html', { 'request': request }) return HttpResponse(json.dumps({ 'shipping_type': shipping_type, 'shipping_total': shipping_total, 'total_price': total, 'discount': discount, 'subtotal': subtotal }), content_type='application/json')
def default_billship_handler(request, order_form): """ Default billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ """ original codes flat rate shipping as below """ """ if not request.session.get("free_shipping"): settings.use_editable() set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE) """ print "checkout ok" total_fee=request.cart.total_price() BOUND=100.00 #shipping fee 0 if not request.session.get("free_shipping"): if total_fee>BOUND: set_shipping(request,_("Diff rate shipping"),0) else: set_shipping(request,_("Diff rate shipping"),0)
def change_shipping(request): if request.is_ajax() and request.POST: shipping = ShippingType.objects.get( id=request.POST['shipping_type_id']) # set_shipping(request, type, cost) set_shipping(request, shipping.shipping_type, shipping.shipping_cost) return HttpResponse(True, 'json') return HttpResponse(False, 'json')
def fudge_shipping_handler(request, order_form): if is_local(request): if request.cart.total_price() >= settings.FREE_SHIP_VALUE: set_shipping(request, _("Free Delivery"),0.00) else: set_shipping(request, _("Pacifica Delivery"),2.00) else: request.cart.invalid_address = True
def personalization_pricing(request, order_form, order): set_personalization_cost(request, 0) personalized_count = sum([item.personalization_price * item.quantity for item in order.items.iterator() if item.personalization and item.personalization.embroidery_type <> 1 and hasattr(item, 'personalization_price')]) if personalized_count: set_personalization_cost(request, personalized_count) item_total = sum([item.total_price for item in order.items.iterator()]) set_tax(request, _("Tax"), (Decimal(request.session.get('personalization_total', '0.0')) + item_total) * Decimal(.06)) set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE)
def billship_handler(request, order_form): """ Calculates Shipping(Processing) """ shipping = Decimal(0) if not request.session.get("free_shipping"): cart = Cart.objects.from_request(request) for item in cart.items.all(): if not item.sku.startswith('PRO-') and not item.sku.startswith('ORG-') and not item.sku.startswith('EVENT-'): shipping += item.unit_price * Decimal(Settings.get_setting('SHOP_DEFAULT_SHIPPING_VALUE')) set_shipping(request, "Shipping", shipping)
def billship_handler(request, order_form): cart = request.cart shipping, q = cart.cart_get_shipping() if shipping: if q == 1: set_shipping(request, "Shipping", 60.00) else: set_shipping(request, "Shipping", (60.00 + ((q - 1) * 10))) else: clear_session(request, "shipping_type", "shipping_total")
def set_discount(self): """ Assigns the session variables for the discount. """ discount = getattr(self, "_discount", None) if discount is not None: total = self._request.cart.calculate_discount(discount) if discount.free_shipping: set_shipping(self._request, _("Free shipping"), 0) self._request.session["free_shipping"] = discount.free_shipping self._request.session["discount_code"] = discount.code self._request.session["discount_total"] = total
def monkey_billship_handler(request, tip): """ Default billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ set_shipping(request, _("Tip"), tip)
def db_billship_handler(request, order_form): """ This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. """ if not request.session.get('free_shipping'): settings.use_editable() shipping_type = order_form.cleaned_data["shipping"] shipping = get_object_or_404(Shipping, title=shipping_type) set_shipping(request, shipping_type, shipping.tax_exact)
def billship_handler(request, order_form): """ If product is all downloads, do not set shipping (defaults to free). """ request.is_download_only = (not ProductVariation.objects.filter( sku__in=request.cart.skus()).exclude(**DOWNLOAD_ONLY_OPTION).exists() if DOWNLOAD_ONLY_OPTION else False) if request.is_download_only: set_shipping(request, "Free shipping", 0) else: default_billship_handler(request, order_form)
def default_billship_handler(request, order_form): """ Default billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ settings.use_editable() set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE)
def billship_handler(request, order_form): """ If product is all downloads, do not set shipping (defaults to free). """ request.is_download_only = ( not ProductVariation.objects .filter(sku__in=request.cart.skus()) .exclude(**DOWNLOAD_ONLY_OPTION) .exists() if DOWNLOAD_ONLY_OPTION else False) if request.is_download_only: set_shipping(request, "Free shipping", 0) else: default_billship_handler(request, order_form)
def default_billship_handler(request, order_form): """ Default billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ if not request.session.get('free_shipping'): settings.use_editable() set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE)
def personalization_pricing(request, order_form, order): set_personalization_cost(request, 0) personalized_count = sum([ item.personalization_price * item.quantity for item in order.items.iterator() if item.personalization and item.personalization.embroidery_type <> 1 and hasattr(item, 'personalization_price') ]) if personalized_count: set_personalization_cost(request, personalized_count) item_total = sum([item.total_price for item in order.items.iterator()]) set_tax(request, _("Tax"), (Decimal(request.session.get('personalization_total', '0.0')) + item_total) * Decimal(.06)) set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE)
def billship_handler(request, order_form): """ Custom billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ```cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ if not request.session.get("free_shipping"): settings.use_editable() if order_form.cleaned_data['shipping_detail_country'].lower() in ['united states', 'usa', 'us',]: set_shipping(request, _("Shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE) else: set_shipping(request, _("Shipping"), settings.SHOP_FOREIGN_SHIPPING_VALUE)
def fretefacil_shipping_handler(request, form, order=None): if request.session.get("free_shipping"): return settings.use_editable() if form is not None: user_postcode = form.cleaned_data['shipping_detail_postcode'] else: user_postcode = settings.STORE_POSTCODE shippingservice = FreteFacilShippingService() cart = Cart.objects.from_request(request) delivery_value = 0.0 if cart.has_items(): for product in cart: properties = DeliverableProperty.objects.filter(sku=product.sku) if len(properties) > 0: props = properties[0] deliverable = shippingservice.create_deliverable(settings.STORE_POSTCODE, user_postcode, props.width, props.height, props.length, props.weight) delivery_value += float(shippingservice.delivery_value(deliverable)) set_shipping(request, _("Correios"),delivery_value)
def shipping_processor(request, form): """ If not shipping was chosen chose max price shipping If Order is more than some value c """ total_price = request.cart.total_price() # check if free shipping discount code was used free_shipping_discount = request.session.get('discount_code') if free_shipping_discount: free_shipping_discount = DiscountCode.objects.get( code=free_shipping_discount).free_shipping if not request.session.get("shipping_total") or\ (int(float(request.session.get("shipping_total"))) == 0 and not free_shipping_discount and total_price <= settings.FREE_SHIPPING_MIN_ORDER): settings.use_editable() set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE) if total_price >= settings.FREE_SHIPPING_MIN_ORDER: settings.use_editable() set_shipping(request, _("Free shipping"), 0)
def update_cart(request): if request.is_ajax() and request.method == "POST": sub = {} grand = 0 form = request.POST cart_formset = CartItemFormSet(request.POST, instance=request.cart) cart = cart_formset[0].instance.cart valid = cart_formset.is_valid() if valid: cart_formset.save() sub = [float(f.instance.total_price) for f in cart_formset] subtotal = float(cart.total_price()) discount = get_discount_on_update(request) grand = "{0:.2f}".format(subtotal - discount) total_qty = int(cart.total_quantity()) if total_qty == 0: set_shipping(request, "Shipping", 0) return HttpResponse(json.dumps({ 'sub': sub, 'subtotal': subtotal, 'grand': grand, 'total_qty': total_qty, 'discount_total': discount }), content_type='application/json') else: error = cart_formset.errors[0]['quantity'][0] cart_formset = CartItemFormSet(instance=request.cart) messages.info(request, _(error)) #cart_formset._errors = errors return HttpResponse(json.dumps({'error': error}), content_type='application/json') else: return HttpResponse('Sth went wrong.')
def correios_billship_handler(request, order_form): """ Default billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ logger.debug("integration.checkout.correios_billship_handler()") if not request.session.get("free_shipping"): settings.use_editable() # http://www.correios.com.br/webservices/default.cfm # http://www.correios.com.br/webServices/PDF/SCPP_manual_implementacao_calculo_remoto_de_precos_e_prazos.pdf client = Client( "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx?wsdl") """ 40010 = SEDEX """ origin_cep = settings.CEP_ORIGIN data = order_form.cleaned_data dest_cep = data["billing_detail_postcode"] logger.debug("cep de %s para %s" % (origin_cep, dest_cep)) # Propriedades fixas apenas para testar por enquanto result = client.service.CalcPreco("", "", 40010, origin_cep, dest_cep, "1.0", 1, 50.0, 50.0, 50.0, 50.0, "N", 0, "N") price = Decimal(result.Servicos[0][0].Valor.replace(",", ".")) logger.debug("preço %s" % price) set_shipping(request, _("SEDEX"), price)
def set_discount(self): """ Assigns the session variables for the discount. """ discount = getattr(self, "_discount", None) if discount is not None: # Clear out any previously defined discount code # session vars. names = ("free_shipping", "discount_code", "discount_total") clear_session(self._request, *names) total = self._request.cart.calculate_discount(discount) if discount.free_shipping: set_shipping(self._request, _("Free shipping"), 0) else: # A previously entered discount code providing free # shipping may have been entered prior to this # discount code beign entered, so clear out any # previously set shipping vars. clear_session(self._request, "shipping_type", "shipping_total") self._request.session["free_shipping"] = discount.free_shipping self._request.session["discount_code"] = discount.code #change by wni, change number to minus for display on page #self._request.session["discount_total"] = str(total) self._request.session["discount_total"] = str(total)
def get_carrier(request): if request.is_ajax() and request.method == 'POST': if not request.POST.get("free_shipping"): carrier = request.POST['carrier'] shipping_type = request.POST['shipping_type'] shipping_total = float(carrier.split()[3][1:]) settings.use_editable() set_shipping(request, shipping_type, shipping_total) recalculate_cart(request) else: shipping_type = 'Regular Shipping' shipping_total = 0.0 set_shipping(request, shipping_type, shipping_total) subtotal = float(request.cart.total_price()) discount = float(request.session.get('discount_total','0.00')) total = subtotal - discount + shipping_total total = "{0:.2f}".format(total) #resp = render_to_string('shop/cart.html', { 'request': request }) return HttpResponse(json.dumps({'shipping_type' : shipping_type, 'shipping_total' : shipping_total, 'total_price' : total, 'discount':discount, 'subtotal':subtotal}), content_type='application/json')
def tax_billship_handler(request, order_form): """ Tax/billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ settings.use_editable() if not request.session.get('free_shipping'): set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE) if settings.TAX_SHIPPING: tax_shipping = \ Decimal(str(request.session.get('shipping_total'))) else: tax_shipping = Decimal(0) if request.session.get('tax_total'): del request.session['tax_total'] if not settings.TAX_USE_TAXCLOUD: if settings.TAX_OUT_OF_STATE or \ request.session.get('order')['shipping_detail_state'] \ == settings.TAX_SHOP_STATE: # Use the flat rate tax_rate = Decimal(settings.TAX_FLAT_RATE) * Decimal(str(.01)) tax_total = (request.cart.total_price() + tax_shipping) * \ Decimal(tax_rate) set_salestax(request, _("Flat sales tax"), tax_total) else: # Sweet: no sales tax set_salestax(request, _("Out of state"), Decimal(0)) else: # Use TaxCloud.net SOAP service. api_key = settings.TAX_TAXCLOUD_API_KEY api_id = settings.TAX_TAXCLOUD_API_ID url = "https://api.taxcloud.net/1.0/?wsdl" client = suds.client.Client(url) order = request.session.get('order') settings.use_editable() origin = client.factory.create('Address') origin.Address1 = settings.TAX_SHOP_ADDRESS origin.Address2 = settings.TAX_SHOP_ADDRESS2 origin.City = settings.TAX_SHOP_CITY origin.State = settings.TAX_SHOP_STATE origin.Zip5 = settings.TAX_SHOP_POSTCODE origin.Zip4 = settings.TAX_SHOP_POSTCODE_PLUS4 if len(str(order['shipping_detail_postcode']).replace('-', '')) == 9: shipping_detail_postcode_plus4 = \ str(order['shipping_detail_postcode'])[:-4] shipping_detail_postcode = \ str(order['shipping_detail_postcode'])[0:5] else: shipping_detail_postcode = \ str(order['shipping_detail_postcode'])[0:5] shipping_detail_postcode_plus4 = '0000' destination = client.factory.create('Address') destination.Address1 = order['shipping_detail_street'] destination.Address2 = '' destination.City = order['shipping_detail_city'] destination.State = order['shipping_detail_state'] destination.Zip5 = shipping_detail_postcode destination.Zip4 = shipping_detail_postcode_plus4 ArrayOfCartItem = client.factory.create('ArrayOfCartItem') items = CartItem.objects.filter(cart_id=request.session.get('cart')) for idx, item in enumerate(items): cartItem = client.factory.create('CartItem') cartItem.Index = idx + 1 cartItem.ItemID = str(item.sku) productVariation = ProductVariation.objects.get(sku=item.sku) product = Product.objects.get(id=productVariation.product_id) cartItem.TIC = int(product.tic) cartItem.Price = float(item.unit_price) cartItem.Qty = float(item.quantity) ArrayOfCartItem.CartItem.append(cartItem) shipping = client.factory.create('CartItem') shipping.Index = len(items) + 1 shipping.ItemID = str('shipping') shipping.TIC = int(11010) shipping.Price = float(tax_shipping) shipping.Qty = float(1) ArrayOfCartItem.CartItem.append(shipping) cartID = uuid4() request.session['cartID'] = cartID request.session.modified = True try: result = client.service.Lookup(str(api_id), str(api_key), str(request.user.id), cartID, ArrayOfCartItem, origin, destination, False) tax_total = 0 except: raise CheckoutError("Unable to contact the TaxCloud \ server.") if str(result.ResponseType) == 'OK' and \ result.CartID == cartID: for CartItemResponse in result.CartItemsResponse[0]: tax_total += CartItemResponse.TaxAmount else: raise CheckoutError(result.Messages) print tax_total set_salestax(request, _("Sales tax for shipping address"), tax_total)
def tax_billship_handler(request, order_form): """ Tax/billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ settings.use_editable() if not request.session.get('free_shipping'): set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE) if settings.TAX_SHIPPING: tax_shipping = \ Decimal(str(request.session.get('shipping_total'))) else: tax_shipping = Decimal(0) if not settings.TAX_USE_TAXCLOUD: if settings.TAX_OUT_OF_STATE or \ request.session.get('order')['shipping_detail_state'] \ == settings.TAX_SHOP_STATE: # Use the flat rate tax_rate = Decimal(settings.TAX_FLAT_RATE) * Decimal(str(.01)) total_tax = (request.cart.total_price() + tax_shipping) * \ Decimal(tax_rate) set_salestax(request, _("Flat sales tax"), total_tax) else: # Sweet: no sales tax set_salestax(request, _("Out of state"), Decimal(0)) else: # Use TaxCloud.net SOAP service. api_key = settings.TAXCLOUD_API_KEY api_id = settings.TAXCLOUD_API_ID order = request.session.get('order') settings.use_editable() origin = (settings.TAX_SHOP_ADDRESS, settings.TAX_SHOP_ADDRESS2, settings.TAX_SHOP_CITY, settings.TAX_SHOP_STATE, settings.TAX_SHOP_POSTCODE, settings.TAX_SHOP_POSTCODE_PLUS4,) if len(str(order['shipping_detail_postcode']).replace('-','')) == 9: shipping_detail_postcode_plus4 = str(order['shipping_detail_postcode'])[:-4] shipping_detail_postcode = str(order['shipping_detail_postcode'])[0:4] else: shipping_detail_postcode = str(order['shipping_detail_postcode'])[0:4] shipping_detail_postcode_plus4 = '0000' destination = [ order['shipping_detail_street'], '', order['shipping_detail_city'], order['shipping_detail_state'], shipping_detail_postcode, shipping_detail_postcode_plus4, ] cartItems = [] items = CartItem.objects.filter(cart_id=request.session.get('cart')) for idx, item in enumerate(items): index = idx itemId = str(item.sku) productVariation = ProductVariation.objects.get(sku=itemId) product = Product.objects.get(id=productVariation.product_id) tic = str(product.tic) price = str(item.unit_price) quantity = item.quantity cartItem = (index, itemId, tic, price, quantity) cartItems.append(cartItem) shipping = (len(items) + 1, 'shipping', '11010', str(tax_shipping), 1) cartItems.append(shipping) url = "https://api.taxcloud.net/1.0/?wsdl" client = suds.client.Client(url) tax_total = client.service.Lookup(api_id, api_key, request.user.id, request.session.get('cart'), cartItems, origin, destination) set_salestax(request, tax_type, tax_total)
def billship_handler(request, order_form): """ Called when the first step in the checkout process with billing/shipping address fields is submitted. Relevant setting: ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ settings.use_editable() wholesale_logged_in = False user_fullname = "" if request.user.is_authenticated(): user_fullname = " ".join([request.user.first_name, request.user.last_name]) if request.user.has_perm('custom.wholesale_customer'): wholesale_logged_in = True total = float(request.cart.total_price()) country = order_form["shipping_detail_country"].value() if wholesale_logged_in: if country == "GB": if total < 150.00: set_shipping(request, "UK delivery, Courier service 1-2 days", 15.50) elif total >= 150.00 and total < 500.00: set_shipping(request, "UK Free delivery, Courier service 1-2 days", 0.00) elif total >= 500.00: set_shipping(request, "UK Free delivery, Courier service 1-2 days", 0.00) elif country in europe: if total < 350.00: set_shipping(request, "EU delivery, Courier service 2-5 days", 35.00) elif order >= 350: set_shipping(request, "EU Free delivery, Courier service 2-5 days", 0.00) else: #international if total < 55.00: set_shipping(request, "International Delivery", 13.50) elif total >= 55.00 and total < 150.00: set_shipping(request, "International Delivery", 25.00) elif total >= 150.00: raise checkout.CheckoutError, 'Sorry, we do not accept online orders of that amount from outside Europe, because of prohibitive delivery costs. However, please get in touch by calling +44 7624 482 582, sending an email to [email protected], or using our online contact form.' else: # retail uk_delivery_rate = float(order_form["uk_delivery_rate"].value()) if country == "GB": if total < 55.00: if uk_delivery_rate == 4.00: set_shipping(request, "UK Royal Mail Recorded 1st Class 3-5 days", 4.00) elif uk_delivery_rate == 7.5: set_shipping(request, "UK Royal Mail Special Delivery 1-2 days", 7.50) elif total >= 55.00 and total < 150.00: set_shipping(request, "UK Courier Service 1-2 days", 13.50) elif total >= 150.00: set_shipping(request, "UK Courier Service 1-2 days", 13.50) elif country in europe: if total < 55.00: set_shipping(request, "EU Royal Mail Special Delivery 3-5 days", 13.50) elif total >= 55.00 and total < 150.00: set_shipping(request, "EU Courier Service 3-5 days", 25.00) elif total >= 150.00: set_shipping(request, "EU Free delivery, Courier Service 3-5 days", 0.00) else: #international if total < 55.00: set_shipping(request, "International Delivery", 13.50) elif total >= 55.00 and total < 150.00: set_shipping(request, "International Delivery", 25.00) # plus 5% discount elif total >= 150.00: raise checkout.CheckoutError, 'Sorry, we do not accept online orders of that amount from outside Europe, because of prohibitive delivery costs. However, please get in touch by calling +44 7624 482 582, sending an email to [email protected], or using our online contact form.'
def billship_handler(request, order_form): from mezzanine.conf import settings from cartridge.shop.utils import set_shipping, sign settings.use_editable() set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE)
def billing_shipping(request, order_form): """ Implement shipping handling here. """ # Cart is also accessible via shop.Cart.objects.from_request(request) set_shipping(request, "Shipping Test", 10)
def checkout_steps(request): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return HttpResponseRedirect(url) step = int(request.POST.get("step", checkout.CHECKOUT_STEP_FIRST)) initial = checkout.initial_order_data(request) form = OrderForm(request, step, initial=initial) data = request.POST checkout_errors = [] if request.POST.get("back") is not None: # Back button was pressed - load the order form for the # previous step and maintain the field values entered. step -= 1 form = OrderForm(request, step, initial=initial) elif request.method == "POST": form = OrderForm(request, step, initial=initial, data=data) if form.is_valid(): # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the cart number so that they're never stored # anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: try: billship_handler(request, form) except checkout.CheckoutError, e: checkout_errors.append(e) # The order form gets assigned a discount attribute # when the discount_code field is validated via # clean_discount_code() discount = getattr(form, "discount", None) if discount is not None: cart = Cart.objects.from_request(request) discount_total = discount.calculate(cart.total_price()) if discount.free_shipping: set_shipping(request, _("Free shipping"), 0) request.session["free_shipping"] = discount.free_shipping request.session["discount_total"] = discount_total # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the inital order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order reciept email. order = form.save(commit=False) order.setup(request) # Try payment. try: payment_handler(request, form, order) except checkout.CheckoutError, e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = HttpResponseRedirect(reverse("shop_complete")) if form.cleaned_data.get("remember") is not None: remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = OrderForm(request, step, initial=initial, data=data, errors=checkout_errors) if form.is_valid(): step += 1 form = OrderForm(request, step, initial=initial)
def tax_billship_handler(request, order_form): """ Tax/billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ settings.use_editable() if not request.session.get('free_shipping'): set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE) if settings.TAX_SHIPPING: tax_shipping = \ Decimal(str(request.session.get('shipping_total'))) else: tax_shipping = Decimal(0) if request.session.get('tax_total'): del request.session['tax_total'] if not settings.TAX_USE_TAXCLOUD: if settings.TAX_OUT_OF_STATE or \ request.session.get('order')['shipping_detail_state'] \ == settings.TAX_SHOP_STATE: # Use the flat rate tax_rate = Decimal(settings.TAX_FLAT_RATE) * Decimal(str(.01)) tax_total = (request.cart.total_price() + tax_shipping) * \ Decimal(tax_rate) set_salestax(request, _("Flat sales tax"), tax_total) else: # Sweet: no sales tax set_salestax(request, _("Out of state"), Decimal(0)) else: # Use TaxCloud.net SOAP service. api_key = settings.TAX_TAXCLOUD_API_KEY api_id = settings.TAX_TAXCLOUD_API_ID url = "https://api.taxcloud.net/1.0/?wsdl" client = suds.client.Client(url) order = request.session.get('order') settings.use_editable() origin = client.factory.create('Address') origin.Address1 = settings.TAX_SHOP_ADDRESS origin.Address2 = settings.TAX_SHOP_ADDRESS2 origin.City = settings.TAX_SHOP_CITY origin.State = settings.TAX_SHOP_STATE origin.Zip5 = settings.TAX_SHOP_POSTCODE origin.Zip4 = settings.TAX_SHOP_POSTCODE_PLUS4 if len(str(order['shipping_detail_postcode']).replace('-','')) == 9: shipping_detail_postcode_plus4 = \ str(order['shipping_detail_postcode'])[:-4] shipping_detail_postcode = \ str(order['shipping_detail_postcode'])[0:5] else: shipping_detail_postcode = \ str(order['shipping_detail_postcode'])[0:5] shipping_detail_postcode_plus4 = '0000' destination = client.factory.create('Address') destination.Address1 = order['shipping_detail_street'] destination.Address2 = '' destination.City = order['shipping_detail_city'] destination.State = order['shipping_detail_state'] destination.Zip5 = shipping_detail_postcode destination.Zip4 = shipping_detail_postcode_plus4 ArrayOfCartItem = client.factory.create('ArrayOfCartItem') items = CartItem.objects.filter(cart_id=request.session.get('cart')) for idx, item in enumerate(items): cartItem = client.factory.create('CartItem') cartItem.Index = idx + 1 cartItem.ItemID = str(item.sku) productVariation = ProductVariation.objects.get(sku=item.sku) product = Product.objects.get(id=productVariation.product_id) cartItem.TIC = int(product.tic) cartItem.Price = float(item.unit_price) cartItem.Qty = float(item.quantity) ArrayOfCartItem.CartItem.append(cartItem) shipping = client.factory.create('CartItem') shipping.Index = len(items) + 1 shipping.ItemID = str('shipping') shipping.TIC = int(11010) shipping.Price = float(tax_shipping) shipping.Qty = float(1) ArrayOfCartItem.CartItem.append(shipping) cartID = uuid4() request.session['cartID'] = cartID request.session.modified = True try: result = client.service.Lookup(str(api_id), str(api_key), str(request.user.id), cartID, ArrayOfCartItem, origin, destination, False ) tax_total = 0 except: raise CheckoutError("Unable to contact the TaxCloud \ server.") if str(result.ResponseType) == 'OK' and \ result.CartID == cartID: for CartItemResponse in result.CartItemsResponse[0]: tax_total += CartItemResponse.TaxAmount else: raise CheckoutError(result.Messages) print tax_total set_salestax(request, _("Sales tax for shipping address"), tax_total)