Webiant Logo Webiant Logo
  1. No results found.

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

CurrencyModelFactory.cs

using Microsoft.AspNetCore.Mvc.Rendering;
using Nop.Core.Domain.Directory;
using Nop.Services.Directory;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Web.Areas.Admin.Infrastructure.Mapper.Extensions;
using Nop.Web.Areas.Admin.Models.Directory;
using Nop.Web.Framework.Factories;
using Nop.Web.Framework.Models.Extensions;

namespace Nop.Web.Areas.Admin.Factories;

/// 
/// Represents the currency model factory implementation
/// 
public partial class CurrencyModelFactory : ICurrencyModelFactory
{
    #region Fields

    protected readonly CurrencySettings _currencySettings;
    protected readonly ICurrencyService _currencyService;
    protected readonly IDateTimeHelper _dateTimeHelper;
    protected readonly IExchangeRatePluginManager _exchangeRatePluginManager;
    protected readonly ILocalizationService _localizationService;
    protected readonly ILocalizedModelFactory _localizedModelFactory;
    protected readonly IStoreMappingSupportedModelFactory _storeMappingSupportedModelFactory;

    #endregion

    #region Ctor

    public CurrencyModelFactory(CurrencySettings currencySettings,
        ICurrencyService currencyService,
        IDateTimeHelper dateTimeHelper,
        IExchangeRatePluginManager exchangeRatePluginManager,
        ILocalizationService localizationService,
        ILocalizedModelFactory localizedModelFactory,
        IStoreMappingSupportedModelFactory storeMappingSupportedModelFactory)
    {
        _currencySettings = currencySettings;
        _currencyService = currencyService;
        _dateTimeHelper = dateTimeHelper;
        _exchangeRatePluginManager = exchangeRatePluginManager;
        _localizationService = localizationService;
        _localizedModelFactory = localizedModelFactory;
        _storeMappingSupportedModelFactory = storeMappingSupportedModelFactory;
    }

    #endregion

    #region Utilities

    /// 
    /// Prepare exchange rate provider model
    /// 
    /// Currency exchange rate provider model
    /// Whether to prepare exchange rate models
    /// A task that represents the asynchronous operation
    protected virtual async Task PrepareExchangeRateProviderModelAsync(CurrencyExchangeRateProviderModel model, bool prepareExchangeRates)
    {
        ArgumentNullException.ThrowIfNull(model);

        model.AutoUpdateEnabled = _currencySettings.AutoUpdateEnabled;

        //prepare available exchange rate providers
        var availableExchangeRateProviders = await _exchangeRatePluginManager.LoadAllPluginsAsync();

        model.ExchangeRateProviders = availableExchangeRateProviders.Select(provider => new SelectListItem
        {
            Text = provider.PluginDescriptor.FriendlyName,
            Value = provider.PluginDescriptor.SystemName,
            Selected = _exchangeRatePluginManager.IsPluginActive(provider)
        }).ToList();

        //prepare exchange rates
        if (prepareExchangeRates)
            await PrepareExchangeRateModelsAsync(model.ExchangeRates);
    }

    /// 
    /// Prepare exchange rate models
    /// 
    /// List of currency exchange rate model
    /// A task that represents the asynchronous operation
    protected virtual async Task PrepareExchangeRateModelsAsync(IList models)
    {
        ArgumentNullException.ThrowIfNull(models);

        //get exchange rates
        var exchangeRates = await _currencyService.GetCurrencyLiveRatesAsync();

        //filter by existing currencies
        var currencies = await _currencyService.GetAllCurrenciesAsync(true);
        exchangeRates = exchangeRates
            .Where(rate => currencies
                .Any(currency => currency.CurrencyCode.Equals(rate.CurrencyCode, StringComparison.InvariantCultureIgnoreCase))).ToList();

        //prepare models
        foreach (var rate in exchangeRates)
        {
            models.Add(new CurrencyExchangeRateModel { CurrencyCode = rate.CurrencyCode, Rate = rate.Rate });
        }
    }

    #endregion

    #region Methods

    /// 
    /// Prepare currency search model
    /// 
    /// Currency search model
    /// Whether to prepare exchange rate models
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the currency search model
    /// 
    public virtual async Task PrepareCurrencySearchModelAsync(CurrencySearchModel searchModel, bool prepareExchangeRates = false)
    {
        ArgumentNullException.ThrowIfNull(searchModel);

        //prepare exchange rate provider model
        await PrepareExchangeRateProviderModelAsync(searchModel.ExchangeRateProviderModel, prepareExchangeRates);

        //prepare page parameters
        searchModel.SetGridPageSize();

        return searchModel;
    }

    /// 
    /// Prepare paged currency list model
    /// 
    /// Currency search model
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the currency list model
    /// 
    public virtual async Task PrepareCurrencyListModelAsync(CurrencySearchModel searchModel)
    {
        ArgumentNullException.ThrowIfNull(searchModel);

        //get currencies
        var currencies = (await _currencyService.GetAllCurrenciesAsync(showHidden: true)).ToPagedList(searchModel);

        //prepare list model
        var model = new CurrencyListModel().PrepareToGrid(searchModel, currencies, () =>
        {
            return currencies.Select(currency =>
            {
                //fill in model values from the entity
                var currencyModel = currency.ToModel();

                //fill in additional values (not existing in the entity)
                currencyModel.IsPrimaryExchangeRateCurrency = currency.Id == _currencySettings.PrimaryExchangeRateCurrencyId;
                currencyModel.IsPrimaryStoreCurrency = currency.Id == _currencySettings.PrimaryStoreCurrencyId;

                return currencyModel;
            });
        });

        return model;
    }

    /// 
    /// Prepare currency model
    /// 
    /// Currency model
    /// Currency
    /// Whether to exclude populating of some properties of model
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the currency model
    /// 
    public virtual async Task PrepareCurrencyModelAsync(CurrencyModel model, Currency currency, bool excludeProperties = false)
    {
        Func localizedModelConfiguration = null;

        if (currency != null)
        {
            //fill in model values from the entity
            model ??= currency.ToModel();

            //convert dates to the user time
            model.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(currency.CreatedOnUtc, DateTimeKind.Utc);

            //define localized model configuration action
            localizedModelConfiguration = async (locale, languageId) =>
            {
                locale.Name = await _localizationService.GetLocalizedAsync(currency, entity => entity.Name, languageId, false, false);
            };
        }

        //set default values for the new model
        if (currency == null)
        {
            model.Published = true;
            model.Rate = 1;
        }

        //prepare localized models
        if (!excludeProperties)
            model.Locales = await _localizedModelFactory.PrepareLocalizedModelsAsync(localizedModelConfiguration);

        //prepare available stores
        await _storeMappingSupportedModelFactory.PrepareModelStoresAsync(model, currency, excludeProperties);

        return model;
    }

    #endregion
}