Webiant Logo Webiant Logo
  1. No results found.

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

DiscountSupportedModelFactory.cs

using Microsoft.AspNetCore.Mvc.Rendering;
using Nop.Core.Domain.Discounts;
using Nop.Services.Discounts;
using Nop.Web.Framework.Models;

namespace Nop.Web.Framework.Factories;

/// 
/// Represents the base discount supported model factory implementation
/// 
public partial class DiscountSupportedModelFactory : IDiscountSupportedModelFactory
{
    #region Fields

    protected readonly IDiscountService _discountService;

    #endregion

    #region Ctor

    public DiscountSupportedModelFactory(IDiscountService discountService)
    {
        _discountService = discountService;
    }

    #endregion

    #region Methods

    /// 
    /// Prepare selected and all available discounts for the passed model
    /// 
    /// Discount supported model type
    /// Model
    /// List of all available discounts
    /// A task that represents the asynchronous operation
    public virtual Task PrepareModelDiscountsAsync(TModel model, IList availableDiscounts) where TModel : IDiscountSupportedModel
    {
        ArgumentNullException.ThrowIfNull(model);

        //prepare available discounts
        model.AvailableDiscounts = availableDiscounts.Select(discount => new SelectListItem
        {
            Text = discount.Name,
            Value = discount.Id.ToString(),
            Selected = model.SelectedDiscountIds.Contains(discount.Id)
        }).ToList();

        return Task.FromResult(model);
    }

    /// 
    /// Prepare selected and all available discounts for the passed model by entity applied discounts
    /// 
    /// Discount supported model type
    /// Discount supported entity type
    /// Model
    /// Entity
    /// List of all available discounts
    /// Whether to ignore existing applied discounts
    /// A task that represents the asynchronous operation
    public virtual async Task PrepareModelDiscountsAsync(TModel model, IDiscountSupported entity,
        IList availableDiscounts, bool ignoreAppliedDiscounts)
        where TModel : IDiscountSupportedModel where TMapping : DiscountMapping
    {
        ArgumentNullException.ThrowIfNull(model);

        //prepare already applied discounts
        if (!ignoreAppliedDiscounts && entity != null)
            model.SelectedDiscountIds = (await _discountService.GetAppliedDiscountsAsync(entity)).Select(discount => discount.Id).ToList();

        return await PrepareModelDiscountsAsync(model, availableDiscounts);
    }

    #endregion
}