Webiant Logo Webiant Logo
  1. No results found.

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

EventConsumer.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Domain.Orders;
using Nop.Core.Events;
using Nop.Core.Http;
using Nop.Data;
using Nop.Plugin.Misc.RFQ.Domains;
using Nop.Services.Cms;
using Nop.Services.Events;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Web.Framework.Events;
using Nop.Web.Framework.Menu;
using Nop.Web.Framework.Models;
using Nop.Web.Models.ShoppingCart;

namespace Nop.Plugin.Misc.RFQ.Services;

/// 
/// Represents plugin event consumer
/// 
public class EventConsumer : IConsumer,
    IConsumer,
    IConsumer>,
    IConsumer>,
    IConsumer>,
    IConsumer
{
    #region Fields

    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ILocalizationService _localizationService;
    private readonly IRepository _shoppingCartItemsRepository;
    private readonly IShoppingCartService _shoppingCartService;
    private readonly IShortTermCacheManager _shortTermCacheManager;
    private readonly IStoreContext _storeContext;
    private readonly IWidgetPluginManager _pluginManager;
    private readonly IWorkContext _workContext;
    private readonly RfqService _rfqService;
    private readonly RfqSettings _rfqSettings;

    #endregion

    #region Ctor

    public EventConsumer(IHttpContextAccessor httpContextAccessor,
        ILocalizationService localizationService,
        IRepository shoppingCartItemsRepository,
        IShoppingCartService shoppingCartService,
        IShortTermCacheManager shortTermCacheManager,
        IStoreContext storeContext,
        IWidgetPluginManager pluginManager,
        IWorkContext workContext,
        RfqService rfqService,
        RfqSettings rfqSettings)
    {
        _httpContextAccessor = httpContextAccessor;
        _localizationService = localizationService;
        _pluginManager = pluginManager;
        _shoppingCartItemsRepository = shoppingCartItemsRepository;
        _shoppingCartService = shoppingCartService;
        _shortTermCacheManager = shortTermCacheManager;
        _storeContext = storeContext;
        _workContext = workContext;
        _rfqService = rfqService;
        _rfqSettings = rfqSettings;
    }

    #endregion

    #region Methods

    /// 
    /// Handle admin menu created event
    /// 
    /// Event message
    /// A task that represents the asynchronous operation
    public async Task HandleEventAsync(AdminMenuCreatedEvent eventMessage)
    {
        var plugin = await _pluginManager.LoadPluginBySystemNameAsync(RfqDefaults.SystemName);
        
        //the LoadPluginBySystemNameAsync method returns only plugins that are already fully installed,
        //while the IConsumer event can be called before the installation is complete
        if (plugin == null || !_pluginManager.IsPluginActive(plugin))
            return;

        var menuItemSystemName = "Current shopping carts and wishlists";

        var baseMenuItem = eventMessage.RootMenuItem.GetItemBySystemName("Sales");
        baseMenuItem.InsertAfter(menuItemSystemName, new AdminMenuItem
        {
            Visible = true,
            SystemName = RfqDefaults.QuotesAdminMenuSystemName,
            Title = await _localizationService.GetResourceAsync("Plugins.Misc.RFQ.Quotes"),
            Url = eventMessage.GetMenuItemUrl("RfqAdmin", "AdminQuotes"),
            IconClass = "far fa-dot-circle",
            PermissionNames = new List { RfqPermissionConfigManager.ADMIN_ACCESS_RFQ }
        });
        baseMenuItem.InsertAfter(menuItemSystemName, new AdminMenuItem
        {
            Visible = true,
            SystemName = RfqDefaults.RequestsAdminMenuSystemName,
            Title = await _localizationService.GetResourceAsync("Plugins.Misc.RFQ.RequestsQuote"),
            Url = eventMessage.GetMenuItemUrl("RfqAdmin", "AdminRequests"),
            IconClass = "far fa-dot-circle",
            PermissionNames = new List { RfqPermissionConfigManager.ADMIN_ACCESS_RFQ }
        });
    }

    /// 
    /// Handle get shopping cart item unit price event
    /// 
    /// Event message
    /// A task that represents the asynchronous operation
    public async Task HandleEventAsync(GetShoppingCartItemUnitPriceEvent eventMessage)
    {
        if (!_rfqSettings.Enabled)
            return;

        var quoteItem = await _shortTermCacheManager.GetAsync(async () => await _rfqService.GetQuoteItemByShoppingCartItemIdAsync(eventMessage.ShoppingCartItem.Id), RfqDefaults.QuoteItemByShoppingCartItemCacheKey, eventMessage.ShoppingCartItem.Id);

        if (quoteItem == null)
            return;

        eventMessage.DiscountAmount = 0;
        eventMessage.AppliedDiscounts?.Clear();
        eventMessage.UnitPrice = quoteItem.OfferedUnitPrice;
        eventMessage.StopProcessing = true;
    }

    /// 
    /// Handle model prepared event
    /// 
    /// Event message
    /// A task that represents the asynchronous operation
    public async Task HandleEventAsync(ModelPreparedEvent eventMessage)
    {
        if (!_rfqSettings.Enabled)
            return;

        if (eventMessage.Model is ShoppingCartModel model)
        {
            var routeName = _httpContextAccessor.HttpContext?.GetEndpoint()?.Metadata.GetMetadata()?.RouteName;

            if (routeName is not NopRouteNames.General.CART)
                return;

            //is shopping cart created by quote
            if (await model.Items.AnyAwaitAsync(async shoppingCartItemModel => (await _rfqService.GetQuoteItemByShoppingCartItemIdAsync(shoppingCartItemModel.Id)) == null))
                return;

            var disableEdit = false;

            foreach (var shoppingCartItemModel in model.Items)
            {
                var quoteItem = await _rfqService.GetQuoteItemByShoppingCartItemIdAsync(shoppingCartItemModel.Id);

                if (quoteItem == null)
                    return;

                shoppingCartItemModel.AllowItemEditing = false;
                shoppingCartItemModel.DisableRemoval = true;
                shoppingCartItemModel.Quantity = quoteItem.OfferedQty;

                disableEdit = true;
            }

            if (disableEdit)
            {
                model.IsEditable = false;
                model.IsReadyToCheckout = true;
            }
        }
    }

    /// 
    /// Handle shopping cart item inserted event
    /// 
    /// Event message
    /// A task that represents the asynchronous operation
    public async Task HandleEventAsync(EntityInsertedEvent eventMessage)
    {
        if (!_rfqSettings.Enabled)
            return;

        var customer = await _workContext.GetCurrentCustomerAsync();
        var store = await _storeContext.GetCurrentStoreAsync();

        var cart = await _shoppingCartService.GetShoppingCartAsync(customer, ShoppingCartType.ShoppingCart, store.Id);

        var quoteItems =
            await _rfqService.GetQuoteItemsByShoppingCartItemIdsAsync(cart.Select(sci => sci.Id).ToArray());

        foreach (var quoteItem in quoteItems)
        {
            await _shoppingCartService.DeleteShoppingCartItemAsync(quoteItem.ShoppingCartItemId!.Value);
            _shortTermCacheManager.Remove(RfqDefaults.QuoteItemByShoppingCartItemCacheKey.Key, quoteItem.ShoppingCartItemId);
            quoteItem.ShoppingCartItemId = null;
        }

        await _rfqService.UpdateQuoteItemsAsync(quoteItems);
    }

    /// 
    /// Handle shopping cart item moved to order item event
    /// 
    /// Event message
    /// A task that represents the asynchronous operation
    public async Task HandleEventAsync(ShoppingCartItemMovedToOrderItemEvent eventMessage)
    {
        if (!_rfqSettings.Enabled)
            return;

        var quoteItem = await _rfqService.GetQuoteItemByShoppingCartItemIdAsync(eventMessage.ShoppingCartItem.Id);

        if (quoteItem == null)
            return;

        var quote = await _rfqService.GetQuoteByIdAsync(quoteItem.QuoteId);
        quote.Status = QuoteStatus.OrderCreated;
        quote.OrderId = eventMessage.OrderItem.OrderId;
        await _rfqService.UpdateQuoteAsync(quote);

        var items = await _rfqService.GetQuoteItemsAsync(quote.Id);

        foreach (var item in items)
        {
            _shortTermCacheManager.Remove(RfqDefaults.QuoteItemByShoppingCartItemCacheKey.Key, quoteItem.ShoppingCartItemId);
            item.ShoppingCartItemId = null;
        }

        await _rfqService.UpdateQuoteItemsAsync(items);
    }

    /// 
    /// Handle event
    /// 
    /// Event
    /// A task that represents the asynchronous operation
    public async Task HandleEventAsync(EntityUpdatedEvent eventMessage)
    {
        if (!_rfqSettings.Enabled)
            return;

        var quoteItem = await _rfqService.GetQuoteItemByShoppingCartItemIdAsync(eventMessage.Entity.Id);
        
        if (quoteItem == null || eventMessage.Entity.Quantity == quoteItem.OfferedQty)
            return;

        eventMessage.Entity.Quantity = quoteItem.OfferedQty;

        await _shoppingCartItemsRepository.UpdateAsync(eventMessage.Entity);
    }

    #endregion
}