/// <summary> /// Gets available shipping options /// </summary> /// <param name="getShippingOptionRequest">A request for getting shipping options</param> /// <returns>Represents a response of getting shipping rate options</returns> public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest) { if (getShippingOptionRequest == null) throw new ArgumentNullException("getShippingOptionRequest"); var response = new GetShippingOptionResponse(); if (getShippingOptionRequest.Items == null || getShippingOptionRequest.Items.Count == 0) { response.AddError("No shipment items"); return response; } int? restrictByCountryId = (getShippingOptionRequest.ShippingAddress != null && getShippingOptionRequest.ShippingAddress.Country != null) ? (int?)getShippingOptionRequest.ShippingAddress.Country.Id : null; var shippingMethods = this._shippingService.GetAllShippingMethods(restrictByCountryId); foreach (var shippingMethod in shippingMethods) { var shippingOption = new ShippingOption(); shippingOption.Name = shippingMethod.GetLocalized(x => x.Name); shippingOption.Description = shippingMethod.GetLocalized(x => x.Description); shippingOption.Rate = GetRate(shippingMethod.Id); response.ShippingOptions.Add(shippingOption); } return response; }
public static ShippingOption ParseShippingOption(this JObject obj, ICurrencyService currencyService) { var audCurrency = currencyService.GetCurrencyByCode("AUD"); if (obj.HasValues) { var shippingOption = new ShippingOption(); foreach (var property in obj.Properties()) { switch (property.Name.ToLower()) { case "name": shippingOption.Name = string.Format("Australia Post. {0}", property.Value); break; case "price": decimal rate; if (decimal.TryParse(property.Value.ToString(), out rate)) { var convertedRate = currencyService.ConvertToPrimaryStoreCurrency(rate, audCurrency); shippingOption.Rate = convertedRate; } break; } } return shippingOption; } return null; }
public void Can_convert_shippingOption_to_string_and_back() { var shippingOptionInput = new ShippingOption { Name = "1", Description = "2", Rate = 3.57M, ShippingRateComputationMethodSystemName = "4" }; var converter = TypeDescriptor.GetConverter(shippingOptionInput.GetType()); var result = converter.ConvertTo(shippingOptionInput, typeof(string)) as string; var shippingOptionOutput = converter.ConvertFrom(result) as ShippingOption; shippingOptionOutput.ShouldNotBeNull(); shippingOptionOutput.Name.ShouldEqual("1"); shippingOptionOutput.Description.ShouldEqual("2"); shippingOptionOutput.Rate.ShouldEqual(3.57M); shippingOptionOutput.ShippingRateComputationMethodSystemName.ShouldEqual("4"); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { ShippingOption shippingOption = value as ShippingOption; if (shippingOption != null) { var sb = new StringBuilder(); using (var tw = new StringWriter(sb)) { var xmlS = new XmlSerializer(typeof(ShippingOption)); xmlS.Serialize(tw, value); string serialized = sb.ToString(); return(serialized); } } else { return(""); } } return(base.ConvertTo(context, culture, value, destinationType)); }
private void ProcessNewOrderNotification(string xmlData) { try { var newOrderNotification = (NewOrderNotification)EncodeHelper.Deserialize(xmlData, typeof(NewOrderNotification)); string googleOrderNumber = newOrderNotification.googleordernumber; XmlNode customerInfo = newOrderNotification.shoppingcart.merchantprivatedata.Any[0]; int customerId = Convert.ToInt32(customerInfo.Attributes["CustomerID"].Value); //int customerLanguageId = Convert.ToInt32(customerInfo.Attributes["CustomerLanguageID"].Value); //int customerCurrencyId = Convert.ToInt32(customerInfo.Attributes["CustomerCurrencyID"].Value); var customer = _customerService.GetCustomerById(customerId); if (customer == null) { LogMessage("Could not load a customer"); return; } var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); _workContext.CurrentCustomer = customer; if (cart.Count == 0) { LogMessage("Cart is empty"); return; } //validate cart foreach (var sci in cart) { bool ok = false; foreach (Item item in newOrderNotification.shoppingcart.items) { if (!String.IsNullOrEmpty(item.merchantitemid)) { if ((Convert.ToInt32(item.merchantitemid) == sci.Id) && (item.quantity == sci.Quantity)) { ok = true; break; } } } if (!ok) { LogMessage(string.Format("Shopping Cart item has been changed. {0}. {1}", sci.Id, sci.Quantity)); return; } } string[] billingFullname = newOrderNotification.buyerbillingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string billingFirstName = billingFullname[0]; string billingLastName = string.Empty; if (billingFullname.Length > 1) billingLastName = billingFullname[1]; string billingEmail = newOrderNotification.buyerbillingaddress.email.Trim(); string billingAddress1 = newOrderNotification.buyerbillingaddress.address1.Trim(); string billingAddress2 = newOrderNotification.buyerbillingaddress.address2.Trim(); string billingPhoneNumber = newOrderNotification.buyerbillingaddress.phone.Trim(); string billingCity = newOrderNotification.buyerbillingaddress.city.Trim(); int? billingStateProvinceId = null; var billingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(newOrderNotification.buyerbillingaddress.region.Trim()); if (billingStateProvince != null) billingStateProvinceId = billingStateProvince.Id; string billingZipPostalCode = newOrderNotification.buyerbillingaddress.postalcode.Trim(); int? billingCountryId = null; var billingCountry = _countryService.GetCountryByTwoLetterIsoCode(newOrderNotification.buyerbillingaddress.countrycode.Trim()); if (billingCountry != null) billingCountryId = billingCountry.Id; var billingAddress = customer.Addresses.ToList().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, 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); _genericAttributeService.SaveAttribute<ShippingOption>(customer, SystemCustomerAttributeNames.LastShippingOption, null); bool shoppingCartRequiresShipping = cart.RequiresShipping(); if (shoppingCartRequiresShipping) { string[] shippingFullname = newOrderNotification.buyershippingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string shippingFirstName = shippingFullname[0]; string shippingLastName = string.Empty; if (shippingFullname.Length > 1) shippingLastName = shippingFullname[1]; string shippingEmail = newOrderNotification.buyershippingaddress.email.Trim(); string shippingAddress1 = newOrderNotification.buyershippingaddress.address1.Trim(); string shippingAddress2 = newOrderNotification.buyershippingaddress.address2.Trim(); string shippingPhoneNumber = newOrderNotification.buyershippingaddress.phone.Trim(); string shippingCity = newOrderNotification.buyershippingaddress.city.Trim(); int? shippingStateProvinceId = null; var shippingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(newOrderNotification.buyershippingaddress.region.Trim()); if (shippingStateProvince != null) shippingStateProvinceId = shippingStateProvince.Id; int? shippingCountryId = null; string shippingZipPostalCode = newOrderNotification.buyershippingaddress.postalcode.Trim(); var shippingCountry = _countryService.GetCountryByTwoLetterIsoCode(newOrderNotification.buyershippingaddress.countrycode.Trim()); if (shippingCountry != null) shippingCountryId = shippingCountry.Id; var shippingAddress = customer.Addresses.ToList().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, Address1 = shippingAddress1, Address2 = shippingAddress2, City = shippingCity, StateProvinceId = shippingStateProvinceId, ZipPostalCode = shippingZipPostalCode, CountryId = shippingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(shippingAddress); } //set default shipping address customer.ShippingAddress = shippingAddress; _customerService.UpdateCustomer(customer); if (newOrderNotification.orderadjustment != null && newOrderNotification.orderadjustment.shipping != null && newOrderNotification.orderadjustment.shipping.Item != null) { var shippingMethod = (FlatRateShippingAdjustment)newOrderNotification.orderadjustment.shipping.Item; var shippingOption = new ShippingOption(); shippingOption.Name = shippingMethod.shippingname; shippingOption.Rate = shippingMethod.shippingcost.Value; _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastShippingOption, shippingOption); } } //customer.LastCalculatedTax = decimal.Zero; var paymentInfo = new ProcessPaymentRequest() { PaymentMethodSystemName = "Payments.GoogleCheckout", CustomerId = customer.Id, GoogleOrderNumber = googleOrderNumber }; //TODO set customer language and currency //paymentInfo.CustomerLanguage = IoC.Resolve<ILanguageService>().GetLanguageById(CustomerLanguageID); //paymentInfo.CustomerCurrency = IoC.Resolve<ICurrencyService>().GetCurrencyById(CustomerCurrencyID); var result = _orderProcessingService.PlaceOrder(paymentInfo); if (!result.Success) { LogMessage("new-order-notification received. CreateOrder() error: Order Number " + googleOrderNumber + ". " + result); return; } var order = result.PlacedOrder; if (order != null) { LogMessage("new-order-notification received and saved: Order Number " + order.Id); } } catch (Exception exc) { LogMessage("processNewOrderNotification Exception: " + exc.Message + ": " + exc.StackTrace); } }
private ShippingOption RequestShippingOption(string zipPostalCodeFrom, string zipPostalCodeTo, string countryCode, string serviceType, int weight, int length, int width, int height, int quantity) { var shippingOption = new ShippingOption(); var sb = new StringBuilder(); sb.AppendFormat(GetGatewayUrl()); sb.AppendFormat("?Pickup_Postcode={0}&", zipPostalCodeFrom); sb.AppendFormat("Destination_Postcode={0}&", zipPostalCodeTo); sb.AppendFormat("Country={0}&", countryCode); sb.AppendFormat("Service_Type={0}&", serviceType); sb.AppendFormat("Weight={0}&", weight); sb.AppendFormat("Length={0}&", length); sb.AppendFormat("Width={0}&", width); sb.AppendFormat("Height={0}&", height); sb.AppendFormat("Quantity={0}", quantity); HttpWebRequest request = WebRequest.Create(sb.ToString()) as HttpWebRequest; request.Method = "GET"; //request.ContentType = "application/x-www-form-urlencoded"; //byte[] reqContent = Encoding.ASCII.GetBytes(sb.ToString()); //request.ContentLength = reqContent.Length; //using (Stream newStream = request.GetRequestStream()) //{ // newStream.Write(reqContent, 0, reqContent.Length); //} WebResponse response = request.GetResponse(); string rspContent; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { rspContent = reader.ReadToEnd(); } string[] tmp = rspContent.Split(new char[] { '\n' }, 3); if (tmp.Length != 3) { throw new NopException("Response is not valid."); } var rspParams = new NameValueCollection(); foreach (string s in tmp) { string[] tmp2 = s.Split(new char[] { '=' }); if (tmp2.Length != 2) { throw new NopException("Response is not valid."); } rspParams.Add(tmp2[0].Trim(), tmp2[1].Trim()); } string err_msg = rspParams["err_msg"]; if (!err_msg.ToUpperInvariant().StartsWith("OK")) { throw new NopException(err_msg); } shippingOption.Name = serviceType; shippingOption.Description = String.Format("{0} Days", rspParams["days"]); shippingOption.Rate = Decimal.Parse(rspParams["charge"]); return shippingOption; }
private List<ShippingOption> ParseResponse(RateReply reply, Currency requestedShipmentCurrency) { var result = new List<ShippingOption>(); Debug.WriteLine("RateReply details:"); Debug.WriteLine("**********************************************************"); foreach (var rateDetail in reply.RateReplyDetails) { var shippingOption = new ShippingOption(); string serviceName = FedexServices.GetServiceName(rateDetail.ServiceType.ToString()); // Skip the current service if services are selected and this service hasn't been selected if (!String.IsNullOrEmpty(_fedexSettings.CarrierServicesOffered) && !_fedexSettings.CarrierServicesOffered.Contains(rateDetail.ServiceType.ToString())) { continue; } Debug.WriteLine("ServiceType: " + rateDetail.ServiceType); if (!serviceName.Equals("UNKNOWN")) { shippingOption.Name = serviceName; foreach (RatedShipmentDetail shipmentDetail in rateDetail.RatedShipmentDetails) { Debug.WriteLine("RateType : " + shipmentDetail.ShipmentRateDetail.RateType); Debug.WriteLine("Total Billing Weight : " + shipmentDetail.ShipmentRateDetail.TotalBillingWeight.Value); Debug.WriteLine("Total Base Charge : " + shipmentDetail.ShipmentRateDetail.TotalBaseCharge.Amount); Debug.WriteLine("Total Discount : " + shipmentDetail.ShipmentRateDetail.TotalFreightDiscounts.Amount); Debug.WriteLine("Total Surcharges : " + shipmentDetail.ShipmentRateDetail.TotalSurcharges.Amount); Debug.WriteLine("Net Charge : " + shipmentDetail.ShipmentRateDetail.TotalNetCharge.Amount + "(" + shipmentDetail.ShipmentRateDetail.TotalNetCharge.Currency + ")"); Debug.WriteLine("*********"); // Get discounted rates if option is selected if (_fedexSettings.ApplyDiscounts & shipmentDetail.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_ACCOUNT) { decimal amount = ConvertChargeToPrimaryCurrency(shipmentDetail.ShipmentRateDetail.TotalNetCharge, requestedShipmentCurrency); shippingOption.Rate = amount + _fedexSettings.AdditionalHandlingCharge; break; } else if (shipmentDetail.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_LIST) // Get List Rates (not discount rates) { decimal amount = ConvertChargeToPrimaryCurrency(shipmentDetail.ShipmentRateDetail.TotalNetCharge, requestedShipmentCurrency); shippingOption.Rate = amount + _fedexSettings.AdditionalHandlingCharge; break; } else // Skip the rate (RATED_ACCOUNT, PAYOR_MULTIWEIGHT, or RATED_LIST) { continue; } } result.Add(shippingOption); } Debug.WriteLine("**********************************************************"); } 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.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; }
private IEnumerable<ShippingOption> ParseResponse(string response, ref string error) { var shippingOptions = new List<ShippingOption>(); string carrierServicesOffered = _upsSettings.CarrierServicesOffered; using (var sr = new StringReader(response)) using (var tr = new XmlTextReader(sr)) while (tr.Read()) { if ((tr.Name == "Error") && (tr.NodeType == XmlNodeType.Element)) { string errorText = ""; while (tr.Read()) { if ((tr.Name == "ErrorCode") && (tr.NodeType == XmlNodeType.Element)) { errorText += "UPS Rating Error, Error Code: " + tr.ReadString() + ", "; } if ((tr.Name == "ErrorDescription") && (tr.NodeType == XmlNodeType.Element)) { errorText += "Error Desc: " + tr.ReadString(); } } error = "UPS Error returned: " + errorText; } if ((tr.Name == "RatedShipment") && (tr.NodeType == XmlNodeType.Element)) { string serviceCode = ""; string monetaryValue = ""; while (tr.Read()) { if ((tr.Name == "Service") && (tr.NodeType == XmlNodeType.Element)) { while (tr.Read()) { if ((tr.Name == "Code") && (tr.NodeType == XmlNodeType.Element)) { serviceCode = tr.ReadString(); tr.ReadEndElement(); } if ((tr.Name == "Service") && (tr.NodeType == XmlNodeType.EndElement)) { break; } } } if (((tr.Name == "RatedShipment") && (tr.NodeType == XmlNodeType.EndElement)) || ((tr.Name == "RatedPackage") && (tr.NodeType == XmlNodeType.Element))) { break; } if ((tr.Name == "TotalCharges") && (tr.NodeType == XmlNodeType.Element)) { while (tr.Read()) { if ((tr.Name == "MonetaryValue") && (tr.NodeType == XmlNodeType.Element)) { monetaryValue = tr.ReadString(); tr.ReadEndElement(); } if ((tr.Name == "TotalCharges") && (tr.NodeType == XmlNodeType.EndElement)) { break; } } } } string service = GetServiceName(serviceCode); string serviceId = String.Format("[{0}]", serviceCode); // Go to the next rate if the service ID is not in the list of services to offer if (!String.IsNullOrEmpty(carrierServicesOffered) && !carrierServicesOffered.Contains(serviceId)) { continue; } //Weed out unwanted or unknown service rates if (service.ToUpper() != "UNKNOWN") { var shippingOption = new ShippingOption(); shippingOption.Rate = Convert.ToDecimal(monetaryValue, new CultureInfo("en-US")); shippingOption.Name = service; shippingOptions.Add(shippingOption); } } } return shippingOptions; }
public ActionResult NewShippingAddress(CheckoutShippingAddressModel model, FormCollection form) { //validation var cart = _workContext.CurrentCustomer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id) .ToList(); if (cart.Count == 0) return RedirectToRoute("ShoppingCart"); if (_orderSettings.OnePageCheckoutEnabled) return RedirectToRoute("CheckoutOnePage"); if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)) return new HttpUnauthorizedResult(); if (!cart.RequiresShipping()) { _workContext.CurrentCustomer.ShippingAddress = null; _customerService.UpdateCustomer(_workContext.CurrentCustomer); return RedirectToRoute("CheckoutShippingMethod"); } //Pick up in store? if (_shippingSettings.AllowPickUpInStore) { if (model.PickUpInStore) { //customer decided to pick up in store //no shipping address selected _workContext.CurrentCustomer.ShippingAddress = null; _customerService.UpdateCustomer(_workContext.CurrentCustomer); //set value indicating that "pick up in store" option has been chosen _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedPickUpInStore, true, _storeContext.CurrentStore.Id); //save "pick up in store" shipping method var pickUpInStoreShippingOption = new ShippingOption { Name = _localizationService.GetResource("Checkout.PickUpInStore.MethodName"), Rate = _shippingSettings.PickUpInStoreFee, Description = null, ShippingRateComputationMethodSystemName = null }; _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, pickUpInStoreShippingOption, _storeContext.CurrentStore.Id); //load next step return RedirectToRoute("CheckoutShippingMethod"); } //set value indicating that "pick up in store" option has not been chosen _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedPickUpInStore, false, _storeContext.CurrentStore.Id); } //custom address attributes var customAttributes = form.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService); var customAttributeWarnings = _addressAttributeParser.GetAttributeWarnings(customAttributes); foreach (var error in customAttributeWarnings) { ModelState.AddModelError("", error); } if (ModelState.IsValid) { //try to find an address with the same values (don't duplicate records) var address = _workContext.CurrentCustomer.Addresses.ToList().FindAddress( model.NewAddress.FirstName, model.NewAddress.LastName, model.NewAddress.PhoneNumber, model.NewAddress.Email, model.NewAddress.FaxNumber, model.NewAddress.Company, model.NewAddress.Address1, model.NewAddress.Address2, model.NewAddress.City, model.NewAddress.StateProvinceId, model.NewAddress.ZipPostalCode, model.NewAddress.CountryId, customAttributes); if (address == null) { address = model.NewAddress.ToEntity(); address.CustomAttributes = customAttributes; address.CreatedOnUtc = DateTime.UtcNow; //some validation if (address.CountryId == 0) address.CountryId = null; if (address.StateProvinceId == 0) address.StateProvinceId = null; _workContext.CurrentCustomer.Addresses.Add(address); } _workContext.CurrentCustomer.ShippingAddress = address; _customerService.UpdateCustomer(_workContext.CurrentCustomer); return RedirectToRoute("CheckoutShippingMethod"); } //If we got this far, something failed, redisplay form model = PrepareShippingAddressModel(selectedCountryId: model.NewAddress.CountryId); return View(model); }
public ActionResult NewShippingAddress(CheckoutShippingAddressModel model, FormCollection form) { //validation var cart = _workContext.CurrentCustomer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id) .ToList(); if (!cart.Any()) return RedirectToRoute("ShoppingCart"); if (_orderSettings.OnePageCheckoutEnabled) return RedirectToRoute("CheckoutOnePage"); if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed) return new HttpUnauthorizedResult(); if (!cart.RequiresShipping()) { _workContext.CurrentCustomer.ShippingAddress = null; _customerService.UpdateCustomer(_workContext.CurrentCustomer); return RedirectToRoute("CheckoutShippingMethod"); } //pickup point if (_shippingSettings.AllowPickUpInStore) { if (model.PickUpInStore) { //no shipping address selected _workContext.CurrentCustomer.ShippingAddress = null; _customerService.UpdateCustomer(_workContext.CurrentCustomer); var pickupPoint = form["pickup-points-id"].Split(new[] { "___" }, StringSplitOptions.None); var pickupPoints = _shippingService .GetPickupPoints(_workContext.CurrentCustomer.BillingAddress, pickupPoint[1], _storeContext.CurrentStore.Id).PickupPoints.ToList(); var selectedPoint = pickupPoints.FirstOrDefault(x => x.Id.Equals(pickupPoint[0])); if (selectedPoint == null) return RedirectToRoute("CheckoutShippingAddress"); var pickUpInStoreShippingOption = new ShippingOption { Name = string.Format(_localizationService.GetResource("Checkout.PickupPoints.Name"), selectedPoint.Name), Rate = selectedPoint.PickupFee, Description = selectedPoint.Description, ShippingRateComputationMethodSystemName = selectedPoint.ProviderSystemName }; _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, pickUpInStoreShippingOption, _storeContext.CurrentStore.Id); _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedPickupPoint, selectedPoint, _storeContext.CurrentStore.Id); return RedirectToRoute("CheckoutPaymentMethod"); } //set value indicating that "pick up in store" option has not been chosen _genericAttributeService.SaveAttribute<PickupPoint>(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedPickupPoint, null, _storeContext.CurrentStore.Id); } //custom address attributes var customAttributes = form.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService); var customAttributeWarnings = _addressAttributeParser.GetAttributeWarnings(customAttributes); foreach (var error in customAttributeWarnings) { ModelState.AddModelError("", error); } if (ModelState.IsValid) { //try to find an address with the same values (don't duplicate records) var address = _workContext.CurrentCustomer.Addresses.ToList().FindAddress( model.NewAddress.FirstName, model.NewAddress.LastName, model.NewAddress.PhoneNumber, model.NewAddress.Email, model.NewAddress.FaxNumber, model.NewAddress.Company, model.NewAddress.Address1, model.NewAddress.Address2, model.NewAddress.City, model.NewAddress.StateProvinceId, model.NewAddress.ZipPostalCode, model.NewAddress.CountryId, customAttributes); if (address == null) { address = model.NewAddress.ToEntity(); address.CustomAttributes = customAttributes; address.CreatedOnUtc = DateTime.UtcNow; //some validation if (address.CountryId == 0) address.CountryId = null; if (address.StateProvinceId == 0) address.StateProvinceId = null; _workContext.CurrentCustomer.Addresses.Add(address); } _workContext.CurrentCustomer.ShippingAddress = address; _customerService.UpdateCustomer(_workContext.CurrentCustomer); return RedirectToRoute("CheckoutShippingMethod"); } //If we got this far, something failed, redisplay form model = PrepareShippingAddressModel( selectedCountryId: model.NewAddress.CountryId, overrideAttributesXml: customAttributes); return View(model); }
private List<ShippingOption> ParseResponse(string response) { var result = new List<ShippingOption>(); string[] lines = response.Split('\n'); string parcelLine = lines.First(x => x.StartsWith(PARCEL_NAME)); string emsLine = lines.First(x => x.StartsWith(EMS_NAME)); if (String.IsNullOrEmpty(parcelLine) && String.IsNullOrEmpty(emsLine)) { throw new Exception("Ошибка при расчете стоимости доставки"); } string[] parcelVals = parcelLine.Split(' '); string[] emsVals = emsLine.Split(' '); if (parcelVals.Length != 3 || emsVals.Length != 3) { throw new Exception("Ошибка при расчете стоимости доставки"); } if (parcelVals[1].Contains('.')) { int i = parcelVals[1].IndexOf('.'); parcelVals[1] = parcelVals[1].Substring(0, i); }; if (emsVals[1].Contains('.')) { int i = emsVals[1].IndexOf('.'); emsVals[1] = emsVals[1].Substring(0, i); }; var parcelOption = new ShippingOption() { Name = RUSSIAN_POST, Rate = Convert.ToDecimal(parcelVals[1]), Description = String.Format(RP_DESCR, parcelVals[2]) }; var emsOption = new ShippingOption() { Name = EMS_NAME, Rate = Convert.ToDecimal(emsVals[1]), Description = String.Format(EMS_DESCR, emsVals[2]) }; result.Add(parcelOption); result.Add(emsOption); return result; }
private ShippingOption RequestShippingOption(string zipPostalCodeFrom, string zipPostalCodeTo, string countryCode, string serviceType, int weight, int length, int width, int height, int quantity) { var shippingOption = new ShippingOption(); var sb = new StringBuilder(); sb.AppendFormat(GetGatewayUrl()); sb.AppendFormat("?Pickup_Postcode={0}&", zipPostalCodeFrom); sb.AppendFormat("Destination_Postcode={0}&", zipPostalCodeTo); sb.AppendFormat("Country={0}&", countryCode); sb.AppendFormat("Service_Type={0}&", serviceType); sb.AppendFormat("Weight={0}&", weight); sb.AppendFormat("Length={0}&", length); sb.AppendFormat("Width={0}&", width); sb.AppendFormat("Height={0}&", height); sb.AppendFormat("Quantity={0}", quantity); var request = WebRequest.Create(sb.ToString()) as HttpWebRequest; request.Method = "GET"; WebResponse response = request.GetResponse(); string rspContent; using (var reader = new StreamReader(response.GetResponseStream())) { rspContent = reader.ReadToEnd(); } string[] tmp = rspContent.Split(new [] { '\n' }, 3); if (tmp.Length != 3) { throw new NopException("Response is not valid."); } var rspParams = new NameValueCollection(); foreach (string s in tmp) { string[] tmp2 = s.Split(new [] { '=' }); if (tmp2.Length != 2) { throw new NopException("Response is not valid."); } rspParams.Add(tmp2[0].Trim(), tmp2[1].Trim()); } string errMsg = rspParams["err_msg"]; if (!errMsg.ToUpperInvariant().StartsWith("OK")) { throw new NopException(errMsg); } var serviceName = GetServiceNameByType(serviceType); if (serviceName != null && !serviceName.StartsWith("Australia Post.", StringComparison.InvariantCultureIgnoreCase)) serviceName = string.Format("Australia Post. {0}", serviceName); shippingOption.Name = serviceName; if (!_australiaPostSettings.HideDeliveryInformation) { shippingOption.Description = String.Format("{0} Days", rspParams["days"]); } shippingOption.Rate = Decimal.Parse(rspParams["charge"]); return shippingOption; }
/// <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("No shipment items"); return response; } if (getShippingOptionRequest.ShippingAddress == null) { response.AddError("Shipping address is not set"); return response; } var storeId = _storeContext.CurrentStore.Id; int countryId = getShippingOptionRequest.ShippingAddress.CountryId.HasValue ? getShippingOptionRequest.ShippingAddress.CountryId.Value : 0; int stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId.HasValue ? getShippingOptionRequest.ShippingAddress.StateProvinceId.Value : 0; string zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode; decimal subTotal = decimal.Zero; foreach (var shoppingCartItem in getShippingOptionRequest.Items) { if (shoppingCartItem.IsFreeShipping || !shoppingCartItem.IsShipEnabled) continue; subTotal += _priceCalculationService.GetSubTotal(shoppingCartItem, true); } decimal weight = _shippingService.GetTotalWeight(getShippingOptionRequest.Items); var shippingMethods = _shippingService.GetAllShippingMethods(countryId); foreach (var shippingMethod in shippingMethods) { decimal? rate = GetRate(subTotal, weight, shippingMethod.Id, storeId, 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; }
public ActionResult OpcSaveShipping(FormCollection form) { try { //validation var cart = _workContext.CurrentCustomer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id) .ToList(); if (cart.Count == 0) throw new Exception("Your cart is empty"); if (!_orderSettings.OnePageCheckoutEnabled) throw new Exception("One page checkout is disabled"); if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)) throw new Exception("Anonymous checkout is not allowed"); if (!cart.RequiresShipping()) throw new Exception("Shipping is not required"); //Pick up in store? if (_shippingSettings.AllowPickUpInStore) { var model = new CheckoutShippingAddressModel(); TryUpdateModel(model); if (model.PickUpInStore) { //customer decided to pick up in store //no shipping address selected _workContext.CurrentCustomer.ShippingAddress = null; _customerService.UpdateCustomer(_workContext.CurrentCustomer); //set value indicating that "pick up in store" option has been chosen _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedPickUpInStore, true, _storeContext.CurrentStore.Id); //save "pick up in store" shipping method var pickUpInStoreShippingOption = new ShippingOption { Name = _localizationService.GetResource("Checkout.PickUpInStore.MethodName"), Rate = _shippingSettings.PickUpInStoreFee, Description = null, ShippingRateComputationMethodSystemName = null }; _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, pickUpInStoreShippingOption, _storeContext.CurrentStore.Id); //load next step return OpcLoadStepAfterShippingMethod(cart); } //set value indicating that "pick up in store" option has not been chosen _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedPickUpInStore, false, _storeContext.CurrentStore.Id); } int shippingAddressId; int.TryParse(form["shipping_address_id"], out shippingAddressId); if (shippingAddressId > 0) { //existing address var address = _workContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == shippingAddressId); if (address == null) throw new Exception("Address can't be loaded"); _workContext.CurrentCustomer.ShippingAddress = address; _customerService.UpdateCustomer(_workContext.CurrentCustomer); } else { //new address var model = new CheckoutShippingAddressModel(); TryUpdateModel(model.NewAddress, "ShippingNewAddress"); //custom address attributes var customAttributes = form.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService); var customAttributeWarnings = _addressAttributeParser.GetAttributeWarnings(customAttributes); foreach (var error in customAttributeWarnings) { ModelState.AddModelError("", error); } //validate model TryValidateModel(model.NewAddress); if (!ModelState.IsValid) { //model is not valid. redisplay the form with errors var shippingAddressModel = PrepareShippingAddressModel(selectedCountryId: model.NewAddress.CountryId); shippingAddressModel.NewAddressPreselected = true; return Json(new { update_section = new UpdateSectionJsonModel { name = "shipping", html = this.RenderPartialViewToString("OpcShippingAddress", shippingAddressModel) } }); } //try to find an address with the same values (don't duplicate records) var address = _workContext.CurrentCustomer.Addresses.ToList().FindAddress( model.NewAddress.FirstName, model.NewAddress.LastName, model.NewAddress.PhoneNumber, model.NewAddress.Email, model.NewAddress.FaxNumber, model.NewAddress.Company, model.NewAddress.Address1, model.NewAddress.Address2, model.NewAddress.City, model.NewAddress.StateProvinceId, model.NewAddress.ZipPostalCode, model.NewAddress.CountryId, customAttributes); if (address == null) { address = model.NewAddress.ToEntity(); address.CustomAttributes = customAttributes; address.CreatedOnUtc = DateTime.UtcNow; //little hack here (TODO: find a better solution) //EF does not load navigation properties for newly created entities (such as this "Address"). //we have to load them manually //otherwise, "Country" property of "Address" entity will be null in shipping rate computation methods if (address.CountryId.HasValue) address.Country = _countryService.GetCountryById(address.CountryId.Value); if (address.StateProvinceId.HasValue) address.StateProvince = _stateProvinceService.GetStateProvinceById(address.StateProvinceId.Value); //other null validations if (address.CountryId == 0) address.CountryId = null; if (address.StateProvinceId == 0) address.StateProvinceId = null; _workContext.CurrentCustomer.Addresses.Add(address); } _workContext.CurrentCustomer.ShippingAddress = address; _customerService.UpdateCustomer(_workContext.CurrentCustomer); } var shippingMethodModel = PrepareShippingMethodModel(cart, _workContext.CurrentCustomer.ShippingAddress); if (_shippingSettings.BypassShippingMethodSelectionIfOnlyOne && shippingMethodModel.ShippingMethods.Count == 1) { //if we have only one shipping method, then a customer doesn't have to choose a shipping method _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, shippingMethodModel.ShippingMethods.First().ShippingOption, _storeContext.CurrentStore.Id); //load next step return OpcLoadStepAfterShippingMethod(cart); } return Json(new { update_section = new UpdateSectionJsonModel { name = "shipping-method", html = this.RenderPartialViewToString("OpcShippingMethods", shippingMethodModel) }, goto_section = "shipping_method" }); } catch (Exception exc) { _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); return Json(new { error = 1, message = exc.Message }); } }
private List<ShippingOption> ParseResponse(string response, bool isDomestic, ref string error) { var shippingOptions = new List<ShippingOption>(); string postageStr = isDomestic ? "Postage" : "Service"; string mailServiceStr = isDomestic ? "MailService" : "SvcDescription"; string rateStr = isDomestic ? "Rate" : "Postage"; string classStr = isDomestic ? "CLASSID" : "ID"; string carrierServicesOffered = isDomestic ? _uspsSettings.CarrierServicesOfferedDomestic : _uspsSettings.CarrierServicesOfferedInternational; using (var sr = new StringReader(response)) using (var tr = new XmlTextReader(sr)) { do { tr.Read(); if ((tr.Name == "Error") && (tr.NodeType == XmlNodeType.Element)) { string errorText = ""; while (tr.Read()) { if ((tr.Name == "Description") && (tr.NodeType == XmlNodeType.Element)) errorText += "Error Desc: " + tr.ReadString(); if ((tr.Name == "HelpContext") && (tr.NodeType == XmlNodeType.Element)) errorText += "USPS Help Context: " + tr.ReadString() + ". "; } error = "USPS Error returned: " + errorText; } if ((tr.Name == postageStr) && (tr.NodeType == XmlNodeType.Element)) { string serviceId = string.Empty; // Find the ID for the service if (tr.HasAttributes) { for (int i = 0; i < tr.AttributeCount; i++) { tr.MoveToAttribute(i); if (tr.Name.Equals(classStr)) { // Add delimiters [] so that single digit IDs aren't found in mutli-digit IDs serviceId = String.Format("[{0}]", tr.Value); break; } } } // Go to the next rate if the service ID is not in the list of services to offer if (!String.IsNullOrEmpty(serviceId) && !String.IsNullOrEmpty(carrierServicesOffered) && !carrierServicesOffered.Contains(serviceId)) { continue; } string serviceCode = string.Empty; string postalRate = string.Empty; do { tr.Read(); if ((tr.Name == mailServiceStr) && (tr.NodeType == XmlNodeType.Element)) { serviceCode = tr.ReadString(); tr.ReadEndElement(); if ((tr.Name == mailServiceStr) && (tr.NodeType == XmlNodeType.EndElement)) break; } if ((tr.Name == rateStr) && (tr.NodeType == XmlNodeType.Element)) { postalRate = tr.ReadString(); tr.ReadEndElement(); if ((tr.Name == rateStr) && (tr.NodeType == XmlNodeType.EndElement)) break; } } while (!((tr.Name == postageStr) && (tr.NodeType == XmlNodeType.EndElement))); //USPS issue fixed char tm = (char)174; serviceCode = serviceCode.Replace("<sup>&reg;</sup>", tm.ToString()); ShippingOption shippingOption = shippingOptions.Find((s) => s.Name == serviceCode); if (shippingOption == null) { shippingOption = new ShippingOption(); shippingOption.Name = serviceCode; shippingOptions.Add(shippingOption); } shippingOption.Rate += Convert.ToDecimal(postalRate, new CultureInfo("en-US")); } } while (!tr.EOF); } return shippingOptions; }
public ActionResult NewShippingAddress(CheckoutShippingAddressModel model, FormCollection form) { bool errors = false; string errorMessage = ""; //validation var cart = _workContext.CurrentCustomer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id) .ToList(); if (cart.Count == 0) return RedirectToRoute("ShoppingCart"); if (_orderSettings.OnePageCheckoutEnabled) return RedirectToRoute("CheckoutOnePage"); if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)) return new HttpUnauthorizedResult(); if (!cart.RequiresShipping()) { _workContext.CurrentCustomer.ShippingAddress = null; _customerService.UpdateCustomer(_workContext.CurrentCustomer); //return RedirectToRoute("CheckoutShippingMethod"); return RedirectToRoute("CheckoutConfirmAddress"); } //Pick up in store? if (_shippingSettings.AllowPickUpInStore) { if (model.PickUpInStore) { //customer decided to pick up in store //no shipping address selected _workContext.CurrentCustomer.ShippingAddress = null; _customerService.UpdateCustomer(_workContext.CurrentCustomer); //set value indicating that "pick up in store" option has been chosen _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedPickUpInStore, true, _storeContext.CurrentStore.Id); //save "pick up in store" shipping method var pickUpInStoreShippingOption = new ShippingOption { Name = _localizationService.GetResource("Checkout.PickUpInStore.MethodName"), Rate = _shippingSettings.PickUpInStoreFee, Description = null, ShippingRateComputationMethodSystemName = null }; _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, pickUpInStoreShippingOption, _storeContext.CurrentStore.Id); //load next step //return RedirectToRoute("CheckoutShippingMethod"); return RedirectToRoute("CheckoutConfirmAddress"); } //set value indicating that "pick up in store" option has not been chosen _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedPickUpInStore, false, _storeContext.CurrentStore.Id); } //custom address attributes var customAttributes = form.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService); var customAttributeWarnings = _addressAttributeParser.GetAttributeWarnings(customAttributes); foreach (var error in customAttributeWarnings) { ModelState.AddModelError("", error); } if (ModelState.IsValid) { if (model.NewAddress.Id > 0) { var address = _workContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == model.NewAddress.Id); if (address != null) { var products = _workContext.CurrentCustomer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); if (products != null) { //foreach (var p in products) { for (int i = 0; i < products.Count; i++) { var p = products[i]; if (p != null) { var city = _zipcodeService.GetZipcodeByName(model.NewAddress.ZipPostalCode.Trim()); if (city != null) { ProductCities productcity = null; foreach (var item in city) { productcity = _productCitiesService.GetProductsCitiesByProductId(p.ProductId).Where(x => x.CityID == item.CityID).FirstOrDefault(); if (productcity != null) break; } if (productcity == null) { errors = true; string msg = p.Product.Name + " is not available on your zip code."; errorMessage = msg; TempData["message"] = errorMessage; return RedirectToRoute("CheckoutShippingAddress"); } } else { errors = true; string msg = "Our services are not available on your zip code."; errorMessage = msg; TempData["message"] = errorMessage; return RedirectToRoute("CheckoutShippingAddress"); } } } } if (errors == false) { address = model.NewAddress.ToEntity(address); address.CustomAttributes = customAttributes; _addressService.UpdateAddress(address); _workContext.CurrentCustomer.ShippingAddress = address; _customerService.UpdateCustomer(_workContext.CurrentCustomer); return RedirectToRoute("CheckoutConfirmAddress"); } } } else { //try to find an address with the same values (don't duplicate records) var address = _workContext.CurrentCustomer.Addresses.ToList().FindAddress( model.NewAddress.FirstName, model.NewAddress.LastName, model.NewAddress.PhoneNumber, model.NewAddress.Email, model.NewAddress.FaxNumber, model.NewAddress.Company, model.NewAddress.Address1, model.NewAddress.Address2, model.NewAddress.City, model.NewAddress.StateProvinceId, model.NewAddress.ZipPostalCode, model.NewAddress.CountryId, customAttributes); if (address == null) { var products = _workContext.CurrentCustomer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); if (products != null) { //foreach (var p in products) { for (int i = 0; i < products.Count; i++) { var p = products[i]; if (p != null) { var city = _zipcodeService.GetZipcodeByName(model.NewAddress.ZipPostalCode.Trim()); if (city != null) { ProductCities productcity = null; foreach (var item in city) { productcity = _productCitiesService.GetProductsCitiesByProductId(p.ProductId).Where(x => x.CityID == item.CityID).FirstOrDefault(); if (productcity != null) break; } if (productcity == null) { errors = true; string msg = p.Product.Name + " is not available on your zip code."; errorMessage = msg; TempData["message"] = errorMessage; return RedirectToRoute("CheckoutShippingAddress"); } } else { errors = true; string msg = "Our services are not available on your zip code."; errorMessage = msg; TempData["message"] = errorMessage; return RedirectToRoute("CheckoutShippingAddress"); } } } } if (errors == false) { address = model.NewAddress.ToEntity(); address.CustomAttributes = customAttributes; address.CreatedOnUtc = DateTime.UtcNow; //some validation if (address.CountryId == 0) address.CountryId = null; if (address.StateProvinceId == 0) address.StateProvinceId = null; _workContext.CurrentCustomer.Addresses.Add(address); } } else { var products = _workContext.CurrentCustomer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); if (products != null) { //foreach (var p in products) { for (int i = 0; i < products.Count; i++) { var p = products[i]; if (p != null) { var city = _zipcodeService.GetZipcodeByName(model.NewAddress.ZipPostalCode.Trim()); if (city != null) { ProductCities productcity = null; foreach (var item in city) { productcity = _productCitiesService.GetProductsCitiesByProductId(p.ProductId).Where(x => x.CityID == item.CityID).FirstOrDefault(); if (productcity != null) break; } if (productcity == null) { errors = true; string msg = p.Product.Name + " is not available on your zip code."; errorMessage = msg; TempData["message"] = errorMessage; return RedirectToRoute("CheckoutShippingAddress"); } } else { errors = true; string msg = "Our services are not available on your zip code."; errorMessage = msg; TempData["message"] = errorMessage; return RedirectToRoute("CheckoutShippingAddress"); } } } } if (errors == false) { _workContext.CurrentCustomer.ShippingAddress = address; _customerService.UpdateCustomer(_workContext.CurrentCustomer); } //return RedirectToRoute("CheckoutShippingMethod"); return RedirectToRoute("CheckoutConfirmAddress"); } } } //If we got this far, something failed, redisplay form model = PrepareShippingAddressModel(selectedCountryId: model.NewAddress.CountryId); return View(model); }