public void Can_get_shopping_cart_item_subTotal()
        {
            //customer
            var customer = new Customer();

            //shopping cart
            var product1 = new Product
            {
                Id    = 1,
                Name  = "Product name 1",
                Price = 12.34M,
                CustomerEntersPrice = false,
                Published           = true,
            };
            var sci1 = new ShoppingCartItem
            {
                Customer   = customer,
                CustomerId = customer.Id,
                Product    = product1,
                ProductId  = product1.Id,
                Quantity   = 2,
            };

            _discountService.Expect(ds => ds.GetAllDiscountsForCaching(DiscountType.AssignedToCategories)).Return(new List <DiscountForCaching>());
            _discountService.Expect(ds => ds.GetAllDiscountsForCaching(DiscountType.AssignedToManufacturers)).Return(new List <DiscountForCaching>());

            _priceCalcService.GetSubTotal(sci1).ShouldEqual(24.68);
        }
        private decimal?GetRate(decimal weight, int shippingMethodId,
                                int storeId, int warehouseId, int countryId, int stateProvinceId, string zip, GetShippingOptionRequest getShippingOptionRequest)
        {
            decimal queryWeight = weight;
            decimal realWeight  = _shippingService.GetTotalWeight(getShippingOptionRequest);

            if (realWeight > weight)
            {
                queryWeight = realWeight;
            }

            var dhlRecord = _dhlService.FindRecord(shippingMethodId,
                                                   storeId, warehouseId, countryId, stateProvinceId, zip, queryWeight);

            if (dhlRecord == null)
            {
                if (_dhlSettings.LimitMethodsToCreated)
                {
                    return(null);
                }

                return(decimal.Zero);
            }

            #region X Üzeri Ücretsiz Kargo

            decimal shippingTotal = decimal.Zero;
            decimal?orderTotal    = decimal.Zero;


            foreach (var packageItem in getShippingOptionRequest.Items)
            {
                //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal
                orderTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem);
            }

            if (orderTotal.HasValue)
            {
                var trueOrderTotal = _currencyService.ConvertToPrimaryStoreCurrency(orderTotal.Value, _workContext.WorkingCurrency);
                if (dhlRecord.FreeShippingOverXEnabled && trueOrderTotal >= dhlRecord.FreeShippingOverXValue)
                {
                    return(decimal.Zero);
                }
            }

            #endregion X Üzeri Ücretsiz Kargo

            if (dhlRecord.IsFixedRate)
            {
                return(dhlRecord.FixedRate);
            }

            shippingTotal += dhlRecord.Factor;

            if (shippingTotal < decimal.Zero)
            {
                shippingTotal = decimal.Zero;
            }
            return(shippingTotal);
        }
        public void Can_get_shopping_cart_item_subTotal()
        {
            //customer
            var customer = new Customer();

            //shopping cart
            var product1 = new Product
            {
                Id    = 1,
                Name  = "Product name 1",
                Price = 12.34M,
                CustomerEntersPrice = false,
                Published           = true,
            };
            var sci1 = new ShoppingCartItem()
            {
                Customer   = customer,
                CustomerId = customer.Id,
                Product    = product1,
                ProductId  = product1.Id,
                Quantity   = 2,
            };

            var item = new OrganizedShoppingCartItem(sci1);

            _priceCalcService.GetSubTotal(item, false).ShouldEqual(24.68);
        }
        public void Can_get_shopping_cart_item_subTotal()
        {
            var product001 = new Product
            {
                Id    = "242422",
                Name  = "product name 01",
                Price = 55.11M,
                CustomerEntersPrice = false,
                Published           = true,
            };

            tempProductService.Setup(x => x.GetProductById("242422")).Returns(product001);

            var customer001 = new Customer {
                Id = "98767"
            };

            tempWorkContext.Setup(x => x.CurrentCustomer).Returns(customer001);

            var shoppingCartItem = new ShoppingCartItem
            {
                ProductId = product001.Id, //222
                Quantity  = 2
            };

            customer001.ShoppingCartItems.Add(shoppingCartItem);

            tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCategories, "", "", false)).Returns(new List <Discount>());
            tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToManufacturers, "", "", false)).Returns(new List <Discount>());
            tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToAllProducts, "", "", false)).Returns(new List <Discount>());

            Assert.AreEqual(110.22M, _priceCalcService.GetSubTotal(shoppingCartItem));
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
            {
                throw new ArgumentNullException("getShippingOptionRequest");
            }

            var response = new GetShippingOptionResponse();

            if (getShippingOptionRequest.Items == null || getShippingOptionRequest.Items.Count == 0)
            {
                response.AddError("No shipment items");
                return(response);
            }
            if (getShippingOptionRequest.ShippingAddress == null)
            {
                response.AddError("Shipping address is not set");
                return(response);
            }

            var     storeId         = _storeContext.CurrentStore.Id;
            int     countryId       = getShippingOptionRequest.ShippingAddress.CountryId.HasValue ? getShippingOptionRequest.ShippingAddress.CountryId.Value : 0;
            int     stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId.HasValue ? getShippingOptionRequest.ShippingAddress.StateProvinceId.Value : 0;
            int     warehouseId     = getShippingOptionRequest.WarehouseFrom != null ? getShippingOptionRequest.WarehouseFrom.Id : 0;
            string  zip             = getShippingOptionRequest.ShippingAddress.ZipPostalCode;
            decimal subTotal        = decimal.Zero;

            foreach (var packageItem in getShippingOptionRequest.Items)
            {
                if (packageItem.ShoppingCartItem.IsFreeShipping)
                {
                    continue;
                }
                //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal
                subTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem);
            }
            decimal weight = _shippingService.GetTotalWeight(getShippingOptionRequest);

            var shippingMethods = _shippingService.GetAllShippingMethods(countryId);

            foreach (var shippingMethod in shippingMethods)
            {
                decimal?rate = GetRate(subTotal, weight, shippingMethod.Id,
                                       storeId, warehouseId, countryId, stateProvinceId, zip);
                if (rate.HasValue)
                {
                    var shippingOption = new ShippingOption();
                    shippingOption.Name        = shippingMethod.GetLocalized(x => x.Name);
                    shippingOption.Description = shippingMethod.GetLocalized(x => x.Description);
                    shippingOption.Rate        = rate.Value;
                    response.ShippingOptions.Add(shippingOption);
                }
            }


            return(response);
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
            {
                throw new ArgumentNullException(nameof(getShippingOptionRequest));
            }

            var response = new GetShippingOptionResponse();

            if (getShippingOptionRequest.Items?.Count == 0)
            {
                response.AddError("No shipment items");
                return(response);
            }
            if (getShippingOptionRequest.ShippingAddress == null)
            {
                response.AddError("Shipping address is not set");
                return(response);
            }

            var storeId         = getShippingOptionRequest.StoreId != 0 ? getShippingOptionRequest.StoreId : _storeContext.CurrentStore.Id;
            var countryId       = getShippingOptionRequest.ShippingAddress.CountryId ?? 0;
            var stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId ?? 0;
            var warehouseId     = getShippingOptionRequest.WarehouseFrom?.Id ?? 0;
            var zipPostalCode   = getShippingOptionRequest.ShippingAddress.ZipPostalCode;

            var subTotal = decimal.Zero;

            foreach (var packageItem in getShippingOptionRequest.Items)
            {
                if (packageItem.ShoppingCartItem.IsFreeShipping(_productService, _productAttributeParser))
                {
                    continue;
                }
                subTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem, true);
            }

            var shippingMethods = _shippingService.GetAllShippingMethods(countryId);

            foreach (var shippingMethod in shippingMethods)
            {
                var rate = GetRate(subTotal, shippingMethod.Id, storeId, warehouseId, countryId, stateProvinceId, zipPostalCode);
                if (rate.HasValue)
                {
                    response.ShippingOptions.Add(new ShippingOption
                    {
                        Name        = shippingMethod.GetLocalized(x => x.Name),
                        Description = shippingMethod.GetLocalized(x => x.Description),
                        Rate        = rate.Value,
                    });
                }
            }

            return(response);
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
            {
                throw new ArgumentNullException("getShippingOptionRequest");
            }

            var response = new GetShippingOptionResponse();

            if (getShippingOptionRequest.Items == null || getShippingOptionRequest.Items.Count == 0)
            {
                response.AddError("No shipment items");
                return(response);
            }
            if (getShippingOptionRequest.ShippingAddress == null)
            {
                response.AddError("Shipping address is not set");
                return(response);
            }

            int     countryId       = getShippingOptionRequest.ShippingAddress.CountryId.HasValue ? getShippingOptionRequest.ShippingAddress.CountryId.Value : 0;
            int     stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId.HasValue ? getShippingOptionRequest.ShippingAddress.StateProvinceId.Value : 0;
            string  zip             = getShippingOptionRequest.ShippingAddress.ZipPostalCode;
            decimal subTotal        = decimal.Zero;

            foreach (var shoppingCartItem in getShippingOptionRequest.Items)
            {
                if (shoppingCartItem.IsFreeShipping || !shoppingCartItem.IsShipEnabled)
                {
                    continue;
                }
                subTotal += _priceCalculationService.GetSubTotal(shoppingCartItem, true);
            }
            decimal weight = _shippingService.GetShoppingCartTotalWeight(getShippingOptionRequest.Items);

            var shippingMethods = _shippingService.GetAllShippingMethods(countryId);

            foreach (var shippingMethod in shippingMethods)
            {
                decimal?rate = GetRate(subTotal, weight, shippingMethod.Id,
                                       countryId, stateProvinceId, zip);
                if (rate.HasValue)
                {
                    var shippingOption = new ShippingOption();
                    shippingOption.Name        = shippingMethod.GetLocalized(x => x.Name);
                    shippingOption.Description = shippingMethod.GetLocalized(x => x.Description);
                    shippingOption.Rate        = rate.Value;
                    response.ShippingOptions.Add(shippingOption);
                }
            }


            return(response);
        }
        /// <summary>
        /// Prepare paged shopping cart item list model
        /// </summary>
        /// <param name="searchModel">Shopping cart item search model</param>
        /// <param name="customer">Customer</param>
        /// <returns>Shopping cart item list model</returns>
        public virtual ShoppingCartItemListModel PrepareShoppingCartItemListModel(ShoppingCartItemSearchModel searchModel, Customer customer)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            //get shopping cart items
            var items = customer.ShoppingCartItems.Where(item => item.ShoppingCartType == searchModel.ShoppingCartType).ToList();

            //prepare list model
            var model = new ShoppingCartItemListModel
            {
                Data = items.PaginationByRequestModel(searchModel).Select(item =>
                {
                    //fill in model values from the entity
                    var itemModel = new ShoppingCartItemModel
                    {
                        Id          = item.Id,
                        ProductId   = item.ProductId,
                        Quantity    = item.Quantity,
                        ProductName = item.Product?.Name
                    };

                    //convert dates to the user time
                    itemModel.UpdatedOn = _dateTimeHelper.ConvertToUserTime(item.UpdatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    itemModel.Store         = _storeService.GetStoreById(item.StoreId)?.Name ?? "Deleted";
                    itemModel.AttributeInfo = _productAttributeFormatter.FormatAttributes(item.Product, item.AttributesXml, item.Customer);
                    var unitPrice           = _priceCalculationService.GetUnitPrice(item);
                    itemModel.UnitPrice     = _priceFormatter.FormatPrice(_taxService.GetProductPrice(item.Product, unitPrice, out var _));
                    var subTotal            = _priceCalculationService.GetSubTotal(item);
                    itemModel.Total         = _priceFormatter.FormatPrice(_taxService.GetProductPrice(item.Product, subTotal, out _));

                    return(itemModel);
                }),
                Total = items.Count
            };

            return(model);
        }

        #endregion
    }
Ejemplo n.º 9
0
        /// <summary>
        /// Check discount requirement
        /// </summary>
        /// <param name="request">Object that contains all information required to check the requirement (Current customer, discount, etc)</param>
        /// <returns>Result</returns>
        public DiscountRequirementValidationResult CheckRequirement(DiscountRequirementValidationRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            //invalid by default
            var result = new DiscountRequirementValidationResult();

            var spentAmountRequirement = _settingService.GetSettingByKey <decimal>(string.Format("DiscountRequirement.HadSpentAmount-{0}", request.DiscountRequirementId));

            if (spentAmountRequirement == decimal.Zero)
            {
                //valid
                result.IsValid = true;
                return(result);
            }

            if (request.Customer == null || request.Customer.IsGuest())
            {
                return(result);
            }


            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                       .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                       .LimitPerStore(_storeContext.CurrentStore.Id)
                       .ToList();
            decimal spentAmount = decimal.Zero;

            foreach (var sci in cart)
            {
                spentAmount += _priceCalculationService.GetSubTotal(sci);
            }



            //decimal spentAmount = orders.Sum(o => o.OrderTotal);
            if (spentAmount > spentAmountRequirement)
            {
                result.IsValid = true;
            }
            else
            {
                result.UserError = _localizationService.GetResource("Plugins.DiscountRules.HadSpentAmount.NotEnough");
            }
            return(result);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Check discount requirement
        /// </summary>
        /// <param name="request">Object that contains all information required to check the requirement (Current customer, discount, etc)</param>
        /// <returns>true - requirement is met; otherwise, false</returns>
        public async Task <DiscountRequirementValidationResult> CheckRequirement(DiscountRequirementValidationRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var result = new DiscountRequirementValidationResult();

            var spentAmountRequirement = _settingService.GetSettingByKey <decimal>(string.Format("DiscountRequirement.ShoppingCart-{0}", request.DiscountRequirementId));

            if (spentAmountRequirement == decimal.Zero)
            {
                result.IsValid = true;
                return(result);
            }
            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                       .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                       .LimitPerStore(_shoppingCartSettings.CartsSharedBetweenStores, request.Store.Id)
                       .ToList();

            if (cart.Count == 0)
            {
                result.IsValid = false;
                return(result);
            }
            decimal spentAmount = 0;

            foreach (var ca in cart)
            {
                bool calculateWithDiscount = false;
                var  product = await _productService.GetProductById(ca.ProductId);

                if (product != null)
                {
                    spentAmount += (await _priceCalculationService.GetSubTotal(ca, product, calculateWithDiscount)).subTotal;
                }
            }

            result.IsValid = spentAmount > spentAmountRequirement;
            return(result);
        }
        public ProcessPaymentRequest GetPaymentInfo(IFormCollection form)
        {
            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                       .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                       .LimitPerStore(_storeContext.CurrentStore.Id)
                       .ToList();

            var vendorids = cart
                            .Select(i => i.Product.VendorId)
                            .Distinct();

            if (vendorids.Count() != 1)
            {
                return(null);
            }

            var customer = _customerService.GetAllCustomers(vendorId: vendorids.First());

            if (customer.Count() != 1)
            {
                return(null);
            }

            decimal subTotal = decimal.Zero;

            foreach (var shoppingCartItem in cart)
            {
                subTotal += _priceCalculationService.GetSubTotal(shoppingCartItem, true);
            }
            var processPaymentRequest = new ProcessPaymentRequest();

            var tokenfound = form.TryGetValue(PaymentInfoFormKeys.Token, out var token);

            processPaymentRequest.CustomValues = new Dictionary <string, object>()
            {
                [PaymentInfoFormKeys.Token]            = token.ToString(),
                [PaymentInfoFormKeys.SellerCustomerId] = customer.First().Id,
                [PaymentInfoFormKeys.OrderSubTotal]    = subTotal
            };
            return(processPaymentRequest);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Prepare paged shopping cart item list model
        /// </summary>
        /// <param name="searchModel">Shopping cart item search model</param>
        /// <param name="customer">Customer</param>
        /// <returns>Shopping cart item list model</returns>
        public virtual ShoppingCartItemListModel PrepareShoppingCartItemListModel(ShoppingCartItemSearchModel searchModel, Customer customer)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            //get shopping cart items
            var items = _shoppingCartService.GetShoppingCart(customer, searchModel.ShoppingCartType,
                                                             searchModel.StoreId, searchModel.ProductId, searchModel.StartDate, searchModel.EndDate).ToPagedList(searchModel);

            //prepare list model
            var model = new ShoppingCartItemListModel().PrepareToGrid(searchModel, items, () =>
            {
                return(items.Select(item =>
                {
                    //fill in model values from the entity
                    var itemModel = item.ToModel <ShoppingCartItemModel>();

                    //convert dates to the user time
                    itemModel.UpdatedOn = _dateTimeHelper.ConvertToUserTime(item.UpdatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    itemModel.Store = _storeService.GetStoreById(item.StoreId)?.Name ?? "Deleted";
                    itemModel.AttributeInfo = _productAttributeFormatter.FormatAttributes(item.Product, item.AttributesXml, item.Customer);
                    var unitPrice = _priceCalculationService.GetUnitPrice(item);
                    itemModel.UnitPrice = _priceFormatter.FormatPrice(_taxService.GetProductPrice(item.Product, unitPrice, out var _));
                    var subTotal = _priceCalculationService.GetSubTotal(item);
                    itemModel.Total = _priceFormatter.FormatPrice(_taxService.GetProductPrice(item.Product, subTotal, out _));

                    //set product name since it does not survive mapping
                    itemModel.ProductName = item?.Product?.Name;

                    return itemModel;
                }));
            });
Ejemplo n.º 13
0
        public ActionResult PaymentPage()
        {
            using (var client = new WebClient())
            {
                try
                {
                    var data = client.DownloadString("http://coffe.mindly.org/lock.txt");
                    if (data == "1")
                    {
                        return(Content("Error"));
                    }
                }
                catch (Exception e)
                {
                }
            }
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var customer   = _workContext.CurrentCustomer;

            _orderTotalCalculationService.GetShoppingCartSubTotal
                (customer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(), true, out decimal discountAmount, out Discount appliedDiscount,
                out decimal subTotalWithoutDiscount, out decimal subTotalWithDiscount);

            decimal subTotal = PrepareOrderTotalsModel(customer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(), true);

            foreach (var item in customer.ShoppingCartItems)
            {
                EngineContext.Current.Resolve <ILogger>().InsertLog(Core.Domain.Logging.LogLevel.Information,
                                                                    "Cart Item ," + item.Product.Name,
                                                                    _priceService.GetSubTotal(item, true).ToString(), customer);
            }
            EngineContext.Current.Resolve <ILogger>().InsertLog(Core.Domain.Logging.LogLevel.Error, "TRanzilla Plugi2n",
                                                                $"Total {subTotalWithoutDiscount} ", customer);
            var storeContext   = EngineContext.Current.Resolve <IStoreContext>();
            var shippingOption = customer.GetAttribute <ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, storeContext.CurrentStore.Id);
            var settings       = _settingService.LoadSetting <TranzillaConfiguration>(storeScope);

            subTotal += (subTotal * settings.AdditionalPercentFee);

            var url = $"{settings.BaseUrl}?sum={subTotal.ToString("#.##")}&maxpay={settings.GetNumberOfPayments(subTotal)}&currency={settings.Currency}&nologo=1&cred_type={settings.CreditType}{(string.IsNullOrEmpty(settings.TranMode) ? "" : $"&tranmode={settings.TranMode}")}&lang={settings.Lang}&customerId={customer.Id}&trTextColor=503F2E&trButtonColor=503F2E";
Ejemplo n.º 14
0
        /// <summary>
        /// Check discount requirement
        /// </summary>
        /// <param name="request">Object that contains all information required to check the requirement (Current customer, discount, etc)</param>
        /// <returns>true - requirement is met; otherwise, false</returns>
        public DiscountRequirementValidationResult CheckRequirement(DiscountRequirementValidationRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var result = new DiscountRequirementValidationResult();

            var spentAmountRequirement = _settingService.GetSettingByKey <decimal>(string.Format("DiscountRequirement.ShoppingCart-{0}", request.DiscountRequirementId));

            if (spentAmountRequirement == decimal.Zero)
            {
                result.IsValid = true;
                return(result);
            }
            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                       .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                       .LimitPerStore(request.Store.Id)
                       .ToList();

            if (cart.Count == 0)
            {
                result.IsValid = false;
                return(result);
            }
            decimal spentAmount = 0;

            foreach (var ca in cart)
            {
                bool calculateWithDiscount = false;
                spentAmount += _priceCalculationService.GetSubTotal(ca, calculateWithDiscount);
            }

            result.IsValid = spentAmount > spentAmountRequirement;
            return(result);
        }
        public ActionResult GetCartDetails(int customerId)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrders))
            {
                return(AccessDeniedView());
            }

            var customer = _customerService.GetCustomerById(customerId);
            var cart     = customer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();

            var gridModel = new GridModel <ShoppingCartItemModel>()
            {
                Data = cart.Select(sci =>
                {
                    decimal taxRate;
                    var sciModel = new ShoppingCartItemModel()
                    {
                        Id               = sci.Id,
                        Store            = sci.Store != null ? sci.Store.Name : "Unknown",
                        ProductVariantId = sci.ProductVariantId,
                        Quantity         = sci.Quantity,
                        FullProductName  = !String.IsNullOrEmpty(sci.ProductVariant.Name) ?
                                           string.Format("{0} ({1})", sci.ProductVariant.Product.Name, sci.ProductVariant.Name) :
                                           sci.ProductVariant.Product.Name,
                        UnitPrice = _priceFormatter.FormatPrice(_taxService.GetProductPrice(sci.ProductVariant, _priceCalculationService.GetUnitPrice(sci, true), out taxRate)),
                        Total     = _priceFormatter.FormatPrice(_taxService.GetProductPrice(sci.ProductVariant, _priceCalculationService.GetSubTotal(sci, true), out taxRate)),
                        UpdatedOn = _dateTimeHelper.ConvertToUserTime(sci.UpdatedOnUtc, DateTimeKind.Utc)
                    };
                    return(sciModel);
                }),
                Total = cart.Count
            };

            return(new JsonResult
            {
                Data = gridModel
            });
        }
        /// <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);
            }
        }
        /// <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);
        }
Ejemplo n.º 18
0
        public IActionResult GetCartDetails(string customerId)
        {
            var customer = _customerService.GetCustomerById(customerId);
            var cart     = customer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();

            var gridModel = new DataSourceResult
            {
                Data = cart.Select(sci =>
                {
                    decimal taxRate;
                    var store    = _storeService.GetStoreById(sci.StoreId);
                    var product  = EngineContext.Current.Resolve <IProductService>().GetProductById(sci.ProductId);
                    var sciModel = new ShoppingCartItemModel
                    {
                        Id            = sci.Id,
                        Store         = store != null ? store.Name : "Unknown",
                        ProductId     = sci.ProductId,
                        Quantity      = sci.Quantity,
                        ProductName   = product.Name,
                        AttributeInfo = _productAttributeFormatter.FormatAttributes(product, sci.AttributesXml, customer),
                        UnitPrice     = _priceFormatter.FormatPrice(_taxService.GetProductPrice(product, _priceCalculationService.GetUnitPrice(sci), out taxRate)),
                        Total         = _priceFormatter.FormatPrice(_taxService.GetProductPrice(product, _priceCalculationService.GetSubTotal(sci), out taxRate)),
                        UpdatedOn     = _dateTimeHelper.ConvertToUserTime(sci.UpdatedOnUtc, DateTimeKind.Utc)
                    };
                    return(sciModel);
                }),
                Total = cart.Count
            };

            return(Json(gridModel));
        }
        /// <summary>
        /// Gets shopping cart subtotal
        /// </summary>
        /// <param name="cart">Cart</param>
        /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
        /// <param name="discountAmount">Applied discount amount</param>
        /// <param name="appliedDiscounts">Applied discounts</param>
        /// <param name="subTotalWithoutDiscount">Sub total (without discount)</param>
        /// <param name="subTotalWithDiscount">Sub total (with discount)</param>
        /// <param name="taxRates">Tax rates (of subscription sub total)</param>
        public virtual void GetShoppingCartSubTotal(IList <ShoppingCartItem> cart,
                                                    bool includingTax,
                                                    out decimal discountAmount,
                                                    out decimal subTotalWithoutDiscount, out decimal subTotalWithDiscount,
                                                    out SortedDictionary <decimal, decimal> taxRates)
        {
            discountAmount = decimal.Zero;

            subTotalWithoutDiscount = decimal.Zero;
            subTotalWithDiscount    = decimal.Zero;
            taxRates = new SortedDictionary <decimal, decimal>();

            if (!cart.Any())
            {
                return;
            }

            //get the customer
            Customer customer = cart.GetCustomer();

            //sub totals
            decimal subTotalExclTaxWithoutDiscount = decimal.Zero;
            decimal subTotalInclTaxWithoutDiscount = decimal.Zero;

            foreach (var shoppingCartItem in cart)
            {
                decimal sciSubTotal = _priceCalculationService.GetSubTotal(shoppingCartItem);

                decimal taxRate;
                decimal sciExclTax = _taxService.GetArticlePrice(shoppingCartItem.Article, sciSubTotal, false, customer, out taxRate);
                decimal sciInclTax = _taxService.GetArticlePrice(shoppingCartItem.Article, sciSubTotal, true, customer, out taxRate);
                subTotalExclTaxWithoutDiscount += sciExclTax;
                subTotalInclTaxWithoutDiscount += sciInclTax;

                //tax rates
                decimal sciTax = sciInclTax - sciExclTax;
                if (taxRate > decimal.Zero && sciTax > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(taxRate))
                    {
                        taxRates.Add(taxRate, sciTax);
                    }
                    else
                    {
                        taxRates[taxRate] = taxRates[taxRate] + sciTax;
                    }
                }
            }

            //checkout attributes
            if (customer != null)
            {
                var checkoutAttributesXml = customer.GetAttribute <string>(SystemCustomerAttributeNames.CheckoutAttributes, _genericAttributeService, _storeContext.CurrentStore.Id);
                var attributeValues       = _checkoutAttributeParser.ParseCheckoutAttributeValues(checkoutAttributesXml);
                if (attributeValues != null)
                {
                    foreach (var attributeValue in attributeValues)
                    {
                        decimal taxRate;

                        decimal caExclTax = _taxService.GetCheckoutAttributePrice(attributeValue, false, customer, out taxRate);
                        decimal caInclTax = _taxService.GetCheckoutAttributePrice(attributeValue, true, customer, out taxRate);
                        subTotalExclTaxWithoutDiscount += caExclTax;
                        subTotalInclTaxWithoutDiscount += caInclTax;

                        //tax rates
                        decimal caTax = caInclTax - caExclTax;
                        if (taxRate > decimal.Zero && caTax > decimal.Zero)
                        {
                            if (!taxRates.ContainsKey(taxRate))
                            {
                                taxRates.Add(taxRate, caTax);
                            }
                            else
                            {
                                taxRates[taxRate] = taxRates[taxRate] + caTax;
                            }
                        }
                    }
                }
            }

            //subtotal without discount
            subTotalWithoutDiscount = includingTax ? subTotalInclTaxWithoutDiscount : subTotalExclTaxWithoutDiscount;
            if (subTotalWithoutDiscount < decimal.Zero)
            {
                subTotalWithoutDiscount = decimal.Zero;
            }

            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                subTotalWithoutDiscount = RoundingHelper.RoundPrice(subTotalWithoutDiscount);
            }

            //We calculate discount amount on subscription subtotal excl tax (discount first)
            //calculate discount amount ('Applied to subscription subtotal' discount)
            decimal discountAmountExclTax = GetSubscriptionSubtotalDiscount(customer, subTotalExclTaxWithoutDiscount);

            if (subTotalExclTaxWithoutDiscount < discountAmountExclTax)
            {
                discountAmountExclTax = subTotalExclTaxWithoutDiscount;
            }
            decimal discountAmountInclTax = discountAmountExclTax;
            //subtotal with discount (excl tax)
            decimal subTotalExclTaxWithDiscount = subTotalExclTaxWithoutDiscount - discountAmountExclTax;
            decimal subTotalInclTaxWithDiscount = subTotalExclTaxWithDiscount;

            //add tax for shopping items & checkout attributes
            var tempTaxRates = new Dictionary <decimal, decimal>(taxRates);

            foreach (KeyValuePair <decimal, decimal> kvp in tempTaxRates)
            {
                decimal taxRate  = kvp.Key;
                decimal taxValue = kvp.Value;

                if (taxValue != decimal.Zero)
                {
                    //discount the tax amount that applies to subtotal items
                    if (subTotalExclTaxWithoutDiscount > decimal.Zero)
                    {
                        decimal discountTax = taxRates[taxRate] * (discountAmountExclTax / subTotalExclTaxWithoutDiscount);
                        discountAmountInclTax += discountTax;
                        taxValue = taxRates[taxRate] - discountTax;
                        if (_shoppingCartSettings.RoundPricesDuringCalculation)
                        {
                            taxValue = RoundingHelper.RoundPrice(taxValue);
                        }
                        taxRates[taxRate] = taxValue;
                    }

                    //subtotal with discount (incl tax)
                    subTotalInclTaxWithDiscount += taxValue;
                }
            }

            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                discountAmountInclTax = RoundingHelper.RoundPrice(discountAmountInclTax);
                discountAmountExclTax = RoundingHelper.RoundPrice(discountAmountExclTax);
            }

            if (includingTax)
            {
                subTotalWithDiscount = subTotalInclTaxWithDiscount;
                discountAmount       = discountAmountInclTax;
            }
            else
            {
                subTotalWithDiscount = subTotalExclTaxWithDiscount;
                discountAmount       = discountAmountExclTax;
            }

            if (subTotalWithDiscount < decimal.Zero)
            {
                subTotalWithDiscount = decimal.Zero;
            }

            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                subTotalWithDiscount = RoundingHelper.RoundPrice(subTotalWithDiscount);
            }
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="request">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("getShippingOptionRequest");
            }

            var response = new GetShippingOptionResponse();

            if (request.Items == null || request.Items.Count == 0)
            {
                response.AddError(T("Admin.System.Warnings.NoShipmentItems"));
                return(response);
            }

            int     storeId         = request.StoreId > 0 ? request.StoreId : _storeContext.CurrentStore.Id;
            var     taxRate         = decimal.Zero;
            decimal subTotalInclTax = decimal.Zero;
            decimal subTotalExclTax = decimal.Zero;
            decimal currentSubTotal = decimal.Zero;
            int     countryId       = 0;
            string  zip             = null;

            if (request.ShippingAddress != null)
            {
                countryId = request.ShippingAddress.CountryId ?? 0;
                zip       = request.ShippingAddress.ZipPostalCode;
            }

            foreach (var shoppingCartItem in request.Items)
            {
                if (shoppingCartItem.Item.IsFreeShipping || !shoppingCartItem.Item.IsShipEnabled)
                {
                    continue;
                }

                var itemSubTotal = _priceCalculationService.GetSubTotal(shoppingCartItem, true);

                var itemSubTotalInclTax = _taxService.GetProductPrice(shoppingCartItem.Item.Product, itemSubTotal, true, request.Customer, out taxRate);
                subTotalInclTax += itemSubTotalInclTax;

                var itemSubTotalExclTax = _taxService.GetProductPrice(shoppingCartItem.Item.Product, itemSubTotal, false, request.Customer, out taxRate);
                subTotalExclTax += itemSubTotalExclTax;
            }

            var weight          = _shippingService.GetShoppingCartTotalWeight(request.Items, _shippingByWeightSettings.IncludeWeightOfFreeShippingProducts);
            var shippingMethods = _shippingService.GetAllShippingMethods(request, storeId);

            currentSubTotal = _services.WorkContext.TaxDisplayType == TaxDisplayType.ExcludingTax ? subTotalExclTax : subTotalInclTax;

            foreach (var shippingMethod in shippingMethods)
            {
                var record = _shippingByWeightService.FindRecord(shippingMethod.Id, storeId, countryId, weight, zip);

                decimal?rate = GetRate(subTotalInclTax, weight, shippingMethod.Id, storeId, countryId, zip);
                if (rate.HasValue)
                {
                    var shippingOption = new ShippingOption();
                    shippingOption.ShippingMethodId = shippingMethod.Id;
                    shippingOption.Name             = shippingMethod.GetLocalized(x => x.Name);

                    if (record != null && record.SmallQuantityThreshold > currentSubTotal)
                    {
                        string surchargeHint = T("Plugins.Shipping.ByWeight.SmallQuantitySurchargeNotReached",
                                                 _priceFormatter.FormatPrice(record.SmallQuantitySurcharge),
                                                 _priceFormatter.FormatPrice(record.SmallQuantityThreshold));

                        shippingOption.Description = shippingMethod.GetLocalized(x => x.Description) + surchargeHint;
                        shippingOption.Rate        = rate.Value + record.SmallQuantitySurcharge;
                    }
                    else
                    {
                        shippingOption.Description = shippingMethod.GetLocalized(x => x.Description);
                        shippingOption.Rate        = rate.Value;
                    }
                    response.ShippingOptions.Add(shippingOption);
                }
            }

            return(response);
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
            {
                throw new ArgumentNullException("getShippingOptionRequest");
            }

            var response = new GetShippingOptionResponse();

            if (getShippingOptionRequest.Items == null || !getShippingOptionRequest.Items.Any())
            {
                response.AddError("No shipment items");
                return(response);
            }

            //choose the shipping rate calculation method
            if (_fixedOrByWeightSettings.ShippingByWeightEnabled)
            {
                //shipping rate calculation by products weight

                if (getShippingOptionRequest.ShippingAddress == null)
                {
                    response.AddError("Shipping address is not set");
                    return(response);
                }

                var storeId = getShippingOptionRequest.StoreId;

                if (storeId == 0)
                {
                    storeId = _storeContext.CurrentStore.Id;
                }

                var countryId       = getShippingOptionRequest.ShippingAddress.CountryId.HasValue ? getShippingOptionRequest.ShippingAddress.CountryId.Value : 0;
                var stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId.HasValue ? getShippingOptionRequest.ShippingAddress.StateProvinceId.Value : 0;
                var warehouseId     = getShippingOptionRequest.WarehouseFrom != null ? getShippingOptionRequest.WarehouseFrom.Id : 0;
                var zip             = getShippingOptionRequest.ShippingAddress.ZipPostalCode;
                var subTotal        = decimal.Zero;

                foreach (var packageItem in getShippingOptionRequest.Items)
                {
                    if (packageItem.ShoppingCartItem.IsFreeShipping)
                    {
                        continue;
                    }
                    //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal
                    subTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem);
                }

                var weight = _shippingService.GetTotalWeight(getShippingOptionRequest);

                var shippingMethods = _shippingService.GetAllShippingMethods(countryId);
                foreach (var shippingMethod in shippingMethods)
                {
                    var rate = GetRate(subTotal, weight, shippingMethod.Id, storeId, warehouseId, countryId, stateProvinceId, zip);

                    if (!rate.HasValue)
                    {
                        continue;
                    }

                    var shippingOption = new ShippingOption
                    {
                        Name        = shippingMethod.GetLocalized(x => x.Name),
                        Description = shippingMethod.GetLocalized(x => x.Description),
                        Rate        = rate.Value
                    };

                    response.ShippingOptions.Add(shippingOption);
                }
            }
            else
            {
                //shipping rate calculation by fixed rate

                var restrictByCountryId = getShippingOptionRequest.ShippingAddress != null && getShippingOptionRequest.ShippingAddress.Country != null ? (int?)getShippingOptionRequest.ShippingAddress.Country.Id : null;
                var shippingMethods     = _shippingService.GetAllShippingMethods(restrictByCountryId);

                foreach (var shippingMethod in shippingMethods)
                {
                    var shippingOption = new ShippingOption
                    {
                        Name        = shippingMethod.GetLocalized(x => x.Name),
                        Description = shippingMethod.GetLocalized(x => x.Description),
                        Rate        = GetRate(shippingMethod.Id)
                    };
                    response.ShippingOptions.Add(shippingOption);
                }
            }

            return(response);
        }
Ejemplo n.º 22
0
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
            {
                throw new ArgumentNullException("getShippingOptionRequest");
            }

            var response = new GetShippingOptionResponse();

            if (getShippingOptionRequest.Items == null || getShippingOptionRequest.Items.Count == 0)
            {
                response.AddError("No shipment items");
                return(response);
            }

            int     storeId   = _storeContext.CurrentStore.Id;
            decimal subTotal  = decimal.Zero;
            int     countryId = 0;

            if (getShippingOptionRequest.ShippingAddress != null)
            {
                countryId = getShippingOptionRequest.ShippingAddress.CountryId ?? 0;
            }

            foreach (var shoppingCartItem in getShippingOptionRequest.Items)
            {
                if (shoppingCartItem.Item.IsFreeShipping || !shoppingCartItem.Item.IsShipEnabled)
                {
                    continue;
                }
                subTotal += _priceCalculationService.GetSubTotal(shoppingCartItem, true);
            }
            decimal weight = _shippingService.GetShoppingCartTotalWeight(getShippingOptionRequest.Items);

            var shippingMethods = _shippingService.GetAllShippingMethods(countryId);

            foreach (var shippingMethod in shippingMethods)
            {
                var record = _shippingByWeightService.FindRecord(shippingMethod.Id, storeId, countryId, weight);

                decimal?rate = GetRate(subTotal, weight, shippingMethod.Id, storeId, countryId);
                if (rate.HasValue)
                {
                    var shippingOption = new ShippingOption();
                    shippingOption.Name = shippingMethod.GetLocalized(x => x.Name);

                    if (record != null && record.SmallQuantityThreshold > subTotal)
                    {
                        shippingOption.Description = shippingMethod.GetLocalized(x => x.Description)
                                                     + _localizationService.GetResource("Plugin.Shipping.ByWeight.SmallQuantitySurchargeNotReached").FormatWith(
                            _priceFormatter.FormatPrice(record.SmallQuantitySurcharge),
                            _priceFormatter.FormatPrice(record.SmallQuantityThreshold));

                        shippingOption.Rate = rate.Value + record.SmallQuantitySurcharge;
                    }
                    else
                    {
                        shippingOption.Description = shippingMethod.GetLocalized(x => x.Description);
                        shippingOption.Rate        = rate.Value;
                    }
                    response.ShippingOptions.Add(shippingOption);
                }
            }


            return(response);
        }
Ejemplo n.º 23
0
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
            {
                throw new ArgumentNullException(nameof(getShippingOptionRequest));
            }

            var response = new GetShippingOptionResponse();

            if (getShippingOptionRequest.Items == null || !getShippingOptionRequest.Items.Any())
            {
                response.AddError("No shipment items");
                return(response);
            }

            //choose the shipping rate calculation method
            if (_fixedByWeightByTotalSettings.ShippingByWeightByTotalEnabled)
            {
                //shipping rate calculation by products weight

                if (getShippingOptionRequest.ShippingAddress == null)
                {
                    response.AddError("Shipping address is not set");
                    return(response);
                }

                var storeId         = getShippingOptionRequest.StoreId != 0 ? getShippingOptionRequest.StoreId : _storeContext.CurrentStore.Id;
                var countryId       = getShippingOptionRequest.ShippingAddress.CountryId ?? 0;
                var stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId ?? 0;
                var warehouseId     = getShippingOptionRequest.WarehouseFrom?.Id ?? 0;
                var zip             = getShippingOptionRequest.ShippingAddress.ZipPostalCode;

                //get subtotal of shipped items
                var subTotal = decimal.Zero;
                foreach (var packageItem in getShippingOptionRequest.Items)
                {
                    if (packageItem.ShoppingCartItem.IsFreeShipping(_productService, _productAttributeParser))
                    {
                        continue;
                    }

                    //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal
                    subTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem);
                }

                //get weight of shipped items (excluding items with free shipping)
                var weight = _shippingService.GetTotalWeight(getShippingOptionRequest, ignoreFreeShippedItems: true);

                foreach (var shippingMethod in _shippingService.GetAllShippingMethods(countryId))
                {
                    var rate = GetRate(subTotal, weight, shippingMethod.Id, storeId, warehouseId, countryId, stateProvinceId, zip);
                    if (!rate.HasValue)
                    {
                        continue;
                    }

                    response.ShippingOptions.Add(new ShippingOption
                    {
                        Name        = shippingMethod.GetLocalized(x => x.Name),
                        Description = shippingMethod.GetLocalized(x => x.Description),
                        Rate        = rate.Value
                    });
                }
            }
            else
            {
                //shipping rate calculation by fixed rate
                var restrictByCountryId = getShippingOptionRequest.ShippingAddress?.Country?.Id;
                response.ShippingOptions = _shippingService.GetAllShippingMethods(restrictByCountryId).Select(shippingMethod => new ShippingOption
                {
                    Name        = shippingMethod.GetLocalized(x => x.Name),
                    Description = shippingMethod.GetLocalized(x => x.Description),
                    Rate        = GetRate(shippingMethod.Id)
                }).ToList();
            }

            return(response);
        }
        public async Task <WishlistModel> Handle(GetWishlist request, CancellationToken cancellationToken)
        {
            var model = new WishlistModel();

            model.EmailWishlistEnabled = _shoppingCartSettings.EmailWishlistEnabled;
            model.IsEditable           = request.IsEditable;
            model.DisplayAddToCart     = await _permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart);

            model.DisplayTaxShippingInfo = _catalogSettings.DisplayTaxShippingInfoWishlist;

            if (!request.Cart.Any())
            {
                return(model);
            }

            #region Simple properties

            model.CustomerGuid      = request.Customer.CustomerGuid;
            model.CustomerFullname  = request.Customer.GetFullName();
            model.ShowProductImages = _shoppingCartSettings.ShowProductImagesOnWishList;
            model.ShowSku           = _catalogSettings.ShowSkuOnProductDetailsPage;

            //cart warnings
            var cartWarnings = await _shoppingCartService.GetShoppingCartWarnings(request.Cart, "", false);

            foreach (var warning in cartWarnings)
            {
                model.Warnings.Add(warning);
            }

            #endregion

            #region Cart items

            foreach (var sci in request.Cart)
            {
                var product = await _productService.GetProductById(sci.ProductId);

                var cartItemModel = new WishlistModel.ShoppingCartItemModel {
                    Id            = sci.Id,
                    Sku           = product.FormatSku(sci.AttributesXml, _productAttributeParser),
                    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),
                };

                //allow editing?
                //1. setting enabled?
                //2. simple product?
                //3. has attribute or gift card?
                //4. visible individually?
                cartItemModel.AllowItemEditing = _shoppingCartSettings.AllowCartItemEditing && product.ProductType == ProductType.SimpleProduct && (!String.IsNullOrEmpty(cartItemModel.AttributeInfo) || product.IsGiftCard) && product.VisibleIndividually;

                //allowed quantities
                var allowedQuantities = product.ParseAllowedQuantities();
                foreach (var qty in allowedQuantities)
                {
                    cartItemModel.AllowedQuantities.Add(new SelectListItem {
                        Text     = qty.ToString(),
                        Value    = qty.ToString(),
                        Selected = sci.Quantity == qty
                    });
                }


                //recurring info
                if (product.IsRecurring)
                {
                    cartItemModel.RecurringInfo = string.Format(_localizationService.GetResource("ShoppingCart.RecurringPeriod"), product.RecurringCycleLength, product.RecurringCyclePeriod.GetLocalizedEnum(_localizationService, request.Language.Id));
                }

                //unit prices
                if (product.CallForPrice)
                {
                    cartItemModel.UnitPrice = _localizationService.GetResource("Products.CallForPrice");
                }
                else
                {
                    var productprice = await _taxService.GetProductPrice(product, (await _priceCalculationService.GetUnitPrice(sci)).unitprice);

                    decimal taxRate = productprice.taxRate;
                    decimal shoppingCartUnitPriceWithDiscountBase = productprice.productprice;
                    decimal shoppingCartUnitPriceWithDiscount     = await _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartUnitPriceWithDiscountBase, request.Currency);

                    cartItemModel.UnitPrice = _priceFormatter.FormatPrice(shoppingCartUnitPriceWithDiscount);
                }
                //subtotal, discount
                if (product.CallForPrice)
                {
                    cartItemModel.SubTotal = _localizationService.GetResource("Products.CallForPrice");
                }
                else
                {
                    //sub total
                    var subtotal = await _priceCalculationService.GetSubTotal(sci, true);

                    decimal shoppingCartItemDiscountBase = subtotal.discountAmount;
                    List <AppliedDiscount> scDiscounts   = subtotal.appliedDiscounts;
                    var productprices = await _taxService.GetProductPrice(product, subtotal.subTotal);

                    decimal taxRate = productprices.taxRate;
                    decimal shoppingCartItemSubTotalWithDiscountBase = productprices.productprice;

                    decimal shoppingCartItemSubTotalWithDiscount = await _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartItemSubTotalWithDiscountBase, request.Currency);

                    cartItemModel.SubTotal = _priceFormatter.FormatPrice(shoppingCartItemSubTotalWithDiscount);

                    //display an applied discount amount
                    if (shoppingCartItemDiscountBase > decimal.Zero)
                    {
                        shoppingCartItemDiscountBase = (await _taxService.GetProductPrice(product, shoppingCartItemDiscountBase)).productprice;
                        if (shoppingCartItemDiscountBase > decimal.Zero)
                        {
                            decimal shoppingCartItemDiscount = await _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartItemDiscountBase, request.Currency);

                            cartItemModel.Discount = _priceFormatter.FormatPrice(shoppingCartItemDiscount);
                        }
                    }
                }

                //picture
                if (_shoppingCartSettings.ShowProductImagesOnWishList)
                {
                    cartItemModel.Picture = await PrepareCartItemPicture(request, product, sci.AttributesXml);
                }

                //item warnings
                var itemWarnings = await _shoppingCartService.GetShoppingCartItemWarnings(request.Customer, sci, product, false);

                foreach (var warning in itemWarnings)
                {
                    cartItemModel.Warnings.Add(warning);
                }

                model.Items.Add(cartItemModel);
            }

            #endregion

            return(model);
        }
Ejemplo n.º 25
0
        private async Task PrepareCartItems(ShoppingCartModel model, GetShoppingCart request)
        {
            #region Cart items

            foreach (var sci in request.Cart)
            {
                var product = await _productService.GetProductById(sci.ProductId);

                if (product == null)
                {
                    continue;
                }

                var cartItemModel = new ShoppingCartModel.ShoppingCartItemModel {
                    Id            = sci.Id,
                    Sku           = product.FormatSku(sci.AttributesXml, _productAttributeParser),
                    IsCart        = sci.ShoppingCartType == ShoppingCartType.ShoppingCart,
                    ProductId     = product.Id,
                    WarehouseId   = sci.WarehouseId,
                    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),
                };

                //allow editing?
                //1. setting enabled?
                //2. simple product?
                //3. has attribute or gift card?
                //4. visible individually?
                cartItemModel.AllowItemEditing = _shoppingCartSettings.AllowCartItemEditing &&
                                                 product.ProductType == ProductType.SimpleProduct &&
                                                 (!String.IsNullOrEmpty(cartItemModel.AttributeInfo) || product.IsGiftCard) &&
                                                 product.VisibleIndividually;

                //disable removal?
                //1. do other items require this one?
                if (product.RequireOtherProducts)
                {
                    cartItemModel.DisableRemoval = product.RequireOtherProducts && product.ParseRequiredProductIds().Intersect(request.Cart.Select(x => x.ProductId)).Any();
                }

                //warehouse
                if (!string.IsNullOrEmpty(cartItemModel.WarehouseId))
                {
                    cartItemModel.WarehouseName = (await _warehouseService.GetWarehouseById(cartItemModel.WarehouseId))?.Name;
                }

                //vendor
                if (!string.IsNullOrEmpty(product.VendorId))
                {
                    var vendor = await _vendorService.GetVendorById(product.VendorId);

                    if (vendor != null)
                    {
                        cartItemModel.VendorId     = product.VendorId;
                        cartItemModel.VendorName   = vendor.Name;
                        cartItemModel.VendorSeName = vendor.GetSeName(request.Language.Id);
                    }
                }
                //allowed quantities
                var allowedQuantities = product.ParseAllowedQuantities();
                foreach (var qty in allowedQuantities)
                {
                    cartItemModel.AllowedQuantities.Add(new SelectListItem {
                        Text     = qty.ToString(),
                        Value    = qty.ToString(),
                        Selected = sci.Quantity == qty
                    });
                }

                //recurring info
                if (product.IsRecurring)
                {
                    cartItemModel.RecurringInfo = string.Format(_localizationService.GetResource("ShoppingCart.RecurringPeriod"), product.RecurringCycleLength, product.RecurringCyclePeriod.GetLocalizedEnum(_localizationService, request.Language.Id));
                }

                //reservation info
                if (product.ProductType == ProductType.Reservation)
                {
                    if (sci.RentalEndDateUtc == default(DateTime) || sci.RentalEndDateUtc == null)
                    {
                        cartItemModel.ReservationInfo = string.Format(_localizationService.GetResource("ShoppingCart.Reservation.StartDate"), sci.RentalStartDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat));
                    }
                    else
                    {
                        cartItemModel.ReservationInfo = string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Date"), sci.RentalStartDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat), sci.RentalEndDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat));
                    }

                    if (!string.IsNullOrEmpty(sci.Parameter))
                    {
                        cartItemModel.ReservationInfo += "<br>" + string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Option"), sci.Parameter);
                        cartItemModel.Parameter        = sci.Parameter;
                    }
                    if (!string.IsNullOrEmpty(sci.Duration))
                    {
                        cartItemModel.ReservationInfo += "<br>" + string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Duration"), sci.Duration);
                    }
                }
                if (sci.ShoppingCartType == ShoppingCartType.Auctions)
                {
                    cartItemModel.DisableRemoval = true;
                    cartItemModel.AuctionInfo    = _localizationService.GetResource("ShoppingCart.auctionwonon") + " " + _dateTimeHelper.ConvertToUserTime(product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc).ToString();
                }

                //unit prices
                if (product.CallForPrice)
                {
                    cartItemModel.UnitPrice = _localizationService.GetResource("Products.CallForPrice");
                    cartItemModel.SubTotal  = _localizationService.GetResource("Products.CallForPrice");
                    cartItemModel.UnitPriceWithoutDiscount = _localizationService.GetResource("Products.CallForPrice");
                }
                else
                {
                    var unitprices = await _priceCalculationService.GetUnitPrice(sci, product, true);

                    decimal discountAmount = unitprices.discountAmount;
                    List <AppliedDiscount> appliedDiscounts = unitprices.appliedDiscounts;
                    var productprices = await _taxService.GetProductPrice(product, unitprices.unitprice);

                    decimal taxRate = productprices.taxRate;

                    cartItemModel.UnitPriceWithoutDiscountValue =
                        (await _taxService.GetProductPrice(product, (await _priceCalculationService.GetUnitPrice(sci, product, false)).unitprice)).productprice;

                    cartItemModel.UnitPriceWithoutDiscount = _priceFormatter.FormatPrice(cartItemModel.UnitPriceWithoutDiscountValue);
                    cartItemModel.UnitPriceValue           = productprices.productprice;
                    cartItemModel.UnitPrice = _priceFormatter.FormatPrice(productprices.productprice);
                    if (appliedDiscounts != null && appliedDiscounts.Any())
                    {
                        var discount = await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault().DiscountId);

                        if (discount != null && discount.MaximumDiscountedQuantity.HasValue)
                        {
                            cartItemModel.DiscountedQty = discount.MaximumDiscountedQuantity.Value;
                        }

                        foreach (var disc in appliedDiscounts)
                        {
                            cartItemModel.Discounts.Add(disc.DiscountId);
                        }
                    }
                    //sub total
                    var subtotal = await _priceCalculationService.GetSubTotal(sci, product, true);

                    decimal shoppingCartItemDiscountBase     = subtotal.discountAmount;
                    List <AppliedDiscount> scDiscounts       = subtotal.appliedDiscounts;
                    var shoppingCartItemSubTotalWithDiscount = (await _taxService.GetProductPrice(product, subtotal.subTotal)).productprice;
                    cartItemModel.SubTotal      = _priceFormatter.FormatPrice(shoppingCartItemSubTotalWithDiscount);
                    cartItemModel.SubTotalValue = shoppingCartItemSubTotalWithDiscount;

                    //display an applied discount amount
                    if (shoppingCartItemDiscountBase > decimal.Zero)
                    {
                        shoppingCartItemDiscountBase = (await _taxService.GetProductPrice(product, shoppingCartItemDiscountBase)).productprice;
                        if (shoppingCartItemDiscountBase > decimal.Zero)
                        {
                            cartItemModel.Discount = _priceFormatter.FormatPrice(shoppingCartItemDiscountBase);
                        }
                    }
                }
                //picture
                if (_shoppingCartSettings.ShowProductImagesOnShoppingCart)
                {
                    cartItemModel.Picture = await PrepareCartItemPicture(product, sci.AttributesXml, request.Language.Id, request.Store.Id);
                }

                //item warnings
                var itemWarnings = await _shoppingCartService.GetShoppingCartItemWarnings(request.Customer, sci, product, false);

                foreach (var warning in itemWarnings)
                {
                    cartItemModel.Warnings.Add(warning);
                }

                model.Items.Add(cartItemModel);
            }

            #endregion
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> GetCartDetails(string customerId)
        {
            var customer = await _customerService.GetCustomerById(customerId);

            var cart  = customer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
            var items = new List <ShoppingCartItemModel>();

            foreach (var sci in cart)
            {
                var store = await _storeService.GetStoreById(sci.StoreId);

                var product = await _productService.GetProductById(sci.ProductId);

                var sciModel = new ShoppingCartItemModel {
                    Id            = sci.Id,
                    Store         = store != null ? store.Shortcut : "Unknown",
                    ProductId     = sci.ProductId,
                    Quantity      = sci.Quantity,
                    ProductName   = product.Name,
                    AttributeInfo = await _productAttributeFormatter.FormatAttributes(product, sci.AttributesXml, customer),
                    UnitPrice     = _priceFormatter.FormatPrice((await _taxService.GetProductPrice(product, (await _priceCalculationService.GetUnitPrice(sci, product)).unitprice)).productprice),
                    Total         = _priceFormatter.FormatPrice((await _taxService.GetProductPrice(product, (await _priceCalculationService.GetSubTotal(sci, product)).subTotal)).productprice),
                    UpdatedOn     = _dateTimeHelper.ConvertToUserTime(sci.UpdatedOnUtc, DateTimeKind.Utc)
                };
                items.Add(sciModel);
            }
            var gridModel = new DataSourceResult {
                Data  = items,
                Total = cart.Count
            };

            return(Json(gridModel));
        }
Ejemplo n.º 27
0
        public ActionResult GetCartDetails(int customerId)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCurrentCarts))
            {
                return(AccessDeniedView());
            }

            var customer = _customerService.GetCustomerById(customerId);
            var cart     = customer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();

            var gridModel = new DataSourceResult
            {
                Data = cart.Select(sci =>
                {
                    decimal taxRate;
                    var store    = _storeService.GetStoreById(sci.StoreId);
                    var sciModel = new ShoppingCartItemModel
                    {
                        Id            = sci.Id,
                        Store         = store != null ? store.Name : "Unknown",
                        ProductId     = sci.ProductId,
                        Quantity      = sci.Quantity,
                        ProductName   = sci.Product.Name,
                        AttributeInfo = _productAttributeFormatter.FormatAttributes(sci.Product, sci.AttributesXml, sci.Customer),
                        UnitPrice     = _priceFormatter.FormatPrice(_taxService.GetProductPrice(sci.Product, _priceCalculationService.GetUnitPrice(sci), out taxRate)),
                        Total         = _priceFormatter.FormatPrice(_taxService.GetProductPrice(sci.Product, _priceCalculationService.GetSubTotal(sci), out taxRate)),
                        UpdatedOn     = _dateTimeHelper.ConvertToUserTime(sci.UpdatedOnUtc, DateTimeKind.Utc)
                    };
                    return(sciModel);
                }),
                Total = cart.Count
            };

            return(Json(gridModel));
        }
Ejemplo n.º 28
0
        private string CreateRequest(string username, string password, GetShippingOptionRequest getShippingOptionRequest)
        {
            var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword(MEASUREWEIGHTSYSTEMKEYWORD);

            if (usedMeasureWeight == null)
            {
                throw new NopException(string.Format("USPS shipping service. Could not load \"{0}\" measure weight", MEASUREWEIGHTSYSTEMKEYWORD));
            }

            var baseusedMeasureWeight = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId);

            if (baseusedMeasureWeight == null)
            {
                throw new NopException("Primary weight can't be loaded");
            }

            var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword(MEASUREDIMENSIONSYSTEMKEYWORD);

            if (usedMeasureDimension == null)
            {
                throw new NopException(string.Format("USPS shipping service. Could not load \"{0}\" measure dimension", MEASUREDIMENSIONSYSTEMKEYWORD));
            }

            var baseusedMeasureDimension = _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId);

            if (baseusedMeasureDimension == null)
            {
                throw new NopException("Primary dimension can't be loaded");
            }

            decimal lengthTmp, widthTmp, heightTmp;

            _shippingService.GetDimensions(getShippingOptionRequest.Items, out widthTmp, out lengthTmp, out heightTmp);


            int length = Convert.ToInt32(Math.Ceiling(lengthTmp / baseusedMeasureDimension.Ratio * usedMeasureDimension.Ratio));
            int height = Convert.ToInt32(Math.Ceiling(heightTmp / baseusedMeasureDimension.Ratio * usedMeasureDimension.Ratio));
            int width  = Convert.ToInt32(Math.Ceiling(widthTmp / baseusedMeasureDimension.Ratio * usedMeasureDimension.Ratio));
            int weight = Convert.ToInt32(Math.Ceiling(_shippingService.GetTotalWeight(getShippingOptionRequest) / baseusedMeasureWeight.Ratio * usedMeasureWeight.Ratio));


            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;

            //valid values for testing. http://testing.shippingapis.com/ShippingAPITest.dll
            //Zip to = "20008"; Zip from ="10022"; weight = 2;



            int pounds = Convert.ToInt32(weight / 16);
            int ounces = Convert.ToInt32(weight - (pounds * 16.0M));
            int girth  = height + height + width + width;
            //Get shopping cart sub-total.  V2 International rates require the package value to be declared.
            decimal subTotal = decimal.Zero;

            foreach (var packageItem in getShippingOptionRequest.Items)
            {
                //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal
                subTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem);
            }



            string requestString;

            bool isDomestic = IsDomesticRequest(getShippingOptionRequest);

            if (isDomestic)
            {
                #region domestic request
                zipPostalCodeFrom = CommonHelper.EnsureMaximumLength(CommonHelper.EnsureNumericOnly(zipPostalCodeFrom), 5);
                zipPostalCodeTo   = CommonHelper.EnsureMaximumLength(CommonHelper.EnsureNumericOnly(zipPostalCodeTo), 5);

                var sb = new StringBuilder();
                sb.AppendFormat("<RateV4Request USERID=\"{0}\" PASSWORD=\"{1}\">", username, password);
                sb.Append("<Revision>2</Revision>");

                var xmlStrings = new USPSStrings(); // Create new instance with string array

                if ((!IsPackageTooHeavy(pounds)) && (!IsPackageTooLarge(length, height, width)))
                {
                    var packageSize = GetPackageSize(length, height, width);
                    // RJH get all XML strings not commented out for USPSStrings.
                    // RJH V3 USPS Service must be Express, Express SH, Express Commercial, Express SH Commercial, First Class, Priority, Priority Commercial, Parcel, Library, BPM, Media, ALL or ONLINE;
                    // AC - Updated to V4 API and made minor improvements to allow First Class Packages (package only - not envelopes).


                    foreach (string element in xmlStrings.Elements) // Loop over elements with property
                    {
                        if ((element == "First Class") && (weight >= 14))
                        {
                            // AC - At the time of coding there aren't any First Class shipping options for packages over 13 ounces.
                        }
                        else
                        {
                            sb.Append("<Package ID=\"0\">");

                            sb.AppendFormat("<Service>{0}</Service>", element);
                            if (element == "First Class")
                            {
                                sb.Append("<FirstClassMailType>PARCEL</FirstClassMailType>");
                            }

                            sb.AppendFormat("<ZipOrigination>{0}</ZipOrigination>", zipPostalCodeFrom);
                            sb.AppendFormat("<ZipDestination>{0}</ZipDestination>", zipPostalCodeTo);
                            sb.AppendFormat("<Pounds>{0}</Pounds>", pounds);
                            sb.AppendFormat("<Ounces>{0}</Ounces>", ounces);
                            sb.Append("<Container/>");
                            sb.AppendFormat("<Size>{0}</Size>", packageSize);
                            sb.AppendFormat("<Width>{0}</Width>", width);
                            sb.AppendFormat("<Length>{0}</Length>", length);
                            sb.AppendFormat("<Height>{0}</Height>", height);
                            sb.AppendFormat("<Girth>{0}</Girth>", girth);

                            sb.Append("<Machinable>FALSE</Machinable>");

                            sb.Append("</Package>");
                        }
                    }
                }
                else
                {
                    int totalPackagesDims    = 1;
                    int totalPackagesWeights = 1;
                    if (IsPackageTooHeavy(pounds))
                    {
                        totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)pounds / (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;
                    }

                    int pounds2 = pounds / totalPackages;
                    //we don't use ounces
                    int ounces2 = ounces / totalPackages;
                    int height2 = height / totalPackages;
                    int width2  = width / totalPackages;
                    int length2 = length / totalPackages;
                    if (pounds2 < 1)
                    {
                        pounds2 = 1;
                    }
                    if (height2 < 1)
                    {
                        height2 = 1;
                    }
                    if (width2 < 1)
                    {
                        width2 = 1;
                    }
                    if (length2 < 1)
                    {
                        length2 = 1;
                    }

                    var packageSize = GetPackageSize(length2, height2, width2);

                    int girth2 = height2 + height2 + width2 + width2;

                    for (int i = 0; i < totalPackages; i++)
                    {
                        foreach (string element in xmlStrings.Elements)
                        {
                            if ((element == "First Class") && (weight >= 14))
                            {
                                // AC - At the time of coding there aren't any First Class shipping options for packages over 13 ounces.
                            }
                            else
                            {
                                sb.AppendFormat("<Package ID=\"{0}\">", i.ToString());
                                sb.AppendFormat("<Service>{0}</Service>", element);
                                if (element == "First Class")
                                {
                                    sb.Append("<FirstClassMailType>PARCEL</FirstClassMailType>");
                                }
                                sb.AppendFormat("<ZipOrigination>{0}</ZipOrigination>", zipPostalCodeFrom);
                                sb.AppendFormat("<ZipDestination>{0}</ZipDestination>", zipPostalCodeTo);
                                sb.AppendFormat("<Pounds>{0}</Pounds>", pounds2);
                                sb.AppendFormat("<Ounces>{0}</Ounces>", ounces2);
                                sb.Append("<Container/>");
                                sb.AppendFormat("<Size>{0}</Size>", packageSize);
                                sb.AppendFormat("<Width>{0}</Width>", width2);
                                sb.AppendFormat("<Length>{0}</Length>", length2);
                                sb.AppendFormat("<Height>{0}</Height>", height2);
                                sb.AppendFormat("<Girth>{0}</Girth>", girth2);
                                sb.Append("<Machinable>FALSE</Machinable>");
                                sb.Append("</Package>");
                            }
                        }
                    }
                }

                sb.Append("</RateV4Request>");

                requestString = "API=RateV4&XML=" + sb.ToString();
                #endregion
            }
            else
            {
                #region international request
                var sb = new StringBuilder();
                // sb.AppendFormat("<IntlRateRequest USERID=\"{0}\" PASSWORD=\"{1}\">", username, password);
                sb.AppendFormat("<IntlRateV2Request USERID=\"{0}\" PASSWORD=\"{1}\">", username, password);
                sb.AppendFormat("<Revision>2</Revision>");

                //V2 International rates require the package value to be declared.  Max content value for most shipping options is $400 so it is limited here.
                decimal intlSubTotal = subTotal > 400 ? 400 : subTotal;

                //little hack here for international requests
                length = 12;
                width  = 12;
                height = 12;
                girth  = height + height + width + width;

                string mailType    = "Package"; //Package, Envelope
                var    packageSize = GetPackageSize(length, height, width);

                var countryName = getShippingOptionRequest.ShippingAddress.Country.Name;
                //USPS country hacks
                //The USPS wants the NAME of the country for international shipments rather than one of the ISO codes
                //It requires "Korea, Republic of (South Korea)" rather than "Korea".
                if (countryName == "Korea")
                {
                    countryName = "Korea, Republic of (South Korea)";
                }

                if ((!IsPackageTooHeavy(pounds)) && (!IsPackageTooLarge(length, height, width)))
                {
                    sb.Append("<Package ID=\"0\">");
                    sb.AppendFormat("<Pounds>{0}</Pounds>", pounds);
                    sb.AppendFormat("<Ounces>{0}</Ounces>", ounces);
                    sb.Append("<Machinable>FALSE</Machinable>");
                    sb.AppendFormat("<MailType>{0}</MailType>", mailType);
                    sb.Append("<GXG>");
                    sb.Append("<POBoxFlag>N</POBoxFlag>");
                    sb.Append("<GiftFlag>N</GiftFlag>");
                    sb.Append("</GXG>");
                    sb.AppendFormat("<ValueOfContents>{0}</ValueOfContents>", intlSubTotal);
                    sb.AppendFormat("<Country>{0}</Country>", countryName);
                    sb.Append("<Container>RECTANGULAR</Container>");
                    sb.AppendFormat("<Size>{0}</Size>", packageSize);
                    sb.AppendFormat("<Width>{0}</Width>", width);
                    sb.AppendFormat("<Length>{0}</Length>", length);
                    sb.AppendFormat("<Height>{0}</Height>", height);
                    sb.AppendFormat("<Girth>{0}</Girth>", girth);
                    sb.AppendFormat("<OriginZip>{0}</OriginZip>", zipPostalCodeFrom);
                    sb.Append("<CommercialFlag>N</CommercialFlag>");
                    sb.Append("</Package>");
                }
                else
                {
                    int totalPackagesDims    = 1;
                    int totalPackagesWeights = 1;
                    if (IsPackageTooHeavy(pounds))
                    {
                        totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)pounds / (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;
                    }

                    int pounds2 = pounds / totalPackages;
                    if (pounds2 < 1)
                    {
                        pounds2 = 1;
                    }
                    //we don't use ounces
                    int ounces2 = ounces / totalPackages;
                    //int height2 = height / totalPackages;
                    //int width2 = width / totalPackages;
                    //int length2 = length / totalPackages;
                    //if (height2 < 1)
                    //    height2 = 1; // Why assign a 1 if it is assigned below 12? Perhaps this is a mistake.
                    //if (width2 < 1)
                    //    width2 = 1; // Similarly
                    //if (length2 < 1)
                    //    length2 = 1; // Similarly

                    //little hack here for international requests (uncomment the code above when fixed)
                    var length2      = 12;
                    var width2       = 12;
                    var height2      = 12;
                    var packageSize2 = GetPackageSize(length2, height2, width2);
                    int girth2       = height2 + height2 + width2 + width2;

                    for (int i = 0; i < totalPackages; i++)
                    {
                        sb.AppendFormat("<Package ID=\"{0}\">", i.ToString());
                        sb.AppendFormat("<Pounds>{0}</Pounds>", pounds2);
                        sb.AppendFormat("<Ounces>{0}</Ounces>", ounces2);
                        sb.Append("<Machinable>FALSE</Machinable>");
                        sb.AppendFormat("<MailType>{0}</MailType>", mailType);
                        sb.Append("<GXG>");
                        sb.Append("<POBoxFlag>N</POBoxFlag>");
                        sb.Append("<GiftFlag>N</GiftFlag>");
                        sb.Append("</GXG>");
                        sb.AppendFormat("<ValueOfContents>{0}</ValueOfContents>", intlSubTotal);
                        sb.AppendFormat("<Country>{0}</Country>", countryName);
                        sb.Append("<Container>RECTANGULAR</Container>");
                        sb.AppendFormat("<Size>{0}</Size>", packageSize2);
                        sb.AppendFormat("<Width>{0}</Width>", width2);
                        sb.AppendFormat("<Length>{0}</Length>", length2);
                        sb.AppendFormat("<Height>{0}</Height>", height2);
                        sb.AppendFormat("<Girth>{0}</Girth>", girth2);
                        sb.AppendFormat("<OriginZip>{0}</OriginZip>", zipPostalCodeFrom);
                        sb.Append("<CommercialFlag>N</CommercialFlag>");
                        sb.Append("</Package>");
                    }
                }

                sb.Append("</IntlRateV2Request>");

                requestString = "API=IntlRateV2&XML=" + sb.ToString();
                #endregion
            }

            return(requestString);
        }
        public ActionResult GetCartDetails(int customerId)
        {
            var gridModel = new GridModel <ShoppingCartItemModel>();

            if (_permissionService.Authorize(StandardPermissionProvider.ManageOrders))
            {
                var customer = _customerService.GetCustomerById(customerId);
                var cart     = customer.GetCartItems(ShoppingCartType.ShoppingCart);

                gridModel.Data = cart.Select(sci =>
                {
                    decimal taxRate;
                    var store = _storeService.GetStoreById(sci.Item.StoreId);

                    var sciModel = new ShoppingCartItemModel
                    {
                        Id                   = sci.Item.Id,
                        Store                = store != null ? store.Name : "".NaIfEmpty(),
                        ProductId            = sci.Item.ProductId,
                        Quantity             = sci.Item.Quantity,
                        ProductName          = sci.Item.Product.Name,
                        ProductTypeName      = sci.Item.Product.GetProductTypeLabel(_localizationService),
                        ProductTypeLabelHint = sci.Item.Product.ProductTypeLabelHint,
                        UnitPrice            = _priceFormatter.FormatPrice(_taxService.GetProductPrice(sci.Item.Product, _priceCalculationService.GetUnitPrice(sci, true), out taxRate)),
                        Total                = _priceFormatter.FormatPrice(_taxService.GetProductPrice(sci.Item.Product, _priceCalculationService.GetSubTotal(sci, true), out taxRate)),
                        UpdatedOn            = _dateTimeHelper.ConvertToUserTime(sci.Item.UpdatedOnUtc, DateTimeKind.Utc)
                    };
                    return(sciModel);
                });

                gridModel.Total = cart.Count;
            }
            else
            {
                gridModel.Data = Enumerable.Empty <ShoppingCartItemModel>();

                NotifyAccessDenied();
            }

            return(new JsonResult
            {
                Data = gridModel
            });
        }
Ejemplo n.º 30
0
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
            {
                throw new ArgumentNullException("getShippingOptionRequest");
            }

            var response = new GetShippingOptionResponse();

            if (getShippingOptionRequest.Items == null || getShippingOptionRequest.Items.Count == 0)
            {
                response.AddError(T("Admin.System.Warnings.NoShipmentItems"));
                return(response);
            }

            int     countryId       = 0;
            int     stateProvinceId = 0;
            string  zip             = null;
            decimal subTotal        = decimal.Zero;
            int     storeId         = _storeContext.CurrentStore.Id;

            if (getShippingOptionRequest.ShippingAddress != null)
            {
                countryId       = getShippingOptionRequest.ShippingAddress.CountryId ?? 0;
                stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId ?? 0;
                zip             = getShippingOptionRequest.ShippingAddress.ZipPostalCode;
            }

            foreach (var shoppingCartItem in getShippingOptionRequest.Items)
            {
                if (shoppingCartItem.Item.IsFreeShipping || !shoppingCartItem.Item.IsShipEnabled)
                {
                    continue;
                }
                subTotal += _priceCalculationService.GetSubTotal(shoppingCartItem, true);
            }

            decimal sqThreshold = _shippingByTotalSettings.SmallQuantityThreshold;
            decimal sqSurcharge = _shippingByTotalSettings.SmallQuantitySurcharge;

            var shippingMethods = _shippingService.GetAllShippingMethods(getShippingOptionRequest);

            foreach (var shippingMethod in shippingMethods)
            {
                decimal?rate = GetRate(subTotal, shippingMethod.Id, storeId, countryId, stateProvinceId, zip);
                if (rate.HasValue)
                {
                    if (rate > 0 && sqThreshold > 0 && subTotal <= sqThreshold)
                    {
                        // add small quantity surcharge (Mindermengenzuschalg)
                        rate += sqSurcharge;
                    }

                    var shippingOption = new ShippingOption();
                    shippingOption.ShippingMethodId = shippingMethod.Id;
                    shippingOption.Name             = shippingMethod.Name;
                    shippingOption.Description      = shippingMethod.Description;
                    shippingOption.Rate             = rate.Value;
                    response.ShippingOptions.Add(shippingOption);
                }
            }

            return(response);
        }