Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Changes with shipping calculation
KrzysztofPajakd5945ed6ae1c
diff --git a/src/Business/Grand.Business.Checkout/Interfaces/Shipping/IShippingService.cs b/src/Business/Grand.Business.Checkout/Interfaces/Shipping/IShippingService.csindex 362af154b..d722d2dff 100644--- a/src/Business/Grand.Business.Checkout/Interfaces/Shipping/IShippingService.cs+++ b/src/Business/Grand.Business.Checkout/Interfaces/Shipping/IShippingService.cs@@ -43,8 +43,8 @@ namespace Grand.Business.Checkout.Interfaces.Shipping/// <param name="cart">Shopping cart</param>/// <param name="shippingAddress">Shipping address</param>/// <param name="store">Store</param>- /// <returns>Shipment packages (requests)</returns>- Task<IList<GetShippingOptionRequest>> CreateShippingOptionRequests(Customer customer,+ /// <returns>Shipment packages</returns>+ Task<GetShippingOptionRequest> CreateShippingOptionRequests(Customer customer,IList<ShoppingCartItem> cart, Address shippingAddress, Store store);/// <summary>diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.csindex 0bf393c84..acd68b980 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs@@ -143,8 +143,7 @@ namespace Grand.Business.Checkout.Services.Ordersdiscount.DiscountTypeId == DiscountType.AssignedToOrderSubTotal &&!allowedDiscounts.Where(x => x.DiscountId == discount.Id).Any()){- allowedDiscounts.Add(new ApplyDiscount- {+ allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,IsCumulative = discount.IsCumulative,CouponCode = validDiscount.CouponCode,@@ -186,8 +185,7 @@ namespace Grand.Business.Checkout.Services.Ordersdiscount.DiscountTypeId == DiscountType.AssignedToShipping &&!allowedDiscounts.Where(x => x.DiscountId == discount.Id).Any()){- allowedDiscounts.Add(new ApplyDiscount- {+ allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,IsCumulative = discount.IsCumulative,CouponCode = validDiscount.CouponCode,@@ -233,8 +231,7 @@ namespace Grand.Business.Checkout.Services.Ordersdiscount.DiscountTypeId == DiscountType.AssignedToOrderTotal &&!allowedDiscounts.Where(x => x.DiscountId == discount.Id).Any()){- allowedDiscounts.Add(new ApplyDiscount- {+ allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,IsCumulative = discount.IsCumulative,CouponCode = validDiscount.CouponCode,@@ -295,7 +292,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="subTotalWithoutDiscount">Sub total (without discount)</param>/// <param name="subTotalWithDiscount">Sub total (with discount)</param>/// <param name="taxRates">Tax rates (of order sub total)</param>- public virtual async Task<(double discountAmount, List<ApplyDiscount> appliedDiscounts,+ public virtual async Task<(double discountAmount, List<ApplyDiscount> appliedDiscounts,double subTotalWithoutDiscount, double subTotalWithDiscount, SortedDictionary<double, double> taxRates)>GetShoppingCartSubTotal(IList<ShoppingCartItem> cart, bool includingTax){@@ -310,7 +307,7 @@ namespace Grand.Business.Checkout.Services.Orders//get the customerCustomer customer = _workContext.CurrentCustomer;-+//sub totalsdouble subTotalExclTaxWithoutDiscount = 0;double subTotalInclTaxWithoutDiscount = 0;@@ -635,22 +632,19 @@ namespace Grand.Business.Checkout.Services.Orders{var shippingRateMethod = shippingRateMethods[0];- var shippingOptionRequests = await _shippingService.CreateShippingOptionRequests(customer, cart,+ var shippingOptionRequest = await _shippingService.CreateShippingOptionRequests(customer, cart,shippingAddress,_workContext.CurrentStore);-+double? fixedRate = null;- foreach (var shippingOptionRequest in shippingOptionRequests)+ //calculate fixed rates for each request-package+ var fixedRateTmp = await shippingRateMethod.GetFixedRate(shippingOptionRequest);+ if (fixedRateTmp.HasValue){- //calculate fixed rates for each request-package- var fixedRateTmp = await shippingRateMethod.GetFixedRate(shippingOptionRequest);- if (fixedRateTmp.HasValue)- {- if (!fixedRate.HasValue)- fixedRate = 0;+ if (!fixedRate.HasValue)+ fixedRate = 0;- fixedRate += fixedRateTmp.Value;- }+ fixedRate += fixedRateTmp.Value;}if (fixedRate.HasValue)@@ -904,8 +898,7 @@ namespace Grand.Business.Checkout.Services.Orders//reduce subtotalresultTemp -= amountCanBeUsed;- var appliedGiftVoucher = new AppliedGiftVoucher- {+ var appliedGiftVoucher = new AppliedGiftVoucher {GiftVoucher = gc,AmountCanBeUsed = amountCanBeUsed};diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.csindex d5e1d0245..5976c0e3d 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs@@ -121,61 +121,39 @@ namespace Grand.Business.Checkout.Services.Shipping/// <param name="shippingAddress">Shipping address</param>/// <param name="store">Store</param>/// <returns>Shipment packages (requests)</returns>- public virtual async Task<IList<GetShippingOptionRequest>> CreateShippingOptionRequests(Customer customer,+ public virtual async Task<GetShippingOptionRequest> CreateShippingOptionRequests(Customer customer,IList<ShoppingCartItem> cart, Address shippingAddress, Store store){- var requests = new List<GetShippingOptionRequest>();-+ var request = new GetShippingOptionRequest();+ //store+ request.StoreId = store?.Id;+ //customer+ request.Customer = customer;++ //ship to+ request.ShippingAddress = shippingAddress;+ //ship from+ Address originAddress = _shippingSettings.ShippingOriginAddress;++ if (originAddress != null)+ {+ var country = await _countryService.GetCountryById(originAddress.CountryId);+ var state = country?.StateProvinces.FirstOrDefault(x => x.Id == originAddress.StateProvinceId);+ request.CountryFrom = country;+ request.StateProvinceFrom = state;+ request.ZipPostalCodeFrom = originAddress.ZipPostalCode;+ request.CityFrom = originAddress.City;+ request.AddressFrom = originAddress.Address1;+ }foreach (var sci in cart){if (!sci.IsShipEnabled)continue;-- //warehouses- Warehouse warehouse = null;-- if (!string.IsNullOrEmpty(sci.WarehouseId))- warehouse = await _warehouseService.GetWarehouseById(sci.WarehouseId);- else- {- if (!string.IsNullOrEmpty(store?.DefaultWarehouseId))- warehouse = await _warehouseService.GetWarehouseById(store.DefaultWarehouseId);- }-- string warehouseId = warehouse != null ? warehouse.Id : "";-- //create a new request- var request = new GetShippingOptionRequest();- //store- request.StoreId = store?.Id;- //customer- request.Customer = customer;//add itemrequest.Items.Add(new GetShippingOptionRequest.PackageItem(sci));- //ship to- request.ShippingAddress = shippingAddress;- //ship from- Address originAddress = _shippingSettings.ShippingOriginAddress;- if (warehouse != null)- {- //warehouse address- originAddress = warehouse.Address;- request.WarehouseFrom = warehouse;- }- if (originAddress != null)- {- var country = await _countryService.GetCountryById(originAddress.CountryId);- var state = country?.StateProvinces.FirstOrDefault(x => x.Id == originAddress.StateProvinceId);- request.CountryFrom = country;- request.StateProvinceFrom = state;- request.ZipPostalCodeFrom = originAddress.ZipPostalCode;- request.CityFrom = originAddress.City;- request.AddressFrom = originAddress.Address1;- }- requests.Add(request);}- return requests;+ return request;}/// <summary>@@ -196,7 +174,7 @@ namespace Grand.Business.Checkout.Services.Shippingvar result = new GetShippingOptionResponse();//create a package- var shippingOptionRequests = await CreateShippingOptionRequests(customer, cart, shippingAddress, store);+ var shippingOptionRequest = await CreateShippingOptionRequests(customer, cart, shippingAddress, store);var shippingRateMethods = await LoadActiveShippingRateCalculationProviders(customer, store?.Id, cart);//filter by system name@@ -214,48 +192,47 @@ namespace Grand.Business.Checkout.Services.Shipping{//request shipping options (separately for each package-request)IList<ShippingOption> srcmShippingOptions = null;- foreach (var shippingOptionRequest in shippingOptionRequests)- {- var getShippingOptionResponse = await srcm.GetShippingOptions(shippingOptionRequest);- if (getShippingOptionResponse.Success)+ var getShippingOptionResponse = await srcm.GetShippingOptions(shippingOptionRequest);++ if (getShippingOptionResponse.Success)+ {+ //success+ if (srcmShippingOptions == null){- //success- if (srcmShippingOptions == null)- {- //first shipping option request- srcmShippingOptions = getShippingOptionResponse.ShippingOptions;- }- else- {- //get shipping options which already exist for prior requested packages for this scrm (i.e. common options)- srcmShippingOptions = srcmShippingOptions- .Where(existingso => getShippingOptionResponse.ShippingOptions.Any(newso => newso.Name == existingso.Name))- .ToList();-- //and sum the rates- foreach (var existingso in srcmShippingOptions)- {- existingso.Rate += getShippingOptionResponse- .ShippingOptions- .First(newso => newso.Name == existingso.Name)- .Rate;- }- }+ //first shipping option request+ srcmShippingOptions = getShippingOptionResponse.ShippingOptions;}else{- //errors- foreach (string error in getShippingOptionResponse.Errors)+ //get shipping options which already exist for prior requested packages for this scrm (i.e. common options)+ srcmShippingOptions = srcmShippingOptions+ .Where(existingso => getShippingOptionResponse.ShippingOptions.Any(newso => newso.Name == existingso.Name))+ .ToList();++ //and sum the rates+ foreach (var existingso in srcmShippingOptions){- result.AddError(error);- _logger.Warning(string.Format("Shipping ({0}). {1}", srcm.FriendlyName, error));+ existingso.Rate += getShippingOptionResponse+ .ShippingOptions+ .First(newso => newso.Name == existingso.Name)+ .Rate;}- //clear the shipping options in this case- srcmShippingOptions = new List<ShippingOption>();- break;}}+ else+ {+ //errors+ foreach (string error in getShippingOptionResponse.Errors)+ {+ result.AddError(error);+ _logger.Warning(string.Format("Shipping ({0}). {1}", srcm.FriendlyName, error));+ }+ //clear the shipping options in this case+ srcmShippingOptions = new List<ShippingOption>();+ break;+ }+// add this scrm's options to the resultif (srcmShippingOptions != null)diff --git a/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs b/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.csindex 6c4f39d2a..54b5bf9d3 100644--- a/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs+++ b/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs@@ -214,7 +214,9 @@ namespace Shipping.ByWeightstoreId = _workContext.CurrentStore.Id;string countryId = getShippingOptionRequest.ShippingAddress.CountryId;string stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId;- string warehouseId = getShippingOptionRequest.WarehouseFrom != null ? getShippingOptionRequest.WarehouseFrom.Id : "";++ //string warehouseId = getShippingOptionRequest.WarehouseFrom != null ? getShippingOptionRequest.WarehouseFrom.Id : "";+string zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode;double subTotal = 0;var priceCalculationService = _serviceProvider.GetRequiredService<IPricingService>();@@ -234,9 +236,20 @@ namespace Shipping.ByWeightvar shippingMethods = await _shippingMethodService.GetAllShippingMethods(countryId, _workContext.CurrentCustomer);foreach (var shippingMethod in shippingMethods){- double? rate = await GetRate(subTotal, weight, shippingMethod.Id,- storeId, warehouseId, countryId, stateProvinceId, zip);- if (rate.HasValue)+ double? rate = null;+ foreach (var item in getShippingOptionRequest.Items.GroupBy(x => x.ShoppingCartItem.WarehouseId).Select(x=>x.Key))+ {+ var _rate = await GetRate(subTotal, weight, shippingMethod.Id, storeId, item, countryId, stateProvinceId, zip);+ if (_rate.HasValue)+ {+ if (rate == null)+ rate = 0;++ rate += _rate.Value;+ }+ }++ if (rate != null && rate.HasValue){var shippingOption = new ShippingOption();shippingOption.Name = shippingMethod.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id);diff --git a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.csindex 97884ff60..914032f99 100644--- a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs+++ b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs@@ -71,60 +71,25 @@ namespace Shipping.ByWeight.Services.Where(sbw => sbw.ShippingMethodId == shippingMethodId && weight >= sbw.From && weight <= sbw.To).ToList();- //filter by store- var matchedByStore = new List<ShippingByWeightRecord>();- foreach (var sbw in existingRates)- if (storeId == sbw.StoreId)- matchedByStore.Add(sbw);- if (matchedByStore.Count == 0)- foreach (var sbw in existingRates)- if (String.IsNullOrEmpty(sbw.StoreId))- matchedByStore.Add(sbw);-- //filter by warehouse- var matchedByWarehouse = new List<ShippingByWeightRecord>();- foreach (var sbw in matchedByStore)- if (warehouseId == sbw.WarehouseId)- matchedByWarehouse.Add(sbw);- if (matchedByWarehouse.Count == 0)- foreach (var sbw in matchedByStore)- if (String.IsNullOrEmpty(sbw.WarehouseId))- matchedByWarehouse.Add(sbw);-- //filter by country- var matchedByCountry = new List<ShippingByWeightRecord>();- foreach (var sbw in matchedByWarehouse)- if (countryId == sbw.CountryId)- matchedByCountry.Add(sbw);- if (matchedByCountry.Count == 0)- foreach (var sbw in matchedByWarehouse)- if (String.IsNullOrEmpty(sbw.CountryId))- matchedByCountry.Add(sbw);-- //filter by state/province- var matchedByStateProvince = new List<ShippingByWeightRecord>();- foreach (var sbw in matchedByCountry)- if (stateProvinceId == sbw.StateProvinceId)- matchedByStateProvince.Add(sbw);- if (matchedByStateProvince.Count == 0)- foreach (var sbw in matchedByCountry)- if (String.IsNullOrEmpty(sbw.StateProvinceId))- matchedByStateProvince.Add(sbw);--- //filter by zip- var matchedByZip = new List<ShippingByWeightRecord>();- foreach (var sbw in matchedByStateProvince)- if ((String.IsNullOrEmpty(zip) && String.IsNullOrEmpty(sbw.Zip)) ||- (zip.Equals(sbw.Zip, StringComparison.OrdinalIgnoreCase)))- matchedByZip.Add(sbw);-- if (matchedByZip.Count == 0)- foreach (var taxRate in matchedByStateProvince)- if (String.IsNullOrWhiteSpace(taxRate.Zip))- matchedByZip.Add(taxRate);-- return matchedByZip.FirstOrDefault();+ if (!string.IsNullOrEmpty(warehouseId))+ existingRates = existingRates.Where(x => x.WarehouseId == warehouseId).ToList();+ else+ existingRates = existingRates.Where(x => string.IsNullOrEmpty(x.WarehouseId)).ToList();++ if (!string.IsNullOrEmpty(storeId))+ existingRates = existingRates.Where(x => x.StoreId == storeId || string.IsNullOrEmpty(x.StoreId)).ToList();++ if (!string.IsNullOrEmpty(countryId))+ existingRates = existingRates.Where(x => x.CountryId == countryId || string.IsNullOrEmpty(x.CountryId)).ToList();++ if (!string.IsNullOrEmpty(stateProvinceId))+ existingRates = existingRates.Where(x => x.StateProvinceId == stateProvinceId || string.IsNullOrEmpty(x.StateProvinceId)).ToList();++ if (!string.IsNullOrEmpty(zip))+ existingRates = existingRates.Where(x => x.Zip == zip || string.IsNullOrEmpty(x.Zip)).ToList();++ return existingRates.FirstOrDefault();+}public virtual Task<ShippingByWeightRecord> GetById(string shippingByWeightRecordId)diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.csindex 3f1cf6613..b1595edf3 100644--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs@@ -99,11 +99,10 @@ namespace Grand.Business.Checkout.Tests.Services.Shippingvar result = await _service.CreateShippingOptionRequests(customer, cart, shippingAddress, store);- Assert.IsTrue(result.Count == 1);- Assert.AreEqual(result.First().ShippingAddress, shippingAddress);- Assert.AreEqual(result.First().WarehouseFrom, warehouse);- Assert.AreEqual(result.First().StoreId, "id");- Assert.AreEqual(result.First().Customer, customer);+ Assert.AreEqual(result.ShippingAddress, shippingAddress);+ Assert.AreEqual(result.WarehouseFrom, warehouse);+ Assert.AreEqual(result.StoreId, "id");+ Assert.AreEqual(result.Customer, customer);}[TestMethod]@@ -128,7 +127,7 @@ namespace Grand.Business.Checkout.Tests.Services.Shipping_warehouseMock.Setup(c => c.GetWarehouseById(It.IsAny<string>())).ReturnsAsync(warehouse);var result = await _service.CreateShippingOptionRequests(customer, cart, shippingAddress, store);- Assert.IsTrue(result.Count == 0);+ Assert.IsTrue(result != null);}}}