Пример #1
0
        public async Task <IActionResult> ForgotPasswordConfirm(string token, string email)
        {
            var user = await _userService.GetUserByEmailAsync(email);

            if (user == null)
            {
                return(RedirectToRoute("Login"));
            }

            if (string.IsNullOrEmpty(await _genericAttributeService.GetAttributeAsync <string>(user, UserDefaults.PasswordRecoveryTokenAttribute)))
            {
                return(View(new ForgotPasswordConfirmViewModel
                {
                    DisablePasswordChanging = true,
                    Result = "Your password already has been changed. For changing it once more, you need to again recover the password."
                }));
            }

            var model = await _userAccountModelFactory.PrepareForgotPasswordConfirmModel();

            //validate token
            if (!await _userService.IsPasswordRecoveryTokenValidAsync(user, token))
            {
                model.DisablePasswordChanging = true;
                model.Result = "Wrong password recovery token";
            }

            if (await _userService.IsPasswordRecoveryLinkExpired(user))
            {
                model.DisablePasswordChanging = true;
                model.Result = "Your password recovery link is expired";
            }

            return(View(model));
        }
Пример #2
0
        /// <returns>A task that represents the asynchronous operation</returns>
        public virtual async Task <IActionResult> Providers(bool showtour = false)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedView());
            }

            //prepare model
            var model = await _taxModelFactory.PrepareTaxProviderSearchModelAsync(new TaxProviderSearchModel());

            //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));
        }
Пример #3
0
        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 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(model));
        }
        public async Task <IActionResult> CustomerDetails()
        {
            var customer = await _workContext.GetCurrentCustomerAsync();

            if (customer == null)
            {
                return(Ok(new { success = false, message = await _localizationService.GetResourceAsync("Customer.Not.Found") }));
            }

            var shippingAddress = customer.ShippingAddressId.HasValue ? await _addressService.GetAddressByIdAsync(customer.ShippingAddressId.Value) : null;

            var firstName = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.FirstNameAttribute);

            var lastName = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.LastNameAttribute);

            return(Ok(new
            {
                success = true,
                message = await _localizationService.GetResourceAsync("Customer.Login.Successfully"),
                pushToken = customer.PushToken,
                shippingAddress,
                firstName,
                lastName,
                RemindMeNotification = customer.RemindMeNotification,
                RateReminderNotification = customer.RateReminderNotification,
                OrderStatusNotification = customer.OrderStatusNotification,
                avatar = await _pictureService.GetPictureUrlAsync(await _genericAttributeService.GetAttributeAsync <int>(customer, NopCustomerDefaults.AvatarPictureIdAttribute), _mediaSettings.AvatarPictureSize, true)
            }));
        }
Пример #5
0
        /// <summary>
        /// Get full name
        /// </summary>
        public async Task <string> GetUserFullNameAsync(User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var firstName = await _genericAttributeService.GetAttributeAsync <string>(user, UserDefaults.FirstNameAttribute);

            var lastName = await _genericAttributeService.GetAttributeAsync <string>(user, UserDefaults.LastNameAttribute);

            var fullName = string.Empty;

            if (!string.IsNullOrWhiteSpace(firstName) && !string.IsNullOrWhiteSpace(lastName))
            {
                fullName = $"{firstName} {lastName}";
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(firstName))
                {
                    fullName = firstName;
                }

                if (!string.IsNullOrWhiteSpace(lastName))
                {
                    fullName = lastName;
                }
            }

            return(fullName);
        }
Пример #6
0
        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);
                }
            }

            //prepare model
            var model = await _homeModelFactory.PrepareDashboardModelAsync(new DashboardModel());

            return(View(model));
        }
Пример #7
0
        /// <summary>
        /// Get a value indicating whether a customer is consumer (a person, not a company) located in Europe Union
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the result
        /// </returns>
        protected virtual async Task <bool> IsEuConsumerAsync(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            Country country = null;

            //get country from billing address
            if (_addressSettings.CountryEnabled && await _customerService.GetCustomerShippingAddressAsync(customer) is Address billingAddress)
            {
                country = await _countryService.GetCountryByAddressAsync(billingAddress);
            }

            //get country specified during registration?
            if (country == null && _customerSettings.CountryEnabled)
            {
                var countryId = await _genericAttributeService.GetAttributeAsync <Customer, int>(customer.Id, NopCustomerDefaults.CountryIdAttribute);

                country = await _countryService.GetCountryByIdAsync(countryId);
            }

            //get country by IP address
            if (country == null)
            {
                var ipAddress      = _webHelper.GetCurrentIpAddress();
                var countryIsoCode = _geoLookupService.LookupCountryIsoCode(ipAddress);
                country = await _countryService.GetCountryByTwoLetterIsoCodeAsync(countryIsoCode);
            }

            //we cannot detect country
            if (country == null)
            {
                return(false);
            }

            //outside EU
            if (!country.SubjectToVat)
            {
                return(false);
            }

            //company (business) or consumer?
            var customerVatStatus = (VatNumberStatus)await _genericAttributeService.GetAttributeAsync <int>(customer, NopCustomerDefaults.VatNumberStatusIdAttribute);

            if (customerVatStatus == VatNumberStatus.Valid)
            {
                return(false);
            }

            //consumer
            return(true);
        }
        /// <summary>
        /// Send SMS notification by message template
        /// </summary>
        /// <param name="messageTemplate">Message template</param>
        /// <param name="tokens">Tokens</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        private async Task SendSmsNotificationAsync(MessageTemplate messageTemplate, IEnumerable <Token> tokens)
        {
            //get plugin settings
            var storeId            = (int?)tokens.FirstOrDefault(token => token.Key == "Store.Id")?.Value;
            var sendinblueSettings = await _settingService.LoadSettingAsync <SendinblueSettings>(storeId ?? 0);

            //ensure SMS notifications enabled
            if (!sendinblueSettings.UseSmsNotifications)
            {
                return;
            }

            //whether to send SMS by the passed message template
            var sendSmsForThisMessageTemplate = await _genericAttributeService
                                                .GetAttributeAsync <bool>(messageTemplate, SendinblueDefaults.UseSmsAttribute);

            if (!sendSmsForThisMessageTemplate)
            {
                return;
            }

            //get text with replaced tokens
            var text = await _genericAttributeService.GetAttributeAsync <string>(messageTemplate, SendinblueDefaults.SmsTextAttribute);

            if (!string.IsNullOrEmpty(text))
            {
                text = _tokenizer.Replace(text, tokens, false);
            }

            //get phone number send to
            var phoneNumberTo = string.Empty;
            var phoneType     = await _genericAttributeService.GetAttributeAsync <int>(messageTemplate, SendinblueDefaults.PhoneTypeAttribute);

            switch (phoneType)
            {
            case 0:
                //merchant phone
                phoneNumberTo = sendinblueSettings.StoreOwnerPhoneNumber;
                break;

            case 1:
                //customer phone
                phoneNumberTo = tokens.FirstOrDefault(token => token.Key == "Customer.PhoneNumber")?.Value?.ToString();
                break;

            case 2:
                //order billing address phone
                phoneNumberTo = tokens.FirstOrDefault(token => token.Key == "Order.BillingPhoneNumber")?.Value?.ToString();
                break;
            }

            //try to send SMS
            await _sendinblueEmailManager.SendSMSAsync(phoneNumberTo, sendinblueSettings.SmsSenderName, text);
        }
Пример #9
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            if (!_storeInformationSettings.DisplayEuCookieLawWarning)
            {
                //disabled
                return(Content(""));
            }

            //ignore search engines because some pages could be indexed with the EU cookie as description
            if ((await _workContext.GetCurrentCustomerAsync()).IsSearchEngineAccount())
            {
                return(Content(""));
            }

            if (await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.EuCookieLawAcceptedAttribute, (await _storeContext.GetCurrentStoreAsync()).Id))
            {
                //already accepted
                return(Content(""));
            }

            //ignore notification?
            //right now it's used during logout so popup window is not displayed twice
            if (TempData[$"{NopCookieDefaults.Prefix}{NopCookieDefaults.IgnoreEuCookieLawWarning}"] != null && Convert.ToBoolean(TempData[$"{NopCookieDefaults.Prefix}{NopCookieDefaults.IgnoreEuCookieLawWarning}"]))
            {
                return(Content(""));
            }

            return(View());
        }
        public async Task SetUp()
        {
            _genericAttributeService = GetService <IGenericAttributeService>();
            _dateTimeSettings        = GetService <DateTimeSettings>();
            _dateTimeHelper          = GetService <IDateTimeHelper>();
            _settingService          = GetService <ISettingService>();

            _customer = await GetService <ICustomerService>().GetCustomerByEmailAsync(NopTestsDefaults.AdminEmail);

            _defaultTimeZone = await _genericAttributeService.GetAttributeAsync <string>(_customer, NopCustomerDefaults.TimeZoneIdAttribute);

            _defaultAllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone;
            _defaultDefaultStoreTimeZoneId      = _dateTimeSettings.DefaultStoreTimeZoneId;

            _gmtPlus2MinskTimeZoneId       = "E. Europe Standard Time";  //(GMT+02:00) Minsk
            _gmtPlus3MoscowTimeZoneId      = "Russian Standard Time";    //(GMT+03:00) Moscow, St. Petersburg, Volgograd
            _gmtPlus7KrasnoyarskTimeZoneId = "North Asia Standard Time"; //(GMT+07:00) Krasnoyarsk;

            if (Environment.OSVersion.Platform != PlatformID.Unix)
            {
                return;
            }

            _gmtPlus2MinskTimeZoneId       = "Europe/Minsk";     //(GMT+02:00) Minsk;
            _gmtPlus3MoscowTimeZoneId      = "Europe/Moscow";    //(GMT+03:00) Moscow, St. Petersburg, Volgograd
            _gmtPlus7KrasnoyarskTimeZoneId = "Asia/Krasnoyarsk"; //(GMT+07:00) Krasnoyarsk;
        }
            /// <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 ValidateAuthenticationForceAsync(ActionExecutingContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

                if (context.HttpContext.Request == null)
                {
                    return;
                }

                if (!DataSettingsManager.IsDatabaseInstalled())
                {
                    return;
                }

                //validate only for registered customers
                var customer = await _workContext.GetCurrentCustomerAsync();

                if (!await _customerService.IsRegisteredAsync(customer))
                {
                    return;
                }

                //don't validate on the 'Multi-factor authentication settings' page
                var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
                var actionName       = actionDescriptor?.ActionName;
                var controllerName   = actionDescriptor?.ControllerName;

                if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName))
                {
                    return;
                }

                if (controllerName.Equals("Customer", StringComparison.InvariantCultureIgnoreCase) &&
                    actionName.Equals("MultiFactorAuthentication", StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                //whether the feature is enabled
                if (!_multiFactorAuthenticationSettings.ForceMultifactorAuthentication ||
                    !await _multiFactorAuthenticationPluginManager.HasActivePluginsAsync())
                {
                    return;
                }

                //check selected provider of MFA
                var selectedProvider = await _genericAttributeService
                                       .GetAttributeAsync <string>(customer, NopCustomerDefaults.SelectedMultiFactorAuthenticationProviderAttribute);

                if (!string.IsNullOrEmpty(selectedProvider))
                {
                    return;
                }

                //redirect to MultiFactorAuthenticationSettings page if force is enabled
                context.Result = new RedirectToRouteResult("MultiFactorAuthenticationSettings", null);
            }
Пример #12
0
        /// <summary>
        /// Handle the customer tokens added event
        /// </summary>
        /// <param name="eventMessage">The event message.</param>
        public async Task HandleEventAsync(EntityTokensAddedEvent <Customer, Token> eventMessage)
        {
            //handle event
            var phone = await _genericAttributeService.GetAttributeAsync <string>(eventMessage.Entity, NopCustomerDefaults.PhoneAttribute);

            eventMessage.Tokens.Add(new Token("Customer.PhoneNumber", phone));
        }
Пример #13
0
        /// <summary>
        /// Gets active store scope configuration
        /// </summary>
        public virtual async Task <int> GetActiveStoreScopeConfigurationAsync()
        {
            if (_cachedActiveStoreScopeConfiguration.HasValue)
            {
                return(_cachedActiveStoreScopeConfiguration.Value);
            }

            //ensure that we have 2 (or more) stores
            if ((await _storeService.GetAllStoresAsync()).Count > 1)
            {
                //do not inject IWorkContext via constructor because it'll cause circular references
                var currentCustomer = await EngineContext.Current.Resolve <IWorkContext>().GetCurrentCustomerAsync();

                //try to get store identifier from attributes
                var storeId = await _genericAttributeService
                              .GetAttributeAsync <int>(currentCustomer, NopCustomerDefaults.AdminAreaStoreScopeConfigurationAttribute);

                _cachedActiveStoreScopeConfiguration = (await _storeService.GetStoreByIdAsync(storeId))?.Id ?? 0;
            }
            else
            {
                _cachedActiveStoreScopeConfiguration = 0;
            }

            return(_cachedActiveStoreScopeConfiguration ?? 0);
        }
Пример #14
0
        /// <summary>
        /// Prepare blog comment model
        /// </summary>
        /// <param name="blogComment">Blog comment entity</param>
        /// <returns>Blog comment model</returns>
        protected virtual async Task <BlogCommentModel> PrepareBlogPostCommentModelAsync(BlogComment blogComment)
        {
            if (blogComment == null)
            {
                throw new ArgumentNullException(nameof(blogComment));
            }

            var customer = await _customerService.GetCustomerByIdAsync(blogComment.CustomerId);

            var model = new BlogCommentModel
            {
                Id                   = blogComment.Id,
                CustomerId           = blogComment.CustomerId,
                CustomerName         = await _customerService.FormatUsernameAsync(customer),
                CommentText          = blogComment.CommentText,
                CreatedOn            = await _dateTimeHelper.ConvertToUserTimeAsync(blogComment.CreatedOnUtc, DateTimeKind.Utc),
                AllowViewingProfiles = _customerSettings.AllowViewingProfiles && customer != null && !await _customerService.IsGuestAsync(customer)
            };

            if (_customerSettings.AllowCustomersToUploadAvatars)
            {
                model.CustomerAvatarUrl = await _pictureService.GetPictureUrlAsync(
                    await _genericAttributeService.GetAttributeAsync <int>(customer, NopCustomerDefaults.AvatarPictureIdAttribute),
                    _mediaSettings.AvatarPictureSize, _customerSettings.DefaultAvatarEnabled, defaultPictureType : PictureType.Avatar);
            }

            return(model);
        }
Пример #15
0
        /// <summary>
        /// Prepare the vendor info model
        /// </summary>
        /// <param name="model">Vendor info model</param>
        /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
        /// <param name="overriddenVendorAttributesXml">Overridden vendor attributes in XML format; pass null to use VendorAttributes of vendor</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the vendor info model
        /// </returns>
        public virtual async Task <VendorInfoModel> PrepareVendorInfoModelAsync(VendorInfoModel model,
                                                                                bool excludeProperties, string overriddenVendorAttributesXml = "")
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var vendor = await _workContext.GetCurrentVendorAsync();

            if (!excludeProperties)
            {
                model.Description = vendor.Description;
                model.Email       = vendor.Email;
                model.Name        = vendor.Name;
            }

            var picture = await _pictureService.GetPictureByIdAsync(vendor.PictureId);

            var pictureSize = _mediaSettings.AvatarPictureSize;

            (model.PictureUrl, _) = picture != null ? await _pictureService.GetPictureUrlAsync(picture, pictureSize) : (string.Empty, null);

            //vendor attributes
            if (string.IsNullOrEmpty(overriddenVendorAttributesXml))
            {
                overriddenVendorAttributesXml = await _genericAttributeService.GetAttributeAsync <string>(vendor, NopVendorDefaults.VendorAttributes);
            }
            model.VendorAttributes = await PrepareVendorAttributesAsync(overriddenVendorAttributesXml);

            return(model);
        }
Пример #16
0
        /// <summary>
        /// Gets a customer time zone
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <returns>Customer time zone; if customer is null, then default store time zone</returns>
        public virtual async Task <TimeZoneInfo> GetCustomerTimeZoneAsync(Customer customer)
        {
            if (!_dateTimeSettings.AllowCustomersToSetTimeZone)
            {
                return(DefaultStoreTimeZone);
            }

            TimeZoneInfo timeZoneInfo = null;

            var timeZoneId = string.Empty;

            if (customer != null)
            {
                timeZoneId = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.TimeZoneIdAttribute);
            }

            try
            {
                if (!string.IsNullOrEmpty(timeZoneId))
                {
                    timeZoneInfo = FindTimeZoneById(timeZoneId);
                }
            }
            catch (Exception exc)
            {
                Debug.Write(exc.ToString());
            }

            return(timeZoneInfo ?? DefaultStoreTimeZone);
        }
        public async Task HandleEventAsync(CustomerRegisteredEvent eventMessage)
        {
            var customer = eventMessage.Customer;

            if (IsServiceTitanEmail(customer.Email))
            {
                await AddAddress(customer, new Address
                {
                    FirstName       = "Melik Adamyan 2/2",
                    LastName        = "3rd floor",
                    Email           = customer.Email,
                    Company         = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.CompanyAttribute),
                    CountryId       = (await _countryService.GetCountryByTwoLetterIsoCodeAsync("AM")).Id,
                    StateProvinceId = null,
                    County          = "",
                    City            = "Yerevan",
                    Address1        = "Melik Adamyan 2/2",
                    Address2        = "3rd floor",
                    ZipPostalCode   = "0010",
                    PhoneNumber     = "+374-99-094095",
                    FaxNumber       = "",
                    CreatedOnUtc    = customer.CreatedOnUtc
                }, true);

                await AddAddress(customer, new Address
                {
                    FirstName       = "Leo 1",
                    LastName        = "2nd floor",
                    Email           = customer.Email,
                    Company         = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.CompanyAttribute),
                    CountryId       = (await _countryService.GetCountryByTwoLetterIsoCodeAsync("AM")).Id,
                    StateProvinceId = null,
                    County          = "",
                    City            = "Yerevan",
                    Address1        = "Leo 1",
                    Address2        = "2nd floor",
                    ZipPostalCode   = "0010",
                    PhoneNumber     = "+374-99-094095",
                    FaxNumber       = "",
                    CreatedOnUtc    = customer.CreatedOnUtc
                }, false);
            }
        }
Пример #18
0
        public async Task <SettingModeModel> PrepareSettingModeModel(string modeName)
        {
            var model = new SettingModeModel
            {
                ModeName = modeName,
                Enabled  = await _genericAttributeService.GetAttributeAsync <bool>(_workContext.CurrentUser, modeName)
            };

            return(model);
        }
Пример #19
0
        public virtual async Task <IActionResult> Index()
        {
            //display a warning to a store owner if there are some error
            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) && 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 currentLanguage = await _workContext.GetWorkingLanguageAsync();

            var progress = await _genericAttributeService.GetAttributeAsync <string>(currentLanguage, 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(currentLanguage, NopCommonDefaults.LanguagePackProgressAttribute, string.Empty);
            }

            //prepare model
            var model = await _homeModelFactory.PrepareDashboardModelAsync(new DashboardModel());

            return(View(model));
        }
        /// <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 what3words widget is active and enabled
            var customer = await _workContext.GetCurrentCustomerAsync();

            if (!await _widgetPluginManager.IsPluginActiveAsync(What3wordsDefaults.SystemName, customer))
            {
                return(Content(string.Empty));
            }

            if (!_what3WordsSettings.Enabled)
            {
                return(Content(string.Empty));
            }

            var summaryModel = additionalData as ShoppingCartModel.OrderReviewDataModel;
            var detailsModel = additionalData as OrderDetailsModel;

            if (summaryModel is null && detailsModel is null)
            {
                return(Content(string.Empty));
            }

            var addressId = 0;

            if (widgetZone.Equals(PublicWidgetZones.OrderSummaryBillingAddress))
            {
                addressId = summaryModel.BillingAddress.Id;
            }
            if (widgetZone.Equals(PublicWidgetZones.OrderSummaryShippingAddress))
            {
                addressId = summaryModel.ShippingAddress.Id;
            }
            if (widgetZone.Equals(PublicWidgetZones.OrderDetailsBillingAddress))
            {
                addressId = detailsModel.BillingAddress.Id;
            }
            if (widgetZone.Equals(PublicWidgetZones.OrderDetailsShippingAddress))
            {
                addressId = detailsModel.ShippingAddress.Id;
            }
            var address = await _addressService.GetAddressByIdAsync(addressId);

            var addressValue = address is not null
                ? await _genericAttributeService.GetAttributeAsync <string>(address, What3wordsDefaults.AddressValueAttribute)
                : null;

            if (string.IsNullOrEmpty(addressValue))
            {
                return(Content(string.Empty));
            }

            return(View("~/Plugins/Widgets.What3words/Views/PublicOrderAddress.cshtml", addressValue));
        }
Пример #21
0
        public async Task PrepareAddressModelShouldFillCustomersInfoIfPrePopulateWithCustomerFieldsFlagEnabledAndCustomerPassed()
        {
            var model = new AddressModel();
            var customer = await GetService<IWorkContext>().GetCurrentCustomerAsync();
            await _addressModelFactory.PrepareAddressModelAsync(model, null, false, _addressSettings,
                prePopulateWithCustomerFields: true, customer: customer);

            model.Email.Should().Be(customer.Email);
            model.FirstName.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.FirstNameAttribute));
            model.LastName.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.LastNameAttribute));

            model.Company.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.CompanyAttribute));
            model.Address1.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.StreetAddressAttribute));
            model.Address2.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.StreetAddress2Attribute));
            model.ZipPostalCode.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute));
            model.City.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.CityAttribute));
            model.County.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.CountyAttribute));
            model.PhoneNumber.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.PhoneAttribute));
            model.FaxNumber.Should().Be(await _genericAttributeService.GetAttributeAsync<string>(customer, NopCustomerDefaults.FaxAttribute));
        }
        /// <returns>A task that represents the asynchronous operation</returns>
        public override async Task <IActionResult> Categories(TaxCategorySearchModel searchModel)
        {
            //ensure that Avalara tax provider is active
            if (!await _taxPluginManager.IsPluginActiveAsync(AvalaraTaxDefaults.SystemName))
            {
                return(await base.Categories(searchModel));
            }

            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings))
            {
                return(await AccessDeniedDataTablesJson());
            }

            //get tax categories
            var taxCategories = (await _taxCategoryService.GetAllTaxCategoriesAsync()).ToPagedList(searchModel);

            //get tax types and define the default value
            var cacheKey = _cacheManager.PrepareKeyForDefaultCache(AvalaraTaxDefaults.TaxCodeTypesCacheKey);
            var taxTypes = (await _cacheManager.GetAsync(cacheKey, async() => await _avalaraTaxManager.GetTaxCodeTypesAsync()))
                           ?.Select(taxType => new { Id = taxType.Key, Name = taxType.Value });
            var defaultType = taxTypes
                              ?.FirstOrDefault(taxType => taxType.Name.Equals("Unknown", StringComparison.InvariantCultureIgnoreCase))
                              ?? taxTypes?.FirstOrDefault();

            //prepare grid model
            var model = await new Models.Tax.TaxCategoryListModel().PrepareToGridAsync(searchModel, taxCategories, () =>
            {
                //fill in model values from the entity
                return(taxCategories.SelectAwait(async taxCategory =>
                {
                    //fill in model values from the entity
                    var taxCategoryModel = new Models.Tax.TaxCategoryModel
                    {
                        Id = taxCategory.Id,
                        Name = taxCategory.Name,
                        DisplayOrder = taxCategory.DisplayOrder
                    };

                    //try to get previously saved tax code type and description
                    var taxCodeType = (await taxTypes?.FirstOrDefaultAwaitAsync(async type =>
                                                                                type.Id.Equals((await _genericAttributeService.GetAttributeAsync <string>(taxCategory, AvalaraTaxDefaults.TaxCodeTypeAttribute)) ?? string.Empty)))
                                      ?? defaultType;
                    taxCategoryModel.Type = taxCodeType?.Name ?? string.Empty;
                    taxCategoryModel.TypeId = taxCodeType?.Id ?? Guid.Empty.ToString();
                    taxCategoryModel.Description = (await _genericAttributeService
                                                    .GetAttributeAsync <string>(taxCategory, AvalaraTaxDefaults.TaxCodeDescriptionAttribute)) ?? string.Empty;

                    return taxCategoryModel;
                }));
            });

            return(Json(model));
        }
        private async Task <string> GetProductDescriptionAsync(Product product)
        {
            var plpDescription = await _genericAttributeService.GetAttributeAsync <Product, string>(
                product.Id, "PLPDescription");

            if (plpDescription != null)
            {
                return(plpDescription);
            }

            var pad = await _productAbcDescriptionService.GetProductAbcDescriptionByProductIdAsync(product.Id);

            return(pad != null ? pad.AbcDescription : product.ShortDescription);
        }
Пример #24
0
        /// <summary>
        /// Prepare the header links model
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the header links model
        /// </returns>
        public virtual async Task <HeaderLinksModel> PrepareHeaderLinksModelAsync()
        {
            var customer = await _workContext.GetCurrentCustomerAsync();

            var store = await _storeContext.GetCurrentStoreAsync();

            var unreadMessageCount = await GetUnreadPrivateMessagesAsync();

            var unreadMessage = string.Empty;
            var alertMessage  = string.Empty;

            if (unreadMessageCount > 0)
            {
                unreadMessage = string.Format(await _localizationService.GetResourceAsync("PrivateMessages.TotalUnread"), unreadMessageCount);

                //notifications here
                if (_forumSettings.ShowAlertForPM &&
                    !await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.NotifiedAboutNewPrivateMessagesAttribute, store.Id))
                {
                    await _genericAttributeService.SaveAttributeAsync(customer, NopCustomerDefaults.NotifiedAboutNewPrivateMessagesAttribute, true, store.Id);

                    alertMessage = string.Format(await _localizationService.GetResourceAsync("PrivateMessages.YouHaveUnreadPM"), unreadMessageCount);
                }
            }

            var model = new HeaderLinksModel
            {
                RegistrationType      = _customerSettings.UserRegistrationType,
                IsAuthenticated       = await _customerService.IsRegisteredAsync(customer),
                CustomerName          = await _customerService.IsRegisteredAsync(customer) ? await _customerService.FormatUsernameAsync(customer) : string.Empty,
                ShoppingCartEnabled   = await _permissionService.AuthorizeAsync(StandardPermissionProvider.EnableShoppingCart),
                WishlistEnabled       = await _permissionService.AuthorizeAsync(StandardPermissionProvider.EnableWishlist),
                AllowPrivateMessages  = await _customerService.IsRegisteredAsync(customer) && _forumSettings.AllowPrivateMessages,
                UnreadPrivateMessages = unreadMessage,
                AlertMessage          = alertMessage,
            };

            //performance optimization (use "HasShoppingCartItems" property)
            if (customer.HasShoppingCartItems)
            {
                model.ShoppingCartItems = (await _shoppingCartService.GetShoppingCartAsync(customer, ShoppingCartType.ShoppingCart, store.Id))
                                          .Sum(item => item.Quantity);

                model.WishlistItems = (await _shoppingCartService.GetShoppingCartAsync(customer, ShoppingCartType.Wishlist, store.Id))
                                      .Sum(item => item.Quantity);
            }

            return(model);
        }
Пример #25
0
        public async Task <IViewComponentResult> InvokeAsync(string widgetZone, ProductModel additionalData = null)
        {
            var productId      = additionalData.Id;
            var plpDescription = await _genericAttributeService.GetAttributeAsync <Product, string>(
                productId, "PLPDescription"
                );

            var model = new ABCProductDetailsModel
            {
                ProductId      = productId,
                PLPDescription = plpDescription
            };

            return(View("~/Plugins/Misc.AbcCore/Views/ProductDetails.cshtml", model));
        }
Пример #26
0
        /// <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));
        }
Пример #27
0
        private async Task <decimal> GetPaymentMethodAdditionalFeeTaxAsync(
            SortedDictionary <decimal, decimal> taxRates,
            TaxTotalRequest taxTotalRequest
            )
        {
            var paymentMethodAdditionalFeeTax = decimal.Zero;

            if (_taxSettings.PaymentMethodAdditionalFeeIsTaxable)
            {
                var paymentMethodSystemName = taxTotalRequest.Customer != null
                    ? await _genericAttributeService
                                              .GetAttributeAsync <string>(taxTotalRequest.Customer, NopCustomerDefaults.SelectedPaymentMethodAttribute, taxTotalRequest.StoreId)
                    : string.Empty;

                var paymentMethodAdditionalFee = await _paymentService
                                                 .GetAdditionalHandlingFeeAsync(taxTotalRequest.ShoppingCart, paymentMethodSystemName);

                var(paymentMethodAdditionalFeeExclTax, _) = await _taxService
                                                            .GetPaymentMethodAdditionalFeeAsync(paymentMethodAdditionalFee, false, taxTotalRequest.Customer);

                var(paymentMethodAdditionalFeeInclTax, taxRate) = await _taxService
                                                                  .GetPaymentMethodAdditionalFeeAsync(paymentMethodAdditionalFee, true, taxTotalRequest.Customer);

                paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;
                if (paymentMethodAdditionalFeeTax < decimal.Zero)
                {
                    paymentMethodAdditionalFeeTax = decimal.Zero;
                }

                if (taxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(taxRate))
                    {
                        taxRates.Add(taxRate, paymentMethodAdditionalFeeTax);
                    }
                    else
                    {
                        taxRates[taxRate] = taxRates[taxRate] + paymentMethodAdditionalFeeTax;
                    }
                }
            }
            return(paymentMethodAdditionalFeeTax);
        }
Пример #28
0
        /// <summary>
        /// Handle order placed event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        public async Task HandleEventAsync(OrderPlacedEvent eventMessage)
        {
            if (eventMessage.Order is null)
            {
                return;
            }

            var customer = await _customerService.GetCustomerByIdAsync(eventMessage.Order.CustomerId);

            if (!await _widgetPluginManager.IsPluginActiveAsync(What3wordsDefaults.SystemName, customer))
            {
                return;
            }

            if (!_what3WordsSettings.Enabled)
            {
                return;
            }

            async Task copyAddressValueAsync(int?customerAddressId, int?orderAddressId)
            {
                var customerAddress = await _addressService.GetAddressByIdAsync(customerAddressId ?? 0);

                var addressValue = customerAddress is not null
                    ? await _genericAttributeService.GetAttributeAsync <string>(customerAddress, What3wordsDefaults.AddressValueAttribute)
                    : null;

                if (!string.IsNullOrEmpty(addressValue))
                {
                    var orderAddress = await _addressService.GetAddressByIdAsync(orderAddressId ?? 0);

                    if (orderAddress is not null)
                    {
                        await _genericAttributeService.SaveAttributeAsync(orderAddress, What3wordsDefaults.AddressValueAttribute, addressValue);
                    }
                }
            }

            //copy values from customer addresses to order addresses for next use
            await copyAddressValueAsync(customer.BillingAddressId, eventMessage.Order.BillingAddressId);
            await copyAddressValueAsync(customer.ShippingAddressId, eventMessage.Order.ShippingAddressId);
        }
        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));
        }
Пример #30
0
        /// <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 what3words widget is active and enabled
            if (!await _widgetPluginManager.IsPluginActiveAsync(What3wordsDefaults.SystemName))
            {
                return(Content(string.Empty));
            }

            if (!_what3WordsSettings.Enabled)
            {
                return(Content(string.Empty));
            }

            if (additionalData is not OrderModel model)
            {
                return(Content(string.Empty));
            }

            var addressId = 0;

            if (widgetZone.Equals(AdminWidgetZones.OrderBillingAddressDetailsBottom))
            {
                addressId = model.BillingAddress.Id;
            }
            if (widgetZone.Equals(AdminWidgetZones.OrderShippingAddressDetailsBottom))
            {
                addressId = model.ShippingAddress.Id;
            }
            var address = await _addressService.GetAddressByIdAsync(addressId);

            var addressValue = address is not null
                ? await _genericAttributeService.GetAttributeAsync <string>(address, What3wordsDefaults.AddressValueAttribute)
                : null;

            if (string.IsNullOrEmpty(addressValue))
            {
                return(Content(string.Empty));
            }

            return(View("~/Plugins/Widgets.What3words/Views/AdminOrderAddress.cshtml", addressValue));
        }