Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

124 KB
Raw Blame
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Business.Core.Interfaces.Catalog.Categories;
using Grand.Business.Core.Interfaces.Catalog.Collections;
using Grand.Business.Core.Interfaces.Catalog.Directory;
using Grand.Business.Core.Interfaces.Catalog.Discounts;
using Grand.Business.Core.Interfaces.Catalog.Prices;
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Catalog.Tax;
using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Storage;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Directory;
using Grand.Domain.Discounts;
using Grand.Domain.Localization;
using Grand.Domain.Media;
using Grand.Domain.Seo;
using Grand.Domain.Tax;
using Grand.Infrastructure;
using Grand.SharedKernel.Extensions;
using Grand.Web.AdminShared.Extensions.Mapping;
using Grand.Web.AdminShared.Interfaces;
using Grand.Web.AdminShared.Models.Catalog;
using Grand.Web.Common.Extensions;
using Grand.Web.Common.Localization;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Net;
using ProductExtensions = Grand.Domain.Catalog.ProductExtensions;

namespace Grand.Web.AdminShared.Services;

public class ProductViewModelService(
    IProductService productService,
    IInventoryManageService inventoryManageService,
    IPictureService pictureService,
    IProductAttributeService productAttributeService,
    IProductTagService productTagService,
    ICurrencyService currencyService,
    IMeasureService measureService,
    IDateTimeService dateTimeService,
    IBrandService brandService,
    ICollectionService collectionService,
    IProductCollectionService productCollectionService,
    ICategoryService categoryService,
    IProductCategoryService productCategoryService,
    IVendorService vendorService,
    ITranslationService translationService,
    IProductLayoutService productLayoutService,
    ISpecificationAttributeService specificationAttributeService,
    IContextAccessor contextAccessor,
    IGroupService groupService,
    IWarehouseService warehouseService,
    IDeliveryDateService deliveryDateService,
    ITaxCategoryService taxCategoryService,
    IDiscountService discountService,
    ICustomerService customerService,
    IStoreService storeService,
    IOutOfStockSubscriptionService outOfStockSubscriptionService,
    IDownloadService downloadService,
    ILanguageService languageService,
    IProductAttributeFormatter productAttributeFormatter,
    IStockQuantityService stockQuantityService,
    CurrencySettings currencySettings,
    MeasureSettings measureSettings,
    TaxSettings taxSettings,
    SeoSettings seoSettings,
    IAuctionService auctionService,
    IPriceFormatter priceFormatter,
    ISeNameService seNameService,
    IEnumTranslationService enumTranslationService,
    IAdminDataScope<Product> scope)
    : IProductViewModelService
{
    public virtual async Task PrepareAddProductAttributeCombinationModel(ProductAttributeCombinationModel model,
        Product product)
    {
        ArgumentNullException.ThrowIfNull(model);
        ArgumentNullException.ThrowIfNull(product);

        if (product.UseMultipleWarehouses) model.UseMultipleWarehouses = product.UseMultipleWarehouses;
        if (string.IsNullOrEmpty(model.Id))
        {
            model.ProductId = product.Id;
            var attributes = product.ProductAttributeMappings
                .Where(x => !x.IsNonCombinable())
                .ToList();
            foreach (var attribute in attributes)
            {
                var productAttribute =
                    await productAttributeService.GetProductAttributeById(attribute.ProductAttributeId);
                var attributeModel = new ProductAttributeCombinationModel.ProductAttributeModel {
                    Id = attribute.Id,
                    ProductAttributeId = attribute.ProductAttributeId,
                    Name = productAttribute.Name,
                    TextPrompt = attribute.TextPrompt,
                    IsRequired = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlTypeId
                };

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = attribute.ProductAttributeValues;
                    foreach (var attributeValue in attributeValues)
                    {
                        var attributeValueModel = new ProductAttributeCombinationModel.ProductAttributeValueModel {
                            Id = attributeValue.Id,
                            Name = attributeValue.Name,
                            IsPreSelected = attributeValue.IsPreSelected
                        };
                        attributeModel.Values.Add(attributeValueModel);
                    }
                }

                model.ProductAttributes.Add(attributeModel);
            }
        }


        if (!string.IsNullOrEmpty(model.PictureId))
        {
            var pictureThumbnailUrl = await pictureService.GetPictureUrl(model.PictureId, 100, false);
            model.PictureThumbnailUrl = pictureThumbnailUrl;
        }

        foreach (var picture in product.ProductPictures)
            model.ProductPictureModels.Add(new ProductModel.ProductPictureModel {
                Id = picture.Id,
                ProductId = product.Id,
                PictureId = picture.PictureId,
                PictureUrl = await pictureService.GetPictureUrl(picture.PictureId),
                DisplayOrder = picture.DisplayOrder,
                IsDefault = picture.IsDefault
            });
        model.PrimaryStoreCurrencyCode =
            (await currencyService.GetCurrencyById(currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode;
    }

    public virtual async Task PrepareTierPriceModel(ProductModel.TierPriceModel model)
    {
        var storeId = scope.DefaultStoreId ?? "";

        //stores - same capability gate as PrepareProductListModel: Vendor's original PrepareTierPriceModel
        //never populated a stores dropdown at all (vendors don't pick stores), so this must not run for
        //Vendor even though its storeId also resolves to "".
        if (scope.ShowStoreSelector)
        {
            if (string.IsNullOrEmpty(storeId))
                model.AvailableStores.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = " " });

            foreach (var store in (await storeService.GetAllStores()).Where(x =>
                         x.Id == storeId || string.IsNullOrWhiteSpace(storeId)))
                model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id });
        }

        //customer groups
        model.AvailableCustomerGroups.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = " " });
        foreach (var role in await groupService.GetAllCustomerGroups(showHidden: true))
            model.AvailableCustomerGroups.Add(new SelectListItem { Text = role.Name, Value = role.Id });

        foreach (var currency in await currencyService.GetAllCurrencies())
            model.AvailableCurrencies.Add(new SelectListItem { Text = currency.Name, Value = currency.CurrencyCode });
    }

    public virtual async Task PrepareProductAttributeValueModel(Product product,
        ProductModel.ProductAttributeValueModel model)
    {
        //pictures
        foreach (var x in product.ProductPictures.OrderBy(x => x.DisplayOrder))
            model.ProductPictureModels.Add(new ProductModel.ProductPictureModel {
                Id = x.Id,
                ProductId = product.Id,
                PictureId = x.PictureId,
                PictureUrl = await pictureService.GetPictureUrl(x.PictureId),
                DisplayOrder = x.DisplayOrder,
                IsDefault = x.IsDefault
            });

        var associatedProduct = await productService.GetProductById(model.AssociatedProductId);
        model.AssociatedProductName = associatedProduct != null ? associatedProduct.Name : "";
    }

    public virtual async Task OutOfStockNotifications(Product product, int prevStockQuantity,
        List<ProductWarehouseInventory> prevMultiWarehouseStock
    )
    {
        if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&
            product.BackorderModeId == BackorderMode.NoBackorders &&
            product.AllowOutOfStockSubscriptions &&
            stockQuantityService.GetTotalStockQuantity(product, total: true) > 0 &&
            prevStockQuantity <= 0 && !product.UseMultipleWarehouses &&
            product.Published)
            await outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");
        if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&
            product.BackorderModeId == BackorderMode.NoBackorders &&
            product.AllowOutOfStockSubscriptions &&
            product.UseMultipleWarehouses &&
            product.Published)
        {
            foreach (var prevstock in prevMultiWarehouseStock)
                if (prevstock.StockQuantity - prevstock.ReservedQuantity <= 0)
                {
                    var actualStock =
                        product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == prevstock.WarehouseId);
                    if (actualStock != null)
                        if (actualStock.StockQuantity - actualStock.ReservedQuantity > 0)
                            await outOfStockSubscriptionService.SendNotificationsToSubscribers(product,
                                prevstock.WarehouseId);
                }

            if (product.ProductWarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity) > 0)
                if (prevMultiWarehouseStock.Sum(x => x.StockQuantity - x.ReservedQuantity) <= 0)
                    await outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");
        }
    }

    public virtual async Task OutOfStockNotifications(Product product, ProductAttributeCombination combination,
        ProductAttributeCombination prevcombination)
    {
        if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes &&
            product.BackorderModeId == BackorderMode.NoBackorders &&
            product.AllowOutOfStockSubscriptions &&
            combination.StockQuantity > 0 &&
            prevcombination.StockQuantity <= 0 && !product.UseMultipleWarehouses &&
            product.Published)
            await outOfStockSubscriptionService.SendNotificationsToSubscribers(product, combination.Attributes, "");
        if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes &&
            product.BackorderModeId == BackorderMode.NoBackorders &&
            product.AllowOutOfStockSubscriptions &&
            product.UseMultipleWarehouses &&
            product.Published)
        {
            foreach (var prevstock in prevcombination.WarehouseInventory)
                if (prevstock.StockQuantity - prevstock.ReservedQuantity <= 0)
                {
                    var actualStock =
                        combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == prevstock.WarehouseId);
                    if (actualStock != null)
                        if (actualStock.StockQuantity - actualStock.ReservedQuantity > 0)
                            await outOfStockSubscriptionService.SendNotificationsToSubscribers(product,
                                combination.Attributes, prevstock.WarehouseId);
                }

            if (combination.WarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity) > 0)
                if (prevcombination.WarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity) <= 0)
                    await outOfStockSubscriptionService.SendNotificationsToSubscribers(product, combination.Attributes,
                        "");
        }
    }

    public virtual async Task PrepareProductModel(ProductModel model, Product product,
        bool setPredefinedValues, bool excludeProperties)
    {
        ArgumentNullException.ThrowIfNull(model);

        model.PrimaryStoreCurrencyCode = (await currencyService.GetCurrencyById(currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode;
        model.BaseWeightIn = (await measureService.GetMeasureWeightById(measureSettings.BaseWeightId))?.Name;
        model.BaseDimensionIn = (await measureService.GetMeasureDimensionById(measureSettings.BaseDimensionId))?.Name;

        if (product != null)
        {
            //date
            model.CreatedOn = dateTimeService.ConvertToUserTime(product.CreatedOnUtc, DateTimeKind.Utc);
            model.UpdatedOn = product.UpdatedOnUtc.HasValue
                ? dateTimeService.ConvertToUserTime(product.UpdatedOnUtc.Value, DateTimeKind.Utc)
                : null;

            //parent grouped product
            var parentGroupedProduct = await productService.GetProductById(product.ParentGroupedProductId);
            if (parentGroupedProduct != null)
            {
                model.AssociatedToProductId = product.ParentGroupedProductId;
                model.AssociatedToProductName = parentGroupedProduct.Name;
            }

            //reservation
            model.CalendarModel.ProductId = product.Id;
            model.CalendarModel.Interval = product.Interval;
            model.CalendarModel.IntervalUnit = (int)product.IntervalUnitId;
            model.CalendarModel.IncBothDate = product.IncBothDate;

            model.AutoAddRequiredProducts = product.AutoAddRequiredProducts;
            //product attributes
            foreach (var productAttribute in await productAttributeService.GetAllProductAttributes(contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
                model.AvailableProductAttributes.Add(new SelectListItem {
                    Text = productAttribute.Name,
                    Value = productAttribute.Id
                });
        }

        //copy product
        if (product != null)
        {
            model.CopyProductModel.Id = product.Id;
            model.CopyProductModel.Name = "Copy of " + product.Name;
            model.CopyProductModel.Published = true;
            model.CopyProductModel.CopyImages = true;
        }

        //layouts
        var layouts = await productLayoutService.GetAllProductLayouts();
        foreach (var layout in layouts)
            model.AvailableProductLayouts.Add(new SelectListItem {
                Text = layout.Name,
                Value = layout.Id
            });

        //delivery dates
        model.AvailableDeliveryDates.Add(new SelectListItem {
            Text = translationService.GetResource("Admin.Catalog.Products.Fields.DeliveryDate.None"),
            Value = ""
        });
        var deliveryDates = await deliveryDateService.GetAllDeliveryDates(model.StoreId);
        foreach (var deliveryDate in deliveryDates)
            model.AvailableDeliveryDates.Add(new SelectListItem {
                Text = deliveryDate.Name,
                Value = deliveryDate.Id
            });

        //warehouses
        var warehouses = await warehouseService.GetAllWarehouses(model.StoreId);
        model.AvailableWarehouses.Add(new SelectListItem {
            Text = translationService.GetResource("Admin.Catalog.Products.Fields.Warehouse.None"),
            Value = ""
        });
        foreach (var warehouse in warehouses)
            model.AvailableWarehouses.Add(new SelectListItem {
                Text = warehouse.Name,
                Value = warehouse.Id
            });

        //multiple warehouses
        foreach (var warehouse in warehouses)
        {
            var pwiModel = new ProductModel.ProductWarehouseInventoryModel {
                WarehouseId = warehouse.Id,
                WarehouseName = warehouse.Name,
                WarehouseCode = warehouse.Code
            };
            if (product != null)
            {
                var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouse.Id);
                if (pwi != null)
                {
                    pwiModel.WarehouseUsed = true;
                    pwiModel.StockQuantity = pwi.StockQuantity;
                    pwiModel.ReservedQuantity = pwi.ReservedQuantity;
                }
            }

            model.ProductWarehouseInventoryModels.Add(pwiModel);
        }

        //product tags
        if (product != null)
        {
            var result = new StringBuilder();
            for (var i = 0; i < product.ProductTags.Count; i++)
            {
                var pt = product.ProductTags.ToList()[i];
                var productTag = await productTagService.GetProductTagByName(pt);
                if (productTag != null)
                {
                    result.Append(productTag.Name);
                    if (i != product.ProductTags.Count - 1)
                        result.Append(", ");
                }
            }

            model.ProductTags = result.ToString();
        }

        //tax categories
        var taxCategories = await taxCategoryService.GetAllTaxCategories(contextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
        model.AvailableTaxCategories.Add(new SelectListItem {
            Text = translationService.GetResource("Admin.Configuration.Tax.Settings.TaxCategories.None"),
            Value = ""
        });
        foreach (var tc in taxCategories)
            model.AvailableTaxCategories.Add(new SelectListItem {
                Text = tc.Name,
                Value = tc.Id,
                Selected = product != null && !setPredefinedValues && tc.Id == product.TaxCategoryId
            });

        //baseprice units
        var measureWeights = await measureService.GetAllMeasureWeights();
        foreach (var mw in measureWeights)
            model.AvailableBasepriceUnits.Add(new SelectListItem {
                Text = mw.Name,
                Value = mw.Id,
                Selected = product != null && !setPredefinedValues && mw.Id == product.BasepriceUnitId
            });
        foreach (var mw in measureWeights)
            model.AvailableBasepriceBaseUnits.Add(new SelectListItem {
                Text = mw.Name,
                Value = mw.Id,
                Selected = product != null && !setPredefinedValues && mw.Id == product.BasepriceBaseUnitId
            });

        //units
        var units = await measureService.GetAllMeasureUnits();
        model.AvailableUnits.Add(new SelectListItem { Text = "---", Value = "" });
        foreach (var un in units)
            model.AvailableUnits.Add(new SelectListItem { Text = un.Name, Value = un.Id, Selected = product != null && un.Id == product.UnitId });

        //discounts
        model.AvailableDiscounts = (await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus, contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
            .Select(d => d.ToModel(dateTimeService))
            .ToList();
        if (!excludeProperties && product != null) model.SelectedDiscountIds = product.AppliedDiscounts.ToArray();

        //default values
        if (setPredefinedValues)
        {
            model.MaxEnteredPrice = 1000;
            model.MaxNumberOfDownloads = 10;
            model.RecurringCycleLength = 100;
            model.RecurringTotalCycles = 10;
            model.StockQuantity = 0;
            model.NotifyAdminForQuantityBelow = 1;
            model.OrderMinimumQuantity = 1;
            model.OrderMaximumQuantity = 10000;
            model.TaxCategoryId = taxSettings.DefaultTaxCategoryId;
            model.UnlimitedDownloads = true;
            model.IsShipEnabled = true;
            model.AllowCustomerReviews = true;
            model.Published = true;
            model.VisibleIndividually = true;
        }
    }

    public virtual async Task SaveProductWarehouseInventory(Product product,
        IList<ProductModel.ProductWarehouseInventoryModel> model)
    {
        ArgumentNullException.ThrowIfNull(product);

        if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStock)
            return;

        if (!product.UseMultipleWarehouses)
            return;

        var warehouses = await warehouseService.GetAllWarehouses(product.Stores.Count == 1 ? product.Stores.First() : null);

        foreach (var warehouse in warehouses)
        {
            var whim = model.FirstOrDefault(x => x.WarehouseId == warehouse.Id);
            var existingPwI = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouse.Id);
            if (existingPwI != null)
            {
                if (whim is { WarehouseUsed: true })
                {
                    //update existing record
                    existingPwI.StockQuantity = whim.StockQuantity;
                    existingPwI.ReservedQuantity = whim.ReservedQuantity;
                    await productService.UpdateProductWarehouseInventory(existingPwI, product.Id);
                }
                else
                {
                    //delete. no need to store record for qty 0
                    await productService.DeleteProductWarehouseInventory(existingPwI, product.Id);
                }
            }
            else
            {
                if (whim is { WarehouseUsed: true })
                {
                    //no need to insert a record for qty 0
                    existingPwI = new ProductWarehouseInventory {
                        WarehouseId = warehouse.Id,
                        StockQuantity = whim.StockQuantity,
                        ReservedQuantity = whim.ReservedQuantity
                    };
                    product.ProductWarehouseInventory.Add(existingPwI);
                    await productService.InsertProductWarehouseInventory(existingPwI, product.Id);
                }
            }
        }

        product.StockQuantity = product.ProductWarehouseInventory.Sum(x => x.StockQuantity);
        product.ReservedQuantity = product.ProductWarehouseInventory.Sum(x => x.ReservedQuantity);
        await inventoryManageService.UpdateStockProduct(product, false);
    }

    public virtual async Task PrepareProductReviewModel(ProductReviewModel model,
        ProductReview productReview, bool excludeProperties, bool formatReviewText)
    {
        ArgumentNullException.ThrowIfNull(model);
        ArgumentNullException.ThrowIfNull(productReview);

        var product = await productService.GetProductById(productReview.ProductId);
        var customer = await customerService.GetCustomerById(productReview.CustomerId);
        var store = await storeService.GetStoreById(productReview.StoreId);
        model.Id = productReview.Id;
        model.StoreName = store != null ? store.Shortcut : "";
        model.ProductId = productReview.ProductId;
        model.ProductName = product.Name;
        model.CustomerId = productReview.CustomerId;
        model.CustomerInfo = customer != null
            ? !string.IsNullOrEmpty(customer.Email)
                ? customer.Email
                : translationService.GetResource("Admin.Customers.Guest")
            : "";
        model.Rating = productReview.Rating;
        model.CreatedOn = dateTimeService.ConvertToUserTime(productReview.CreatedOnUtc, DateTimeKind.Utc);
        model.Signature = productReview.Signature;
        if (!excludeProperties)
        {
            model.Title = productReview.Title;
            if (formatReviewText)
            {
                model.ReviewText = FormatText.ConvertText(productReview.ReviewText);
                model.ReplyText = FormatText.ConvertText(productReview.ReplyText);
            }
            else
            {
                model.ReviewText = productReview.ReviewText;
                model.ReplyText = productReview.ReplyText;
            }

            model.IsApproved = productReview.IsApproved;
        }
    }

    public virtual async Task<ProductListModel> PrepareProductListModel()
    {
        var model = new ProductListModel();
        var storeId = scope.DefaultStoreId ?? "";

        //stores - Vendor has no store concept at all (ShowStoreSelector is false), so the dropdown
        //is left empty entirely rather than populated off storeId, which is "" for Vendor same as Admin.
        if (scope.ShowStoreSelector)
        {
            model.AvailableStores.Add(new SelectListItem { Text = translationService.GetResource($"{scope.ResourceKeyPrefix}.Common.All"), Value = " " });
            foreach (var s in (await storeService.GetAllStores()).Where(x =>
                         x.Id == storeId || string.IsNullOrWhiteSpace(storeId)))
                model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
        }

        //warehouses
        model.AvailableWarehouses.Add(new SelectListItem { Text = translationService.GetResource($"{scope.ResourceKeyPrefix}.Common.All"), Value = " " });
        foreach (var wh in await warehouseService.GetAllWarehouses(storeId))
            model.AvailableWarehouses.Add(new SelectListItem { Text = wh.Name, Value = wh.Id });

        //product types
        model.AvailableProductTypes = enumTranslationService.ToSelectList(ProductType.SimpleProduct, false).ToList();
        model.AvailableProductTypes.Insert(0,
            new SelectListItem { Text = translationService.GetResource($"{scope.ResourceKeyPrefix}.Common.All"), Value = "0" });

        //"published" property
        //0 - all (according to "ShowHidden" parameter)
        //1 - published only
        //2 - unpublished only
        //3 - Show on homepage
        //4 - mark as new
        model.AvailablePublishedOptions.Add(new SelectListItem { Text = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.List.SearchPublished.All"), Value = " " });
        model.AvailablePublishedOptions.Add(new SelectListItem {
            Text = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.List.SearchPublished.PublishedOnly"),
            Value = "1"
        });
        model.AvailablePublishedOptions.Add(new SelectListItem {
            Text = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.List.SearchPublished.UnpublishedOnly"),
            Value = "2"
        });

        // Admin/Store show "Show on homepage" (value 3); Vendor's original copy omits it entirely - vendors
        // can't feature products on the homepage, a real capability difference, not a naming difference.
        if (scope.CanFeatureOnHomepage)
            model.AvailablePublishedOptions.Add(new SelectListItem {
                Text = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.List.SearchPublished.ShowOnHomePage"),
                Value = "3"
            });

        model.AvailablePublishedOptions.Add(new SelectListItem {
            Text = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.List.SearchPublished.MarkAsNew"),
            Value = "4"
        });

        return model;
    }

    public virtual async Task<(IEnumerable<ProductModel> productModels, int totalCount)> PrepareProductsModel(
        ProductListModel model, int pageIndex, int pageSize)
    {

        var categoryIds = new List<string>();
        if (!string.IsNullOrEmpty(model.SearchCategoryId))
            categoryIds.Add(model.SearchCategoryId);

        //include subcategories
        if (model.SearchIncludeSubCategories && !string.IsNullOrEmpty(model.SearchCategoryId))
            categoryIds.AddRange(await GetChildCategoryIds(model.SearchCategoryId));

        //0 - all (according to "ShowHidden" parameter)
        //1 - published only
        //2 - unpublished only
        bool? overridePublished = null;
        switch (model.SearchPublishedId)
        {
            case 1:
                overridePublished = true;
                break;
            case 2:
                overridePublished = false;
                break;
        }

        bool? showOnHomePage = null;
        if (model.SearchPublishedId == 3)
            showOnHomePage = true;

        var markedAsNewOnly = model.SearchPublishedId == 4;

        // vendorId: scope.DefaultVendorId (when set) overrides whatever the search model asks for - mirrors
        // Vendor's original PrepareProductsModel, which always passed vendorId: CurrentVendor.Id regardless
        // of any vendor filter on the model. Admin/Store have no DefaultVendorId, so this falls back to
        // model.SearchVendorId unchanged for them.
        var products = (await productService.SearchProducts(
            categoryIds: categoryIds,
            brandId: model.SearchBrandId,
            collectionId: model.SearchCollectionId,
            storeId: model.SearchStoreId,
            vendorId: scope.DefaultVendorId ?? model.SearchVendorId,
            warehouseId: model.SearchWarehouseId,
            productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null,
            keywords: model.SearchProductName,
            pageIndex: pageIndex - 1,
            pageSize: pageSize,
            showHidden: true,
            showOnHomePage: showOnHomePage,
            overridePublished: overridePublished,
            markedAsNewOnly: markedAsNewOnly
        )).products;

        var items = new List<ProductModel>();
        //the brand and the first category of every row on the page, each looked up once: both
        //services read through the cache, and a page is 15 rows of mostly repeating ids
        var brandNames = new Dictionary<string, string>();
        var categoryNames = new Dictionary<string, string>();
        foreach (var x in products)
        {
            var productModel = x.ToModel(dateTimeService);
            //"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. "
            //also it improves performance
            productModel.FullDescription = "";

            //picture
            var defaultProductPicture = x.ProductPictures.FirstOrDefault() ?? new ProductPicture();
            productModel.PictureThumbnailUrl = await pictureService.GetPictureUrl(defaultProductPicture.PictureId, 100);
            //product type
            productModel.ProductTypeName = enumTranslationService.GetTranslationEnum(x.ProductTypeId);
            //brand
            if (!string.IsNullOrEmpty(x.BrandId))
            {
                if (!brandNames.TryGetValue(x.BrandId, out var brandName))
                {
                    brandName = (await brandService.GetBrandById(x.BrandId))?.Name;
                    brandNames[x.BrandId] = brandName;
                }

                productModel.BrandName = brandName;
            }

            //the first category the product is mapped to
            var firstCategoryId = x.ProductCategories.FirstOrDefault()?.CategoryId;
            if (!string.IsNullOrEmpty(firstCategoryId))
            {
                if (!categoryNames.TryGetValue(firstCategoryId, out var categoryName))
                {
                    categoryName = (await categoryService.GetCategoryById(firstCategoryId))?.Name;
                    categoryNames[firstCategoryId] = categoryName;
                }

                productModel.CategoryName = categoryName;
            }
            //friendly stock quantity
            //if a simple product AND "manage inventory" is "Track inventory", then display
            if (x.ProductTypeId == ProductType.SimpleProduct &&
                x.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)
                productModel.StockQuantityStr = stockQuantityService.GetTotalStockQuantity(x, total: true).ToString();
            items.Add(productModel);
        }

        return (items, products.TotalCount);
    }

    public virtual async Task<IList<Product>> PrepareProducts(ProductListModel model)
    {
        var categoryIds = new List<string>();
        if (!string.IsNullOrEmpty(model.SearchCategoryId))
            categoryIds.Add(model.SearchCategoryId);

        //include subcategories
        if (model.SearchIncludeSubCategories && !string.IsNullOrEmpty(model.SearchCategoryId))
            categoryIds.AddRange(await GetChildCategoryIds(model.SearchCategoryId));

        //0 - all (according to "ShowHidden" parameter)
        //1 - published only
        //2 - unpublished only
        bool? overridePublished = null;
        switch (model.SearchPublishedId)
        {
            case 1:
                overridePublished = true;
                break;
            case 2:
                overridePublished = false;
                break;
        }

        // vendorId: same override as PrepareProductsModel above - mirrors Vendor's original PrepareProducts,
        // which always passed vendorId: CurrentVendor.Id regardless of the search model.
        var products = (await productService.SearchProducts(
            categoryIds: categoryIds,
            brandId: model.SearchBrandId,
            collectionId: model.SearchCollectionId,
            storeId: model.SearchStoreId,
            vendorId: scope.DefaultVendorId ?? model.SearchVendorId,
            warehouseId: model.SearchWarehouseId,
            productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null,
            keywords: model.SearchProductName,
            showHidden: true,
            overridePublished: overridePublished
        )).products;

        return products;
    }

    public virtual async Task<Product> InsertProductModel(ProductModel model)
    {
        //product
        var product = model.ToEntity(dateTimeService);

        // VendorId: forced onto new products when scope.DefaultVendorId is set - mirrors Vendor's original
        // InsertProductModel, which always set product.VendorId = CurrentVendor?.Id explicitly and ignored
        // VendorId in its AutoMapper profile for exactly this reason. AdminShared's shared ProductProfile
        // does *not* ignore ProductModel.VendorId -> Product.VendorId (Admin's create form legitimately
        // assigns vendor ownership), so without this, a vendor host would map whatever (usually blank)
        // VendorId the model carries, leaving newly-created products belonging to no vendor at all -
        // orphaned and inaccessible to the vendor who just created them once VendorProductDataScope.HasAccess
        // gates on VendorId equality.
        if (scope.DefaultVendorId is not null) product.VendorId = scope.DefaultVendorId;

        //discounts
        var allDiscounts = await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus, model.StoreId);
        foreach (Discount discount in allDiscounts)
            if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))
            {
                product.AppliedDiscounts.Add(discount.Id);
            }

        product.Locales = await seNameService.TranslationSeNameProperties(model.Locales, product, x => x.Name);
        product.SeName = await seNameService.ValidateSeName(product, model.SeName, product.Name, true);

        await productService.InsertProduct(product);

        //search engine name
        await seNameService.SaveSeName(product);

        //tags
        await SaveProductTags(product, ParseProductTags(model.ProductTags));

        //warehouses
        await SaveProductWarehouseInventory(product, model.ProductWarehouseInventoryModels);

        await productService.UpdateProduct(product);

        return product;
    }

    public virtual async Task<Product> UpdateProductModel(Product product, ProductModel model)
    {
        var prevStockQuantity = stockQuantityService.GetTotalStockQuantity(product, total: true);
        var prevMultiWarehouseStock = product.ProductWarehouseInventory.Select(i => new ProductWarehouseInventory { WarehouseId = i.WarehouseId, StockQuantity = i.StockQuantity, ReservedQuantity = i.ReservedQuantity })
            .ToList();

        var prevDownloadId = product.DownloadId;
        var prevSampleDownloadId = product.SampleDownloadId;

        //product
        product = model.ToEntity(product, dateTimeService);
        product.AutoAddRequiredProducts = model.AutoAddRequiredProducts;

        // VendorId: re-forced to scope.DefaultVendorId (when set) after mapping, not merely left alone -
        // AdminShared's shared ProductProfile does not ignore ProductModel.VendorId -> Product.VendorId, so
        // without this, mapping a caller-supplied model onto the existing entity would let a vendor
        // reassign their own product to a different vendor id via a tampered/mass-assigned VendorId field.
        // Vendor's original UpdateProductModel never touched VendorId at all (its own AutoMapper profile
        // ignores it), relying on the pre-loaded entity's existing value - forcing it here is strictly
        // equivalent for legitimately-owned products (already gated by scope.HasAccess before reaching this
        // method) while also closing that mass-assignment gap for Admin/Store's shared profile.
        if (scope.DefaultVendorId is not null) product.VendorId = scope.DefaultVendorId;
        product.Locales = await seNameService.TranslationSeNameProperties(model.Locales, product, x => x.Name);
        product.SeName = await seNameService.ValidateSeName(product, model.SeName, product.Name, true);
        //discounts
        var allDiscounts = await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus, model.StoreId);

        foreach (var discount in allDiscounts)
            if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))
            {
                //new discount
                if (product.AppliedDiscounts.Count(d => d == discount.Id) == 0)
                {
                    product.AppliedDiscounts.Add(discount.Id);
                }
            }
            else
            {
                //remove discount
                if (product.AppliedDiscounts.Count(d => d == discount.Id) > 0)
                {
                    product.AppliedDiscounts.Remove(discount.Id);
                }
            }

        await productService.UpdateProduct(product);

        //search engine name
        await seNameService.SaveSeName(product);
        //tags
        await SaveProductTags(product, ParseProductTags(model.ProductTags));
        //warehouses
        await SaveProductWarehouseInventory(product, model.ProductWarehouseInventoryModels);
        //picture seo names
        await UpdatePictureSeoNames(product);

        //out of stock notifications
        await OutOfStockNotifications(product, prevStockQuantity, prevMultiWarehouseStock);

        //delete an old "download" file (if deleted or updated)
        if (!string.IsNullOrEmpty(prevDownloadId) && prevDownloadId != product.DownloadId)
        {
            var prevDownload = await downloadService.GetDownloadById(prevDownloadId);
            if (prevDownload != null)
                await downloadService.DeleteDownload(prevDownload);
        }

        //delete an old "sample download" file (if deleted or updated)
        if (!string.IsNullOrEmpty(prevSampleDownloadId) && prevSampleDownloadId != product.SampleDownloadId)
        {
            var prevSampleDownload = await downloadService.GetDownloadById(prevSampleDownloadId);
            if (prevSampleDownload != null)
                await downloadService.DeleteDownload(prevSampleDownload);
        }

        return product;
    }

    public virtual async Task DeleteProduct(Product product)
    {
        await productService.DeleteProduct(product);

        //delete an "download" file
        if (!string.IsNullOrEmpty(product.DownloadId))
        {
            var download = await downloadService.GetDownloadById(product.DownloadId);
            if (download != null)
                await downloadService.DeleteDownload(download);
        }

        if (!string.IsNullOrEmpty(product.SampleDownloadId))
        {
            var sampledownload = await downloadService.GetDownloadById(product.SampleDownloadId);
            if (sampledownload != null)
                await downloadService.DeleteDownload(sampledownload);
        }
    }

    public virtual async Task DeleteSelected(IEnumerable<string> selectedIds)
    {
        var products = new List<Product>();
        products.AddRange(await productService.GetProductsByIds(selectedIds.ToArray(), true));
        for (var i = 0; i < products.Count; i++)
        {
            await DeleteProduct(products[i]);
        }
    }

    public virtual async Task<ProductModel.AddRequiredProductModel> PrepareAddRequiredProductModel()
    {
        var model = await PrepareAddProductModel<ProductModel.AddRequiredProductModel>();
        return model;
    }

    public virtual async Task<(IList<ProductModel> products, int totalCount)> PrepareProductModel(
        ProductModel.AddProductModel model, int pageIndex, int pageSize)
    {
        // vendorId: scope.DefaultVendorId (when set) overrides the search model - mirrors Vendor's original
        // PrepareProductModel(AddProductModel,...), which always passed vendorId: CurrentVendor.Id (and
        // storeId: string.Empty) regardless of the model, so the "add related/similar/bundle/etc. product"
        // popups can never surface another vendor's products.
        var products = await productService.PrepareProductList(model.SearchCategoryId, model.SearchBrandId,
            model.SearchCollectionId, model.SearchStoreId, scope.DefaultVendorId ?? model.SearchVendorId, model.SearchProductTypeId,
            model.SearchProductName, pageIndex, pageSize);
        return (products.Select(x => x.ToModel(dateTimeService)).ToList(), products.TotalCount);
    }

    public virtual async Task<IList<ProductModel.ProductCategoryModel>> PrepareProductCategoryModel(Product product)
    {
        var productCategories = product.ProductCategories.OrderBy(x => x.DisplayOrder);
        var items = new List<ProductModel.ProductCategoryModel>();
        foreach (var x in productCategories)
        {
            var category = await categoryService.GetCategoryById(x.CategoryId);
            items.Add(new ProductModel.ProductCategoryModel {
                Id = x.Id,
                Category = await categoryService.GetFormattedBreadCrumb(category),
                ProductId = product.Id,
                CategoryId = x.CategoryId,
                IsFeaturedProduct = x.IsFeaturedProduct,
                DisplayOrder = x.DisplayOrder
            });
        }

        return items;
    }

    public virtual async Task InsertProductCategoryModel(ProductModel.ProductCategoryModel model)
    {
        var product = await productService.GetProductById(model.ProductId, true);
        if (product != null && product.ProductCategories.All(x => x.CategoryId != model.CategoryId))
        {
            var productCategory = new ProductCategory {
                CategoryId = model.CategoryId,
                DisplayOrder = model.DisplayOrder,
                IsFeaturedProduct = model.IsFeaturedProduct
            };
            await productCategoryService.InsertProductCategory(productCategory, product.Id);
        }
    }

    public virtual async Task UpdateProductCategoryModel(ProductModel.ProductCategoryModel model)
    {
        var product = await productService.GetProductById(model.ProductId, true);
        var productCategory = product.ProductCategories.FirstOrDefault(x => x.Id == model.Id);
        if (productCategory == null)
            throw new ArgumentException("No product category mapping found with the specified id");

        if (product.ProductCategories.Any(x => x.Id != model.Id && x.CategoryId == model.CategoryId))
            throw new ArgumentException("This category is already mapped with this product");

        productCategory.CategoryId = model.CategoryId;
        productCategory.DisplayOrder = model.DisplayOrder;
        productCategory.IsFeaturedProduct = model.IsFeaturedProduct;
        await productCategoryService.UpdateProductCategory(productCategory, product.Id);
    }

    public virtual async Task DeleteProductCategory(string id, string productId)
    {
        var product = await productService.GetProductById(productId, true);
        var productCategory = product.ProductCategories.FirstOrDefault(x => x.Id == id);
        if (productCategory == null)
            throw new ArgumentException("No product category mapping found with the specified id");

        await productCategoryService.DeleteProductCategory(productCategory, product.Id);
    }

    public virtual async Task<IList<ProductModel.ProductCollectionModel>> PrepareProductCollectionModel(Product product)
    {
        var items = new List<ProductModel.ProductCollectionModel>();
        foreach (var x in product.ProductCollections.OrderBy(x => x.DisplayOrder))
            items.Add(new ProductModel.ProductCollectionModel {
                Id = x.Id,
                Collection = (await collectionService.GetCollectionById(x.CollectionId)).Name,
                ProductId = product.Id,
                CollectionId = x.CollectionId,
                IsFeaturedProduct = x.IsFeaturedProduct,
                DisplayOrder = x.DisplayOrder
            });
        return items;
    }

    public virtual async Task InsertProductCollection(ProductModel.ProductCollectionModel model)
    {
        var collectionId = model.CollectionId;
        var product = await productService.GetProductById(model.ProductId, true);
        if (product != null && product.ProductCollections.All(x => x.CollectionId != collectionId))
        {
            var productCollection = new ProductCollection {
                CollectionId = collectionId,
                DisplayOrder = model.DisplayOrder,
                IsFeaturedProduct = model.IsFeaturedProduct
            };
            await productCollectionService.InsertProductCollection(productCollection, model.ProductId);
        }
    }

    public virtual async Task UpdateProductCollection(ProductModel.ProductCollectionModel model)
    {
        var product = await productService.GetProductById(model.ProductId, true);
        var productCollection = product.ProductCollections.FirstOrDefault(x => x.Id == model.Id);
        if (productCollection == null)
            throw new ArgumentException("No product collection mapping found with the specified id");

        if (product.ProductCollections.Any(x => x.Id != model.Id && x.CollectionId == model.CollectionId))
            throw new ArgumentException("This collection is already mapped with this product");

        productCollection.CollectionId = model.CollectionId;
        productCollection.DisplayOrder = model.DisplayOrder;
        productCollection.IsFeaturedProduct = model.IsFeaturedProduct;

        await productCollectionService.UpdateProductCollection(productCollection, product.Id);
    }

    public virtual async Task DeleteProductCollection(string id, string productId)
    {
        var product = await productService.GetProductById(productId, true);
        var productCollection = product.ProductCollections.FirstOrDefault(x => x.Id == id);
        if (productCollection == null)
            throw new ArgumentException("No product collection mapping found with the specified id");

        await productCollectionService.DeleteProductCollection(productCollection, product.Id);
    }

    public virtual async Task InsertRelatedProductModel(ProductModel.AddRelatedProductModel model)
    {
        var productId1 = await productService.GetProductById(model.ProductId, true);

        foreach (var id in model.SelectedProductIds)
        {
            var product = await productService.GetProductById(id);
            if (product == null || !await scope.HasAccess(product)) continue;

            var existingRelatedProducts = productId1.RelatedProducts;
            if (model.ProductId != id)
                if (!existingRelatedProducts.Any(x => x.ProductId2 == id))
                {
                    var related = new RelatedProduct {
                        ProductId2 = id,
                        DisplayOrder = 1
                    };
                    productId1.RelatedProducts.Add(related);
                    await productService.InsertRelatedProduct(related, model.ProductId);
                }
        }
    }

    public virtual async Task UpdateRelatedProductModel(ProductModel.RelatedProductModel model)
    {
        var product1 = await productService.GetProductById(model.ProductId1, true);
        var relatedProduct = product1.RelatedProducts.FirstOrDefault(x => x.Id == model.Id);
        if (relatedProduct == null)
            throw new ArgumentException("No related product found with the specified id");

        var product2 = await productService.GetProductById(relatedProduct.ProductId2);
        if (product2 == null)
            throw new ArgumentException("No product found with the specified id");

        relatedProduct.DisplayOrder = model.DisplayOrder;
        await productService.UpdateRelatedProduct(relatedProduct, model.ProductId1);
    }

    public virtual async Task DeleteRelatedProductModel(ProductModel.RelatedProductModel model)
    {
        var product = await productService.GetProductById(model.ProductId1, true);
        var relatedProduct = product.RelatedProducts.FirstOrDefault(x => x.Id == model.Id);
        if (relatedProduct == null)
            throw new ArgumentException("No related product found with the specified id");

        await productService.DeleteRelatedProduct(relatedProduct, model.ProductId1);
    }

    public virtual async Task InsertSimilarProductModel(ProductModel.AddSimilarProductModel model)
    {
        var productId1 = await productService.GetProductById(model.ProductId, true);

        foreach (var id in model.SelectedProductIds)
        {
            var product = await productService.GetProductById(id);
            // scope.HasAccess: see InsertRelatedProductModel above.
            if (product == null || !await scope.HasAccess(product)) continue;

            var existingSimilarProducts = productId1.SimilarProducts;
            if (model.ProductId != id)
                if (!existingSimilarProducts.Any(x => x.ProductId2 == id))
                {
                    var similar = new SimilarProduct {
                        ProductId1 = model.ProductId,
                        ProductId2 = id,
                        DisplayOrder = 1
                    };
                    productId1.SimilarProducts.Add(similar);
                    await productService.InsertSimilarProduct(similar);
                }
        }
    }

    public virtual async Task UpdateSimilarProductModel(ProductModel.SimilarProductModel model)
    {
        var product1 = await productService.GetProductById(model.ProductId1, true);
        var similarProduct = product1.SimilarProducts.FirstOrDefault(x => x.Id == model.Id);
        if (similarProduct == null)
            throw new ArgumentException("No similar product found with the specified id");

        var product2 = await productService.GetProductById(similarProduct.ProductId2);
        if (product2 == null)
            throw new ArgumentException("No product found with the specified id");

        similarProduct.ProductId1 = model.ProductId1;
        similarProduct.DisplayOrder = model.DisplayOrder;
        await productService.UpdateSimilarProduct(similarProduct);
    }

    public virtual async Task DeleteSimilarProductModel(ProductModel.SimilarProductModel model)
    {
        var product = await productService.GetProductById(model.ProductId1, true);
        var similarProduct = product.SimilarProducts.FirstOrDefault(x => x.Id == model.Id);
        if (similarProduct == null)
            throw new ArgumentException("No similar product found with the specified id");

        similarProduct.ProductId1 = model.ProductId1;
        await productService.DeleteSimilarProduct(similarProduct);
    }

    public virtual async Task InsertBundleProductModel(ProductModel.AddBundleProductModel model)
    {
        var productId1 = await productService.GetProductById(model.ProductId, true);

        foreach (var id in model.SelectedProductIds)
        {
            var product = await productService.GetProductById(id);
            // scope.HasAccess: see InsertRelatedProductModel above.
            if (product == null || !await scope.HasAccess(product)) continue;

            var existingBundleProducts = productId1.BundleProducts;
            if (model.ProductId != id)
                if (!existingBundleProducts.Any(x => x.ProductId == id))
                {
                    var bundle = new BundleProduct {
                        ProductId = id,
                        DisplayOrder = 1,
                        Quantity = 1
                    };
                    productId1.BundleProducts.Add(bundle);
                    await productService.InsertBundleProduct(bundle, model.ProductId);
                }
        }
    }

    public virtual async Task UpdateBundleProductModel(ProductModel.BundleProductModel model)
    {
        var product = await productService.GetProductById(model.ProductBundleId, true);
        var bundleProduct = product.BundleProducts.FirstOrDefault(x => x.Id == model.Id);
        if (bundleProduct == null)
            throw new ArgumentException("No bundle product found with the specified id");

        var product2 = await productService.GetProductById(bundleProduct.ProductId);
        if (product2 == null)
            throw new ArgumentException("No product found with the specified id");

        bundleProduct.ProductId = model.ProductId;
        bundleProduct.Quantity = model.Quantity > 0 ? model.Quantity : 1;
        bundleProduct.DisplayOrder = model.DisplayOrder;
        await productService.UpdateBundleProduct(bundleProduct, model.ProductBundleId);
    }

    public virtual async Task DeleteBundleProductModel(ProductModel.BundleProductModel model)
    {
        var product = await productService.GetProductById(model.ProductBundleId, true);
        var bundleProduct = product.BundleProducts.FirstOrDefault(x => x.Id == model.Id);
        if (bundleProduct == null)
            throw new ArgumentException("No bundle product found with the specified id");

        await productService.DeleteBundleProduct(bundleProduct, model.ProductBundleId);
    }

    public virtual async Task InsertCrossSellProductModel(ProductModel.AddCrossSellProductModel model)
    {
        var crossSellProduct = await productService.GetProductById(model.ProductId, true);
        foreach (var id in model.SelectedProductIds)
        {
            var product = await productService.GetProductById(id);
            // scope.HasAccess: see InsertRelatedProductModel above.
            if (product == null || !await scope.HasAccess(product)) continue;

            if (!crossSellProduct.CrossSellProduct.Any(x => x == id))
                if (model.ProductId != id)
                    await productService.InsertCrossSellProduct(
                        new CrossSellProduct {
                            ProductId1 = model.ProductId,
                            ProductId2 = id
                        });
        }
    }

    public virtual async Task DeleteCrossSellProduct(string productId, string crossSellProductId)
    {
        var crosssell = new CrossSellProduct {
            ProductId1 = productId,
            ProductId2 = crossSellProductId
        };
        await productService.DeleteCrossSellProduct(crosssell);
    }

    public virtual async Task InsertRecommendedProductModel(ProductModel.AddRecommendedProductModel model)
    {
        var mainproduct = await productService.GetProductById(model.ProductId, true);
        foreach (var id in model.SelectedProductIds)
        {
            var product = await productService.GetProductById(id);
            // scope.HasAccess: see InsertRelatedProductModel above.
            if (product == null || !await scope.HasAccess(product)) continue;

            if (!mainproduct.RecommendedProduct.Any(x => x == id))
                if (model.ProductId != id)
                    await productService.InsertRecommendedProduct(model.ProductId, id);
        }
    }

    public virtual async Task DeleteRecommendedProduct(string productId, string recommendedProductId)
    {
        await productService.DeleteRecommendedProduct(productId, recommendedProductId);
    }

    public virtual async Task InsertAssociatedProductModel(ProductModel.AddAssociatedProductModel model)
    {
        foreach (var id in model.SelectedProductIds)
        {
            var product = await productService.GetProductById(id);
            if (product != null)
            {
                product.ParentGroupedProductId = model.ProductId;
                await productService.UpdateAssociatedProduct(product);
            }
        }
    }

    public virtual async Task DeleteAssociatedProduct(Product product)
    {
        product.ParentGroupedProductId = "";
        await productService.UpdateAssociatedProduct(product);
    }

    public virtual async Task<ProductModel.AddRelatedProductModel> PrepareRelatedProductModel()
    {
        var model = await PrepareAddProductModel<ProductModel.AddRelatedProductModel>();
        return model;
    }

    public virtual async Task<ProductModel.AddSimilarProductModel> PrepareSimilarProductModel()
    {
        var model = await PrepareAddProductModel<ProductModel.AddSimilarProductModel>();
        return model;
    }

    public virtual async Task<ProductModel.AddBundleProductModel> PrepareBundleProductModel()
    {
        var model = await PrepareAddProductModel<ProductModel.AddBundleProductModel>();
        return model;
    }

    public virtual async Task<ProductModel.AddCrossSellProductModel> PrepareCrossSellProductModel()
    {
        var model = await PrepareAddProductModel<ProductModel.AddCrossSellProductModel>();
        return model;
    }

    public virtual async Task<ProductModel.AddRecommendedProductModel> PrepareRecommendedProductModel()
    {
        var model = await PrepareAddProductModel<ProductModel.AddRecommendedProductModel>();
        return model;
    }

    public virtual async Task<ProductModel.AddAssociatedProductModel> PrepareAssociatedProductModel()
    {
        var model = await PrepareAddProductModel<ProductModel.AddAssociatedProductModel>();
        return model;
    }

    public virtual async Task<BulkEditListModel> PrepareBulkEditListModel()
    {
        var storeId = scope.DefaultStoreId ?? "";
        var model = new BulkEditListModel();

        //product types
        model.AvailableProductTypes = enumTranslationService.ToSelectList(ProductType.SimpleProduct, false).ToList();
        model.AvailableProductTypes.Insert(0,
            new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "0" });

        // avaible stores - same capability gate as PrepareProductListModel: Vendor's original never
        // populated a stores dropdown here at all (vendors don't pick stores), so this must not run for
        // Vendor even though its storeId also resolves to "".
        if (scope.ShowStoreSelector)
        {
            if (!string.IsNullOrEmpty(storeId))
            {
                var store = (await storeService.GetAllStores()).FirstOrDefault(x => x.Id == storeId);
                if (store != null)
                    model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id });
            }
            else
            {
                model.AvailableStores.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "" });

                foreach (var s in await storeService.GetAllStores())
                    model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
            }
        }

        return model;
    }

    public virtual async Task<(IEnumerable<BulkEditProductModel> bulkEditProductModels, int totalCount)>
        PrepareBulkEditProductModel(BulkEditListModel model, int pageIndex, int pageSize)
    {
        var searchCategoryIds = new List<string>();
        if (!string.IsNullOrEmpty(model.SearchCategoryId))
            searchCategoryIds.Add(model.SearchCategoryId);

        // vendorId: scope.DefaultVendorId forces the bulk-edit grid to the current vendor's own products.
        // Vendor's original PrepareBulkEditProductModel always passed vendorId: CurrentVendor.Id; this
        // shared version previously had no vendor filtering at all - a real gap, since BulkEditListModel
        // has no SearchVendorId field for a caller to (mis)supply in the first place, so there is nothing
        // to fall back to for Admin/Store, whose scope.DefaultVendorId is null and who intentionally see
        // every vendor's products in bulk-edit.
        var products = (await productService.SearchProducts(categoryIds: searchCategoryIds,
            brandId: model.SearchBrandId,
            collectionId: model.SearchCollectionId,
            storeId: model.SearchStoreId,
            vendorId: scope.DefaultVendorId ?? "",
            productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null,
            keywords: model.SearchProductName,
            pageIndex: pageIndex - 1,
            pageSize: pageSize,
            showHidden: true)).products;

        var items = new List<BulkEditProductModel>();
        foreach (var x in products)
        {
            var productModel = new BulkEditProductModel {
                Id = x.Id,
                Name = x.Name,
                Sku = x.Sku,
                OldPrice = x.OldPrice,
                Price = x.Price,
                ManageInventoryMethodId = (int)x.ManageInventoryMethodId,
                ManageInventoryMethod = enumTranslationService.GetTranslationEnum(x.ManageInventoryMethodId),
                StockQuantity = x.StockQuantity,
                Published = x.Published
            };
            items.Add(productModel);
        }

        return (items, products.TotalCount);
    }

    public virtual async Task UpdateBulkEdit(IEnumerable<BulkEditProductModel> products)
    {
        foreach (var pModel in products)
        {
            //update
            var product = await productService.GetProductById(pModel.Id, true);
            if (product != null)
            {
                var prevStockQuantity = stockQuantityService.GetTotalStockQuantity(product, total: true);

                product.Sku = pModel.Sku;
                product.Price = pModel.Price;
                product.OldPrice = pModel.OldPrice;
                product.StockQuantity = pModel.StockQuantity;
                product.Published = pModel.Published;
                product.Name = pModel.Name;
                product.ManageInventoryMethodId = (ManageInventoryMethod)pModel.ManageInventoryMethodId;
                await productService.UpdateProduct(product);

                //out of stock notifications
                if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&
                    product.BackorderModeId == BackorderMode.NoBackorders &&
                    product.AllowOutOfStockSubscriptions &&
                    stockQuantityService.GetTotalStockQuantity(product, total: true) > 0 &&
                    prevStockQuantity <= 0 && !product.UseMultipleWarehouses &&
                    product.Published)
                    await outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");
            }
        }
    }

    public virtual async Task InsertBulkEdit(IEnumerable<BulkEditProductModel> products)
    {
        foreach (var pModel in products)
        {
            if (string.IsNullOrWhiteSpace(pModel.Name))
                continue;

            //the defaults and the path of the Create screen: layout, tax category, store and
            //vendor ownership and the search engine name come out the same as there
            var model = new ProductModel { StoreId = scope.DefaultStoreId };
            await PrepareProductModel(model, null, true, true);
            model.ProductTypeId = (int)ProductType.SimpleProduct;
            model.ProductLayoutId = model.AvailableProductLayouts.FirstOrDefault()?.Value;
            model.Name = pModel.Name.Trim();
            model.Sku = pModel.Sku;
            model.Price = pModel.Price;
            model.OldPrice = pModel.OldPrice;
            model.StockQuantity = pModel.StockQuantity;
            model.ManageInventoryMethodId = pModel.ManageInventoryMethodId;
            model.Published = pModel.Published;
            if (scope.DefaultStoreId is not null)
                model.Stores = [scope.DefaultStoreId];

            await InsertProductModel(model);
        }
    }

    public virtual async Task DeleteBulkEdit(IEnumerable<BulkEditProductModel> products)
    {
        foreach (var pModel in products)
        {
            //delete
            var product = await productService.GetProductById(pModel.Id, true);
            if (product != null)
            {
                await productService.DeleteProduct(product);
            }
        }
    }

    public virtual async Task<IList<ProductModel.TierPriceModel>> PrepareTierPriceModel(Product product)
    {
        var storeId = scope.DefaultStoreId ?? "";
        var items = new List<ProductModel.TierPriceModel>();
        foreach (var x in product.TierPrices
                     .Where(x => x.StoreId == storeId || string.IsNullOrWhiteSpace(storeId) ||
                                 string.IsNullOrWhiteSpace(x.StoreId)).OrderBy(x => x.StoreId).ThenBy(x => x.Quantity)
                     .ThenBy(x => x.CustomerGroupId))
        {
            string storeName;
            if (!string.IsNullOrEmpty(x.StoreId))
            {
                var store = await storeService.GetStoreById(x.StoreId);
                storeName = store != null ? store.Shortcut : "Deleted";
            }
            else
            {
                storeName = translationService.GetResource("Admin.Catalog.Products.TierPrices.Fields.Store.All");
            }

            var groupName = string.Empty;
            if (string.IsNullOrEmpty(x.CustomerGroupId))
                groupName = translationService.GetResource(
                    "Admin.Catalog.Products.TierPrices.Fields.CustomerGroup.All");
            else
                groupName = (await groupService.GetCustomerGroupById(x.CustomerGroupId))?.Name ?? "NOT FOUND";

            items.Add(new ProductModel.TierPriceModel {
                Id = x.Id,
                StoreId = x.StoreId,
                Store = storeName,
                CurrencyCode = x.CurrencyCode,
                CustomerGroup = groupName,
                ProductId = product.Id,
                CustomerGroupId = !string.IsNullOrEmpty(x.CustomerGroupId) ? x.CustomerGroupId : "",
                Quantity = x.Quantity,
                Price = x.Price,
                StartDateTime = x.StartDateTimeUtc.HasValue
                    ? dateTimeService.ConvertToUserTime(x.StartDateTimeUtc.Value, DateTimeKind.Utc)
                    : new DateTime?(),
                EndDateTime = x.EndDateTimeUtc.HasValue
                    ? dateTimeService.ConvertToUserTime(x.EndDateTimeUtc.Value, DateTimeKind.Utc)
                    : new DateTime?()
            });
        }

        return items;
    }

    public virtual async Task<(IEnumerable<ProductModel.BidModel> bidModels, int totalCount)> PrepareBidMode(
        string productId, int pageIndex, int pageSize)
    {
        var bids = await auctionService.GetBidsByProductId(productId, pageIndex - 1, pageSize);
        var bidsModel = new List<ProductModel.BidModel>();
        foreach (var x in bids)
            bidsModel.Add(new ProductModel.BidModel {
                BidId = x.Id,
                ProductId = x.ProductId,
                Amount = priceFormatter.FormatPrice(x.Amount),
                Date = dateTimeService.ConvertToUserTime(x.Date, DateTimeKind.Utc),
                CustomerId = x.CustomerId,
                Email = (await customerService.GetCustomerById(x.CustomerId))?.Email,
                OrderId = x.OrderId
            });
        return (bidsModel, bids.TotalCount);
    }

    public virtual async Task<ProductModel.ProductAttributeMappingModel> PrepareProductAttributeMappingModel(
        Product product)
    {
        var model = new ProductModel.ProductAttributeMappingModel {
            ProductId = product.Id
        };
        foreach (var attribute in await productAttributeService.GetAllProductAttributes(contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
            model.AvailableProductAttribute.Add(new SelectListItem {
                Value = attribute.Id,
                Text = attribute.Name
            });
        return model;
    }

    public virtual async Task<ProductModel.ProductAttributeMappingModel> PrepareProductAttributeMappingModel(
        Product product, ProductAttributeMapping productAttributeMapping)
    {
        var model = productAttributeMapping.ToModel();
        foreach (var attribute in await productAttributeService.GetAllProductAttributes(contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
            model.AvailableProductAttribute.Add(new SelectListItem {
                Value = attribute.Id,
                Text = attribute.Name,
                Selected = attribute.Id == model.ProductAttributeId
            });
        return model;
    }

    public virtual async Task<ProductModel.ProductAttributeMappingModel> PrepareProductAttributeMappingModel(
        ProductModel.ProductAttributeMappingModel model)
    {
        foreach (var attribute in await productAttributeService.GetAllProductAttributes(contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
            model.AvailableProductAttribute.Add(new SelectListItem {
                Value = attribute.Id,
                Text = attribute.Name
            });
        return model;
    }

    public virtual async Task<IList<ProductModel.ProductAttributeMappingModel>> PrepareProductAttributeMappingModels(
        Product product)
    {
        var items = new List<ProductModel.ProductAttributeMappingModel>();
        foreach (var x in product.ProductAttributeMappings.OrderBy(x => x.DisplayOrder))
        {
            var attributeModel = new ProductModel.ProductAttributeMappingModel {
                Id = x.Id,
                ProductId = product.Id,
                ProductAttribute = (await productAttributeService.GetProductAttributeById(x.ProductAttributeId))?.Name,
                ProductAttributeId = x.ProductAttributeId,
                TextPrompt = x.TextPrompt,
                IsRequired = x.IsRequired,
                ShowOnCatalogPage = x.ShowOnCatalogPage,
                AttributeControlType = enumTranslationService.GetTranslationEnum(x.AttributeControlTypeId),
                AttributeControlTypeId = x.AttributeControlTypeId,
                DisplayOrder = x.DisplayOrder,
                Combination = x.Combination
            };


            if (x.ShouldHaveValues())
            {
                attributeModel.ShouldHaveValues = true;
                attributeModel.TotalValues = x.ProductAttributeValues.Count;
            }

            if (x.ValidationRulesAllowed())
            {
                var validationRules = new StringBuilder(string.Empty);
                attributeModel.ValidationRulesAllowed = true;
                if (x.ValidationMinLength != null)
                    validationRules.AppendFormat("{0}: {1}<br />",
                        translationService.GetResource(
                            "Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules.MinLength"),
                        x.ValidationMinLength);
                if (x.ValidationMaxLength != null)
                    validationRules.AppendFormat("{0}: {1}<br />",
                        translationService.GetResource(
                            "Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules.MaxLength"),
                        x.ValidationMaxLength);
                if (!string.IsNullOrEmpty(x.ValidationFileAllowedExtensions))
                    validationRules.AppendFormat("{0}: {1}<br />",
                        translationService.GetResource(
                            "Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules.FileAllowedExtensions"),
                        WebUtility.HtmlEncode(x.ValidationFileAllowedExtensions));
                if (x.ValidationFileMaximumSize != null)
                    validationRules.AppendFormat("{0}: {1}<br />",
                        translationService.GetResource(
                            "Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules.FileMaximumSize"),
                        x.ValidationFileMaximumSize);
                if (!string.IsNullOrEmpty(x.DefaultValue))
                    validationRules.AppendFormat("{0}: {1}<br />",
                        translationService.GetResource(
                            "Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules.DefaultValue"),
                        WebUtility.HtmlEncode(x.DefaultValue));
                attributeModel.ValidationRulesString = validationRules.ToString();
            }

            //currenty any attribute can have condition. why not?
            attributeModel.ConditionAllowed = true;
            var conditionAttribute = product.ParseProductAttributeMappings(x.ConditionAttribute).FirstOrDefault();
            var conditionValue = product.ParseProductAttributeValues(x.ConditionAttribute).FirstOrDefault();
            if (conditionAttribute != null && conditionValue != null)
            {
                var productAttribute =
                    await productAttributeService.GetProductAttributeById(conditionAttribute.ProductAttributeId);
                var _paname = productAttribute != null ? productAttribute.Name : "";
                attributeModel.ConditionString =
                    $"{WebUtility.HtmlEncode(_paname)}: {WebUtility.HtmlEncode(conditionValue.Name)}";
            }
            else
            {
                attributeModel.ConditionString = string.Empty;
            }

            items.Add(attributeModel);
        }

        return items;
    }

    public virtual async Task InsertProductAttributeMappingModel(ProductModel.ProductAttributeMappingModel model)
    {
        //insert mapping
        var productAttributeMapping = model.ToEntity();
        //predefined values
        var predefinedValues = (await productAttributeService.GetProductAttributeById(model.ProductAttributeId))
            .PredefinedProductAttributeValues;
        foreach (var predefinedValue in predefinedValues)
        {
            var pav = predefinedValue.ToEntity();
            //locales
            pav.Locales.Clear();
            var languages = await languageService.GetAllLanguages(true);
            //localization
            foreach (var lang in languages)
            {
                var name = predefinedValue.GetTranslation(x => x.Name, lang.Id, false);
                if (!string.IsNullOrEmpty(name))
                    pav.Locales.Add(new TranslationEntity { LanguageId = lang.Id, LocaleKey = "Name", LocaleValue = name });
            }

            productAttributeMapping.ProductAttributeValues.Add(pav);
        }

        await productAttributeService.InsertProductAttributeMapping(productAttributeMapping, model.ProductId);
    }

    public virtual async Task UpdateProductAttributeMappingModel(ProductModel.ProductAttributeMappingModel model)
    {
        var product = await productService.GetProductById(model.ProductId, true);
        if (product != null)
        {
            var productAttributeMapping = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == model.Id);
            if (productAttributeMapping != null)
            {
                productAttributeMapping = model.ToEntity(productAttributeMapping);
                await productAttributeService.UpdateProductAttributeMapping(productAttributeMapping, model.ProductId);
            }
        }
    }

    public virtual async Task<ProductModel.ProductAttributeMappingModel> PrepareProductAttributeMappingModel(
        ProductAttributeMapping productAttributeMapping)
    {
        var model = new ProductModel.ProductAttributeMappingModel {
            //prepare only used properties
            Id = productAttributeMapping.Id,
            ValidationRulesAllowed = productAttributeMapping.ValidationRulesAllowed(),
            AttributeControlTypeId = productAttributeMapping.AttributeControlTypeId,
            ValidationMinLength = productAttributeMapping.ValidationMinLength,
            ValidationMaxLength = productAttributeMapping.ValidationMaxLength,
            ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions,
            ValidationFileMaximumSize = productAttributeMapping.ValidationFileMaximumSize,
            DefaultValue = productAttributeMapping.DefaultValue
        };
        return await Task.FromResult(model);
    }

    public virtual async Task UpdateProductAttributeValidationRulesModel(
        ProductAttributeMapping productAttributeMapping, ProductModel.ProductAttributeMappingModel model)
    {
        productAttributeMapping.ValidationMinLength = model.ValidationMinLength;
        productAttributeMapping.ValidationMaxLength = model.ValidationMaxLength;
        productAttributeMapping.ValidationFileAllowedExtensions = model.ValidationFileAllowedExtensions;
        productAttributeMapping.ValidationFileMaximumSize = model.ValidationFileMaximumSize;
        productAttributeMapping.DefaultValue = model.DefaultValue;
        await productAttributeService.UpdateProductAttributeMapping(productAttributeMapping, model.ProductId);
    }

    public virtual async Task<ProductAttributeConditionModel> PrepareProductAttributeConditionModel(Product product,
        ProductAttributeMapping productAttributeMapping)
    {
        var model = new ProductAttributeConditionModel {
            ProductAttributeMappingId = productAttributeMapping.Id,
            EnableCondition = productAttributeMapping.ConditionAttribute.Any(),
            ProductId = product.Id
        };
        //pre-select attribute and values
        var selectedPva = product.ParseProductAttributeMappings(productAttributeMapping.ConditionAttribute)
            .FirstOrDefault();

        var attributes = product.ProductAttributeMappings
            //ignore non-combinable attributes (should have selectable values)
            .Where(x => x.CanBeUsedAsCondition())
            //ignore this attribute (it cannot depend on itself)
            .Where(x => x.Id != productAttributeMapping.Id)
            .ToList();
        foreach (var attribute in attributes)
        {
            var pam = await productAttributeService.GetProductAttributeById(attribute.ProductAttributeId);
            var attributeModel = new ProductAttributeConditionModel.ProductAttributeModel {
                Id = attribute.Id,
                ProductAttributeId = attribute.ProductAttributeId,
                Name = pam.Name,
                TextPrompt = attribute.TextPrompt,
                IsRequired = attribute.IsRequired,
                AttributeControlType = attribute.AttributeControlTypeId
            };

            if (attribute.ShouldHaveValues())
            {
                //values
                var attributeValues = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attribute.Id)
                    ?.ProductAttributeValues;
                if (attributeValues != null)
                    foreach (var attributeValue in attributeValues)
                    {
                        var attributeValueModel = new ProductAttributeConditionModel.ProductAttributeValueModel {
                            Id = attributeValue.Id,
                            Name = attributeValue.Name,
                            IsPreSelected = attributeValue.IsPreSelected
                        };
                        attributeModel.Values.Add(attributeValueModel);
                    }

                //pre-select attribute and value
                if (selectedPva != null && attribute.Id == selectedPva.Id)
                {
                    //attribute
                    model.SelectedProductAttributeId = selectedPva.Id;

                    //values
                    switch (attribute.AttributeControlTypeId)
                    {
                        case AttributeControlType.DropdownList:
                        case AttributeControlType.RadioList:
                        case AttributeControlType.Checkboxes:
                        case AttributeControlType.ColorSquares:
                        case AttributeControlType.ImageSquares:
                            {
                                if (productAttributeMapping.ConditionAttribute.Any())
                                {
                                    //clear default selection
                                    foreach (var item in attributeModel.Values)
                                        item.IsPreSelected = false;

                                    //select new values
                                    var selectedValues =
                                        product.ParseProductAttributeValues(productAttributeMapping.ConditionAttribute);
                                    foreach (var attributeValue in selectedValues)
                                        foreach (var item in attributeModel.Values)
                                            if (attributeValue.Id == item.Id)
                                                item.IsPreSelected = true;
                                }
                            }
                            break;
                        case AttributeControlType.ReadonlyCheckboxes:
                        case AttributeControlType.TextBox:
                        case AttributeControlType.MultilineTextbox:
                        case AttributeControlType.Datepicker:
                        case AttributeControlType.FileUpload:
                        default:
                            //these attribute types are supported as conditions
                            break;
                    }
                }
            }

            model.ProductAttributes.Add(attributeModel);
        }

        return model;
    }

    public virtual async Task UpdateProductAttributeConditionModel(Product product,
        ProductAttributeMapping productAttributeMapping, ProductAttributeConditionModel model)
    {
        var customAttributes = new List<CustomAttribute>();
        if (model.EnableCondition)
        {
            var attribute =
                product.ProductAttributeMappings.FirstOrDefault(x => x.Id == model.SelectedProductAttributeId);
            if (attribute != null)
                switch (attribute.AttributeControlTypeId)
                {
                    case AttributeControlType.DropdownList:
                    case AttributeControlType.RadioList:
                    case AttributeControlType.ColorSquares:
                    case AttributeControlType.ImageSquares:
                        {
                            var ctrlAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
                            if (!string.IsNullOrEmpty(ctrlAttributes))
                                customAttributes = ProductExtensions.AddProductAttribute(customAttributes,
                                    attribute, ctrlAttributes).ToList();
                            else
                                customAttributes = ProductExtensions.AddProductAttribute(customAttributes,
                                    attribute, "").ToList();
                        }
                        break;
                    case AttributeControlType.Checkboxes:
                        {
                            var cblAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
                            if (!string.IsNullOrEmpty(cblAttributes))
                            {
                                var anyValueSelected = false;
                                foreach (var item in cblAttributes.Split([','],
                                             StringSplitOptions.RemoveEmptyEntries))
                                    if (!string.IsNullOrEmpty(item))
                                    {
                                        customAttributes = ProductExtensions.AddProductAttribute(customAttributes,
                                            attribute, item).ToList();
                                        anyValueSelected = true;
                                    }

                                if (!anyValueSelected)
                                    customAttributes = ProductExtensions.AddProductAttribute(customAttributes,
                                        attribute, "").ToList();
                            }
                            else
                            {
                                customAttributes = ProductExtensions.AddProductAttribute(customAttributes,
                                    attribute, "").ToList();
                            }
                        }
                        break;
                    case AttributeControlType.ReadonlyCheckboxes:
                    case AttributeControlType.TextBox:
                    case AttributeControlType.MultilineTextbox:
                    case AttributeControlType.Datepicker:
                    case AttributeControlType.FileUpload:
                    default:
                        //these attribute types are supported as conditions
                        break;
                }
        }

        productAttributeMapping.ConditionAttribute = customAttributes;
        await productAttributeService.UpdateProductAttributeMapping(productAttributeMapping, model.ProductId);
    }

    public virtual async Task<ProductModel.ProductAttributeValueModel> PrepareProductAttributeValueModel(
        Product product, ProductAttributeMapping productAttributeMapping)
    {
        var model = new ProductModel.ProductAttributeValueModel {
            ProductAttributeMappingId = productAttributeMapping.Id,
            ProductId = product.Id,

            //color squares
            DisplayColorSquaresRgb =
                productAttributeMapping.AttributeControlTypeId == AttributeControlType.ColorSquares,
            ColorSquaresRgb = "#000000",
            //image squares
            DisplayImageSquaresPicture =
                productAttributeMapping.AttributeControlTypeId == AttributeControlType.ImageSquares,
            PrimaryStoreCurrencyCode = (await currencyService.GetCurrencyById(currencySettings.PrimaryStoreCurrencyId))
                ?.CurrencyCode,
            //default qantity for associated product
            Quantity = 1
        };

        //pictures
        foreach (var x in product.ProductPictures)
            model.ProductPictureModels.Add(new ProductModel.ProductPictureModel {
                Id = x.Id,
                ProductId = product.Id,
                PictureId = x.PictureId,
                PictureUrl = await pictureService.GetPictureUrl(x.PictureId),
                DisplayOrder = x.DisplayOrder,
                IsDefault = x.IsDefault
            });
        return model;
    }

    public virtual async Task<IList<ProductModel.ProductAttributeValueModel>> PrepareProductAttributeValueModels(
        Product product, ProductAttributeMapping productAttributeMapping)
    {
        var items = new List<ProductModel.ProductAttributeValueModel>();
        foreach (var x in productAttributeMapping.ProductAttributeValues.OrderBy(x => x.DisplayOrder))
        {
            Product associatedProduct = null;
            if (x.AttributeValueTypeId == AttributeValueType.AssociatedToProduct)
                associatedProduct = await productService.GetProductById(x.AssociatedProductId);

            var pictureThumbnailUrl =
                await pictureService.GetPictureUrl(
                    string.IsNullOrEmpty(x.PictureId) ? x.ImageSquaresPictureId : x.PictureId, 100, false);

            if (string.IsNullOrEmpty(pictureThumbnailUrl))
                pictureThumbnailUrl = await pictureService.GetPictureUrl("", 1);

            items.Add(new ProductModel.ProductAttributeValueModel {
                Id = x.Id,
                ProductAttributeMappingId = productAttributeMapping.Id, //TODO - check x.ProductAttributeMappingId,
                AttributeValueTypeId = x.AttributeValueTypeId,
                AttributeValueTypeName = enumTranslationService.GetTranslationEnum(x.AttributeValueTypeId),
                AssociatedProductId = x.AssociatedProductId,
                AssociatedProductName = associatedProduct != null ? associatedProduct.Name : "",
                Name = productAttributeMapping.AttributeControlTypeId != AttributeControlType.ColorSquares
                    ? x.Name
                    : $"{x.Name} - {x.ColorSquaresRgb}",
                ColorSquaresRgb = x.ColorSquaresRgb,
                ImageSquaresPictureId = x.ImageSquaresPictureId,
                PriceAdjustment = x.PriceAdjustment,
                PriceAdjustmentStr = x.PriceAdjustment.ToString("G29"),
                WeightAdjustment = x.WeightAdjustment,
                WeightAdjustmentStr = x.AttributeValueTypeId == AttributeValueType.Simple
                    ? x.WeightAdjustment.ToString("G29")
                    : "",
                Cost = x.Cost,
                PrimaryStoreCurrencyCode =
                    (await currencyService.GetCurrencyById(currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode,
                Quantity = x.Quantity,
                IsPreSelected = x.IsPreSelected,
                DisplayOrder = x.DisplayOrder,
                PictureId = x.PictureId,
                PictureThumbnailUrl = pictureThumbnailUrl,
                ProductId = product.Id
            });
        }

        return items;
    }

    public virtual async Task<ProductModel.ProductAttributeValueModel> PrepareProductAttributeValueModel(
        ProductAttributeMapping pa, ProductAttributeValue pav)
    {
        var associatedProduct = await productService.GetProductById(pav.AssociatedProductId);

        var model = new ProductModel.ProductAttributeValueModel {
            ProductAttributeMappingId = pa.Id, //TODO - check pav.ProductAttributeMappingId,
            AttributeValueTypeId = pav.AttributeValueTypeId,
            AttributeValueTypeName = enumTranslationService.GetTranslationEnum(pav.AttributeValueTypeId),
            AssociatedProductId = pav.AssociatedProductId,
            AssociatedProductName = associatedProduct != null ? associatedProduct.Name : "",
            Name = pav.Name,
            ColorSquaresRgb = pav.ColorSquaresRgb,
            DisplayColorSquaresRgb = pa.AttributeControlTypeId == AttributeControlType.ColorSquares,
            ImageSquaresPictureId = pav.ImageSquaresPictureId,
            DisplayImageSquaresPicture = pa.AttributeControlTypeId == AttributeControlType.ImageSquares,
            PriceAdjustment = pav.PriceAdjustment,
            WeightAdjustment = pav.WeightAdjustment,
            Cost = pav.Cost,
            PrimaryStoreCurrencyCode = (await currencyService.GetCurrencyById(currencySettings.PrimaryStoreCurrencyId))
                ?.CurrencyCode,
            Quantity = pav.Quantity,
            IsPreSelected = pav.IsPreSelected,
            DisplayOrder = pav.DisplayOrder,
            PictureId = pav.PictureId
        };
        if (model.DisplayColorSquaresRgb && string.IsNullOrEmpty(model.ColorSquaresRgb))
            model.ColorSquaresRgb = "#000000";
        return model;
    }

    public virtual async Task InsertProductAttributeValueModel(ProductModel.ProductAttributeValueModel model)
    {
        var pav = new ProductAttributeValue {
            AttributeValueTypeId = model.AttributeValueTypeId,
            AssociatedProductId = model.AssociatedProductId,
            Name = model.Name,
            ColorSquaresRgb = model.ColorSquaresRgb,
            ImageSquaresPictureId = model.ImageSquaresPictureId,
            PriceAdjustment = model.PriceAdjustment,
            WeightAdjustment = model.WeightAdjustment,
            Cost = model.Cost,
            Quantity = model.Quantity,
            IsPreSelected = model.IsPreSelected,
            DisplayOrder = model.DisplayOrder,
            PictureId = model.PictureId,
            Locales = model.Locales.ToTranslationProperty()
        };
        await productAttributeService.InsertProductAttributeValue(pav, model.ProductId,
            model.ProductAttributeMappingId);
    }

    public virtual async Task UpdateProductAttributeValueModel(ProductAttributeValue pav,
        ProductModel.ProductAttributeValueModel model)
    {
        pav.AttributeValueTypeId = model.AttributeValueTypeId;
        pav.AssociatedProductId = model.AssociatedProductId;
        pav.Name = model.Name;
        pav.ColorSquaresRgb = model.ColorSquaresRgb;
        pav.ImageSquaresPictureId = model.ImageSquaresPictureId;
        pav.PriceAdjustment = model.PriceAdjustment;
        pav.WeightAdjustment = model.WeightAdjustment;
        pav.Cost = model.Cost;
        pav.Quantity = model.Quantity;
        pav.IsPreSelected = model.IsPreSelected;
        pav.DisplayOrder = model.DisplayOrder;
        pav.PictureId = model.PictureId;
        pav.Locales = model.Locales.ToTranslationProperty();

        await productAttributeService.UpdateProductAttributeValue(pav, model.ProductId,
            model.ProductAttributeMappingId);
    }

    public virtual async Task<ProductModel.ProductAttributeValueModel.AssociateProductToAttributeValueModel> PrepareAssociateProductToAttributeValueModel()
    {
        var model = await PrepareAddProductModel<ProductModel.ProductAttributeValueModel.AssociateProductToAttributeValueModel>();
        return model;
    }

    public virtual async Task<IList<ProductModel.ProductAttributeCombinationModel>>
        PrepareProductAttributeCombinationModel(Product product)
    {
        var items = new List<ProductModel.ProductAttributeCombinationModel>();
        foreach (var x in product.ProductAttributeCombinations)
        {
            var attributes = await productAttributeFormatter.FormatAttributes(product, x.Attributes,
                contextAccessor.WorkContext.CurrentCustomer, "<br />", true, true, true, false, true, true);
            var pacModel = new ProductModel.ProductAttributeCombinationModel {
                Id = x.Id,
                ProductId = product.Id,
                Attributes = string.IsNullOrEmpty(attributes) ? "(null)" : attributes,
                StockQuantity = product.UseMultipleWarehouses
                    ? x.WarehouseInventory.Sum(y => y.StockQuantity - y.ReservedQuantity)
                    : x.StockQuantity,
                AllowOutOfStockOrders = x.AllowOutOfStockOrders,
                Sku = x.Sku,
                Mpn = x.Mpn,
                Gtin = x.Gtin,
                OverriddenPrice = x.OverriddenPrice,
                NotifyAdminForQuantityBelow = x.NotifyAdminForQuantityBelow
            };
            items.Add(pacModel);
        }

        return items;
    }

    public virtual async Task<ProductAttributeCombinationModel> PrepareProductAttributeCombinationModel(Product product,
        string combinationId)
    {
        var model = new ProductAttributeCombinationModel();
        var wim = new List<ProductAttributeCombinationModel.WarehouseInventoryModel>();
        foreach (var warehouse in await warehouseService.GetAllWarehouses())
        {
            var pwiModel = new ProductAttributeCombinationModel.WarehouseInventoryModel {
                WarehouseId = warehouse.Id,
                WarehouseName = warehouse.Name
            };
            wim.Add(pwiModel);
        }

        if (product.UseMultipleWarehouses)
        {
            model.UseMultipleWarehouses = product.UseMultipleWarehouses;
            model.WarehouseInventoryModels = wim;
        }

        if (!string.IsNullOrEmpty(combinationId))
        {
            var combination = product.ProductAttributeCombinations.FirstOrDefault(x => x.Id == combinationId);
            if (combination != null)
            {
                model = combination.ToModel();
                model.UseMultipleWarehouses = product.UseMultipleWarehouses;
                model.WarehouseInventoryModels = wim;
                model.ProductId = product.Id;
                model.Attributes = await productAttributeFormatter.FormatAttributes(product, combination.Attributes,
                    contextAccessor.WorkContext.CurrentCustomer, "<br />", true, true, true, false);
                if (model.UseMultipleWarehouses)
                    foreach (var _winv in combination.WarehouseInventory)
                    {
                        var warehouseInventoryModel =
                            model.WarehouseInventoryModels.FirstOrDefault(x => x.WarehouseId == _winv.WarehouseId);
                        if (warehouseInventoryModel != null)
                        {
                            warehouseInventoryModel.WarehouseUsed = true;
                            warehouseInventoryModel.Id = _winv.Id;
                            warehouseInventoryModel.StockQuantity = _winv.StockQuantity;
                            warehouseInventoryModel.ReservedQuantity = _winv.ReservedQuantity;
                        }
                    }
            }
        }

        return model;
    }

    public virtual async Task<IList<string>> InsertOrUpdateProductAttributeCombinationPopup(Product product,
        ProductAttributeCombinationModel model)
    {
        var customAttributes = new List<CustomAttribute>();
        var warnings = new List<string>();

        async Task PrepareCombinationWarehouseInventory(ProductAttributeCombination combination)
        {
            var warehouses = await warehouseService.GetAllWarehouses();

            foreach (var warehouse in warehouses)
            {
                var whim = model.WarehouseInventoryModels.FirstOrDefault(x => x.WarehouseId == warehouse.Id);
                var existingPwI = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouse.Id);
                if (existingPwI != null)
                {
                    if (whim is { WarehouseUsed: true })
                    {
                        //update 
                        existingPwI.StockQuantity = whim.StockQuantity;
                        existingPwI.ReservedQuantity = whim.ReservedQuantity;
                    }
                    else
                    {
                        //delete 
                        combination.WarehouseInventory.Remove(existingPwI);
                    }
                }
                else
                {
                    if (whim is { WarehouseUsed: true })
                    {
                        //no need to insert a record for qty 0
                        existingPwI = new ProductCombinationWarehouseInventory {
                            WarehouseId = whim.WarehouseId,
                            StockQuantity = whim.StockQuantity,
                            ReservedQuantity = whim.ReservedQuantity
                        };
                        combination.WarehouseInventory.Add(existingPwI);
                    }
                }
            }
        }

        if (string.IsNullOrEmpty(model.Id))
        {
            #region Product attributes

            var attributes = product.ProductAttributeMappings
                .Where(x => !x.IsNonCombinable())
                .ToList();
            if (attributes.Count == 0)
            {
                warnings.Add("This combination attributes is empty!");
                return warnings;
            }

            foreach (var attribute in attributes)
                switch (attribute.AttributeControlTypeId)
                {
                    case AttributeControlType.DropdownList:
                    case AttributeControlType.RadioList:
                    case AttributeControlType.ColorSquares:
                    case AttributeControlType.ImageSquares:
                        {
                            var ctrlAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
                            if (!string.IsNullOrEmpty(ctrlAttributes))
                                customAttributes = ProductExtensions.AddProductAttribute(customAttributes,
                                    attribute, ctrlAttributes).ToList();
                        }
                        break;
                    case AttributeControlType.Checkboxes:
                        {
                            var cblAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;
                            if (!string.IsNullOrEmpty(cblAttributes))
                                foreach (var item in cblAttributes.Split([','],
                                             StringSplitOptions.RemoveEmptyEntries))
                                    if (!string.IsNullOrEmpty(item))
                                        customAttributes = ProductExtensions.AddProductAttribute(customAttributes,
                                            attribute, item).ToList();
                        }
                        break;
                    case AttributeControlType.ReadonlyCheckboxes:
                        {
                            //load read-only (already server-side selected) values
                            var attributeValues = attribute.ProductAttributeValues;
                            foreach (var selectedAttributeId in attributeValues
                                         .Where(v => v.IsPreSelected)
                                         .Select(v => v.Id)
                                         .ToList())
                                customAttributes = ProductExtensions.AddProductAttribute(customAttributes,
                                    attribute, selectedAttributeId).ToList();
                        }
                        break;
                }

            //validate conditional attributes (if specified)
            foreach (var attribute in attributes)
            {
                var conditionMet = product.IsConditionMet(attribute, customAttributes);
                if (conditionMet.HasValue && !conditionMet.Value)
                    customAttributes = ProductExtensions.RemoveProductAttribute(customAttributes, attribute).ToList();
            }

            if (customAttributes.Count == 0)
            {
                warnings.Add("This combination custom attributes is empty!");
                return warnings;
            }

            foreach (var customAttribute in customAttributes)
                if (string.IsNullOrEmpty(customAttribute.Value))
                {
                    warnings.Add("Combination custom attributes need to be selected value!");
                    return warnings;
                }

            #endregion

            if (product.FindProductAttributeCombination(customAttributes) != null)
                warnings.Add("This combination attributes exists!");
            if (warnings.Count == 0)
            {
                var combination = new ProductAttributeCombination {
                    Attributes = customAttributes,
                    StockQuantity = model.StockQuantity,
                    ReservedQuantity = model.ReservedQuantity,
                    AllowOutOfStockOrders = model.AllowOutOfStockOrders,
                    Sku = model.Sku,
                    Text = model.Text,
                    Mpn = model.Mpn,
                    Gtin = model.Gtin,
                    OverriddenPrice = model.OverriddenPrice,
                    NotifyAdminForQuantityBelow = model.NotifyAdminForQuantityBelow,
                    PictureId = model.PictureId
                };

                if (product.UseMultipleWarehouses)
                {
                    await PrepareCombinationWarehouseInventory(combination);
                    combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
                    combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
                }

                await productAttributeService.InsertProductAttributeCombination(combination, product.Id);

                if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
                {
                    product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
                    product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
                    await inventoryManageService.UpdateStockProduct(product, false);
                }
            }
        }
        else
        {
            var combination = product.ProductAttributeCombinations.FirstOrDefault(x => x.Id == model.Id);
            var prevCombination = (ProductAttributeCombination)combination!.Clone();

            combination.StockQuantity = model.StockQuantity;
            combination.ReservedQuantity = model.ReservedQuantity;
            combination.AllowOutOfStockOrders = model.AllowOutOfStockOrders;
            combination.Sku = model.Sku;
            combination.Text = model.Text;
            combination.Mpn = model.Mpn;
            combination.Gtin = model.Gtin;
            combination.OverriddenPrice = model.OverriddenPrice;
            combination.NotifyAdminForQuantityBelow = model.NotifyAdminForQuantityBelow;
            combination.PictureId = model.PictureId;

            if (product.UseMultipleWarehouses)
            {
                await PrepareCombinationWarehouseInventory(combination);
                combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
            }

            //notification - out of stock
            await OutOfStockNotifications(product, combination, prevCombination);

            //update combination
            await productAttributeService.UpdateProductAttributeCombination(combination, product.Id);

            if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
            {
                var pr = await productService.GetProductById(model.ProductId);
                pr.StockQuantity = pr.ProductAttributeCombinations.Sum(x => x.StockQuantity);
                pr.ReservedQuantity = pr.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
                await inventoryManageService.UpdateStockProduct(pr, false);
            }
        }

        return warnings;
    }

    public virtual async Task GenerateAllAttributeCombinations(Product product)
    {
        var allAttributesComb = product.GenerateAllCombinations();
        if (allAttributesComb == null || allAttributesComb.Count == 0)
            return;

        foreach (var attributes in allAttributesComb)
        {
            var customAttributes = attributes.ToList();
            if (!customAttributes.Any())
                continue;

            var existingCombination = product.FindProductAttributeCombination(customAttributes);

            //already exists?
            if (existingCombination != null)
                continue;

            //save combination
            var combination = new ProductAttributeCombination {
                Attributes = customAttributes.ToList(),
                StockQuantity = 0,
                AllowOutOfStockOrders = false,
                Sku = null,
                Mpn = null,
                Gtin = null,
                OverriddenPrice = null,
                NotifyAdminForQuantityBelow = 1
            };
            await productAttributeService.InsertProductAttributeCombination(combination, product.Id);
        }

        if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
        {
            product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
            product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
            await inventoryManageService.UpdateStockProduct(product, false);
        }
    }

    public virtual async Task ClearAllAttributeCombinations(Product product)
    {
        foreach (var combination in product.ProductAttributeCombinations)
            await productAttributeService.DeleteProductAttributeCombination(combination, product.Id);
    }

    public virtual async Task<IList<ProductModel.ProductAttributeCombinationTierPricesModel>>
        PrepareProductAttributeCombinationTierPricesModel(Product product, string productAttributeCombinationId)
    {
        var items = new List<ProductModel.ProductAttributeCombinationTierPricesModel>();
        foreach (var x in product.ProductAttributeCombinations.Where(x => x.Id == productAttributeCombinationId)
                     .SelectMany(x => x.TierPrices))
        {
            string storeName;
            if (!string.IsNullOrEmpty(x.StoreId))
            {
                var store = await storeService.GetStoreById(x.StoreId);
                storeName = store != null ? store.Shortcut : "Deleted";
            }
            else
            {
                storeName = translationService.GetResource("Admin.Catalog.Products.TierPrices.Fields.Store.All");
            }

            var priceModel = new ProductModel.ProductAttributeCombinationTierPricesModel {
                Id = x.Id,
                CustomerGroupId = x.CustomerGroupId,
                CustomerGroup = !string.IsNullOrEmpty(x.CustomerGroupId)
                    ? (await groupService.GetCustomerGroupById(x.CustomerGroupId)).Name
                    : translationService.GetResource("Admin.Catalog.Products.TierPrices.Fields.CustomerGroup.All"),
                StoreId = x.StoreId,
                Store = storeName,
                Price = x.Price,
                Quantity = x.Quantity
            };
            items.Add(priceModel);
        }

        return items;
    }

    public virtual async Task InsertProductAttributeCombinationTierPricesModel(Product product,
        ProductAttributeCombination productAttributeCombination,
        ProductModel.ProductAttributeCombinationTierPricesModel model)
    {
        model.CustomerGroupId = !string.IsNullOrEmpty(model.CustomerGroupId) ? model.CustomerGroupId.Trim() : "";

        model.StoreId = !string.IsNullOrEmpty(model.StoreId) ? model.StoreId.Trim() : "";

        if (productAttributeCombination != null)
        {
            var pctp = new ProductCombinationTierPrices {
                Price = model.Price,
                Quantity = model.Quantity,
                StoreId = model.StoreId,
                CustomerGroupId = model.CustomerGroupId
            };
            productAttributeCombination.TierPrices.Add(pctp);
            await productAttributeService.UpdateProductAttributeCombination(productAttributeCombination, product.Id);
        }
    }

    public virtual async Task UpdateProductAttributeCombinationTierPricesModel(Product product,
        ProductAttributeCombination productAttributeCombination,
        ProductModel.ProductAttributeCombinationTierPricesModel model)
    {
        model.CustomerGroupId = !string.IsNullOrEmpty(model.CustomerGroupId) ? model.CustomerGroupId.Trim() : "";
        model.StoreId = !string.IsNullOrEmpty(model.StoreId) ? model.StoreId.Trim() : "";

        if (productAttributeCombination != null)
        {
            var tierPrice = productAttributeCombination.TierPrices.FirstOrDefault(x => x.Id == model.Id);
            if (tierPrice != null)
            {
                tierPrice.Price = model.Price;
                tierPrice.Quantity = model.Quantity;
                tierPrice.StoreId = model.StoreId;
                tierPrice.CustomerGroupId = model.CustomerGroupId;
                await productAttributeService.UpdateProductAttributeCombination(productAttributeCombination,
                    product.Id);
            }
        }
    }

    public virtual async Task DeleteProductAttributeCombinationTierPrices(Product product,
        ProductAttributeCombination productAttributeCombination, ProductCombinationTierPrices tierPrice)
    {
        productAttributeCombination.TierPrices.Remove(tierPrice);
        await productAttributeService.UpdateProductAttributeCombination(productAttributeCombination, product.Id);
    }

    //Pictures
    public virtual async Task<IList<ProductModel.ProductPictureModel>> PrepareProductPicturesModel(Product product)
    {
        var items = new List<ProductModel.ProductPictureModel>();
        foreach (var x in product.ProductPictures.OrderBy(x => x.DisplayOrder))
        {
            var picture = await pictureService.GetPictureById(x.PictureId);
            var m = new ProductModel.ProductPictureModel {
                Id = x.Id,
                ProductId = product.Id,
                PictureId = x.PictureId,
                PictureUrl = picture != null ? await pictureService.GetPictureUrl(picture) : null,
                AltAttribute = picture?.AltAttribute,
                TitleAttribute = picture?.TitleAttribute,
                DisplayOrder = x.DisplayOrder,
                IsDefault = x.IsDefault,
                Style = picture?.Style,
                ExtraField = picture?.ExtraField
            };
            items.Add(m);
        }

        return items;
    }

    public virtual async Task<(ProductModel.ProductPictureModel model, Picture Picture)> PrepareProductPictureModel(
        Product product, ProductPicture productPicture)
    {
        var picture = await pictureService.GetPictureById(productPicture.PictureId);
        var model = new ProductModel.ProductPictureModel {
            Id = productPicture.Id,
            ProductId = product.Id,
            PictureId = productPicture.PictureId,
            PictureUrl = picture != null ? await pictureService.GetPictureUrl(picture) : null,
            AltAttribute = picture?.AltAttribute,
            TitleAttribute = picture?.TitleAttribute,
            DisplayOrder = productPicture.DisplayOrder,
            IsDefault = productPicture.IsDefault,
            Style = picture?.Style,
            ExtraField = picture?.ExtraField
        };

        return (model, picture);
    }

    public virtual async Task InsertProductPicture(Product product, Picture picture, int displayOrder)
    {
        if (picture == null)
            throw new ArgumentException("No picture found with the specified id");

        if (product.ProductPictures.Any(x => x.PictureId == picture.Id))
            return;

        var productPicture = new ProductPicture {
            PictureId = picture.Id,
            DisplayOrder = displayOrder
        };
        await productService.InsertProductPicture(productPicture, product.Id);
        await pictureService.SetSeoFilename(picture, pictureService.GetPictureSeName(product.Name));
    }

    public virtual async Task UpdateProductPicture(ProductModel.ProductPictureModel model)
    {
        var product = await productService.GetProductById(model.ProductId, true);

        var productPicture = product.ProductPictures.FirstOrDefault(x => x.Id == model.Id);
        if (productPicture == null)
            throw new ArgumentException("No product picture found with the specified id");

        var picture = await pictureService.GetPictureById(productPicture.PictureId);
        if (picture == null)
            throw new ArgumentException("No picture found with the specified id");

        productPicture.DisplayOrder = model.DisplayOrder;
        productPicture.IsDefault = model.IsDefault;
        await productService.UpdateProductPicture(productPicture, product.Id);

        //Update picture fields
        await pictureService.UpdatePictureField(picture, x => x.AltAttribute, model.AltAttribute);
        await pictureService.UpdatePictureField(picture, x => x.TitleAttribute, model.TitleAttribute);
        await pictureService.UpdatePictureField(picture, x => x.Locales, model.Locales.ToTranslationProperty());
        await pictureService.UpdatePictureField(picture, x => x.Style, model.Style);
        await pictureService.UpdatePictureField(picture, x => x.ExtraField, model.ExtraField);
    }

    public virtual async Task DeleteProductPicture(ProductModel.ProductPictureModel model)
    {
        var product = await productService.GetProductById(model.ProductId, true);

        var productPicture = product.ProductPictures.FirstOrDefault(x => x.Id == model.Id);
        if (productPicture == null)
            throw new ArgumentException("No product picture found with the specified id");

        var pictureId = productPicture.PictureId;
        await productService.DeleteProductPicture(productPicture, product.Id);

        var picture = await pictureService.GetPictureById(pictureId);
        if (picture != null)
            await pictureService.DeletePicture(picture);
    }

    //Product specification
    public virtual async Task<IList<ProductSpecificationAttributeModel>> PrepareProductSpecificationAttributeModel(
        Product product)
    {
        var items = new List<ProductSpecificationAttributeModel>();
        foreach (var x in product.ProductSpecificationAttributes.OrderBy(x => x.DisplayOrder))
        {
            var psaModel = new ProductSpecificationAttributeModel {
                Id = x.Id,
                AttributeTypeId = (int)x.AttributeTypeId,
                AttributeId = x.SpecificationAttributeId,
                ProductId = product.Id,
                AttributeTypeName = enumTranslationService.GetTranslationEnum(x.AttributeTypeId),
                AllowFiltering = x.AllowFiltering,
                ShowOnProductPage = x.ShowOnProductPage,
                DisplayOrder = x.DisplayOrder,
                AttributeName = x.CustomName
            };

            switch (x.AttributeTypeId)
            {
                case SpecificationAttributeType.Option:
                    var specificationAttribute =
                        await specificationAttributeService.GetSpecificationAttributeById(x.SpecificationAttributeId);
                    if (specificationAttribute != null)
                    {
                        psaModel.AttributeName = specificationAttribute.Name;
                        psaModel.ValueRaw = WebUtility.HtmlEncode(specificationAttribute.SpecificationAttributeOptions
                            .FirstOrDefault(y => y.Id == x.SpecificationAttributeOptionId)?.Name);
                    }

                    psaModel.SpecificationAttributeOptionId = x.SpecificationAttributeOptionId;
                    break;
                case SpecificationAttributeType.CustomText:
                    psaModel.ValueRaw = WebUtility.HtmlEncode(x.CustomValue);
                    break;
                case SpecificationAttributeType.CustomHtmlText:
                    //do not encode?
                    psaModel.ValueRaw = WebUtility.HtmlEncode(x.CustomValue);
                    break;
                case SpecificationAttributeType.Hyperlink:
                    psaModel.ValueRaw = x.CustomValue;
                    break;
            }

            items.Add(psaModel);
        }

        return items;
    }

    public virtual async Task InsertProductSpecificationAttributeModel(
        ProductModel.AddProductSpecificationAttributeModel model, Product product)
    {
        //we allow filtering only for "Option" attribute type
        if (model.AttributeTypeId != (int)SpecificationAttributeType.Option)
        {
            model.AllowFiltering = false;
            model.SpecificationAttributeOptionId = null;
        }

        var psa = model.ToEntity();

        await specificationAttributeService.InsertProductSpecificationAttribute(psa, product.Id);
        product.ProductSpecificationAttributes.Add(psa);
    }

    public virtual async Task UpdateProductSpecificationAttributeModel(ProductSpecificationAttribute psa,
        ProductModel.AddProductSpecificationAttributeModel model)
    {
        psa = model.ToEntity(psa);
        await specificationAttributeService.UpdateProductSpecificationAttribute(psa, model.ProductId);
    }

    public virtual async Task DeleteProductSpecificationAttribute(Product product, ProductSpecificationAttribute psa)
    {
        product.ProductSpecificationAttributes.Remove(psa);
        await specificationAttributeService.DeleteProductSpecificationAttribute(psa, product.Id);
    }

    protected virtual async Task UpdatePictureSeoNames(Product product)
    {
        var picturesename = pictureService.GetPictureSeName(product.Name);
        foreach (var pp in product.ProductPictures)
        {
            var picture = await pictureService.GetPictureById(pp.PictureId);
            if (picture != null)
                await pictureService.SetSeoFilename(picture, picturesename);
        }
    }

    protected virtual async Task<List<string>> GetChildCategoryIds(string parentCategoryId)
    {
        var categoriesIds = new List<string>();
        var categories = await categoryService.GetAllCategoriesByParentCategoryId(parentCategoryId, true);
        foreach (var category in categories)
        {
            categoriesIds.Add(category.Id);
            categoriesIds.AddRange(await GetChildCategoryIds(category.Id));
        }

        return categoriesIds;
    }

    protected virtual string[] ParseProductTags(string productTags)
    {
        var result = new List<string>();
        if (!string.IsNullOrWhiteSpace(productTags))
        {
            var values = productTags.Split([','], StringSplitOptions.RemoveEmptyEntries);
            foreach (var val1 in values)
                if (!string.IsNullOrEmpty(val1.Trim()))
                    result.Add(val1.Trim());
        }

        return result.ToArray();
    }

    protected virtual async Task SaveProductTags(Product product, string[] productTags)
    {
        ArgumentNullException.ThrowIfNull(product);

        //product tags
        var existingProductTags = product.ProductTags.ToList();
        var productTagsToRemove = new List<ProductTag>();
        foreach (var existingProductTag in existingProductTags)
        {
            var existingProductTagText =
                await productTagService.GetProductTagByName(existingProductTag.ToLowerInvariant());
            var found = false;
            foreach (var newProductTag in productTags)
                if (existingProductTagText != null)
                    if (existingProductTagText.Name.Equals(newProductTag, StringComparison.OrdinalIgnoreCase))
                    {
                        found = true;
                        break;
                    }

            if (!found) productTagsToRemove.Add(existingProductTagText);
        }

        foreach (var productTag in productTagsToRemove)
            if (productTag != null)
                await productTagService.DetachProductTag(productTag, product.Id);
        foreach (var productTagName in productTags)
        {
            ProductTag productTag;
            var productTag2 = await productTagService.GetProductTagByName(productTagName);
            if (productTag2 == null)
            {
                //add new product tag
                productTag = new ProductTag {
                    Name = productTagName,
                    SeName = SeoExtensions.GetSeName(productTagName, seoSettings.ConvertNonWesternChars,
                        seoSettings.AllowUnicodeCharsInUrls, seoSettings.SeoCharConversion),
                    Count = 0
                };
                await productTagService.InsertProductTag(productTag);
            }
            else
            {
                productTag = productTag2;
            }

            if (!product.ProductTagExists(productTag.Name))
                await productTagService.AttachProductTag(productTag, product.Id);
        }
    }

    protected virtual async Task<T> PrepareAddProductModel<T>() where T : ProductModel.AddProductModel, new()
    {
        var storeId = scope.DefaultStoreId ?? "";
        var model = new T();

        //stores - same capability gate as PrepareProductListModel: Vendor's original PrepareAddProductModel<T>
        //never populated a stores dropdown at all (vendors don't pick stores), so this must not run for
        //Vendor even though its storeId also resolves to "".
        if (scope.ShowStoreSelector)
        {
            model.AvailableStores.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = " " });
            foreach (var s in (await storeService.GetAllStores()).Where(x =>
                         x.Id == storeId || string.IsNullOrWhiteSpace(storeId)))
                model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
        }

        //vendors - only when the host isn't already forced onto a single vendor (scope.DefaultVendorId):
        //Vendor's original PrepareAddProductModel<T> never populated a vendor picker at all (matches the
        //ShowStoreSelector gate above for the same reason - there's nothing to pick, the search is always
        //forced to the current vendor).
        if (scope.DefaultVendorId is null)
        {
            model.AvailableVendors.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = " " });
            foreach (var v in await vendorService.GetAllVendors(showHidden: true))
                model.AvailableVendors.Add(new SelectListItem { Text = v.Name, Value = v.Id });
        }

        //product types
        model.AvailableProductTypes = enumTranslationService.ToSelectList(ProductType.SimpleProduct, false).ToList();
        model.AvailableProductTypes.Insert(0,
            new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "0" });

        return model;
    }
}