Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

SaveLastVisitedPageAttribute.cs

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Nop.Core;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Http.Extensions;
using Nop.Data;
using Nop.Services.Common;

namespace Nop.Web.Framework.Mvc.Filters;

/// 
/// Represents filter attribute that saves last visited page by customer
/// 
public sealed class SaveLastVisitedPageAttribute : TypeFilterAttribute
{
    #region Ctor

    /// 
    /// Create instance of the filter attribute
    /// 
    public SaveLastVisitedPageAttribute() : base(typeof(SaveLastVisitedPageFilter))
    {
    }

    #endregion

    #region Nested filter

    /// 
    /// Represents a filter that saves last visited page by customer
    /// 
    private class SaveLastVisitedPageFilter : IAsyncActionFilter
    {
        #region Fields

        protected readonly CustomerSettings _customerSettings;
        protected readonly IGenericAttributeService _genericAttributeService;
        protected readonly IRepository _genericAttributeRepository;
        protected readonly IWebHelper _webHelper;
        protected readonly IWorkContext _workContext;

        #endregion

        #region Ctor

        public SaveLastVisitedPageFilter(CustomerSettings customerSettings,
            IGenericAttributeService genericAttributeService,
            IRepository genericAttributeRepository,
            IWebHelper webHelper,
            IWorkContext workContext)
        {
            _customerSettings = customerSettings;
            _genericAttributeService = genericAttributeService;
            _genericAttributeRepository = genericAttributeRepository;
            _webHelper = webHelper;
            _workContext = workContext;
        }

        #endregion

        #region Utilities

        /// 
        /// Called asynchronously before the action, after model binding is complete.
        /// 
        /// A context for action filters
        /// A task that represents the asynchronous operation
        private async Task SaveLastVisitedPageAsync(ActionExecutingContext context)
        {
            ArgumentNullException.ThrowIfNull(context);

            //only in GET requests
            if (!context.HttpContext.Request.IsGetRequest())
                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);
            }
        }

        #endregion

        #region Methods

        /// 
        /// Called asynchronously before the action, after model binding is complete.
        /// 
        /// A context for action filters
        /// A delegate invoked to execute the next action filter or the action itself
        /// A task that represents the asynchronous operation
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            await SaveLastVisitedPageAsync(context);
            if (context.Result == null)
                await next();
        }

        #endregion
    }

    #endregion
}