/// <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); }
public async Task <EstimateShippingResultModel> Handle(GetEstimateShippingResult request, CancellationToken cancellationToken) { var model = new EstimateShippingResultModel(); if (request.Cart.RequiresShipping()) { var address = new Address { CountryId = request.CountryId, StateProvinceId = request.StateProvinceId, ZipPostalCode = request.ZipPostalCode, }; GetShippingOptionResponse getShippingOptionResponse = await _shippingService .GetShippingOptions(request.Customer, request.Cart, address, "", request.Store); if (!getShippingOptionResponse.Success) { foreach (var error in getShippingOptionResponse.Errors) { model.Warnings.Add(error); } } else { if (getShippingOptionResponse.ShippingOptions.Any()) { foreach (var shippingOption in getShippingOptionResponse.ShippingOptions) { var soModel = new EstimateShippingResultModel.ShippingOptionModel { Name = shippingOption.Name, Description = shippingOption.Description, }; //calculate discounted and taxed rate var total = await _orderTotalCalculationService.AdjustShippingRate(shippingOption.Rate, request.Cart); List <AppliedDiscount> appliedDiscounts = total.appliedDiscounts; decimal shippingTotal = total.shippingRate; decimal rateBase = (await _taxService.GetShippingPrice(shippingTotal, request.Customer)).shippingPrice; decimal rate = await _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, request.Currency); soModel.Price = _priceFormatter.FormatShippingPrice(rate, true); model.ShippingOptions.Add(soModel); } //pickup in store? if (_shippingSettings.AllowPickUpInStore) { var pickupPoints = await _shippingService.GetAllPickupPoints(); if (pickupPoints.Count > 0) { var soModel = new EstimateShippingResultModel.ShippingOptionModel { Name = _localizationService.GetResource("Checkout.PickUpInStore"), Description = _localizationService.GetResource("Checkout.PickUpInStore.Description"), }; decimal shippingTotal = pickupPoints.Max(x => x.PickupFee); decimal rateBase = (await _taxService.GetShippingPrice(shippingTotal, request.Customer)).shippingPrice; decimal rate = await _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, request.Currency); soModel.Price = _priceFormatter.FormatShippingPrice(rate, true); model.ShippingOptions.Add(soModel); } } } else { model.Warnings.Add(_localizationService.GetResource("Checkout.ShippingIsNotAllowed")); } } } return(model); }
/// <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(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 : (await _storeContext.GetCurrentStoreAsync()).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 (await _shippingService.IsFreeShippingAsync(packageItem.ShoppingCartItem)) { continue; } subTotal += (await _shoppingCartService.GetSubTotalAsync(packageItem.ShoppingCartItem, true)).subTotal; } //get weight of shipped items (excluding items with free shipping) var weight = await _shippingService.GetTotalWeightAsync(getShippingOptionRequest, ignoreFreeShippedItems : true); foreach (var shippingMethod in await _shippingService.GetAllShippingMethodsAsync(countryId)) { int?transitDays = null; var rate = decimal.Zero; var shippingByWeightByTotalRecord = await _shippingByWeightByTotalService.FindRecordsAsync( 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 = await _localizationService.GetLocalizedAsync(shippingMethod, x => x.Name), Description = await _localizationService.GetLocalizedAsync(shippingMethod, x => x.Description), Rate = rate, TransitDays = transitDays }); } } else { //shipping rate calculation by fixed rate var restrictByCountryId = getShippingOptionRequest.ShippingAddress?.CountryId; response.ShippingOptions = await(await _shippingService.GetAllShippingMethodsAsync(restrictByCountryId)).SelectAwait(async shippingMethod => new ShippingOption { Name = await _localizationService.GetLocalizedAsync(shippingMethod, x => x.Name), Description = await _localizationService.GetLocalizedAsync(shippingMethod, x => x.Description), Rate = await GetRateAsync(shippingMethod.Id), TransitDays = await GetTransitDaysAsync(shippingMethod.Id) }).ToListAsync(); } 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); }
/// <summary> /// Gets available shipping options /// </summary> /// <param name="request">A request for getting shipping options</param> /// <returns>Represents a response of getting shipping rate options</returns> public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest request) { if (request == null) { throw new ArgumentNullException("getShippingOptionRequest"); } var response = new GetShippingOptionResponse(); if (request.Items == null || request.Items.Count == 0) { response.AddError(T("Admin.System.Warnings.NoShipmentItems")); return(response); } int storeId = request.StoreId > 0 ? request.StoreId : _storeContext.CurrentStore.Id; decimal subTotal = decimal.Zero; int countryId = 0; string zip = null; if (request.ShippingAddress != null) { countryId = request.ShippingAddress.CountryId ?? 0; zip = request.ShippingAddress.ZipPostalCode; } foreach (var shoppingCartItem in request.Items) { if (shoppingCartItem.Item.IsFreeShipping || !shoppingCartItem.Item.IsShipEnabled) { continue; } subTotal += _priceCalculationService.GetSubTotal(shoppingCartItem, true); } var weight = _shippingService.GetShoppingCartTotalWeight(request.Items, _shippingByWeightSettings.IncludeWeightOfFreeShippingProducts); var shippingMethods = _shippingService.GetAllShippingMethods(request); 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("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(nameof(getShippingOptionRequest)); } var response = new GetShippingOptionResponse(); if (getShippingOptionRequest.Items == null || !getShippingOptionRequest.Items.Any()) { response.AddError("No shipment items"); return(response); } //choose the shipping rate calculation method if (_fixedByWeightByTotalSettings.ShippingByWeightByTotalEnabled) { //shipping rate calculation by products weight if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } var storeId = getShippingOptionRequest.StoreId != 0 ? getShippingOptionRequest.StoreId : _storeContext.CurrentStore.Id; var countryId = getShippingOptionRequest.ShippingAddress.CountryId ?? 0; var stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId ?? 0; var warehouseId = getShippingOptionRequest.WarehouseFrom?.Id ?? 0; var zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode; //get subtotal of shipped items var subTotal = decimal.Zero; foreach (var packageItem in getShippingOptionRequest.Items) { if (packageItem.ShoppingCartItem.IsFreeShipping(_productService, _productAttributeParser)) { continue; } //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal subTotal += _priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem); } //get weight of shipped items (excluding items with free shipping) var weight = _shippingService.GetTotalWeight(getShippingOptionRequest, ignoreFreeShippedItems: true); foreach (var shippingMethod in _shippingService.GetAllShippingMethods(countryId)) { var rate = GetRate(subTotal, weight, shippingMethod.Id, storeId, warehouseId, countryId, stateProvinceId, zip); if (!rate.HasValue) { continue; } response.ShippingOptions.Add(new ShippingOption { Name = shippingMethod.GetLocalized(x => x.Name), Description = shippingMethod.GetLocalized(x => x.Description), Rate = rate.Value }); } } else { //shipping rate calculation by fixed rate var restrictByCountryId = getShippingOptionRequest.ShippingAddress?.Country?.Id; response.ShippingOptions = _shippingService.GetAllShippingMethods(restrictByCountryId).Select(shippingMethod => new ShippingOption { Name = shippingMethod.GetLocalized(x => x.Name), Description = shippingMethod.GetLocalized(x => x.Description), Rate = GetRate(shippingMethod.Id) }).ToList(); } return(response); }
public GetShippingOptionResponse GetShippingOptions( GetShippingOptionRequest getShippingOptionRequest ) { if (getShippingOptionRequest == null) { throw new ArgumentNullException( nameof(getShippingOptionRequest) ); } // Validate that 'lb' measure weight exists in system var lbsMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword("lb"); if (lbsMeasureWeight == null) { return(new GetShippingOptionResponse { Errors = new[] { "Cannot perform weight conversion, unable " + "to find 'lb' measure weight. Make sure a measure weight " + "with 'lb' system keyword exists." } }); } if (!getShippingOptionRequest.Items?.Any() ?? true) { return(new GetShippingOptionResponse { Errors = new[] { "No shipment items" } }); } // Check that destination zip/postal was provided var destinationZip = getShippingOptionRequest.ShippingAddress?.ZipPostalCode; if (destinationZip == null) { return(new GetShippingOptionResponse { Errors = new[] { "Destination shipping zip/postal code is not set" } }); } var weight = _shippingService.GetTotalWeight( getShippingOptionRequest ); var weightInLbs = _measureService.ConvertFromPrimaryMeasureWeight( weight, lbsMeasureWeight); // If under minimum, don't provide as option if (weightInLbs < _settings.MinimumWeightLimitInLbs) { return(new GetShippingOptionResponse()); } decimal rateQuote; try { rateQuote = _rateQuoteService.GetRateQuote( destinationZip, decimal.ToInt32(decimal.Round(weightInLbs)) ); } catch (NopException ex) { return(new GetShippingOptionResponse { Errors = new[] { $"{ex.Message}" } }); } var response = new GetShippingOptionResponse(); response.ShippingOptions.Add(new ShippingOption() { Name = _settings.ShippingOptionName, Rate = rateQuote }); 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; } 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) { 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 || 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); }
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="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); }
private cResultado ProcessShipping(GetShippingOptionRequest getShippingOptionRequest, GetShippingOptionResponse getShippingOptionResponse) { var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword(MEASURE_WEIGHT_SYSTEM_KEYWORD); if (usedMeasureWeight == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure peso", MEASURE_WEIGHT_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword(MEASURE_DIMENSION_SYSTEM_KEYWORD); if (usedMeasureDimension == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure dimension", MEASURE_DIMENSION_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } //Na versão 2.2 o getShippingOptionRequest.ZipPostalCodeFrom retorna string.Empty, possui um TODO... string cepOrigem = null; if (this._shippingSettings.ShippingOriginAddressId > 0) { var addr = this._addressService.GetAddressById(this._shippingSettings.ShippingOriginAddressId); if (addr != null && !String.IsNullOrEmpty(addr.ZipPostalCode) && addr.ZipPostalCode.Length >= 8 && addr.ZipPostalCode.Length <= 9) { cepOrigem = addr.ZipPostalCode; } } if (cepOrigem == null) { _logger.Fatal("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); throw new NopException("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); } if (!string.IsNullOrEmpty(_correiosSettings.CEPRestito)) { string CepDestinoRestrito = getShippingOptionRequest.ShippingAddress.ZipPostalCode.Replace("-", "").Replace(".", ""); int[] ints = _correiosSettings.CEPRestito.Split(';').Select(s => int.Parse(s)).ToArray(); bool is_cep_retrict = false; bool is_categoria_retrict = false; bool is_restric = false; string[] categoriasrestritas = _correiosSettings.CategoriasRetritras.Split(';'); // esta na lista de cep restrito if (Enumerable.Range(ints[0], ints[1]).Contains(int.Parse(CepDestinoRestrito))) { is_cep_retrict = true; } // se tiver catergoria, quer dizer que so restringe apenas se houver x categrorais if (!string.IsNullOrEmpty(categoriasrestritas[0]) && is_cep_retrict) { var itens = getShippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList(); int _categoria; foreach (var a in itens) { _categoria = a.Product.ProductCategories.Select(p => p.CategoryId).FirstOrDefault(); if (categoriasrestritas.Contains(_categoria.ToString())) { is_categoria_retrict = true; break; } } } is_restric = is_categoria_retrict && is_cep_retrict; if (is_restric) { _logger.Fatal("Plugin.Shipping.Correios: Você contém produtos que não podem ser entregue pelos correios na sua região"); return(null); } //89000000-99000000 } var correiosCalculation = new CorreiosBatchCalculation(this._logger) { CodigoEmpresa = _correiosSettings.CodigoEmpresa, Senha = _correiosSettings.Senha, CepOrigem = cepOrigem, Servicos = _correiosSettings.CarrierServicesOffered, AvisoRecebimento = _correiosSettings.IncluirAvisoRecebimento, MaoPropria = _correiosSettings.IncluirMaoPropria, CepDestino = getShippingOptionRequest.ShippingAddress.ZipPostalCode }; decimal subtotalBase = decimal.Zero; decimal orderSubTotalDiscountAmount = decimal.Zero; List <DiscountForCaching> orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList(), false, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); subtotalBase = subTotalWithDiscountBase; decimal comprimentoTmp, larguraTmp, alturaTmp; _shippingService.GetDimensions(getShippingOptionRequest.Items, out larguraTmp, out comprimentoTmp, out alturaTmp); int comprimento = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(comprimentoTmp, usedMeasureDimension)) / 10); int altura = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(alturaTmp, usedMeasureDimension)) / 10); int largura = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(larguraTmp, usedMeasureDimension)) / 10); int peso = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureWeight(_shippingService.GetTotalWeight(getShippingOptionRequest), usedMeasureWeight))); if (comprimento < 1) { comprimento = 1; } if (altura < 1) { altura = 1; } if (largura < 1) { largura = 1; } if (peso < 1) { peso = 1; } //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (altura > comprimento) { comprimento = altura; } // string ms = " Antes" + "Altura " + altura.ToString() + " Comprimento " + comprimento.ToString() + " Largura " + largura.ToString() + " Peso " + peso.ToString() ; // _logger.Error(ms); if (IsPackageTooSmall(comprimento, altura, largura)) { comprimento = MININO_COMPRIMENTO_PACOTE; altura = MININO_ALTURA_PACOTE; largura = MININO_LARGURA_PACOTE; } if ((!IsPackageTooHeavy(peso)) && (!IsPackageTooLarge(comprimento, altura, largura))) { Debug.WriteLine("Plugin.Shipping.Correios: Pacote unico"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = altura, Comprimento = comprimento, Largura = largura, Diametro = 0, FormatoPacote = true, Peso = peso, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase : 0) }); return(correiosCalculation.Calculate()); } else { int totalPackages = 1; int totalPackagesDims = 1; int totalPackagesWeights = 1; if (IsPackageTooHeavy(peso)) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)peso / (decimal)MAX_PACKAGE_WEIGHT)); } if (IsPackageTooLarge(comprimento, altura, largura)) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(comprimento, altura, largura) / (decimal)MAX_PACKAGE_TOTAL_DIMENSION)); } totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } int weight2 = peso / totalPackages; int height2 = altura / totalPackages; int width2 = largura / totalPackages; int length2 = comprimento / totalPackages; if (weight2 < 1) { weight2 = 1; } if (height2 < 1) { height2 = 1; } if (width2 < 1) { width2 = 1; } if (length2 < 1) { length2 = 1; } //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (height2 > width2) { width2 = height2; } // Debug.WriteLine("Plugin.Shipping.Correios: Multiplos pacotes"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = height2, Comprimento = length2, Largura = width2, Diametro = 0, FormatoPacote = true, Peso = weight2, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase / totalPackages : 0) }); var result = correiosCalculation.Calculate(); if (result != null) { foreach (cServico s in result.Servicos) { if (s.Erro == "0") { s.Valor = (decimal.Parse(s.Valor, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorAvisoRecebimento = (decimal.Parse(s.ValorAvisoRecebimento, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorMaoPropria = (decimal.Parse(s.ValorMaoPropria, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorValorDeclarado = (decimal.Parse(s.ValorValorDeclarado, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); } } } 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 (string.IsNullOrEmpty(getShippingOptionRequest.ZipPostalCodeFrom)) { response.AddError("Shipping origin zip is not set"); return(response); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return(response); } var country = getShippingOptionRequest.ShippingAddress.Country; if (country == null) { response.AddError("Shipping country is not specified"); 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="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": 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: 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); } 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, false); 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, false, 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); } //saturday delivery if (_upsSettings.CarrierServicesOffered.Contains("[sa]")) { requestString = CreateRequest(_upsSettings.AccessKey, _upsSettings.Username, _upsSettings.Password, getShippingOptionRequest, _upsSettings.CustomerClassification, _upsSettings.PickupType, _upsSettings.PackagingType, true); if (_upsSettings.Tracing) { _traceMessages.AppendLine("Request:").AppendLine(requestString); } responseXml = DoRequest(_upsSettings.Url, requestString); if (_upsSettings.Tracing) { _traceMessages.AppendLine("Response:").AppendLine(responseXml); } error = string.Empty; var saturdayDeliveryShippingOptions = ParseResponse(responseXml, true, ref error); if (string.IsNullOrEmpty(error)) { foreach (var shippingOption in saturdayDeliveryShippingOptions) { shippingOption.Name = string.Format("{0}{1} - Saturday Delivery", shippingOption.Name.ToLower().StartsWith("ups") ? string.Empty : "UPS ", shippingOption.Name); shippingOption.Rate += _upsSettings.AdditionalHandlingCharge; response.ShippingOptions.Add(shippingOption); } } else { response.AddError(error); } } if (response.ShippingOptions.Any()) { response.Errors.Clear(); } } 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); }
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("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 = _storeContext.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; 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, _workContext.CurrentCustomer); 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="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); }
/// <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; double subTotal = 0; 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; } } double weight = await GetTotalWeight(getShippingOptionRequest); var shippingMethods = await _shippingMethodService.GetAllShippingMethods(countryId, _workContext.CurrentCustomer); foreach (var shippingMethod in shippingMethods) { 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); 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="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) { 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) + _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); } }
/// <summary> /// Gets available shipping options /// </summary> /// <param name="getShippingOptionRequest">A request for getting shipping options</param> /// <returns>Represents a response of getting shipping rate options</returns> public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest) { if (getShippingOptionRequest == null) { throw new ArgumentNullException("getShippingOptionRequest"); } var response = new GetShippingOptionResponse(); if (getShippingOptionRequest.Items == null || getShippingOptionRequest.Items.Count == 0) { response.AddError(T("Admin.System.Warnings.NoShipmentItems")); return(response); } int countryId = 0; int stateProvinceId = 0; string zip = null; decimal subTotal = decimal.Zero; int storeId = _storeContext.CurrentStore.Id; if (getShippingOptionRequest.ShippingAddress != null) { countryId = getShippingOptionRequest.ShippingAddress.CountryId ?? 0; stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId ?? 0; zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode; } foreach (var shoppingCartItem in getShippingOptionRequest.Items) { if (shoppingCartItem.Item.IsFreeShipping || !shoppingCartItem.Item.IsShipEnabled) { continue; } subTotal += _priceCalculationService.GetSubTotal(shoppingCartItem, true); } decimal sqThreshold = _shippingByTotalSettings.SmallQuantityThreshold; decimal sqSurcharge = _shippingByTotalSettings.SmallQuantitySurcharge; var shippingMethods = _shippingService.GetAllShippingMethods(getShippingOptionRequest); foreach (var shippingMethod in shippingMethods) { decimal?rate = GetRate(subTotal, shippingMethod.Id, storeId, countryId, stateProvinceId, zip); if (rate.HasValue) { if (rate > 0 && sqThreshold > 0 && subTotal <= sqThreshold) { // add small quantity surcharge (Mindermengenzuschalg) rate += sqSurcharge; } var shippingOption = new ShippingOption(); shippingOption.ShippingMethodId = shippingMethod.Id; shippingOption.Name = shippingMethod.Name; shippingOption.Description = shippingMethod.Description; shippingOption.Rate = rate.Value; response.ShippingOptions.Add(shippingOption); } } return(response); }
private cResultado ProcessShipping(GetShippingOptionRequest getShippingOptionRequest, GetShippingOptionResponse getShippingOptionResponse) { var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword(MEASURE_WEIGHT_SYSTEM_KEYWORD); if (usedMeasureWeight == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure weight", MEASURE_WEIGHT_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword(MEASURE_DIMENSION_SYSTEM_KEYWORD); if (usedMeasureDimension == null) { string e = string.Format("Plugin.Shipping.Correios: Could not load \"{0}\" measure dimension", MEASURE_DIMENSION_SYSTEM_KEYWORD); _logger.Fatal(e); throw new NopException(e); } //Na versão 2.2 o getShippingOptionRequest.ZipPostalCodeFrom retorna string.Empty, possui um TODO... string cepOrigem = null; if (this._shippingSettings.ShippingOriginAddressId > 0) { var addr = this._addressService.GetAddressById(this._shippingSettings.ShippingOriginAddressId); if (addr != null && !String.IsNullOrEmpty(addr.ZipPostalCode) && addr.ZipPostalCode.Length >= 8 && addr.ZipPostalCode.Length <= 9) { cepOrigem = addr.ZipPostalCode; } } if (cepOrigem == null) { _logger.Fatal("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); throw new NopException("Plugin.Shipping.Correios: CEP de Envio em branco ou inválido, configure nas opções de envio do NopCommerce.Em Administração > Configurações > Configurações de Envio. Formato: 00000000"); } var correiosCalculation = new CorreiosBatchCalculation(this._logger) { CodigoEmpresa = _correiosSettings.CodigoEmpresa, Senha = _correiosSettings.Senha, CepOrigem = cepOrigem, Servicos = _correiosSettings.CarrierServicesOffered, AvisoRecebimento = _correiosSettings.IncluirAvisoRecebimento, MaoPropria = _correiosSettings.IncluirMaoPropria, CepDestino = getShippingOptionRequest.ShippingAddress.ZipPostalCode }; decimal subtotalBase = decimal.Zero; decimal orderSubTotalDiscountAmount = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); subtotalBase = subTotalWithDiscountBase; int length = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalLength(), usedMeasureDimension)) / 10); int height = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalHeight(), usedMeasureDimension)) / 10); int width = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalWidth(), usedMeasureDimension)) / 10); int weight = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureWeight(_shippingService.GetShoppingCartTotalWeight(getShippingOptionRequest.Items), usedMeasureWeight))); if (length < 1) { length = 1; } if (height < 1) { height = 1; } if (width < 1) { width = 1; } if (weight < 1) { weight = 1; } //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (height > length) { length = height; } if (IsPackageTooSmall(length, height, width)) { length = MIN_PACKAGE_LENGTH; height = MIN_PACKAGE_HEIGHT; width = MIN_PACKAGE_WIDTH; } if ((!IsPackageTooHeavy(weight)) && (!IsPackageTooLarge(length, height, width))) { Debug.WriteLine("Plugin.Shipping.Correios: Pacote unico"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = height, Comprimento = length, Largura = width, Diametro = 0, FormatoPacote = true, Peso = weight, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase : 0) }); return(correiosCalculation.Calculate()); } else { int totalPackages = 1; int totalPackagesDims = 1; int totalPackagesWeights = 1; if (IsPackageTooHeavy(weight)) { totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAX_PACKAGE_WEIGHT)); } if (IsPackageTooLarge(length, height, width)) { totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)MAX_PACKAGE_TOTAL_DIMENSION)); } totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights; if (totalPackages == 0) { totalPackages = 1; } int weight2 = weight / totalPackages; int height2 = height / totalPackages; int width2 = width / totalPackages; int length2 = length / totalPackages; if (weight2 < 1) { weight2 = 1; } if (height2 < 1) { height2 = 1; } if (width2 < 1) { width2 = 1; } if (length2 < 1) { length2 = 1; } //Altura não pode ser maior que o comprimento, para evitar erro, igualamos e a embalagem deve ser adaptada. if (height2 > width2) { width2 = height2; } Debug.WriteLine("Plugin.Shipping.Correios: Multiplos pacotes"); correiosCalculation.Pacotes.Add(new CorreiosBatchCalculation.Pacote() { Altura = height2, Comprimento = length2, Largura = width2, Diametro = 0, FormatoPacote = true, Peso = weight2, ValorDeclarado = (_correiosSettings.IncluirValorDeclarado ? subtotalBase / totalPackages : 0) }); var result = correiosCalculation.Calculate(); if (result != null) { foreach (cServico s in result.Servicos) { if (s.Erro == "0") { s.Valor = (decimal.Parse(s.Valor, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorAvisoRecebimento = (decimal.Parse(s.ValorAvisoRecebimento, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorMaoPropria = (decimal.Parse(s.ValorMaoPropria, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); s.ValorValorDeclarado = (decimal.Parse(s.ValorValorDeclarado, correiosCalculation.PtBrCulture) * totalPackages).ToString(correiosCalculation.PtBrCulture); } } } return(result); } }
public ProcessPaymentRequest SetCheckoutDetails(ProcessPaymentRequest processPaymentRequest, GetExpressCheckoutDetailsResponseDetailsType checkoutDetails) { int customerId = Convert.ToInt32(Services.WorkContext.CurrentCustomer.Id.ToString()); var customer = _customerService.GetCustomerById(customerId); var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(Services.StoreContext.CurrentStore.Id); Services.WorkContext.CurrentCustomer = customer; //var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); var cart = Services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, Services.StoreContext.CurrentStore.Id); // get/update billing address string billingFirstName = checkoutDetails.PayerInfo.PayerName.FirstName; string billingLastName = checkoutDetails.PayerInfo.PayerName.LastName; string billingEmail = checkoutDetails.PayerInfo.Payer; string billingAddress1 = checkoutDetails.PayerInfo.Address.Street1; string billingAddress2 = checkoutDetails.PayerInfo.Address.Street2; string billingPhoneNumber = checkoutDetails.PayerInfo.ContactPhone; string billingCity = checkoutDetails.PayerInfo.Address.CityName; int? billingStateProvinceId = null; var billingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(checkoutDetails.PayerInfo.Address.StateOrProvince); if (billingStateProvince != null) { billingStateProvinceId = billingStateProvince.Id; } string billingZipPostalCode = checkoutDetails.PayerInfo.Address.PostalCode; int? billingCountryId = null; var billingCountry = _countryService.GetCountryByTwoLetterIsoCode(checkoutDetails.PayerInfo.Address.Country.ToString()); if (billingCountry != null) { billingCountryId = billingCountry.Id; } var billingAddress = customer.Addresses.FindAddress( billingFirstName, billingLastName, billingPhoneNumber, billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity, billingStateProvinceId, billingZipPostalCode, billingCountryId); if (billingAddress == null) { billingAddress = new Core.Domain.Common.Address() { FirstName = billingFirstName, LastName = billingLastName, PhoneNumber = billingPhoneNumber, Email = billingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = billingAddress1, Address2 = billingAddress2, City = billingCity, StateProvinceId = billingStateProvinceId, ZipPostalCode = billingZipPostalCode, CountryId = billingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(billingAddress); } //set default billing address customer.BillingAddress = billingAddress; _customerService.UpdateCustomer(customer); var genericAttributeService = EngineContext.Current.Resolve <IGenericAttributeService>(); genericAttributeService.SaveAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.SelectedShippingOption, null); bool shoppingCartRequiresShipping = cart.RequiresShipping(); if (shoppingCartRequiresShipping) { var paymentDetails = checkoutDetails.PaymentDetails.FirstOrDefault(); string[] shippingFullname = paymentDetails.ShipToAddress.Name.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string shippingFirstName = shippingFullname[0]; string shippingLastName = string.Empty; if (shippingFullname.Length > 1) { shippingLastName = shippingFullname[1]; } string shippingEmail = checkoutDetails.PayerInfo.Payer; string shippingAddress1 = paymentDetails.ShipToAddress.Street1; string shippingAddress2 = paymentDetails.ShipToAddress.Street2; string shippingPhoneNumber = paymentDetails.ShipToAddress.Phone; string shippingCity = paymentDetails.ShipToAddress.CityName; int? shippingStateProvinceId = null; var shippingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(paymentDetails.ShipToAddress.StateOrProvince); if (shippingStateProvince != null) { shippingStateProvinceId = shippingStateProvince.Id; } int? shippingCountryId = null; string shippingZipPostalCode = paymentDetails.ShipToAddress.PostalCode; var shippingCountry = _countryService.GetCountryByTwoLetterIsoCode(paymentDetails.ShipToAddress.Country.ToString()); if (shippingCountry != null) { shippingCountryId = shippingCountry.Id; } var shippingAddress = customer.Addresses.FindAddress( shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail, string.Empty, string.Empty, shippingAddress1, shippingAddress2, shippingCity, shippingStateProvinceId, shippingZipPostalCode, shippingCountryId); if (shippingAddress == null) { shippingAddress = new Core.Domain.Common.Address() { FirstName = shippingFirstName, LastName = shippingLastName, PhoneNumber = shippingPhoneNumber, Email = shippingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = shippingAddress1, Address2 = shippingAddress2, City = shippingCity, StateProvinceId = shippingStateProvinceId, ZipPostalCode = shippingZipPostalCode, CountryId = shippingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(shippingAddress); } customer.ShippingAddress = shippingAddress; _customerService.UpdateCustomer(customer); } bool isShippingSet = false; GetShippingOptionResponse getShippingOptionResponse = _shippingService.GetShippingOptions(cart, customer.ShippingAddress); if (checkoutDetails.UserSelectedOptions != null) { if (getShippingOptionResponse.Success && getShippingOptionResponse.ShippingOptions.Count > 0) { foreach (var shippingOption in getShippingOptionResponse.ShippingOptions) { if (checkoutDetails.UserSelectedOptions.ShippingOptionName.Contains(shippingOption.Name) && checkoutDetails.UserSelectedOptions.ShippingOptionName.Contains(shippingOption.Description)) { _genericAttributeService.SaveAttribute(Services.WorkContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, shippingOption); isShippingSet = true; break; } } } if (!isShippingSet) { var shippingOption = new ShippingOption(); shippingOption.Name = checkoutDetails.UserSelectedOptions.ShippingOptionName; decimal shippingPrice = settings.DefaultShippingPrice; decimal.TryParse(checkoutDetails.UserSelectedOptions.ShippingOptionAmount.Value, out shippingPrice); shippingOption.Rate = shippingPrice; _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.SelectedShippingOption, shippingOption); } } processPaymentRequest.PaypalPayerId = checkoutDetails.PayerInfo.PayerID; return(processPaymentRequest); }
private bool ValidateRequest(GetShippingOptionRequest getShippingOptionRequest, GetShippingOptionResponse response) { if (getShippingOptionRequest.Items == null) { response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.NoShipmentItems")); } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.AddressNotSet")); } if (getShippingOptionRequest.CountryFrom == null) { response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.CountryNotSet")); } if (getShippingOptionRequest.StateProvinceFrom == null) { response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.StateNotSet")); } if (getShippingOptionRequest.ShippingAddress.ZipPostalCode == null) { response.AddError(_localizationService.GetResource("Plugins.Shipping.Correios.Message.PostalCodeNotSet")); } return(response.Errors.Count > 0 ? false : true); }
/// <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); } string countryTwoLetterIsoCode = null; 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); if (getShippingOptionRequest.ShippingAddress != null) { countryTwoLetterIsoCode = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode; } //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 { if (countryTwoLetterIsoCode.HasValue()) { if (countryTwoLetterIsoCode.IsCaseInsensitiveEqual("AU")) { //domestic services response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, countryTwoLetterIsoCode, "Standard", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, countryTwoLetterIsoCode, "Express", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, countryTwoLetterIsoCode, "EXP_PLT", weight, length, width, height, totalPackages)); } else { //international services response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, countryTwoLetterIsoCode, "Air", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, countryTwoLetterIsoCode, "Sea", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, countryTwoLetterIsoCode, "ECI_D", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, countryTwoLetterIsoCode, "ECI_M", weight, length, width, height, totalPackages)); response.ShippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, countryTwoLetterIsoCode, "EPI", weight, length, width, height, totalPackages)); } } foreach (var shippingOption in response.ShippingOptions) { shippingOption.Rate += _australiaPostSettings.AdditionalHandlingCharge; } } catch (Exception ex) { response.AddError(ex.Message); } 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); }