public virtual async Task <IActionResult> Index() { //display a warning to a store owner if there are some error var hideCard = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.HideConfigurationStepsAttribute); var closeCard = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.CloseConfigurationStepsAttribute); if ((hideCard || closeCard) && await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageMaintenance)) { var warnings = await _commonModelFactory.PrepareSystemWarningModelsAsync(); if (warnings.Any(warning => warning.Level == SystemWarningLevel.Fail || warning.Level == SystemWarningLevel.CopyrightRemovalKey || warning.Level == SystemWarningLevel.Warning)) { _notificationService.WarningNotification( string.Format(await _localizationService.GetResourceAsync("Admin.System.Warnings.Errors"), Url.Action("Warnings", "Common")), //do not encode URLs false); } } //progress of localozation var progress = await _genericAttributeService.GetAttributeAsync <string>(await _workContext.GetWorkingLanguageAsync(), NopCommonDefaults.LanguagePackProgressAttribute); if (!string.IsNullOrEmpty(progress)) { var locale = await _localizationService.GetResourceAsync("Admin.Configuration.LanguagePackProgressMessage"); _notificationService.SuccessNotification(string.Format(locale, progress, NopLinksDefaults.OfficialSite.Translations), false); await _genericAttributeService.SaveAttributeAsync(await _workContext.GetWorkingLanguageAsync(), NopCommonDefaults.LanguagePackProgressAttribute, string.Empty); } //prepare model var model = await _homeModelFactory.PrepareDashboardModelAsync(new DashboardModel()); return(View(model)); }
/// <summary> /// Invoke view component /// </summary> /// <param name="widgetZone">Widget zone name</param> /// <param name="additionalData">Additional data</param> /// <returns>View component result</returns> public async Task <IViewComponentResult> InvokeAsync(string widgetZone, object additionalData) { if (!await _paymentPluginManager.IsPluginActiveAsync(Defaults.SystemName, await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).Id)) { return(Content(string.Empty)); } if (string.IsNullOrEmpty(_settings.ClientId)) { return(Content(string.Empty)); } if (!widgetZone.Equals(PublicWidgetZones.ProductDetailsAddInfo) && !widgetZone.Equals(PublicWidgetZones.OrderSummaryContentAfter)) { return(Content(string.Empty)); } if (widgetZone.Equals(PublicWidgetZones.OrderSummaryContentAfter)) { if (!_settings.DisplayButtonsOnShoppingCart) { return(Content(string.Empty)); } var routeName = HttpContext.GetEndpoint()?.Metadata.GetMetadata <RouteNameMetadata>()?.RouteName; if (routeName != Defaults.ShoppingCartRouteName) { return(Content(string.Empty)); } } if (widgetZone.Equals(PublicWidgetZones.ProductDetailsAddInfo) && !_settings.DisplayButtonsOnProductDetails) { return(Content(string.Empty)); } var productId = additionalData is ProductDetailsModel.AddToCartModel model ? model.ProductId : 0; return(View("~/Plugins/Payments.PayPalSmartPaymentButtons/Views/Buttons.cshtml", (widgetZone, productId))); }
public async Task <IActionResult> Configure(bool showtour = false) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageShippingSettings)) { return(AccessDeniedView()); } var model = new ConfigurationModel { LimitMethodsToCreated = _fixedByWeightByTotalSettings.LimitMethodsToCreated, ShippingByWeightByTotalEnabled = _fixedByWeightByTotalSettings.ShippingByWeightByTotalEnabled }; //stores model.AvailableStores.Add(new SelectListItem { Text = "*", Value = "0" }); foreach (var store in await _storeService.GetAllStoresAsync()) { model.AvailableStores.Add(new SelectListItem { Text = store.Name, Value = store.Id.ToString() }); } //warehouses model.AvailableWarehouses.Add(new SelectListItem { Text = "*", Value = "0" }); foreach (var warehouses in await _shippingService.GetAllWarehousesAsync()) { model.AvailableWarehouses.Add(new SelectListItem { Text = warehouses.Name, Value = warehouses.Id.ToString() }); } //shipping methods foreach (var sm in await _shippingService.GetAllShippingMethodsAsync()) { model.AvailableShippingMethods.Add(new SelectListItem { Text = sm.Name, Value = sm.Id.ToString() }); } //countries model.AvailableCountries.Add(new SelectListItem { Text = "*", Value = "0" }); var countries = await _countryService.GetAllCountriesAsync(); foreach (var c in countries) { model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() }); } //states model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "0" }); model.SetGridPageSize(); //show configuration tour if (showtour) { var hideCard = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.HideConfigurationStepsAttribute); var closeCard = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.CloseConfigurationStepsAttribute); if (!hideCard && !closeCard) { ViewBag.ShowTour = true; } } return(View("~/Plugins/Shipping.FixedByWeightByTotal/Views/Configure.cshtml", model)); }
public virtual async Task <IActionResult> BlogCommentAdd(int blogPostId, BlogPostModel model, bool captchaValid) { if (!_blogSettings.Enabled) { return(RedirectToRoute("Homepage")); } var blogPost = await _blogService.GetBlogPostByIdAsync(blogPostId); if (blogPost == null || !blogPost.AllowComments) { return(RedirectToRoute("Homepage")); } if (await _customerService.IsGuestAsync(await _workContext.GetCurrentCustomerAsync()) && !_blogSettings.AllowNotRegisteredUsersToLeaveComments) { ModelState.AddModelError("", await _localizationService.GetResourceAsync("Blog.Comments.OnlyRegisteredUsersLeaveComments")); } //validate CAPTCHA if (_captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage && !captchaValid) { ModelState.AddModelError("", await _localizationService.GetResourceAsync("Common.WrongCaptchaMessage")); } if (ModelState.IsValid) { var comment = new BlogComment { BlogPostId = blogPost.Id, CustomerId = (await _workContext.GetCurrentCustomerAsync()).Id, CommentText = model.AddNewComment.CommentText, IsApproved = !_blogSettings.BlogCommentsMustBeApproved, StoreId = (await _storeContext.GetCurrentStoreAsync()).Id, CreatedOnUtc = DateTime.UtcNow, }; await _blogService.InsertBlogCommentAsync(comment); //notify a store owner if (_blogSettings.NotifyAboutNewBlogComments) { await _workflowMessageService.SendBlogCommentNotificationMessageAsync(comment, _localizationSettings.DefaultAdminLanguageId); } //activity log await _customerActivityService.InsertActivityAsync("PublicStore.AddBlogComment", await _localizationService.GetResourceAsync("ActivityLog.PublicStore.AddBlogComment"), comment); //raise event if (comment.IsApproved) { await _eventPublisher.PublishAsync(new BlogCommentApprovedEvent(comment)); } //The text boxes should be cleared after a comment has been posted //That' why we reload the page TempData["nop.blog.addcomment.result"] = comment.IsApproved ? await _localizationService.GetResourceAsync("Blog.Comments.SuccessfullyAdded") : await _localizationService.GetResourceAsync("Blog.Comments.SeeAfterApproving"); return(RedirectToRoute("BlogPost", new { SeName = await _urlRecordService.GetSeNameAsync(blogPost, blogPost.LanguageId, ensureTwoPublishedLanguages: false) })); } //If we got this far, something failed, redisplay form await _blogModelFactory.PrepareBlogPostModelAsync(model, blogPost, true); return(View(model)); }
/// <summary> /// Called asynchronously before the action, after model binding is complete. /// </summary> /// <param name="context">A context for action filters</param> /// <returns>A task that represents the asynchronous operation</returns> private async Task SaveLastVisitedPageAsync(ActionExecutingContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.HttpContext.Request == null) { return; } //only in GET requests if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase)) { return; } if (!DataSettingsManager.IsDatabaseInstalled()) { return; } //check whether we store last visited page URL if (!_customerSettings.StoreLastVisitedPage) { return; } //get current page var pageUrl = _webHelper.GetThisPageUrl(true); if (string.IsNullOrEmpty(pageUrl)) { return; } //get previous last page var customer = await _workContext.GetCurrentCustomerAsync(); var previousPageAttribute = (await _genericAttributeService .GetAttributesForEntityAsync(customer.Id, nameof(Customer))) .FirstOrDefault(attribute => attribute.Key .Equals(NopCustomerDefaults.LastVisitedPageAttribute, StringComparison.InvariantCultureIgnoreCase)); //save new one if don't match if (previousPageAttribute == null) { //insert without event notification await _genericAttributeRepository.InsertAsync(new GenericAttribute { EntityId = customer.Id, Key = NopCustomerDefaults.LastVisitedPageAttribute, KeyGroup = nameof(Customer), Value = pageUrl, CreatedOrUpdatedDateUTC = DateTime.UtcNow }, false); } else if (!pageUrl.Equals(previousPageAttribute.Value, StringComparison.InvariantCultureIgnoreCase)) { //update without event notification previousPageAttribute.Value = pageUrl; previousPageAttribute.CreatedOrUpdatedDateUTC = DateTime.UtcNow; await _genericAttributeRepository.UpdateAsync(previousPageAttribute, false); } }
/// <summary> /// Called asynchronously before the action, after model binding is complete. /// </summary> /// <param name="context">A context for action filters</param> /// <returns>A task that represents the asynchronous operation</returns> private async Task ValidateCaptchaAsync(ActionExecutingContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (!await DataSettingsManager.IsDatabaseInstalledAsync()) { return; } //whether CAPTCHA is enabled if (_captchaSettings.Enabled && context.HttpContext?.Request != null) { //push the validation result as an action parameter var isValid = false; //get form values var captchaResponseValue = context.HttpContext.Request.Form[RESPONSE_FIELD_KEY]; var gCaptchaResponseValue = context.HttpContext.Request.Form[G_RESPONSE_FIELD_KEY]; if (!StringValues.IsNullOrEmpty(captchaResponseValue) || !StringValues.IsNullOrEmpty(gCaptchaResponseValue)) { //validate request try { var value = !StringValues.IsNullOrEmpty(captchaResponseValue) ? captchaResponseValue : gCaptchaResponseValue; var response = await _captchaHttpClient.ValidateCaptchaAsync(value); switch (_captchaSettings.CaptchaType) { case CaptchaType.CheckBoxReCaptchaV2: isValid = response.IsValid; break; case CaptchaType.ReCaptchaV3: isValid = response.IsValid && response.Action == context.RouteData.Values["action"].ToString() && response.Score > _captchaSettings.ReCaptchaV3ScoreThreshold; break; default: break; } } catch (Exception exception) { await _logger.ErrorAsync("Error occurred on CAPTCHA validation", exception, await _workContext.GetCurrentCustomerAsync()); } } context.ActionArguments[_actionParameterName] = isValid; } else { context.ActionArguments[_actionParameterName] = false; } }
public async Task <IPagedList <Slider> > GetAllSlidersAsync( string name = null, int storeId = 0, int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false, bool?overridePublished = null) { var query = _sliderRepository.Table; if (!showHidden) { query = query.Where(s => s.Published); } if (!string.IsNullOrWhiteSpace(name)) { query = query.Where(s => s.Name.Contains(name)); } query = query.OrderBy(p => p.DisplayOrder).ThenBy(p => p.Id); if ((storeId > 0 && !_catalogSettings.IgnoreStoreLimitations) || (!showHidden && !_catalogSettings.IgnoreAcl)) { if (!showHidden && !_catalogSettings.IgnoreAcl) { //ACL (access control list) var allowedCustomerRolesIds = await _customerService.GetCustomerRoleIdsAsync(await _workContext.GetCurrentCustomerAsync()); query = from c in query join acl in _aclRepository.Table on new { c1 = c.Id, c2 = nameof(Slider) } equals new { c1 = acl.EntityId, c2 = acl.EntityName } into c_acl from acl in Enumerable.DefaultIfEmpty <AclRecord>(c_acl) where !c.SubjectToAcl || allowedCustomerRolesIds.Contains((int)acl.CustomerRoleId) select c; } if (storeId > 0 && !_catalogSettings.IgnoreStoreLimitations) { //Store mapping query = from c in query join sm in _storeMappingRepository.Table on new { c1 = c.Id, c2 = nameof(Slider) } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into c_sm from sm in Enumerable.DefaultIfEmpty <StoreMapping>(c_sm) where !c.LimitedToStores || storeId == sm.StoreId select c; } } return(await query.ToPagedListAsync(pageIndex, pageSize)); }
/// <summary> /// Formats attributes /// </summary> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the attributes /// </returns> public virtual async Task <string> FormatAttributesAsync(Product product, string attributesXml) { var customer = await _workContext.GetCurrentCustomerAsync(); return(await FormatAttributesAsync(product, attributesXml, customer)); }
/// <summary> /// Called asynchronously before the action, after model binding is complete. /// </summary> /// <param name="context">A context for action filters</param> /// <returns>A task that represents the asynchronous operation</returns> private async Task CheckDiscountCouponAsync(ActionExecutingContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } //check request query parameters if (!context.HttpContext.Request?.Query?.Any() ?? true) { return; } //only in GET requests if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase)) { return; } if (!DataSettingsManager.IsDatabaseInstalled()) { return; } var customer = await _workContext.GetCurrentCustomerAsync(); //ignore search engines if (customer.IsSearchEngineAccount()) { return; } //try to get discount coupon code var queryKey = NopDiscountDefaults.DiscountCouponQueryParameter; if (!context.HttpContext.Request.Query.TryGetValue(queryKey, out var couponCodes) || StringValues.IsNullOrEmpty(couponCodes)) { return; } //get validated discounts with passed coupon codes var validCouponCodes = new List <string>(); var discounts = await couponCodes .SelectManyAwait(async couponCode => await _discountService.GetAllDiscountsAsync(couponCode: couponCode)) .Distinct() .ToListAsync(); foreach (var discount in discounts) { var result = await _discountService.ValidateDiscountAsync(discount, customer, couponCodes.ToArray()); if (!result.IsValid) { continue; } //apply discount coupon codes to customer await _customerService.ApplyDiscountCouponCodeAsync(customer, discount.CouponCode); validCouponCodes.Add(discount.CouponCode); } //show notifications for activated coupon codes var locale = await _localizationService.GetResourceAsync("ShoppingCart.DiscountCouponCode.Activated"); foreach (var validCouponCode in validCouponCodes.Distinct()) { _notificationService.SuccessNotification(string.Format(locale, WebUtility.HtmlEncode(validCouponCode))); } //show notifications for invalid coupon codes var invalidLocale = await _localizationService.GetResourceAsync("ShoppingCart.DiscountCouponCode.Invalid"); foreach (var invalidCouponCode in couponCodes.Except(validCouponCodes.Distinct())) { _notificationService.WarningNotification(string.Format(invalidLocale, WebUtility.HtmlEncode(invalidCouponCode))); } }
/// <summary> /// Authorize ACL permission /// </summary> /// <typeparam name="TEntity">Type of entity that supports the ACL</typeparam> /// <param name="entity">Entity</param> /// <returns>true - authorized; otherwise, false</returns> public virtual async Task <bool> AuthorizeAsync <TEntity>(TEntity entity) where TEntity : BaseEntity, IAclSupported { return(await AuthorizeAsync(entity, await _workContext.GetCurrentCustomerAsync())); }
/// <returns>A task that represents the asynchronous operation</returns> public async Task <IActionResult> Login(string returnUrl) { var methodIsAvailable = await _authenticationPluginManager .IsPluginActiveAsync(FacebookAuthenticationDefaults.SystemName, await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).Id); if (!methodIsAvailable) { throw new NopException("Facebook authentication module cannot be loaded"); } if (string.IsNullOrEmpty(_facebookExternalAuthSettings.ClientKeyIdentifier) || string.IsNullOrEmpty(_facebookExternalAuthSettings.ClientSecret)) { throw new NopException("Facebook authentication module not configured"); } //configure login callback action var authenticationProperties = new AuthenticationProperties { RedirectUri = Url.Action("LoginCallback", "FacebookAuthentication", new { returnUrl = returnUrl }) }; authenticationProperties.SetString(FacebookAuthenticationDefaults.ErrorCallback, Url.RouteUrl("Login", new { returnUrl })); return(Challenge(authenticationProperties, FacebookDefaults.AuthenticationScheme)); }
public async Task <IActionResult> Configure() { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageWidgets)) { return(AccessDeniedView()); } //prepare plugin configuration model var model = new ConfigurationModel(); await _baseAdminModelFactory.PrepareStoresAsync(model.FacebookPixelSearchModel.AvailableStores); model.FacebookPixelSearchModel.HideStoresList = model.FacebookPixelSearchModel.AvailableStores.SelectionIsNotPossible(); model.FacebookPixelSearchModel.HideSearchBlock = await _genericAttributeService .GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), FacebookPixelDefaults.HideSearchBlockAttribute); model.FacebookPixelSearchModel.SetGridPageSize(); model.HideList = !(await _facebookPixelService.GetPagedConfigurationsAsync()).Any(); return(View("~/Plugins/Widgets.FacebookPixel/Views/Configuration/Configure.cshtml", model)); }
/// <returns>A task that represents the asynchronous operation</returns> public async Task <IActionResult> Configure() { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageMultifactorAuthenticationMethods)) { return(AccessDeniedView()); } //prepare model var model = new ConfigurationModel { QRPixelsPerModule = _googleAuthenticatorSettings.QRPixelsPerModule, BusinessPrefix = _googleAuthenticatorSettings.BusinessPrefix }; model.GoogleAuthenticatorSearchModel.HideSearchBlock = await _genericAttributeService .GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), GoogleAuthenticatorDefaults.HideSearchBlockAttribute); return(View("~/Plugins/MultiFactorAuth.GoogleAuthenticator/Views/Configure.cshtml", model)); }
public async Task <IActionResult> Configure(ConfigurationModel model) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageWidgets)) { return(AccessDeniedView()); } if (!ModelState.IsValid) { return(await Configure()); } //request client API key if doesn't exist if (string.IsNullOrEmpty(_what3WordsSettings.ApiKey)) { try { var store = await _storeContext.GetCurrentStoreAsync(); var storeUrl = $"{store.Url?.TrimEnd('/')}/"; var apiKey = await _what3WordsHttpClient.RequestClientApiAsync(storeUrl); _what3WordsSettings.ApiKey = apiKey; } catch (Exception exception) { await _logger.ErrorAsync($"what3words error: {exception.Message}.", exception, await _workContext.GetCurrentCustomerAsync()); _notificationService .ErrorNotification(await _localizationService.GetResourceAsync("Plugins.Widgets.What3words.Configuration.Failed")); return(await Configure()); } } _what3WordsSettings.Enabled = model.Enabled; await _settingService.SaveSettingAsync(_what3WordsSettings); _notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.Plugins.Saved")); return(await Configure()); }
/// <summary> /// Prepare the poll model /// </summary> /// <param name="poll">Poll</param> /// <param name="setAlreadyVotedProperty">Whether to load a value indicating that customer already voted for this poll</param> /// <returns>Poll model</returns> public virtual async Task <PollModel> PreparePollModelAsync(Poll poll, bool setAlreadyVotedProperty) { if (poll == null) { throw new ArgumentNullException(nameof(poll)); } var model = new PollModel { Id = poll.Id, AlreadyVoted = setAlreadyVotedProperty && await _pollService.AlreadyVotedAsync(poll.Id, (await _workContext.GetCurrentCustomerAsync()).Id), Name = poll.Name }; var answers = await _pollService.GetPollAnswerByPollAsync(poll.Id); foreach (var answer in answers) { model.TotalVotes += answer.NumberOfVotes; } foreach (var pa in answers) { model.Answers.Add(new PollAnswerModel { Id = pa.Id, Name = pa.Name, NumberOfVotes = pa.NumberOfVotes, PercentOfTotalVotes = model.TotalVotes > 0 ? ((Convert.ToDouble(pa.NumberOfVotes) / Convert.ToDouble(model.TotalVotes)) * Convert.ToDouble(100)) : 0, }); } return(model); }
/// <summary> /// Register new user /// </summary> /// <param name="parameters">Authentication parameters received from external authentication method</param> /// <param name="returnUrl">URL to which the user will return after authentication</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the result of an authentication /// </returns> protected virtual async Task <IActionResult> RegisterNewUserAsync(ExternalAuthenticationParameters parameters, string returnUrl) { //check whether the specified email has been already registered if (await _customerService.GetCustomerByEmailAsync(parameters.Email) != null) { var alreadyExistsError = string.Format(await _localizationService.GetResourceAsync("Account.AssociatedExternalAuth.EmailAlreadyExists"), !string.IsNullOrEmpty(parameters.ExternalDisplayIdentifier) ? parameters.ExternalDisplayIdentifier : parameters.ExternalIdentifier); return(ErrorAuthentication(new[] { alreadyExistsError }, returnUrl)); } //registration is approved if validation isn't required var registrationIsApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard || (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation && !_externalAuthenticationSettings.RequireEmailValidation); //create registration request var registrationRequest = new CustomerRegistrationRequest(await _workContext.GetCurrentCustomerAsync(), parameters.Email, parameters.Email, CommonHelper.GenerateRandomDigitCode(20), PasswordFormat.Hashed, (await _storeContext.GetCurrentStoreAsync()).Id, registrationIsApproved); //whether registration request has been completed successfully var registrationResult = await _customerRegistrationService.RegisterCustomerAsync(registrationRequest); if (!registrationResult.Success) { return(ErrorAuthentication(registrationResult.Errors, returnUrl)); } //allow to save other customer values by consuming this event await _eventPublisher.PublishAsync(new CustomerAutoRegisteredByExternalMethodEvent(await _workContext.GetCurrentCustomerAsync(), parameters)); //raise customer registered event await _eventPublisher.PublishAsync(new CustomerRegisteredEvent(await _workContext.GetCurrentCustomerAsync())); //store owner notifications if (_customerSettings.NotifyNewCustomerRegistration) { await _workflowMessageService.SendCustomerRegisteredNotificationMessageAsync(await _workContext.GetCurrentCustomerAsync(), _localizationSettings.DefaultAdminLanguageId); } //associate external account with registered user await AssociateExternalAccountWithUserAsync(await _workContext.GetCurrentCustomerAsync(), parameters); //authenticate if (registrationIsApproved) { await _workflowMessageService.SendCustomerWelcomeMessageAsync(await _workContext.GetCurrentCustomerAsync(), (await _workContext.GetWorkingLanguageAsync()).Id); //raise event await _eventPublisher.PublishAsync(new CustomerActivatedEvent(await _workContext.GetCurrentCustomerAsync())); return(await _customerRegistrationService.SignInCustomerAsync(await _workContext.GetCurrentCustomerAsync(), returnUrl, true)); } //registration is succeeded but isn't activated if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation) { //email validation message await _genericAttributeService.SaveAttributeAsync(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.AccountActivationTokenAttribute, Guid.NewGuid().ToString()); await _workflowMessageService.SendCustomerEmailValidationMessageAsync(await _workContext.GetCurrentCustomerAsync(), (await _workContext.GetWorkingLanguageAsync()).Id); return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation, returnUrl })); } //registration is succeeded but isn't approved by admin if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval) { return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval, returnUrl })); } return(ErrorAuthentication(new[] { "Error on registration" }, returnUrl)); }
/// <summary> /// Prepares the checkout pickup points model /// </summary> /// <param name="cart">Cart</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the checkout pickup points model /// </returns> protected virtual async Task <CheckoutPickupPointsModel> PrepareCheckoutPickupPointsModelAsync(IList <ShoppingCartItem> cart) { var model = new CheckoutPickupPointsModel { AllowPickupInStore = _shippingSettings.AllowPickupInStore }; if (!model.AllowPickupInStore) { return(model); } model.DisplayPickupPointsOnMap = _shippingSettings.DisplayPickupPointsOnMap; model.GoogleMapsApiKey = _shippingSettings.GoogleMapsApiKey; var pickupPointProviders = await _pickupPluginManager.LoadActivePluginsAsync(await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).Id); if (pickupPointProviders.Any()) { var languageId = (await _workContext.GetWorkingLanguageAsync()).Id; var pickupPointsResponse = await _shippingService.GetPickupPointsAsync((await _workContext.GetCurrentCustomerAsync()).BillingAddressId ?? 0, await _workContext.GetCurrentCustomerAsync(), storeId : (await _storeContext.GetCurrentStoreAsync()).Id); if (pickupPointsResponse.Success) { model.PickupPoints = await pickupPointsResponse.PickupPoints.SelectAwait(async point => { var country = await _countryService.GetCountryByTwoLetterIsoCodeAsync(point.CountryCode); var state = await _stateProvinceService.GetStateProvinceByAbbreviationAsync(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 ? await _localizationService.GetLocalizedAsync(state, x => x.Name, languageId) : string.Empty, CountryName = country != null ? await _localizationService.GetLocalizedAsync(country, x => x.Name, languageId) : string.Empty, ZipPostalCode = point.ZipPostalCode, Latitude = point.Latitude, Longitude = point.Longitude, OpeningHours = point.OpeningHours }; var cart = await _shoppingCartService.GetShoppingCartAsync(await _workContext.GetCurrentCustomerAsync(), ShoppingCartType.ShoppingCart, (await _storeContext.GetCurrentStoreAsync()).Id); var amount = await _orderTotalCalculationService.IsFreeShippingAsync(cart) ? 0 : point.PickupFee; if (amount > 0) { (amount, _) = await _taxService.GetShippingPriceAsync(amount, await _workContext.GetCurrentCustomerAsync()); amount = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(amount, await _workContext.GetWorkingCurrencyAsync()); pickupPointModel.PickupFee = await _priceFormatter.FormatShippingPriceAsync(amount, true); } //adjust rate var(shippingTotal, _) = await _orderTotalCalculationService.AdjustShippingRateAsync(point.PickupFee, cart, true); var(rateBase, _) = await _taxService.GetShippingPriceAsync(shippingTotal, await _workContext.GetCurrentCustomerAsync()); var rate = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(rateBase, await _workContext.GetWorkingCurrencyAsync()); pickupPointModel.PickupFee = await _priceFormatter.FormatShippingPriceAsync(rate, true); return(pickupPointModel); }).ToListAsync(); } else { foreach (var error in pickupPointsResponse.Errors) { model.Warnings.Add(error); } } } //only available pickup points var shippingProviders = await _shippingPluginManager.LoadActivePluginsAsync(await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).Id); if (!shippingProviders.Any()) { if (!pickupPointProviders.Any()) { model.Warnings.Add(await _localizationService.GetResourceAsync("Checkout.ShippingIsNotAllowed")); model.Warnings.Add(await _localizationService.GetResourceAsync("Checkout.PickupPoints.NotAvailable")); } model.PickupInStoreOnly = true; model.PickupInStore = true; return(model); } return(model); }
public virtual async Task <IActionResult> AsyncUpload() { var httpPostedFile = Request.Form.Files.FirstOrDefault(); if (httpPostedFile == null) { return(Json(new { success = false, message = "No file uploaded" })); } var fileBinary = await _downloadService.GetDownloadBitsAsync(httpPostedFile); var qqFileNameParameter = "qqfilename"; var fileName = httpPostedFile.FileName; if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter)) { fileName = Request.Form[qqFileNameParameter].ToString(); } //remove path (passed in IE) fileName = _fileProvider.GetFileName(fileName); var contentType = httpPostedFile.ContentType; var fileExtension = _fileProvider.GetFileExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } var download = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = string.Empty, DownloadBinary = fileBinary, ContentType = contentType, //we store filename without extension for downloads Filename = _fileProvider.GetFileNameWithoutExtension(fileName), Extension = fileExtension, IsNew = true }; try { await _downloadService.InsertDownloadAsync(download); //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return(Json(new { success = true, downloadId = download.Id, downloadUrl = Url.Action("DownloadFile", new { downloadGuid = download.DownloadGuid }) })); } catch (Exception exc) { await _logger.ErrorAsync(exc.Message, exc, await _workContext.GetCurrentCustomerAsync()); return(Json(new { success = false, message = "File cannot be saved" })); } }
/// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="price">Price</param> /// <returns>Price. Tax rate</returns> public virtual async Task <(decimal price, decimal taxRate)> GetProductPriceAsync(Product product, decimal price) { var customer = await _workContext.GetCurrentCustomerAsync(); return(await GetProductPriceAsync(product, price, customer)); }
public async Task <IActionResult> Configure(string testTaxResult = null) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings)) { return(AccessDeniedView()); } var customer = await _workContext.GetCurrentCustomerAsync(); var model = new ConfigurationModel { AccountId = _avalaraTaxSettings.AccountId, LicenseKey = _avalaraTaxSettings.LicenseKey, CompanyCode = _avalaraTaxSettings.CompanyCode, UseSandbox = _avalaraTaxSettings.UseSandbox, CommitTransactions = _avalaraTaxSettings.CommitTransactions, ValidateAddress = _avalaraTaxSettings.ValidateAddress, TaxOriginAddressTypeId = (int)_avalaraTaxSettings.TaxOriginAddressType, EnableLogging = _avalaraTaxSettings.EnableLogging, GetTaxRateByAddressOnly = _avalaraTaxSettings.GetTaxRateByAddressOnly, EnableCertificates = _avalaraTaxSettings.EnableCertificates, AutoValidateCertificate = _avalaraTaxSettings.AutoValidateCertificate, AllowEditCustomer = _avalaraTaxSettings.AllowEditCustomer, DisplayNoValidCertificatesMessage = _avalaraTaxSettings.DisplayNoValidCertificatesMessage, SelectedCustomerRoleIds = _avalaraTaxSettings.CustomerRoleIds, TestTaxResult = testTaxResult }; model.IsConfigured = !string.IsNullOrEmpty(_avalaraTaxSettings.AccountId) && !string.IsNullOrEmpty(_avalaraTaxSettings.LicenseKey); model.TaxOriginAddressTypes = (await TaxOriginAddressType.DefaultTaxAddress.ToSelectListAsync(false)) .Select(type => new SelectListItem(type.Text, type.Value)).ToList(); model.HideGeneralBlock = await _genericAttributeService.GetAttributeAsync <bool>(customer, AvalaraTaxDefaults.HideGeneralBlock); model.HideLogBlock = await _genericAttributeService.GetAttributeAsync <bool>(customer, AvalaraTaxDefaults.HideLogBlock); //prepare model customer roles await _aclSupportedModelFactory.PrepareModelCustomerRolesAsync(model); //prepare address model await _baseAdminModelFactory.PrepareCountriesAsync(model.TestAddress.AvailableCountries); await _baseAdminModelFactory.PrepareStatesAndProvincesAsync(model.TestAddress.AvailableStates, model.TestAddress.CountryId); //prepare tax transaction log model model.TaxTransactionLogSearchModel.SetGridPageSize(); //get active account companies var activeCompanies = model.IsConfigured ? await _avalaraTaxManager.GetAccountCompaniesAsync() : null; if (activeCompanies?.Any() ?? false) { model.Companies = activeCompanies.OrderBy(company => company.isDefault ?? false ? 0 : 1).Select(company => new SelectListItem { Text = company.isTest ?? false ? $"{company.name} (Test)" : company.name, Value = company.companyCode }).ToList(); } var defaultCompanyCode = _avalaraTaxSettings.CompanyCode; if (!model.Companies.Any()) { //add the special item for 'there are no companies' with empty guid value var noCompaniesText = await _localizationService.GetResourceAsync("Plugins.Tax.Avalara.Fields.Company.NotExist"); model.Companies.Add(new SelectListItem { Text = noCompaniesText, Value = Guid.Empty.ToString() }); defaultCompanyCode = Guid.Empty.ToString(); } else if (string.IsNullOrEmpty(_avalaraTaxSettings.CompanyCode) || _avalaraTaxSettings.CompanyCode.Equals(Guid.Empty.ToString())) { defaultCompanyCode = model.Companies.FirstOrDefault()?.Value; } //set the default company var selectedCompany = activeCompanies?.FirstOrDefault(company => company.companyCode.Equals(defaultCompanyCode)); model.CompanyCode = defaultCompanyCode; _avalaraTaxSettings.CompanyCode = defaultCompanyCode; _avalaraTaxSettings.CompanyId = selectedCompany?.id; await _settingService.SaveSettingAsync(_avalaraTaxSettings); //display warning in case of company currency differ from the primary store currency var primaryCurrency = await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId); if (!selectedCompany?.baseCurrencyCode?.Equals(primaryCurrency?.CurrencyCode, StringComparison.InvariantCultureIgnoreCase) ?? false) { var warning = string.Format(await _localizationService.GetResourceAsync("Plugins.Tax.Avalara.Fields.Company.Currency.Warning"), selectedCompany.name, selectedCompany.baseCurrencyCode, primaryCurrency?.CurrencyCode); _notificationService.WarningNotification(warning); } return(View("~/Plugins/Tax.Avalara/Views/Configuration/Configure.cshtml", model)); }
/// <summary> /// Authorize permission /// </summary> /// <param name="permission">Permission record</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the rue - authorized; otherwise, false /// </returns> public virtual async Task <bool> AuthorizeAsync(PermissionRecord permission) { return(await AuthorizeAsync(permission, await _workContext.GetCurrentCustomerAsync())); }
/// <summary> /// Invoke view component /// </summary> /// <param name="widgetZone">Widget zone name</param> /// <param name="additionalData">Additional data</param> /// <returns>View component result</returns> public async Task <IViewComponentResult> InvokeAsync(string widgetZone, object additionalData) { if (!await _paymentPluginManager.IsPluginActiveAsync(Defaults.SystemName, await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).Id)) { return(Content(string.Empty)); } if (string.IsNullOrEmpty(_settings.ClientId)) { return(Content(string.Empty)); } if (!widgetZone.Equals(PublicWidgetZones.CheckoutPaymentInfoTop) && !widgetZone.Equals(PublicWidgetZones.OpcContentBefore) && !widgetZone.Equals(PublicWidgetZones.ProductDetailsTop) && !widgetZone.Equals(PublicWidgetZones.OrderSummaryContentBefore)) { return(Content(string.Empty)); } if (widgetZone.Equals(PublicWidgetZones.OrderSummaryContentBefore)) { if (!_settings.DisplayButtonsOnShoppingCart) { return(Content(string.Empty)); } var routeName = HttpContext.GetEndpoint()?.Metadata.GetMetadata <RouteNameMetadata>()?.RouteName; if (routeName != Defaults.ShoppingCartRouteName) { return(Content(string.Empty)); } } if (widgetZone.Equals(PublicWidgetZones.ProductDetailsTop) && !_settings.DisplayButtonsOnProductDetails) { return(Content(string.Empty)); } var(script, _) = await _serviceManager.GetScriptAsync(_settings); return(new HtmlContentViewComponentResult(new HtmlString(script ?? string.Empty))); }
/// <returns>A task that represents the asynchronous operation</returns> public virtual async Task <IActionResult> List(bool showtour = false) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTopics)) { return(AccessDeniedView()); } //prepare model var model = await _topicModelFactory.PrepareTopicSearchModelAsync(new TopicSearchModel()); //show configuration tour if (showtour) { var hideCard = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.HideConfigurationStepsAttribute); var closeCard = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.CloseConfigurationStepsAttribute); if (!hideCard && !closeCard) { ViewBag.ShowTour = true; } } return(View(model)); }
/// <summary> /// Invoke view component /// </summary> /// <param name="widgetZone">Widget zone name</param> /// <param name="additionalData">Additional data</param> /// <returns>View component result</returns> public async Task <IViewComponentResult> InvokeAsync(string widgetZone, object additionalData) { if (!await _paymentPluginManager.IsPluginActiveAsync(Defaults.SystemName, await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).Id)) { return(Content(string.Empty)); } var script = widgetZone.Equals(PublicWidgetZones.HeaderLinksBefore) && _settings.DisplayLogoInHeaderLinks ? _settings.LogoInHeaderLinks : (widgetZone.Equals(PublicWidgetZones.Footer) && _settings.DisplayLogoInFooter ? _settings.LogoInFooter : null); return(new HtmlContentViewComponentResult(new HtmlString(script ?? string.Empty))); }
/// <summary> /// Invoke the widget view component /// </summary> /// <param name="widgetZone">Widget zone</param> /// <param name="additionalData">Additional parameters</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the view component result /// </returns> public async Task <IViewComponentResult> InvokeAsync(string widgetZone, object additionalData) { //ensure that Avalara tax provider is active if (!await _taxPluginManager.IsPluginActiveAsync(AvalaraTaxDefaults.SystemName, await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).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 ? (await _workContext.GetCurrentCustomerAsync()).BillingAddressId : _taxSettings.TaxBasedOn == TaxBasedOn.ShippingAddress ? (await _workContext.GetCurrentCustomerAsync()).ShippingAddressId : null; var address = await _addressService.GetAddressByIdAsync(addressId ?? 0); if (address == null) { return(Content(string.Empty)); } //validate address var validationResult = await _avalaraTaxManager.ValidateAddressAsync(address); //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()) { //display error message to customer return(View("~/Plugins/Tax.Avalara/Views/Checkout/AddressValidation.cshtml", new AddressValidationModel { Message = string.Format(await _localizationService.GetResourceAsync("Plugins.Tax.Avalara.AddressValidation.Error"), WebUtility.HtmlEncode(string.Join("; ", errorDetails))), 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 = (await _countryService.GetCountryByTwoLetterIsoCodeAsync(validatedAddressInfo.country))?.Id; validatedAddress.Address1 = validatedAddressInfo.line1; validatedAddress.Address2 = validatedAddressInfo.line2; validatedAddress.ZipPostalCode = validatedAddressInfo.postalCode; validatedAddress.StateProvinceId = (await _stateProvinceService.GetStateProvinceByAbbreviationAsync(validatedAddressInfo.region))?.Id; //try to find an existing address with the same values var existingAddress = _addressService.FindAddress((await _customerService.GetAddressesByCustomerIdAsync((await _workContext.GetCurrentCustomerAsync()).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) { await _addressService.InsertAddressAsync(validatedAddress); model.AddressId = validatedAddress.Id; model.IsNewAddress = true; } else { model.AddressId = existingAddress.Id; } async Task <string> getAddressLineAsync(Address address) => WebUtility.HtmlEncode($"{(!string.IsNullOrEmpty(address.Address1) ? $"{address.Address1}, " : string.Empty)}" + $"{(!string.IsNullOrEmpty(address.Address2) ? $"{address.Address2}, " : string.Empty)}" + $"{(!string.IsNullOrEmpty(address.City) ? $"{address.City}, " : string.Empty)}" + $"{(await _stateProvinceService.GetStateProvinceByAddressAsync(address) is StateProvince stateProvince ? $"{stateProvince.Name}, " : string.Empty)}" + $"{(await _countryService.GetCountryByAddressAsync(address) is Country country ? $"{country.Name}, " : string.Empty)}" + $"{(!string.IsNullOrEmpty(address.ZipPostalCode) ? $"{address.ZipPostalCode}, " : string.Empty)}" .TrimEnd(' ').TrimEnd(',')); model.Message = string.Format(await _localizationService.GetResourceAsync("Plugins.Tax.Avalara.AddressValidation.Confirm"), await getAddressLineAsync(address), await getAddressLineAsync(existingAddress ?? validatedAddress)); return(View("~/Plugins/Tax.Avalara/Views/Checkout/AddressValidation.cshtml", model)); }
/// <summary> /// Prepare the customer return requests model /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the customer return requests model /// </returns> public virtual async Task <CustomerReturnRequestsModel> PrepareCustomerReturnRequestsModelAsync() { var model = new CustomerReturnRequestsModel(); var returnRequests = await _returnRequestService.SearchReturnRequestsAsync((await _storeContext.GetCurrentStoreAsync()).Id, (await _workContext.GetCurrentCustomerAsync()).Id); foreach (var returnRequest in returnRequests) { var orderItem = await _orderService.GetOrderItemByIdAsync(returnRequest.OrderItemId); if (orderItem != null) { var product = await _productService.GetProductByIdAsync(orderItem.ProductId); var download = await _downloadService.GetDownloadByIdAsync(returnRequest.UploadedFileId); var itemModel = new CustomerReturnRequestsModel.ReturnRequestModel { Id = returnRequest.Id, CustomNumber = returnRequest.CustomNumber, ReturnRequestStatus = await _localizationService.GetLocalizedEnumAsync(returnRequest.ReturnRequestStatus), ProductId = product.Id, ProductName = await _localizationService.GetLocalizedAsync(product, x => x.Name), ProductSeName = await _urlRecordService.GetSeNameAsync(product), Quantity = returnRequest.Quantity, ReturnAction = returnRequest.RequestedAction, ReturnReason = returnRequest.ReasonForReturn, Comments = returnRequest.CustomerComments, UploadedFileGuid = download?.DownloadGuid ?? Guid.Empty, CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(returnRequest.CreatedOnUtc, DateTimeKind.Utc), }; model.Items.Add(itemModel); } } return(model); }
public virtual async Task <IActionResult> Edit(int id, bool showtour = false) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageStores)) { return(AccessDeniedView()); } //try to get a store with the specified id var store = await _storeService.GetStoreByIdAsync(id); if (store == null) { return(RedirectToAction("List")); } //prepare model var model = await _storeModelFactory.PrepareStoreModelAsync(null, store); //show configuration tour if (showtour) { var hideCard = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.HideConfigurationStepsAttribute); var closeCard = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.CloseConfigurationStepsAttribute); if (!hideCard && !closeCard) { ViewBag.ShowTour = true; } } return(View(model)); }
public async Task <IActionResult> Configure(bool showtour = false) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings)) { return(AccessDeniedView()); } var taxCategories = await _taxCategoryService.GetAllTaxCategoriesAsync(); if (!taxCategories.Any()) { var errorModel = new ConfigurationModel { TaxCategoriesCanNotLoadedError = string.Format( await _localizationService.GetResourceAsync( "Plugins.Tax.FixedOrByCountryStateZip.TaxCategoriesCanNotLoaded"), Url.Action("Categories", "Tax")) }; return(View("~/Plugins/Tax.FixedOrByCountryStateZip/Views/Configure.cshtml", errorModel)); } var model = new ConfigurationModel { CountryStateZipEnabled = _countryStateZipSettings.CountryStateZipEnabled }; //stores model.AvailableStores.Add(new SelectListItem { Text = "*", Value = "0" }); var stores = await _storeService.GetAllStoresAsync(); foreach (var s in stores) { model.AvailableStores.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() }); } //tax categories foreach (var tc in taxCategories) { model.AvailableTaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id.ToString() }); } //countries var countries = await _countryService.GetAllCountriesAsync(showHidden : true); foreach (var c in countries) { model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() }); } //states model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "0" }); var defaultCountry = countries.FirstOrDefault(); if (defaultCountry != null) { var states = await _stateProvinceService.GetStateProvincesByCountryIdAsync(defaultCountry.Id); foreach (var s in states) { model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() }); } } //show configuration tour if (showtour) { var customer = await _workContext.GetCurrentCustomerAsync(); var hideCard = await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.HideConfigurationStepsAttribute); var closeCard = await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.CloseConfigurationStepsAttribute); if (!hideCard && !closeCard) { ViewBag.ShowTour = true; } } return(View("~/Plugins/Tax.FixedOrByCountryStateZip/Views/Configure.cshtml", model)); }
/// <summary> /// Prepare SendinBlueModel /// </summary> /// <param name="model">Model</param> private async Task PrepareModelAsync(ConfigurationModel model) { //load settings for active store scope var storeId = await _storeContext.GetActiveStoreScopeConfigurationAsync(); var sendinBlueSettings = await _settingService.LoadSettingAsync <SendinBlueSettings>(storeId); //whether plugin is configured if (string.IsNullOrEmpty(sendinBlueSettings.ApiKey)) { return; } //prepare common properties model.ActiveStoreScopeConfiguration = storeId; model.ApiKey = sendinBlueSettings.ApiKey; model.ListId = sendinBlueSettings.ListId; model.SmtpKey = sendinBlueSettings.SmtpKey; model.SenderId = sendinBlueSettings.SenderId; model.UseSmsNotifications = sendinBlueSettings.UseSmsNotifications; model.SmsSenderName = sendinBlueSettings.SmsSenderName; model.StoreOwnerPhoneNumber = sendinBlueSettings.StoreOwnerPhoneNumber; model.UseMarketingAutomation = sendinBlueSettings.UseMarketingAutomation; model.TrackingScript = sendinBlueSettings.TrackingScript; model.HideGeneralBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinBlueDefaults.HideGeneralBlock); model.HideSynchronizationBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinBlueDefaults.HideSynchronizationBlock); model.HideTransactionalBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinBlueDefaults.HideTransactionalBlock); model.HideSmsBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinBlueDefaults.HideSmsBlock); model.HideMarketingAutomationBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinBlueDefaults.HideMarketingAutomationBlock); //prepare nested search models model.MessageTemplateSearchModel.SetGridPageSize(); model.SmsSearchModel.SetGridPageSize(); //prepare add SMS model model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(await _localizationService.GetResourceAsync("Plugins.Misc.SendinBlue.MyPhone"), "0")); model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(await _localizationService.GetResourceAsync("Plugins.Misc.SendinBlue.CustomerPhone"), "1")); model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(await _localizationService.GetResourceAsync("Plugins.Misc.SendinBlue.BillingAddressPhone"), "2")); model.AddSms.DefaultSelectedPhoneTypeId = model.AddSms.AvailablePhoneTypes.First().Value; var stores = await _storeService.GetAllStoresAsync(); var messageTemplates = await _messageTemplateService.GetAllMessageTemplatesAsync(storeId); model.AddSms.AvailableMessages = await messageTemplates.SelectAwait(async messageTemplate => { var name = messageTemplate.Name; if (storeId == 0 && messageTemplate.LimitedToStores) { var storeIds = await _storeMappingService.GetStoresIdsWithAccessAsync(messageTemplate); var storeNames = stores.Where(store => storeIds.Contains(store.Id)).Select(store => store.Name); name = $"{name} ({string.Join(',', storeNames)})"; } return(new SelectListItem(name, messageTemplate.Id.ToString())); }).ToListAsync(); var defaultSelectedMessage = model.AddSms.AvailableMessages.FirstOrDefault(); model.AddSms.DefaultSelectedMessageId = defaultSelectedMessage?.Value ?? "0"; //check whether email account exists if (sendinBlueSettings.UseSmtp && await _emailAccountService.GetEmailAccountByIdAsync(sendinBlueSettings.EmailAccountId) != null) { model.UseSmtp = sendinBlueSettings.UseSmtp; } //get account info var(accountInfo, marketingAutomationEnabled, maKey, accountErrors) = await _sendinBlueEmailManager.GetAccountInfoAsync(); model.AccountInfo = accountInfo; model.MarketingAutomationKey = maKey; model.MarketingAutomationDisabled = !marketingAutomationEnabled; if (!string.IsNullOrEmpty(accountErrors)) { _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {accountErrors}"); } //prepare overridable settings if (storeId > 0) { model.ListId_OverrideForStore = await _settingService.SettingExistsAsync(sendinBlueSettings, settings => settings.ListId, storeId); model.UseSmtp_OverrideForStore = await _settingService.SettingExistsAsync(sendinBlueSettings, settings => settings.UseSmtp, storeId); model.SenderId_OverrideForStore = await _settingService.SettingExistsAsync(sendinBlueSettings, settings => settings.SenderId, storeId); model.UseSmsNotifications_OverrideForStore = await _settingService.SettingExistsAsync(sendinBlueSettings, settings => settings.UseSmsNotifications, storeId); model.SmsSenderName_OverrideForStore = await _settingService.SettingExistsAsync(sendinBlueSettings, settings => settings.SmsSenderName, storeId); model.UseMarketingAutomation_OverrideForStore = await _settingService.SettingExistsAsync(sendinBlueSettings, settings => settings.UseMarketingAutomation, storeId); } //check SMTP status var(smtpEnabled, smtpErrors) = await _sendinBlueEmailManager.SmtpIsEnabledAsync(); if (!string.IsNullOrEmpty(smtpErrors)) { _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {smtpErrors}"); } //get available contact lists to synchronize var(lists, listsErrors) = await _sendinBlueEmailManager.GetListsAsync(); model.AvailableLists = lists.Select(list => new SelectListItem(list.Name, list.Id)).ToList(); model.AvailableLists.Insert(0, new SelectListItem("Select list", "0")); if (!string.IsNullOrEmpty(listsErrors)) { _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {listsErrors}"); } //get available senders of emails from account var(senders, sendersErrors) = await _sendinBlueEmailManager.GetSendersAsync(); model.AvailableSenders = senders.Select(list => new SelectListItem(list.Name, list.Id)).ToList(); model.AvailableSenders.Insert(0, new SelectListItem("Select sender", "0")); if (!string.IsNullOrEmpty(sendersErrors)) { _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {sendersErrors}"); } //get allowed tokens model.AllowedTokens = string.Join(", ", await _messageTokenProvider.GetListOfAllowedTokensAsync()); //create attributes in account var attributesErrors = await _sendinBlueEmailManager.PrepareAttributesAsync(); if (!string.IsNullOrEmpty(attributesErrors)) { _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {attributesErrors}"); } //try to set account partner if (!sendinBlueSettings.PartnerValueSet) { var partnerSet = await _sendinBlueEmailManager.SetPartnerAsync(); if (partnerSet) { sendinBlueSettings.PartnerValueSet = true; await _settingService.SaveSettingAsync(sendinBlueSettings, settings => settings.PartnerValueSet, clearCache : false); await _settingService.ClearCacheAsync(); } } }
/// <summary> /// Prepare paged low stock product list model /// </summary> /// <param name="searchModel">Low stock product search model</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the low stock product list model /// </returns> public virtual async Task <LowStockProductListModel> PrepareLowStockProductListModelAsync(LowStockProductSearchModel searchModel) { if (searchModel == null) { throw new ArgumentNullException(nameof(searchModel)); } //get parameters to filter comments var publishedOnly = searchModel.SearchPublishedId == 0 ? null : searchModel.SearchPublishedId == 1 ? true : (bool?)false; var vendorId = (await _workContext.GetCurrentVendorAsync())?.Id ?? 0; //get low stock product and product combinations var products = await _productService.GetLowStockProductsAsync(vendorId : vendorId, loadPublishedOnly : publishedOnly); var combinations = await _productService.GetLowStockProductCombinationsAsync(vendorId : vendorId, loadPublishedOnly : publishedOnly); //prepare low stock product models var lowStockProductModels = new List <LowStockProductModel>(); lowStockProductModels.AddRange(await products.SelectAwait(async product => new LowStockProductModel { Id = product.Id, Name = product.Name, ManageInventoryMethod = await _localizationService.GetLocalizedEnumAsync(product.ManageInventoryMethod), StockQuantity = await _productService.GetTotalStockQuantityAsync(product), Published = product.Published }).ToListAsync()); lowStockProductModels.AddRange(await combinations.SelectAwait(async combination => { var product = await _productService.GetProductByIdAsync(combination.ProductId); return(new LowStockProductModel { Id = combination.ProductId, Name = product.Name, Attributes = await _productAttributeFormatter .FormatAttributesAsync(product, combination.AttributesXml, await _workContext.GetCurrentCustomerAsync(), "<br />", true, true, true, false), ManageInventoryMethod = await _localizationService.GetLocalizedEnumAsync(product.ManageInventoryMethod), StockQuantity = combination.StockQuantity, Published = product.Published }); }).ToListAsync()); var pagesList = lowStockProductModels.ToPagedList(searchModel); //prepare list model var model = new LowStockProductListModel().PrepareToGrid(searchModel, pagesList, () => pagesList); return(model); }