Ejemplo n.º 1
0
        public ActionResult RelatedProducts(int productId, int?productThumbPictureSize)
        {
            var products        = new List <Product>();
            var relatedProducts = _productService.GetRelatedProductsByProductId1(productId);

            foreach (var product in _productService.GetProductsByIds(relatedProducts.Select(x => x.ProductId2).ToArray()))
            {
                // Ensure has ACL permission and appropriate store mapping
                if (_aclService.Authorize(product) && _storeMappingService.Authorize(product))
                {
                    products.Add(product);
                }
            }

            if (products.Count == 0)
            {
                return(Content(""));
            }

            var settings = _helper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Grid, x =>
            {
                x.ThumbnailSize    = productThumbPictureSize;
                x.MapDeliveryTimes = false;
            });

            var model = _helper.MapProductSummaryModel(products, settings);

            model.ShowBasePrice = false;

            return(PartialView("Product.RelatedProducts", model));
        }
        public ActionResult InstantSearch(CatalogSearchQuery query)
        {
            if (string.IsNullOrWhiteSpace(query.Term) || query.Term.Length < _searchSettings.InstantSearchTermMinLength)
            {
                return(Content(string.Empty));
            }

            query
            .BuildFacetMap(false)
            .Slice(0, Math.Min(16, _searchSettings.InstantSearchNumberOfProducts))
            .SortBy(ProductSortingEnum.Relevance);

            var result = _catalogSearchService.Search(query);

            var model = new SearchResultModel(query)
            {
                SearchResult       = result,
                Term               = query.Term,
                TotalProductsCount = result.TotalHitsCount
            };

            var mappingSettings = _catalogHelper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Mini, x =>
            {
                x.MapPrices            = false;
                x.MapShortDescription  = true;
                x.MapPictures          = _searchSettings.ShowProductImagesInInstantSearch;
                x.ThumbnailSize        = _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage;
                x.PrefetchTranslations = true;
                x.PrefetchUrlSlugs     = true;
            });

            using (_urlRecordService.BeginScope(false))
                using (_localizedEntityService.BeginScope(false))
                {
                    // InstantSearch should be REALLY very fast! No time for smart caching stuff.
                    if (result.Hits.Count > 0)
                    {
                        _localizedEntityService.PrefetchLocalizedProperties(
                            nameof(Product),
                            Services.WorkContext.WorkingLanguage.Id,
                            result.Hits.Select(x => x.Id).ToArray());
                    }

                    // Add product hits.
                    model.TopProducts = _catalogHelper.MapProductSummaryModel(result.Hits, mappingSettings);

                    // Add spell checker suggestions (if any).
                    model.AddSpellCheckerSuggestions(result.SpellCheckerSuggestions, T, x => Url.RouteUrl("Search", new { q = x }));
                }

            return(PartialView(model));
        }
        public ActionResult InstantSearch(CatalogSearchQuery query)
        {
            if (string.IsNullOrWhiteSpace(query.Term) || query.Term.Length < _searchSettings.InstantSearchTermMinLength)
            {
                return(Content(string.Empty));
            }

            query
            .BuildFacetMap(false)
            .Slice(0, Math.Min(16, _searchSettings.InstantSearchNumberOfProducts))
            .SortBy(ProductSortingEnum.Relevance);

            var result = _catalogSearchService.Search(query);

            var model = new SearchResultModel(query)
            {
                SearchResult       = result,
                Term               = query.Term,
                TotalProductsCount = result.TotalHitsCount
            };

            var mappingSettings = _catalogHelper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Mini, x =>
            {
                x.MapPrices           = false;
                x.MapShortDescription = true;
            });

            mappingSettings.MapPictures   = _searchSettings.ShowProductImagesInInstantSearch;
            mappingSettings.ThumbnailSize = _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage;

            var summaryModel = _catalogHelper.MapProductSummaryModel(result.Hits, mappingSettings);

            // Add product hits
            model.TopProducts = summaryModel;

            // Add spell checker suggestions (if any)
            AddSpellCheckerSuggestionsToModel(result.SpellCheckerSuggestions, model);

            return(PartialView(model));
        }
        public ActionResult Category(int categoryId, CatalogSearchQuery query)
        {
            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(Permissions.Catalog.Category.Read))
            {
                return(HttpNotFound());
            }

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

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

            var store    = Services.StoreContext.CurrentStore;
            var customer = Services.WorkContext.CurrentCustomer;

            // 'Continue shopping' URL.
            if (!Services.WorkContext.CurrentCustomer.IsSystemAccount)
            {
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastContinueShoppingPage, Services.WebHelper.GetThisPageUrl(false), store.Id);
            }

            var model = category.ToModel();

            if (query.IsSubPage && !_catalogSettings.ShowDescriptionInSubPages)
            {
                model.Description.ChangeValue(string.Empty);
                model.BottomDescription.ChangeValue(string.Empty);
            }

            Services.DisplayControl.Announce(category);

            // Category breadcrumb.
            if (_catalogSettings.CategoryBreadcrumbEnabled)
            {
                _helper.GetCategoryBreadcrumb(_breadcrumb, ControllerContext);
            }

            // Products.
            var catIds = new int[] { categoryId };

            if (_catalogSettings.ShowProductsFromSubcategories)
            {
                // Include subcategories.
                catIds = catIds.Concat(_helper.GetChildCategoryIds(categoryId)).ToArray();
            }

            query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? (bool?)null : false, catIds);

            var searchResult = _catalogSearchService.Search(query);

            model.SearchResult = searchResult;

            var mappingSettings = _helper.GetBestFitProductSummaryMappingSettings(query.GetViewMode());

            model.Products = _helper.MapProductSummaryModel(searchResult.Hits, mappingSettings);

            model.SubCategoryDisplayType = _catalogSettings.SubCategoryDisplayType;

            var customerRolesIds = customer.CustomerRoleMappings
                                   .Select(x => x.CustomerRole)
                                   .Where(x => x.Active)
                                   .Select(x => x.Id)
                                   .ToList();

            var pictureSize  = _mediaSettings.CategoryThumbPictureSize;
            var fallbackType = _catalogSettings.HideCategoryDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity;

            var hideSubCategories = _catalogSettings.SubCategoryDisplayType == SubCategoryDisplayType.Hide ||
                                    (_catalogSettings.SubCategoryDisplayType == SubCategoryDisplayType.AboveProductList && query.IsSubPage && !_catalogSettings.ShowSubCategoriesInSubPages);
            var hideFeaturedProducts = _catalogSettings.IgnoreFeaturedProducts || (query.IsSubPage && !_catalogSettings.IncludeFeaturedProductsInSubPages);

            // Subcategories.
            if (!hideSubCategories)
            {
                var subCategories = _categoryService.GetAllCategoriesByParentCategoryId(categoryId);
                model.SubCategories = _helper.MapCategorySummaryModel(subCategories, pictureSize);
            }

            // Featured Products.
            if (!hideFeaturedProducts)
            {
                CatalogSearchResult featuredProductsResult = null;

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

                var featuredProductsQuery = new CatalogSearchQuery()
                                            .VisibleOnly(customer)
                                            .WithVisibility(ProductVisibility.Full)
                                            .WithCategoryIds(true, categoryId)
                                            .HasStoreId(Services.StoreContext.CurrentStore.Id)
                                            .WithLanguage(Services.WorkContext.WorkingLanguage)
                                            .WithCurrency(Services.WorkContext.WorkingCurrency);

                if (!hasFeaturedProductsCache.HasValue)
                {
                    featuredProductsResult   = _catalogSearchService.Search(featuredProductsQuery);
                    hasFeaturedProductsCache = featuredProductsResult.TotalHitsCount > 0;
                    Services.Cache.Put(cacheKey, hasFeaturedProductsCache, TimeSpan.FromHours(6));
                }

                if (hasFeaturedProductsCache.Value && featuredProductsResult == null)
                {
                    featuredProductsResult = _catalogSearchService.Search(featuredProductsQuery);
                }

                if (featuredProductsResult != null)
                {
                    var featuredProductsmappingSettings = _helper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Grid);
                    model.FeaturedProducts = _helper.MapProductSummaryModel(featuredProductsResult.Hits, featuredProductsmappingSettings);
                }
            }

            // Prepare paging/sorting/mode stuff.
            _helper.MapListActions(model.Products, category, _catalogSettings.DefaultPageSizeOptions);

            // 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));
        }
Ejemplo n.º 5
0
        public ActionResult Category(int categoryId, CatalogSearchQuery query)
        {
            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
            if (!_services.WorkContext.CurrentCustomer.IsSystemAccount)
            {
                _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentCustomer,
                                                       SystemCustomerAttributeNames.LastContinueShoppingPage,
                                                       _services.WebHelper.GetThisPageUrl(false),
                                                       _services.StoreContext.CurrentStore.Id);
            }

            var model = category.ToModel();

            _services.DisplayControl.Announce(category);

            // Category breadcrumb
            if (_catalogSettings.CategoryBreadcrumbEnabled)
            {
                _helper.GetCategoryBreadCrumb(category.Id, 0).Select(x => x.Value).Each(x => _breadcrumb.Track(x));
            }

            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(),
                };

                _services.DisplayControl.Announce(x);

                // 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.StoreContext.CurrentStore.Id);
                subCatModel.PictureModel    = _services.Cache.Get(categoryPictureCacheKey, () =>
                {
                    var picture      = _pictureService.GetPictureById(x.PictureId.GetValueOrDefault());
                    var pictureModel = new PictureModel
                    {
                        PictureId           = x.PictureId.GetValueOrDefault(),
                        Size                = pictureSize,
                        FullSizeImageUrl    = _pictureService.GetPictureUrl(picture),
                        FullSizeImageWidth  = picture?.Width,
                        FullSizeImageHeight = picture?.Height,
                        ImageUrl            = _pictureService.GetPictureUrl(picture, pictureSize, !_catalogSettings.HideCategoryDefaultPictures),
                        Title               = string.Format(T("Media.Category.ImageLinkTitleFormat"), subCatName),
                        AlternateText       = string.Format(T("Media.Category.ImageAlternateTextFormat"), subCatName)
                    };

                    return(pictureModel);
                }, TimeSpan.FromHours(6));

                return(subCatModel);
            })
                                  .ToList();

            // Featured Products
            if (!_catalogSettings.IgnoreFeaturedProducts)
            {
                CatalogSearchResult featuredProductsResult = 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 featuredProductsQuery = new CatalogSearchQuery()
                                            .VisibleOnly(_services.WorkContext.CurrentCustomer)
                                            .VisibleIndividuallyOnly(true)
                                            .WithCategoryIds(true, categoryId)
                                            .HasStoreId(_services.StoreContext.CurrentStore.Id)
                                            .WithLanguage(_services.WorkContext.WorkingLanguage)
                                            .WithCurrency(_services.WorkContext.WorkingCurrency);

                if (!hasFeaturedProductsCache.HasValue)
                {
                    featuredProductsResult   = _catalogSearchService.Search(featuredProductsQuery);
                    hasFeaturedProductsCache = featuredProductsResult.TotalHitsCount > 0;
                    _services.Cache.Put(cacheKey, hasFeaturedProductsCache, TimeSpan.FromHours(6));
                }

                if (hasFeaturedProductsCache.Value && featuredProductsResult == null)
                {
                    featuredProductsResult = _catalogSearchService.Search(featuredProductsQuery);
                }

                if (featuredProductsResult != null)
                {
                    var featuredProductsmappingSettings = _helper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Grid);
                    model.FeaturedProducts = _helper.MapProductSummaryModel(featuredProductsResult.Hits, featuredProductsmappingSettings);
                }
            }

            // Products
            int[] catIds = new int[] { categoryId };
            if (_catalogSettings.ShowProductsFromSubcategories)
            {
                // Include subcategories
                catIds = catIds.Concat(_helper.GetChildCategoryIds(categoryId)).ToArray();
            }

            query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? (bool?)null : false, catIds);

            var searchResult = _catalogSearchService.Search(query);

            model.SearchResult = searchResult;

            var mappingSettings = _helper.GetBestFitProductSummaryMappingSettings(query.GetViewMode());

            model.Products = _helper.MapProductSummaryModel(searchResult.Hits, mappingSettings);

            // Prepare paging/sorting/mode stuff
            _helper.MapListActions(model.Products, category, _catalogSettings.DefaultPageSizeOptions);

            // 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));
        }