/// <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) { response.AddError("No shipment items"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } string zipPostalCodeFrom = getShippingOptionRequest.ZipPostalCodeFrom; string zipPostalCodeTo = getShippingOptionRequest.ShippingAddress.ZipPostalCode; int weight = GetWeight(getShippingOptionRequest); decimal lengthTmp, widthTmp, heightTmp; _shippingService.GetDimensions(getShippingOptionRequest.Items, out widthTmp, out lengthTmp, out heightTmp); int length = Math.Min(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(lengthTmp, this.GatewayMeasureDimension))), MIN_LENGTH); int width = Math.Min(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(widthTmp, this.GatewayMeasureDimension))), MIN_LENGTH); int height = Math.Min(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(heightTmp, this.GatewayMeasureDimension))), MIN_LENGTH); //estimate packaging int totalPackagesDims = 1; int totalPackagesWeights = 1; if (length > MAX_LENGTH || width > MAX_LENGTH || height > MAX_LENGTH) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)Math.Max(Math.Max(length, width), height) / MAX_LENGTH)); } if (weight > MAX_WEIGHT) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAX_WEIGHT)); } var totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } if (totalPackages > 1) { //recalculate dims, weight weight = weight / totalPackages; height = height / totalPackages; width = width / totalPackages; length = length / totalPackages; if (weight < MIN_WEIGHT) { weight = MIN_WEIGHT; } if (height < MIN_LENGTH) { height = MIN_LENGTH; } if (width < MIN_LENGTH) { width = MIN_LENGTH; } if (length < MIN_LENGTH) { length = MIN_LENGTH; } } int girth = height + height + width + width; if (girth < MIN_GIRTH) { height = MIN_LENGTH; width = MIN_LENGTH; } if (girth > MAX_GIRTH) { height = MAX_LENGTH / 4; width = MAX_LENGTH / 4; } try { var country = EngineContext.Current.Resolve <ICountryService>().GetCountryById(getShippingOptionRequest.ShippingAddress.CountryId); if (country == null) { response.AddError("Shipping country is not specified"); return(response); } switch (country.ThreeLetterIsoCode) { case "AUS": //domestic services response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Standard", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Express", weight, length, width, height, totalPackages)); //discontinued //response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "EXP_PLT", weight, length, width, height, totalPackages)); break; default: //international services response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Air", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Sea", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "ECI_D", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "ECI_M", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "EPI", weight, length, width, height, totalPackages)); break; } foreach (var shippingOption in response.ShippingOptions) { shippingOption.Rate += _australiaPostSettings.AdditionalHandlingCharge; } } catch (Exception ex) { response.AddError(ex.Message); } 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) { _TableName = _localizationService.GetLocaleStringResourceByName("Plugins.Shipping.GBS.Product.Table.Name").ResourceValue.ToString(); 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); } int?restrictByCountryId = (getShippingOptionRequest.ShippingAddress != null && getShippingOptionRequest.ShippingAddress.Country != null) ? (int?)getShippingOptionRequest.ShippingAddress.Country.Id : null; var shippingMethods = this._shippingService.GetAllShippingMethods(restrictByCountryId); IEnumerable <int> productId = getShippingOptionRequest.Items.Select(x => x.ShoppingCartItem.ProductId).Distinct(); ShippingRateConversionModels _lstOfProduct = new ShippingRateConversionModels(); foreach (var pID in productId) { ProductGBSModel _prodModel = DataManager.GetGBSShippingCategory(pID, _TableName); ShippingRateConversionModels.ProductGBSModel _productGBSModel = new ShippingRateConversionModels.ProductGBSModel(); _productGBSModel.ProductID = _prodModel.ProductID.ToString(); _productGBSModel.ShippingCategoryA = _prodModel.ShippingCategoryA; _productGBSModel.ShippingCategoryB = _prodModel.ShippingCategoryB; _lstOfProduct.productGBSModels.Add(_productGBSModel); } // Get ZipCode and Product/s ID/S var zipCode = (getShippingOptionRequest.ShippingAddress != null && !String.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.ZipPostalCode)) ? getShippingOptionRequest.ShippingAddress.ZipPostalCode.Substring(0, 3) : String.Empty; // Get Categorized Value from String Resources _lstOfProduct.zipCode = zipCode; // Call Web Service to get the Shipping rate GBSShippingServiceClient myShippingRateSrv = new GBSShippingServiceClient(); //check for Flat Rate string _FixedRate = String.Empty; if (_gbsShippingSetting.UseFlatRate) { _FixedRate = _gbsShippingSetting.FlatRateAmount.ToString(); } else { _FixedRate = myShippingRateSrv.GetShippingRate(_gbsShippingSetting.GBSShippingWebServiceAddress, _gbsShippingSetting.LoginId, _gbsShippingSetting.Password, _lstOfProduct); } // Build response with custom shipping option try { //see if we have a parsable string decimal parsedRate = decimal.Parse(_FixedRate); } catch (Exception e) { _FixedRate = "0.00"; } decimal?maxRate = decimal.Parse(_FixedRate); var shippingOption = new ShippingOption(); var shipOpName = _localizationService.GetResource("Plugins.Shipping.GBS.Product.ShippingOption.Description.Name"); shippingOption.Name = shipOpName.ToString(); shippingOption.Rate = maxRate.HasValue == true ? maxRate.Value : 0; var shipOpDesError = _localizationService.GetResource("Plugins.Shipping.GBS.Product.ShippingOption.Description.Error"); var shipOpDesSuccess = _localizationService.GetResource("Plugins.Shipping.GBS.Product.ShippingOption.Description.Success"); shippingOption.Description = shippingOption.Rate == 0 ? shipOpDesError : shipOpDesSuccess; 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 async Task <GetShippingOptionResponse> GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest) { if (getShippingOptionRequest == null) { throw new ArgumentNullException(nameof(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 = getShippingOptionRequest.StoreId; if (String.IsNullOrEmpty(storeId)) { storeId = _workContext.CurrentStore.Id; } string countryId = getShippingOptionRequest.ShippingAddress.CountryId; string stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId; string warehouseId = getShippingOptionRequest.WarehouseFrom != null ? getShippingOptionRequest.WarehouseFrom.Id : ""; string zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode; decimal subTotal = decimal.Zero; var priceCalculationService = _serviceProvider.GetRequiredService <IPricingService>(); foreach (var packageItem in getShippingOptionRequest.Items) { if (packageItem.ShoppingCartItem.IsFreeShipping) { continue; } var product = await _productService.GetProductById(packageItem.ShoppingCartItem.ProductId); if (product != null) { subTotal += (await priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem, product)).subTotal; } } decimal weight = await GetTotalWeight(getShippingOptionRequest); var shippingMethods = await _shippingMethodService.GetAllShippingMethods(countryId, _workContext.CurrentCustomer); foreach (var shippingMethod in shippingMethods) { decimal?rate = await GetRate(subTotal, weight, shippingMethod.Id, storeId, warehouseId, countryId, stateProvinceId, zip); if (rate.HasValue) { var shippingOption = new ShippingOption(); shippingOption.Name = shippingMethod.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id); shippingOption.Description = shippingMethod.GetTranslation(x => x.Description, _workContext.WorkingLanguage.Id); shippingOption.Rate = await _currencyService.ConvertFromPrimaryStoreCurrency(rate.Value, _workContext.WorkingCurrency); response.ShippingOptions.Add(shippingOption); } } return(response); }
/// <summary> /// Gets available shipping options /// </summary> /// <param name="cart">Shopping cart</param> /// <param name="shippingAddress">Shipping address</param> /// <param name="allowedShippingRateMethodSystemName">Filter by Shipping rate method identifier; null to load shipping options of all Shipping rate methods</param> /// <param name="storeId">Load records allowed only in a specified store; pass "" to load all records</param> /// <returns>Shipping options</returns> public virtual async Task <GetShippingOptionResponse> GetShippingOptions(Customer customer, IList <ShoppingCartItem> cart, Address shippingAddress, string allowedShippingRateMethodSystemName = "", Store store = null) { if (cart == null) { throw new ArgumentNullException(nameof(cart)); } var result = new GetShippingOptionResponse(); //create a package var shippingOptionRequest = await CreateShippingOptionRequests(customer, cart, shippingAddress, store); var shippingRateMethods = await LoadActiveShippingRateCalculationProviders(customer, store?.Id, cart); //filter by system name if (!String.IsNullOrWhiteSpace(allowedShippingRateMethodSystemName)) { shippingRateMethods = shippingRateMethods .Where(srcm => allowedShippingRateMethodSystemName.Equals(srcm.SystemName, StringComparison.OrdinalIgnoreCase)) .ToList(); } if (!shippingRateMethods.Any()) { throw new GrandException("Shipping rate method could not be loaded"); } //request shipping options from each Shipping rate methods foreach (var srcm in shippingRateMethods) { //request shipping options (separately for each package-request) IList <ShippingOption> srcmShippingOptions = null; var getShippingOptionResponse = await srcm.GetShippingOptions(shippingOptionRequest); if (getShippingOptionResponse.Success) { //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; } } } 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 result if (srcmShippingOptions != null) { foreach (var so in srcmShippingOptions) { //set system name if not set yet if (String.IsNullOrEmpty(so.ShippingRateProviderSystemName)) { so.ShippingRateProviderSystemName = srcm.SystemName; } result.ShippingOptions.Add(so); } } } //returnvalidoptions if there are any (no matter of the errors returned by other shipping rate compuation methods). if (!result.ShippingOptions.Any() && !result.Errors.Any()) { result.Errors.Clear(); } //no shipping options loaded if (result.ShippingOptions.Count == 0 && result.Errors.Count == 0) { result.Errors.Add(_translationService.GetResource("Checkout.ShippingOptionCouldNotBeLoaded")); } return(result); }
/// <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) { response.AddError("No shipment items"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } if (getShippingOptionRequest.ShippingAddress.Country == null) { response.AddError("Shipping country is not set"); return(response); } if (getShippingOptionRequest.CountryFrom == null) { getShippingOptionRequest.CountryFrom = _countryService.GetCountryById(_upsSettings.DefaultShippedFromCountryId); if (getShippingOptionRequest.CountryFrom == null) { getShippingOptionRequest.CountryFrom = _countryService.GetAllCountries(true).ToList().FirstOrDefault(); } } if (String.IsNullOrEmpty(getShippingOptionRequest.ZipPostalCodeFrom)) { getShippingOptionRequest.ZipPostalCodeFrom = _upsSettings.DefaultShippedFromZipPostalCode; } string requestString = CreateRequest(_upsSettings.AccessKey, _upsSettings.Username, _upsSettings.Password, getShippingOptionRequest, _upsSettings.CustomerClassification, _upsSettings.PickupType, _upsSettings.PackagingType); string responseXml = DoRequest(_upsSettings.Url, requestString); string error = ""; var shippingOptions = ParseResponse(responseXml, ref error); if (String.IsNullOrEmpty(error)) { foreach (var shippingOption in shippingOptions) { if (!shippingOption.Name.ToLower().StartsWith("ups")) { shippingOption.Name = string.Format("UPS {0}", shippingOption.Name); } shippingOption.Rate += _upsSettings.AdditionalHandlingCharge; response.ShippingOptions.Add(shippingOption); } } else { response.AddError(error); } return(response); }
public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest) { if (getShippingOptionRequest == null) { throw new ArgumentNullException("getShippingOptionRequest"); } if (getShippingOptionRequest.Items == null) { return new GetShippingOptionResponse { Errors = new List <string> { "Sem itens poara envioNo." } } } ; if (getShippingOptionRequest.ShippingAddress == null) { return new GetShippingOptionResponse { Errors = new List <string> { "Endereço não foi informado." } } } ; //if (getShippingOptionRequest.ShippingAddress.Country == null) // return new GetShippingOptionResponse { Errors = new List<string> { "País não foi Shipping country is not set" } }; if (string.IsNullOrEmpty(getShippingOptionRequest.ZipPostalCodeFrom)) { return new GetShippingOptionResponse { Errors = new List <string> { "CEP de origem não foi informado." } } } ; //create object for the get rates requests var result = new GetShippingOptionResponse(); //get rate for all available services var errorSummary = new StringBuilder(); //write errors var errorString = errorSummary.ToString(); var frete = new FreteCorreiosWS().CalcPrecoAsync("", "", "41106", getShippingOptionRequest.ZipPostalCodeFrom, getShippingOptionRequest.ShippingAddress.ZipPostalCode, getShippingOptionRequest.Items[0].ShoppingCartItem.Product.Weight.ToString(), 1, 16, 5, 11, 0, "N", getShippingOptionRequest.Items[0].ShoppingCartItem.Product.Price, "N"); result.ShippingOptions.Add(new ShippingOption { Name = "PAC", Rate = 0, Description = frete.Result.Servicos.ToList().ToString() }); if (!string.IsNullOrEmpty(errorString)) { _logger.Error(errorString); } if (!result.ShippingOptions.Any()) { result.AddError(errorString); } return(result); }
/// <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 (_shippingService.IsFreeShipping(packageItem.ShoppingCartItem)) { continue; } //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal subTotal += _shoppingCartService.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)) { int? transitDays = null; decimal rate = decimal.Zero; var shippingByWeightByTotalRecord = _shippingByWeightByTotalService.FindRecords( shippingMethod.Id, storeId, warehouseId, countryId, stateProvinceId, zip, weight, subTotal); if (shippingByWeightByTotalRecord == null) { if (_fixedByWeightByTotalSettings.LimitMethodsToCreated) { continue; } } else { rate = GetRate(shippingByWeightByTotalRecord, subTotal, weight); transitDays = shippingByWeightByTotalRecord.TransitDays; } response.ShippingOptions.Add(new ShippingOption { Name = _localizationService.GetLocalized(shippingMethod, x => x.Name), Description = _localizationService.GetLocalized(shippingMethod, x => x.Description), Rate = rate, TransitDays = transitDays }); } } else { //shipping rate calculation by fixed rate var restrictByCountryId = getShippingOptionRequest.ShippingAddress?.CountryId; response.ShippingOptions = _shippingService.GetAllShippingMethods(restrictByCountryId).Select(shippingMethod => new ShippingOption { Name = _localizationService.GetLocalized(shippingMethod, x => x.Name), Description = _localizationService.GetLocalized(shippingMethod, x => x.Description), Rate = GetRate(shippingMethod.Id), TransitDays = GetTransitDays(shippingMethod.Id) }).ToList(); } 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) { response.AddError("No shipment items"); return(response); } if (string.IsNullOrEmpty(getShippingOptionRequest.ZipPostalCodeFrom)) { response.AddError("Shipping origin zip is not set"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not specified"); return(response); } var country = _countryService.GetCountryById(getShippingOptionRequest.ShippingAddress.CountryId); if (country == null) { response.AddError("Shipping country is not specified"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } if (string.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.ZipPostalCode)) { response.AddError("Shipping zip (postal code) is not set"); return(response); } string zipPostalCodeFrom = getShippingOptionRequest.ZipPostalCodeFrom; string zipPostalCodeTo = getShippingOptionRequest.ShippingAddress.ZipPostalCode; int weight = GetWeight(getShippingOptionRequest); decimal lengthTmp, widthTmp, heightTmp; _shippingService.GetDimensions(getShippingOptionRequest.Items, out widthTmp, out lengthTmp, out heightTmp); int length = Math.Max(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(lengthTmp, this.GatewayMeasureDimension))), MIN_LENGTH); int width = Math.Max(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(widthTmp, this.GatewayMeasureDimension))), MIN_LENGTH); int height = Math.Max(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(heightTmp, this.GatewayMeasureDimension))), MIN_LENGTH); //estimate packaging int totalPackagesDims = 1; int totalPackagesWeights = 1; if (length > MAX_LENGTH || width > MAX_LENGTH || height > MAX_LENGTH) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)Math.Max(Math.Max(length, width), height) / MAX_LENGTH)); } int maxWeight = country.TwoLetterIsoCode.Equals("AU") ? MAX_DOMESTIC_WEIGHT : MAX_INTERNATIONAL_WEIGHT; if (weight > maxWeight) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)maxWeight)); } var totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } if (totalPackages > 1) { //recalculate dims, weight weight = weight / totalPackages; height = height / totalPackages; width = width / totalPackages; length = length / totalPackages; if (weight < MIN_WEIGHT) { weight = MIN_WEIGHT; } if (height < MIN_LENGTH) { height = MIN_LENGTH; } if (width < MIN_LENGTH) { width = MIN_LENGTH; } if (length < MIN_LENGTH) { length = MIN_LENGTH; } } int girth = height + height + width + width; if (girth < MIN_GIRTH) { height = MIN_LENGTH; width = MIN_LENGTH; } if (girth > MAX_GIRTH) { height = MAX_LENGTH / 4; width = MAX_LENGTH / 4; } // Australia post takes the dimensions in centimeters and weight in kilograms, // so dimensions should be converted and rounded up from millimeters to centimeters, // grams should be converted to kilograms and rounded to two decimal. length = length / ONE_CENTIMETER + (length % ONE_CENTIMETER > 0 ? 1 : 0); width = width / ONE_CENTIMETER + (width % ONE_CENTIMETER > 0 ? 1 : 0); height = height / ONE_CENTIMETER + (height % ONE_CENTIMETER > 0 ? 1 : 0); var kgWeight = Math.Round(weight / (decimal)ONE_KILO, 2); try { var shippingOptions = RequestShippingOptions(country.TwoLetterIsoCode, zipPostalCodeFrom, zipPostalCodeTo, kgWeight, length, width, height, totalPackages); foreach (var shippingOption in shippingOptions) { response.ShippingOptions.Add(shippingOption); } } catch (NopException ex) { response.AddError(ex.Message); return(response); } catch (Exception) { response.AddError("Australia Post Service is currently unavailable, try again later"); return(response); } foreach (var shippingOption in response.ShippingOptions) { shippingOption.Rate += _australiaPostSettings.AdditionalHandlingCharge; } return(response); }
/// <summary> /// Gets available shipping options /// </summary> /// <param name="cart">Shopping cart</param> /// <param name="shippingAddress">Shipping address</param> /// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param> /// <param name="allowedShippingRateComputationMethodSystemName">Filter by shipping rate computation method identifier; null to load shipping options of all shipping rate computation methods</param> /// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param> /// <returns>Shipping options</returns> public virtual GetShippingOptionResponse GetShippingOptions(IList <ShoppingCartItem> cart, Address shippingAddress, Customer customer = null, string allowedShippingRateComputationMethodSystemName = "", int storeId = 0) { if (cart == null) { throw new ArgumentNullException(nameof(cart)); } var result = new GetShippingOptionResponse(); //create a package var shippingOptionRequests = CreateShippingOptionRequests(cart, shippingAddress, storeId, out var shippingFromMultipleLocations); result.ShippingFromMultipleLocations = shippingFromMultipleLocations; var shippingRateComputationMethods = _shippingPluginManager .LoadActivePlugins(customer, storeId, allowedShippingRateComputationMethodSystemName); if (!shippingRateComputationMethods.Any()) { return(result); } //request shipping options from each shipping rate computation methods foreach (var srcm in shippingRateComputationMethods) { //request shipping options (separately for each package-request) IList <ShippingOption> srcmShippingOptions = null; foreach (var shippingOptionRequest in shippingOptionRequests) { var getShippingOptionResponse = srcm.GetShippingOptions(shippingOptionRequest); if (getShippingOptionResponse.Success) { //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; } } } else { //errors foreach (var error in getShippingOptionResponse.Errors) { result.AddError(error); _logger.Warning($"Shipping ({srcm.PluginDescriptor.FriendlyName}). {error}"); } //clear the shipping options in this case srcmShippingOptions = new List <ShippingOption>(); break; } } //add this scrm's options to the result if (srcmShippingOptions == null) { continue; } foreach (var so in srcmShippingOptions) { //set system name if not set yet if (string.IsNullOrEmpty(so.ShippingRateComputationMethodSystemName)) { so.ShippingRateComputationMethodSystemName = srcm.PluginDescriptor.SystemName; } if (_shoppingCartSettings.RoundPricesDuringCalculation) { so.Rate = _priceCalculationService.RoundPrice(so.Rate); } result.ShippingOptions.Add(so); } } if (_shippingSettings.ReturnValidOptionsIfThereAreAny) { //return valid options if there are any (no matter of the errors returned by other shipping rate computation methods). if (result.ShippingOptions.Any() && result.Errors.Any()) { result.Errors.Clear(); } } //no shipping options loaded if (!result.ShippingOptions.Any() && !result.Errors.Any()) { result.Errors.Add(_localizationService.GetResource("Checkout.ShippingOptionCouldNotBeLoaded")); } return(result); }
/// <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 async Task <GetShippingOptionResponse> GetShippingOptionsAsync(GetShippingOptionRequest getShippingOptionRequest) { if (getShippingOptionRequest == null) { throw new ArgumentNullException("getShippingOptionRequest"); } var response = new GetShippingOptionResponse(); if (getShippingOptionRequest.Items == null) { response.AddError("No shipment items"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } if (getShippingOptionRequest.ShippingAddress.CountryId == null) { response.AddError("Shipping country is not set"); return(response); } //TODO clone the request to prevent issues cause by modification var it = getShippingOptionRequest.Items.GetEnumerator(); var homeDeliveryList = new List <GetShippingOptionRequest.PackageItem>(); var pickupInStoreList = new List <GetShippingOptionRequest.PackageItem>(); //find and separately process all home delivery items foreach (var item in getShippingOptionRequest.Items) { //checking first for items that are pickup in store so they dont get charged as home delivery string itemAttributeXml = item.ShoppingCartItem.AttributesXml; List <ProductAttributeMapping> pam = (await _productAttributeParser.ParseProductAttributeMappingsAsync(itemAttributeXml)).ToList(); if (await pam.Select(p => p).WhereAwait(async p => ((await _productAttributeService.GetProductAttributeByIdAsync(p.ProductAttributeId)).Name == "Pickup")).CountAsync() > 0) { pickupInStoreList.Add(item); } // also checking product attribute (why not only check the product attribute?) else if (_productHomeDeliveryRepo.Table.Any(phd => phd.Product_Id == item.ShoppingCartItem.ProductId) || await pam.Select(p => p) .WhereAwait(async p => ((await _productAttributeService.GetProductAttributeByIdAsync(p.ProductAttributeId)).Name == "Home Delivery")) .AnyAsync()) { homeDeliveryList.Add(item); } } foreach (var item in pickupInStoreList) { getShippingOptionRequest.Items.Remove(item); } foreach (var item in homeDeliveryList) { getShippingOptionRequest.Items.Remove(item); } var homeDeliveryCharge = await _homeDeliveryCostService.GetHomeDeliveryCostAsync(homeDeliveryList); //if there are items to be shipped, use the base calculation service if items remain that will be shipped by ups if (getShippingOptionRequest.Items.Count > 0) { var oldProtocol = ServicePointManager.SecurityProtocol; try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls; response = await _baseShippingComputation.GetShippingOptionsAsync(getShippingOptionRequest); } catch { throw; } finally { ServicePointManager.SecurityProtocol = oldProtocol; } if (homeDeliveryList.Count > 0) { var zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode; await CheckZipcodeAsync(zip, response); foreach (var shippingOption in response.ShippingOptions) { shippingOption.Name += " and Home Delivery"; shippingOption.Rate += homeDeliveryCharge; } } }//else the cart contains only home delivery and/or pickup in store else if (homeDeliveryList.Count > 0) { var zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode; await CheckZipcodeAsync(zip, response); response.ShippingOptions.Add(new ShippingOption { Name = "Home Delivery", Rate = homeDeliveryCharge }); }//else the cart contains only pickup in store else { response.ShippingOptions.Add(new ShippingOption { Name = "Pickup in Store", Rate = decimal.Zero }); } 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) { response.AddError("Sem items para enviar"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Endereço de envio em branco"); return(response); } if (getShippingOptionRequest.ShippingAddress.ZipPostalCode == null) { response.AddError("CEP de envio em branco"); return(response); } var result = ProcessShipping(getShippingOptionRequest, response); if (result == null) { response.AddError("Não há serviços disponíveis no momento"); return(response); } else { List <string> group = new List <string>(); foreach (cServico servico in result.Servicos.OrderBy(s => s.Valor)) { Debug.WriteLine("Plugin.Shipping.Correios: Retorno WS"); Debug.WriteLine("Codigo: " + servico.Codigo); Debug.WriteLine("Valor: " + servico.Valor); Debug.WriteLine("Valor Mão Própria: " + servico.ValorMaoPropria); Debug.WriteLine("Valor Aviso Recebimento: " + servico.ValorAvisoRecebimento); Debug.WriteLine("Valor Declarado: " + servico.ValorValorDeclarado); Debug.WriteLine("Prazo Entrega: " + servico.PrazoEntrega); Debug.WriteLine("Entrega Domiciliar: " + servico.EntregaDomiciliar); Debug.WriteLine("Entrega Sabado: " + servico.EntregaSabado); Debug.WriteLine("Erro: " + servico.Erro); Debug.WriteLine("Msg Erro: " + servico.MsgErro); if (servico.Erro == "0") { string name = CorreiosServices.GetServicePublicNameById(servico.Codigo.ToString()); if (!group.Contains(name)) { ShippingOption option = new ShippingOption(); option.Name = name; option.Description = "Prazo médio de entrega " + (servico.PrazoEntrega + _correiosSettings.DiasUteisAdicionais) + " dias úteis"; option.Rate = decimal.Parse(servico.Valor, CultureInfo.GetCultureInfo("pt-BR")) + _orderTotalCalculationService.GetShoppingCartAdditionalShippingCharge(getShippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList()) + _correiosSettings.CustoAdicionalEnvio; response.ShippingOptions.Add(option); group.Add(name); } } else { _logger.Error("Plugin.Shipping.Correios: erro ao calcular frete: (" + CorreiosServices.GetServiceName(servico.Codigo.ToString()) + ")( " + servico.Erro + ") " + servico.MsgErro); } } return(response); } }
public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest) { var response = new GetShippingOptionResponse(); if (_glsSettings.Tracing) { _traceMessages.AppendLine("\r\nReady to validate shipping input"); } AOGLSCountry glsCountry = null; bool validInput = ValidateShippingInfo(getShippingOptionRequest, ref response, ref glsCountry); if (validInput == false && response.Errors != null && response.Errors.Count > 0) { var test = _workContext; return(response); } try { if (_glsSettings.Tracing) { _traceMessages.AppendLine("Ready to prapare GLS call"); } List <PakkeshopData> parcelShops = null; if (glsCountry.SupportParcelShop) { wsShopFinderSoapClient client = new wsShopFinderSoapClient(EndpointConfiguration.wsShopFinderSoap12, _glsSettings.EndpointAddress); string zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode; string street = getShippingOptionRequest.ShippingAddress.Address1; if (_glsSettings.Tracing) { _traceMessages.AppendLine("Ready to call GLS at: '" + _glsSettings.EndpointAddress + "'"); } try { // First try to find a number of shops near the address parcelShops = client.GetParcelShopDropPointAsync(street, zip, glsCountry.TwoLetterGLSCode, _glsSettings.AmountNearestShops).Result.parcelshops.ToList(); } catch (Exception ex) { if (_glsSettings.Tracing) { _traceMessages.AppendLine("Error finding parcelshops: " + ex.ToString()); } } if (parcelShops == null || parcelShops.Count == 0) { try { // If any errors or no shop found, try to find shops from only zip code parcelShops = client.GetParcelShopsInZipcodeAsync(zip, glsCountry.TwoLetterGLSCode).Result.GetParcelShopsInZipcodeResult.ToList(); } catch (Exception ex) { if (_glsSettings.Tracing) { _traceMessages.AppendLine("Error finding parcelshops: " + ex.ToString()); } } } if (_glsSettings.Tracing && parcelShops != null && parcelShops.Count > 0) { _traceMessages.AppendLine(parcelShops.Count + " parcelshops found:"); } if (parcelShops != null && parcelShops.Count > 0) { foreach (var parcelShop in parcelShops) { ShippingOption shippingOption = new ShippingOption() { Name = BuildGLSName(parcelShop), Description = "", ShippingRateComputationMethodSystemName = "GLS", Rate = GetRate(glsCountry.ShippingPrice_0_1) }; response.ShippingOptions.Add(shippingOption); if (_glsSettings.Tracing) { _traceMessages.AppendLine(" - " + shippingOption.Name); } } } } if (parcelShops == null || parcelShops.Count == 0) { Address address = getShippingOptionRequest.ShippingAddress; ShippingOption shippingOption = new ShippingOption() { Name = address.FirstName + " " + address.LastName, Description = BuildDescription(address), ShippingRateComputationMethodSystemName = "GLS", Rate = GetRate(glsCountry.ShippingPrice_0_1) }; response.ShippingOptions.Add(shippingOption); } if (response.ShippingOptions.Any()) { response.Errors.Clear(); } } catch (Exception exc) { while (exc.InnerException != null) { exc = exc.InnerException; } response.AddError($"GLS Service is currently unavailable, try again later. {exc.ToString()}"); if (_glsSettings.Tracing) { _traceMessages.AppendLine($"GLS Service is currently unavailable, try again later. {exc.ToString()}"); } } finally { if (_glsSettings.Tracing && _traceMessages.Length > 0) { var shortMessage = $"GLS Shipping Options for customer {getShippingOptionRequest.Customer.Email}. {getShippingOptionRequest.Items.Count} item(s) in cart (See more in full message)"; _logger.Information(shortMessage, new Exception(_traceMessages.ToString()), getShippingOptionRequest.Customer); } } 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); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } var storeId = getShippingOptionRequest.StoreId; if (storeId == 0) { 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; var shippingMethods = _shippingService.GetAllShippingMethods(countryId); foreach (var shippingMethod in shippingMethods) { // SPC - Calc weight per shipping method decimal subTotal = decimal.Zero; decimal weightToSubtract = decimal.Zero; foreach (var packageItem in getShippingOptionRequest.Items) { // this is the original code which is wrong, its cacluating a price total, and not the weight total. // so the weight of the free item is still part of the calculation // left here for backwards compatibility if (packageItem.ShoppingCartItem.IsFreeShipping) { continue; } //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal subTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem); // SPC - add free ship by shipping method check if (_ShippingByWeightExtendedService.ProductHasFreeShipping(packageItem.ShoppingCartItem.ProductId, shippingMethod.Id)) { // product options have weight also? weightToSubtract = weightToSubtract + (packageItem.ShoppingCartItem.Product.Weight * packageItem.ShoppingCartItem.Quantity); } } decimal weight = _shippingService.GetTotalWeight(getShippingOptionRequest); weight = weight - weightToSubtract; 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("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); }
/// <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 storeId = _storeContext.CurrentStore.Id; decimal subTotal = decimal.Zero; int countryId = 0; string zip = null; if (getShippingOptionRequest.ShippingAddress != null) { countryId = getShippingOptionRequest.ShippingAddress.CountryId ?? 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 weight = _shippingService.GetShoppingCartTotalWeight(getShippingOptionRequest.Items); var shippingMethods = _shippingService.GetAllShippingMethods(getShippingOptionRequest); foreach (var shippingMethod in shippingMethods) { var record = _shippingByWeightService.FindRecord(shippingMethod.Id, storeId, countryId, weight, zip); decimal?rate = GetRate(subTotal, 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 > 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); }
/// <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 (_shippingService.IsFreeShipping(packageItem.ShoppingCartItem)) { continue; } //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal subTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem); } //Metodo Creado para filtrar por el peso. decimal weight = decimal.MinusOne; //get weight of shipped items (excluding items with free shipping) if (!string.IsNullOrEmpty(getShippingOptionRequest.Customer.AdminComment)) { weight = decimal.Parse(getShippingOptionRequest.Customer.AdminComment); getShippingOptionRequest.Customer.AdminComment = null; } else { weight = _shippingService.GetTotalWeight(getShippingOptionRequest, ignoreFreeShippedItems: true); } //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 = _localizationService.GetLocalized(shippingMethod, x => x.Name), Description = _localizationService.GetLocalized(shippingMethod, 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 = _localizationService.GetLocalized(shippingMethod, x => x.Name), Description = _localizationService.GetLocalized(shippingMethod, x => x.Description), Rate = GetRate(shippingMethod.Id) }).ToList(); } 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); } var storeId = getShippingOptionRequest.StoreId; if (storeId == 0) { storeId = _storeContext.CurrentStore.Id; } int countryId = getShippingOptionRequest.ShippingAddress.CountryId; int stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId; 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("getShippingOptionRequest"); } var response = new GetShippingOptionResponse(); if (getShippingOptionRequest.Items == null) { response.AddError(T("Admin.System.Warnings.NoShipmentItems")); return(response); } if (getShippingOptionRequest.ShippingAddress == null || getShippingOptionRequest.ShippingAddress.Country == null) { return(response); } Currency requestedShipmentCurrency; var request = CreateRateRequest(getShippingOptionRequest, out requestedShipmentCurrency); var service = new RateService(); // Initialize the service service.Url = _fedexSettings.Url; try { // This is the call to the web service passing in a RateRequest and returning a RateReply var reply = service.getRates(request); // Service call if (reply.HighestSeverity == RateServiceWebReference.NotificationSeverityType.SUCCESS || reply.HighestSeverity == RateServiceWebReference.NotificationSeverityType.NOTE || reply.HighestSeverity == RateServiceWebReference.NotificationSeverityType.WARNING) // check if the call was successful { if (reply != null && reply.RateReplyDetails != null) { var shippingOptions = ParseResponse(reply, requestedShipmentCurrency); foreach (var shippingOption in shippingOptions) { response.ShippingOptions.Add(shippingOption); } } else { if (reply != null && reply.Notifications != null && reply.Notifications.Length > 0 && !String.IsNullOrEmpty(reply.Notifications[0].Message)) { response.AddError(string.Format("{0} (code: {1})", reply.Notifications[0].Message, reply.Notifications[0].Code)); return(response); } else { response.AddError("Could not get reply from shipping server"); return(response); } } } else { Debug.WriteLine(reply.Notifications[0].Message); response.AddError(reply.Notifications[0].Message); return(response); } } catch (SoapException e) { Debug.WriteLine(e.Detail.InnerText); response.AddError(e.Detail.InnerText); return(response); } catch (Exception e) { Debug.WriteLine(e.Message); response.AddError(e.Message); return(response); } 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) { response.AddError("No shipment items"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } if (getShippingOptionRequest.ShippingAddress.Country == null) { response.AddError("Shipping country is not set"); return(response); } if (getShippingOptionRequest.ShippingAddress.StateProvince == null) { response.AddError("Shipping state is not set"); return(response); } try { var profile = new Profile(); profile.MerchantId = _canadaPostSettings.CustomerId; var destination = new Destination(); destination.City = getShippingOptionRequest.ShippingAddress.City; destination.StateOrProvince = getShippingOptionRequest.ShippingAddress.StateProvince.Abbreviation; destination.Country = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode; destination.PostalCode = getShippingOptionRequest.ShippingAddress.ZipPostalCode; var items = CreateItems(getShippingOptionRequest); var lang = CanadaPostLanguageEnum.English; if (_workContext.WorkingLanguage.LanguageCulture.StartsWith("fr", StringComparison.InvariantCultureIgnoreCase)) { lang = CanadaPostLanguageEnum.French; } var requestResult = GetShippingOptionsInternal(profile, destination, items, lang); if (requestResult.IsError) { response.AddError(requestResult.StatusMessage); } else { foreach (var dr in requestResult.AvailableRates) { var so = new ShippingOption(); so.Name = dr.Name; if (!string.IsNullOrEmpty(dr.DeliveryDate)) { so.Name += string.Format(" - {0}", dr.DeliveryDate); } so.Rate = dr.Amount; response.ShippingOptions.Add(so); } } foreach (var shippingOption in response.ShippingOptions) { if (!shippingOption.Name.StartsWith("canada post", StringComparison.InvariantCultureIgnoreCase)) { shippingOption.Name = string.Format("Canada Post {0}", shippingOption.Name); } } } catch (Exception e) { response.AddError(e.Message); } return(response); }
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); } if (getShippingOptionRequest.ShippingAddress.Country == null) { response.AddError("Shipping country is not set"); return(response); } var orderRef = "NOP" + getShippingOptionRequest.Items.FirstOrDefault().ShoppingCartItem.Id; var checkSum = CheckSumCalculator.CalculateChecksum( new Dictionary <string, string> { { "accountId", _settings.AccountId }, { "action", "START" }, { "customerCountry", getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode }, { "orderReference", orderRef } }, _settings.PassPhrase); var storeUrl = _storeContext.CurrentStore.Url; if (!storeUrl.EndsWith("/")) { storeUrl += "/"; } var confirmUrl = storeUrl + "Plugins/BpostShippingManager/ConfirmHandler"; var cancelUrl = storeUrl + "Plugins/BpostShippingManager/CancelHandler"; var errorUrl = storeUrl + "Plugins/BpostShippingManager/ErrorHandler"; var street = string.Empty; var streetNumber = string.Empty; if (!string.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.Address1)) { var streetNumberStart = getShippingOptionRequest.ShippingAddress.Address1.IndexOfAny("0123456789".ToCharArray()); if (streetNumberStart >= 0) { street = getShippingOptionRequest.ShippingAddress.Address1.Substring(0, streetNumberStart - 1); streetNumber = getShippingOptionRequest.ShippingAddress.Address1.Substring(streetNumberStart); } } var rate = _workContext.CurrentCustomer.GetAttribute <decimal>(CustomCustomerAttributeNames.DeliveryMethodRate, _storeContext.CurrentStore.Id); var deliveryMethodAddress = _workContext.CurrentCustomer.GetAttribute <string>(CustomCustomerAttributeNames.DeliveryMethodAddress, _storeContext.CurrentStore.Id); var deliveryMethod = _workContext.CurrentCustomer.GetAttribute <string>(CustomCustomerAttributeNames.DeliveryMethod, _storeContext.CurrentStore.Id); LocaleStringResource deliveryMethodDescription = null; var buttonDiv = string.Empty; var loadShm = string.Format( "loadShm('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}');", _settings.AccountId, orderRef, getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode, checkSum, getShippingOptionRequest.ShippingAddress.FirstName, getShippingOptionRequest.ShippingAddress.LastName, getShippingOptionRequest.Customer.Email, street, getShippingOptionRequest.ShippingAddress.ZipPostalCode, getShippingOptionRequest.ShippingAddress.City, confirmUrl, cancelUrl, errorUrl, _workContext.WorkingLanguage.UniqueSeoCode, streetNumber); var startupShmScript = @"<script>$(document).ready(function() { " + loadShm + " expandShm(); }); </script>"; if (!string.IsNullOrEmpty(deliveryMethod)) { deliveryMethodDescription = _localizationService.GetLocaleStringResourceByName( $"MakeIT.Nop.Shipping.Bpost.ShippingManager.DeliveryMethod.{deliveryMethod.Replace(" ", "")}"); buttonDiv = @"<div><input class='{13}' type='button' onclick=""loadShm('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{15}', '{16}');"" value='{14}'></div>"; startupShmScript = @" <script> $(document).ready(function() { collapseShm(); }); </script> "; } var collectPoint = String.Empty; if (!string.IsNullOrEmpty(deliveryMethodAddress) && deliveryMethodDescription != null) { collectPoint = $"<div style='margin-bottom: 10px;'>{deliveryMethodDescription.ResourceValue}<br/>{deliveryMethodAddress}</div>"; } var description = string.Format( collectPoint + buttonDiv + @"<div id='shm-inline-container' style='width: 100%; margin-top: 10px;'></div>", _settings.AccountId, orderRef, getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode, checkSum, getShippingOptionRequest.ShippingAddress.FirstName, getShippingOptionRequest.ShippingAddress.LastName, getShippingOptionRequest.Customer.Email, street, getShippingOptionRequest.ShippingAddress.ZipPostalCode, getShippingOptionRequest.ShippingAddress.City, confirmUrl, cancelUrl, errorUrl, _settings.ButtonCssClass, _localizationService.GetResource("MakeIT.Nop.Shipping.Bpost.ShippingManager.ButtonCaption"), _workContext.WorkingLanguage.UniqueSeoCode, streetNumber); var shmShippingOption = new ShippingOption { Name = _localizationService.GetResource("MakeIT.Nop.Shipping.Bpost.ShippingManager.ShippingOptionTitle"), Rate = (rate > 0) ? rate : _settings.Standardprice, ShippingRateComputationMethodSystemName = "Shipping.Bpost.ShippingManager", Description = description + startupShmScript }; response.ShippingOptions.Add(shmShippingOption); 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(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.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("getShippingOptionRequest"); } if (getShippingOptionRequest.Items == null) { return new GetShippingOptionResponse { Errors = new List <string> { "No shipment items" } } } ; if (getShippingOptionRequest.ShippingAddress == null) { return new GetShippingOptionResponse { Errors = new List <string> { "Shipping address is not set" } } } ; if (getShippingOptionRequest.ShippingAddress.Country == null) { return new GetShippingOptionResponse { Errors = new List <string> { "Shipping country is not set" } } } ; if (string.IsNullOrEmpty(getShippingOptionRequest.ZipPostalCodeFrom)) { return new GetShippingOptionResponse { Errors = new List <string> { "Origin postal code is not set" } } } ; //get available services string errors; var availableServices = CanadaPostHelper.GetServices(getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode, _canadaPostSettings.ApiKey, _canadaPostSettings.UseSandbox, out errors); if (availableServices == null) { return new GetShippingOptionResponse { Errors = new List <string> { errors } } } ; //create object for the get rates requests var result = new GetShippingOptionResponse(); object destinationCountry; switch (getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode.ToLowerInvariant()) { case "us": destinationCountry = new mailingscenarioDestinationUnitedstates { zipcode = getShippingOptionRequest.ShippingAddress.ZipPostalCode }; break; case "ca": destinationCountry = new mailingscenarioDestinationDomestic { postalcode = getShippingOptionRequest.ShippingAddress.ZipPostalCode.Replace(" ", string.Empty).ToUpperInvariant() }; break; default: destinationCountry = new mailingscenarioDestinationInternational { countrycode = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode }; break; } var mailingScenario = new mailingscenario { quotetype = mailingscenarioQuotetype.counter, quotetypeSpecified = true, originpostalcode = getShippingOptionRequest.ZipPostalCodeFrom.Replace(" ", string.Empty).ToUpperInvariant(), destination = new mailingscenarioDestination { Item = destinationCountry } }; //set contract customer properties if (!string.IsNullOrEmpty(_canadaPostSettings.CustomerNumber)) { mailingScenario.quotetype = mailingscenarioQuotetype.commercial; mailingScenario.customernumber = _canadaPostSettings.CustomerNumber; mailingScenario.contractid = !string.IsNullOrEmpty(_canadaPostSettings.ContractId) ? _canadaPostSettings.ContractId : null; } //get original parcel characteristics decimal originalLength; decimal originalWidth; decimal originalHeight; decimal originalWeight; GetWeight(getShippingOptionRequest, out originalWeight); GetDimensions(getShippingOptionRequest, out originalLength, out originalWidth, out originalHeight); //get rate for all available services var errorSummary = new StringBuilder(); foreach (var service in availableServices.service) { var currentService = CanadaPostHelper.GetServiceDetails(_canadaPostSettings.ApiKey, service.link.href, service.link.mediatype, out errors); if (currentService != null) { #region parcels count calculation var totalParcels = 1; //parcels count by weight var maxWeight = currentService.restrictions != null && currentService.restrictions.weightrestriction != null && currentService.restrictions.weightrestriction.maxSpecified ? currentService.restrictions.weightrestriction.max : int.MaxValue; if (originalWeight * 1000 > maxWeight) { var parcelsOnWeight = Convert.ToInt32(Math.Ceiling(originalWeight * 1000 / maxWeight)); if (parcelsOnWeight > totalParcels) { totalParcels = parcelsOnWeight; } } //parcels count by length var maxLength = currentService.restrictions != null && currentService.restrictions.dimensionalrestrictions != null && currentService.restrictions.dimensionalrestrictions.length != null && currentService.restrictions.dimensionalrestrictions.length.maxSpecified ? currentService.restrictions.dimensionalrestrictions.length.max : int.MaxValue; if (originalLength > maxLength) { var parcelsOnLength = Convert.ToInt32(Math.Ceiling(originalLength / maxLength)); if (parcelsOnLength > totalParcels) { totalParcels = parcelsOnLength; } } //parcels count by width var maxWidth = currentService.restrictions != null && currentService.restrictions.dimensionalrestrictions != null && currentService.restrictions.dimensionalrestrictions.width != null && currentService.restrictions.dimensionalrestrictions.width.maxSpecified ? currentService.restrictions.dimensionalrestrictions.width.max : int.MaxValue; if (originalWidth > maxWidth) { var parcelsOnWidth = Convert.ToInt32(Math.Ceiling(originalWidth / maxWidth)); if (parcelsOnWidth > totalParcels) { totalParcels = parcelsOnWidth; } } //parcels count by height var maxHeight = currentService.restrictions != null && currentService.restrictions.dimensionalrestrictions != null && currentService.restrictions.dimensionalrestrictions.height != null && currentService.restrictions.dimensionalrestrictions.height.maxSpecified ? currentService.restrictions.dimensionalrestrictions.height.max : int.MaxValue; if (originalHeight > maxHeight) { var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(originalHeight / maxHeight)); if (parcelsOnHeight > totalParcels) { totalParcels = parcelsOnHeight; } } //parcel count by girth var lengthPlusGirthMax = currentService.restrictions != null && currentService.restrictions.dimensionalrestrictions != null && currentService.restrictions.dimensionalrestrictions.lengthplusgirthmaxSpecified ? currentService.restrictions.dimensionalrestrictions.lengthplusgirthmax : int.MaxValue; var lengthPlusGirth = 2 * (originalWidth + originalHeight) + originalLength; if (lengthPlusGirth > lengthPlusGirthMax) { var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(lengthPlusGirth / lengthPlusGirthMax)); if (parcelsOnHeight > totalParcels) { totalParcels = parcelsOnHeight; } } //parcel count by sum of length, width and height var lengthWidthHeightMax = currentService.restrictions != null && currentService.restrictions.dimensionalrestrictions != null && currentService.restrictions.dimensionalrestrictions.lengthheightwidthsummaxSpecified ? currentService.restrictions.dimensionalrestrictions.lengthheightwidthsummax : int.MaxValue; var lengthWidthHeight = originalLength + originalWidth + originalHeight; if (lengthWidthHeight > lengthWidthHeightMax) { var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(lengthWidthHeight / lengthWidthHeightMax)); if (parcelsOnHeight > totalParcels) { totalParcels = parcelsOnHeight; } } #endregion //set parcel characteristics mailingScenario.services = new[] { currentService.servicecode }; mailingScenario.parcelcharacteristics = new mailingscenarioParcelcharacteristics { weight = Math.Round(originalWeight / totalParcels, 3), dimensions = new mailingscenarioParcelcharacteristicsDimensions { length = Math.Round(originalLength / totalParcels, 1), width = Math.Round(originalWidth / totalParcels, 1), height = Math.Round(originalHeight / totalParcels, 1) } }; //get rate var priceQuotes = CanadaPostHelper.GetShippingRates(mailingScenario, _canadaPostSettings.ApiKey, _canadaPostSettings.UseSandbox, out errors); if (priceQuotes != null) { foreach (var option in priceQuotes.pricequote) { result.ShippingOptions.Add(new ShippingOption { Name = option.servicename, Rate = PriceToPrimaryStoreCurrency(option.pricedetails.due * totalParcels), Description = string.Format("Delivery {0}into {1} parcels", option.servicestandard != null && !string.IsNullOrEmpty(option.servicestandard.expectedtransittime) ? string.Format("in {0} days ", option.servicestandard.expectedtransittime) : string.Empty, totalParcels), }); } } else { errorSummary.AppendLine(errors); } } else { errorSummary.AppendLine(errors); } } //write errors var errorString = errorSummary.ToString(); if (!string.IsNullOrEmpty(errorString)) { _logger.Error(errorString); } if (!result.ShippingOptions.Any()) { result.AddError(errorString); } return(result); }
/// <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) { response.AddError("No shipment items"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } if (getShippingOptionRequest.ShippingAddress.Country == null) { response.AddError("Shipping country is not set"); return(response); } if (getShippingOptionRequest.CountryFrom == null) { getShippingOptionRequest.CountryFrom = _countryService.GetAllCountries().FirstOrDefault(); } try { string requestString = CreateRequest(_upsSettings.AccessKey, _upsSettings.Username, _upsSettings.Password, getShippingOptionRequest, _upsSettings.CustomerClassification, _upsSettings.PickupType, _upsSettings.PackagingType); if (_upsSettings.Tracing) { _traceMessages.AppendLine("Request:").AppendLine(requestString); } string responseXml = DoRequest(_upsSettings.Url, requestString); if (_upsSettings.Tracing) { _traceMessages.AppendLine("Response:").AppendLine(responseXml); } string error = ""; var shippingOptions = ParseResponse(responseXml, ref error); if (String.IsNullOrEmpty(error)) { foreach (var shippingOption in shippingOptions) { if (!shippingOption.Name.ToLower().StartsWith("ups")) { shippingOption.Name = string.Format("UPS {0}", shippingOption.Name); } shippingOption.Rate += _upsSettings.AdditionalHandlingCharge; response.ShippingOptions.Add(shippingOption); } } else { response.AddError(error); } } finally { if (_upsSettings.Tracing && _traceMessages.Length > 0) { string shortMessage = String.Format("UPS Get Shipping Options for customer {0}. {1} item(s) in cart", getShippingOptionRequest.Customer.Email, getShippingOptionRequest.Items.Count); _logger.Information(shortMessage, new Exception(_traceMessages.ToString()), getShippingOptionRequest.Customer); } } 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) { var originAddress = _shippingSettings.ShippingOriginAddressId > 0 ? _addressService.GetAddressById(_shippingSettings.ShippingOriginAddressId) : null; if (originAddress == null) { response.AddError("Origin Address or Shipping address is not set"); return(response); } getShippingOptionRequest.ShippingAddress = originAddress; } int countryId = getShippingOptionRequest.ShippingAddress.CountryId.HasValue ? getShippingOptionRequest.ShippingAddress.CountryId.Value : 0; decimal subTotal = decimal.Zero; foreach (var shoppingCartItem in getShippingOptionRequest.Items) { if (shoppingCartItem.IsFreeShipping || !shoppingCartItem.IsShipEnabled) { continue; } subTotal += _priceCalculationService.GetSubTotal(shoppingCartItem, true); } decimal deci = GetShoppingCartTotalDeci(getShippingOptionRequest.Items); var shippingMethods = _shippingService.GetAllShippingMethods(countryId); decimal additionalRate = _settingService.GetSettingByKey <decimal>("ShippingRateComputationMethod.ByWeight.DHLRate"); additionalRate = Math.Max(1, additionalRate); foreach (var shippingMethod in shippingMethods) { decimal?rate = GetRate(subTotal, deci, shippingMethod.Id, countryId); 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 * additionalRate; 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) { response.AddError("No shipment items"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } string zipPostalCodeFrom = _australiaPostSettings.ShippedFromZipPostalCode; string zipPostalCodeTo = getShippingOptionRequest.ShippingAddress.ZipPostalCode; int weight = GetWeight(getShippingOptionRequest); int length = GetLength(getShippingOptionRequest); int width = GetWidth(getShippingOptionRequest); int height = GetHeight(getShippingOptionRequest); var country = getShippingOptionRequest.ShippingAddress.Country; //estimate packaging int totalPackages = 1; int totalPackagesDims = 1; int totalPackagesWeights = 1; if (length > MAX_LENGTH || width > MAX_LENGTH || height > MAX_LENGTH) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)Math.Max(Math.Max(length, width), height) / MAX_LENGTH)); } if (weight > MAX_WEIGHT) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAX_WEIGHT)); } totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } if (totalPackages > 1) { //recalculate dims, weight weight = weight / totalPackages; height = height / totalPackages; width = width / totalPackages; length = length / totalPackages; if (weight < MIN_WEIGHT) { weight = MIN_WEIGHT; } if (height < MIN_LENGTH) { height = MIN_LENGTH; } if (width < MIN_LENGTH) { width = MIN_LENGTH; } if (length < MIN_LENGTH) { length = MIN_LENGTH; } } int girth = height + height + width + width; if (girth < MIN_GIRTH) { height = MIN_LENGTH; width = MIN_LENGTH; } if (girth > MAX_GIRTH) { height = MAX_LENGTH / 4; width = MAX_LENGTH / 4; } try { switch (country.ThreeLetterIsoCode) { case "AUS": //domestic services response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Standard", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Express", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "EXP_PLT", weight, length, width, height, totalPackages)); break; default: //international services response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Air", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Sea", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "ECI_D", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "ECI_M", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "EPI", weight, length, width, height, totalPackages)); break; } foreach (var shippingOption in response.ShippingOptions) { shippingOption.Rate += _australiaPostSettings.AdditionalHandlingCharge; } } catch (Exception ex) { response.AddError(ex.Message); } 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) { response.AddError("No shipment items"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } string zipPostalCodeFrom = getShippingOptionRequest.ZipPostalCodeFrom; string zipPostalCodeTo = getShippingOptionRequest.ShippingAddress.ZipPostalCode; int weight = GetWeight(getShippingOptionRequest); decimal lengthTmp, widthTmp, heightTmp; _shippingService.GetDimensions(getShippingOptionRequest.Items, out widthTmp, out lengthTmp, out heightTmp); int length = Math.Min(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(lengthTmp, this.GatewayMeasureDimension))), MIN_LENGTH); int width = Math.Min(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(widthTmp, this.GatewayMeasureDimension))), MIN_LENGTH); int height = Math.Min(Convert.ToInt32(Math.Ceiling(this._measureService.ConvertFromPrimaryMeasureDimension(heightTmp, this.GatewayMeasureDimension))), MIN_LENGTH); //estimate packaging int totalPackagesDims = 1; int totalPackagesWeights = 1; if (length > MAX_LENGTH || width > MAX_LENGTH || height > MAX_LENGTH) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)Math.Max(Math.Max(length, width), height) / MAX_LENGTH)); } if (weight > MAX_WEIGHT) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAX_WEIGHT)); } var totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } if (totalPackages > 1) { //recalculate dims, weight weight = weight / totalPackages; height = height / totalPackages; width = width / totalPackages; length = length / totalPackages; if (weight < MIN_WEIGHT) { weight = MIN_WEIGHT; } if (height < MIN_LENGTH) { height = MIN_LENGTH; } if (width < MIN_LENGTH) { width = MIN_LENGTH; } if (length < MIN_LENGTH) { length = MIN_LENGTH; } } int girth = height + height + width + width; if (girth < MIN_GIRTH) { height = MIN_LENGTH; width = MIN_LENGTH; } if (girth > MAX_GIRTH) { height = MAX_LENGTH / 4; width = MAX_LENGTH / 4; } var country = getShippingOptionRequest.ShippingAddress.Country; if (country == null) { response.AddError("Shipping country is not specified"); return(response); } var serviceTypes = new List <string>(); switch (country.ThreeLetterIsoCode) { case "AUS": //domestic services serviceTypes.Add("Standard"); serviceTypes.Add("Express"); //discontinued serviceTypes.Add("EXP_PLT"); break; default: //international services serviceTypes.Add("Air"); serviceTypes.Add("Sea"); serviceTypes.Add("ECI_D"); serviceTypes.Add("ECI_M"); serviceTypes.Add("EPI"); break; } foreach (var serviceType in serviceTypes) { try { response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, serviceType, weight, length, width, height, totalPackages)); } catch { //If this plugin doesn't allow some method (e.g. sea freight) to the selected country (e.g. New Zealand), //the AusPost API returns an err_msg. //This throws an exception which results in no shipping options being offered at all. //The result is that customers from NZ can't buy anything. //That why we commented the code below (do not exit) //and process each "RequestShippingOption" separately (in try-catch) //response.AddError(ex.Message); } } foreach (var shippingOption in response.ShippingOptions) { shippingOption.Rate += _australiaPostSettings.AdditionalHandlingCharge; } return(response); }