Example #1
0
        static Rate ChooseRate(AddressValidatingShipment shipment, Carrier carrier, string apiKey)
        {
            Console.WriteLine("Getting rates...");

            var ratesApi            = new RatesApi();
            var rateShipmentRequest = new RateShipmentRequest(shipment: shipment, rateOptions: new RateRequest(new List <string> {
                carrier.CarrierId
            }));
            var rates = ratesApi.RatesRateShipment(rateShipmentRequest, apiKey).RateResponse.Rates;

            Console.WriteLine("Let's choose a rate:");

            for (var i = 0; i < rates.Count; i++)
            {
                Console.WriteLine($"\t{i + 1}) {rates[i].ServiceCode} - ${rates[i].ShippingAmount.Amount}");
            }

            Console.Write("\nChoose a rate: ");

            var selectionRaw = Console.ReadLine();
            var selection    = -1;

            if (selectionRaw == null || !int.TryParse(selectionRaw, out selection))
            {
                Console.WriteLine("No!");
                WaitToQuit();
            }

            Console.WriteLine($"You selected {rates[selection - 1].ServiceCode}.");
            Console.WriteLine();

            return(rates[selection - 1]);
        }
Example #2
0
        public ShippingRateResult GetShippingRate(
            string shippingMethod,
            Cart cart,
            CommercePipelineExecutionContext context,
            GetSellableItemCommand getSellableItemCommand
            )
        {
            if (cart == null ||
                !cart.HasComponent <PhysicalFulfillmentComponent>() ||
                string.IsNullOrEmpty(shippingMethod)
                )
            {
                return(null);
            }


            context.Logger.LogInformation($"{this.GetType().Name} - Begin GetShippingRate", Array.Empty <object>());



            var policy        = context.CommerceContext.GetPolicy <ShipEnginePolicy>();
            var component     = cart.GetComponent <PhysicalFulfillmentComponent>();
            var shippingParty = component?.ShippingParty;

            var     countryCode = Get2DigitCountryCode(shippingParty.CountryCode);
            Carrier carrier     = policy.DefaultCarrier;

            var shipment = new AddressValidatingShipment()
            {
                Confirmation = policy.ShipDeliveryConfirmation,

                InsuranceProvider = policy.ShipInsuranceProvider,

                CarrierId = carrier.CarrierId,

                ServiceCode = carrier.Services.FirstOrDefault().ServiceCode, // "usps_priority_mail" edvin change

                Packages = new List <ShipmentPackage>(),

                ShipFrom = new AddressDTO(
                    name: String.IsNullOrWhiteSpace(policy.ShipperName) ? context.CommerceContext.CurrentShopName() : policy.ShipperName,
                    phone: policy.ShipperPhone,
                    companyName: String.IsNullOrWhiteSpace(policy.ShipperCompany) ? context.CommerceContext.CurrentShopName() : policy.ShipperCompany,
                    addressLine1: policy.ShipperAddressLine1,
                    addressLine2: policy.ShipperAddressLine2,
                    addressLine3: policy.ShipperAddressLine3,
                    cityLocality: policy.ShipperCityLocality,
                    stateProvince: policy.ShipperStateProvince,
                    postalCode: policy.ShipperPostalCode,
                    countryCode: policy.ShipperCountryCode
                    ),

                ShipTo = new AddressDTO(
                    name: shippingParty.AddressName,
                    phone: shippingParty.PhoneNumber,
                    companyName: shippingParty.Name,
                    addressLine1: shippingParty.Address1,
                    addressLine2: shippingParty.Address2,
                    addressLine3: string.Empty,
                    cityLocality: shippingParty.City,
                    stateProvince: Get2DigitStateCode(countryCode, shippingParty.State),
                    postalCode: shippingParty.ZipPostalCode,
                    countryCode: countryCode
                    ),
            };


            // Address validation handled in ResolveAddressBlock
            shipment.ValidateAddress = AddressValidatingShipment.ValidateAddressEnum.NoValidation;

            shipment.WarehouseId = policy.GetWearhouseId(shipment.ShipTo);

            // Get sellableItem weight and dimensions
            //
            var shipmentPackages = new List <ShipmentPackage>();

            var dim = new Dimensions(Dimensions.UnitEnum.Inch);

            MoneyDTO insuredValue = null;

            foreach (var cartLineItem in cart.Lines)
            {
                var sellableItem = getSellableItemCommand.Process(context.CommerceContext, cartLineItem.ItemId, filterVariations: true).Result;

                // get specific weight value
                //
                var itemSpec = sellableItem.GetComponent <ItemSpecificationsComponent>();

                if (itemSpec == null || String.IsNullOrWhiteSpace(itemSpec.DimensionsUnitOfMeasure))
                {
                    var errorMessage = string.Format("{0} - no Item Specification (Weight, Dimension) exists for SellableItem {1}, productId {2}",
                                                     this.GetType().Name,
                                                     sellableItem.Name,
                                                     sellableItem.ProductId);


                    context.CommerceContext.AddMessage(
                        context.GetPolicy <KnownResultCodes>().Error,
                        "InvalidOrMissingPropertyValue",
                        new object[] { errorMessage })
                    ;

                    context.Logger.LogError(errorMessage);

                    return(new ShippingRateResult()
                    {
                        ErrorMessage = errorMessage,
                        IsErrorAddedToCommerceContext = true
                    });
                }

                var globalPolicy = context.GetPolicy <GlobalPhysicalFulfillmentPolicy>();


                // Get the unit for dimension and weight as required by ShipEngine
                //



                // Handle edge case of Feet and Meters by converting them to inches and centimeters
                switch (itemSpec.DimensionsUnitOfMeasure.ToLower().Substring(0, 2))
                {
                case "fe":     // feet
                case "fo":     // foot

                    itemSpec.Length *= 12;
                    itemSpec.Width  *= 12;
                    itemSpec.Height *= 12;
                    itemSpec.DimensionsUnitOfMeasure = "Inch";
                    break;

                case "me":     // Meters

                    itemSpec.Length *= 100;
                    itemSpec.Width  *= 100;
                    itemSpec.Height *= 100;
                    itemSpec.DimensionsUnitOfMeasure = "Centimeter";
                    break;

                case "mi":     // Millimeter

                    itemSpec.Length = Math.Max(itemSpec.Length / 10, 1);
                    itemSpec.Width  = Math.Max(itemSpec.Width / 10, 1);
                    itemSpec.Height = Math.Max(itemSpec.Height / 10, 1);
                    itemSpec.DimensionsUnitOfMeasure = "Centimeter";
                    break;
                }


                var dimensionUnit = policy.StringToDimensionUnit(
                    string.IsNullOrEmpty(itemSpec.DimensionsUnitOfMeasure)
                        ? globalPolicy.MeasurementUnits
                        : itemSpec.DimensionsUnitOfMeasure
                    );

                var weightUnit = policy.StringToWeightUnit(
                    string.IsNullOrEmpty(itemSpec.WeightUnitOfMeasure)
                        ? globalPolicy.WeightUnits
                        : itemSpec.WeightUnitOfMeasure
                    );



                if (policy.ShipInsuranceProvider != AddressValidatingShipment.InsuranceProviderEnum.None)
                {
                    insuredValue = policy.GetInsuredAmount(sellableItem, context);
                }


                if (!isSellableItemWeightWithInPolicyLimit(itemSpec, policy, globalPolicy))
                {
                    context.Logger.LogError(
                        string.Format("{0} - Item weight ({1}) Exceeding golbal policy MaximumShippingWeigh ({2}) for SellableItem {3}, productId {4}",
                                      this.GetType().Name,
                                      itemSpec.Weight,
                                      globalPolicy.MaxShippingWeight,
                                      sellableItem.Name,
                                      sellableItem.ProductId)
                        );
                }

                shipmentPackages.Add(new ShipmentPackage
                {
                    Weight        = new Weight(itemSpec.Weight, weightUnit),
                    Dimensions    = new Dimensions(dimensionUnit, itemSpec.Length, itemSpec.Width, itemSpec.Height),
                    InsuredValue  = insuredValue,
                    LabelMessages = null
                });
            }

            //Func<Rate, bool> shippingMethodMatchDelegate = rate => rate.ServiceCode?.IndexOf(shippingMethod, StringComparison.InvariantCultureIgnoreCase) >= 0;

            MoneyDTO shipmentAmount = null;

            // Get shipping rate if the fullfilment center supports multi-package shipment
            //
            RatesApi shippingRate = new RatesApi();

            if (carrier.HasMultiPackageSupportingServices ?? false)
            {
                shipment.Packages = shipmentPackages;

                var rateShipmentRequest = new RateShipmentRequest(shipment: shipment, rateOptions: new RateRequest(new List <string> {
                    carrier.CarrierId
                }));

                rateShipmentRequest.Shipment.Confirmation = policy.GetShippingConfirmationMethod();

                var shipmentResponse = shippingRate.RatesRateShipment(rateShipmentRequest, policy.ApiKey);

                shipmentAmount = GetShippingResponseRatesAsync(shipmentResponse, shippingMethod, context).Result;
            }

            // If multi-package shipment is not supported; then we will get rate for
            // each package and and calculate the total sum as shipping rate.
            //
            else
            {
                var currency = (MoneyDTO.CurrencyEnum)Enum.Parse(typeof(MoneyDTO.CurrencyEnum), context.CommerceContext.CurrentCurrency());

                shipmentAmount = new MoneyDTO(currency, amount: 0);
                foreach (var package in shipmentPackages)
                {
                    shipment.Packages.RemoveAll(s => true);
                    shipment.Packages.Add(package);

                    var rateShipmentRequest = new RateShipmentRequest(shipment: shipment, rateOptions: new RateRequest(new List <string> {
                        carrier.CarrierId
                    }));

                    var shipmentRate = shippingRate.RatesRateShipment(rateShipmentRequest, policy.ApiKey);

                    var amount = GetShippingResponseRatesAsync(shipmentRate, shippingMethod, context).Result;

                    if (amount == null)
                    {
                        return(null);
                    }
                    shipmentAmount.Amount += amount.Amount;
                    insuredValue.Amount   += package.InsuredValue.Amount;
                }
            }
            context.Logger.LogInformation($"{this.GetType().Name} - End GetShippingRate", Array.Empty <object>());


            return(new ShippingRateResult()
            {
                ShippingRate = shipmentAmount,
                InsuranceAmount = insuredValue
            });
        }
 public IActionResult CalculateRates(Request model)
 {
     HttpContext.Session.Clear();
     if (ModelState.IsValid)
     {
         //create dimensions object
         Dimensions.UnitEnum dimensionsUnit = new Dimensions.UnitEnum();
         foreach (KeyValuePair <string, Dimensions.UnitEnum> item in DimensionUnitsConfig.DimensionsUnitsList)
         {
             if (item.Key == model.shipment.package.dimensions.unit)
             {
                 dimensionsUnit = item.Value;
             }
         }
         Dimensions dimensions = new Dimensions
         {
             Length = model.shipment.package.dimensions.length,
             Width  = model.shipment.package.dimensions.width,
             Height = model.shipment.package.dimensions.height,
             Unit   = dimensionsUnit
         };
         //create weight object
         Weight.UnitEnum weightUnit = new Weight.UnitEnum();
         foreach (KeyValuePair <string, Weight.UnitEnum> item in WeightUnitsConfig.WeightUnitsList)
         {
             if (item.Key == model.shipment.package.weight.unit)
             {
                 weightUnit = item.Value;
             }
         }
         Weight weight = new Weight
         {
             Value = model.shipment.package.weight.value,
             Unit  = weightUnit
         };
         //create package list
         List <ShipmentPackage> packageList = new List <ShipmentPackage>();
         //create package and push to package list
         ShipmentPackage package = new ShipmentPackage
         {
             Weight     = weight,
             Dimensions = dimensions
         };
         packageList.Add(package);
         // create ship to address
         AddressDTO ship_to = new AddressDTO
         {
             Name          = model.shipment.ship_to.name,
             Phone         = model.shipment.ship_to.phone,
             PostalCode    = model.shipment.ship_to.postal_code,
             StateProvince = model.shipment.ship_to.state_province,
             CityLocality  = model.shipment.ship_to.city_locality,
             AddressLine1  = model.shipment.ship_to.address_line1,
             AddressLine2  = model.shipment.ship_to.address_line2,
             CompanyName   = model.shipment.ship_to.company_name,
             CountryCode   = model.shipment.ship_to.country_code
         };
         // create ship from address
         AddressDTO ship_from = new AddressDTO
         {
             Name          = model.shipment.ship_from.name,
             Phone         = model.shipment.ship_from.phone,
             PostalCode    = model.shipment.ship_from.postal_code,
             StateProvince = model.shipment.ship_from.state_province,
             CityLocality  = model.shipment.ship_from.city_locality,
             AddressLine1  = model.shipment.ship_from.address_line1,
             AddressLine2  = model.shipment.ship_from.address_line2,
             CompanyName   = model.shipment.ship_from.company_name,
             CountryCode   = model.shipment.ship_from.country_code
         };
         // create shipment
         AddressValidatingShipment shipment = new AddressValidatingShipment
         {
             Packages = packageList,
             ShipFrom = ship_from,
             ShipTo   = ship_to
         };
         // create rateoptions
         var           apiKey     = "2zWOj6zfmwc98DLwos4B9U5Jg9wOxkAjlX20vgEYtDs";
         var           carrierApi = new CarriersApi();
         List <string> carrierIds = new List <string>();
         try
         {
             List <Carrier> carrierList = carrierApi.CarriersList(apiKey).Carriers;
             foreach (Carrier carrier in carrierList)
             {
                 carrierIds.Add(carrier.CarrierId);
             }
         }
         catch (Exception e)
         {
             Debug.Print("Exception when calling CarriersApi.CarriersList: " + e.Message);
         }
         RateRequest rateOptions = new RateRequest
         {
             CarrierIds = carrierIds
         };
         // create request
         RateShipmentRequest request = new RateShipmentRequest
         {
             Shipment    = shipment,
             RateOptions = rateOptions
         };
         //send rate results to action through tempdata
         var rateApi = new RatesApi();
         try
         {
             RateShipmentResponse result = rateApi.RatesRateShipment(request, apiKey);
             RateResponse         rates  = result.RateResponse;
             HttpContext.Session.SetString("rates", JsonConvert.SerializeObject(rates));
             return(RedirectToAction("RateResults"));
         }
         catch (Exception e)
         {
             Debug.Print("Exception when calling RatesApi.RatesRateShipment: " + e.Message);
         }
     }
     return(RedirectToAction("Rates"));
 }