/// <summary> /// Create packages (total dimensions of shopping cart items determines number of packages) /// </summary> /// <param name="shippingOptionRequest">shipping option request</param> /// <returns>Packages</returns> private IEnumerable<UPSRate.PackageType> GetPackagesByDimensions(GetShippingOptionRequest shippingOptionRequest) { //get dimensions and weight of the whole package var (width, length, height) = GetDimensions(shippingOptionRequest.Items); var weight = GetWeight(shippingOptionRequest); //whether the package doesn't exceed the weight and size limits if (weight <= WEIGHT_LIMIT && GetPackageSize(width, length, height) <= SIZE_LIMIT) { var insuranceAmount = 0; if (_upsSettings.InsurePackage) { //The maximum declared amount per package: 50000 USD. //use subTotalWithoutDiscount as insured value var cart = shippingOptionRequest.Items.Select(item => { var shoppingCartItem = item.ShoppingCartItem; shoppingCartItem.Quantity = item.GetQuantity(); return shoppingCartItem; }).ToList(); _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false, out var _, out var _, out var subTotalWithoutDiscount, out var _); insuranceAmount = Convert.ToInt32(subTotalWithoutDiscount); } return new[] { CreatePackage(width, length, height, weight, insuranceAmount) }; } //get total packages number according to package limits var totalPackagesByWeightLimit = weight > WEIGHT_LIMIT ? Convert.ToInt32(Math.Ceiling(weight / WEIGHT_LIMIT)) : 1; var totalPackagesBySizeLimit = GetPackageSize(width, length, height) > SIZE_LIMIT ? Convert.ToInt32(Math.Ceiling(GetPackageSize(width, length, height) / LENGTH_LIMIT)) : 1; var totalPackages = Math.Max(Math.Max(totalPackagesBySizeLimit, totalPackagesByWeightLimit), 1); width = Math.Max(width / totalPackages, 1); length = Math.Max(length / totalPackages, 1); height = Math.Max(height / totalPackages, 1); weight = Math.Max(weight / totalPackages, 1); var insuranceAmountPerPackage = 0; if (_upsSettings.InsurePackage) { //The maximum declared amount per package: 50000 USD. //use subTotalWithoutDiscount as insured value var cart = shippingOptionRequest.Items.Select(item => { var shoppingCartItem = item.ShoppingCartItem; shoppingCartItem.Quantity = item.GetQuantity(); return shoppingCartItem; }).ToList(); _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false, out var _, out var _, out var subTotalWithoutDiscount, out var _); insuranceAmountPerPackage = Convert.ToInt32(subTotalWithoutDiscount / totalPackages); } //create packages according to calculated value var package = CreatePackage(width, length, height, weight, insuranceAmountPerPackage); return Enumerable.Repeat(package, totalPackages); }
public decimal GetCartItemTotal(IList <ShoppingCartItem> cart) { decimal discountAmount; List <Discount> appliedDiscounts; decimal subTotalWithoutDiscount; decimal subTotalWithDiscount; _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false, out discountAmount, out appliedDiscounts, out subTotalWithoutDiscount, out subTotalWithDiscount); return(subTotalWithDiscount); }
public void CanGetShoppingCartSubTotalExcludingTax() { //10% - default tax rate _orderTotalCalcService.GetShoppingCartSubTotal(ShoppingCart, false, out var discountAmount, out var appliedDiscounts, out var subTotalWithoutDiscount, out var subTotalWithDiscount, out var taxRates); discountAmount.Should().Be(0); appliedDiscounts.Count.Should().Be(0); subTotalWithoutDiscount.Should().Be(207M); subTotalWithDiscount.Should().Be(207M); taxRates.Count.Should().Be(1); taxRates.ContainsKey(10).Should().BeTrue(); taxRates[10].Should().Be(20.7M); }
public bool Match(CartRuleContext context, RuleExpression expression) { var result = true; // We must prevent the rule from indirectly calling itself. It would cause a stack overflow on cart page // and wrong discount calculation (due to MergeWithCombination, if the cart contains a product several times). if (Interlocked.CompareExchange(ref _reentrancyNum, 1, 0) == 0) { try { var cart = _shoppingCartService.GetCartItems(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id); _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out _, out _, out var cartSubtotal, out _); // Currency values must be rounded, otherwise unexpected results may occur. var money = new Money(cartSubtotal, context.WorkContext.WorkingCurrency); cartSubtotal = money.RoundedAmount; result = expression.Operator.Match(cartSubtotal, expression.Value); } finally { _reentrancyNum = 0; } } return(result); }
public bool Match(CartRuleContext context, RuleExpression expression) { var lockKey = $"rule:cart:cartsubtotalrule:{Thread.CurrentThread.ManagedThreadId}-{expression.Id}"; if (KeyedLock.IsLockHeld(lockKey)) { //$"locked: {lockKey}".Dump(); return(false); } // We must prevent the rule from indirectly calling itself. It would cause a stack overflow on cart page. using (KeyedLock.Lock(lockKey)) { var cart = _shoppingCartService.GetCartItems(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id); _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out _, out _, out var cartSubtotal, out _); // Currency values must be rounded, otherwise unexpected results may occur. var money = new Money(cartSubtotal, context.WorkContext.WorkingCurrency); cartSubtotal = money.RoundedAmount; var result = expression.Operator.Match(cartSubtotal, expression.Value); //$"unlocked {result}: {lockKey}".Dump(); return(result); } }
/// <summary> /// Calculate payment method fee /// </summary> /// <param name="paymentMethod">Payment method</param> /// <param name="orderTotalCalculationService">Order total calculation service</param> /// <param name="cart">Shopping cart</param> /// <param name="fee">Fee value</param> /// <param name="usePercentage">Is fee amount specified as percentage or fixed value?</param> /// <returns>Result</returns> public static decimal CalculateAdditionalFee(this IPaymentMethod paymentMethod, IOrderTotalCalculationService orderTotalCalculationService, IList <ShoppingCartItem> cart, decimal fee, bool usePercentage) { if (paymentMethod == null) { throw new ArgumentNullException("paymentMethod"); } if (fee <= 0) { return(fee); } decimal result; if (usePercentage) { //percentage orderTotalCalculationService.GetShoppingCartSubTotal(cart, true, out decimal discountAmount, out List <AppliedDiscount> appliedDiscounts, out decimal subTotalWithoutDiscount, out decimal subTotalWithDiscount); result = (decimal)((((float)subTotalWithDiscount) * ((float)fee)) / 100f); } else { //fixed value result = fee; } return(result); }
protected virtual async Task <bool> ValidateMinOrderSubtotalAmount(IList <ShoppingCartItem> cart) { if (cart == null) { throw new ArgumentNullException("cart"); } if (!cart.Any()) { return(false); } //min order amount sub-total validation if (cart.Any() && _orderSettings.MinOrderSubtotalAmount > decimal.Zero) { //subtotal var(_, _, subTotalWithoutDiscount, _, _) = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false); if (subTotalWithoutDiscount < _orderSettings.MinOrderSubtotalAmount) { return(false); } } return(true); }
public void Can_get_shopping_cart_subTotal_excluding_tax() { //customer var customer = _customerService.GetCustomerById(1); //shopping cart var product1 = new Product { Name = "Product name 1", Price = 12.34M, CustomerEntersPrice = false, Published = true }; _productService.InsertProduct(product1); var sci1 = new ShoppingCartItem { ProductId = product1.Id, Quantity = 2 }; var product2 = new Product { Name = "Product name 2", Price = 21.57M, CustomerEntersPrice = false, Published = true }; _productService.InsertProduct(product2); var sci2 = new ShoppingCartItem { ProductId = product2.Id, Quantity = 3 }; var cart = new List <ShoppingCartItem> { sci1, sci2 }; cart.ForEach(sci => sci.CustomerId = customer.Id); //10% - default tax rate _orderTotalCalcService.GetShoppingCartSubTotal(cart, false, out var discountAmount, out var appliedDiscounts, out var subTotalWithoutDiscount, out var subTotalWithDiscount, out var taxRates); discountAmount.Should().Be(0); appliedDiscounts.Count.Should().Be(0); subTotalWithoutDiscount.Should().Be(89.39M); subTotalWithDiscount.Should().Be(89.39M); taxRates.Count.Should().Be(1); taxRates.ContainsKey(10).Should().BeTrue(); taxRates[10].Should().Be(8.939M); }
/// <summary> /// Create item for discount to order subtotal /// </summary> /// <param name="shoppingCart">Shopping cart</param> /// <returns>PayPal item</returns> protected Item CreateItemForSubtotalDiscount(IList <ShoppingCartItem> shoppingCart) { //get subtotal discount amount _orderTotalCalculationService.GetShoppingCartSubTotal(shoppingCart, false, out decimal discountAmount, out List <DiscountForCaching> _, out decimal _, out decimal _); if (discountAmount <= decimal.Zero) { return(null); } //create item with negative price return(new Item { name = "Discount for the subtotal of order", price = (-discountAmount).ToString("N", new CultureInfo("en-US")), quantity = "1" }); }
private async Task PrepareSubtotal(OrderTotalsModel model, GetOrderTotals request) { var subTotalIncludingTax = request.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal; var shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(request.Cart, subTotalIncludingTax); model.SubTotal = _priceFormatter.FormatPrice(shoppingCartSubTotal.subTotalWithoutDiscount, true, request.Currency, request.Language, subTotalIncludingTax); if (shoppingCartSubTotal.discountAmount > decimal.Zero) { model.SubTotalDiscount = _priceFormatter.FormatPrice(-shoppingCartSubTotal.discountAmount, true, request.Currency, request.Language, subTotalIncludingTax); } }
public bool Match(CartRuleContext context, RuleExpression expression) { var cart = _shoppingCartService.GetCartItems(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id); _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out _, out _, out var cartSubtotal, out _); // Currency values must be rounded, otherwise unexpected results may occur. var money = new Money(cartSubtotal, context.WorkContext.WorkingCurrency); cartSubtotal = money.RoundedAmount; return(expression.Operator.Match(cartSubtotal, expression.Value)); }
private decimal GetRate(decimal price) { var cartItems = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); _orderTotalCalculationService.GetShoppingCartSubTotal(cartItems, true, out var orderSubTotalDiscountAmount, out var orderSubTotalAppliedDiscounts, out var subTotalWithoutDiscountBase, out var _); if (_glsSettings.FreeShippingLimit > 0 && subTotalWithoutDiscountBase > _glsSettings.FreeShippingLimit) { return(0); } Currency eurCurrency = _currencyService.GetCurrencyByCode("EUR", true); decimal storePrice = _currencyService.ConvertToPrimaryStoreCurrency(price, eurCurrency); return(storePrice.AdjustPriceToPresentation(_glsSettings.PricesEndsWith)); }
private RateRequest CreateRateRequest(GetShippingOptionRequest getShippingOptionRequest) { // Build the RateRequest var request = new RateRequest(); request.WebAuthenticationDetail = new WebAuthenticationDetail(); request.WebAuthenticationDetail.UserCredential = new WebAuthenticationCredential(); request.WebAuthenticationDetail.UserCredential.Key = _fedexSettings.Key; request.WebAuthenticationDetail.UserCredential.Password = _fedexSettings.Password; request.ClientDetail = new ClientDetail(); request.ClientDetail.AccountNumber = _fedexSettings.AccountNumber; request.ClientDetail.MeterNumber = _fedexSettings.MeterNumber; request.TransactionDetail = new TransactionDetail(); request.TransactionDetail.CustomerTransactionId = "***Rate Available Services v7 Request - nopCommerce***"; // This is a reference field for the customer. Any value can be used and will be provided in the response. request.Version = new VersionId(); // WSDL version information, value is automatically set from wsdl request.ReturnTransitAndCommit = true; request.ReturnTransitAndCommitSpecified = true; request.CarrierCodes = new CarrierCodeType[2]; // Insert the Carriers you would like to see the rates for request.CarrierCodes[0] = CarrierCodeType.FDXE; request.CarrierCodes[1] = CarrierCodeType.FDXG; decimal subtotalBase = decimal.Zero; decimal orderSubTotalDiscountAmount = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); subtotalBase = subTotalWithDiscountBase; SetShipmentDetails(request, getShippingOptionRequest, subtotalBase); SetOrigin(request); SetDestination(request, getShippingOptionRequest); SetPayment(request, getShippingOptionRequest); SetIndividualPackageLineItems(request, getShippingOptionRequest, subtotalBase); return(request); }
public ActionResult Index() { AffiliateProgram program = new AffiliateProgram(); ProgramCondition condition = new ProgramCondition(); condition.Name = "CartTotal"; condition.Operation = LogicalOperation.Is; condition.Value = "10"; condition.AffiliateProgram = program; //_affiliateProgramService.InsertAffiliateProgram(program); //_affiliateProgramService.InsertProgramCondition(condition); program = _affiliateProgramService.GetAffiliateProgramById(1); Order order = new Order { OrderTotal = 10 }; var cart = _workContext.CurrentCustomer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id) .ToList(); decimal orderSubTotalDiscountAmountBase; Discount orderSubTotalAppliedDiscount; decimal subTotalWithoutDiscountBase; decimal subTotalWithDiscountBase; var subTotalIncludingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal; _orderTotalCalculationService.GetShoppingCartSubTotal(cart, subTotalIncludingTax, out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); decimal subtotalBase = subTotalWithoutDiscountBase; decimal subtotal = _currencyService.ConvertFromPrimaryStoreCurrency(subtotalBase, _workContext.WorkingCurrency); var subTotal = _priceFormatter.FormatPrice(subtotal, true, _workContext.WorkingCurrency, _workContext.WorkingLanguage, subTotalIncludingTax); //_affiliateProgramService.VerifyQualificaion(program, order); var valueType = "qwer".GetType().IsValueType; var ans = CompareReferenceTypes <string, string> ("<=", "15.", "12.33"); //_shoppingCartService. return(View()); }
private decimal GetCartTotalPrice() { var cart = GetCartItems().ToList(); decimal orderSubTotalDiscountAmountBase; Discount orderSubTotalAppliedDiscount; decimal subTotalWithoutDiscountBase; decimal subTotalWithDiscountBase; var subTotalIncludingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal; _orderTotalCalculationService.GetShoppingCartSubTotal(cart, subTotalIncludingTax, out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); decimal subtotalBase = subTotalWithoutDiscountBase; decimal subtotal = _currencyService.ConvertFromPrimaryStoreCurrency(subtotalBase, _workContext.WorkingCurrency); var subTotalFormated = _priceFormatter.FormatPrice(subtotal, true, _workContext.WorkingCurrency, _workContext.WorkingLanguage, subTotalIncludingTax); var totalProducts = cart.GetTotalProducts(); return(subtotal); }
/// <summary> /// Gets additional handling fee /// </summary> /// <param name="cart">Shoping cart</param> /// <returns>Additional handling fee</returns> public async Task <decimal> GetAdditionalHandlingFee(IList <ShoppingCartItem> cart) { if (_brainTreePaymentSettings.AdditionalFee <= 0) { return(_brainTreePaymentSettings.AdditionalFee); } decimal result; if (_brainTreePaymentSettings.AdditionalFeePercentage) { //percentage var subtotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, true); result = (decimal)((((float)subtotal.subTotalWithDiscount) * ((float)_brainTreePaymentSettings.AdditionalFee)) / 100f); } else { //fixed value result = _brainTreePaymentSettings.AdditionalFee; } //return result; return(await Task.FromResult(result)); }
/// <summary> /// Prepare tax details by Avalara tax service /// </summary> /// <param name="cart">Shopping cart</param> private void PrepareTaxDetails(IList <ShoppingCartItem> cart) { //ensure that Avalara tax provider is active var taxProvider = _taxPluginManager .LoadPluginBySystemName(AvalaraTaxDefaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id) as AvalaraTaxProvider; if (!_taxPluginManager.IsPluginActive(taxProvider)) { return; } //create dummy order for the tax request var order = new Order { Customer = _workContext.CurrentCustomer }; //addresses order.BillingAddress = _workContext.CurrentCustomer.BillingAddress; order.ShippingAddress = _workContext.CurrentCustomer.ShippingAddress; if (_shippingSettings.AllowPickupInStore) { var pickupPoint = _genericAttributeService.GetAttribute <PickupPoint>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedPickupPointAttribute, _storeContext.CurrentStore.Id); if (pickupPoint != null) { var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode); order.PickupAddress = new Address { Address1 = pickupPoint.Address, City = pickupPoint.City, Country = country, StateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id), ZipPostalCode = pickupPoint.ZipPostalCode, CreatedOnUtc = DateTime.UtcNow, }; } } //checkout attributes order.CheckoutAttributesXml = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer, NopCustomerDefaults.CheckoutAttributes, _storeContext.CurrentStore.Id); //shipping method var shippingRateComputationMethods = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id); order.OrderShippingExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(cart, false, shippingRateComputationMethods) ?? 0; order.ShippingMethod = _genericAttributeService.GetAttribute <ShippingOption>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedShippingOptionAttribute, _storeContext.CurrentStore.Id)?.Name; //payment method var paymentMethod = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id); var paymentFee = _paymentService.GetAdditionalHandlingFee(cart, paymentMethod); order.PaymentMethodAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentFee, false, _workContext.CurrentCustomer); order.PaymentMethodSystemName = paymentMethod; //add discount amount _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false, out var orderSubTotalDiscountExclTax, out _, out _, out _); order.OrderSubTotalDiscountExclTax = orderSubTotalDiscountExclTax; //create dummy order items foreach (var cartItem in cart) { var orderItem = new OrderItem { AttributesXml = cartItem.AttributesXml, Product = cartItem.Product, Quantity = cartItem.Quantity }; var itemSubtotal = _priceCalculationService.GetSubTotal(cartItem, true, out _, out _, out _); orderItem.PriceExclTax = _taxService.GetProductPrice(cartItem.Product, itemSubtotal, false, _workContext.CurrentCustomer, out _); order.OrderItems.Add(orderItem); } //get tax details var taxTransaction = taxProvider.CreateOrderTaxTransaction(order, false); if (taxTransaction == null) { return; } //and save it for the further usage var taxDetails = new TaxDetails { TaxTotal = taxTransaction.totalTax }; foreach (var item in taxTransaction.summary) { if (!item.rate.HasValue || !item.tax.HasValue) { continue; } var taxRate = item.rate.Value * 100; var taxValue = item.tax.Value; if (!taxDetails.TaxRates.ContainsKey(taxRate)) { taxDetails.TaxRates.Add(taxRate, taxValue); } else { taxDetails.TaxRates[taxRate] = taxDetails.TaxRates[taxRate] + taxValue; } } _httpContextAccessor.HttpContext.Session.Set(AvalaraTaxDefaults.TaxDetailsSessionValue, taxDetails); }
private RateRequest CreateRateRequest(GetShippingOptionRequest getShippingOptionRequest, out Currency requestedShipmentCurrency) { // Build the RateRequest var request = new RateRequest(); request.WebAuthenticationDetail = new RateServiceWebReference.WebAuthenticationDetail(); request.WebAuthenticationDetail.UserCredential = new RateServiceWebReference.WebAuthenticationCredential(); request.WebAuthenticationDetail.UserCredential.Key = _fedexSettings.Key; request.WebAuthenticationDetail.UserCredential.Password = _fedexSettings.Password; request.ClientDetail = new RateServiceWebReference.ClientDetail(); request.ClientDetail.AccountNumber = _fedexSettings.AccountNumber; request.ClientDetail.MeterNumber = _fedexSettings.MeterNumber; request.TransactionDetail = new RateServiceWebReference.TransactionDetail(); request.TransactionDetail.CustomerTransactionId = "***Rate Available Services v7 Request***"; // This is a reference field for the customer. Any value can be used and will be provided in the response. request.Version = new RateServiceWebReference.VersionId(); // WSDL version information, value is automatically set from wsdl request.ReturnTransitAndCommit = true; request.ReturnTransitAndCommitSpecified = true; request.CarrierCodes = new RateServiceWebReference.CarrierCodeType[2]; // Insert the Carriers you would like to see the rates for request.CarrierCodes[0] = RateServiceWebReference.CarrierCodeType.FDXE; request.CarrierCodes[1] = RateServiceWebReference.CarrierCodeType.FDXG; decimal subTotalBase = decimal.Zero; decimal orderSubTotalDiscountAmount = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); subTotalBase = subTotalWithDiscountBase; request.RequestedShipment = new RequestedShipment(); SetOrigin(request, getShippingOptionRequest); SetDestination(request, getShippingOptionRequest); requestedShipmentCurrency = GetRequestedShipmentCurrency( request.RequestedShipment.Shipper.Address.CountryCode, // origin request.RequestedShipment.Recipient.Address.CountryCode); // destination decimal subTotalShipmentCurrency; var primaryStoreCurrency = _services.StoreContext.CurrentStore.PrimaryStoreCurrency; if (requestedShipmentCurrency.CurrencyCode == primaryStoreCurrency.CurrencyCode) { subTotalShipmentCurrency = subTotalBase; } else { subTotalShipmentCurrency = _currencyService.ConvertFromPrimaryStoreCurrency(subTotalBase, requestedShipmentCurrency); } Debug.WriteLine(String.Format("SubTotal (Primary Currency) : {0} ({1})", subTotalBase, primaryStoreCurrency.CurrencyCode)); Debug.WriteLine(String.Format("SubTotal (Shipment Currency): {0} ({1})", subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode)); SetShipmentDetails(request, getShippingOptionRequest, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode); SetPayment(request, getShippingOptionRequest); switch (_fedexSettings.PackingType) { case PackingType.PackByOneItemPerPackage: SetIndividualPackageLineItemsOneItemPerPackage(request, getShippingOptionRequest, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode); break; case PackingType.PackByVolume: SetIndividualPackageLineItemsCubicRootDimensions(request, getShippingOptionRequest, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode); break; case PackingType.PackByDimensions: default: SetIndividualPackageLineItems(request, getShippingOptionRequest, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode); break; } return(request); }
private string CreateRequest(string accessKey, string username, string password, GetShippingOptionRequest getShippingOptionRequest, UPSCustomerClassification customerClassification, UPSPickupType pickupType, UPSPackagingType packagingType) { var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword(MEASUREWEIGHTSYSTEMKEYWORD); if (usedMeasureWeight == null) { throw new NopException(string.Format("UPS shipping service. Could not load \"{0}\" measure weight", MEASUREWEIGHTSYSTEMKEYWORD)); } var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword(MEASUREDIMENSIONSYSTEMKEYWORD); if (usedMeasureDimension == null) { throw new NopException(string.Format("UPS shipping service. Could not load \"{0}\" measure dimension", MEASUREDIMENSIONSYSTEMKEYWORD)); } int length = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalLength(), usedMeasureDimension))); int height = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalHeight(), usedMeasureDimension))); int width = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalWidth(), usedMeasureDimension))); int weight = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureWeight(_shippingService.GetShoppingCartTotalWeight(getShippingOptionRequest.Items), usedMeasureWeight))); if (length < 1) { length = 1; } if (height < 1) { height = 1; } if (width < 1) { width = 1; } if (weight < 1) { weight = 1; } string zipPostalCodeFrom = getShippingOptionRequest.ZipPostalCodeFrom; string zipPostalCodeTo = getShippingOptionRequest.ShippingAddress.ZipPostalCode; string countryCodeFrom = getShippingOptionRequest.CountryFrom.TwoLetterIsoCode; string countryCodeTo = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode; decimal orderSubTotalDiscountAmount = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); var sb = new StringBuilder(); sb.Append("<?xml version='1.0'?>"); sb.Append("<AccessRequest xml:lang='en-US'>"); sb.AppendFormat("<AccessLicenseNumber>{0}</AccessLicenseNumber>", accessKey); sb.AppendFormat("<UserId>{0}</UserId>", username); sb.AppendFormat("<Password>{0}</Password>", password); sb.Append("</AccessRequest>"); sb.Append("<?xml version='1.0'?>"); sb.Append("<RatingServiceSelectionRequest xml:lang='en-US'>"); sb.Append("<Request>"); sb.Append("<TransactionReference>"); sb.Append("<CustomerContext>Bare Bones Rate Request</CustomerContext>"); sb.Append("<XpciVersion>1.0001</XpciVersion>"); sb.Append("</TransactionReference>"); sb.Append("<RequestAction>Rate</RequestAction>"); sb.Append("<RequestOption>Shop</RequestOption>"); sb.Append("</Request>"); if (String.Equals(countryCodeFrom, "US", StringComparison.InvariantCultureIgnoreCase) == true) { sb.Append("<PickupType>"); sb.AppendFormat("<Code>{0}</Code>", GetPickupTypeCode(pickupType)); sb.Append("</PickupType>"); sb.Append("<CustomerClassification>"); sb.AppendFormat("<Code>{0}</Code>", GetCustomerClassificationCode(customerClassification)); sb.Append("</CustomerClassification>"); } sb.Append("<Shipment>"); sb.Append("<Shipper>"); sb.Append("<Address>"); sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom); sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom); sb.Append("</Address>"); sb.Append("</Shipper>"); sb.Append("<ShipTo>"); sb.Append("<Address>"); sb.Append("<ResidentialAddressIndicator/>"); sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeTo); sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeTo); sb.Append("</Address>"); sb.Append("</ShipTo>"); sb.Append("<ShipFrom>"); sb.Append("<Address>"); sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom); sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom); sb.Append("</Address>"); sb.Append("</ShipFrom>"); sb.Append("<Service>"); sb.Append("<Code>03</Code>"); sb.Append("</Service>"); if ((!IsPackageTooHeavy(weight)) && (!IsPackageTooLarge(length, height, width))) { sb.Append("<Package>"); sb.Append("<PackagingType>"); sb.AppendFormat("<Code>{0}</Code>", GetPackagingTypeCode(packagingType)); sb.Append("</PackagingType>"); sb.Append("<Dimensions>"); sb.AppendFormat("<Length>{0}</Length>", length); sb.AppendFormat("<Width>{0}</Width>", width); sb.AppendFormat("<Height>{0}</Height>", height); sb.Append("</Dimensions>"); sb.Append("<PackageWeight>"); sb.AppendFormat("<Weight>{0}</Weight>", weight); sb.Append("</PackageWeight>"); if (_upsSettings.InsurePackage) { //The maximum declared amount per package: 50000 USD. int packageInsurancePrice = Convert.ToInt32(subTotalWithDiscountBase); sb.Append("<PackageServiceOptions>"); sb.Append("<InsuredValue>"); sb.AppendFormat("<CurrencyCode>{0}</CurrencyCode>", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode); sb.AppendFormat("<MonetaryValue>{0}</MonetaryValue>", packageInsurancePrice); sb.Append("</InsuredValue>"); sb.Append("</PackageServiceOptions>"); } sb.Append("</Package>"); } else { int totalPackages = 1; int totalPackagesDims = 1; int totalPackagesWeights = 1; if (IsPackageTooHeavy(weight)) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAXPACKAGEWEIGHT)); } if (IsPackageTooLarge(length, height, width)) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)108)); } totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } int weight2 = weight / totalPackages; int height2 = height / totalPackages; int width2 = width / totalPackages; int length2 = length / totalPackages; if (weight2 < 1) { weight2 = 1; } if (height2 < 1) { height2 = 1; } if (width2 < 1) { width2 = 1; } if (length2 < 1) { length2 = 1; } //The maximum declared amount per package: 50000 USD. int packageInsurancePrice = Convert.ToInt32(subTotalWithDiscountBase / totalPackages); for (int i = 0; i < totalPackages; i++) { sb.Append("<Package>"); sb.Append("<PackagingType>"); sb.AppendFormat("<Code>{0}</Code>", GetPackagingTypeCode(packagingType)); sb.Append("</PackagingType>"); sb.Append("<Dimensions>"); sb.AppendFormat("<Length>{0}</Length>", length2); sb.AppendFormat("<Width>{0}</Width>", width2); sb.AppendFormat("<Height>{0}</Height>", height2); sb.Append("</Dimensions>"); sb.Append("<PackageWeight>"); sb.AppendFormat("<Weight>{0}</Weight>", weight2); sb.Append("</PackageWeight>"); if (_upsSettings.InsurePackage) { sb.Append("<PackageServiceOptions>"); sb.Append("<InsuredValue>"); sb.AppendFormat("<CurrencyCode>{0}</CurrencyCode>", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode); sb.AppendFormat("<MonetaryValue>{0}</MonetaryValue>", packageInsurancePrice); sb.Append("</InsuredValue>"); sb.Append("</PackageServiceOptions>"); } sb.Append("</Package>"); } } sb.Append("</Shipment>"); sb.Append("</RatingServiceSelectionRequest>"); string requestString = sb.ToString(); return(requestString); }
public ActionResult SubmitButton() { try { //user validation if ((Services.WorkContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)) { return(RedirectToRoute("Login")); } var store = Services.StoreContext.CurrentStore; var customer = Services.WorkContext.CurrentCustomer; var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(store.Id); var cart = Services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, store.Id); if (cart.Count == 0) { return(RedirectToRoute("ShoppingCart")); } if (String.IsNullOrEmpty(settings.ApiAccountName)) { throw new ApplicationException("PayPal API Account Name is not set"); } if (String.IsNullOrEmpty(settings.ApiAccountPassword)) { throw new ApplicationException("PayPal API Password is not set"); } if (String.IsNullOrEmpty(settings.Signature)) { throw new ApplicationException("PayPal API Signature is not set"); } var provider = PaymentService.LoadPaymentMethodBySystemName(PayPalExpressProvider.SystemName, true); var processor = provider != null ? provider.Value as PayPalExpressProvider : null; if (processor == null) { throw new SmartException(T("Plugins.CannotLoadModule", T("Plugins.FriendlyName.Payments.PayPalExpress"))); } var processPaymentRequest = new PayPalProcessPaymentRequest(); processPaymentRequest.StoreId = store.Id; //Get sub-total and discounts that apply to sub-total decimal orderSubTotalDiscountAmountBase = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); //order total decimal resultTemp = decimal.Zero; resultTemp += subTotalWithDiscountBase; //Get discounts that apply to Total Discount appliedDiscount = null; var discountAmount = _orderTotalCalculationService.GetOrderTotalDiscount(customer, resultTemp, out appliedDiscount); //if the current total is less than the discount amount, we only make the discount equal to the current total if (resultTemp < discountAmount) { discountAmount = resultTemp; } //reduce subtotal resultTemp -= discountAmount; if (resultTemp < decimal.Zero) { resultTemp = decimal.Zero; } decimal tempDiscount = discountAmount + orderSubTotalDiscountAmountBase; resultTemp = _currencyService.ConvertFromPrimaryStoreCurrency(resultTemp, Services.WorkContext.WorkingCurrency); if (tempDiscount > decimal.Zero) { tempDiscount = _currencyService.ConvertFromPrimaryStoreCurrency(tempDiscount, Services.WorkContext.WorkingCurrency); } processPaymentRequest.PaymentMethodSystemName = PayPalExpressProvider.SystemName; processPaymentRequest.OrderTotal = resultTemp; processPaymentRequest.Discount = tempDiscount; processPaymentRequest.IsRecurringPayment = false; //var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _storeContext.CurrentStore.Id); processPaymentRequest.CustomerId = Services.WorkContext.CurrentCustomer.Id; this.Session["OrderPaymentInfo"] = processPaymentRequest; var resp = processor.SetExpressCheckout(processPaymentRequest, cart); if (resp.Ack == AckCodeType.Success) { // Note: If Token is null and an empty page with "No token passed" is displyed, then this is caused by a broken // Web References/PayPalSvc/Reference.cs file. To fix it, check git history of the file and revert changes. processPaymentRequest.PaypalToken = resp.Token; processPaymentRequest.OrderGuid = new Guid(); processPaymentRequest.IsShippingMethodSet = ControllerContext.RouteData.IsRouteEqual("ShoppingCart", "Cart"); this.Session["OrderPaymentInfo"] = processPaymentRequest; _genericAttributeService.SaveAttribute <string>(customer, SystemCustomerAttributeNames.SelectedPaymentMethod, PayPalExpressProvider.SystemName, store.Id); var result = new RedirectResult(String.Format(settings.GetPayPalUrl() + "?cmd=_express-checkout&useraction=commit&token={0}", resp.Token)); return(result); } else { var error = new StringBuilder("We apologize, but an error has occured.<br />"); foreach (var errormsg in resp.Errors) { error.AppendLine(String.Format("{0} | {1} | {2}", errormsg.ErrorCode, errormsg.ShortMessage, errormsg.LongMessage)); } Logger.Error(new Exception(error.ToString()), resp.Errors[0].ShortMessage); NotifyError(error.ToString(), false); return(RedirectToAction("Cart", "ShoppingCart", new { area = "" })); } } catch (Exception ex) { Logger.Error(ex); NotifyError(ex.Message, false); return(RedirectToAction("Cart", "ShoppingCart", new { area = "" })); } }
public ActionResult ShopBar() { var customer = _services.WorkContext.CurrentCustomer; var unreadMessageCount = GetUnreadPrivateMessages(); var unreadMessage = string.Empty; var alertMessage = string.Empty; if (unreadMessageCount > 0) { unreadMessage = T("PrivateMessages.TotalUnread"); //notifications here if (_forumSettings.ShowAlertForPM && !customer.GetAttribute <bool>(SystemCustomerAttributeNames.NotifiedAboutNewPrivateMessages, _services.StoreContext.CurrentStore.Id)) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.NotifiedAboutNewPrivateMessages, true, _services.StoreContext.CurrentStore.Id); alertMessage = T("PrivateMessages.YouHaveUnreadPM", unreadMessageCount); } } //subtotal decimal subtotal = 0; var cart = _services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _services.StoreContext.CurrentStore.Id); if (cart.Count > 0) { decimal subtotalBase = decimal.Zero; decimal orderSubTotalDiscountAmountBase = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); subtotalBase = subTotalWithoutDiscountBase; subtotal = _currencyService.ConvertFromPrimaryStoreCurrency(subtotalBase, _services.WorkContext.WorkingCurrency); } var model = new ShopBarModel() { IsAuthenticated = customer.IsRegistered(), CustomerEmailUsername = customer.IsRegistered() ? (_customerSettings.UsernamesEnabled ? customer.Username : customer.Email) : "", IsCustomerImpersonated = _services.WorkContext.OriginalCustomerIfImpersonated != null, DisplayAdminLink = _services.Permissions.Authorize(StandardPermissionProvider.AccessAdminPanel), ShoppingCartEnabled = _services.Permissions.Authorize(StandardPermissionProvider.EnableShoppingCart), ShoppingCartAmount = _priceFormatter.FormatPrice(subtotal, true, false), WishlistEnabled = _services.Permissions.Authorize(StandardPermissionProvider.EnableWishlist), AllowPrivateMessages = _forumSettings.AllowPrivateMessages, UnreadPrivateMessages = unreadMessage, AlertMessage = alertMessage, CompareProductsEnabled = _catalogSettings.CompareProductsEnabled }; if (model.ShoppingCartEnabled || model.WishlistEnabled) { if (model.ShoppingCartEnabled) { model.ShoppingCartItems = cart.GetTotalProducts(); } if (model.WishlistEnabled) { model.WishlistItems = customer.CountProductsInCart(ShoppingCartType.Wishlist, _services.StoreContext.CurrentStore.Id); } } if (_catalogSettings.CompareProductsEnabled) { model.CompareItems = EngineContext.Current.Resolve <ICompareProductsService>().GetComparedProductsCount(); } return(PartialView(model)); }
public async Task <MiniShoppingCartModel> Handle(GetMiniShoppingCart request, CancellationToken cancellationToken) { var model = new MiniShoppingCartModel { ShowProductImages = _shoppingCartSettings.ShowProductImagesInMiniShoppingCart, DisplayShoppingCartButton = true, CurrentCustomerIsGuest = request.Customer.IsGuest(), AnonymousCheckoutAllowed = _orderSettings.AnonymousCheckoutAllowed, }; if (request.Customer.ShoppingCartItems.Any()) { var shoppingCartTypes = new List <ShoppingCartType>(); shoppingCartTypes.Add(ShoppingCartType.ShoppingCart); shoppingCartTypes.Add(ShoppingCartType.Auctions); if (_shoppingCartSettings.AllowOnHoldCart) { shoppingCartTypes.Add(ShoppingCartType.OnHoldCart); } var cart = _shoppingCartService.GetShoppingCart(request.Store.Id, shoppingCartTypes.ToArray()); model.TotalProducts = cart.Sum(x => x.Quantity); if (cart.Any()) { //subtotal var subTotalIncludingTax = request.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal; var shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, subTotalIncludingTax); decimal orderSubTotalDiscountAmountBase = shoppingCartSubTotal.discountAmount; List <AppliedDiscount> orderSubTotalAppliedDiscounts = shoppingCartSubTotal.appliedDiscounts; model.SubTotal = _priceFormatter.FormatPrice(shoppingCartSubTotal.subTotalWithoutDiscount, false, request.Currency, request.Language, subTotalIncludingTax); var requiresShipping = cart.RequiresShipping(); var checkoutAttributesExist = (await _checkoutAttributeService.GetAllCheckoutAttributes(request.Store.Id, !requiresShipping)).Any(); var minOrderSubtotalAmountOk = await _mediator.Send(new ValidateMinShoppingCartSubtotalAmountCommand() { Customer = request.Customer, Cart = cart.Where (x => x.ShoppingCartType == ShoppingCartType.ShoppingCart || x.ShoppingCartType == ShoppingCartType.Auctions).ToList() }); model.DisplayCheckoutButton = !_orderSettings.TermsOfServiceOnShoppingCartPage && minOrderSubtotalAmountOk && !checkoutAttributesExist; //products. sort descending (recently added products) foreach (var sci in cart .OrderByDescending(x => x.Id) .Take(_shoppingCartSettings.MiniShoppingCartProductNumber) .ToList()) { var product = await _productService.GetProductById(sci.ProductId); if (product == null) { continue; } var cartItemModel = new MiniShoppingCartModel.ShoppingCartItemModel { Id = sci.Id, ProductId = product.Id, ProductName = product.GetLocalized(x => x.Name, request.Language.Id), ProductSeName = product.GetSeName(request.Language.Id), Quantity = sci.Quantity, AttributeInfo = await _productAttributeFormatter.FormatAttributes(product, sci.AttributesXml) }; if (product.ProductType == ProductType.Reservation) { var reservation = ""; if (sci.RentalEndDateUtc == default(DateTime) || sci.RentalEndDateUtc == null) { reservation = string.Format(_localizationService.GetResource("ShoppingCart.Reservation.StartDate"), sci.RentalStartDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat)); } else { reservation = string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Date"), sci.RentalStartDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat), sci.RentalEndDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat)); } if (!string.IsNullOrEmpty(sci.Parameter)) { reservation += "<br>" + string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Option"), sci.Parameter); } if (!string.IsNullOrEmpty(sci.Duration)) { reservation += "<br>" + string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Duration"), sci.Duration); } if (string.IsNullOrEmpty(cartItemModel.AttributeInfo)) { cartItemModel.AttributeInfo = reservation; } else { cartItemModel.AttributeInfo += "<br>" + reservation; } } //unit prices if (product.CallForPrice) { cartItemModel.UnitPrice = _localizationService.GetResource("Products.CallForPrice"); } else { var productprices = await _taxService.GetProductPrice(product, (await _priceCalculationService.GetUnitPrice(sci, product)).unitprice); decimal taxRate = productprices.taxRate; cartItemModel.UnitPrice = _priceFormatter.FormatPrice(productprices.productprice); } //picture if (_shoppingCartSettings.ShowProductImagesInMiniShoppingCart) { cartItemModel.Picture = await PrepareCartItemPicture(request, product, sci.AttributesXml); } model.Items.Add(cartItemModel); } } } return(model); }
/// <summary> /// Gets tax total /// </summary> /// <param name="taxTotalRequest">Tax total request</param> /// <returns>Tax total</returns> public TaxTotalResult GetTaxTotal(TaxTotalRequest taxTotalRequest) { if (!(_httpContextAccessor.HttpContext.Items.TryGetValue("nop.TaxTotal", out var result) && result is TaxTotalResult taxTotalResult)) { var taxRates = new SortedDictionary <decimal, decimal>(); //order sub total (items + checkout attributes) _orderTotalCalculationService .GetShoppingCartSubTotal(taxTotalRequest.ShoppingCart, false, out _, out _, out _, out _, out var orderSubTotalTaxRates); var subTotalTaxTotal = decimal.Zero; foreach (var kvp in orderSubTotalTaxRates) { var taxRate = kvp.Key; var taxValue = kvp.Value; subTotalTaxTotal += taxValue; if (taxRate > decimal.Zero && taxValue > decimal.Zero) { if (!taxRates.ContainsKey(taxRate)) { taxRates.Add(taxRate, taxValue); } else { taxRates[taxRate] = taxRates[taxRate] + taxValue; } } } //shipping var shippingTax = decimal.Zero; if (_taxSettings.ShippingIsTaxable) { var shippingExclTax = _orderTotalCalculationService .GetShoppingCartShippingTotal(taxTotalRequest.ShoppingCart, false, out _); var shippingInclTax = _orderTotalCalculationService .GetShoppingCartShippingTotal(taxTotalRequest.ShoppingCart, true, out var taxRate); if (shippingExclTax.HasValue && shippingInclTax.HasValue) { shippingTax = shippingInclTax.Value - shippingExclTax.Value; if (shippingTax < decimal.Zero) { shippingTax = decimal.Zero; } if (taxRate > decimal.Zero && shippingTax > decimal.Zero) { if (!taxRates.ContainsKey(taxRate)) { taxRates.Add(taxRate, shippingTax); } else { taxRates[taxRate] = taxRates[taxRate] + shippingTax; } } } } //add at least one tax rate (0%) if (!taxRates.Any()) { taxRates.Add(decimal.Zero, decimal.Zero); } var taxTotal = subTotalTaxTotal + shippingTax; if (taxTotal < decimal.Zero) { taxTotal = decimal.Zero; } taxTotalResult = new TaxTotalResult { TaxTotal = taxTotal, TaxRates = taxRates }; _httpContextAccessor.HttpContext.Items.TryAdd("nop.TaxTotal", taxTotalResult); } //payment method additional fee if (taxTotalRequest.UsePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable) { var paymentMethodSystemName = taxTotalRequest.Customer != null ? _genericAttributeService.GetAttribute <string>(taxTotalRequest.Customer, NopCustomerDefaults.SelectedPaymentMethodAttribute, taxTotalRequest.StoreId) : string.Empty; var paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(taxTotalRequest.ShoppingCart, paymentMethodSystemName); var paymentMethodAdditionalFeeExclTax = _taxService .GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, taxTotalRequest.Customer, out _); var paymentMethodAdditionalFeeInclTax = _taxService .GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, taxTotalRequest.Customer, out var taxRate); var paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax; if (paymentMethodAdditionalFeeTax < decimal.Zero) { paymentMethodAdditionalFeeTax = decimal.Zero; } taxTotalResult.TaxTotal += paymentMethodAdditionalFeeTax; if (taxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero) { if (!taxTotalResult.TaxRates.ContainsKey(taxRate)) { taxTotalResult.TaxRates.Add(taxRate, paymentMethodAdditionalFeeTax); } else { taxTotalResult.TaxRates[taxRate] = taxTotalResult.TaxRates[taxRate] + paymentMethodAdditionalFeeTax; } } } return(taxTotalResult); }
public decimal GetCartItemTotal(IList <ShoppingCartItem> cart) { _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false, out _, out _, out _, out var subTotalWithDiscount); return(subTotalWithDiscount); }
private string CreateRequest(string accessKey, string username, string password, GetShippingOptionRequest getShippingOptionRequest, UPSCustomerClassification customerClassification, UPSPickupType pickupType, UPSPackagingType packagingType) { string zipPostalCodeFrom = getShippingOptionRequest.ZipPostalCodeFrom; string zipPostalCodeTo = getShippingOptionRequest.ShippingAddress.ZipPostalCode; string countryCodeFrom = getShippingOptionRequest.CountryFrom.TwoLetterIsoCode; string countryCodeTo = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode; var sb = new StringBuilder(); sb.Append("<?xml version='1.0'?>"); sb.Append("<AccessRequest xml:lang='en-US'>"); sb.AppendFormat("<AccessLicenseNumber>{0}</AccessLicenseNumber>", accessKey); sb.AppendFormat("<UserId>{0}</UserId>", username); sb.AppendFormat("<Password>{0}</Password>", password); sb.Append("</AccessRequest>"); sb.Append("<?xml version='1.0'?>"); sb.Append("<RatingServiceSelectionRequest xml:lang='en-US'>"); sb.Append("<Request>"); sb.Append("<TransactionReference>"); sb.Append("<CustomerContext>Bare Bones Rate Request</CustomerContext>"); sb.Append("<XpciVersion>1.0001</XpciVersion>"); sb.Append("</TransactionReference>"); sb.Append("<RequestAction>Rate</RequestAction>"); sb.Append("<RequestOption>Shop</RequestOption>"); sb.Append("</Request>"); if (String.Equals(countryCodeFrom, "US", StringComparison.InvariantCultureIgnoreCase)) { sb.Append("<PickupType>"); sb.AppendFormat("<Code>{0}</Code>", GetPickupTypeCode(pickupType)); sb.Append("</PickupType>"); sb.Append("<CustomerClassification>"); sb.AppendFormat("<Code>{0}</Code>", GetCustomerClassificationCode(customerClassification)); sb.Append("</CustomerClassification>"); } sb.Append("<Shipment>"); sb.Append("<Shipper>"); sb.Append("<Address>"); sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom); sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom); sb.Append("</Address>"); sb.Append("</Shipper>"); sb.Append("<ShipTo>"); sb.Append("<Address>"); sb.Append("<ResidentialAddressIndicator/>"); sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeTo); sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeTo); sb.Append("</Address>"); sb.Append("</ShipTo>"); sb.Append("<ShipFrom>"); sb.Append("<Address>"); sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom); sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom); sb.Append("</Address>"); sb.Append("</ShipFrom>"); sb.Append("<Service>"); sb.Append("<Code>03</Code>"); sb.Append("</Service>"); string currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode; //get subTotalWithoutDiscountBase, for use as insured value (when Settings.InsurePackage) //(note: prior versions used "with discount", but "without discount" better reflects true value to insure.) decimal orderSubTotalDiscountAmount; List <Discount> orderSubTotalAppliedDiscounts; decimal subTotalWithoutDiscountBase; decimal subTotalWithDiscountBase; //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList(), false, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscounts, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); if (_upsSettings.Tracing) { _traceMessages.AppendLine(" Packing Type: " + _upsSettings.PackingType.ToString()); } switch (_upsSettings.PackingType) { case PackingType.PackByOneItemPerPackage: SetIndividualPackageLineItemsOneItemPerPackage(sb, getShippingOptionRequest, packagingType, currencyCode); break; case PackingType.PackByVolume: SetIndividualPackageLineItemsCubicRootDimensions(sb, getShippingOptionRequest, packagingType, subTotalWithoutDiscountBase, currencyCode); break; case PackingType.PackByDimensions: default: SetIndividualPackageLineItems(sb, getShippingOptionRequest, packagingType, subTotalWithoutDiscountBase, currencyCode); break; } sb.Append("</Shipment>"); sb.Append("</RatingServiceSelectionRequest>"); return(sb.ToString()); }
private string CreateRequest(string accessKey, string username, string password, GetShippingOptionRequest getShippingOptionRequest, OntracCustomerClassification customerClassification, OntracPickupType pickupType, OntracPackagingType packagingType, bool saturdayDelivery) { var zipPostalCodeFrom = getShippingOptionRequest.ZipPostalCodeFrom; var zipPostalCodeTo = getShippingOptionRequest.ShippingAddress.ZipPostalCode; var countryCodeFrom = getShippingOptionRequest.CountryFrom.TwoLetterIsoCode; var countryCodeTo = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode; var stateCodeFrom = getShippingOptionRequest.StateProvinceFrom?.Abbreviation; var stateCodeTo = getShippingOptionRequest.ShippingAddress.StateProvince?.Abbreviation; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList(), false, out decimal _, out List <DiscountForCaching> _, out decimal orderSubTotal, out decimal _); // Rate request setup - Total Dimensions of Shopping Cart Items determines number of packages var usedMeasureWeight = GetUsedMeasureWeight(); var usedMeasureDimension = GetUsedMeasureDimension(); _shippingService.GetDimensions(getShippingOptionRequest.Items, out decimal widthTmp, out decimal lengthTmp, out decimal heightTmp, true); var length = ConvertFromPrimaryMeasureDimension(lengthTmp, usedMeasureDimension); var height = ConvertFromPrimaryMeasureDimension(heightTmp, usedMeasureDimension); var width = ConvertFromPrimaryMeasureDimension(widthTmp, usedMeasureDimension); var weight = ConvertFromPrimaryMeasureWeight(_shippingService.GetTotalWeight(getShippingOptionRequest, ignoreFreeShippedItems: true), usedMeasureWeight); if (length < 1) { length = 1; } if (height < 1) { height = 1; } if (width < 1) { width = 1; } if (weight < 1) { weight = 1; } var totalPackagesDims = 1; var totalPackagesWeights = 1; if (IsPackageTooHeavy(weight)) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAXPACKAGEWEIGHT)); } if (IsPackageTooLarge(length, height, width)) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)108)); } var totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } //The maximum declared amount per package: 50000 USD. var InsureCost = _ontracSettings.InsurePackage ? Convert.ToInt32(orderSubTotal / totalPackages) : 0; //var Product = "S"; var res = "true"; var urlString = "?pw=" + password + "&packages=ID1;" + zipPostalCodeFrom + ";" + zipPostalCodeTo + ";" + res + ";0.00;false;" + InsureCost + ";" + weight + ";" + length + "X" + width + "X" + height + ";"; return(urlString); }
/// <summary> /// Prepare details to place an order. It also sets some properties to "processPaymentRequest" /// </summary> /// <param name="processPaymentRequest">Process payment request</param> /// <returns>Details</returns> protected override PlaceOrderContainer PreparePlaceOrderDetails(ProcessPaymentRequest processPaymentRequest) { var details = new PlaceOrderContainer { //customer Customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId) }; if (details.Customer == null) { throw new ArgumentException("Customer is not set"); } //affiliate var affiliate = _affiliateService.GetAffiliateById(details.Customer.AffiliateId); if (affiliate != null && affiliate.Active && !affiliate.Deleted) { details.AffiliateId = affiliate.Id; } //check whether customer is guest if (details.Customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed) { throw new QNetException("Anonymous checkout is not allowed"); } //customer currency var currencyTmp = _currencyService.GetCurrencyById( _genericAttributeService.GetAttribute <int>(details.Customer, QNetCustomerDefaults.CurrencyIdAttribute, processPaymentRequest.StoreId)); var customerCurrency = currencyTmp != null && currencyTmp.Published ? currencyTmp : _workContext.WorkingCurrency; var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); details.CustomerCurrencyCode = customerCurrency.CurrencyCode; details.CustomerCurrencyRate = customerCurrency.Rate / primaryStoreCurrency.Rate; //customer language details.CustomerLanguage = _languageService.GetLanguageById( _genericAttributeService.GetAttribute <int>(details.Customer, QNetCustomerDefaults.LanguageIdAttribute, processPaymentRequest.StoreId)); if (details.CustomerLanguage == null || !details.CustomerLanguage.Published) { details.CustomerLanguage = _workContext.WorkingLanguage; } //billing address if (details.Customer.BillingAddress == null) { throw new QNetException("Billing address is not provided"); } if (!CommonHelper.IsValidEmail(details.Customer.BillingAddress.Email)) { throw new QNetException("Email is not valid"); } details.BillingAddress = (Address)details.Customer.BillingAddress.Clone(); if (details.BillingAddress.Country != null && !details.BillingAddress.Country.AllowsBilling) { throw new QNetException($"Country '{details.BillingAddress.Country.Name}' is not allowed for billing"); } //checkout attributes details.CheckoutAttributesXml = _genericAttributeService.GetAttribute <string>(details.Customer, QNetCustomerDefaults.CheckoutAttributes, processPaymentRequest.StoreId); details.CheckoutAttributeDescription = _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributesXml, details.Customer); //load shopping cart details.Cart = _shoppingCartService.GetShoppingCart(details.Customer, ShoppingCartType.ShoppingCart, processPaymentRequest.StoreId); if (!details.Cart.Any()) { throw new QNetException("Cart is empty"); } //validate the entire shopping cart var warnings = _shoppingCartService.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributesXml, true); if (warnings.Any()) { throw new QNetException(warnings.Aggregate(string.Empty, (current, next) => $"{current}{next};")); } //validate individual cart items foreach (var sci in details.Cart) { var sciWarnings = _shoppingCartService.GetShoppingCartItemWarnings(details.Customer, sci.ShoppingCartType, sci.Product, processPaymentRequest.StoreId, sci.AttributesXml, sci.CustomerEnteredPrice, sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.Id); if (sciWarnings.Any()) { throw new QNetException(sciWarnings.Aggregate(string.Empty, (current, next) => $"{current}{next};")); } } //min totals validation if (!ValidateMinOrderSubtotalAmount(details.Cart)) { var minOrderSubtotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency); throw new QNetException(string.Format(_localizationService.GetResource("Checkout.MinOrderSubtotalAmount"), _priceFormatter.FormatPrice(minOrderSubtotalAmount, true, false))); } if (!ValidateMinOrderTotalAmount(details.Cart)) { var minOrderTotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderTotalAmount, _workContext.WorkingCurrency); throw new QNetException(string.Format(_localizationService.GetResource("Checkout.MinOrderTotalAmount"), _priceFormatter.FormatPrice(minOrderTotalAmount, true, false))); } //tax display type if (_taxSettings.AllowCustomersToSelectTaxDisplayType) { details.CustomerTaxDisplayType = (TaxDisplayType)_genericAttributeService.GetAttribute <int>(details.Customer, QNetCustomerDefaults.TaxDisplayTypeIdAttribute, processPaymentRequest.StoreId); } else { details.CustomerTaxDisplayType = _taxSettings.TaxDisplayType; } //sub total (incl tax) _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, true, out var orderSubTotalDiscountAmount, out var orderSubTotalAppliedDiscounts, out var subTotalWithoutDiscountBase, out var _); details.OrderSubTotalInclTax = subTotalWithoutDiscountBase; details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount; //discount history foreach (var disc in orderSubTotalAppliedDiscounts) { if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc)) { details.AppliedDiscounts.Add(disc); } } //sub total (excl tax) _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, false, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscounts, out subTotalWithoutDiscountBase, out _); details.OrderSubTotalExclTax = subTotalWithoutDiscountBase; details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount; //shipping info if (_shoppingCartService.ShoppingCartRequiresShipping(details.Cart)) { var pickupPoint = _genericAttributeService.GetAttribute <PickupPoint>(details.Customer, QNetCustomerDefaults.SelectedPickupPointAttribute, processPaymentRequest.StoreId); if (_shippingSettings.AllowPickupInStore && pickupPoint != null) { var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id); details.PickupInStore = true; details.PickupAddress = new Address { Address1 = pickupPoint.Address, City = pickupPoint.City, County = pickupPoint.County, Country = country, StateProvince = state, ZipPostalCode = pickupPoint.ZipPostalCode, CreatedOnUtc = DateTime.UtcNow }; } else { if (details.Customer.ShippingAddress == null) { throw new QNetException("Shipping address is not provided"); } if (!CommonHelper.IsValidEmail(details.Customer.ShippingAddress.Email)) { throw new QNetException("Email is not valid"); } //clone shipping address details.ShippingAddress = (Address)details.Customer.ShippingAddress.Clone(); if (details.ShippingAddress.Country != null && !details.ShippingAddress.Country.AllowsShipping) { throw new QNetException($"Country '{details.ShippingAddress.Country.Name}' is not allowed for shipping"); } } var shippingOption = _genericAttributeService.GetAttribute <ShippingOption>(details.Customer, QNetCustomerDefaults.SelectedShippingOptionAttribute, processPaymentRequest.StoreId); if (shippingOption != null) { details.ShippingMethodName = shippingOption.Name; details.ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName; } details.ShippingStatus = ShippingStatus.NotYetShipped; } else { details.ShippingStatus = ShippingStatus.ShippingNotRequired; } //LoadAllShippingRateComputationMethods var shippingRateComputationMethods = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id); //shipping total var orderShippingTotalInclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true, shippingRateComputationMethods, out var _, out var shippingTotalDiscounts); var orderShippingTotalExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false, shippingRateComputationMethods); if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue) { throw new QNetException("Shipping total couldn't be calculated"); } details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value; details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value; foreach (var disc in shippingTotalDiscounts) { if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc)) { details.AppliedDiscounts.Add(disc); } } //payment total var paymentAdditionalFee = _paymentService.GetAdditionalHandlingFee(details.Cart, processPaymentRequest.PaymentMethodSystemName); details.PaymentAdditionalFeeInclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer); details.PaymentAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer); //tax amount details.OrderTaxTotal = _orderTotalCalculationService.GetTaxTotal(details.Cart, shippingRateComputationMethods, out var taxRatesDictionary); //Avalara plugin changes //get previously saved tax details received from the Avalara tax service var taxDetails = _httpContextAccessor.HttpContext.Session.Get <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue); if (taxDetails != null) { //adjust tax total according to received value from the Avalara if (taxDetails.TaxTotal.HasValue) { details.OrderTaxTotal = taxDetails.TaxTotal.Value; } if (taxDetails.TaxRates?.Any() ?? false) { taxRatesDictionary = new SortedDictionary <decimal, decimal>(taxDetails.TaxRates); } } //Avalara plugin changes //VAT number var customerVatStatus = (VatNumberStatus)_genericAttributeService.GetAttribute <int>(details.Customer, QNetCustomerDefaults.VatNumberStatusIdAttribute); if (_taxSettings.EuVatEnabled && customerVatStatus == VatNumberStatus.Valid) { details.VatNumber = _genericAttributeService.GetAttribute <string>(details.Customer, QNetCustomerDefaults.VatNumberAttribute); } //tax rates details.TaxRates = taxRatesDictionary.Aggregate(string.Empty, (current, next) => $"{current}{next.Key.ToString(CultureInfo.InvariantCulture)}:{next.Value.ToString(CultureInfo.InvariantCulture)}; "); //order total (and applied discounts, gift cards, reward points) var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(details.Cart, out var orderDiscountAmount, out var orderAppliedDiscounts, out var appliedGiftCards, out var redeemedRewardPoints, out var redeemedRewardPointsAmount); if (!orderTotal.HasValue) { throw new QNetException("Order total couldn't be calculated"); } details.OrderDiscountAmount = orderDiscountAmount; details.RedeemedRewardPoints = redeemedRewardPoints; details.RedeemedRewardPointsAmount = redeemedRewardPointsAmount; details.AppliedGiftCards = appliedGiftCards; details.OrderTotal = orderTotal.Value; //discount history foreach (var disc in orderAppliedDiscounts) { if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc)) { details.AppliedDiscounts.Add(disc); } } processPaymentRequest.OrderTotal = details.OrderTotal; //Avalara plugin changes //delete custom value _httpContextAccessor.HttpContext.Session.Set <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue, null); //Avalara plugin changes //recurring or standard shopping cart? details.IsRecurringShoppingCart = _shoppingCartService.ShoppingCartIsRecurring(details.Cart); if (!details.IsRecurringShoppingCart) { return(details); } var recurringCyclesError = _shoppingCartService.GetRecurringCycleInfo(details.Cart, out var recurringCycleLength, out var recurringCyclePeriod, out var recurringTotalCycles); if (!string.IsNullOrEmpty(recurringCyclesError)) { throw new QNetException(recurringCyclesError); } processPaymentRequest.RecurringCycleLength = recurringCycleLength; processPaymentRequest.RecurringCyclePeriod = recurringCyclePeriod; processPaymentRequest.RecurringTotalCycles = recurringTotalCycles; return(details); }
/// <summary> /// Handle shopping cart changed event /// </summary> /// <param name="cartItem">Shopping cart item</param> public void HandleShoppingCartChangedEvent(ShoppingCartItem cartItem) { //whether marketing automation is enabled if (!_sendInBlueSettings.UseMarketingAutomation) { return; } try { //create API client var client = CreateMarketingAutomationClient(); //first, try to identify current customer client.Identify(new Identify(cartItem.Customer.Email)); //get shopping cart GUID var shoppingCartGuid = _genericAttributeService.GetAttribute <Guid?>(cartItem.Customer, SendinBlueDefaults.ShoppingCartGuidAttribute); //create track event object var trackEvent = new TrackEvent(cartItem.Customer.Email, string.Empty); //get current customer's shopping cart var cart = cartItem.Customer.ShoppingCartItems .Where(item => item.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id).ToList(); if (cart.Any()) { //get URL helper var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext); //get shopping cart amounts _orderTotalCalculationService.GetShoppingCartSubTotal(cart, _workContext.TaxDisplayType == TaxDisplayType.IncludingTax, out var cartDiscount, out _, out var cartSubtotal, out _); var cartTax = _orderTotalCalculationService.GetTaxTotal(cart, false); var cartShipping = _orderTotalCalculationService.GetShoppingCartShippingTotal(cart); var cartTotal = _orderTotalCalculationService.GetShoppingCartTotal(cart, false, false); //get products data by shopping cart items var itemsData = cart.Where(item => item.Product != null).Select(item => { //try to get product attribute combination var combination = _productAttributeParser.FindProductAttributeCombination(item.Product, item.AttributesXml); //get default product picture var picture = _pictureService.GetProductPicture(item.Product, item.AttributesXml); //get product SEO slug name var seName = _urlRecordService.GetSeName(item.Product); //create product data return(new { id = item.Product.Id, name = item.Product.Name, variant_id = combination?.Id ?? item.Product.Id, variant_name = combination?.Sku ?? item.Product.Name, sku = combination?.Sku ?? item.Product.Sku, category = item.Product.ProductCategories.Aggregate(",", (all, category) => { var res = category.Category.Name; res = all == "," ? res : all + ", " + res; return res; }), url = urlHelper.RouteUrl("Product", new { SeName = seName }, _webHelper.CurrentRequestProtocol), image = _pictureService.GetPictureUrl(picture), quantity = item.Quantity, price = _priceCalculationService.GetSubTotal(item) }); }).ToArray(); //prepare cart data var cartData = new { affiliation = _storeContext.CurrentStore.Name, subtotal = cartSubtotal, shipping = cartShipping ?? decimal.Zero, total_before_tax = cartSubtotal + cartShipping ?? decimal.Zero, tax = cartTax, discount = cartDiscount, revenue = cartTotal ?? decimal.Zero, url = urlHelper.RouteUrl("ShoppingCart", null, _webHelper.CurrentRequestProtocol), currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode, //gift_wrapping = string.Empty, //currently we can't get this value items = itemsData }; //if there is a single item in the cart, so the cart is just created if (cart.Count == 1) { shoppingCartGuid = Guid.NewGuid(); } else { //otherwise cart is updated shoppingCartGuid = shoppingCartGuid ?? Guid.NewGuid(); } trackEvent.EventName = SendinBlueDefaults.CartUpdatedEventName; trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}", data = cartData }; } else { //there are no items in the cart, so the cart is deleted shoppingCartGuid = shoppingCartGuid ?? Guid.NewGuid(); trackEvent.EventName = SendinBlueDefaults.CartDeletedEventName; trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}" }; } //track event client.TrackEvent(trackEvent); //update GUID for the current customer's shopping cart _genericAttributeService.SaveAttribute(cartItem.Customer, SendinBlueDefaults.ShoppingCartGuidAttribute, shoppingCartGuid); } catch (Exception exception) { //log full error _logger.Error($"SendinBlue Marketing Automation error: {exception.Message}.", exception, cartItem.Customer); } }
public async Task <AddToCartModel> Handle(GetAddToCart request, CancellationToken cancellationToken) { var model = new AddToCartModel(); model.AttributeDescription = await _productAttributeFormatter.FormatAttributes(request.Product, request.AttributesXml); model.ProductSeName = request.Product.GetSeName(request.Language.Id); model.CartType = request.CartType; model.ProductId = request.Product.Id; model.ProductName = request.Product.GetLocalized(x => x.Name, request.Language.Id); model.Quantity = request.Quantity; //reservation info if (request.Product.ProductType == ProductType.Reservation) { if (request.EndDate == default(DateTime) || request.EndDate == null) { model.ReservationInfo = string.Format(_localizationService.GetResource("ShoppingCart.Reservation.StartDate"), request.StartDate?.ToString(_shoppingCartSettings.ReservationDateFormat)); } else { model.ReservationInfo = string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Date"), request.StartDate?.ToString(_shoppingCartSettings.ReservationDateFormat), request.EndDate?.ToString(_shoppingCartSettings.ReservationDateFormat)); } if (!string.IsNullOrEmpty(request.Parameter)) { model.ReservationInfo += "<br>" + string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Option"), request.Parameter); } if (!string.IsNullOrEmpty(request.Duration)) { model.ReservationInfo += "<br>" + string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Duration"), request.Duration); } } if (request.CartType != ShoppingCartType.Auctions) { var sci = request.Customer.ShoppingCartItems.FirstOrDefault(x => x.ProductId == request.Product.Id && (string.IsNullOrEmpty(x.AttributesXml) ? "" : x.AttributesXml) == request.AttributesXml); model.ItemQuantity = sci.Quantity; //unit prices if (request.Product.CallForPrice) { model.Price = _localizationService.GetResource("Products.CallForPrice"); } else { var productprices = await _taxService.GetProductPrice(request.Product, (await _priceCalculationService.GetUnitPrice(sci)).unitprice); decimal taxRate = productprices.taxRate; decimal shoppingCartUnitPriceWithDiscountBase = productprices.productprice; decimal shoppingCartUnitPriceWithDiscount = await _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartUnitPriceWithDiscountBase, request.Currency); model.Price = request.CustomerEnteredPrice == 0 ? _priceFormatter.FormatPrice(shoppingCartUnitPriceWithDiscount) : _priceFormatter.FormatPrice(request.CustomerEnteredPrice); model.DecimalPrice = request.CustomerEnteredPrice == 0 ? shoppingCartUnitPriceWithDiscount : request.CustomerEnteredPrice; model.TotalPrice = _priceFormatter.FormatPrice(shoppingCartUnitPriceWithDiscount * sci.Quantity); } //picture model.Picture = await PrepareCartItemPicture(request); } else { model.Picture = await PrepareCartItemPicture(request); } var cart = _shoppingCartService.GetShoppingCart(request.Store.Id, request.CartType); if (request.CartType != ShoppingCartType.Auctions) { model.TotalItems = cart.Sum(x => x.Quantity); } else { model.TotalItems = 0; var grouped = (await _auctionService.GetBidsByCustomerId(request.Customer.Id)).GroupBy(x => x.ProductId); foreach (var item in grouped) { var p = await _productService.GetProductById(item.Key); if (p != null && p.AvailableEndDateTimeUtc > DateTime.UtcNow) { model.TotalItems++; } } } if (request.CartType == ShoppingCartType.ShoppingCart) { var subTotalIncludingTax = request.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal; var shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, subTotalIncludingTax); decimal orderSubTotalDiscountAmountBase = shoppingCartSubTotal.discountAmount; List <AppliedDiscount> orderSubTotalAppliedDiscounts = shoppingCartSubTotal.appliedDiscounts; decimal subTotalWithoutDiscountBase = shoppingCartSubTotal.subTotalWithoutDiscount; decimal subTotalWithDiscountBase = shoppingCartSubTotal.subTotalWithDiscount; decimal subtotalBase = subTotalWithoutDiscountBase; decimal subtotal = await _currencyService.ConvertFromPrimaryStoreCurrency(subtotalBase, request.Currency); model.SubTotal = _priceFormatter.FormatPrice(subtotal, true, request.Currency, request.Language, subTotalIncludingTax); model.DecimalSubTotal = subtotal; if (orderSubTotalDiscountAmountBase > decimal.Zero) { decimal orderSubTotalDiscountAmount = await _currencyService.ConvertFromPrimaryStoreCurrency(orderSubTotalDiscountAmountBase, request.Currency); model.SubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountAmount, true, request.Currency, request.Language, subTotalIncludingTax); } } else if (request.CartType == ShoppingCartType.Auctions) { model.IsAuction = true; model.HighestBidValue = request.Product.HighestBid; model.HighestBid = _priceFormatter.FormatPrice(request.Product.HighestBid); model.EndTime = request.Product.AvailableEndDateTimeUtc; } return(model); }
public ActionResult SubmitButton() { try { //user validation if ((_services.WorkContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)) { return(RedirectToRoute("Login")); } var settings = _services.Settings.LoadSetting <PayPalExpressPaymentSettings>(_services.StoreContext.CurrentStore.Id); var cart = _services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _services.StoreContext.CurrentStore.Id); if (cart.Count == 0) { return(RedirectToRoute("ShoppingCart")); } var currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode; if (String.IsNullOrEmpty(settings.ApiAccountName)) { throw new ApplicationException("PayPal API Account Name is not set"); } if (String.IsNullOrEmpty(settings.ApiAccountPassword)) { throw new ApplicationException("PayPal API Password is not set"); } if (String.IsNullOrEmpty(settings.Signature)) { throw new ApplicationException("PayPal API Signature is not set"); } var provider = _paymentService.LoadPaymentMethodBySystemName("Payments.PayPalExpress", true); var processor = provider != null ? provider.Value as PayPalExpress : null; if (processor == null) { throw new SmartException("PayPal Express Checkout module cannot be loaded"); } var processPaymentRequest = new PayPalProcessPaymentRequest(); processPaymentRequest.StoreId = _services.StoreContext.CurrentStore.Id; //Get sub-total and discounts that apply to sub-total decimal orderSubTotalDiscountAmountBase = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); //order total decimal resultTemp = decimal.Zero; resultTemp += subTotalWithDiscountBase; // get customer int customerId = Convert.ToInt32(_services.WorkContext.CurrentCustomer.Id.ToString()); var customer = _customerService.GetCustomerById(customerId); //Get discounts that apply to Total Discount appliedDiscount = null; var discountAmount = _orderTotalCalculationService.GetOrderTotalDiscount(customer, resultTemp, out appliedDiscount); //if the current total is less than the discount amount, we only make the discount equal to the current total if (resultTemp < discountAmount) { discountAmount = resultTemp; } //reduce subtotal resultTemp -= discountAmount; if (resultTemp < decimal.Zero) { resultTemp = decimal.Zero; } decimal tempDiscount = discountAmount + orderSubTotalDiscountAmountBase; resultTemp = _currencyService.ConvertFromPrimaryStoreCurrency(resultTemp, _services.WorkContext.WorkingCurrency); if (tempDiscount > decimal.Zero) { tempDiscount = _currencyService.ConvertFromPrimaryStoreCurrency(tempDiscount, _services.WorkContext.WorkingCurrency); } processPaymentRequest.PaymentMethodSystemName = "Payments.PayPalExpress"; processPaymentRequest.OrderTotal = resultTemp; processPaymentRequest.Discount = tempDiscount; processPaymentRequest.IsRecurringPayment = false; //var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _storeContext.CurrentStore.Id); processPaymentRequest.CustomerId = _services.WorkContext.CurrentCustomer.Id; this.Session["OrderPaymentInfo"] = processPaymentRequest; var resp = processor.SetExpressCheckout(processPaymentRequest, cart); if (resp.Ack == AckCodeType.Success) { processPaymentRequest.PaypalToken = resp.Token; processPaymentRequest.OrderGuid = new Guid(); processPaymentRequest.IsShippingMethodSet = PayPalHelper.CurrentPageIsBasket(this.RouteData); this.Session["OrderPaymentInfo"] = processPaymentRequest; _genericAttributeService.SaveAttribute <string>(customer, SystemCustomerAttributeNames.SelectedPaymentMethod, "Payments.PayPalExpress", _services.StoreContext.CurrentStore.Id); var result = new RedirectResult(String.Format( PayPalHelper.GetPaypalUrl(settings) + "?cmd=_express-checkout&useraction=commit&token={0}", resp.Token)); return(result); } else { var error = new StringBuilder("We apologize, but an error has occured.<br />"); foreach (var errormsg in resp.Errors) { error.AppendLine(String.Format("{0} | {1} | {2}", errormsg.ErrorCode, errormsg.ShortMessage, errormsg.LongMessage)); } _logger.InsertLog(LogLevel.Error, resp.Errors[0].ShortMessage, resp.Errors[0].LongMessage, _services.WorkContext.CurrentCustomer); NotifyError(error.ToString(), false); return(RedirectToAction("Cart", "ShoppingCart", new { area = "" })); } } catch (Exception ex) { _logger.InsertLog(LogLevel.Error, ex.Message, ex.StackTrace, _services.WorkContext.CurrentCustomer); NotifyError(ex.Message, false); return(RedirectToAction("Cart", "ShoppingCart", new { area = "" })); } }