public void UpdateOrderBillingInfo(int orderId, string firstName, string lastName, string phone, string email, string fax, string company, string address1, string address2, string city, string stateProvinceAbbreviation, string countryThreeLetterIsoCode, string postalCode, string usernameOrEmail, string userPassword) { CheckAccess(usernameOrEmail, userPassword); if (!_permissionSettings.Authorize(StandardPermissionProvider.ManageOrders)) { throw new ApplicationException("Not allowed to manage orders"); } try { var order = _orderService.GetOrderById(orderId); var a = order.BillingAddress; a.FirstName = firstName; a.LastName = lastName; a.PhoneNumber = phone; a.Email = email; a.FaxNumber = fax; a.Company = company; a.Address1 = address1; a.Address2 = address2; a.City = city; StateProvince stateProvince = null; if (!String.IsNullOrEmpty(stateProvinceAbbreviation)) { stateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(stateProvinceAbbreviation); } a.StateProvince = stateProvince; Country country = null; if (!String.IsNullOrEmpty(countryThreeLetterIsoCode)) { country = _countryService.GetCountryByThreeLetterIsoCode(countryThreeLetterIsoCode); } a.Country = country; a.ZipPostalCode = postalCode; _addressService.UpdateAddress(a); } catch (Exception ex) { throw new ApplicationException(ex.Message); } }
/// <summary> /// Install the plugin /// </summary> public override void Install() { //database objects _objectContext.Install(); //sample pickup point var country = _countryService.GetCountryByThreeLetterIsoCode("USA"); var state = _stateProvinceService.GetStateProvinceByAbbreviation("NY", country?.Id); var address = new Address { Address1 = "21 West 52nd Street", City = "New York", CountryId = country?.Id, StateProvinceId = state?.Id, ZipPostalCode = "10021", CreatedOnUtc = DateTime.UtcNow }; _addressService.InsertAddress(address); var pickupPoint = new StorePickupPoint { Name = "New York store", AddressId = address.Id, OpeningHours = "10.00 - 19.00", PickupFee = 1.99m }; _storePickupPointService.InsertStorePickupPoint(pickupPoint); //locales _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.AddNew", "Add a new pickup point"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Description", "Description"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Description.Hint", "Specify a description of the pickup point."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.DisplayOrder", "Display order"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.DisplayOrder.Hint", "Specify the pickup point display order."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Latitude", "Latitude"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Latitude.Hint", "Specify a latitude (DD.dddddddd°)."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Latitude.InvalidPrecision", "Precision should be less then 8"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Latitude.InvalidRange", "Latitude should be in range -90 to 90"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Latitude.IsNullWhenLongitudeHasValue", "Latitude and Longitude should be specify together"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Longitude", "Longitude"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Longitude.Hint", "Specify a longitude (DD.dddddddd°)."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Longitude.InvalidPrecision", "Precision should be less then 8"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Longitude.InvalidRange", "Longitude should be in range -180 to 180"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Longitude.IsNullWhenLatitudeHasValue", "Latitude and Longitude should be specify together"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Name", "Name"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Name.Hint", "Specify a name of the pickup point."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.OpeningHours", "Opening hours"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.OpeningHours.Hint", "Specify opening hours of the pickup point (Monday - Friday: 09:00 - 19:00 for example)."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.PickupFee", "Pickup fee"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.PickupFee.Hint", "Specify a fee for the shipping to the pickup point."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Store", "Store"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Store.Hint", "A store name for which this pickup point will be available."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.NoPickupPoints", "No pickup points are available"); base.Install(); }
public static string ToFormatedAddress(this Address amazonAddress, ICountryService countryService, IStateProvinceService stateProvinceService) { var sb = new StringBuilder(); try { var city = (amazonAddress.IsSetCity() ? amazonAddress.City : null); var zip = (amazonAddress.IsSetPostalCode() ? amazonAddress.PostalCode : null); sb.AppendLine(""); if (amazonAddress.Name.HasValue()) sb.AppendLine(amazonAddress.Name); if (amazonAddress.AddressLine1.HasValue()) sb.AppendLine(amazonAddress.AddressLine1); if (amazonAddress.AddressLine2.HasValue()) sb.AppendLine(amazonAddress.AddressLine2); if (amazonAddress.AddressLine3.HasValue()) sb.AppendLine(amazonAddress.AddressLine3); sb.AppendLine(zip.Grow(city, " ")); if (amazonAddress.IsSetStateOrRegion()) { var stateProvince = stateProvinceService.GetStateProvinceByAbbreviation(amazonAddress.StateOrRegion); if (stateProvince == null) sb.AppendLine(amazonAddress.StateOrRegion); else sb.AppendLine("{0} {1}".FormatWith(amazonAddress.StateOrRegion, stateProvince.GetLocalized(x => x.Name))); } if (amazonAddress.IsSetCountryCode()) { var country = countryService.GetCountryByTwoOrThreeLetterIsoCode(amazonAddress.CountryCode); if (country == null) sb.AppendLine(amazonAddress.CountryCode); else sb.AppendLine("{0} {1}".FormatWith(amazonAddress.CountryCode, country.GetLocalized(x => x.Name))); } if (amazonAddress.Phone.HasValue()) { sb.AppendLine(amazonAddress.Phone); } } catch (Exception exc) { exc.Dump(); } return sb.ToString(); }
/// <summary> /// Install the plugin /// </summary> public override void Install() { //database objects _objectContext.Install(); //sample pickup point var country = _countryService.GetCountryByThreeLetterIsoCode("USA"); var state = _stateProvinceService.GetStateProvinceByAbbreviation("NY"); var address = new Address { Address1 = "21 West 52nd Street", City = "New York", CountryId = country != null ? (int?)country.Id : null, StateProvinceId = state != null ? (int?)state.Id : null, ZipPostalCode = "10021", CreatedOnUtc = DateTime.UtcNow }; _addressService.InsertAddress(address); var pickupPoint = new StorePickupPoint { Name = "New York store", AddressId = address.Id, OpeningHours = "10.00 - 19.00", PickupFee = 1.99m }; _storePickupPointService.InsertStorePickupPoint(pickupPoint); //locales this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.AddNew", "Add a new pickup point"); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Description", "Description"); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Description.Hint", "Specify a description of the pickup point."); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Name", "Name"); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Name.Hint", "Specify a name of the pickup point."); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.OpeningHours", "Opening hours"); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.OpeningHours.Hint", "Specify an openning hours of the pickup point (Monday - Friday: 09:00 - 19:00 for example)."); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.PickupFee", "Pickup fee"); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.PickupFee.Hint", "Specify a fee for the shipping to the pickup point."); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Store", "Store"); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.Fields.Store.Hint", "A store name for which this pickup point will be available."); this.AddOrUpdatePluginLocaleResource("Plugins.Pickup.PickupInStore.NoPickupPoints", "No pickup points are available"); base.Install(); }
/// <summary> /// Gets or sets a pickup point address for tax calculation /// </summary> /// <param name="pickupPoint">Pickup point</param> /// <returns>Address</returns> protected virtual Address LoadPickupPointTaxAddress(PickupPoint pickupPoint) { if (pickupPoint == null) throw new ArgumentNullException(nameof(pickupPoint)); var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id); return new Address { CountryId = country?.Id ?? 0, StateProvinceId = state?.Id ?? 0, County = pickupPoint.County, City = pickupPoint.City, Address1 = pickupPoint.Address, ZipPostalCode = pickupPoint.ZipPostalCode }; }
/// <summary> /// Prepare tax details by Avalara tax service /// </summary> /// <param name="cart">Shopping cart</param> private void PrepareTaxDetails(IList <ShoppingCartItem> cart) { //ensure that Avalara tax provider is active var taxProvider = _taxPluginManager .LoadPluginBySystemName(AvalaraTaxDefaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id) as AvalaraTaxProvider; if (!_taxPluginManager.IsPluginActive(taxProvider)) { return; } //create dummy order for the tax request var order = new Order { Customer = _workContext.CurrentCustomer }; //addresses order.BillingAddress = _workContext.CurrentCustomer.BillingAddress; order.ShippingAddress = _workContext.CurrentCustomer.ShippingAddress; if (_shippingSettings.AllowPickupInStore) { var pickupPoint = _genericAttributeService.GetAttribute <PickupPoint>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedPickupPointAttribute, _storeContext.CurrentStore.Id); if (pickupPoint != null) { var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode); order.PickupAddress = new Address { Address1 = pickupPoint.Address, City = pickupPoint.City, Country = country, StateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id), ZipPostalCode = pickupPoint.ZipPostalCode, CreatedOnUtc = DateTime.UtcNow, }; } } //checkout attributes order.CheckoutAttributesXml = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer, NopCustomerDefaults.CheckoutAttributes, _storeContext.CurrentStore.Id); //shipping method var shippingRateComputationMethods = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id); order.OrderShippingExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(cart, false, shippingRateComputationMethods) ?? 0; order.ShippingMethod = _genericAttributeService.GetAttribute <ShippingOption>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedShippingOptionAttribute, _storeContext.CurrentStore.Id)?.Name; //payment method var paymentMethod = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer, NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id); var paymentFee = _paymentService.GetAdditionalHandlingFee(cart, paymentMethod); order.PaymentMethodAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentFee, false, _workContext.CurrentCustomer); order.PaymentMethodSystemName = paymentMethod; //add discount amount _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false, out var orderSubTotalDiscountExclTax, out _, out _, out _); order.OrderSubTotalDiscountExclTax = orderSubTotalDiscountExclTax; //create dummy order items foreach (var cartItem in cart) { var orderItem = new OrderItem { AttributesXml = cartItem.AttributesXml, Product = cartItem.Product, Quantity = cartItem.Quantity }; var itemSubtotal = _priceCalculationService.GetSubTotal(cartItem, true, out _, out _, out _); orderItem.PriceExclTax = _taxService.GetProductPrice(cartItem.Product, itemSubtotal, false, _workContext.CurrentCustomer, out _); order.OrderItems.Add(orderItem); } //get tax details var taxTransaction = taxProvider.CreateOrderTaxTransaction(order, false); if (taxTransaction == null) { return; } //and save it for the further usage var taxDetails = new TaxDetails { TaxTotal = taxTransaction.totalTax }; foreach (var item in taxTransaction.summary) { if (!item.rate.HasValue || !item.tax.HasValue) { continue; } var taxRate = item.rate.Value * 100; var taxValue = item.tax.Value; if (!taxDetails.TaxRates.ContainsKey(taxRate)) { taxDetails.TaxRates.Add(taxRate, taxValue); } else { taxDetails.TaxRates[taxRate] = taxDetails.TaxRates[taxRate] + taxValue; } } _httpContextAccessor.HttpContext.Session.Set(AvalaraTaxDefaults.TaxDetailsSessionValue, taxDetails); }
public void ImportProvincesFromXlsx(Stream stream, int countryId) { using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) { throw new NopException("No worksheet found"); } //the columns var properties = GetPropertiesByExcelCells <StateProvince>(worksheet); var manager = new PropertyManager <StateProvince>(properties); var iRow = 2; var setSeName = properties.Any(p => p.PropertyName == "SeName"); while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) { break; } manager.ReadFromXlsx(worksheet, iRow); //var seName = string.Empty; string name = ""; string postalCode = ""; string abbreviation = ""; foreach (var property in manager.GetProperties) { switch (property.PropertyName) { case "Name": name = property.StringValue; break; case "PostalCode": postalCode = property.StringValue; break; case "Abbreviation": abbreviation = property.StringValue; break; } } var stateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(abbreviation) ?? new StateProvince { Published = true, CountryId = countryId, Name = name, Abbreviation = abbreviation, Id = 0 }; var isNew = stateProvince.Id == 0; if (isNew) { _stateProvinceService.InsertStateProvince(stateProvince); } else { _stateProvinceService.UpdateStateProvince(stateProvince); } if (stateProvince.Id > 0) { var postalCodes = postalCode.Split(',').ToList(); if (postalCodes != null) { foreach (var postal in postalCodes) { var stateProvinceWB = _stateProvinceWBService.GetByPostalCodeAndProvinceID(postal, stateProvince.Id) ?? new StateProvincePostalCode { Id = 0, StateProvinceID = stateProvince.Id, PostalCode = postal }; if (stateProvinceWB.Id == 0) { _stateProvinceWBService.Insert(stateProvinceWB); } } } } iRow++; } } }
/// <summary> /// Prepare shipping address model /// </summary> /// <param name="selectedCountryId">Selected country identifier</param> /// <param name="prePopulateNewAddressWithCustomerFields">Pre populate new address with customer fields</param> /// <param name="overrideAttributesXml">Override attributes xml</param> /// <returns>Shipping address model</returns> public virtual CheckoutShippingAddressModel PrepareShippingAddressModel(int?selectedCountryId = null, bool prePopulateNewAddressWithCustomerFields = false, string overrideAttributesXml = "") { var model = new CheckoutShippingAddressModel(); //allow pickup in store? model.AllowPickUpInStore = _shippingSettings.AllowPickUpInStore; if (model.AllowPickUpInStore) { model.DisplayPickupPointsOnMap = _shippingSettings.DisplayPickupPointsOnMap; model.GoogleMapsApiKey = _shippingSettings.GoogleMapsApiKey; var pickupPointProviders = _shippingService.LoadActivePickupPointProviders(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id); if (pickupPointProviders.Any()) { var pickupPointsResponse = _shippingService.GetPickupPoints(_workContext.CurrentCustomer.BillingAddress, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id); if (pickupPointsResponse.Success) { model.PickupPoints = pickupPointsResponse.PickupPoints.Select(x => { var country = _countryService.GetCountryByTwoLetterIsoCode(x.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(x.StateAbbreviation); var pickupPointModel = new CheckoutPickupPointModel { Id = x.Id, Name = x.Name, Description = x.Description, ProviderSystemName = x.ProviderSystemName, Address = x.Address, City = x.City, StateName = state != null ? state.Name : string.Empty, CountryName = country != null ? country.Name : string.Empty, ZipPostalCode = x.ZipPostalCode, Latitude = x.Latitude, Longitude = x.Longitude, OpeningHours = x.OpeningHours }; if (x.PickupFee > 0) { var amount = _taxService.GetShippingPrice(x.PickupFee, _workContext.CurrentCustomer); amount = _currencyService.ConvertFromPrimaryStoreCurrency(amount, _workContext.WorkingCurrency); pickupPointModel.PickupFee = _priceFormatter.FormatShippingPrice(amount, true); } return(pickupPointModel); }).ToList(); } else { foreach (var error in pickupPointsResponse.Errors) { model.Warnings.Add(error); } } } //only available pickup points if (!_shippingService.LoadActiveShippingRateComputationMethods(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id).Any()) { if (!pickupPointProviders.Any()) { model.Warnings.Add(_localizationService.GetResource("Checkout.ShippingIsNotAllowed")); model.Warnings.Add(_localizationService.GetResource("Checkout.PickupPoints.NotAvailable")); } model.PickUpInStoreOnly = true; model.PickUpInStore = true; return(model); } } //existing addresses var addresses = _workContext.CurrentCustomer.Addresses .Where(a => a.Country == null || (//published a.Country.Published && //allow shipping a.Country.AllowsShipping && //enabled for the current store _storeMappingService.Authorize(a.Country))) .ToList(); foreach (var address in addresses) { var addressModel = new AddressModel(); _addressModelFactory.PrepareAddressModel(addressModel, address: address, excludeProperties: false, addressSettings: _addressSettings); model.ExistingAddresses.Add(addressModel); } //new address model.NewAddress.CountryId = selectedCountryId; _addressModelFactory.PrepareAddressModel(model.NewAddress, address: null, excludeProperties: false, addressSettings: _addressSettings, loadCountries: () => _countryService.GetAllCountriesForShipping(_workContext.WorkingLanguage.Id), prePopulateWithCustomerFields: prePopulateNewAddressWithCustomerFields, customer: _workContext.CurrentCustomer, overrideAttributesXml: overrideAttributesXml); return(model); }
public static string ToFormatedAddress(this Address amazonAddress, ICountryService countryService, IStateProvinceService stateProvinceService) { var sb = new StringBuilder(); try { var city = (amazonAddress.IsSetCity() ? amazonAddress.City : null); var zip = (amazonAddress.IsSetPostalCode() ? amazonAddress.PostalCode : null); sb.AppendLine(""); if (amazonAddress.Name.HasValue()) { sb.AppendLine(amazonAddress.Name); } if (amazonAddress.AddressLine1.HasValue()) { sb.AppendLine(amazonAddress.AddressLine1); } if (amazonAddress.AddressLine2.HasValue()) { sb.AppendLine(amazonAddress.AddressLine2); } if (amazonAddress.AddressLine3.HasValue()) { sb.AppendLine(amazonAddress.AddressLine3); } sb.AppendLine(zip.Grow(city, " ")); if (amazonAddress.IsSetStateOrRegion()) { var stateProvince = stateProvinceService.GetStateProvinceByAbbreviation(amazonAddress.StateOrRegion); if (stateProvince == null) { sb.AppendLine(amazonAddress.StateOrRegion); } else { sb.AppendLine("{0} {1}".FormatWith(amazonAddress.StateOrRegion, stateProvince.GetLocalized(x => x.Name))); } } if (amazonAddress.IsSetCountryCode()) { var country = countryService.GetCountryByTwoOrThreeLetterIsoCode(amazonAddress.CountryCode); if (country == null) { sb.AppendLine(amazonAddress.CountryCode); } else { sb.AppendLine("{0} {1}".FormatWith(amazonAddress.CountryCode, country.GetLocalized(x => x.Name))); } } if (amazonAddress.Phone.HasValue()) { sb.AppendLine(amazonAddress.Phone); } } catch (Exception exc) { exc.Dump(); } return(sb.ToString()); }
public static void ToAddress(this Address amazonAddress, SmartStore.Core.Domain.Common.Address address, ICountryService countryService, IStateProvinceService stateProvinceService, out bool countryAllowsShipping, out bool countryAllowsBilling) { countryAllowsShipping = countryAllowsBilling = true; if (amazonAddress.IsSetName()) { address.ToFirstAndLastName(amazonAddress.Name); } if (amazonAddress.IsSetAddressLine1()) { address.Address1 = amazonAddress.AddressLine1.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetAddressLine2()) { address.Address2 = amazonAddress.AddressLine2.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetAddressLine3()) { address.Address2 = address.Address2.Grow(amazonAddress.AddressLine3.TrimSafe(), ", ").Truncate(4000); } // normalize if (address.Address1.IsEmpty() && address.Address2.HasValue()) { address.Address1 = address.Address2; address.Address2 = null; } else if (address.Address1.HasValue() && address.Address1 == address.Address2) { address.Address2 = null; } if (amazonAddress.IsSetCity()) { address.City = amazonAddress.City.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetPostalCode()) { address.ZipPostalCode = amazonAddress.PostalCode.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetPhone()) { address.PhoneNumber = amazonAddress.Phone.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetCountryCode()) { var country = countryService.GetCountryByTwoOrThreeLetterIsoCode(amazonAddress.CountryCode); if (country != null) { address.CountryId = country.Id; countryAllowsShipping = country.AllowsShipping; countryAllowsBilling = country.AllowsBilling; } } if (amazonAddress.IsSetStateOrRegion()) { var stateProvince = stateProvinceService.GetStateProvinceByAbbreviation(amazonAddress.StateOrRegion); if (stateProvince != null) address.StateProvinceId = stateProvince.Id; } //amazonAddress.District, amazonAddress.County ?? if (address.CountryId == 0) address.CountryId = null; if (address.StateProvinceId == 0) address.StateProvinceId = null; }
/// <summary> /// Prepares the checkout pickup points model /// </summary> /// <param name="cart">Cart</param> /// <returns>The checkout pickup points model</returns> protected virtual CheckoutPickupPointsModel PrepareCheckoutPickupPointsModel(IList <ShoppingCartItem> cart) { var model = new CheckoutPickupPointsModel() { AllowPickupInStore = _shippingSettings.AllowPickupInStore }; if (model.AllowPickupInStore) { model.DisplayPickupPointsOnMap = _shippingSettings.DisplayPickupPointsOnMap; model.GoogleMapsApiKey = _shippingSettings.GoogleMapsApiKey; var pickupPointProviders = _pickupPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id); if (pickupPointProviders.Any()) { var languageId = _workContext.WorkingLanguage.Id; var pickupPointsResponse = _shippingService.GetPickupPoints(_workContext.CurrentCustomer.BillingAddressId ?? 0, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id); if (pickupPointsResponse.Success) { model.PickupPoints = pickupPointsResponse.PickupPoints.Select(point => { var country = _countryService.GetCountryByTwoLetterIsoCode(point.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(point.StateAbbreviation, country?.Id); var pickupPointModel = new CheckoutPickupPointModel { Id = point.Id, Name = point.Name, Description = point.Description, ProviderSystemName = point.ProviderSystemName, Address = point.Address, City = point.City, County = point.County, StateName = state != null ? _localizationService.GetLocalized(state, x => x.Name, languageId) : string.Empty, CountryName = country != null ? _localizationService.GetLocalized(country, x => x.Name, languageId) : string.Empty, ZipPostalCode = point.ZipPostalCode, Latitude = point.Latitude, Longitude = point.Longitude, OpeningHours = point.OpeningHours }; var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentCustomer, ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id); var amount = _orderTotalCalculationService.IsFreeShipping(cart) ? 0 : point.PickupFee; if (amount > 0) { amount = _taxService.GetShippingPrice(amount, _workContext.CurrentCustomer); amount = _currencyService.ConvertFromPrimaryStoreCurrency(amount, _workContext.WorkingCurrency); pickupPointModel.PickupFee = _priceFormatter.FormatShippingPrice(amount, true); } //adjust rate var shippingTotal = _orderTotalCalculationService.AdjustShippingRate(point.PickupFee, cart, out var _, true); var rateBase = _taxService.GetShippingPrice(shippingTotal, _workContext.CurrentCustomer); var rate = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency); pickupPointModel.PickupFee = _priceFormatter.FormatShippingPrice(rate, true); return(pickupPointModel); }).ToList(); } else { foreach (var error in pickupPointsResponse.Errors) { model.Warnings.Add(error); } } } //only available pickup points var shippingProviders = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id); if (!shippingProviders.Any()) { if (!pickupPointProviders.Any()) { model.Warnings.Add(_localizationService.GetResource("Checkout.ShippingIsNotAllowed")); model.Warnings.Add(_localizationService.GetResource("Checkout.PickupPoints.NotAvailable")); } model.PickupInStoreOnly = true; model.PickupInStore = true; return(model); } } return(model); }
public static void ToAddress(this Address amazonAddress, SmartStore.Core.Domain.Common.Address address, ICountryService countryService, IStateProvinceService stateProvinceService, out bool countryAllowsShipping, out bool countryAllowsBilling) { countryAllowsShipping = countryAllowsBilling = true; if (amazonAddress.IsSetName()) { address.ToFirstAndLastName(amazonAddress.Name); } if (amazonAddress.IsSetAddressLine1()) { address.Address1 = amazonAddress.AddressLine1.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetAddressLine2()) { address.Address2 = amazonAddress.AddressLine2.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetAddressLine3()) { address.Address2 = address.Address2.Grow(amazonAddress.AddressLine3.TrimSafe(), ", ").Truncate(4000); } // normalize if (address.Address1.IsNullOrEmpty() && address.Address2.HasValue()) { address.Address1 = address.Address2; address.Address2 = null; } else if (address.Address1.HasValue() && address.Address1 == address.Address2) { address.Address2 = null; } if (amazonAddress.IsSetCity()) { address.City = amazonAddress.City.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetPostalCode()) { address.ZipPostalCode = amazonAddress.PostalCode.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetPhone()) { address.PhoneNumber = amazonAddress.Phone.TrimSafe().Truncate(4000); } if (amazonAddress.IsSetCountryCode()) { var country = countryService.GetCountryByTwoOrThreeLetterIsoCode(amazonAddress.CountryCode); if (country != null) { address.CountryId = country.Id; countryAllowsShipping = country.AllowsShipping; countryAllowsBilling = country.AllowsBilling; } } if (amazonAddress.IsSetStateOrRegion()) { var stateProvince = stateProvinceService.GetStateProvinceByAbbreviation(amazonAddress.StateOrRegion); if (stateProvince != null) { address.StateProvinceId = stateProvince.Id; } } //amazonAddress.District, amazonAddress.County ?? if (address.CountryId == 0) { address.CountryId = null; } if (address.StateProvinceId == 0) { address.StateProvinceId = null; } }
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.SetBillingAddress(billingAddress); _customerService.UpdateCustomer(customer); _customerService.SaveCustomerAttribute <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.SetShippingAddress(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; _customerService.SaveCustomerAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.LastShippingOption, shippingOption); } } //customer.LastCalculatedTax = decimal.Zero; var paymentInfo = new ProcessPaymentRequest() { PaymentMethodSystemName = "Payments.GoogleCheckout", Customer = customer, 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); } }
public ProcessPaymentRequest SetCheckoutDetails(ProcessPaymentRequest processPaymentRequest, GetExpressCheckoutDetailsResponseDetailsType checkoutDetails) { int customerId = Convert.ToInt32(Services.WorkContext.CurrentCustomer.Id.ToString()); var customer = _customerService.GetCustomerById(customerId); var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(Services.StoreContext.CurrentStore.Id); Services.WorkContext.CurrentCustomer = customer; //var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); var cart = Services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, Services.StoreContext.CurrentStore.Id); // get/update billing address string billingFirstName = checkoutDetails.PayerInfo.PayerName.FirstName; string billingLastName = checkoutDetails.PayerInfo.PayerName.LastName; string billingEmail = checkoutDetails.PayerInfo.Payer; string billingAddress1 = checkoutDetails.PayerInfo.Address.Street1; string billingAddress2 = checkoutDetails.PayerInfo.Address.Street2; string billingPhoneNumber = checkoutDetails.PayerInfo.ContactPhone; string billingCity = checkoutDetails.PayerInfo.Address.CityName; int? billingStateProvinceId = null; var billingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(checkoutDetails.PayerInfo.Address.StateOrProvince); if (billingStateProvince != null) { billingStateProvinceId = billingStateProvince.Id; } string billingZipPostalCode = checkoutDetails.PayerInfo.Address.PostalCode; int? billingCountryId = null; var billingCountry = _countryService.GetCountryByTwoLetterIsoCode(checkoutDetails.PayerInfo.Address.Country.ToString()); if (billingCountry != null) { billingCountryId = billingCountry.Id; } var billingAddress = customer.Addresses.FindAddress( billingFirstName, billingLastName, billingPhoneNumber, billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity, billingStateProvinceId, billingZipPostalCode, billingCountryId); if (billingAddress == null) { billingAddress = new Core.Domain.Common.Address() { FirstName = billingFirstName, LastName = billingLastName, PhoneNumber = billingPhoneNumber, Email = billingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = billingAddress1, Address2 = billingAddress2, City = billingCity, StateProvinceId = billingStateProvinceId, ZipPostalCode = billingZipPostalCode, CountryId = billingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(billingAddress); } //set default billing address customer.BillingAddress = billingAddress; _customerService.UpdateCustomer(customer); var genericAttributeService = EngineContext.Current.Resolve <IGenericAttributeService>(); genericAttributeService.SaveAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.SelectedShippingOption, null); bool shoppingCartRequiresShipping = cart.RequiresShipping(); if (shoppingCartRequiresShipping) { var paymentDetails = checkoutDetails.PaymentDetails.FirstOrDefault(); string[] shippingFullname = paymentDetails.ShipToAddress.Name.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string shippingFirstName = shippingFullname[0]; string shippingLastName = string.Empty; if (shippingFullname.Length > 1) { shippingLastName = shippingFullname[1]; } string shippingEmail = checkoutDetails.PayerInfo.Payer; string shippingAddress1 = paymentDetails.ShipToAddress.Street1; string shippingAddress2 = paymentDetails.ShipToAddress.Street2; string shippingPhoneNumber = paymentDetails.ShipToAddress.Phone; string shippingCity = paymentDetails.ShipToAddress.CityName; int? shippingStateProvinceId = null; var shippingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(paymentDetails.ShipToAddress.StateOrProvince); if (shippingStateProvince != null) { shippingStateProvinceId = shippingStateProvince.Id; } int? shippingCountryId = null; string shippingZipPostalCode = paymentDetails.ShipToAddress.PostalCode; var shippingCountry = _countryService.GetCountryByTwoLetterIsoCode(paymentDetails.ShipToAddress.Country.ToString()); if (shippingCountry != null) { shippingCountryId = shippingCountry.Id; } var shippingAddress = customer.Addresses.FindAddress( shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail, string.Empty, string.Empty, shippingAddress1, shippingAddress2, shippingCity, shippingStateProvinceId, shippingZipPostalCode, shippingCountryId); if (shippingAddress == null) { shippingAddress = new Core.Domain.Common.Address() { FirstName = shippingFirstName, LastName = shippingLastName, PhoneNumber = shippingPhoneNumber, Email = shippingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = shippingAddress1, Address2 = shippingAddress2, City = shippingCity, StateProvinceId = shippingStateProvinceId, ZipPostalCode = shippingZipPostalCode, CountryId = shippingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(shippingAddress); } customer.ShippingAddress = shippingAddress; _customerService.UpdateCustomer(customer); } bool isShippingSet = false; GetShippingOptionResponse getShippingOptionResponse = _shippingService.GetShippingOptions(cart, customer.ShippingAddress); if (checkoutDetails.UserSelectedOptions != null) { if (getShippingOptionResponse.Success && getShippingOptionResponse.ShippingOptions.Count > 0) { foreach (var shippingOption in getShippingOptionResponse.ShippingOptions) { if (checkoutDetails.UserSelectedOptions.ShippingOptionName.Contains(shippingOption.Name) && checkoutDetails.UserSelectedOptions.ShippingOptionName.Contains(shippingOption.Description)) { _genericAttributeService.SaveAttribute(Services.WorkContext.CurrentCustomer, SystemCustomerAttributeNames.SelectedShippingOption, shippingOption); isShippingSet = true; break; } } } if (!isShippingSet) { var shippingOption = new ShippingOption(); shippingOption.Name = checkoutDetails.UserSelectedOptions.ShippingOptionName; decimal shippingPrice = settings.DefaultShippingPrice; decimal.TryParse(checkoutDetails.UserSelectedOptions.ShippingOptionAmount.Value, out shippingPrice); shippingOption.Rate = shippingPrice; _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.SelectedShippingOption, shippingOption); } } processPaymentRequest.PaypalPayerId = checkoutDetails.PayerInfo.PayerID; return(processPaymentRequest); }
public ProcessPaymentRequest SetCheckoutDetails(GetExpressCheckoutDetailsResponseDetailsType checkoutDetails) { // get customer & cart var customerId = Convert.ToInt32(_workContext.CurrentCustomer.Id.ToString()); var customer = _customerService.GetCustomerById(customerId); _workContext.CurrentCustomer = customer; var cart = _shoppingCartService.GetShoppingCart(customer, ShoppingCartType.ShoppingCart).ToList(); // get/update billing address var billingFirstName = checkoutDetails.PayerInfo.PayerName.FirstName; var billingLastName = checkoutDetails.PayerInfo.PayerName.LastName; var billingEmail = checkoutDetails.PayerInfo.Payer; var billingAddress1 = checkoutDetails.PayerInfo.Address.Street1; var billingAddress2 = checkoutDetails.PayerInfo.Address.Street2; var billingPhoneNumber = checkoutDetails.PayerInfo.ContactPhone; var billingCity = checkoutDetails.PayerInfo.Address.CityName; int?billingStateProvinceId = null; var billingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(checkoutDetails.PayerInfo.Address.StateOrProvince); if (billingStateProvince != null) { billingStateProvinceId = billingStateProvince.Id; } var billingZipPostalCode = checkoutDetails.PayerInfo.Address.PostalCode; int?billingCountryId = null; var billingCountry = _countryService.GetCountryByTwoLetterIsoCode(checkoutDetails.PayerInfo.Address.Country.ToString()); if (billingCountry != null) { billingCountryId = billingCountry.Id; } var billingAddress = _addressService.FindAddress(_customerService.GetAddressesByCustomerId(_workContext.CurrentCustomer.Id).ToList(), billingFirstName, billingLastName, billingPhoneNumber, billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity, billingCountry?.Name, billingStateProvinceId, billingZipPostalCode, billingCountryId, null); //TODO process custom attributes if (billingAddress == null) { billingAddress = new Core.Domain.Common.Address { FirstName = billingFirstName, LastName = billingLastName, PhoneNumber = billingPhoneNumber, Email = billingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = billingAddress1, Address2 = billingAddress2, City = billingCity, StateProvinceId = billingStateProvinceId, ZipPostalCode = billingZipPostalCode, CountryId = billingCountryId, CreatedOnUtc = DateTime.UtcNow }; _addressService.InsertAddress(billingAddress); _customerService.InsertCustomerAddress(customer, billingAddress); } //set default billing address customer.BillingAddressId = billingAddress.Id; _customerService.UpdateCustomer(customer); _genericAttributeService.SaveAttribute <ShippingOption>(customer, NopCustomerDefaults.SelectedShippingOptionAttribute, null, customer.RegisteredInStoreId); var shoppingCartRequiresShipping = _shoppingCartService.ShoppingCartRequiresShipping(cart); if (shoppingCartRequiresShipping) { var paymentDetails = checkoutDetails.PaymentDetails.FirstOrDefault() ?? new PaymentDetailsType(); var shippingFullname = paymentDetails.ShipToAddress.Name.Trim() .Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); var shippingFirstName = shippingFullname[0]; var shippingLastName = string.Empty; if (shippingFullname.Length > 1) { shippingLastName = shippingFullname[1]; } var shippingEmail = checkoutDetails.PayerInfo.Payer; var shippingAddress1 = paymentDetails.ShipToAddress.Street1; var shippingAddress2 = paymentDetails.ShipToAddress.Street2; var shippingPhoneNumber = paymentDetails.ShipToAddress.Phone; var shippingCity = paymentDetails.ShipToAddress.CityName; int?shippingStateProvinceId = null; var shippingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(paymentDetails.ShipToAddress.StateOrProvince); if (shippingStateProvince != null) { shippingStateProvinceId = shippingStateProvince.Id; } int?shippingCountryId = null; var shippingZipPostalCode = paymentDetails.ShipToAddress.PostalCode; var shippingCountry = _countryService.GetCountryByTwoLetterIsoCode(paymentDetails.ShipToAddress.Country.ToString()); if (shippingCountry != null) { shippingCountryId = shippingCountry.Id; } var shippingAddress = _addressService.FindAddress(_customerService.GetAddressesByCustomerId(_workContext.CurrentCustomer.Id).ToList(), shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail, string.Empty, string.Empty, shippingAddress1, shippingAddress2, shippingCity, shippingCountry?.Name, shippingStateProvinceId, shippingZipPostalCode, shippingCountryId, null); //TODO process custom attributes if (shippingAddress == null) { shippingAddress = new Core.Domain.Common.Address { FirstName = shippingFirstName, LastName = shippingLastName, PhoneNumber = shippingPhoneNumber, Email = shippingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = shippingAddress1, Address2 = shippingAddress2, City = shippingCity, StateProvinceId = shippingStateProvinceId, ZipPostalCode = shippingZipPostalCode, CountryId = shippingCountryId, CreatedOnUtc = DateTime.UtcNow }; _addressService.InsertAddress(shippingAddress); _customerService.InsertCustomerAddress(customer, shippingAddress); } //set default shipping address customer.ShippingAddressId = shippingAddress.Id; _customerService.UpdateCustomer(customer); } var processPaymentRequest = new ProcessPaymentRequest { CustomerId = customerId, CustomValues = { [Defaults.PaypalTokenKey] = checkoutDetails.Token, [Defaults.PaypalPayerIdKey] = checkoutDetails.PayerInfo.PayerID } }; return(processPaymentRequest); }
public ProcessPaymentRequest SetCheckoutDetails(StripeSource stripeSource) { // get customer & cart //var customer = customer; int customerId = Convert.ToInt32(_workContext.CurrentCustomer.Id.ToString()); var customer = _customerService.GetCustomerById(customerId); _workContext.CurrentCustomer = customer; var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); if (customer.BillingAddress == null) { // get/update billing address string name = stripeSource.Owner.Name; string billingEmail = customer.Email; string billingAddress1 = stripeSource.Owner.Address.Line1; string billingAddress2 = stripeSource.Owner.Address.Line2; string billingCity = stripeSource.Owner.Address.City; int? billingStateProvinceId = null; var billingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(stripeSource.Owner.Address.State); if (billingStateProvince != null) { billingStateProvinceId = billingStateProvince.Id; } string billingZipPostalCode = stripeSource.Owner.Address.PostalCode; int? billingCountryId = null; var billingCountry = _countryService.GetCountryByTwoLetterIsoCode(stripeSource.Owner.Address.Country); if (billingCountry != null) { billingCountryId = billingCountry.Id; } var billingAddress = customer.Addresses.ToList().FindAddress( null, null, null, billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity, billingStateProvinceId, billingZipPostalCode, billingCountryId, //TODO process custom attributes null); billingAddress = new Core.Domain.Common.Address() { FirstName = null, LastName = null, PhoneNumber = null, Email = billingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = billingAddress1, Address2 = billingAddress2, City = billingCity, StateProvinceId = billingStateProvinceId, ZipPostalCode = billingZipPostalCode, CountryId = billingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(billingAddress); //set default billing address customer.BillingAddress = billingAddress; _customerService.UpdateCustomer(customer); } _genericAttributeService.SaveAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.SelectedShippingOption, null); var processPaymentRequest = new ProcessPaymentRequest { CustomerId = customerId }; processPaymentRequest.CustomValues["StripeSourceId"] = stripeSource.Id; return(processPaymentRequest); }
/// <summary> /// Prepare details to place an order. It also sets some properties to "processPaymentRequest" /// </summary> /// <param name="processPaymentRequest">Process payment request</param> /// <returns>Details</returns> protected override PlaceOrderContainer PreparePlaceOrderDetails(ProcessPaymentRequest processPaymentRequest) { var details = new PlaceOrderContainer { //customer Customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId) }; if (details.Customer == null) { throw new ArgumentException("Customer is not set"); } //affiliate var affiliate = _affiliateService.GetAffiliateById(details.Customer.AffiliateId); if (affiliate != null && affiliate.Active && !affiliate.Deleted) { details.AffiliateId = affiliate.Id; } //check whether customer is guest if (details.Customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed) { throw new QNetException("Anonymous checkout is not allowed"); } //customer currency var currencyTmp = _currencyService.GetCurrencyById( _genericAttributeService.GetAttribute <int>(details.Customer, QNetCustomerDefaults.CurrencyIdAttribute, processPaymentRequest.StoreId)); var customerCurrency = currencyTmp != null && currencyTmp.Published ? currencyTmp : _workContext.WorkingCurrency; var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); details.CustomerCurrencyCode = customerCurrency.CurrencyCode; details.CustomerCurrencyRate = customerCurrency.Rate / primaryStoreCurrency.Rate; //customer language details.CustomerLanguage = _languageService.GetLanguageById( _genericAttributeService.GetAttribute <int>(details.Customer, QNetCustomerDefaults.LanguageIdAttribute, processPaymentRequest.StoreId)); if (details.CustomerLanguage == null || !details.CustomerLanguage.Published) { details.CustomerLanguage = _workContext.WorkingLanguage; } //billing address if (details.Customer.BillingAddress == null) { throw new QNetException("Billing address is not provided"); } if (!CommonHelper.IsValidEmail(details.Customer.BillingAddress.Email)) { throw new QNetException("Email is not valid"); } details.BillingAddress = (Address)details.Customer.BillingAddress.Clone(); if (details.BillingAddress.Country != null && !details.BillingAddress.Country.AllowsBilling) { throw new QNetException($"Country '{details.BillingAddress.Country.Name}' is not allowed for billing"); } //checkout attributes details.CheckoutAttributesXml = _genericAttributeService.GetAttribute <string>(details.Customer, QNetCustomerDefaults.CheckoutAttributes, processPaymentRequest.StoreId); details.CheckoutAttributeDescription = _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributesXml, details.Customer); //load shopping cart details.Cart = _shoppingCartService.GetShoppingCart(details.Customer, ShoppingCartType.ShoppingCart, processPaymentRequest.StoreId); if (!details.Cart.Any()) { throw new QNetException("Cart is empty"); } //validate the entire shopping cart var warnings = _shoppingCartService.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributesXml, true); if (warnings.Any()) { throw new QNetException(warnings.Aggregate(string.Empty, (current, next) => $"{current}{next};")); } //validate individual cart items foreach (var sci in details.Cart) { var sciWarnings = _shoppingCartService.GetShoppingCartItemWarnings(details.Customer, sci.ShoppingCartType, sci.Product, processPaymentRequest.StoreId, sci.AttributesXml, sci.CustomerEnteredPrice, sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.Id); if (sciWarnings.Any()) { throw new QNetException(sciWarnings.Aggregate(string.Empty, (current, next) => $"{current}{next};")); } } //min totals validation if (!ValidateMinOrderSubtotalAmount(details.Cart)) { var minOrderSubtotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency); throw new QNetException(string.Format(_localizationService.GetResource("Checkout.MinOrderSubtotalAmount"), _priceFormatter.FormatPrice(minOrderSubtotalAmount, true, false))); } if (!ValidateMinOrderTotalAmount(details.Cart)) { var minOrderTotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderTotalAmount, _workContext.WorkingCurrency); throw new QNetException(string.Format(_localizationService.GetResource("Checkout.MinOrderTotalAmount"), _priceFormatter.FormatPrice(minOrderTotalAmount, true, false))); } //tax display type if (_taxSettings.AllowCustomersToSelectTaxDisplayType) { details.CustomerTaxDisplayType = (TaxDisplayType)_genericAttributeService.GetAttribute <int>(details.Customer, QNetCustomerDefaults.TaxDisplayTypeIdAttribute, processPaymentRequest.StoreId); } else { details.CustomerTaxDisplayType = _taxSettings.TaxDisplayType; } //sub total (incl tax) _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, true, out var orderSubTotalDiscountAmount, out var orderSubTotalAppliedDiscounts, out var subTotalWithoutDiscountBase, out var _); details.OrderSubTotalInclTax = subTotalWithoutDiscountBase; details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount; //discount history foreach (var disc in orderSubTotalAppliedDiscounts) { if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc)) { details.AppliedDiscounts.Add(disc); } } //sub total (excl tax) _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, false, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscounts, out subTotalWithoutDiscountBase, out _); details.OrderSubTotalExclTax = subTotalWithoutDiscountBase; details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount; //shipping info if (_shoppingCartService.ShoppingCartRequiresShipping(details.Cart)) { var pickupPoint = _genericAttributeService.GetAttribute <PickupPoint>(details.Customer, QNetCustomerDefaults.SelectedPickupPointAttribute, processPaymentRequest.StoreId); if (_shippingSettings.AllowPickupInStore && pickupPoint != null) { var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id); details.PickupInStore = true; details.PickupAddress = new Address { Address1 = pickupPoint.Address, City = pickupPoint.City, County = pickupPoint.County, Country = country, StateProvince = state, ZipPostalCode = pickupPoint.ZipPostalCode, CreatedOnUtc = DateTime.UtcNow }; } else { if (details.Customer.ShippingAddress == null) { throw new QNetException("Shipping address is not provided"); } if (!CommonHelper.IsValidEmail(details.Customer.ShippingAddress.Email)) { throw new QNetException("Email is not valid"); } //clone shipping address details.ShippingAddress = (Address)details.Customer.ShippingAddress.Clone(); if (details.ShippingAddress.Country != null && !details.ShippingAddress.Country.AllowsShipping) { throw new QNetException($"Country '{details.ShippingAddress.Country.Name}' is not allowed for shipping"); } } var shippingOption = _genericAttributeService.GetAttribute <ShippingOption>(details.Customer, QNetCustomerDefaults.SelectedShippingOptionAttribute, processPaymentRequest.StoreId); if (shippingOption != null) { details.ShippingMethodName = shippingOption.Name; details.ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName; } details.ShippingStatus = ShippingStatus.NotYetShipped; } else { details.ShippingStatus = ShippingStatus.ShippingNotRequired; } //LoadAllShippingRateComputationMethods var shippingRateComputationMethods = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id); //shipping total var orderShippingTotalInclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true, shippingRateComputationMethods, out var _, out var shippingTotalDiscounts); var orderShippingTotalExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false, shippingRateComputationMethods); if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue) { throw new QNetException("Shipping total couldn't be calculated"); } details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value; details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value; foreach (var disc in shippingTotalDiscounts) { if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc)) { details.AppliedDiscounts.Add(disc); } } //payment total var paymentAdditionalFee = _paymentService.GetAdditionalHandlingFee(details.Cart, processPaymentRequest.PaymentMethodSystemName); details.PaymentAdditionalFeeInclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer); details.PaymentAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer); //tax amount details.OrderTaxTotal = _orderTotalCalculationService.GetTaxTotal(details.Cart, shippingRateComputationMethods, out var taxRatesDictionary); //Avalara plugin changes //get previously saved tax details received from the Avalara tax service var taxDetails = _httpContextAccessor.HttpContext.Session.Get <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue); if (taxDetails != null) { //adjust tax total according to received value from the Avalara if (taxDetails.TaxTotal.HasValue) { details.OrderTaxTotal = taxDetails.TaxTotal.Value; } if (taxDetails.TaxRates?.Any() ?? false) { taxRatesDictionary = new SortedDictionary <decimal, decimal>(taxDetails.TaxRates); } } //Avalara plugin changes //VAT number var customerVatStatus = (VatNumberStatus)_genericAttributeService.GetAttribute <int>(details.Customer, QNetCustomerDefaults.VatNumberStatusIdAttribute); if (_taxSettings.EuVatEnabled && customerVatStatus == VatNumberStatus.Valid) { details.VatNumber = _genericAttributeService.GetAttribute <string>(details.Customer, QNetCustomerDefaults.VatNumberAttribute); } //tax rates details.TaxRates = taxRatesDictionary.Aggregate(string.Empty, (current, next) => $"{current}{next.Key.ToString(CultureInfo.InvariantCulture)}:{next.Value.ToString(CultureInfo.InvariantCulture)}; "); //order total (and applied discounts, gift cards, reward points) var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(details.Cart, out var orderDiscountAmount, out var orderAppliedDiscounts, out var appliedGiftCards, out var redeemedRewardPoints, out var redeemedRewardPointsAmount); if (!orderTotal.HasValue) { throw new QNetException("Order total couldn't be calculated"); } details.OrderDiscountAmount = orderDiscountAmount; details.RedeemedRewardPoints = redeemedRewardPoints; details.RedeemedRewardPointsAmount = redeemedRewardPointsAmount; details.AppliedGiftCards = appliedGiftCards; details.OrderTotal = orderTotal.Value; //discount history foreach (var disc in orderAppliedDiscounts) { if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc)) { details.AppliedDiscounts.Add(disc); } } processPaymentRequest.OrderTotal = details.OrderTotal; //Avalara plugin changes //delete custom value _httpContextAccessor.HttpContext.Session.Set <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue, null); //Avalara plugin changes //recurring or standard shopping cart? details.IsRecurringShoppingCart = _shoppingCartService.ShoppingCartIsRecurring(details.Cart); if (!details.IsRecurringShoppingCart) { return(details); } var recurringCyclesError = _shoppingCartService.GetRecurringCycleInfo(details.Cart, out var recurringCycleLength, out var recurringCyclePeriod, out var recurringTotalCycles); if (!string.IsNullOrEmpty(recurringCyclesError)) { throw new QNetException(recurringCyclesError); } processPaymentRequest.RecurringCycleLength = recurringCycleLength; processPaymentRequest.RecurringCyclePeriod = recurringCyclePeriod; processPaymentRequest.RecurringTotalCycles = recurringTotalCycles; return(details); }
public ProcessPaymentRequest SetCheckoutDetails(GetExpressCheckoutDetailsResponseDetailsType checkoutDetails) { // get customer & cart //var customer = customer; int customerId = Convert.ToInt32(_workContext.CurrentCustomer.Id.ToString()); var customer = _customerService.GetCustomerById(customerId); _workContext.CurrentCustomer = customer; var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList(); // get/update billing address string billingFirstName = checkoutDetails.PayerInfo.PayerName.FirstName; string billingLastName = checkoutDetails.PayerInfo.PayerName.LastName; string billingEmail = checkoutDetails.PayerInfo.Payer; string billingAddress1 = checkoutDetails.PayerInfo.Address.Street1; string billingAddress2 = checkoutDetails.PayerInfo.Address.Street2; string billingPhoneNumber = string.IsNullOrEmpty(checkoutDetails.PayerInfo.ContactPhone) ? checkoutDetails.ContactPhone : checkoutDetails.PayerInfo.ContactPhone; //check if customer has entered the phone number, if not, get the contact phone number string billingCity = checkoutDetails.PayerInfo.Address.CityName; int? billingStateProvinceId = null; var billingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(checkoutDetails.PayerInfo.Address.StateOrProvince); if (billingStateProvince != null) { billingStateProvinceId = billingStateProvince.Id; } string billingZipPostalCode = checkoutDetails.PayerInfo.Address.PostalCode; int? billingCountryId = null; var billingCountry = _countryService.GetCountryByTwoLetterIsoCode(checkoutDetails.PayerInfo.Address.Country.ToString()); if (billingCountry != null) { billingCountryId = billingCountry.Id; } var billingAddress = customer.Addresses.ToList().FindAddress( billingFirstName, billingLastName, billingPhoneNumber, billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity, billingStateProvinceId, billingZipPostalCode, billingCountryId, //TODO process custom attributes null); if (billingAddress == null) { billingAddress = new Core.Domain.Common.Address() { FirstName = billingFirstName, LastName = billingLastName, PhoneNumber = billingPhoneNumber, Email = billingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = billingAddress1, Address2 = billingAddress2, City = billingCity, StateProvinceId = billingStateProvinceId, ZipPostalCode = billingZipPostalCode, CountryId = billingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(billingAddress); } //set default billing address customer.BillingAddress = billingAddress; _customerService.UpdateCustomer(customer); _genericAttributeService.SaveAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.SelectedShippingOption, null); bool shoppingCartRequiresShipping = cart.RequiresShipping(); if (shoppingCartRequiresShipping) { var paymentDetails = checkoutDetails.PaymentDetails.FirstOrDefault(); string[] shippingFullname = paymentDetails.ShipToAddress.Name.Trim() .Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string shippingFirstName = shippingFullname[0]; string shippingLastName = string.Empty; if (shippingFullname.Length > 1) { shippingLastName = shippingFullname[1]; } string shippingEmail = checkoutDetails.PayerInfo.Payer; string shippingAddress1 = paymentDetails.ShipToAddress.Street1; string shippingAddress2 = paymentDetails.ShipToAddress.Street2; string shippingPhoneNumber = string.IsNullOrEmpty(paymentDetails.ShipToAddress.Phone) ? checkoutDetails.ContactPhone : paymentDetails.ShipToAddress.Phone; //check if customer has entered the shipping phone, if not, get the contact phone number string shippingCity = paymentDetails.ShipToAddress.CityName; int? shippingStateProvinceId = null; var shippingStateProvince = _stateProvinceService.GetStateProvinceByAbbreviation( paymentDetails.ShipToAddress.StateOrProvince); if (shippingStateProvince != null) { shippingStateProvinceId = shippingStateProvince.Id; } int? shippingCountryId = null; string shippingZipPostalCode = paymentDetails.ShipToAddress.PostalCode; var shippingCountry = _countryService.GetCountryByTwoLetterIsoCode(paymentDetails.ShipToAddress.Country.ToString()); if (shippingCountry != null) { shippingCountryId = shippingCountry.Id; } var shippingAddress = customer.Addresses.ToList().FindAddress( shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail, string.Empty, string.Empty, shippingAddress1, shippingAddress2, shippingCity, shippingStateProvinceId, shippingZipPostalCode, shippingCountryId, //TODO process custom attributes null); if (shippingAddress == null) { shippingAddress = new Core.Domain.Common.Address() { FirstName = shippingFirstName, LastName = shippingLastName, PhoneNumber = shippingPhoneNumber, Email = shippingEmail, FaxNumber = string.Empty, Company = string.Empty, Address1 = shippingAddress1, Address2 = shippingAddress2, City = shippingCity, StateProvinceId = shippingStateProvinceId, ZipPostalCode = shippingZipPostalCode, CountryId = shippingCountryId, CreatedOnUtc = DateTime.UtcNow, }; customer.Addresses.Add(shippingAddress); } //set default shipping address customer.ShippingAddress = shippingAddress; _customerService.UpdateCustomer(customer); } var processPaymentRequest = new ProcessPaymentRequest { CustomerId = customerId }; processPaymentRequest.CustomValues["PaypalToken"] = checkoutDetails.Token; processPaymentRequest.CustomValues["PaypalPayerId"] = checkoutDetails.PayerInfo.PayerID; return(processPaymentRequest); }
public IActionResult GetShippings([FromBody] ShippingsParametersModel parameters) { var consumerKey = Request.Headers.GetInstantCheckoutConsumerKey(); var consumerSecret = Request.Headers.GetInstantCheckoutConsumerSecret(); if (consumerKey == Guid.Empty || consumerSecret == Guid.Empty) { return(Unauthorized()); } var storeScope = _storeContext.ActiveStoreScopeConfiguration; var instantCheckoutSettings = _settingService.LoadSetting <InstantCheckoutSettings>(storeScope); if (consumerKey != instantCheckoutSettings.ConsumerKey && consumerSecret != instantCheckoutSettings.ConsumerSecret) { return(Unauthorized()); } if (parameters.Ids == null && parameters.Ids.Any(x => x <= 0)) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var allProducts = _productApiService.GetProducts(parameters.Ids) .Where(p => _storeMappingService.Authorize(p)); var cart = new List <ShoppingCartItem> { }; foreach (var product in allProducts) { cart.Add(new ShoppingCartItem { Customer = _workContext.CurrentCustomer, CustomerId = _workContext.CurrentCustomer.Id, ProductId = product.Id, Product = product, Quantity = 1 //TODO ADD Proper Quantity by Product Check Shipping By Weight }); } var model = new ShippingOptionsViewModel(); var country = _countryService.GetCountryByTwoLetterIsoCode(parameters.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(parameters.StateCode); var address = new Address { CountryId = country.Id, Country = country, StateProvinceId = state != null ? state.Id : 0, StateProvince = state != null ? state : null, ZipPostalCode = parameters.ZipCode, }; var getShippingOptionResponse = _shippingService.GetShippingOptions(cart, address, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id); if (getShippingOptionResponse.Success) { if (getShippingOptionResponse.ShippingOptions.Any()) { foreach (var shippingOption in getShippingOptionResponse.ShippingOptions) { //calculate discounted and taxed rate var shippingRate = _orderTotalCalculationService.AdjustShippingRate(shippingOption.Rate, cart, out var _); shippingRate = _taxService.GetShippingPrice(shippingRate, _workContext.CurrentCustomer); shippingRate = _currencyService.ConvertFromPrimaryStoreCurrency(shippingRate, _workContext.WorkingCurrency); model.ShippingOptions.Add(new ShippingOptionModel { Name = shippingOption.Name, Description = shippingOption.Description, Price = shippingRate, Plugin = shippingOption.ShippingRateComputationMethodSystemName }); } } } else { foreach (var error in getShippingOptionResponse.Errors) { model.Warnings.Add(error); } } if (_shippingSettings.AllowPickupInStore) { var pickupPointsResponse = _shippingService.GetPickupPoints(address, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id); if (pickupPointsResponse.Success) { if (pickupPointsResponse.PickupPoints.Any()) { var soModel = new ShippingOptionModel { Name = _localizationService.GetResource("Checkout.PickupPoints"), Description = _localizationService.GetResource("Checkout.PickupPoints.Description"), }; var pickupFee = pickupPointsResponse.PickupPoints.Min(x => x.PickupFee); if (pickupFee > 0) { pickupFee = _taxService.GetShippingPrice(pickupFee, _workContext.CurrentCustomer); pickupFee = _currencyService.ConvertFromPrimaryStoreCurrency(pickupFee, _workContext.WorkingCurrency); } soModel.Price = pickupFee; soModel.Plugin = "Pickup.PickupInStore"; model.ShippingOptions.Add(soModel); } } else { foreach (var error in pickupPointsResponse.Errors) { model.Warnings.Add(error); } } } return(Ok(model)); }
/// <summary> /// Create request for tax calculation /// </summary> /// <param name="product">Product</param> /// <param name="taxCategoryId">Tax category identifier</param> /// <param name="customer">Customer</param> /// <param name="price">Price</param> /// <returns>Package for tax calculation</returns> protected virtual CalculateTaxRequest CreateCalculateTaxRequest(Product product, int taxCategoryId, Customer customer, decimal price) { if (customer == null) { throw new ArgumentNullException(nameof(customer)); } var calculateTaxRequest = new CalculateTaxRequest { Customer = customer, Product = product, Price = price, TaxCategoryId = taxCategoryId > 0 ? taxCategoryId : (product != null ? product.TaxCategoryId : 0) }; var basedOn = _taxSettings.TaxBasedOn; //new EU VAT rules starting January 1st 2015 //find more info at http://ec.europa.eu/taxation_customs/taxation/vat/how_vat_works/telecom/index_en.htm#new_rules var overridenBasedOn = _taxSettings.EuVatEnabled && //EU VAT enabled? product != null && product.IsTelecommunicationsOrBroadcastingOrElectronicServices && //telecommunications, broadcasting and electronic services? DateTime.UtcNow > new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc) && //January 1st 2015 passed? IsEuConsumer(customer); //Europe Union consumer? if (overridenBasedOn) { //We must charge VAT in the EU country where the customer belongs (not where the business is based) basedOn = TaxBasedOn.BillingAddress; } //tax is based on pickup point address if (!overridenBasedOn && _taxSettings.TaxBasedOnPickupPointAddress && _shippingSettings.AllowPickUpInStore) { var pickupPoint = customer.GetAttribute <PickupPoint>(SystemCustomerAttributeNames.SelectedPickupPoint, 0); if (pickupPoint != null) { var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id); calculateTaxRequest.Address = new Address { Address1 = pickupPoint.Address, City = pickupPoint.City, Country = country, CountryId = country?.Id ?? 0, StateProvince = state, StateProvinceId = state?.Id ?? 0, ZipPostalCode = pickupPoint.ZipPostalCode, CreatedOnUtc = DateTime.UtcNow }; return(calculateTaxRequest); } } //if (basedOn == TaxBasedOn.BillingAddress && customer.BillingAddress == null || // basedOn == TaxBasedOn.ShippingAddress && customer.ShippingAddress == null) //{ // basedOn = TaxBasedOn.DefaultAddress; //} //switch (basedOn) //{ // case TaxBasedOn.BillingAddress: // calculateTaxRequest.Address = customer.BillingAddress; // break; // case TaxBasedOn.ShippingAddress: // calculateTaxRequest.Address = customer.ShippingAddress; // break; // case TaxBasedOn.DefaultAddress: // default: // calculateTaxRequest.Address = _addressService.GetAddressById(_taxSettings.DefaultTaxAddressId); // break; //} return(calculateTaxRequest); }
/// <summary> /// Invoke the widget view component /// </summary> /// <param name="widgetZone">Widget zone</param> /// <param name="additionalData">Additional parameters</param> /// <returns>View component result</returns> public IViewComponentResult Invoke(string widgetZone, object additionalData) { //ensure that Avalara tax provider is active if (!_taxPluginManager.IsPluginActive(AvalaraTaxDefaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id)) { return(Content(string.Empty)); } //ensure that it's a proper widget zone if (!widgetZone.Equals(PublicWidgetZones.CheckoutConfirmTop) && !widgetZone.Equals(PublicWidgetZones.OpCheckoutConfirmTop)) { return(Content(string.Empty)); } //ensure thet address validation is enabled if (!_avalaraTaxSettings.ValidateAddress) { return(Content(string.Empty)); } //validate entered by customer addresses only var addressId = _taxSettings.TaxBasedOn == TaxBasedOn.BillingAddress ? _workContext.CurrentCustomer.BillingAddressId : _taxSettings.TaxBasedOn == TaxBasedOn.ShippingAddress ? _workContext.CurrentCustomer.ShippingAddressId : null; var address = _addressService.GetAddressById(addressId ?? 0); if (address == null) { return(Content(string.Empty)); } //validate address var validationResult = _avalaraTaxManager.ValidateAddress(new AddressValidationInfo { city = CommonHelper.EnsureMaximumLength(address.City, 50), country = CommonHelper.EnsureMaximumLength(_countryService.GetCountryByAddress(address)?.TwoLetterIsoCode, 2), line1 = CommonHelper.EnsureMaximumLength(address.Address1, 50), line2 = CommonHelper.EnsureMaximumLength(address.Address2, 100), postalCode = CommonHelper.EnsureMaximumLength(address.ZipPostalCode, 11), region = CommonHelper.EnsureMaximumLength(_stateProvinceService.GetStateProvinceByAddress(address)?.Abbreviation, 3), textCase = TextCase.Mixed }); //whether there are errors in validation result var errorDetails = validationResult.messages? .Where(message => message.severity.Equals("Error", StringComparison.InvariantCultureIgnoreCase)) .Select(message => message.details) ?? new List <string>(); if (errorDetails.Any()) { var errorMessage = errorDetails.Aggregate(string.Empty, (message, errorDetail) => $"{message}{errorDetail}; "); //log errors _logger.Error($"Avalara tax provider error. {errorMessage}", customer: _workContext.CurrentCustomer); //and display error message to customer return(View("~/Plugins/Tax.Avalara/Views/Checkout/AddressValidation.cshtml", new AddressValidationModel { Message = string.Format(_localizationService.GetResource("Plugins.Tax.Avalara.AddressValidation.Error"), WebUtility.HtmlEncode(errorMessage)), IsError = true })); } //if there are no errors and no validated addresses, nothing to display if (!validationResult.validatedAddresses?.Any() ?? true) { return(Content(string.Empty)); } //get validated address info var validatedAddressInfo = validationResult.validatedAddresses.FirstOrDefault(); //create new address as a copy of address to validate and with details of the validated one var validatedAddress = _addressService.CloneAddress(address); validatedAddress.City = validatedAddressInfo.city; validatedAddress.CountryId = _countryService.GetCountryByTwoLetterIsoCode(validatedAddressInfo.country)?.Id; validatedAddress.Address1 = validatedAddressInfo.line1; validatedAddress.Address2 = validatedAddressInfo.line2; validatedAddress.ZipPostalCode = validatedAddressInfo.postalCode; validatedAddress.StateProvinceId = _stateProvinceService.GetStateProvinceByAbbreviation(validatedAddressInfo.region)?.Id; //try to find an existing address with the same values var existingAddress = _addressService.FindAddress(_customerService.GetAddressesByCustomerId(_workContext.CurrentCustomer.Id).ToList(), validatedAddress.FirstName, validatedAddress.LastName, validatedAddress.PhoneNumber, validatedAddress.Email, validatedAddress.FaxNumber, validatedAddress.Company, validatedAddress.Address1, validatedAddress.Address2, validatedAddress.City, validatedAddress.County, validatedAddress.StateProvinceId, validatedAddress.ZipPostalCode, validatedAddress.CountryId, validatedAddress.CustomAttributes); //if the found address is the same as address to validate, nothing to display if (address.Id == existingAddress?.Id) { return(Content(string.Empty)); } //otherwise display to customer a confirmation dialog about address updating var model = new AddressValidationModel(); if (existingAddress == null) { _addressService.InsertAddress(validatedAddress); model.AddressId = validatedAddress.Id; model.IsNewAddress = true; } else { model.AddressId = existingAddress.Id; } model.Message = string.Format(_localizationService.GetResource("Plugins.Tax.Avalara.AddressValidation.Confirm"), GetAddressLine(address), GetAddressLine(existingAddress ?? validatedAddress)); return(View("~/Plugins/Tax.Avalara/Views/Checkout/AddressValidation.cshtml", model)); }
/// <summary> /// Gets a state/province /// </summary> /// <param name="abbreviation">The state/province abbreviation</param> /// <returns>State/province</returns> StateProvince GetStateProvinceByAbbreviation(string abbreviation) { return(_stateProvinceService.GetStateProvinceByAbbreviation(abbreviation)); }
/// <summary> /// Prepare details to place an order. It also sets some properties to "processPaymentRequest" /// </summary> /// <param name="processPaymentRequest">Process payment request</param> /// <returns>Details</returns> protected override PlaceOrderContainter PreparePlaceOrderDetails(ProcessPaymentRequest processPaymentRequest) { var details = new PlaceOrderContainter(); //customer details.Customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId); if (details.Customer == null) { throw new ArgumentException("Customer is not set"); } //affiliate var affiliate = _affiliateService.GetAffiliateById(details.Customer.AffiliateId); if (affiliate != null && affiliate.Active && !affiliate.Deleted) { details.AffiliateId = affiliate.Id; } //check whether customer is guest if (details.Customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed) { throw new NopException("Anonymous checkout is not allowed"); } //customer currency var currencyTmp = _currencyService.GetCurrencyById( details.Customer.GetAttribute <int>(SystemCustomerAttributeNames.CurrencyId, processPaymentRequest.StoreId)); var customerCurrency = (currencyTmp != null && currencyTmp.Published) ? currencyTmp : _workContext.WorkingCurrency; var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); details.CustomerCurrencyCode = customerCurrency.CurrencyCode; //START PATCH var coinServiceSettings = EngineContext.Current.ContainerManager.Resolve <CoinServiceSettings>(); string[] Cryptos; if (coinServiceSettings.SupportedCoins != null) { Cryptos = coinServiceSettings.SupportedCoins.Split(','); } else { Cryptos = new string[0]; } if (Cryptos.Contains(details.CustomerCurrencyCode)) { details.CustomerCurrencyRate = CoinMarketCapHelper.GetCoinMarketCapRate(details.CustomerCurrencyCode) / primaryStoreCurrency.Rate; } else { details.CustomerCurrencyRate = customerCurrency.Rate / primaryStoreCurrency.Rate; } //END PATCH //customer language details.CustomerLanguage = _languageService.GetLanguageById( details.Customer.GetAttribute <int>(SystemCustomerAttributeNames.LanguageId, processPaymentRequest.StoreId)); if (details.CustomerLanguage == null || !details.CustomerLanguage.Published) { details.CustomerLanguage = _workContext.WorkingLanguage; } //billing address if (details.Customer.BillingAddress == null) { throw new NopException("Billing address is not provided"); } if (!CommonHelper.IsValidEmail(details.Customer.BillingAddress.Email)) { throw new NopException("Email is not valid"); } details.BillingAddress = (Address)details.Customer.BillingAddress.Clone(); if (details.BillingAddress.Country != null && !details.BillingAddress.Country.AllowsBilling) { throw new NopException(string.Format("Country '{0}' is not allowed for billing", details.BillingAddress.Country.Name)); } //checkout attributes details.CheckoutAttributesXml = details.Customer.GetAttribute <string>(SystemCustomerAttributeNames.CheckoutAttributes, processPaymentRequest.StoreId); details.CheckoutAttributeDescription = _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributesXml, details.Customer); //load shopping cart details.Cart = details.Customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(processPaymentRequest.StoreId).ToList(); if (!details.Cart.Any()) { throw new NopException("Cart is empty"); } //validate the entire shopping cart var warnings = _shoppingCartService.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributesXml, true); if (warnings.Any()) { throw new NopException(warnings.Aggregate(string.Empty, (current, next) => string.Format("{0}{1};", current, next))); } //validate individual cart items foreach (var sci in details.Cart) { var sciWarnings = _shoppingCartService.GetShoppingCartItemWarnings(details.Customer, sci.ShoppingCartType, sci.Product, processPaymentRequest.StoreId, sci.AttributesXml, sci.CustomerEnteredPrice, sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false); if (sciWarnings.Any()) { throw new NopException(sciWarnings.Aggregate(string.Empty, (current, next) => string.Format("{0}{1};", current, next))); } } //min totals validation if (!ValidateMinOrderSubtotalAmount(details.Cart)) { var minOrderSubtotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency); throw new NopException(string.Format(_localizationService.GetResource("Checkout.MinOrderSubtotalAmount"), _priceFormatter.FormatPrice(minOrderSubtotalAmount, true, false))); } if (!ValidateMinOrderTotalAmount(details.Cart)) { var minOrderTotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderTotalAmount, _workContext.WorkingCurrency); throw new NopException(string.Format(_localizationService.GetResource("Checkout.MinOrderTotalAmount"), _priceFormatter.FormatPrice(minOrderTotalAmount, true, false))); } //tax display type if (_taxSettings.AllowCustomersToSelectTaxDisplayType) { details.CustomerTaxDisplayType = (TaxDisplayType)details.Customer.GetAttribute <int>(SystemCustomerAttributeNames.TaxDisplayTypeId, processPaymentRequest.StoreId); } else { details.CustomerTaxDisplayType = _taxSettings.TaxDisplayType; } //sub total (incl tax) decimal orderSubTotalDiscountAmount; List <DiscountForCaching> orderSubTotalAppliedDiscounts; decimal subTotalWithoutDiscountBase; decimal subTotalWithDiscountBase; _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, true, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscounts, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); details.OrderSubTotalInclTax = subTotalWithoutDiscountBase; details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount; //discount history foreach (var disc in orderSubTotalAppliedDiscounts) { if (!details.AppliedDiscounts.ContainsDiscount(disc)) { details.AppliedDiscounts.Add(disc); } } //sub total (excl tax) _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, false, out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscounts, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); details.OrderSubTotalExclTax = subTotalWithoutDiscountBase; details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount; //shipping info if (details.Cart.RequiresShipping()) { var pickupPoint = details.Customer.GetAttribute <PickupPoint>(SystemCustomerAttributeNames.SelectedPickupPoint, processPaymentRequest.StoreId); if (_shippingSettings.AllowPickUpInStore && pickupPoint != null) { var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode); var state = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation); details.PickUpInStore = true; details.PickupAddress = new Address { Address1 = pickupPoint.Address, City = pickupPoint.City, Country = country, StateProvince = state, ZipPostalCode = pickupPoint.ZipPostalCode, CreatedOnUtc = DateTime.UtcNow, }; } else { if (details.Customer.ShippingAddress == null) { throw new NopException("Shipping address is not provided"); } if (!CommonHelper.IsValidEmail(details.Customer.ShippingAddress.Email)) { throw new NopException("Email is not valid"); } //clone shipping address details.ShippingAddress = (Address)details.Customer.ShippingAddress.Clone(); if (details.ShippingAddress.Country != null && !details.ShippingAddress.Country.AllowsShipping) { throw new NopException(string.Format("Country '{0}' is not allowed for shipping", details.ShippingAddress.Country.Name)); } } var shippingOption = details.Customer.GetAttribute <ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, processPaymentRequest.StoreId); if (shippingOption != null) { details.ShippingMethodName = shippingOption.Name; details.ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName; } details.ShippingStatus = ShippingStatus.NotYetShipped; } else { details.ShippingStatus = ShippingStatus.ShippingNotRequired; } //shipping total decimal tax; List <DiscountForCaching> shippingTotalDiscounts; var orderShippingTotalInclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true, out tax, out shippingTotalDiscounts); var orderShippingTotalExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false); if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue) { throw new NopException("Shipping total couldn't be calculated"); } details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value; details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value; foreach (var disc in shippingTotalDiscounts) { if (!details.AppliedDiscounts.ContainsDiscount(disc)) { details.AppliedDiscounts.Add(disc); } } //payment total var paymentAdditionalFee = _paymentService.GetAdditionalHandlingFee(details.Cart, processPaymentRequest.PaymentMethodSystemName); details.PaymentAdditionalFeeInclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer); details.PaymentAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer); //tax amount SortedDictionary <decimal, decimal> taxRatesDictionary; details.OrderTaxTotal = _orderTotalCalculationService.GetTaxTotal(details.Cart, out taxRatesDictionary); //VAT number var customerVatStatus = (VatNumberStatus)details.Customer.GetAttribute <int>(SystemCustomerAttributeNames.VatNumberStatusId); if (_taxSettings.EuVatEnabled && customerVatStatus == VatNumberStatus.Valid) { details.VatNumber = details.Customer.GetAttribute <string>(SystemCustomerAttributeNames.VatNumber); } //tax rates details.TaxRates = taxRatesDictionary.Aggregate(string.Empty, (current, next) => string.Format("{0}{1}:{2}; ", current, next.Key.ToString(CultureInfo.InvariantCulture), next.Value.ToString(CultureInfo.InvariantCulture))); //order total (and applied discounts, gift cards, reward points) List <AppliedGiftCard> appliedGiftCards; List <DiscountForCaching> orderAppliedDiscounts; decimal orderDiscountAmount; int redeemedRewardPoints; decimal redeemedRewardPointsAmount; var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(details.Cart, out orderDiscountAmount, out orderAppliedDiscounts, out appliedGiftCards, out redeemedRewardPoints, out redeemedRewardPointsAmount); if (!orderTotal.HasValue) { throw new NopException("Order total couldn't be calculated"); } details.OrderDiscountAmount = orderDiscountAmount; details.RedeemedRewardPoints = redeemedRewardPoints; details.RedeemedRewardPointsAmount = redeemedRewardPointsAmount; details.AppliedGiftCards = appliedGiftCards; details.OrderTotal = orderTotal.Value; //discount history foreach (var disc in orderAppliedDiscounts) { if (!details.AppliedDiscounts.ContainsDiscount(disc)) { details.AppliedDiscounts.Add(disc); } } processPaymentRequest.OrderTotal = details.OrderTotal; //recurring or standard shopping cart? details.IsRecurringShoppingCart = details.Cart.IsRecurring(); if (details.IsRecurringShoppingCart) { int recurringCycleLength; RecurringProductCyclePeriod recurringCyclePeriod; int recurringTotalCycles; var recurringCyclesError = details.Cart.GetRecurringCycleInfo(_localizationService, out recurringCycleLength, out recurringCyclePeriod, out recurringTotalCycles); if (!string.IsNullOrEmpty(recurringCyclesError)) { throw new NopException(recurringCyclesError); } processPaymentRequest.RecurringCycleLength = recurringCycleLength; processPaymentRequest.RecurringCyclePeriod = recurringCyclePeriod; processPaymentRequest.RecurringTotalCycles = recurringTotalCycles; } return(details); }