本文整理汇总了C#中Nop.Core.Domain.Shipping.ShippingOption类的典型用法代码示例。如果您正苦于以下问题:C# ShippingOption类的具体用法?C# ShippingOption怎么用?C# ShippingOption使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ShippingOption类属于Nop.Core.Domain.Shipping命名空间,在下文中一共展示了ShippingOption类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ParseShippingOption
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;
}
示例2: GetShippingOptions
/// <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;
}
示例3: Can_convert_shippingOption_to_string_and_back
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");
}
示例4: ProcessNewOrderNotification
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);
//.........这里部分代码省略.........
示例5: RequestShippingOption
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;
}
示例6: ParseResponse
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;
}
示例7: GetShippingOptions
/// <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;
}
示例8: ParseResponse
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;
}
示例9: NewShippingAddress
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);
}
示例10: GetShippingOptions
/// <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;
}
}
示例11: NewShippingAddress
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);
}
示例12: ParseResponse
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;
}
示例13: RequestShippingOption
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;
}
示例14: GetShippingOptions
/// <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;
}
示例15: OpcSaveShipping
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)
}
//.........这里部分代码省略.........