public virtual int GetComparedProductsCount()
        {
            var searchContext = new ProductSearchContext()
            {
                ProductIds = GetComparedProductIds()
            };

            if (searchContext.ProductIds.Count <= 0)
            {
                return(0);
            }

            var query = _productService.PrepareProductSearchQuery(searchContext);

            return(query.Count());
        }
Example #2
0
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
        /// <returns>Product entity</returns>
        public virtual Product CopyProduct(Product product, string newName, bool isPublished, bool copyImages, bool copyAssociatedProducts = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            if (String.IsNullOrEmpty(newName))
            {
                throw new ArgumentException("Product name is required");
            }

            Product productCopy = null;
            var     utcNow      = DateTime.UtcNow;

            // product download & sample download
            int downloadId       = product.DownloadId;
            int?sampleDownloadId = product.SampleDownloadId;

            if (product.IsDownload)
            {
                var download = _downloadService.GetDownloadById(product.DownloadId);
                if (download != null)
                {
                    var downloadCopy = new Download()
                    {
                        DownloadGuid   = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl    = download.DownloadUrl,
                        DownloadBinary = download.DownloadBinary,
                        ContentType    = download.ContentType,
                        Filename       = download.Filename,
                        Extension      = download.Extension,
                        IsNew          = download.IsNew,
                    };
                    _downloadService.InsertDownload(downloadCopy);
                    downloadId = downloadCopy.Id;
                }

                if (product.HasSampleDownload)
                {
                    var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault());
                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download()
                        {
                            DownloadGuid   = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl    = sampleDownload.DownloadUrl,
                            DownloadBinary = sampleDownload.DownloadBinary,
                            ContentType    = sampleDownload.ContentType,
                            Filename       = sampleDownload.Filename,
                            Extension      = sampleDownload.Extension,
                            IsNew          = sampleDownload.IsNew
                        };
                        _downloadService.InsertDownload(sampleDownloadCopy);
                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            // product
            productCopy = new Product()
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                ProductTemplateId    = product.ProductTemplateId,
                AdminComment         = product.AdminComment,
                ShowOnHomePage       = product.ShowOnHomePage,
                MetaKeywords         = product.MetaKeywords,
                MetaDescription      = product.MetaDescription,
                MetaTitle            = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores      = product.LimitedToStores,
                Sku = product.Sku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin                             = product.Gtin,
                IsGiftCard                       = product.IsGiftCard,
                GiftCardType                     = product.GiftCardType,
                RequireOtherProducts             = product.RequireOtherProducts,
                RequiredProductIds               = product.RequiredProductIds,
                AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
                IsDownload                       = product.IsDownload,
                DownloadId                       = downloadId,
                UnlimitedDownloads               = product.UnlimitedDownloads,
                MaxNumberOfDownloads             = product.MaxNumberOfDownloads,
                DownloadExpirationDays           = product.DownloadExpirationDays,
                DownloadActivationType           = product.DownloadActivationType,
                HasSampleDownload                = product.HasSampleDownload,
                SampleDownloadId                 = sampleDownloadId,
                HasUserAgreement                 = product.HasUserAgreement,
                UserAgreementText                = product.UserAgreementText,
                IsRecurring                      = product.IsRecurring,
                RecurringCycleLength             = product.RecurringCycleLength,
                RecurringCyclePeriod             = product.RecurringCyclePeriod,
                RecurringTotalCycles             = product.RecurringTotalCycles,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                IsEsd                            = product.IsEsd,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                ManageInventoryMethod            = product.ManageInventoryMethod,
                StockQuantity                    = product.StockQuantity,
                DisplayStockAvailability         = product.DisplayStockAvailability,
                DisplayStockQuantity             = product.DisplayStockQuantity,
                MinStockQuantity                 = product.MinStockQuantity,
                LowStockActivityId               = product.LowStockActivityId,
                NotifyAdminForQuantityBelow      = product.NotifyAdminForQuantityBelow,
                BackorderMode                    = product.BackorderMode,
                AllowBackInStockSubscriptions    = product.AllowBackInStockSubscriptions,
                OrderMinimumQuantity             = product.OrderMinimumQuantity,
                OrderMaximumQuantity             = product.OrderMaximumQuantity,
                AllowedQuantities                = product.AllowedQuantities,
                DisableBuyButton                 = product.DisableBuyButton,
                DisableWishlistButton            = product.DisableWishlistButton,
                AvailableForPreOrder             = product.AvailableForPreOrder,
                CallForPrice                     = product.CallForPrice,
                Price                            = product.Price,
                OldPrice                         = product.OldPrice,
                ProductCost                      = product.ProductCost,
                SpecialPrice                     = product.SpecialPrice,
                SpecialPriceStartDateTimeUtc     = product.SpecialPriceStartDateTimeUtc,
                SpecialPriceEndDateTimeUtc       = product.SpecialPriceEndDateTimeUtc,
                CustomerEntersPrice              = product.CustomerEntersPrice,
                MinimumCustomerEnteredPrice      = product.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice      = product.MaximumCustomerEnteredPrice,
                LowestAttributeCombinationPrice  = product.LowestAttributeCombinationPrice,
                Weight                           = product.Weight,
                Length                           = product.Length,
                Width                            = product.Width,
                Height                           = product.Height,
                AvailableStartDateTimeUtc        = product.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc          = product.AvailableEndDateTimeUtc,
                DisplayOrder                     = product.DisplayOrder,
                Published                        = isPublished,
                Deleted                          = product.Deleted,
                CreatedOnUtc                     = utcNow,
                UpdatedOnUtc                     = utcNow,
                DeliveryTimeId                   = product.DeliveryTimeId,
                QuantityUnitId                   = product.QuantityUnitId,
                BasePriceEnabled                 = product.BasePriceEnabled,
                BasePriceMeasureUnit             = product.BasePriceMeasureUnit,
                BasePriceAmount                  = product.BasePriceAmount,
                BasePriceBaseAmount              = product.BasePriceBaseAmount,
                BundleTitleText                  = product.BundleTitleText,
                BundlePerItemShipping            = product.BundlePerItemShipping,
                BundlePerItemPricing             = product.BundlePerItemPricing,
                BundlePerItemShoppingCart        = product.BundlePerItemShoppingCart
            };

            _productService.InsertProduct(productCopy);

            //search engine name
            _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

            var languages = _languageService.GetAllLanguages(true);

            //localization
            foreach (var lang in languages)
            {
                var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                if (!String.IsNullOrEmpty(name))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
                }

                var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(shortDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
                }

                var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(fullDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
                }

                var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaKeywords))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
                }

                var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
                }

                var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaTitle))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
                }

                var bundleTitleText = product.GetLocalized(x => x.BundleTitleText, lang.Id, false, false);
                if (!String.IsNullOrEmpty(bundleTitleText))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.BundleTitleText, bundleTitleText, lang.Id);
                }

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
            }

            // product pictures
            if (copyImages)
            {
                foreach (var productPicture in product.ProductPictures)
                {
                    var picture     = productPicture.Picture;
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(newName),
                        true);
                    _productService.InsertProductPicture(new ProductPicture()
                    {
                        ProductId    = productCopy.Id,
                        PictureId    = pictureCopy.Id,
                        DisplayOrder = productPicture.DisplayOrder
                    });
                }
            }

            // product <-> categories mappings
            foreach (var productCategory in product.ProductCategories)
            {
                var productCategoryCopy = new ProductCategory()
                {
                    ProductId         = productCopy.Id,
                    CategoryId        = productCategory.CategoryId,
                    IsFeaturedProduct = productCategory.IsFeaturedProduct,
                    DisplayOrder      = productCategory.DisplayOrder
                };

                _categoryService.InsertProductCategory(productCategoryCopy);
            }

            // product <-> manufacturers mappings
            foreach (var productManufacturers in product.ProductManufacturers)
            {
                var productManufacturerCopy = new ProductManufacturer()
                {
                    ProductId         = productCopy.Id,
                    ManufacturerId    = productManufacturers.ManufacturerId,
                    IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
                    DisplayOrder      = productManufacturers.DisplayOrder
                };

                _manufacturerService.InsertProductManufacturer(productManufacturerCopy);
            }

            // product <-> releated products mappings
            foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true))
            {
                _productService.InsertRelatedProduct(
                    new RelatedProduct()
                {
                    ProductId1   = productCopy.Id,
                    ProductId2   = relatedProduct.ProductId2,
                    DisplayOrder = relatedProduct.DisplayOrder
                });
            }

            // product <-> cross sells mappings
            foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
            {
                _productService.InsertCrossSellProduct(
                    new CrossSellProduct()
                {
                    ProductId1 = productCopy.Id,
                    ProductId2 = csProduct.ProductId2,
                });
            }

            // product specifications
            foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
            {
                var psaCopy = new ProductSpecificationAttribute()
                {
                    ProductId = productCopy.Id,
                    SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                    AllowFiltering    = productSpecificationAttribute.AllowFiltering,
                    ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                    DisplayOrder      = productSpecificationAttribute.DisplayOrder
                };
                _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
            }

            //store mapping
            var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);

            foreach (var id in selectedStoreIds)
            {
                _storeMappingService.InsertStoreMapping(productCopy, id);
            }

            // product <-> attributes mappings
            var associatedAttributes      = new Dictionary <int, int>();
            var associatedAttributeValues = new Dictionary <int, int>();

            foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductId(product.Id))
            {
                var productVariantAttributeCopy = new ProductVariantAttribute()
                {
                    ProductId              = productCopy.Id,
                    ProductAttributeId     = productVariantAttribute.ProductAttributeId,
                    TextPrompt             = productVariantAttribute.TextPrompt,
                    IsRequired             = productVariantAttribute.IsRequired,
                    AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId,
                    DisplayOrder           = productVariantAttribute.DisplayOrder
                };
                _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id);

                // product variant attribute values
                var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id);
                foreach (var productVariantAttributeValue in productVariantAttributeValues)
                {
                    var pvavCopy = new ProductVariantAttributeValue()
                    {
                        ProductVariantAttributeId = productVariantAttributeCopy.Id,
                        Name             = productVariantAttributeValue.Name,
                        ColorSquaresRgb  = productVariantAttributeValue.ColorSquaresRgb,
                        PriceAdjustment  = productVariantAttributeValue.PriceAdjustment,
                        WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                        IsPreSelected    = productVariantAttributeValue.IsPreSelected,
                        DisplayOrder     = productVariantAttributeValue.DisplayOrder,
                        ValueTypeId      = productVariantAttributeValue.ValueTypeId,
                        LinkedProductId  = productVariantAttributeValue.LinkedProductId,
                        Quantity         = productVariantAttributeValue.Quantity,
                    };
                    _productAttributeService.InsertProductVariantAttributeValue(pvavCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productVariantAttributeValue.Id, pvavCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productVariantAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(pvavCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }

            // attribute combinations
            foreach (var combination in _productAttributeService.GetAllProductVariantAttributeCombinations(product.Id))
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml = "";
                var    parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml);
                foreach (var oldPva in parsedProductVariantAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldPva.Id))
                    {
                        int newPvaId = associatedAttributes[oldPva.Id];
                        var newPva   = _productAttributeService.GetProductVariantAttributeById(newPvaId);
                        if (newPva != null)
                        {
                            var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id);
                            foreach (var oldPvaValueStr in oldPvaValuesStr)
                            {
                                if (newPva.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldPvaValue = int.Parse(oldPvaValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldPvaValue))
                                    {
                                        int newPvavId = associatedAttributeValues[oldPvaValue];
                                        var newPvav   = _productAttributeService.GetProductVariantAttributeValueById(newPvavId);
                                        if (newPvav != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                           newPva, newPvav.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                   newPva, oldPvaValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductVariantAttributeCombination()
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,

                    // SmartStore extension
                    Sku  = combination.Sku,
                    Gtin = combination.Gtin,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Price = combination.Price,
                    AssignedPictureIds = copyImages ? combination.AssignedPictureIds : null,
                    Length             = combination.Length,
                    Width               = combination.Width,
                    Height              = combination.Height,
                    BasePriceAmount     = combination.BasePriceAmount,
                    BasePriceBaseAmount = combination.BasePriceBaseAmount,
                    DeliveryTimeId      = combination.DeliveryTimeId,
                    QuantityUnitId      = combination.QuantityUnitId,
                    IsActive            = combination.IsActive
                                          //IsDefaultCombination = combination.IsDefaultCombination
                };
                _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy);
            }

            // tier prices
            foreach (var tierPrice in product.TierPrices)
            {
                _productService.InsertTierPrice(
                    new TierPrice()
                {
                    ProductId      = productCopy.Id,
                    StoreId        = tierPrice.StoreId,
                    CustomerRoleId = tierPrice.CustomerRoleId,
                    Quantity       = tierPrice.Quantity,
                    Price          = tierPrice.Price
                });
            }

            // product <-> discounts mapping
            foreach (var discount in product.AppliedDiscounts)
            {
                productCopy.AppliedDiscounts.Add(discount);
                _productService.UpdateProduct(productCopy);
            }

            // update "HasTierPrices" and "HasDiscountsApplied" properties
            _productService.UpdateHasTierPricesProperty(productCopy);
            _productService.UpdateLowestAttributeCombinationPriceProperty(productCopy);
            _productService.UpdateHasDiscountsApplied(productCopy);

            // associated products
            if (copyAssociatedProducts && product.ProductType != ProductType.BundledProduct)
            {
                var searchContext = new ProductSearchContext()
                {
                    ParentGroupedProductId = product.Id,
                    PageSize   = int.MaxValue,
                    ShowHidden = true
                };

                string copyOf             = _localizationService.GetResource("Admin.Common.CopyOf");
                var    associatedProducts = _productService.SearchProducts(searchContext);

                foreach (var associatedProduct in associatedProducts)
                {
                    var associatedProductCopy = CopyProduct(associatedProduct, string.Format("{0} {1}", copyOf, associatedProduct.Name), isPublished, copyImages, false);
                    associatedProductCopy.ParentGroupedProductId = productCopy.Id;

                    _productService.UpdateProduct(productCopy);
                }
            }

            // bundled products
            var bundledItems = _productService.GetBundleItems(product.Id, true);

            foreach (var bundleItem in bundledItems)
            {
                var newBundleItem = bundleItem.Item.Clone();
                newBundleItem.BundleProductId = productCopy.Id;
                newBundleItem.CreatedOnUtc    = utcNow;
                newBundleItem.UpdatedOnUtc    = utcNow;

                _productService.InsertBundleItem(newBundleItem);

                foreach (var itemFilter in bundleItem.Item.AttributeFilters)
                {
                    var newItemFilter = itemFilter.Clone();
                    newItemFilter.BundleItemId = newBundleItem.Id;

                    _productAttributeService.InsertProductBundleItemAttributeFilter(newItemFilter);
                }
            }

            return(productCopy);
        }
        public ActionResult ProductAddPopupList(GridCommand command, ManufacturerModel.AddManufacturerProductModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return AccessDeniedView();

            var gridModel = new GridModel();

            var ctx = new ProductSearchContext();

            if (model.SearchCategoryId > 0)
                ctx.CategoryIds.Add(model.SearchCategoryId);

            ctx.ManufacturerId = model.SearchManufacturerId;
            ctx.Keywords = model.SearchProductName;
            ctx.LanguageId = _workContext.WorkingLanguage.Id;
            ctx.OrderBy = ProductSortingEnum.Position;
            ctx.PageIndex = command.Page - 1;
            ctx.PageSize = command.PageSize;
            ctx.ShowHidden = true;
            ctx.ProductType = model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null;

            var products = _productService.SearchProducts(ctx);

            gridModel.Data = products.Select(x =>
            {
                var productModel = x.ToModel();
                productModel.ProductTypeName = x.GetProductTypeLabel(_localizationService);

                return productModel;
            });
            gridModel.Total = products.TotalCount;
            return new JsonResult
            {
                Data = gridModel
            };
        }
Example #4
0
        public ActionResult RecentlyAddedProducts(CatalogPagingFilteringModel command)
        {
            var model = new RecentlyAddedProductsModel();

            if (_catalogSettings.RecentlyAddedProductsEnabled)
            {
                IList<int> filterableSpecificationAttributeOptionIds = null;

                var ctx = new ProductSearchContext();
                ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
                //ctx.OrderBy = (ProductSortingEnum)command.OrderBy;
                ctx.OrderBy = ProductSortingEnum.CreatedOn;
                //ctx.PageSize = command.PageSize;
                ctx.PageSize = _catalogSettings.RecentlyAddedProductsNumber;
                //ctx.PageIndex = command.PageNumber - 1;
                ctx.FilterableSpecificationAttributeOptionIds = filterableSpecificationAttributeOptionIds;
                ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                ctx.VisibleIndividuallyOnly = true;

                var products = _productService.SearchProducts(ctx);

                //var products = _productService.SearchProducts(ctx).Take(_catalogSettings.RecentlyAddedProductsNumber).OrderBy((ProductSortingEnum)command.OrderBy);

                model.Products.AddRange(_helper.PrepareProductOverviewModels(products));
                //model.PagingFilteringContext.LoadPagedList(products);
            }
            return View(model);
        }
Example #5
0
        public ActionResult Manufacturer(int manufacturerId, CatalogPagingFilteringModel command)
        {
            var manufacturer = _manufacturerService.GetManufacturerById(manufacturerId);
            if (manufacturer == null || manufacturer.Deleted)
                return HttpNotFound();

            //Check whether the current user has a "Manage catalog" permission
            //It allows him to preview a manufacturer before publishing
            if (!manufacturer.Published && !_services.Permissions.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpNotFound();

            //Store mapping
            if (!_storeMappingService.Authorize(manufacturer))
                return HttpNotFound();

            //'Continue shopping' URL
            _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentCustomer,
                SystemCustomerAttributeNames.LastContinueShoppingPage,
                _services.WebHelper.GetThisPageUrl(false),
                _services.StoreContext.CurrentStore.Id);

            if (command.PageNumber <= 0)
                command.PageNumber = 1;

            var model = manufacturer.ToModel();

            // prepare picture model
            model.PictureModel = _helper.PrepareManufacturerPictureModel(manufacturer, model.Name);

            if (command.OrderBy == (int)ProductSortingEnum.Initial)
            {
                command.OrderBy = (int)_catalogSettings.DefaultSortOrder;
            }

            _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
            {
                AllowCustomersToSelectPageSize = manufacturer.AllowCustomersToSelectPageSize,
                PageSize = manufacturer.PageSize,
                PageSizeOptions = manufacturer.PageSizeOptions
            });

            //price ranges
            model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(manufacturer.PriceRanges, _services.WebHelper, _priceFormatter);
            var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_services.WebHelper, manufacturer.PriceRanges);
            decimal? minPriceConverted = null;
            decimal? maxPriceConverted = null;
            if (selectedPriceRange != null)
            {
                if (selectedPriceRange.From.HasValue)
                    minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _services.WorkContext.WorkingCurrency);

                if (selectedPriceRange.To.HasValue)
                    maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _services.WorkContext.WorkingCurrency);
            }

            var customerRolesIds = _services.WorkContext.CurrentCustomer.CustomerRoles.Where(x => x.Active).Select(x => x.Id).ToList();

            // Featured products
            if (!_catalogSettings.IgnoreFeaturedProducts)
            {
                IPagedList<Product> featuredProducts = null;

                string cacheKey = ModelCacheEventConsumer.MANUFACTURER_HAS_FEATURED_PRODUCTS_KEY.FormatInvariant(manufacturerId, string.Join(",", customerRolesIds), _services.StoreContext.CurrentStore.Id);
                var hasFeaturedProductsCache = _services.Cache.Get<bool?>(cacheKey);

                var ctx = new ProductSearchContext();
                ctx.ManufacturerId = manufacturer.Id;
                ctx.FeaturedProducts = true;
                ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
                ctx.OrderBy = ProductSortingEnum.Position;
                ctx.PageSize = int.MaxValue;
                ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                ctx.VisibleIndividuallyOnly = true;

                if (!hasFeaturedProductsCache.HasValue)
                {
                    featuredProducts = _productService.SearchProducts(ctx);
                    hasFeaturedProductsCache = featuredProducts.TotalCount > 0;
                    _services.Cache.Set(cacheKey, hasFeaturedProductsCache, 240);
                }

                if (hasFeaturedProductsCache.Value && featuredProducts == null)
                {
                    featuredProducts = _productService.SearchProducts(ctx);
                }

                if (featuredProducts != null)
                {
                    model.FeaturedProducts = _helper.PrepareProductOverviewModels(featuredProducts, prepareColorAttributes: true).ToList();
                }
            }

            //products
            var ctx2 = new ProductSearchContext();
            ctx2.ManufacturerId = manufacturer.Id;
            ctx2.FeaturedProducts = _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false;
            ctx2.PriceMin = minPriceConverted;
            ctx2.PriceMax = maxPriceConverted;
            ctx2.LanguageId = _services.WorkContext.WorkingLanguage.Id;
            ctx2.OrderBy = (ProductSortingEnum)command.OrderBy;
            ctx2.PageIndex = command.PageNumber - 1;
            ctx2.PageSize = command.PageSize;
            ctx2.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
            ctx2.VisibleIndividuallyOnly = true;

            var products = _productService.SearchProducts(ctx2);

            model.Products = _helper.PrepareProductOverviewModels(
                products,
                prepareColorAttributes: false,
                prepareManufacturers: command.ViewMode.IsCaseInsensitiveEqual("list")).ToList();

            model.PagingFilteringContext.LoadPagedList(products);
            //model.PagingFilteringContext.ViewMode = viewMode;

            //template
            var templateCacheKey = string.Format(ModelCacheEventConsumer.MANUFACTURER_TEMPLATE_MODEL_KEY, manufacturer.ManufacturerTemplateId);
            var templateViewPath = _services.Cache.Get(templateCacheKey, () =>
            {
                var template = _manufacturerTemplateService.GetManufacturerTemplateById(manufacturer.ManufacturerTemplateId);
                if (template == null)
                    template = _manufacturerTemplateService.GetAllManufacturerTemplates().FirstOrDefault();
                return template.ViewPath;
            });

            //activity log
            _services.CustomerActivity.InsertActivity("PublicStore.ViewManufacturer", T("ActivityLog.PublicStore.ViewManufacturer"), manufacturer.Name);

            return View(templateViewPath, model);
        }
Example #6
0
        public ActionResult SearchTermAutoComplete(string term)
        {
            if (String.IsNullOrWhiteSpace(term) || term.Length < _catalogSettings.ProductSearchTermMinimumLength)
                return Content("");

            // products
            var pageSize = _catalogSettings.ProductSearchAutoCompleteNumberOfProducts > 0 ? _catalogSettings.ProductSearchAutoCompleteNumberOfProducts : 10;

            var ctx = new ProductSearchContext();
            ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
            ctx.Keywords = term;
            ctx.SearchSku = !_catalogSettings.SuppressSkuSearch;
            ctx.OrderBy = ProductSortingEnum.Position;
            ctx.PageSize = pageSize;
            ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
            ctx.VisibleIndividuallyOnly = true;

            var products = _productService.SearchProducts(ctx);

            var models = _helper.PrepareProductOverviewModels(
                products,
                false,
                _catalogSettings.ShowProductImagesInSearchAutoComplete,
                _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage).ToList();

            var result = (from p in models
                          select new
                          {
                              label = p.Name,
                              secondary = p.ShortDescription.Truncate(70, "...") ?? "",
                              producturl = Url.RouteUrl("Product", new { SeName = p.SeName }),
                              productpictureurl = p.DefaultPictureModel.ImageUrl
                          })
                          .ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// Print product collection to PDF
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="products">Products</param>
        /// <param name="lang">Language</param>
        public virtual void PrintProductsToPdf(Stream stream, IList<Product> products, Language lang)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            if (products == null)
                throw new ArgumentNullException("products");

            if (lang == null)
                throw new ArgumentNullException("lang");

            var pageSize = PageSize.A4;

            if (_pdfSettings.LetterPageSizeEnabled)
            {
                pageSize = PageSize.LETTER;
            }

            var doc = new Document(pageSize);
            PdfWriter.GetInstance(doc, stream);
            doc.Open();

            //fonts
            var titleFont = GetFont();
            titleFont.SetStyle(Font.BOLD);
            titleFont.Color = BaseColor.BLACK;
            var font = GetFont();

            int productNumber = 1;
            int prodCount = products.Count;
			string currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
			string measureWeightName = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).Name;
			string labelPrice = _localizationService.GetResource("PDFProductCatalog.Price", lang.Id);
			string labelSku = _localizationService.GetResource("PDFProductCatalog.SKU", lang.Id);
			string labelWeight = _localizationService.GetResource("PDFProductCatalog.Weight", lang.Id);
			string labelStock = _localizationService.GetResource("PDFProductCatalog.StockQuantity", lang.Id);

            foreach (var product in products)
            {
                string productName = product.GetLocalized(x => x.Name, lang.Id);
                string productFullDescription = product.GetLocalized(x => x.FullDescription, lang.Id);

                doc.Add(new Paragraph(String.Format("{0}. {1}", productNumber, productName), titleFont));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(HtmlUtils.StripTags(HtmlUtils.ConvertHtmlToPlainText(productFullDescription)), font));
                doc.Add(new Paragraph(" "));

				if (product.ProductType == ProductType.SimpleProduct || product.ProductType == ProductType.BundledProduct)
				{
					doc.Add(new Paragraph(String.Format("{0}: {1} {2}", labelPrice, product.Price.ToString("0.00"), currencyCode), font));
					doc.Add(new Paragraph(String.Format("{0}: {1}", labelSku, product.Sku), font));

					if (product.IsShipEnabled && product.Weight > Decimal.Zero)
						doc.Add(new Paragraph(String.Format("{0}: {1} {2}", labelWeight, product.Weight.ToString("0.00"), measureWeightName), font));

					if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock)
						doc.Add(new Paragraph(String.Format("{0}: {1}", labelStock, product.StockQuantity), font));

					doc.Add(new Paragraph(" "));
				}

                var pictures = _pictureService.GetPicturesByProductId(product.Id);
                if (pictures.Count > 0)
                {
                    var table = new PdfPTable(2);
                    table.WidthPercentage = 100f;

                    for (int i = 0; i < pictures.Count; i++)
                    {
                        var pic = pictures[i];
                        if (pic != null)
                        {
                            var picBinary = _pictureService.LoadPictureBinary(pic);
                            if (picBinary != null && picBinary.Length > 0)
                            {
                                var pictureLocalPath = _pictureService.GetThumbLocalPath(pic, 200, false);
								if (pictureLocalPath.HasValue()) {
									var cell = new PdfPCell(Image.GetInstance(pictureLocalPath));
									cell.HorizontalAlignment = Element.ALIGN_LEFT;
									cell.Border = Rectangle.NO_BORDER;
									cell.PaddingBottom = 5f;
									table.AddCell(cell);
								}
                            }
                        }
                    }

                    if (pictures.Count % 2 > 0)
                    {
                        var cell = new PdfPCell(new Phrase(" "));
                        cell.Border = Rectangle.NO_BORDER;
                        table.AddCell(cell);
                    }

                    doc.Add(table);
                    doc.Add(new Paragraph(" "));
                }

				if (product.ProductType == ProductType.GroupedProduct)
				{
					//grouped product. render its associated products
					int pNum = 1;
					var searchContext = new ProductSearchContext()
					{
						ParentGroupedProductId = product.Id,
						ShowHidden = true
					};

					foreach (var associatedProduct in _productService.SearchProducts(searchContext))
					{
						doc.Add(new Paragraph(String.Format("{0}-{1}. {2}", productNumber, pNum, associatedProduct.GetLocalized(x => x.Name, lang.Id)), font));
						doc.Add(new Paragraph(" "));

						//uncomment to render associated product description
						//string apDescription = associatedProduct.GetLocalized(x => x.ShortDescription, lang.Id);
						//if (!String.IsNullOrEmpty(apDescription))
						//{
						//    doc.Add(new Paragraph(HtmlHelper.StripTags(HtmlHelper.ConvertHtmlToPlainText(apDescription)), font));
						//    doc.Add(new Paragraph(" "));
						//}

						//uncomment to render associated product picture
						//var apPicture = _pictureService.GetPicturesByProductId(associatedProduct.Id).FirstOrDefault();
						//if (apPicture != null)
						//{
						//    var picBinary = _pictureService.LoadPictureBinary(apPicture);
						//    if (picBinary != null && picBinary.Length > 0)
						//    {
						//        var pictureLocalPath = _pictureService.GetThumbLocalPath(apPicture, 200, false);
						//        doc.Add(Image.GetInstance(pictureLocalPath));
						//    }
						//}

						doc.Add(new Paragraph(String.Format("{0}: {1} {2}", labelPrice, associatedProduct.Price.ToString("0.00"), currencyCode), font));
						doc.Add(new Paragraph(String.Format("{0}: {1}", labelSku, associatedProduct.Sku), font));

						if (associatedProduct.IsShipEnabled && associatedProduct.Weight > Decimal.Zero)
							doc.Add(new Paragraph(String.Format("{0}: {1} {2}", labelWeight, associatedProduct.Weight.ToString("0.00"), measureWeightName), font));

						if (associatedProduct.ManageInventoryMethod == ManageInventoryMethod.ManageStock)
							doc.Add(new Paragraph(String.Format("{0}: {1}", labelStock, associatedProduct.StockQuantity), font));

						doc.Add(new Paragraph(" "));

						pNum++;
					}
				}
				else if (product.ProductType == ProductType.BundledProduct)
				{
					int pNum = 1;

					foreach (var item in _productService.GetBundleItems(product.Id).Select(x => x.Item))
					{
						doc.Add(new Paragraph("{0}-{1}. {2}".FormatWith(productNumber, pNum, item.GetLocalizedName(lang.Id)), font));

						doc.Add(new Paragraph(String.Format("{0}: {1} {2}", labelPrice, item.Product.Price.ToString("0.00"), currencyCode), font));
						doc.Add(new Paragraph(String.Format("{0}: {1}", labelSku, item.Product.Sku), font));

						if (item.Product.IsShipEnabled && item.Product.Weight > Decimal.Zero)
							doc.Add(new Paragraph(String.Format("{0}: {1} {2}", labelWeight, item.Product.Weight.ToString("0.00"), measureWeightName), font));

						if (item.Product.ManageInventoryMethod == ManageInventoryMethod.ManageStock)
							doc.Add(new Paragraph(String.Format("{0}: {1}", labelStock, item.Product.StockQuantity), font));

						doc.Add(new Paragraph(" "));

						pNum++;
					}
				}

                productNumber++;

                if (productNumber <= prodCount)
                {
                    doc.NewPage();
                }
            }

            doc.Close();
        }
        private IQueryable<Product> AllProducts(List<int> categoryIds)
        {
            if (_products == null)
            {
                var searchContext = new ProductSearchContext
                {
                    Query = _productRepository.TableUntracked,
                    FeaturedProducts = (_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false),
                    StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode,
                    VisibleIndividuallyOnly = true
                };

                if (categoryIds != null && categoryIds.Count > 1)
                {
                    _products = _productService.PrepareProductSearchQuery(searchContext);

                    var distinctIds = (
                        from p in _productRepository.TableUntracked
                        join pc in _productCategoryRepository.TableUntracked on p.Id equals pc.ProductId
                        where categoryIds.Contains(pc.CategoryId)
                        select p.Id).Distinct();

                    _products =
                        from p in _products
                        join x in distinctIds on p.Id equals x
                        select p;
                }
                else
                {
                    searchContext.CategoryIds = categoryIds;

                    _products = _productService.PrepareProductSearchQuery(searchContext);
                }
            }
            return _products;
        }
        public ActionResult Sitemap()
        {
            if (!_commonSettings.SitemapEnabled)
                return RedirectToRoute("HomePage");

            var model = new SitemapModel();
            if (_commonSettings.SitemapIncludeCategories)
            {
                var categories = _categoryService.GetAllCategories();
                model.Categories = categories.Select(x => x.ToModel()).ToList();
            }
            if (_commonSettings.SitemapIncludeManufacturers)
            {
                var manufacturers = _manufacturerService.GetAllManufacturers();
                model.Manufacturers = manufacturers.Select(x => x.ToModel()).ToList();
            }
            if (_commonSettings.SitemapIncludeProducts)
            {
                //limit product to 200 until paging is supported on this page
                IList<int> filterableSpecificationAttributeOptionIds = null;

                var productSearchContext = new ProductSearchContext();

                productSearchContext.OrderBy = ProductSortingEnum.Position;
                productSearchContext.PageSize = 200;
                productSearchContext.FilterableSpecificationAttributeOptionIds = filterableSpecificationAttributeOptionIds;
				productSearchContext.StoreId = _storeContext.CurrentStoreIdIfMultiStoreMode;
				productSearchContext.VisibleIndividuallyOnly = true;

                var products = _productService.SearchProducts(productSearchContext);

                model.Products = products.Select(product => new ProductOverviewModel()
                {
                    Id = product.Id,
                    Name = product.GetLocalized(x => x.Name).EmptyNull(),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription = product.GetLocalized(x => x.FullDescription),
                    SeName = product.GetSeName(),
                }).ToList();
            }
            if (_commonSettings.SitemapIncludeTopics)
            {
				var topics = _topicService.GetAllTopics(_storeContext.CurrentStore.Id)
					 .ToList()
					 .FindAll(t => t.IncludeInSitemap);
                model.Topics = topics.Select(topic => new TopicModel()
                {
                    Id = topic.Id,
                    SystemName = topic.SystemName,
                    IncludeInSitemap = topic.IncludeInSitemap,
                    IsPasswordProtected = topic.IsPasswordProtected,
                    Title = topic.GetLocalized(x => x.Title),
                })
                .ToList();
            }
            return View(model);
        }
        public List<Product> QualifiedProductsByProduct(IProductService productService, Product product, Store store)
        {
            var lst = new List<Product>();

            if (product.ProductType == ProductType.SimpleProduct || product.ProductType == ProductType.BundledProduct)
            {
                lst.Add(product);
            }
            else if (product.ProductType == ProductType.GroupedProduct)
            {
                var associatedSearchContext = new ProductSearchContext()
                {
                    OrderBy = ProductSortingEnum.CreatedOn,
                    PageSize = int.MaxValue,
                    StoreId = store.Id,
                    VisibleIndividuallyOnly = false,
                    ParentGroupedProductId = product.Id
                };

                lst.AddRange(productService.SearchProducts(associatedSearchContext));
            }
            return lst;
        }
        public ActionResult RecentlyAddedProductsRss()
        {
            var feed = new SyndicationFeed(
                                string.Format("{0}: {1}", _services.StoreContext.CurrentStore.Name, T("RSS.RecentlyAddedProducts")),
                                T("RSS.InformationAboutProducts"),
                                new Uri(_services.WebHelper.GetStoreLocation(false)),
                                "RecentlyAddedProductsRSS",
                                DateTime.UtcNow);

            if (!_catalogSettings.RecentlyAddedProductsEnabled)
                return new RssActionResult() { Feed = feed };

            var items = new List<SyndicationItem>();

            var ctx = new ProductSearchContext();
            ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
            ctx.OrderBy = ProductSortingEnum.CreatedOn;
            ctx.PageSize = _catalogSettings.RecentlyAddedProductsNumber;
            ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
            ctx.VisibleIndividuallyOnly = true;

            var products = _productService.SearchProducts(ctx);

            foreach (var product in products)
            {
                string productUrl = Url.RouteUrl("Product", new { SeName = product.GetSeName() }, "http");
                if (!String.IsNullOrEmpty(productUrl))
                {
                    items.Add(new SyndicationItem(product.GetLocalized(x => x.Name), product.GetLocalized(x => x.ShortDescription), new Uri(productUrl), String.Format("RecentlyAddedProduct:{0}", product.Id), product.CreatedOnUtc));
                }
            }
            feed.Items = items;
            return new RssActionResult() { Feed = feed };
        }
        private void WriteProducts()
        {
            string location = _webHelper.GetStoreLocation(false);
            
            var ctx = new ProductSearchContext()
			{
				OrderBy = ProductSortingEnum.CreatedOn,
				PageSize = int.MaxValue,
				StoreId = _storeContext.CurrentStoreIdIfMultiStoreMode,
				VisibleIndividuallyOnly = true
			};

			var products = _productService.SearchProducts(ctx);
            foreach (var product in products)
            {
                //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                var url = string.Format("{0}{1}", location, product.GetSeName());
                var updateFrequency = UpdateFrequency.Weekly;
                var updateTime = product.UpdatedOnUtc;
                WriteUrlLocation(url, updateFrequency, updateTime);
            }
        }
        public virtual int GetComparedProductsCount()
        {
			var searchContext = new ProductSearchContext()
			{
				ProductIds = GetComparedProductIds()
			};

			if (searchContext.ProductIds.Count <= 0)
				return 0;

			var query = _productService.PrepareProductSearchQuery(searchContext);

            return query.Count();
        }
Example #14
0
        public ActionResult Sitemap()
        {
            if (!_commonSettings.Value.SitemapEnabled)
                return HttpNotFound();

            var roleIds = _services.WorkContext.CurrentCustomer.CustomerRoles.Where(x => x.Active).Select(x => x.Id).ToList();
            string cacheKey = ModelCacheEventConsumer.SITEMAP_PAGE_MODEL_KEY.FormatInvariant(_services.WorkContext.WorkingLanguage.Id, string.Join(",", roleIds), _services.StoreContext.CurrentStore.Id);

            var result = _services.Cache.Get(cacheKey, () =>
            {
                var model = new SitemapModel();
                if (_commonSettings.Value.SitemapIncludeCategories)
                {
                    var categories = _categoryService.Value.GetAllCategories();
                    model.Categories = categories.Select(x => x.ToModel()).ToList();
                }

                if (_commonSettings.Value.SitemapIncludeManufacturers)
                {
                    var manufacturers = _manufacturerService.Value.GetAllManufacturers();
                    model.Manufacturers = manufacturers.Select(x => x.ToModel()).ToList();
                }

                if (_commonSettings.Value.SitemapIncludeProducts)
                {
                    //limit product to 200 until paging is supported on this page
                    IList<int> filterableSpecificationAttributeOptionIds = null;

                    var productSearchContext = new ProductSearchContext();

                    productSearchContext.OrderBy = ProductSortingEnum.Position;
                    productSearchContext.PageSize = 200;
                    productSearchContext.FilterableSpecificationAttributeOptionIds = filterableSpecificationAttributeOptionIds;
                    productSearchContext.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                    productSearchContext.VisibleIndividuallyOnly = true;

                    var products = _productService.Value.SearchProducts(productSearchContext);

                    model.Products = products.Select(product => new ProductOverviewModel()
                    {
                        Id = product.Id,
                        Name = product.GetLocalized(x => x.Name).EmptyNull(),
                        ShortDescription = product.GetLocalized(x => x.ShortDescription),
                        SeName = product.GetSeName(),
                    }).ToList();
                }
                if (_commonSettings.Value.SitemapIncludeTopics)
                {
                    var topics = _topicService.Value.GetAllTopics(_services.StoreContext.CurrentStore.Id)
                         .ToList()
                         .FindAll(t => t.IncludeInSitemap);

                    model.Topics = topics.Select(topic => new TopicModel()
                    {
                        Id = topic.Id,
                        SystemName = topic.SystemName,
                        IncludeInSitemap = topic.IncludeInSitemap,
                        IsPasswordProtected = topic.IsPasswordProtected,
                        Title = topic.GetLocalized(x => x.Title),
                    })
                    .ToList();
                }
                return model;
            });

            return View(result);
        }
        public virtual void InheritAclIntoChildren(int categoryId, 
            bool touchProductsWithMultipleCategories = false,
            bool touchExistingAcls = false,
            bool categoriesOnly = false)
        {

            var category = GetCategoryById(categoryId);
            var subcategories = GetAllCategoriesByParentCategoryId(categoryId, true);
            var context = new ProductSearchContext { PageSize = int.MaxValue, ShowHidden = true };
            context.CategoryIds.AddRange(subcategories.Select(x => x.Id));
            context.CategoryIds.Add(categoryId);
            var products = _productService.SearchProducts(context);
            var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
            var categoryCustomerRoles = _aclService.GetCustomerRoleIdsWithAccess(category);

            using (var scope = new DbContextScope(ctx: _aclRepository.Context, autoDetectChanges: false, proxyCreation: false, validateOnSave: false))
            {
                _aclRepository.AutoCommitEnabled = false;

                foreach (var subcategory in subcategories)
                {
                    if (subcategory.SubjectToAcl != category.SubjectToAcl)
                    {
                        subcategory.SubjectToAcl = category.SubjectToAcl;
                        _categoryRepository.Update(subcategory);
                    }

                    var existingAclRecords = _aclService.GetAclRecords(subcategory).ToDictionary(x => x.CustomerRoleId);

                    foreach (var customerRole in allCustomerRoles)
                    {
                        if (categoryCustomerRoles.Contains(customerRole.Id))
                        {
                            if (!existingAclRecords.ContainsKey(customerRole.Id))
                            {
                                _aclRepository.Insert(new AclRecord { CustomerRole = customerRole, CustomerRoleId = customerRole.Id, EntityId = subcategory.Id, EntityName = "Category" });
                            }
                        }
                        else
                        {
                            AclRecord aclRecordToDelete;
                            if (existingAclRecords.TryGetValue(customerRole.Id, out aclRecordToDelete))
                            {
                                _aclRepository.Delete(aclRecordToDelete);
                            }
                        }
                    }
                }
                
                _aclRepository.Context.SaveChanges();

                foreach (var product in products)
                {
                    if (product.SubjectToAcl != category.SubjectToAcl)
                    {
                        product.SubjectToAcl = category.SubjectToAcl;
                        _productRepository.Update(product);
                    }

                    var existingAclRecords = _aclService.GetAclRecords(product).ToDictionary(x => x.CustomerRoleId);

                    foreach (var customerRole in allCustomerRoles)
                    {
                        if (categoryCustomerRoles.Contains(customerRole.Id))
                        {
                            if (!existingAclRecords.ContainsKey(customerRole.Id))
                            {
                                _aclRepository.Insert(new AclRecord { CustomerRole = customerRole, CustomerRoleId = customerRole.Id, EntityId = product.Id, EntityName = "Product" });
                            }
                        }
                        else
                        {
                            AclRecord aclRecordToDelete;
                            if (existingAclRecords.TryGetValue(customerRole.Id, out aclRecordToDelete))
                            {
                                _aclRepository.Delete(aclRecordToDelete);
                            }
                        }
                    }
                }

                _aclRepository.Context.SaveChanges();
            }
        }
Example #16
0
        private IQueryable<Product> AllProducts(List<int> categoryIds)
        {
            if (_products == null)
            {
                var searchContext = new ProductSearchContext()
                {
                    FeaturedProducts = (_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false),
                    StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode,
                    VisibleIndividuallyOnly = true
                };

                if (categoryIds != null && categoryIds.Count > 1)
                {
                    _products = _productService.PrepareProductSearchQuery(searchContext);

                    var distinctIds = (
                        from p in _productRepository.TableUntracked
                        join pc in _productCategoryRepository.TableUntracked on p.Id equals pc.ProductId
                        where categoryIds.Contains(pc.CategoryId)
                        select p.Id).Distinct();

                    _products =
                        from p in _products
                        join x in distinctIds on p.Id equals x
                        select p;
                }
                else
                {
                    searchContext.CategoryIds = categoryIds;

                    _products = _productService.PrepareProductSearchQuery(searchContext);
                }

                //string.Join(", ", distinctIds.ToList()).Dump();

                //_products
                //	.Select(x => new { x.Id, x.Name })
                //	.ToList()
                //	.ForEach(x => {
                //		"{0} {1}".FormatWith(x.Id, x.Name).Dump();
                //	});

                //_products.ToString().Dump(true);
            }
            return _products;
        }
        public IEnumerable<ProductOverviewModel> PrepareProductOverviewModels(IEnumerable<Product> products,
			bool preparePriceModel = true, bool preparePictureModel = true,
			int? productThumbPictureSize = null, bool prepareSpecificationAttributes = false,
			bool forceRedirectionAfterAddingToCart = false, bool prepareColorAttributes = false)
        {
            if (products == null)
                throw new ArgumentNullException("products");

            var models = new List<ProductOverviewModel>();

            foreach (var product in products)
            {
                var minPriceProduct = product;

                var model = new ProductOverviewModel()
                {
                    Id = product.Id,
                    Name = product.GetLocalized(x => x.Name).EmptyNull(),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription = product.GetLocalized(x => x.FullDescription),
                    SeName = product.GetSeName()
                };

                // price
                if (preparePriceModel)
                {
                    #region Prepare product price

                    var priceModel = new ProductOverviewModel.ProductPriceModel()
                    {
                        ForceRedirectionAfterAddingToCart = forceRedirectionAfterAddingToCart,
                        ShowDiscountSign = _catalogSettings.ShowDiscountSign
                    };

                    switch (product.ProductType)
                    {
                        case ProductType.GroupedProduct:
                            {
                                #region Grouped product

                                var searchContext = new ProductSearchContext()
                                {
                                    StoreId = _services.StoreContext.CurrentStore.Id,
                                    ParentGroupedProductId = product.Id,
                                    PageSize = int.MaxValue,
                                    VisibleIndividuallyOnly = false
                                };

                                var associatedProducts = _productService.SearchProducts(searchContext);

                                if (associatedProducts.Count <= 0)
                                {
                                    priceModel.OldPrice = null;
                                    priceModel.Price = null;
                                    priceModel.DisableBuyButton = true;
                                    priceModel.DisableWishListButton = true;
                                    priceModel.AvailableForPreOrder = false;
                                }
                                else
                                {
                                    priceModel.DisableBuyButton = true;
                                    priceModel.DisableWishListButton = true;
                                    priceModel.AvailableForPreOrder = false;

                                    if (_services.Permissions.Authorize(StandardPermissionProvider.DisplayPrices))
                                    {
                                        decimal? minPossiblePrice = _priceCalculationService.GetLowestPrice(product, associatedProducts, out minPriceProduct);

                                        if (minPriceProduct != null && !minPriceProduct.CustomerEntersPrice)
                                        {
                                            if (minPriceProduct.CallForPrice)
                                            {
                                                priceModel.OldPrice = null;
                                                priceModel.Price = T("Products.CallForPrice");
                                            }
                                            else if (minPossiblePrice.HasValue)
                                            {
                                                //calculate prices
                                                decimal taxRate = decimal.Zero;
                                                decimal oldPriceBase = _taxService.GetProductPrice(minPriceProduct, minPriceProduct.OldPrice, out taxRate);
                                                decimal finalPriceBase = _taxService.GetProductPrice(minPriceProduct, minPossiblePrice.Value, out taxRate);
                                                decimal finalPrice = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, _services.WorkContext.WorkingCurrency);

                                                priceModel.OldPrice = null;
                                                priceModel.Price = String.Format(T("Products.PriceRangeFrom"), _priceFormatter.FormatPrice(finalPrice));
                                                priceModel.HasDiscount = finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero;
                                            }
                                            else
                                            {
                                                //Actually it's not possible (we presume that minimalPrice always has a value)
                                                //We never should get here
                                                Debug.WriteLine(string.Format("Cannot calculate minPrice for product #{0}", product.Id));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //hide prices
                                        priceModel.OldPrice = null;
                                        priceModel.Price = null;
                                    }
                                }

                                #endregion
                            }
                            break;
                        case ProductType.SimpleProduct:
                        default:
                            {
                                #region Simple product

                                //add to cart button
                                priceModel.DisableBuyButton = product.DisableBuyButton ||
                                    !_services.Permissions.Authorize(StandardPermissionProvider.EnableShoppingCart) ||
                                    !_services.Permissions.Authorize(StandardPermissionProvider.DisplayPrices);

                                //add to wishlist button
                                priceModel.DisableWishListButton = product.DisableWishlistButton ||
                                    !_services.Permissions.Authorize(StandardPermissionProvider.EnableWishlist) ||
                                    !_services.Permissions.Authorize(StandardPermissionProvider.DisplayPrices);

                                //pre-order
                                priceModel.AvailableForPreOrder = product.AvailableForPreOrder;

                                //prices
                                if (_services.Permissions.Authorize(StandardPermissionProvider.DisplayPrices))
                                {
                                    if (!product.CustomerEntersPrice)
                                    {
                                        if (product.CallForPrice)
                                        {
                                            //call for price
                                            priceModel.OldPrice = null;
                                            priceModel.Price = T("Products.CallForPrice");
                                        }
                                        else
                                        {
                                            //calculate prices
                                            bool isBundlePerItemPricing = (product.ProductType == ProductType.BundledProduct && product.BundlePerItemPricing);

                                            bool displayFromMessage = false;
                                            decimal minPossiblePrice = _priceCalculationService.GetLowestPrice(product, out displayFromMessage);

                                            decimal taxRate = decimal.Zero;
                                            decimal oldPriceBase = _taxService.GetProductPrice(product, product.OldPrice, out taxRate);
                                            decimal finalPriceBase = _taxService.GetProductPrice(product, minPossiblePrice, out taxRate);

                                            decimal oldPrice = _currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase, _services.WorkContext.WorkingCurrency);
                                            decimal finalPrice = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, _services.WorkContext.WorkingCurrency);

                                            priceModel.HasDiscount = (finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero);

                                            // check tier prices
                                            if (product.HasTierPrices && !isBundlePerItemPricing && !displayFromMessage)
                                            {
                                                var tierPrices = new List<TierPrice>();

                                                tierPrices.AddRange(product.TierPrices
                                                    .OrderBy(tp => tp.Quantity)
                                                    .FilterByStore(_services.StoreContext.CurrentStore.Id)
                                                    .FilterForCustomer(_services.WorkContext.CurrentCustomer)
                                                    .ToList()
                                                    .RemoveDuplicatedQuantities());

                                                // When there is just one tier (with  qty 1), there are no actual savings in the list.
                                                displayFromMessage = (tierPrices.Count > 0 && !(tierPrices.Count == 1 && tierPrices[0].Quantity <= 1));
                                            }

                                            if (displayFromMessage)
                                            {
                                                priceModel.OldPrice = null;
                                                priceModel.Price = String.Format(T("Products.PriceRangeFrom"), _priceFormatter.FormatPrice(finalPrice));
                                            }
                                            else
                                            {
                                                if (priceModel.HasDiscount)
                                                {
                                                    priceModel.OldPrice = _priceFormatter.FormatPrice(oldPrice);
                                                    priceModel.Price = _priceFormatter.FormatPrice(finalPrice);
                                                }
                                                else
                                                {
                                                    priceModel.OldPrice = null;
                                                    priceModel.Price = _priceFormatter.FormatPrice(finalPrice);
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //hide prices
                                    priceModel.OldPrice = null;
                                    priceModel.Price = null;
                                }

                                #endregion
                            }
                            break;
                    }

                    model.ProductPrice = priceModel;
                    model.ProductPrice.CallForPrice = product.CallForPrice;

                    #endregion
                }

                // picture
                if (preparePictureModel)
                {
                    #region Prepare product picture

                    //If a size has been set in the view, we use it in priority
                    int pictureSize = productThumbPictureSize.HasValue ? productThumbPictureSize.Value : _mediaSettings.ProductThumbPictureSize;

                    //prepare picture model
                    var defaultProductPictureCacheKey = string.Format(ModelCacheEventConsumer.PRODUCT_DEFAULTPICTURE_MODEL_KEY, product.Id, pictureSize, true,
                        _services.WorkContext.WorkingLanguage.Id, _services.WebHelper.IsCurrentConnectionSecured(), _services.StoreContext.CurrentStore.Id);

                    model.DefaultPictureModel = _services.Cache.Get(defaultProductPictureCacheKey, () =>
                    {
                        var picture = product.GetDefaultProductPicture(_pictureService);
                        var pictureModel = new PictureModel
                        {
                            ImageUrl = _pictureService.GetPictureUrl(picture, pictureSize),
                            FullSizeImageUrl = _pictureService.GetPictureUrl(picture),
                            Title = string.Format(T("Media.Product.ImageLinkTitleFormat"), model.Name),
                            AlternateText = string.Format(T("Media.Product.ImageAlternateTextFormat"), model.Name)
                        };
                        return pictureModel;
                    });

                    #endregion
                }

                // specs
                if (prepareSpecificationAttributes)
                {
                    model.SpecificationAttributeModels = PrepareProductSpecificationModel(product);
                }

                // available colors
                if (prepareColorAttributes && _catalogSettings.ShowColorSquaresInLists)
                {
                    #region Prepare color attributes

                    // get the FIRST color type attribute
                    var colorAttr = _productAttributeService.GetProductVariantAttributesByProductId(minPriceProduct.Id)
                        .FirstOrDefault(x => x.AttributeControlType == AttributeControlType.ColorSquares);

                    if (colorAttr != null)
                    {
                        var colorValues =
                            from a in colorAttr.ProductVariantAttributeValues.Take(50)
                            where (a.ColorSquaresRgb.HasValue() && !a.ColorSquaresRgb.IsCaseInsensitiveEqual("transparent"))
                            select new ProductOverviewModel.ColorAttributeModel()
                            {
                                Color = a.ColorSquaresRgb,
                                Alias = a.Alias,
                                FriendlyName = a.GetLocalized(l => l.Name)
                            };

                        if (colorValues.Any())
                        {
                            model.ColorAttributes.AddRange(colorValues.Distinct());
                        }
                    }

                    #endregion
                }

                var currentCustomer = _services.WorkContext.CurrentCustomer;
                var taxDisplayType = _services.WorkContext.GetTaxDisplayTypeFor(currentCustomer, _services.StoreContext.CurrentStore.Id);
                string taxInfo = T(taxDisplayType == TaxDisplayType.IncludingTax ? "Tax.InclVAT" : "Tax.ExclVAT");
                string shippingInfoLink = _urlHelper.RouteUrl("Topic", new { SystemName = "shippinginfo" });

                model.ProductMinPriceId = minPriceProduct.Id;
                model.Manufacturers = PrepareManufacturersOverviewModel(_manufacturerService.GetProductManufacturersByProductId(product.Id));
                model.ShowSku = _catalogSettings.ShowProductSku;
                model.ShowWeight = _catalogSettings.ShowWeight;
                model.ShowDimensions = _catalogSettings.ShowDimensions;
                model.Sku = minPriceProduct.Sku;
                model.Dimensions = T("Products.DimensionsValue").Text.FormatCurrent(
                    minPriceProduct.Width.ToString("F2"),
                    minPriceProduct.Height.ToString("F2"),
                    minPriceProduct.Length.ToString("F2")
                );
                model.DimensionMeasureUnit = _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId).Name;
                model.ThumbDimension = _mediaSettings.ProductThumbPictureSize;
                model.ShowLegalInfo = _taxSettings.ShowLegalHintsInProductList;
                model.LegalInfo = T("Tax.LegalInfoFooter").Text.FormatWith(taxInfo, shippingInfoLink);
                model.RatingSum = product.ApprovedRatingSum;
                model.TotalReviews = product.ApprovedTotalReviews;
                model.ShowReviews = _catalogSettings.ShowProductReviewsInProductLists;
                model.ShowDeliveryTimes = _catalogSettings.ShowDeliveryTimesInProductLists;

                var deliveryTime = _deliveryTimeService.GetDeliveryTime(minPriceProduct);
                if (deliveryTime != null)
                {
                    model.DeliveryTimeName = deliveryTime.GetLocalized(x => x.Name);
                    model.DeliveryTimeHexValue = deliveryTime.ColorHexValue;
                }

                model.IsShipEnabled = minPriceProduct.IsShipEnabled;
                model.DisplayDeliveryTimeAccordingToStock = minPriceProduct.DisplayDeliveryTimeAccordingToStock(_catalogSettings);
                model.StockAvailablity = minPriceProduct.FormatStockMessage(_localizationService);

                model.DisplayBasePrice = _catalogSettings.ShowBasePriceInProductLists;
                model.BasePriceInfo = minPriceProduct.GetBasePriceInfo(_localizationService, _priceFormatter);
                model.CompareEnabled = _catalogSettings.CompareProductsEnabled;
                model.HideBuyButtonInLists = _catalogSettings.HideBuyButtonInLists;

                var addShippingPrice = _currencyService.ConvertCurrency(minPriceProduct.AdditionalShippingCharge,
                    _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId), _services.WorkContext.WorkingCurrency);

                if (addShippingPrice > 0)
                {
                    model.TransportSurcharge = T("Common.AdditionalShippingSurcharge").Text.FormatWith(_priceFormatter.FormatPrice(addShippingPrice, true, false));
                }

                if (minPriceProduct.Weight > 0)
                {
                    model.Weight = "{0} {1}".FormatCurrent(minPriceProduct.Weight.ToString("F2"), _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).Name);
                }

                // IsNew
                if (_catalogSettings.LabelAsNewForMaxDays.HasValue)
                {
                    model.IsNew = (DateTime.UtcNow - product.CreatedOnUtc).Days <= _catalogSettings.LabelAsNewForMaxDays.Value;
                }

                models.Add(model);
            }
            return models;
        }
        public virtual void InheritStoresIntoChildren(int categoryId,
                                                      bool touchProductsWithMultipleCategories = false,
                                                      bool touchExistingAcls = false,
                                                      bool categoriesOnly    = false)
        {
            var category      = GetCategoryById(categoryId);
            var subcategories = GetAllCategoriesByParentCategoryId(categoryId, true);
            var context       = new ProductSearchContext {
                PageSize = int.MaxValue, ShowHidden = true
            };

            context.CategoryIds.AddRange(subcategories.Select(x => x.Id));
            context.CategoryIds.Add(categoryId);
            var products = _productService.SearchProducts(context);

            var allStores             = _storeService.GetAllStores();
            var categoryStoreMappings = _storeMappingService.GetStoresIdsWithAccess(category);

            using (var scope = new DbContextScope(ctx: _storeMappingRepository.Context, autoDetectChanges: false, proxyCreation: false, validateOnSave: false))
            {
                _storeMappingRepository.AutoCommitEnabled = false;

                foreach (var subcategory in subcategories)
                {
                    if (subcategory.LimitedToStores != category.LimitedToStores)
                    {
                        subcategory.LimitedToStores = category.LimitedToStores;
                        _categoryRepository.Update(subcategory);
                    }

                    var existingStoreMappingsRecords = _storeMappingService.GetStoreMappings(subcategory).ToDictionary(x => x.StoreId);

                    foreach (var store in allStores)
                    {
                        if (categoryStoreMappings.Contains(store.Id))
                        {
                            if (!existingStoreMappingsRecords.ContainsKey(store.Id))
                            {
                                _storeMappingRepository.Insert(new StoreMapping {
                                    StoreId = store.Id, EntityId = subcategory.Id, EntityName = "Category"
                                });
                            }
                        }
                        else
                        {
                            StoreMapping storeMappingToDelete;
                            if (existingStoreMappingsRecords.TryGetValue(store.Id, out storeMappingToDelete))
                            {
                                _storeMappingRepository.Delete(storeMappingToDelete);
                            }
                        }
                    }
                }

                _storeMappingRepository.Context.SaveChanges();

                foreach (var product in products)
                {
                    if (product.LimitedToStores != category.LimitedToStores)
                    {
                        product.LimitedToStores = category.LimitedToStores;
                        _productRepository.Update(product);
                    }

                    var existingStoreMappingsRecords = _storeMappingService.GetStoreMappings(product).ToDictionary(x => x.StoreId);

                    foreach (var store in allStores)
                    {
                        if (categoryStoreMappings.Contains(store.Id))
                        {
                            if (!existingStoreMappingsRecords.ContainsKey(store.Id))
                            {
                                _storeMappingRepository.Insert(new StoreMapping {
                                    StoreId = store.Id, EntityId = product.Id, EntityName = "Product"
                                });
                            }
                        }
                        else
                        {
                            StoreMapping storeMappingToDelete;
                            if (existingStoreMappingsRecords.TryGetValue(store.Id, out storeMappingToDelete))
                            {
                                _storeMappingRepository.Delete(storeMappingToDelete);
                            }
                        }
                    }
                }

                _storeMappingRepository.Context.SaveChanges();
            }
        }
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
        /// <returns>Product entity</returns>
        public virtual Product CopyProduct(Product product, string newName, bool isPublished, bool copyImages, bool copyAssociatedProducts = true)
        {
            if (product == null)
                throw new ArgumentNullException("product");

            if (String.IsNullOrEmpty(newName))
                throw new ArgumentException("Product name is required");

            Product productCopy = null;
            var utcNow = DateTime.UtcNow;

            // product download & sample download
            int downloadId = 0;
            int? sampleDownloadId = null;

            if (product.IsDownload)
            {
                var download = _downloadService.GetDownloadById(product.DownloadId);
                if (download != null)
                {
                    var downloadCopy = new Download
                    {
                        DownloadGuid = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl = download.DownloadUrl,
                        DownloadBinary = download.DownloadBinary,
                        ContentType = download.ContentType,
                        Filename = download.Filename,
                        Extension = download.Extension,
                        IsNew = download.IsNew,
                    };

                    _downloadService.InsertDownload(downloadCopy);
                    downloadId = downloadCopy.Id;
                }

                if (product.HasSampleDownload)
                {
                    var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault());
                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download
                        {
                            DownloadGuid = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl = sampleDownload.DownloadUrl,
                            DownloadBinary = sampleDownload.DownloadBinary,
                            ContentType = sampleDownload.ContentType,
                            Filename = sampleDownload.Filename,
                            Extension = sampleDownload.Extension,
                            IsNew = sampleDownload.IsNew
                        };

                        _downloadService.InsertDownload(sampleDownloadCopy);
                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            // product
            productCopy = new Product
            {
                ProductTypeId = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually = product.VisibleIndividually,
                Name = newName,
                ShortDescription = product.ShortDescription,
                FullDescription = product.FullDescription,
                ProductTemplateId = product.ProductTemplateId,
                AdminComment = product.AdminComment,
                ShowOnHomePage = product.ShowOnHomePage,
                HomePageDisplayOrder = product.HomePageDisplayOrder,
                MetaKeywords = product.MetaKeywords,
                MetaDescription = product.MetaDescription,
                MetaTitle = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores = product.LimitedToStores,
                Sku = product.Sku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin = product.Gtin,
                IsGiftCard = product.IsGiftCard,
                GiftCardType = product.GiftCardType,
                RequireOtherProducts = product.RequireOtherProducts,
                RequiredProductIds = product.RequiredProductIds,
                AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
                IsDownload = product.IsDownload,
                DownloadId = downloadId,
                UnlimitedDownloads = product.UnlimitedDownloads,
                MaxNumberOfDownloads = product.MaxNumberOfDownloads,
                DownloadExpirationDays = product.DownloadExpirationDays,
                DownloadActivationType = product.DownloadActivationType,
                HasSampleDownload = product.HasSampleDownload,
                SampleDownloadId = sampleDownloadId,
                HasUserAgreement = product.HasUserAgreement,
                UserAgreementText = product.UserAgreementText,
                IsRecurring = product.IsRecurring,
                RecurringCycleLength = product.RecurringCycleLength,
                RecurringCyclePeriod = product.RecurringCyclePeriod,
                RecurringTotalCycles = product.RecurringTotalCycles,
                IsShipEnabled = product.IsShipEnabled,
                IsFreeShipping = product.IsFreeShipping,
                AdditionalShippingCharge = product.AdditionalShippingCharge,
                IsEsd = product.IsEsd,
                IsTaxExempt = product.IsTaxExempt,
                TaxCategoryId = product.TaxCategoryId,
                ManageInventoryMethod = product.ManageInventoryMethod,
                StockQuantity = product.StockQuantity,
                DisplayStockAvailability = product.DisplayStockAvailability,
                DisplayStockQuantity = product.DisplayStockQuantity,
                MinStockQuantity = product.MinStockQuantity,
                LowStockActivityId = product.LowStockActivityId,
                NotifyAdminForQuantityBelow = product.NotifyAdminForQuantityBelow,
                BackorderMode = product.BackorderMode,
                AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions,
                OrderMinimumQuantity = product.OrderMinimumQuantity,
                OrderMaximumQuantity = product.OrderMaximumQuantity,
                AllowedQuantities = product.AllowedQuantities,
                DisableBuyButton = product.DisableBuyButton,
                DisableWishlistButton = product.DisableWishlistButton,
                AvailableForPreOrder = product.AvailableForPreOrder,
                CallForPrice = product.CallForPrice,
                Price = product.Price,
                OldPrice = product.OldPrice,
                ProductCost = product.ProductCost,
                SpecialPrice = product.SpecialPrice,
                SpecialPriceStartDateTimeUtc = product.SpecialPriceStartDateTimeUtc,
                SpecialPriceEndDateTimeUtc = product.SpecialPriceEndDateTimeUtc,
                CustomerEntersPrice = product.CustomerEntersPrice,
                MinimumCustomerEnteredPrice = product.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice = product.MaximumCustomerEnteredPrice,
                LowestAttributeCombinationPrice = product.LowestAttributeCombinationPrice,
                Weight = product.Weight,
                Length = product.Length,
                Width = product.Width,
                Height = product.Height,
                AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc = product.AvailableEndDateTimeUtc,
                DisplayOrder = product.DisplayOrder,
                Published = isPublished,
                Deleted = product.Deleted,
                CreatedOnUtc = utcNow,
                UpdatedOnUtc = utcNow,
                DeliveryTimeId = product.DeliveryTimeId,
                QuantityUnitId = product.QuantityUnitId,
                BasePriceEnabled = product.BasePriceEnabled,
                BasePriceMeasureUnit = product.BasePriceMeasureUnit,
                BasePriceAmount = product.BasePriceAmount,
                BasePriceBaseAmount = product.BasePriceBaseAmount,
                BundleTitleText = product.BundleTitleText,
                BundlePerItemShipping = product.BundlePerItemShipping,
                BundlePerItemPricing = product.BundlePerItemPricing,
                BundlePerItemShoppingCart = product.BundlePerItemShoppingCart
            };

            _productService.InsertProduct(productCopy);

            //search engine name
            _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

            var languages = _languageService.GetAllLanguages(true);

            //localization
            foreach (var lang in languages)
            {
                var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                if (!String.IsNullOrEmpty(name))
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);

                var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(shortDescription))
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);

                var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(fullDescription))
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);

                var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaKeywords))
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);

                var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaDescription))
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);

                var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaTitle))
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);

                var bundleTitleText = product.GetLocalized(x => x.BundleTitleText, lang.Id, false, false);
                if (!String.IsNullOrEmpty(bundleTitleText))
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.BundleTitleText, bundleTitleText, lang.Id);

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);

            }

            // product pictures
            if (copyImages)
            {
                foreach (var productPicture in product.ProductPictures)
                {
                    var picture = productPicture.Picture;
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(newName),
                        true,
                        false,
                        false);

                    _productService.InsertProductPicture(new ProductPicture
                    {
                        ProductId = productCopy.Id,
                        PictureId = pictureCopy.Id,
                        DisplayOrder = productPicture.DisplayOrder
                    });
                }
            }

            // product <-> categories mappings
            foreach (var productCategory in product.ProductCategories)
            {
                var productCategoryCopy = new ProductCategory
                {
                    ProductId = productCopy.Id,
                    CategoryId = productCategory.CategoryId,
                    IsFeaturedProduct = productCategory.IsFeaturedProduct,
                    DisplayOrder = productCategory.DisplayOrder
                };

                _categoryService.InsertProductCategory(productCategoryCopy);
            }

            // product <-> manufacturers mappings
            foreach (var productManufacturers in product.ProductManufacturers)
            {
                var productManufacturerCopy = new ProductManufacturer
                {
                    ProductId = productCopy.Id,
                    ManufacturerId = productManufacturers.ManufacturerId,
                    IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
                    DisplayOrder = productManufacturers.DisplayOrder
                };

                _manufacturerService.InsertProductManufacturer(productManufacturerCopy);
            }

            // product <-> releated products mappings
            foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true))
            {
                _productService.InsertRelatedProduct(new RelatedProduct
                {
                    ProductId1 = productCopy.Id,
                    ProductId2 = relatedProduct.ProductId2,
                    DisplayOrder = relatedProduct.DisplayOrder
                });
            }

            // product <-> cross sells mappings
            foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
            {
                _productService.InsertCrossSellProduct(new CrossSellProduct
                {
                    ProductId1 = productCopy.Id,
                    ProductId2 = csProduct.ProductId2,
                });
            }

            // product specifications
            foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
            {
                var psaCopy = new ProductSpecificationAttribute
                {
                    ProductId = productCopy.Id,
                    SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                    AllowFiltering = productSpecificationAttribute.AllowFiltering,
                    ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                    DisplayOrder = productSpecificationAttribute.DisplayOrder
                };

                _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
            }

            //store mapping
            var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);
            foreach (var id in selectedStoreIds)
            {
                _storeMappingService.InsertStoreMapping(productCopy, id);
            }

            // product <-> attributes mappings
            var associatedAttributes = new Dictionary<int, int>();
            var associatedAttributeValues = new Dictionary<int, int>();

            foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductId(product.Id))
            {
                var productVariantAttributeCopy = new ProductVariantAttribute
                {
                    ProductId = productCopy.Id,
                    ProductAttributeId = productVariantAttribute.ProductAttributeId,
                    TextPrompt = productVariantAttribute.TextPrompt,
                    IsRequired = productVariantAttribute.IsRequired,
                    AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId,
                    DisplayOrder = productVariantAttribute.DisplayOrder
                };

                _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id);

                // product variant attribute values
                var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id);

                foreach (var productVariantAttributeValue in productVariantAttributeValues)
                {
                    var pvavCopy = new ProductVariantAttributeValue
                    {
                        ProductVariantAttributeId = productVariantAttributeCopy.Id,
                        Name = productVariantAttributeValue.Name,
                        ColorSquaresRgb = productVariantAttributeValue.ColorSquaresRgb,
                        PriceAdjustment = productVariantAttributeValue.PriceAdjustment,
                        WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                        IsPreSelected = productVariantAttributeValue.IsPreSelected,
                        DisplayOrder = productVariantAttributeValue.DisplayOrder,
                        ValueTypeId = productVariantAttributeValue.ValueTypeId,
                        LinkedProductId = productVariantAttributeValue.LinkedProductId,
                        Quantity = productVariantAttributeValue.Quantity,
                    };

                    _productAttributeService.InsertProductVariantAttributeValue(pvavCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productVariantAttributeValue.Id, pvavCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productVariantAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                            _localizedEntityService.SaveLocalizedValue(pvavCopy, x => x.Name, name, lang.Id);
                    }
                }
            }

            // attribute combinations
            using (var scope = new DbContextScope(lazyLoading: false, forceNoTracking: false))
            {
                scope.LoadCollection(product, (Product p) => p.ProductVariantAttributeCombinations);
            }

            foreach (var combination in product.ProductVariantAttributeCombinations)
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml = "";
                var parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml);
                foreach (var oldPva in parsedProductVariantAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldPva.Id))
                    {
                        int newPvaId = associatedAttributes[oldPva.Id];
                        var newPva = _productAttributeService.GetProductVariantAttributeById(newPvaId);
                        if (newPva != null)
                        {
                            var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id);
                            foreach (var oldPvaValueStr in oldPvaValuesStr)
                            {
                                if (newPva.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldPvaValue = int.Parse(oldPvaValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldPvaValue))
                                    {
                                        int newPvavId = associatedAttributeValues[oldPvaValue];
                                        var newPvav = _productAttributeService.GetProductVariantAttributeValueById(newPvavId);
                                        if (newPvav != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, newPvav.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, oldPvaValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductVariantAttributeCombination
                {
                    ProductId = productCopy.Id,
                    AttributesXml = newAttributesXml,
                    StockQuantity = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,

                    // SmartStore extension
                    Sku = combination.Sku,
                    Gtin = combination.Gtin,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Price = combination.Price,
                    AssignedPictureIds = copyImages ? combination.AssignedPictureIds : null,
                    Length = combination.Length,
                    Width = combination.Width,
                    Height = combination.Height,
                    BasePriceAmount = combination.BasePriceAmount,
                    BasePriceBaseAmount = combination.BasePriceBaseAmount,
                    DeliveryTimeId = combination.DeliveryTimeId,
                    QuantityUnitId = combination.QuantityUnitId,
                    IsActive = combination.IsActive
                    //IsDefaultCombination = combination.IsDefaultCombination
                };
                _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy);
            }

            // tier prices
            foreach (var tierPrice in product.TierPrices)
            {
                _productService.InsertTierPrice(new TierPrice
                {
                    ProductId = productCopy.Id,
                    StoreId = tierPrice.StoreId,
                    CustomerRoleId = tierPrice.CustomerRoleId,
                    Quantity = tierPrice.Quantity,
                    Price = tierPrice.Price
                });
            }

            // product <-> discounts mapping
            foreach (var discount in product.AppliedDiscounts)
            {
                productCopy.AppliedDiscounts.Add(discount);
                _productService.UpdateProduct(productCopy);
            }

            // update "HasTierPrices" and "HasDiscountsApplied" properties
            _productService.UpdateHasTierPricesProperty(productCopy);
            _productService.UpdateLowestAttributeCombinationPriceProperty(productCopy);
            _productService.UpdateHasDiscountsApplied(productCopy);

            // associated products
            if (copyAssociatedProducts && product.ProductType != ProductType.BundledProduct)
            {
                var searchContext = new ProductSearchContext
                {
                    OrderBy = ProductSortingEnum.Position,
                    ParentGroupedProductId = product.Id,
                    PageSize = int.MaxValue,
                    ShowHidden = true
                };

                string copyOf = _localizationService.GetResource("Admin.Common.CopyOf");
                var associatedProducts = _productService.SearchProducts(searchContext);

                foreach (var associatedProduct in associatedProducts)
                {
                    var associatedProductCopy = CopyProduct(associatedProduct, string.Format("{0} {1}", copyOf, associatedProduct.Name), isPublished, copyImages, false);
                    associatedProductCopy.ParentGroupedProductId = productCopy.Id;

                    _productService.UpdateProduct(productCopy);
                }
            }

            // bundled products
            var bundledItems = _productService.GetBundleItems(product.Id, true);

            foreach (var bundleItem in bundledItems)
            {
                var newBundleItem = bundleItem.Item.Clone();
                newBundleItem.BundleProductId = productCopy.Id;
                newBundleItem.CreatedOnUtc = utcNow;
                newBundleItem.UpdatedOnUtc = utcNow;

                _productService.InsertBundleItem(newBundleItem);

                foreach (var itemFilter in bundleItem.Item.AttributeFilters)
                {
                    var newItemFilter = itemFilter.Clone();
                    newItemFilter.BundleItemId = newBundleItem.Id;

                    _productAttributeService.InsertProductBundleItemAttributeFilter(newItemFilter);
                }
            }

            return productCopy;
        }
Example #20
0
        public ActionResult Search(SearchModel model, SearchPagingFilteringModel command)
        {
            if (model == null)
                model = new SearchModel();

            // 'Continue shopping' URL
            _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentCustomer,
                SystemCustomerAttributeNames.LastContinueShoppingPage,
                _services.WebHelper.GetThisPageUrl(false),
                _services.StoreContext.CurrentStore.Id);

            if (command.PageSize <= 0)
                command.PageSize = _catalogSettings.SearchPageProductsPerPage;
            if (command.PageNumber <= 0)
                command.PageNumber = 1;

            if (command.OrderBy == (int)ProductSortingEnum.Initial)
            {
                command.OrderBy = (int)_catalogSettings.DefaultSortOrder;
            }

            _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
            {
                AllowCustomersToSelectPageSize = _catalogSettings.ProductSearchAllowCustomersToSelectPageSize,
                PageSize = _catalogSettings.SearchPageProductsPerPage,
                PageSizeOptions = _catalogSettings.ProductSearchPageSizeOptions
            });

            if (model.Q == null)
                model.Q = "";
            model.Q = model.Q.Trim();

            // Build AvailableCategories
            // first empty entry
            model.AvailableCategories.Add(new SelectListItem
            {
                Value = "0",
                Text = T("Common.All")
            });

            var navModel = _helper.PrepareCategoryNavigationModel(0, 0);

            navModel.Root.TraverseTree((node) =>
            {
                if (node.IsRoot)
                    return;

                int id = node.Value.EntityId;
                var breadcrumb = node.GetBreadcrumb().Select(x => x.Text).ToArray();

                model.AvailableCategories.Add(new SelectListItem
                {
                    Value = id.ToString(),
                    Text = String.Join(" > ", breadcrumb),
                    Selected = model.Cid == id
                });
            });

            var manufacturers = _manufacturerService.GetAllManufacturers();
            if (manufacturers.Count > 0)
            {
                model.AvailableManufacturers.Add(new SelectListItem
                {
                    Value = "0",
                    Text = T("Common.All")
                });
                foreach (var m in manufacturers)
                    model.AvailableManufacturers.Add(new SelectListItem
                    {
                        Value = m.Id.ToString(),
                        Text = m.GetLocalized(x => x.Name),
                        Selected = model.Mid == m.Id
                    });
            }

            IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
            // only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
            if (Request.Params["Q"] != null)
            {
                if (model.Q.Length < _catalogSettings.ProductSearchTermMinimumLength)
                {
                    model.Warning = string.Format(T("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
                }
                else
                {
                    var categoryIds = new List<int>();
                    int manufacturerId = 0;
                    decimal? minPriceConverted = null;
                    decimal? maxPriceConverted = null;
                    bool searchInDescriptions = false;
                    if (model.As)
                    {
                        // advanced search
                        var categoryId = model.Cid;
                        if (categoryId > 0)
                        {
                            categoryIds.Add(categoryId);
                            if (model.Isc)
                            {
                                // include subcategories
                                categoryIds.AddRange(_helper.GetChildCategoryIds(categoryId));
                            }
                        }

                        manufacturerId = model.Mid;

                        // min price
                        if (!string.IsNullOrEmpty(model.Pf))
                        {
                            decimal minPrice = decimal.Zero;
                            if (decimal.TryParse(model.Pf, out minPrice))
                                minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _services.WorkContext.WorkingCurrency);
                        }
                        // max price
                        if (!string.IsNullOrEmpty(model.Pt))
                        {
                            decimal maxPrice = decimal.Zero;
                            if (decimal.TryParse(model.Pt, out maxPrice))
                                maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _services.WorkContext.WorkingCurrency);
                        }

                        searchInDescriptions = model.Sid;
                    }

                    //var searchInProductTags = false;
                    var searchInProductTags = searchInDescriptions;

                    //products

                    var ctx = new ProductSearchContext();
                    ctx.CategoryIds = categoryIds;
                    ctx.ManufacturerId = manufacturerId;
                    ctx.PriceMin = minPriceConverted;
                    ctx.PriceMax = maxPriceConverted;
                    ctx.Keywords = model.Q;
                    ctx.SearchDescriptions = searchInDescriptions;
                    ctx.SearchSku = !_catalogSettings.SuppressSkuSearch;
                    ctx.SearchProductTags = searchInProductTags;
                    ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
                    ctx.OrderBy = (ProductSortingEnum)command.OrderBy; // ProductSortingEnum.Position;
                    ctx.PageIndex = command.PageNumber - 1;
                    ctx.PageSize = command.PageSize;
                    ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                    ctx.VisibleIndividuallyOnly = true;

                    products = _productService.SearchProducts(ctx);

                    model.Products = _helper.PrepareProductOverviewModels(
                        products,
                        prepareColorAttributes: true,
                        prepareManufacturers: command.ViewMode.IsCaseInsensitiveEqual("list")).ToList();

                    model.NoResults = !model.Products.Any();
                }
            }

            model.PagingFilteringContext.LoadPagedList(products);
            return View(model);
        }
        public ProductDetailsModel PrepareProductDetailsPageModel(
			Product product, 
			bool isAssociatedProduct = false,
			ProductBundleItemData productBundleItem = null, 
			IList<ProductBundleItemData> productBundleItems = null, 
			NameValueCollection selectedAttributes = null,
			NameValueCollection queryData = null)
        {
            if (product == null)
                throw new ArgumentNullException("product");

            var model = new ProductDetailsModel
            {
                Id = product.Id,
                Name = product.GetLocalized(x => x.Name),
                ShortDescription = product.GetLocalized(x => x.ShortDescription),
                FullDescription = product.GetLocalized(x => x.FullDescription),
                MetaKeywords = product.GetLocalized(x => x.MetaKeywords),
                MetaDescription = product.GetLocalized(x => x.MetaDescription),
                MetaTitle = product.GetLocalized(x => x.MetaTitle),
                SeName = product.GetSeName(),
                ProductType = product.ProductType,
                VisibleIndividually = product.VisibleIndividually,
                //Manufacturers = _manufacturerService.GetProductManufacturersByProductId(product.Id),
                Manufacturers = PrepareManufacturersOverviewModel(_manufacturerService.GetProductManufacturersByProductId(product.Id), null, true),
                ReviewCount = product.ApprovedTotalReviews,
                DisplayAdminLink = _services.Permissions.Authorize(StandardPermissionProvider.AccessAdminPanel),
                //EnableHtmlTextCollapser = Convert.ToBoolean(_settingService.GetSettingByKey<string>("CatalogSettings.EnableHtmlTextCollapser")),
                //HtmlTextCollapsedHeight = Convert.ToString(_settingService.GetSettingByKey<string>("CatalogSettings.HtmlTextCollapsedHeight")),
                ShowSku = _catalogSettings.ShowProductSku,
                Sku = product.Sku,
                ShowManufacturerPartNumber = _catalogSettings.ShowManufacturerPartNumber,
                DisplayProductReviews = _catalogSettings.ShowProductReviewsInProductDetail,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                ShowGtin = _catalogSettings.ShowGtin,
                Gtin = product.Gtin,
                StockAvailability = product.FormatStockMessage(_localizationService),
                HasSampleDownload = product.IsDownload && product.HasSampleDownload,
                IsCurrentCustomerRegistered = _services.WorkContext.CurrentCustomer.IsRegistered()
            };

            // get gift card values from query string
            if (queryData != null && queryData.Count > 0)
            {
                var giftCardItems = queryData.AllKeys
                    .Where(x => x.EmptyNull().StartsWith("giftcard_"))
                    .SelectMany(queryData.GetValues, (k, v) => new { key = k, value = v.TrimSafe() });

                foreach (var item in giftCardItems)
                {
                    var key = item.key.EmptyNull().ToLower();

                    if (key.EndsWith("recipientname"))
                        model.GiftCard.RecipientName = item.value;
                    else if (key.EndsWith("recipientemail"))
                        model.GiftCard.RecipientEmail = item.value;
                    else if (key.EndsWith("sendername"))
                        model.GiftCard.SenderName = item.value;
                    else if (key.EndsWith("senderemail"))
                        model.GiftCard.SenderEmail = item.value;
                    else if (key.EndsWith("message"))
                        model.GiftCard.Message = item.value;
                }
            }

            // Back in stock subscriptions
            if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
                 product.BackorderMode == BackorderMode.NoBackorders &&
                 product.AllowBackInStockSubscriptions &&
                 product.StockQuantity <= 0)
            {
                //out of stock
                model.DisplayBackInStockSubscription = true;
                model.BackInStockAlreadySubscribed = _backInStockSubscriptionService
                    .FindSubscription(_services.WorkContext.CurrentCustomer.Id, product.Id, _services.StoreContext.CurrentStore.Id) != null;
            }

            //template
            var templateCacheKey = string.Format(ModelCacheEventConsumer.PRODUCT_TEMPLATE_MODEL_KEY, product.ProductTemplateId);
            model.ProductTemplateViewPath = _services.Cache.Get(templateCacheKey, () =>
            {
                var template = _productTemplateService.GetProductTemplateById(product.ProductTemplateId);
                if (template == null)
                    template = _productTemplateService.GetAllProductTemplates().FirstOrDefault();
                return template.ViewPath;
            });

            IList<ProductBundleItemData> bundleItems = null;
            ProductVariantAttributeCombination combination = null;

            if (product.ProductType == ProductType.GroupedProduct && !isAssociatedProduct)	// associated products
            {
                var searchContext = new ProductSearchContext
                {
                    OrderBy = ProductSortingEnum.Position,
                    StoreId = _services.StoreContext.CurrentStore.Id,
                    ParentGroupedProductId = product.Id,
                    PageSize = int.MaxValue,
                    VisibleIndividuallyOnly = false
                };

                var associatedProducts = _productService.SearchProducts(searchContext);

                foreach (var associatedProduct in associatedProducts)
                    model.AssociatedProducts.Add(PrepareProductDetailsPageModel(associatedProduct, true));
            }
            else if (product.ProductType == ProductType.BundledProduct && productBundleItem == null)		// bundled items
            {
                bundleItems = _productService.GetBundleItems(product.Id);

                foreach (var itemData in bundleItems.Where(x => x.Item.Product.CanBeBundleItem()))
                {
                    var item = itemData.Item;
                    var bundleItemAttributes = new NameValueCollection();

                    if (selectedAttributes != null)
                    {
                        var keyPrefix = "product_attribute_{0}_{1}".FormatInvariant(item.ProductId, item.Id);

                        foreach (var key in selectedAttributes.AllKeys.Where(x => x.HasValue() && x.StartsWith(keyPrefix)))
                        {
                            bundleItemAttributes.Add(key, selectedAttributes[key]);
                        }
                    }

                    var bundledProductModel = PrepareProductDetailsPageModel(item.Product, false, itemData, null, bundleItemAttributes);

                    bundledProductModel.BundleItem.Id = item.Id;
                    bundledProductModel.BundleItem.Quantity = item.Quantity;
                    bundledProductModel.BundleItem.HideThumbnail = item.HideThumbnail;
                    bundledProductModel.BundleItem.Visible = item.Visible;
                    bundledProductModel.BundleItem.IsBundleItemPricing = item.BundleProduct.BundlePerItemPricing;

                    var bundleItemName = item.GetLocalized(x => x.Name);
                    if (bundleItemName.HasValue())
                        bundledProductModel.Name = bundleItemName;

                    var bundleItemShortDescription = item.GetLocalized(x => x.ShortDescription);
                    if (bundleItemShortDescription.HasValue())
                        bundledProductModel.ShortDescription = bundleItemShortDescription;

                    model.BundledItems.Add(bundledProductModel);
                }
            }

            model = PrepareProductDetailModel(model, product, isAssociatedProduct, productBundleItem, bundleItems, selectedAttributes);

            IList<int> combinationPictureIds = null;

            if (productBundleItem == null)
            {
                combinationPictureIds = _productAttributeService.GetAllProductVariantAttributeCombinationPictureIds(product.Id);
                if (combination == null && model.SelectedCombination != null)
                    combination = model.SelectedCombination;
            }

            // pictures
            var pictures = _pictureService.GetPicturesByProductId(product.Id);
            PrepareProductDetailsPictureModel(model.DetailsPictureModel, pictures, model.Name, combinationPictureIds, isAssociatedProduct, productBundleItem, combination);

            return model;
        }
Example #22
0
        public ActionResult Category(int categoryId, CatalogPagingFilteringModel command, string filter)
        {
            var category = _categoryService.GetCategoryById(categoryId);
            if (category == null || category.Deleted)
                return HttpNotFound();

            //Check whether the current user has a "Manage catalog" permission
            //It allows him to preview a category before publishing
            if (!category.Published && !_services.Permissions.Authorize(StandardPermissionProvider.ManageCatalog))
                return HttpNotFound();

            //ACL (access control list)
            if (!_aclService.Authorize(category))
                return HttpNotFound();

            //Store mapping
            if (!_storeMappingService.Authorize(category))
                return HttpNotFound();

            //'Continue shopping' URL
            _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentCustomer,
                SystemCustomerAttributeNames.LastContinueShoppingPage,
                _services.WebHelper.GetThisPageUrl(false),
                _services.StoreContext.CurrentStore.Id);

            if (command.PageNumber <= 0)
                command.PageNumber = 1;

            if (command.ViewMode.IsEmpty() && category.DefaultViewMode.HasValue())
            {
                command.ViewMode = category.DefaultViewMode;
            }

            if (command.OrderBy == (int)ProductSortingEnum.Initial)
            {
                command.OrderBy = (int)_catalogSettings.DefaultSortOrder;
            }

            var model = category.ToModel();

            _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
            {
                AllowCustomersToSelectPageSize = category.AllowCustomersToSelectPageSize,
                PageSize = category.PageSize,
                PageSizeOptions = category.PageSizeOptions
            });

            //price ranges
            model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(category.PriceRanges, _services.WebHelper, _priceFormatter);
            var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_services.WebHelper, category.PriceRanges);
            decimal? minPriceConverted = null;
            decimal? maxPriceConverted = null;

            if (selectedPriceRange != null)
            {
                if (selectedPriceRange.From.HasValue)
                    minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _services.WorkContext.WorkingCurrency);

                if (selectedPriceRange.To.HasValue)
                    maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _services.WorkContext.WorkingCurrency);
            }

            //category breadcrumb
            model.DisplayCategoryBreadcrumb = _catalogSettings.CategoryBreadcrumbEnabled;
            if (model.DisplayCategoryBreadcrumb)
            {
                model.CategoryBreadcrumb = _helper.GetCategoryBreadCrumb(category.Id, 0);
            }

            model.DisplayFilter = _catalogSettings.FilterEnabled;
            model.SubCategoryDisplayType = _catalogSettings.SubCategoryDisplayType;

            var customerRolesIds = _services.WorkContext.CurrentCustomer.CustomerRoles.Where(x => x.Active).Select(x => x.Id).ToList();

            // subcategories
            model.SubCategories = _categoryService
                .GetAllCategoriesByParentCategoryId(categoryId)
                .Select(x =>
                {
                    var subCatName = x.GetLocalized(y => y.Name);
                    var subCatModel = new CategoryModel.SubCategoryModel
                    {
                        Id = x.Id,
                        Name = subCatName,
                        SeName = x.GetSeName(),
                    };

                    //prepare picture model
                    int pictureSize = _mediaSettings.CategoryThumbPictureSize;
                    var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _services.WorkContext.WorkingLanguage.Id, _services.WebHelper.IsCurrentConnectionSecured(), _services.StoreContext.CurrentStore.Id);
                    subCatModel.PictureModel = _services.Cache.Get(categoryPictureCacheKey, () =>
                    {
                        var picture = _pictureService.GetPictureById(x.PictureId.GetValueOrDefault());
                        var pictureModel = new PictureModel()
                        {
                            PictureId = x.PictureId.GetValueOrDefault(),
                            FullSizeImageUrl = _pictureService.GetPictureUrl(picture),
                            ImageUrl = _pictureService.GetPictureUrl(picture, targetSize: pictureSize),
                            Title = string.Format(T("Media.Category.ImageLinkTitleFormat"), subCatName),
                            AlternateText = string.Format(T("Media.Category.ImageAlternateTextFormat"), subCatName)
                        };
                        return pictureModel;
                    });

                    return subCatModel;
                })
                .ToList();

            // Featured products
            if (!_catalogSettings.IgnoreFeaturedProducts)
            {
                IPagedList<Product> featuredProducts = null;

                string cacheKey = ModelCacheEventConsumer.CATEGORY_HAS_FEATURED_PRODUCTS_KEY.FormatInvariant(categoryId, string.Join(",", customerRolesIds), _services.StoreContext.CurrentStore.Id);
                var hasFeaturedProductsCache = _services.Cache.Get<bool?>(cacheKey);

                var ctx = new ProductSearchContext();
                if (category.Id > 0)
                    ctx.CategoryIds.Add(category.Id);
                ctx.FeaturedProducts = true;
                ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
                ctx.OrderBy = ProductSortingEnum.Position;
                ctx.PageSize = int.MaxValue;
                ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                ctx.VisibleIndividuallyOnly = true;
                ctx.Origin = categoryId.ToString();

                if (!hasFeaturedProductsCache.HasValue)
                {
                    featuredProducts = _productService.SearchProducts(ctx);
                    hasFeaturedProductsCache = featuredProducts.TotalCount > 0;
                    _services.Cache.Set(cacheKey, hasFeaturedProductsCache, 240);
                }

                if (hasFeaturedProductsCache.Value && featuredProducts == null)
                {
                    featuredProducts = _productService.SearchProducts(ctx);
                }

                if (featuredProducts != null)
                {
                    model.FeaturedProducts = _helper.PrepareProductOverviewModels(
                        featuredProducts,
                        prepareColorAttributes: true).ToList();
                }
            }

            // Products
            if (filter.HasValue())
            {
                var context = new FilterProductContext
                {
                    ParentCategoryID = category.Id,
                    CategoryIds = new List<int> { category.Id },
                    Criteria = _filterService.Deserialize(filter),
                    OrderBy = command.OrderBy
                };

                if (_catalogSettings.ShowProductsFromSubcategories)
                    context.CategoryIds.AddRange(_helper.GetChildCategoryIds(category.Id));

                var filterQuery = _filterService.ProductFilter(context);
                var products = new PagedList<Product>(filterQuery, command.PageIndex, command.PageSize);

                model.Products = _helper.PrepareProductOverviewModels(
                    products,
                    prepareColorAttributes: true,
                    prepareManufacturers: command.ViewMode.IsCaseInsensitiveEqual("list")).ToList();
                model.PagingFilteringContext.LoadPagedList(products);
            }
            else
            {	// use old filter
                IList<int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_services.WebHelper);

                var ctx2 = new ProductSearchContext();
                if (category.Id > 0)
                {
                    ctx2.CategoryIds.Add(category.Id);
                    if (_catalogSettings.ShowProductsFromSubcategories)
                    {
                        // include subcategories
                        ctx2.CategoryIds.AddRange(_helper.GetChildCategoryIds(category.Id));
                    }
                }
                ctx2.FeaturedProducts = _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false;
                ctx2.PriceMin = minPriceConverted;
                ctx2.PriceMax = maxPriceConverted;
                ctx2.LanguageId = _services.WorkContext.WorkingLanguage.Id;
                ctx2.FilteredSpecs = alreadyFilteredSpecOptionIds;
                ctx2.OrderBy = (ProductSortingEnum)command.OrderBy; // ProductSortingEnum.Position;
                ctx2.PageIndex = command.PageNumber - 1;
                ctx2.PageSize = command.PageSize;
                ctx2.LoadFilterableSpecificationAttributeOptionIds = true;
                ctx2.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                ctx2.VisibleIndividuallyOnly = true;
                ctx2.Origin = categoryId.ToString();

                var products = _productService.SearchProducts(ctx2);

                model.Products = _helper.PrepareProductOverviewModels(
                    products,
                    prepareColorAttributes: true,
                    prepareManufacturers: command.ViewMode.IsCaseInsensitiveEqual("list")).ToList();

                model.PagingFilteringContext.LoadPagedList(products);
                //model.PagingFilteringContext.ViewMode = viewMode;

                //specs
                model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds,
                    ctx2.FilterableSpecificationAttributeOptionIds,
                    _specificationAttributeService, _services.WebHelper, _services.WorkContext);
            }

            // template
            var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId);
            var templateViewPath = _services.Cache.Get(templateCacheKey, () =>
            {
                var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId);
                if (template == null)
                    template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault();
                return template.ViewPath;
            });

            // activity log
            _services.CustomerActivity.InsertActivity("PublicStore.ViewCategory", T("ActivityLog.PublicStore.ViewCategory"), category.Name);

            return View(templateViewPath, model);
        }
        public IEnumerable<ProductOverviewModel> PrepareProductOverviewModels(
			IEnumerable<Product> products,
			bool preparePriceModel = true, 
			bool preparePictureModel = true,
			int? productThumbPictureSize = null, 
			bool prepareSpecificationAttributes = false,
			bool forceRedirectionAfterAddingToCart = false, 
			bool prepareColorAttributes = false,
			bool prepareManufacturers = false,
            bool isCompact = false,
			bool prepareFullDescription = false,
			bool isCompareList = false)
        {
            if (products == null)
                throw new ArgumentNullException("products");

            // PERF!!
            var currentStore = _services.StoreContext.CurrentStore;
            var currentCustomer = _services.WorkContext.CurrentCustomer;
            var workingCurrency = _services.WorkContext.WorkingCurrency;
            var displayPrices = _services.Permissions.Authorize(StandardPermissionProvider.DisplayPrices);
            var enableShoppingCart = _services.Permissions.Authorize(StandardPermissionProvider.EnableShoppingCart);
            var enableWishlist = _services.Permissions.Authorize(StandardPermissionProvider.EnableWishlist);
            var taxDisplayType = _services.WorkContext.GetTaxDisplayTypeFor(currentCustomer, currentStore.Id);
            var cachedManufacturerModels = new Dictionary<int, ManufacturerOverviewModel>();

            string taxInfo = T(taxDisplayType == TaxDisplayType.IncludingTax ? "Tax.InclVAT" : "Tax.ExclVAT");
            var legalInfo = "";

            var res = new Dictionary<string, LocalizedString>(StringComparer.OrdinalIgnoreCase)
            {
                { "Products.CallForPrice", T("Products.CallForPrice") },
                { "Products.PriceRangeFrom", T("Products.PriceRangeFrom") },
                { "Media.Product.ImageLinkTitleFormat", T("Media.Product.ImageLinkTitleFormat") },
                { "Media.Product.ImageAlternateTextFormat", T("Media.Product.ImageAlternateTextFormat") },
                { "Products.DimensionsValue", T("Products.DimensionsValue") },
                { "Common.AdditionalShippingSurcharge", T("Common.AdditionalShippingSurcharge") }
            };

            if (_taxSettings.ShowLegalHintsInProductList)
            {
                if (_topicService.Value.GetTopicBySystemName("ShippingInfo", currentStore.Id) == null)
                {
                    legalInfo = T("Tax.LegalInfoFooter2").Text.FormatInvariant(taxInfo);
                }
                else
                {
                    var shippingInfoLink = _urlHelper.RouteUrl("Topic", new { SystemName = "shippinginfo" });
                    legalInfo = T("Tax.LegalInfoFooter").Text.FormatInvariant(taxInfo, shippingInfoLink);
                }
            }

            var cargoData = _priceCalculationService.CreatePriceCalculationContext(products);

            var models = new List<ProductOverviewModel>();

            foreach (var product in products)
            {
                var contextProduct = product;
                var finalPrice = decimal.Zero;

                var model = new ProductOverviewModel
                {
                    Id = product.Id,
                    Name = product.GetLocalized(x => x.Name).EmptyNull(),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    SeName = product.GetSeName()
                };

                if (prepareFullDescription)
                {
                    model.FullDescription = product.GetLocalized(x => x.FullDescription);
                }

                // price
                if (preparePriceModel)
                {
                    #region Prepare product price

                    var priceModel = new ProductOverviewModel.ProductPriceModel
                    {
                        ForceRedirectionAfterAddingToCart = forceRedirectionAfterAddingToCart,
                        ShowDiscountSign = _catalogSettings.ShowDiscountSign
                    };

                    if (product.ProductType == ProductType.GroupedProduct)
                    {
                        #region Grouped product

                        priceModel.DisableBuyButton = true;
                        priceModel.DisableWishListButton = true;
                        priceModel.AvailableForPreOrder = false;

                        var searchContext = new ProductSearchContext
                        {
                            OrderBy = ProductSortingEnum.Position,
                            StoreId = currentStore.Id,
                            ParentGroupedProductId = product.Id,
                            PageSize = int.MaxValue,
                            VisibleIndividuallyOnly = false
                        };

                        var associatedProducts = _productService.SearchProducts(searchContext);

                        if (associatedProducts.Count > 0)
                        {
                            contextProduct = associatedProducts.OrderBy(x => x.DisplayOrder).First();

                            if (displayPrices && _catalogSettings.PriceDisplayType != PriceDisplayType.Hide)
                            {
                                decimal? displayPrice = null;
                                bool displayFromMessage = false;

                                if (_catalogSettings.PriceDisplayType == PriceDisplayType.PreSelectedPrice)
                                {
                                    displayPrice = _priceCalculationService.GetPreselectedPrice(contextProduct, cargoData);
                                }
                                else if (_catalogSettings.PriceDisplayType == PriceDisplayType.PriceWithoutDiscountsAndAttributes)
                                {
                                    displayPrice = _priceCalculationService.GetFinalPrice(contextProduct, null, currentCustomer, decimal.Zero, false, 1, null, cargoData);
                                }
                                else
                                {
                                    displayFromMessage = true;
                                    displayPrice = _priceCalculationService.GetLowestPrice(product, cargoData, associatedProducts, out contextProduct);
                                }

                                if (contextProduct != null && !contextProduct.CustomerEntersPrice)
                                {
                                    if (contextProduct.CallForPrice)
                                    {
                                        priceModel.OldPrice = null;
                                        priceModel.Price = res["Products.CallForPrice"];
                                    }
                                    else if (displayPrice.HasValue)
                                    {
                                        //calculate prices
                                        decimal taxRate = decimal.Zero;
                                        decimal oldPriceBase = _taxService.GetProductPrice(contextProduct, contextProduct.OldPrice, out taxRate);
                                        decimal finalPriceBase = _taxService.GetProductPrice(contextProduct, displayPrice.Value, out taxRate);
                                        finalPrice = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, workingCurrency);

                                        priceModel.OldPrice = null;

                                        if (displayFromMessage)
                                            priceModel.Price = String.Format(res["Products.PriceRangeFrom"], _priceFormatter.FormatPrice(finalPrice));
                                        else
                                            priceModel.Price = _priceFormatter.FormatPrice(finalPrice);

                                        priceModel.HasDiscount = (finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero);
                                    }
                                    else
                                    {
                                        // Actually it's not possible (we presume that displayPrice always has a value). We never should get here
                                        Debug.WriteLine(string.Format("Cannot calculate displayPrice for product #{0}", product.Id));
                                    }
                                }
                            }
                        }

                        #endregion
                    }
                    else
                    {
                        #region Simple product

                        //add to cart button
                        priceModel.DisableBuyButton = product.DisableBuyButton || !enableShoppingCart || !displayPrices;

                        //add to wishlist button
                        priceModel.DisableWishListButton = product.DisableWishlistButton || !enableWishlist || !displayPrices;

                        //pre-order
                        priceModel.AvailableForPreOrder = product.AvailableForPreOrder;

                        //prices
                        if (displayPrices && _catalogSettings.PriceDisplayType != PriceDisplayType.Hide && !product.CustomerEntersPrice)
                        {
                            if (product.CallForPrice)
                            {
                                //call for price
                                priceModel.OldPrice = null;
                                priceModel.Price = res["Products.CallForPrice"];
                            }
                            else
                            {
                                //calculate prices
                                bool displayFromMessage = false;
                                decimal displayPrice = decimal.Zero;

                                if (_catalogSettings.PriceDisplayType == PriceDisplayType.PreSelectedPrice)
                                {
                                    displayPrice = _priceCalculationService.GetPreselectedPrice(product, cargoData);
                                }
                                else if (_catalogSettings.PriceDisplayType == PriceDisplayType.PriceWithoutDiscountsAndAttributes)
                                {
                                    displayPrice = _priceCalculationService.GetFinalPrice(product, null, currentCustomer, decimal.Zero, false, 1, null, cargoData);
                                }
                                else
                                {
                                    displayPrice = _priceCalculationService.GetLowestPrice(product, cargoData, out displayFromMessage);
                                }

                                decimal taxRate = decimal.Zero;
                                decimal oldPriceBase = _taxService.GetProductPrice(product, product.OldPrice, out taxRate);
                                decimal finalPriceBase = _taxService.GetProductPrice(product, displayPrice, out taxRate);

                                decimal oldPrice = _currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase, workingCurrency);
                                finalPrice = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, workingCurrency);

                                priceModel.HasDiscount = (finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero);

                                if (displayFromMessage)
                                {
                                    priceModel.OldPrice = null;
                                    priceModel.Price = String.Format(res["Products.PriceRangeFrom"], _priceFormatter.FormatPrice(finalPrice));
                                }
                                else
                                {
                                    if (priceModel.HasDiscount)
                                    {
                                        priceModel.OldPrice = _priceFormatter.FormatPrice(oldPrice);
                                        priceModel.Price = _priceFormatter.FormatPrice(finalPrice);
                                    }
                                    else
                                    {
                                        priceModel.OldPrice = null;
                                        priceModel.Price = _priceFormatter.FormatPrice(finalPrice);
                                    }
                                }
                            }
                        }

                        #endregion
                    }

                    model.ProductPrice = priceModel;
                    model.ProductPrice.CallForPrice = product.CallForPrice;

                    #endregion
                }

                // color squares
                if (prepareColorAttributes && _catalogSettings.ShowColorSquaresInLists)
                {
                    #region Prepare color attributes

                    var attributes = cargoData.Attributes.Load(contextProduct.Id);
                    var colorAttribute = attributes.FirstOrDefault(x => x.AttributeControlType == AttributeControlType.ColorSquares);

                    if (colorAttribute != null)
                    {
                        var colorValues =
                            from a in colorAttribute.ProductVariantAttributeValues.Take(50)
                            where (a.ColorSquaresRgb.HasValue() && !a.ColorSquaresRgb.IsCaseInsensitiveEqual("transparent"))
                            select new ProductOverviewModel.ColorAttributeModel
                            {
                                Color = a.ColorSquaresRgb,
                                Alias = a.Alias,
                                FriendlyName = a.GetLocalized(l => l.Name)
                            };

                        if (colorValues.Any())
                        {
                            model.ColorAttributes.AddRange(colorValues.Distinct());
                        }
                    }

                    #endregion
                }

                // picture
                if (preparePictureModel)
                {
                    #region Prepare product picture

                    //If a size has been set in the view, we use it in priority
                    int pictureSize = productThumbPictureSize.HasValue ? productThumbPictureSize.Value : _mediaSettings.ProductThumbPictureSize;

                    //prepare picture model
                    var defaultProductPictureCacheKey = string.Format(ModelCacheEventConsumer.PRODUCT_DEFAULTPICTURE_MODEL_KEY, product.Id, pictureSize, true,
                        _services.WorkContext.WorkingLanguage.Id, _services.WebHelper.IsCurrentConnectionSecured(), currentStore.Id);

                    model.DefaultPictureModel = _services.Cache.Get(defaultProductPictureCacheKey, () =>
                    {
                        var picture = product.GetDefaultProductPicture(_pictureService);
                        var pictureModel = new PictureModel
                        {
                            ImageUrl = _pictureService.GetPictureUrl(picture, pictureSize, !_catalogSettings.HideProductDefaultPictures),
                            FullSizeImageUrl = _pictureService.GetPictureUrl(picture, 0, !_catalogSettings.HideProductDefaultPictures),
                            Title = string.Format(res["Media.Product.ImageLinkTitleFormat"], model.Name),
                            AlternateText = string.Format(res["Media.Product.ImageAlternateTextFormat"], model.Name)
                        };
                        return pictureModel;
                    });

                    #endregion
                }

                // specs
                if (prepareSpecificationAttributes)
                {
                    model.SpecificationAttributeModels = PrepareProductSpecificationModel(product);
                }

                model.MinPriceProductId = contextProduct.Id;
                model.ShowSku = _catalogSettings.ShowProductSku;
                model.ShowWeight = _catalogSettings.ShowWeight;
                model.ShowDimensions = _catalogSettings.ShowDimensions;
                model.Sku = contextProduct.Sku;
                model.Dimensions = res["Products.DimensionsValue"].Text.FormatCurrent(
                    contextProduct.Width.ToString("F2"),
                    contextProduct.Height.ToString("F2"),
                    contextProduct.Length.ToString("F2")
                );
                model.DimensionMeasureUnit = _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId).Name;
                model.ThumbDimension = _mediaSettings.ProductThumbPictureSize;
                model.ShowLegalInfo = _taxSettings.ShowLegalHintsInProductList;
                model.LegalInfo = legalInfo;
                model.RatingSum = product.ApprovedRatingSum;
                model.TotalReviews = product.ApprovedTotalReviews;
                model.ShowReviews = _catalogSettings.ShowProductReviewsInProductLists;
                model.ShowDeliveryTimes = _catalogSettings.ShowDeliveryTimesInProductLists;
                model.InvisibleDeliveryTime = (product.ProductType == ProductType.GroupedProduct);

                model.IsShipEnabled = contextProduct.IsShipEnabled;
                model.DisplayDeliveryTimeAccordingToStock = contextProduct.DisplayDeliveryTimeAccordingToStock(_catalogSettings);
                model.StockAvailablity = contextProduct.FormatStockMessage(_localizationService);

                model.DisplayBasePrice = _catalogSettings.ShowBasePriceInProductLists;
                model.CompareEnabled = _catalogSettings.CompareProductsEnabled;
                model.HideBuyButtonInLists = _catalogSettings.HideBuyButtonInLists;

                if (model.ShowDeliveryTimes)
                {
                    var deliveryTime = _deliveryTimeService.GetDeliveryTime(contextProduct);
                    if (deliveryTime != null)
                    {
                        model.DeliveryTimeName = deliveryTime.GetLocalized(x => x.Name);
                        model.DeliveryTimeHexValue = deliveryTime.ColorHexValue;
                    }
                }

                if (prepareManufacturers)
                {
                    model.Manufacturers = PrepareManufacturersOverviewModel(_manufacturerService.GetProductManufacturersByProductId(product.Id), cachedManufacturerModels, false);
                }

                if (finalPrice != decimal.Zero && (_catalogSettings.ShowBasePriceInProductLists || isCompareList))
                {
                    model.BasePriceInfo = contextProduct.GetBasePriceInfo(finalPrice, _localizationService,	_priceFormatter, workingCurrency);
                }

                if (displayPrices)
                {
                    var addShippingPrice = _currencyService.ConvertCurrency(contextProduct.AdditionalShippingCharge, currentStore.PrimaryStoreCurrency, workingCurrency);

                    if (addShippingPrice > 0)
                    {
                        model.TransportSurcharge = res["Common.AdditionalShippingSurcharge"].Text.FormatCurrent(_priceFormatter.FormatPrice(addShippingPrice, true, false));
                    }
                }

                if (contextProduct.Weight > 0)
                {
                    model.Weight = "{0} {1}".FormatCurrent(contextProduct.Weight.ToString("F2"), _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).Name);
                }

                // IsNew
                if (_catalogSettings.LabelAsNewForMaxDays.HasValue)
                {
                    model.IsNew = ((DateTime.UtcNow - product.CreatedOnUtc).Days <= _catalogSettings.LabelAsNewForMaxDays.Value);
                }

                models.Add(model);
            }

            return models;
        }
Example #24
0
        public ActionResult ProductsByTag(int productTagId, CatalogPagingFilteringModel command)
        {
            var productTag = _productTagService.GetProductTagById(productTagId);
            if (productTag == null)
                return HttpNotFound();

            if (command.PageNumber <= 0)
                command.PageNumber = 1;

            var model = new ProductsByTagModel()
            {
                Id = productTag.Id,
                TagName = productTag.GetLocalized(y => y.Name)
            };

            if (command.OrderBy == (int)ProductSortingEnum.Initial)
            {
                command.OrderBy = (int)_catalogSettings.DefaultSortOrder;
            }

            _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
            {
                AllowCustomersToSelectPageSize = _catalogSettings.ProductsByTagAllowCustomersToSelectPageSize,
                PageSize = _catalogSettings.ProductsByTagPageSize,
                PageSizeOptions = _catalogSettings.ProductsByTagPageSizeOptions.IsEmpty()
                    ? _catalogSettings.DefaultPageSizeOptions
                    : _catalogSettings.ProductsByTagPageSizeOptions
            });

            //products

            var ctx = new ProductSearchContext();
            ctx.ProductTagId = productTag.Id;
            ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
            ctx.OrderBy = (ProductSortingEnum)command.OrderBy;
            ctx.PageIndex = command.PageNumber - 1;
            ctx.PageSize = command.PageSize;
            ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
            ctx.VisibleIndividuallyOnly = true;

            var products = _productService.SearchProducts(ctx);

            model.Products = _helper.PrepareProductOverviewModels(
                products,
                prepareColorAttributes: true,
                prepareManufacturers: command.ViewMode.IsCaseInsensitiveEqual("list")).ToList();

            model.PagingFilteringContext.LoadPagedList(products);
            //model.PagingFilteringContext.ViewMode = viewMode;
            return View(model);
        }
        protected void ResolveCategoryProductsCount(TreeNode<MenuItem> curNode)
        {
            try
            {
                // Perf: only resolve counts for categories in the current path.
                while (curNode != null)
                {
                    if (curNode.Children.Any(x => !x.Value.ElementsCount.HasValue))
                    {
                        lock (s_lock)
                        {
                            if (curNode.Children.Any(x => !x.Value.ElementsCount.HasValue))
                            {
                                foreach (var node in curNode.Children)
                                {
                                    var categoryIds = new List<int>();

                                    if (_catalogSettings.ShowCategoryProductNumberIncludingSubcategories)
                                    {
                                        // include subcategories
                                        node.TraverseTree(x => categoryIds.Add(x.Value.EntityId));
                                    }
                                    else
                                    {
                                        categoryIds.Add(node.Value.EntityId);
                                    }

                                    var ctx = new ProductSearchContext();
                                    ctx.CategoryIds = categoryIds;
                                    ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                                    node.Value.ElementsCount = _productService.CountProducts(ctx);
                                }
                            }
                        }
                    }

                    curNode = curNode.Parent;
                }
            }
            catch (Exception exc)
            {
                Logger.Error(exc.Message, exc);
            }
        }
        public ActionResult ProductAddPopup(int manufacturerId)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
                return AccessDeniedView();

            var ctx = new ProductSearchContext();
            ctx.LanguageId = _workContext.WorkingLanguage.Id;
            ctx.OrderBy = ProductSortingEnum.Position;
            ctx.PageSize = _adminAreaSettings.GridPageSize;
            ctx.ShowHidden = true;

            var products = _productService.SearchProducts(ctx);

            var model = new ManufacturerModel.AddManufacturerProductModel();
            model.Products = new GridModel<ProductModel>
            {
                Data = products.Select(x =>
                {
                    var productModel = x.ToModel();
                    productModel.ProductTypeName = x.GetProductTypeLabel(_localizationService);

                    return productModel;
                }),
                Total = products.TotalCount
            };

            //categories
            var allCategories = _categoryService.GetAllCategories(showHidden: true);
            var mappedCategories = allCategories.ToDictionary(x => x.Id);
            foreach (var c in allCategories)
            {
                model.AvailableCategories.Add(new SelectListItem() { Text = c.GetCategoryNameWithPrefix(_categoryService, mappedCategories), Value = c.Id.ToString() });
            }

            //manufacturers
            foreach (var m in _manufacturerService.GetAllManufacturers(true))
            {
                model.AvailableManufacturers.Add(new SelectListItem() { Text = m.Name, Value = m.Id.ToString() });
            }

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

            return View(model);
        }
		private void WriteProducts(UrlHelper urlHelper)
        {
            var ctx = new ProductSearchContext()
			{
				OrderBy = ProductSortingEnum.CreatedOn,
				PageSize = int.MaxValue,
				StoreId = _storeContext.CurrentStoreIdIfMultiStoreMode,
				VisibleIndividuallyOnly = true
			};

			var products = _productService.SearchProducts(ctx);
			var protocol = _securitySettings.ForceSslForAllPages ? "https" : "http";
            foreach (var product in products)
            {
				var url = urlHelper.RouteUrl("Product", new { SeName = product.GetSeName() }, protocol);
                var updateFrequency = UpdateFrequency.Weekly;
                var updateTime = product.UpdatedOnUtc;
                WriteUrlLocation(url, updateFrequency, updateTime);
            }
        }
Example #28
0
        private void CreateFeed(FeedFileCreationContext fileCreation, TaskExecutionContext taskContext)
        {
            var xmlSettings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                CheckCharacters = false
            };

            using (var writer = XmlWriter.Create(fileCreation.Stream, xmlSettings))
            {
                try
                {
                    fileCreation.Logger.Information("Log file - Google Merchant Center feed.");

                    var searchContext = new ProductSearchContext
                    {
                        OrderBy = ProductSortingEnum.CreatedOn,
                        PageSize = Settings.PageSize,
                        StoreId = fileCreation.Store.Id,
                        VisibleIndividuallyOnly = true
                    };

                    var currency = _currencyService.GetCurrencyById(Settings.CurrencyId);
                    var measureWeightSystemKey = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).SystemKeyword;

                    if (currency == null || !currency.Published)
                        currency = _services.WorkContext.WorkingCurrency;

                    writer.WriteStartDocument();
                    writer.WriteStartElement("rss");
                    writer.WriteAttributeString("version", "2.0");
                    writer.WriteAttributeString("xmlns", "g", null, _googleNamespace);
                    writer.WriteStartElement("channel");
                    writer.WriteElementString("title", "{0} - Feed for Google Merchant Center".FormatWith(fileCreation.Store.Name));
                    writer.WriteElementString("link", "http://base.google.com/base/");
                    writer.WriteElementString("description", "Information about products");

                    for (int i = 0; i < 9999999; ++i)
                    {
                        searchContext.PageIndex = i;

                        // Perf
                        _dbContext.DetachAll();

                        var products = _productService.SearchProducts(searchContext);

                        if (fileCreation.TotalRecords == 0)
                            fileCreation.TotalRecords = products.TotalCount * fileCreation.StoreCount;	// approx

                        foreach (var product in products)
                        {
                            fileCreation.Report();

                            if (product.ProductType == ProductType.SimpleProduct || product.ProductType == ProductType.BundledProduct)
                            {
                                WriteItem(fileCreation, writer, product, currency, measureWeightSystemKey);
                            }
                            else if (product.ProductType == ProductType.GroupedProduct)
                            {
                                var associatedSearchContext = new ProductSearchContext
                                {
                                    OrderBy = ProductSortingEnum.CreatedOn,
                                    PageSize = int.MaxValue,
                                    StoreId = fileCreation.Store.Id,
                                    VisibleIndividuallyOnly = false,
                                    ParentGroupedProductId = product.Id
                                };

                                foreach (var associatedProduct in _productService.SearchProducts(associatedSearchContext))
                                {
                                    WriteItem(fileCreation, writer, associatedProduct, currency, measureWeightSystemKey);
                                }
                            }

                            if (taskContext.CancellationToken.IsCancellationRequested)
                            {
                                fileCreation.Logger.Warning("A cancellation has been requested");
                                break;
                            }
                        }

                        if (!products.HasNextPage || taskContext.CancellationToken.IsCancellationRequested)
                            break;
                    }

                    writer.WriteEndElement(); // channel
                    writer.WriteEndElement(); // rss
                    writer.WriteEndDocument();

                    if (fileCreation.ErrorMessage.HasValue())
                        fileCreation.Logger.Error(fileCreation.ErrorMessage);
                }
                catch (Exception exc)
                {
                    fileCreation.Logger.Error(exc.Message, exc);
                }
            }
        }
        private void CreateFeed(FeedFileCreationContext fileCreation, TaskExecutionContext taskContext)
        {
            var xmlSettings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                CheckCharacters = false
            };

            using (var writer = XmlWriter.Create(fileCreation.Stream, xmlSettings))
            {
                try
                {
                    fileCreation.Logger.Information("Log file - Google Merchant Center feed.");

                    var searchContext = new ProductSearchContext()
                    {
                        OrderBy = ProductSortingEnum.CreatedOn,
                        PageSize = int.MaxValue,
                        StoreId = fileCreation.Store.Id,
                        VisibleIndividuallyOnly = true
                    };

                    string breakingError = null;
                    var qualifiedProducts = new List<Product>();
                    var currency = Helper.GetUsedCurrency(Settings.CurrencyId);
                    var products = _productService.SearchProducts(searchContext);
                    var measureWeightSystemKey = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).SystemKeyword;

                    if (fileCreation.TotalRecords == 0)
                        fileCreation.TotalRecords = products.Count * fileCreation.StoreCount;

                    writer.WriteStartDocument();
                    writer.WriteStartElement("rss");
                    writer.WriteAttributeString("version", "2.0");
                    writer.WriteAttributeString("xmlns", "g", null, _googleNamespace);
                    writer.WriteStartElement("channel");
                    writer.WriteElementString("title", "{0} - Feed for Google Merchant Center".FormatWith(fileCreation.Store.Name));
                    writer.WriteElementString("link", "http://base.google.com/base/");
                    writer.WriteElementString("description", "Information about products");

                    foreach (var product in products)
                    {
                        fileCreation.Report();

                        Helper.GetQualifiedProductsByProduct(product, fileCreation.Store, qualifiedProducts);

                        foreach (var qualifiedProduct in qualifiedProducts)
                        {
                            writer.WriteStartElement("item");

                            try
                            {
                                breakingError = WriteItem(writer, fileCreation.Store, qualifiedProduct, currency, measureWeightSystemKey);
                            }
                            catch (Exception exc)
                            {
                                fileCreation.Logger.Error(exc.Message, exc);
                            }

                            writer.WriteEndElement(); // item
                        }

                        if (breakingError.HasValue())
                        {
                            fileCreation.Logger.Error(breakingError);
                            break;
                        }
                        if (taskContext.CancellationToken.IsCancellationRequested)
                        {
                            fileCreation.Logger.Warning("A cancellation has been requested");
                            break;
                        }
                    }

                    writer.WriteEndElement(); // channel
                    writer.WriteEndElement(); // rss
                    writer.WriteEndDocument();

                    if (breakingError.HasValue())
                        throw new SmartException(breakingError);
                }
                catch (Exception exc)
                {
                    fileCreation.Logger.Error(exc.Message, exc);
                }
            }
        }
Example #30
0
		/// <summary>
		/// Export product list to XML
		/// </summary>
		/// <param name="stream">Stream to write</param>
		/// <param name="searchContext">Search context</param>
		public virtual void ExportProductsToXml(Stream stream, ProductSearchContext searchContext)
		{
			var settings = new XmlWriterSettings
			{
				Encoding = new UTF8Encoding(false),
				CheckCharacters = false
			};

			var context = new XmlExportContext
			{
				ProductTemplates = _productTemplateService.GetAllProductTemplates(),
				Languages = _languageService.GetAllLanguages(true),
				Store = _services.StoreContext.CurrentStore
			};

			using (var writer = XmlWriter.Create(stream, settings))
			{
				writer.WriteStartDocument();
				writer.WriteStartElement("Products");
				writer.WriteAttributeString("Version", SmartStoreVersion.CurrentVersion);

				for (int i = 0; i < 9999999; ++i)
				{
					searchContext.PageIndex = i;

					var products = _productService.SearchProducts(searchContext);

					foreach (var product in products)
					{
						writer.WriteStartElement("Product");

						try
						{
							WriteProductToXml(writer, product, context);
						}
						catch (Exception exc)
						{
							Logger.Error("{0} (Product.Id {1})".FormatWith(exc.Message, product.Id), exc);
						}

						writer.WriteEndElement();		// Product
					}

					if (!products.HasNextPage)
						break;
				}

				writer.WriteEndElement();
				writer.WriteEndDocument();
				writer.Flush();
				writer.Close();

				stream.Seek(0, SeekOrigin.Begin);
			}
		}
        public ActionResult AddProductToOrder(GridCommand command, OrderModel.AddOrderProductModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrders))
                return AccessDeniedView();

            var gridModel = new GridModel();
            var searchContext = new ProductSearchContext()
            {
                CategoryIds = new List<int>() { model.SearchCategoryId },
                ManufacturerId = model.SearchManufacturerId,
                Keywords = model.SearchProductName,
                PageIndex = command.Page - 1,
                PageSize = command.PageSize,
                ShowHidden = true,
                ProductType = model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null
            };

            var products = _productService.SearchProducts(searchContext);
            gridModel.Data = products.Select(x =>
            {
                var productModel = new OrderModel.AddOrderProductModel.ProductModel()
                {
                    Id = x.Id,
                    Name =  x.Name,
                    Sku = x.Sku,
                    ProductTypeName = x.GetProductTypeLabel(_localizationService),
                    ProductTypeLabelHint = x.ProductTypeLabelHint
                };

                return productModel;
            });
            gridModel.Total = products.TotalCount;
            return new JsonResult
            {
                Data = gridModel
            };
        }
        public virtual void InheritStoresIntoChildren(int categoryId, 
            bool touchProductsWithMultipleCategories = false,
            bool touchExistingAcls = false,
            bool categoriesOnly = false)
        {

            var category = GetCategoryById(categoryId);
            var subcategories = GetAllCategoriesByParentCategoryId(categoryId, true);
            var context = new ProductSearchContext { PageSize = int.MaxValue , ShowHidden = true };
            context.CategoryIds.AddRange(subcategories.Select(x => x.Id));
            context.CategoryIds.Add(categoryId);
            var products = _productService.SearchProducts(context);

            var allStores = _storeService.GetAllStores();
            var categoryStoreMappings = _storeMappingService.GetStoresIdsWithAccess(category);

            using (var scope = new DbContextScope(ctx: _storeMappingRepository.Context, autoDetectChanges: false, proxyCreation: false, validateOnSave: false))
            {
                _storeMappingRepository.AutoCommitEnabled = false;

                foreach (var subcategory in subcategories)
                {
                    if (subcategory.LimitedToStores != category.LimitedToStores)
                    {
                        subcategory.LimitedToStores = category.LimitedToStores;
                        _categoryRepository.Update(subcategory);
                    }

                    var existingStoreMappingsRecords = _storeMappingService.GetStoreMappings(subcategory).ToDictionary(x => x.StoreId);

                    foreach (var store in allStores)
                    {
                        if (categoryStoreMappings.Contains(store.Id))
                        {
                            if (!existingStoreMappingsRecords.ContainsKey(store.Id))
                            {
                                _storeMappingRepository.Insert(new StoreMapping { StoreId = store.Id, EntityId = subcategory.Id, EntityName = "Category" });
                            }
                        }
                        else
                        {
                            StoreMapping storeMappingToDelete;
                            if (existingStoreMappingsRecords.TryGetValue(store.Id, out storeMappingToDelete))
                            {
                                _storeMappingRepository.Delete(storeMappingToDelete);
                            }
                        }
                    }
                }

                _storeMappingRepository.Context.SaveChanges();

                foreach (var product in products)
                {
                    if (product.LimitedToStores != category.LimitedToStores)
                    {
                        product.LimitedToStores = category.LimitedToStores;
                        _productRepository.Update(product);
                    }

                    var existingStoreMappingsRecords = _storeMappingService.GetStoreMappings(product).ToDictionary(x => x.StoreId);

                    foreach (var store in allStores)
                    {
                        if (categoryStoreMappings.Contains(store.Id))
                        {
                            if (!existingStoreMappingsRecords.ContainsKey(store.Id))
                            {
                                _storeMappingRepository.Insert(new StoreMapping { StoreId = store.Id, EntityId = product.Id, EntityName = "Product" });
                            }
                        }
                        else
                        {
                            StoreMapping storeMappingToDelete;
                            if (existingStoreMappingsRecords.TryGetValue(store.Id, out storeMappingToDelete))
                            {
                                _storeMappingRepository.Delete(storeMappingToDelete);
                            }
                        }
                    }
                }

                _storeMappingRepository.Context.SaveChanges();
            }
        }
        public ActionResult EntityPicker(EntityPickerModel model, FormCollection form)
        {
            model.PageSize = 48; // _commonSettings.EntityPickerPageSize;
            model.PublishedString = T("Common.Published");
            model.UnpublishedString = T("Common.Unpublished");

            try
            {
                var disableIf = model.DisableIf.SplitSafe(",").Select(x => x.ToLower().Trim()).ToList();
                var disableIds = model.DisableIds.SplitSafe(",").Select(x => x.ToInt()).ToList();

                using (var scope = new DbContextScope(_services.DbContext, autoDetectChanges: false, proxyCreation: true, validateOnSave: false, forceNoTracking: true))
                {
                    if (model.Entity.IsCaseInsensitiveEqual("product"))
                    {
                        #region Product

                        model.SearchTerm = model.ProductName.TrimSafe();

                        var hasPermission = _services.Permissions.Authorize(StandardPermissionProvider.ManageCatalog);
                        var storeLocation = _services.WebHelper.GetStoreLocation(false);
                        var disableIfNotSimpleProduct = disableIf.Contains("notsimpleproduct");
                        var labelTextGrouped = T("Admin.Catalog.Products.ProductType.GroupedProduct.Label").Text;
                        var labelTextBundled = T("Admin.Catalog.Products.ProductType.BundledProduct.Label").Text;
                        var sku = T("Products.Sku").Text;

                        var searchContext = new ProductSearchContext
                        {
                            CategoryIds = (model.CategoryId == 0 ? null : new List<int> { model.CategoryId }),
                            ManufacturerId = model.ManufacturerId,
                            StoreId = model.StoreId,
                            Keywords = model.SearchTerm,
                            ProductType = model.ProductTypeId > 0 ? (ProductType?)model.ProductTypeId : null,
                            SearchSku = !_catalogSettings.SuppressSkuSearch,
                            ShowHidden = hasPermission
                        };

                        var query = _productService.Value.PrepareProductSearchQuery(searchContext, x => new { x.Id, x.Sku, x.Name, x.Published, x.ProductTypeId });

                        query = from x in query
                                group x by x.Id into grp
                                orderby grp.Key
                                select grp.FirstOrDefault();

                        var products = query
                            .OrderBy(x => x.Name)
                            .Skip(model.PageIndex * model.PageSize)
                            .Take(model.PageSize)
                            .ToList();

                        var productIds = products.Select(x => x.Id).ToArray();
                        var pictures = _productService.Value.GetProductPicturesByProductIds(productIds, true);

                        model.SearchResult = products
                            .Select(x =>
                            {
                                var item = new EntityPickerModel.SearchResultModel
                                {
                                    Id = x.Id,
                                    ReturnValue = (model.ReturnField.IsCaseInsensitiveEqual("sku") ? x.Sku : x.Id.ToString()),
                                    Title = x.Name,
                                    Summary = x.Sku,
                                    SummaryTitle = "{0}: {1}".FormatInvariant(sku, x.Sku.NaIfEmpty()),
                                    Published = (hasPermission ? x.Published : (bool?)null)
                                };

                                if (disableIfNotSimpleProduct)
                                {
                                    item.Disable = (x.ProductTypeId != (int)ProductType.SimpleProduct);
                                }

                                if (!item.Disable && disableIds.Contains(x.Id))
                                {
                                    item.Disable = true;
                                }

                                if (x.ProductTypeId == (int)ProductType.GroupedProduct)
                                {
                                    item.LabelText = labelTextGrouped;
                                    item.LabelClassName = "label-success";
                                }
                                else if (x.ProductTypeId == (int)ProductType.BundledProduct)
                                {
                                    item.LabelText = labelTextBundled;
                                    item.LabelClassName = "label-info";
                                }

                                var productPicture = pictures.FirstOrDefault(y => y.Key == x.Id);
                                if (productPicture.Value != null)
                                {
                                    var picture = productPicture.Value.FirstOrDefault();
                                    if (picture != null)
                                    {
                                        item.ImageUrl = _pictureService.Value.GetPictureUrl(picture.Picture, _mediaSettings.Value.ProductThumbPictureSizeOnProductDetailsPage,
                                            !_catalogSettings.HideProductDefaultPictures, storeLocation);
                                    }
                                }

                                return item;
                            })
                            .ToList();

                        #endregion
                    }
                }
            }
            catch (Exception exception)
            {
                NotifyError(exception.ToAllMessages());
            }

            return PartialView("EntityPickerList", model);
        }
        public virtual void InheritAclIntoChildren(int categoryId,
                                                   bool touchProductsWithMultipleCategories = false,
                                                   bool touchExistingAcls = false,
                                                   bool categoriesOnly    = false)
        {
            var category      = GetCategoryById(categoryId);
            var subcategories = GetAllCategoriesByParentCategoryId(categoryId, true);
            var context       = new ProductSearchContext {
                PageSize = int.MaxValue, ShowHidden = true
            };

            context.CategoryIds.AddRange(subcategories.Select(x => x.Id));
            context.CategoryIds.Add(categoryId);
            var products              = _productService.SearchProducts(context);
            var allCustomerRoles      = _customerService.GetAllCustomerRoles(true);
            var categoryCustomerRoles = _aclService.GetCustomerRoleIdsWithAccess(category);

            using (var scope = new DbContextScope(ctx: _aclRepository.Context, autoDetectChanges: false, proxyCreation: false, validateOnSave: false))
            {
                _aclRepository.AutoCommitEnabled = false;

                foreach (var subcategory in subcategories)
                {
                    if (subcategory.SubjectToAcl != category.SubjectToAcl)
                    {
                        subcategory.SubjectToAcl = category.SubjectToAcl;
                        _categoryRepository.Update(subcategory);
                    }

                    var existingAclRecords = _aclService.GetAclRecords(subcategory).ToDictionary(x => x.CustomerRoleId);

                    foreach (var customerRole in allCustomerRoles)
                    {
                        if (categoryCustomerRoles.Contains(customerRole.Id))
                        {
                            if (!existingAclRecords.ContainsKey(customerRole.Id))
                            {
                                _aclRepository.Insert(new AclRecord {
                                    CustomerRole = customerRole, CustomerRoleId = customerRole.Id, EntityId = subcategory.Id, EntityName = "Category"
                                });
                            }
                        }
                        else
                        {
                            AclRecord aclRecordToDelete;
                            if (existingAclRecords.TryGetValue(customerRole.Id, out aclRecordToDelete))
                            {
                                _aclRepository.Delete(aclRecordToDelete);
                            }
                        }
                    }
                }

                _aclRepository.Context.SaveChanges();

                foreach (var product in products)
                {
                    if (product.SubjectToAcl != category.SubjectToAcl)
                    {
                        product.SubjectToAcl = category.SubjectToAcl;
                        _productRepository.Update(product);
                    }

                    var existingAclRecords = _aclService.GetAclRecords(product).ToDictionary(x => x.CustomerRoleId);

                    foreach (var customerRole in allCustomerRoles)
                    {
                        if (categoryCustomerRoles.Contains(customerRole.Id))
                        {
                            if (!existingAclRecords.ContainsKey(customerRole.Id))
                            {
                                _aclRepository.Insert(new AclRecord {
                                    CustomerRole = customerRole, CustomerRoleId = customerRole.Id, EntityId = product.Id, EntityName = "Product"
                                });
                            }
                        }
                        else
                        {
                            AclRecord aclRecordToDelete;
                            if (existingAclRecords.TryGetValue(customerRole.Id, out aclRecordToDelete))
                            {
                                _aclRepository.Delete(aclRecordToDelete);
                            }
                        }
                    }
                }

                _aclRepository.Context.SaveChanges();
            }
        }
 public ProductsSearchingEvent(ProductSearchContext ctx)
 {
     SearchContext = ctx;
 }