示例#1
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));
        }
        public ActionResult ProductDetails(int productId, string attributes, ProductVariantQuery query)
        {
            var product = _productService.GetProductById(productId);

            if (product == null || product.Deleted || product.IsSystemProduct)
            {
                return(HttpNotFound());
            }

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

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

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

            // Is product individually visible?
            if (!product.VisibleIndividually)
            {
                // Find parent grouped product.
                var parentGroupedProduct = _productService.GetProductById(product.ParentGroupedProductId);

                if (parentGroupedProduct == null)
                {
                    return(HttpNotFound());
                }

                var routeValues = new RouteValueDictionary();
                routeValues.Add("SeName", parentGroupedProduct.GetSeName());

                // Add query string parameters.
                Request.QueryString.AllKeys.Each(x => routeValues.Add(x, Request.QueryString[x]));

                return(RedirectToRoute("Product", routeValues));
            }

            // Prepare the view model
            var model = _helper.PrepareProductDetailsPageModel(product, query);

            // Some cargo data
            model.PictureSize          = _mediaSettings.ProductDetailsPictureSize;
            model.CanonicalUrlsEnabled = _seoSettings.CanonicalUrlsEnabled;

            // Save as recently viewed
            _recentlyViewedProductsService.AddProductToRecentlyViewedList(product.Id);

            // Activity log
            _services.CustomerActivity.InsertActivity("PublicStore.ViewProduct", T("ActivityLog.PublicStore.ViewProduct"), product.Name);

            // Breadcrumb
            if (_catalogSettings.CategoryBreadcrumbEnabled)
            {
                _helper.GetCategoryBreadCrumb(0, productId).Select(x => x.Value).Each(x => _breadcrumb.Track(x));
                _breadcrumb.Track(new MenuItem
                {
                    Text     = model.Name,
                    Rtl      = model.Name.CurrentLanguage.Rtl,
                    EntityId = product.Id,
                    Url      = Url.RouteUrl("Product", new { productId = product.Id, SeName = model.SeName })
                });
            }

            return(View(model.ProductTemplateViewPath, model));
        }