protected virtual void ConvertCategory(CatalogSearchQuery query, RouteData routeData, string origin) { if (origin == "Catalog/Category") { // we don't need category facetting in category pages return; } List <int> ids; if (GetValueFor(query, "c", FacetGroupKind.Category, out ids) && ids != null && ids.Any()) { // TODO; (mc) Get deep ids (???) Make a low-level version of CatalogHelper.GetChildCategoryIds() query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, ids.ToArray()); } AddFacet(query, FacetGroupKind.Category, true, FacetSorting.HitsDesc, descriptor => { if (ids != null) { foreach (var id in ids) { descriptor.AddValue(new FacetValue(id, IndexTypeCode.Int32) { IsSelected = true }); } } }); }
protected virtual void ConvertCategory(CatalogSearchQuery query, string origin) { if (origin == "Catalog/Category") { // We don't need category facetting in category pages. return; } var alias = _catalogSearchQueryAliasMapper.GetCommonFacetAliasByGroupKind(FacetGroupKind.Category, query.LanguageId ?? 0); if (TryGetValueFor(alias ?? "c", out List <int> ids) && ids != null && ids.Any()) { // TODO; (mc) Get deep ids (???) Make a low-level version of CatalogHelper.GetChildCategoryIds() query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : false, ids.ToArray()); } AddFacet(query, FacetGroupKind.Category, true, FacetSorting.HitsDesc, descriptor => { if (ids != null) { foreach (var id in ids) { descriptor.AddValue(new FacetValue(id, IndexTypeCode.Int32) { IsSelected = true }); } } }); }
public async Task <IActionResult> Category(int categoryId, CatalogSearchQuery query) { var category = await _db.Categories .Include(x => x.MediaFile) .FindByIdAsync(categoryId, false); if (category == null || category.Deleted) { return(NotFound()); } // Check whether the current user has a "Manage catalog" permission. // It allows him to preview a category before publishing. if (!category.Published && !await Services.Permissions.AuthorizeAsync(Permissions.Catalog.Category.Read)) { return(NotFound()); } // ACL (access control list). if (!await _aclService.AuthorizeAsync(category)) { return(NotFound()); } // Store mapping. if (!await _storeMappingService.AuthorizeAsync(category)) { return(NotFound()); } var customer = Services.WorkContext.CurrentCustomer; var storeId = Services.StoreContext.CurrentStore.Id; // 'Continue shopping' URL. if (!customer.IsSystemAccount) { customer.GenericAttributes.LastContinueShoppingPage = Services.WebHelper.GetCurrentPageUrl(false); } var model = await _helper.PrepareCategoryModelAsync(category); if (_seoSettings.CanonicalUrlsEnabled) { model.CanonicalUrl = _urlHelper.Value.RouteUrl("Category", new { model.SeName }, Request.Scheme); } if (query.IsSubPage && !_catalogSettings.ShowDescriptionInSubPages) { model.Description.ChangeValue(string.Empty); model.BottomDescription.ChangeValue(string.Empty); } model.Image = await _helper.PrepareCategoryImageModelAsync(category, model.Name); // Category breadcrumb. if (_catalogSettings.CategoryBreadcrumbEnabled) { await _helper.GetBreadcrumbAsync(_breadcrumb, ControllerContext); } // Products. var catIds = new int[] { categoryId }; if (_catalogSettings.ShowProductsFromSubcategories) { // Include subcategories. catIds = catIds.Concat(await _helper.GetChildCategoryIdsAsync(categoryId)).ToArray(); } query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : false, catIds); var searchResult = await _catalogSearchService.SearchAsync(query); model.SearchResult = searchResult; var viewMode = _helper.GetSearchQueryViewMode(query); var mappingSettings = _helper.GetBestFitProductSummaryMappingSettings(viewMode); model.Products = await _helper.MapProductSummaryModelAsync(searchResult, mappingSettings); model.SubCategoryDisplayType = _catalogSettings.SubCategoryDisplayType; 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 = await _categoryService.GetCategoriesByParentCategoryIdAsync(categoryId); model.SubCategories = await _helper.MapCategorySummaryModelAsync(subCategories, pictureSize); } // Featured Products. if (!hideFeaturedProducts) { CatalogSearchResult featuredProductsResult = null; string cacheKey = ModelCacheInvalidator.CATEGORY_HAS_FEATURED_PRODUCTS_KEY.FormatInvariant(categoryId, string.Join(",", customer.GetRoleIds()), storeId); var hasFeaturedProductsCache = await Services.Cache.GetAsync <bool?>(cacheKey); var featuredProductsQuery = new CatalogSearchQuery() .VisibleOnly(customer) .WithVisibility(ProductVisibility.Full) .WithCategoryIds(true, categoryId) .HasStoreId(storeId) .WithLanguage(Services.WorkContext.WorkingLanguage) .WithCurrency(Services.WorkContext.WorkingCurrency); if (!hasFeaturedProductsCache.HasValue) { featuredProductsResult = await _catalogSearchService.SearchAsync(featuredProductsQuery); hasFeaturedProductsCache = featuredProductsResult.TotalHitsCount > 0; await Services.Cache.PutAsync(cacheKey, hasFeaturedProductsCache); } if (hasFeaturedProductsCache.Value && featuredProductsResult == null) { featuredProductsResult = await _catalogSearchService.SearchAsync(featuredProductsQuery); } if (featuredProductsResult != null) { var featuredProductsMappingSettings = _helper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Grid); model.FeaturedProducts = await _helper.MapProductSummaryModelAsync(featuredProductsResult, featuredProductsMappingSettings); } } // Prepare paging/sorting/mode stuff. _helper.MapListActions(model.Products, category, _catalogSettings.DefaultPageSizeOptions); // Template. var templateCacheKey = string.Format(ModelCacheInvalidator.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId); var templateViewPath = await Services.Cache.GetAsync(templateCacheKey, async() => { var template = await _db.CategoryTemplates.FindByIdAsync(category.CategoryTemplateId, false) ?? await _db.CategoryTemplates.FirstOrDefaultAsync(); return(template.ViewPath); }); // Activity log. Services.ActivityLogger.LogActivity("PublicStore.ViewCategory", T("ActivityLog.PublicStore.ViewCategory"), category.Name); Services.DisplayControl.Announce(category); return(View(templateViewPath, 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)); }
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 Picker(EntityPickerModel model, FormCollection form) { try { var languageId = model.LanguageId == 0 ? Services.WorkContext.WorkingLanguage.Id : model.LanguageId; var disableIf = model.DisableIf.SplitSafe(",").Select(x => x.ToLower().Trim()).ToList(); var disableIds = model.DisableIds.SplitSafe(",").Select(x => x.ToInt()).ToList(); var selected = model.Selected.SplitSafe(","); var returnSku = model.ReturnField.IsCaseInsensitiveEqual("sku"); using (var scope = new DbContextScope(Services.DbContext, autoDetectChanges: false, proxyCreation: true, validateOnSave: false, forceNoTracking: true)) { if (model.EntityType.IsCaseInsensitiveEqual("product")) { model.SearchTerm = model.SearchTerm.TrimSafe(); var hasPermission = Services.Permissions.Authorize(StandardPermissionProvider.ManageCatalog); var disableIfNotSimpleProduct = disableIf.Contains("notsimpleproduct"); var disableIfGroupedProduct = disableIf.Contains("groupedproduct"); 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 fields = new List <string> { "name" }; if (_searchSettings.SearchFields.Contains("sku")) { fields.Add("sku"); } if (_searchSettings.SearchFields.Contains("shortdescription")) { fields.Add("shortdescription"); } var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchTerm) .HasStoreId(model.StoreId); if (!hasPermission) { searchQuery = searchQuery.VisibleOnly(Services.WorkContext.CurrentCustomer); } if (model.ProductTypeId > 0) { searchQuery = searchQuery.IsProductType((ProductType)model.ProductTypeId); } if (model.ManufacturerId != 0) { searchQuery = searchQuery.WithManufacturerIds(null, model.ManufacturerId); } if (model.CategoryId != 0) { var node = _categoryService.GetCategoryTree(model.CategoryId, true); if (node != null) { searchQuery = searchQuery.WithCategoryIds(null, node.Flatten(true).Select(x => x.Id).ToArray()); } } var skip = model.PageIndex * model.PageSize; var query = _catalogSearchService.PrepareQuery(searchQuery); var products = query .Select(x => new { x.Id, x.Sku, x.Name, x.Published, x.ProductTypeId, x.MainPictureId }) .OrderBy(x => x.Name) .Skip(() => skip) .Take(() => model.PageSize) .ToList(); var allPictureIds = products.Select(x => x.MainPictureId.GetValueOrDefault()); var allPictureInfos = _pictureService.GetPictureInfos(allPictureIds); model.SearchResult = products .Select(x => { var item = new EntityPickerModel.SearchResultModel { Id = x.Id, Title = x.Name, Summary = x.Sku, SummaryTitle = "{0}: {1}".FormatInvariant(sku, x.Sku.NaIfEmpty()), Published = hasPermission ? x.Published : (bool?)null, ReturnValue = returnSku ? x.Sku : x.Id.ToString() }; item.Selected = selected.Contains(item.ReturnValue); if (disableIfNotSimpleProduct) { item.Disable = x.ProductTypeId != (int)ProductType.SimpleProduct; } else if (disableIfGroupedProduct) { item.Disable = x.ProductTypeId == (int)ProductType.GroupedProduct; } if (!item.Disable && disableIds.Contains(x.Id)) { item.Disable = true; } if (x.ProductTypeId == (int)ProductType.GroupedProduct) { item.LabelText = labelTextGrouped; item.LabelClassName = "badge-success"; } else if (x.ProductTypeId == (int)ProductType.BundledProduct) { item.LabelText = labelTextBundled; item.LabelClassName = "badge-info"; } var pictureInfo = allPictureInfos.Get(x.MainPictureId.GetValueOrDefault()); var fallbackType = _catalogSettings.HideProductDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity; item.ImageUrl = _pictureService.GetUrl( allPictureInfos.Get(x.MainPictureId.GetValueOrDefault()), _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, fallbackType); return(item); }) .ToList(); } else if (model.EntityType.IsCaseInsensitiveEqual("category")) { var categories = _categoryService.GetAllCategories(model.SearchTerm, showHidden: true); var allPictureIds = categories.Select(x => x.PictureId.GetValueOrDefault()); var allPictureInfos = _pictureService.GetPictureInfos(allPictureIds); model.SearchResult = categories .Select(x => { var path = ((ICategoryNode)x).GetCategoryPath(_categoryService, languageId, "({0})"); var item = new EntityPickerModel.SearchResultModel { Id = x.Id, Title = x.Name, Summary = path, SummaryTitle = path, Published = x.Published, ReturnValue = x.Id.ToString(), Selected = selected.Contains(x.Id.ToString()), Disable = disableIds.Contains(x.Id) }; if (x.Alias.HasValue()) { item.LabelText = x.Alias; item.LabelClassName = "badge-secondary"; } var pictureInfo = allPictureInfos.Get(x.PictureId.GetValueOrDefault()); var fallbackType = _catalogSettings.HideProductDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity; item.ImageUrl = _pictureService.GetUrl( allPictureInfos.Get(x.PictureId.GetValueOrDefault()), _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, fallbackType); return(item); }) .ToList(); } else if (model.EntityType.IsCaseInsensitiveEqual("manufacturer")) { var manufacturers = _manufacturerService.GetAllManufacturers(model.SearchTerm, model.PageIndex, model.PageSize, showHidden: true); var allPictureIds = manufacturers.Select(x => x.PictureId.GetValueOrDefault()); var allPictureInfos = _pictureService.GetPictureInfos(allPictureIds); model.SearchResult = manufacturers .Select(x => { var item = new EntityPickerModel.SearchResultModel { Id = x.Id, Title = x.Name, Published = x.Published, ReturnValue = x.Id.ToString(), Selected = selected.Contains(x.Id.ToString()), Disable = disableIds.Contains(x.Id) }; var pictureInfo = allPictureInfos.Get(x.PictureId.GetValueOrDefault()); var fallbackType = _catalogSettings.HideProductDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity; item.ImageUrl = _pictureService.GetUrl( allPictureInfos.Get(x.PictureId.GetValueOrDefault()), _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, fallbackType); return(item); }) .ToList(); } else if (model.EntityType.IsCaseInsensitiveEqual("customer")) { var registeredRoleId = _customerService.GetCustomerRoleBySystemName("Registered").Id; var searchTermName = string.Empty; var searchTermEmail = string.Empty; var searchTermCustomerNumber = string.Empty; if (model.CustomerSearchType.IsCaseInsensitiveEqual("Name")) { searchTermName = model.SearchTerm; } else if (model.CustomerSearchType.IsCaseInsensitiveEqual("Email")) { searchTermEmail = model.SearchTerm; } else if (model.CustomerSearchType.IsCaseInsensitiveEqual("CustomerNumber")) { searchTermCustomerNumber = model.SearchTerm; } var q = new CustomerSearchQuery { SearchTerm = searchTermName, Email = searchTermEmail, CustomerNumber = searchTermCustomerNumber, CustomerRoleIds = new int[] { registeredRoleId }, PageIndex = model.PageIndex, PageSize = model.PageSize }; var customers = _customerService.SearchCustomers(q); model.SearchResult = customers .Select(x => { var fullName = x.GetFullName(); var item = new EntityPickerModel.SearchResultModel { Id = x.Id, ReturnValue = x.Id.ToString(), Title = x.Username.NullEmpty() ?? x.Email, Summary = fullName, SummaryTitle = fullName, Published = true, Selected = selected.Contains(x.Id.ToString()), Disable = disableIds.Contains(x.Id) }; return(item); }) .ToList(); } } } catch (Exception ex) { NotifyError(ex.ToAllMessages()); } return(PartialView("Picker.List", model)); }
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 disableIfGroupedProduct = disableIf.Contains("groupedproduct"); 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 fields = new List <string> { "name" }; if (_searchSettings.Value.SearchFields.Contains("sku")) { fields.Add("sku"); } if (_searchSettings.Value.SearchFields.Contains("shortdescription")) { fields.Add("shortdescription"); } var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchTerm) .HasStoreId(model.StoreId); if (!hasPermission) { searchQuery = searchQuery.VisibleOnly(_services.WorkContext.CurrentCustomer); } if (model.ProductTypeId > 0) { searchQuery = searchQuery.IsProductType((ProductType)model.ProductTypeId); } if (model.ManufacturerId != 0) { searchQuery = searchQuery.WithManufacturerIds(null, model.ManufacturerId); } if (model.CategoryId != 0) { searchQuery = searchQuery.WithCategoryIds(null, model.CategoryId); } var query = _catalogSearchService.Value.PrepareQuery(searchQuery); var products = query .Select(x => new { x.Id, x.Sku, x.Name, x.Published, x.ProductTypeId }) .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); } else if (disableIfGroupedProduct) { item.Disable = (x.ProductTypeId == (int)ProductType.GroupedProduct); } if (!item.Disable && disableIds.Contains(x.Id)) { item.Disable = true; } if (x.ProductTypeId == (int)ProductType.GroupedProduct) { item.LabelText = labelTextGrouped; item.LabelClassName = "badge-success"; } else if (x.ProductTypeId == (int)ProductType.BundledProduct) { item.LabelText = labelTextBundled; item.LabelClassName = "badge-info"; } var productPicture = pictures.FirstOrDefault(y => y.Key == x.Id); if (productPicture.Value != null) { var picture = productPicture.Value.FirstOrDefault(); if (picture != null) { try { item.ImageUrl = _pictureService.Value.GetPictureUrl( picture.Picture, _mediaSettings.Value.ProductThumbPictureSizeOnProductDetailsPage, !_catalogSettings.HideProductDefaultPictures, storeLocation); } catch (Exception exception) { exception.Dump(); } } } return(item); }) .ToList(); #endregion } } } catch (Exception exception) { NotifyError(exception.ToAllMessages()); } return(PartialView("EntityPickerList", model)); }
public async Task <IActionResult> ProductList(GridCommand command, ProductListModel model) { var gridModel = new GridModel <ProductOverviewModel>(); var fields = new List <string> { "name" }; if (_searchSettings.SearchFields.Contains("sku")) { fields.Add("sku"); } if (_searchSettings.SearchFields.Contains("shortdescription")) { fields.Add("shortdescription"); } var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchProductName) .HasStoreId(model.SearchStoreId) .WithCurrency(_workContext.WorkingCurrency) .WithLanguage(_workContext.WorkingLanguage); if (model.SearchIsPublished.HasValue) { searchQuery = searchQuery.PublishedOnly(model.SearchIsPublished.Value); } if (model.SearchHomePageProducts.HasValue) { searchQuery = searchQuery.HomePageProductsOnly(model.SearchHomePageProducts.Value); } if (model.SearchProductTypeId > 0) { searchQuery = searchQuery.IsProductType((ProductType)model.SearchProductTypeId); } if (model.SearchWithoutManufacturers.HasValue) { searchQuery = searchQuery.HasAnyManufacturer(!model.SearchWithoutManufacturers.Value); } else if (model.SearchManufacturerId != 0) { searchQuery = searchQuery.WithManufacturerIds(null, model.SearchManufacturerId); } if (model.SearchWithoutCategories.HasValue) { searchQuery = searchQuery.HasAnyCategory(!model.SearchWithoutCategories.Value); } else if (model.SearchCategoryId != 0) { searchQuery = searchQuery.WithCategoryIds(null, model.SearchCategoryId); } IPagedList <Product> products; if (_searchSettings.UseCatalogSearchInBackend) { searchQuery = searchQuery.Slice((command.Page - 1) * command.PageSize, command.PageSize); var sort = command.Sorting?.FirstOrDefault(); if (sort != null) { switch (sort.Member) { case nameof(ProductModel.Name): searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.NameDesc : ProductSortingEnum.NameAsc); break; case nameof(ProductModel.Price): searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.PriceDesc : ProductSortingEnum.PriceAsc); break; case nameof(ProductModel.CreatedOn): searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.CreatedOn : ProductSortingEnum.CreatedOnAsc); break; } } if (!searchQuery.Sorting.Any()) { searchQuery = searchQuery.SortBy(ProductSortingEnum.NameAsc); } var searchResult = await _catalogSearchService.SearchAsync(searchQuery); products = await searchResult.GetHitsAsync(); } else { var query = _catalogSearchService .PrepareQuery(searchQuery) .ApplyGridCommand(command, false); products = await new PagedList <Product>(query, command.Page - 1, command.PageSize).LoadAsync(); } var fileIds = products.AsEnumerable() .Select(x => x.MainPictureId ?? 0) .Where(x => x != 0) .Distinct() .ToArray(); var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id); gridModel.Rows = products.AsEnumerable().Select(x => { var productModel = new ProductOverviewModel { Sku = x.Sku, Published = x.Published, ProductTypeLabelHint = x.ProductTypeLabelHint, Name = x.Name, Id = x.Id, StockQuantity = x.StockQuantity, Price = x.Price, LimitedToStores = x.LimitedToStores, EditUrl = Url.Action("Edit", "Product", new { id = x.Id }), ManufacturerPartNumber = x.ManufacturerPartNumber, Gtin = x.Gtin, MinStockQuantity = x.MinStockQuantity, OldPrice = x.OldPrice, AvailableStartDateTimeUtc = x.AvailableStartDateTimeUtc, AvailableEndDateTimeUtc = x.AvailableEndDateTimeUtc }; //MiniMapper.Map(x, productModel); files.TryGetValue(x.MainPictureId ?? 0, out var file); // TODO: (core) Use IImageModel productModel.PictureThumbnailUrl = _mediaService.GetUrl(file, _mediaSettings.CartThumbPictureSize); productModel.NoThumb = file == null; productModel.ProductTypeName = x.GetProductTypeLabel(_localizationService); productModel.UpdatedOn = _dateTimeHelper.ConvertToUserTime(x.UpdatedOnUtc, DateTimeKind.Utc); productModel.CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc); return(productModel); }); gridModel.Total = products.TotalCount; return(Json(gridModel)); }
public override void ResolveElementCounts(TreeNode <MenuItem> curNode, bool deep = false) { if (curNode == null || !ContainsProvider("catalog") || !_catalogSettings.Value.ShowCategoryProductNumber) { return; } try { using (Services.Chronometer.Step($"DatabaseMenu.ResolveElementsCount() for {curNode.Value.Text.NaIfEmpty()}")) { // 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)) { var nodes = deep ? curNode.SelectNodes(x => true, false) : curNode.Children.AsEnumerable(); nodes = nodes.Where(x => x.Value.EntityId != 0); foreach (var node in nodes) { var isCategory = node.Value.EntityName.IsCaseInsensitiveEqual(nameof(Category)); var isManufacturer = node.Value.EntityName.IsCaseInsensitiveEqual(nameof(Manufacturer)); if (isCategory || isManufacturer) { var entityIds = new HashSet <int>(); if (isCategory && _catalogSettings.Value.ShowCategoryProductNumberIncludingSubcategories) { // Include sub-categories. node.Traverse(x => { entityIds.Add(x.Value.EntityId); }, true); } else { entityIds.Add(node.Value.EntityId); } var context = new CatalogSearchQuery() .VisibleOnly() .WithVisibility(ProductVisibility.Full) .HasStoreId(Services.StoreContext.CurrentStoreIdIfMultiStoreMode) .BuildFacetMap(false) .BuildHits(false); if (isCategory) { context = context.WithCategoryIds(null, entityIds.ToArray()); } else { context = context.WithManufacturerIds(null, entityIds.ToArray()); } if (!_searchSettings.Value.IncludeNotAvailable) { context = context.AvailableOnly(true); } node.Value.ElementsCount = _catalogSearchService.Value.Search(context).TotalHitsCount; } } } } } curNode = curNode.Parent; } } } catch (Exception ex) { _logger.Error(ex); } }
public async Task <IActionResult> PickerPost(EntityPickerModel model) { try { var form = Request.Form; var disableIf = model.DisableIf.SplitSafe(",").Select(x => x.ToLower().Trim()).ToList(); var disableIds = model.DisableIds.SplitSafe(",").Select(x => x.ToInt()).ToList(); var selected = model.Selected.SplitSafe(","); var returnSku = model.ReturnField.EqualsNoCase("sku"); using var scope = new DbContextScope(Services.DbContext, autoDetectChanges: false, forceNoTracking: true); if (model.EntityType.EqualsNoCase("product")) { model.SearchTerm = model.SearchTerm.TrimSafe(); var hasPermission = await Services.Permissions.AuthorizeAsync(Permissions.Catalog.Product.Read); var disableIfNotSimpleProduct = disableIf.Contains("notsimpleproduct"); var disableIfGroupedProduct = disableIf.Contains("groupedproduct"); var labelTextGrouped = T("Admin.Catalog.Products.ProductType.GroupedProduct.Label").Value; var labelTextBundled = T("Admin.Catalog.Products.ProductType.BundledProduct.Label").Value; var sku = T("Products.Sku"); var fields = new List <string> { "name" }; if (_searchSettings.SearchFields.Contains("sku")) { fields.Add("sku"); } if (_searchSettings.SearchFields.Contains("shortdescription")) { fields.Add("shortdescription"); } var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchTerm) .HasStoreId(model.StoreId); if (!hasPermission) { searchQuery = searchQuery.VisibleOnly(Services.WorkContext.CurrentCustomer); } if (model.ProductTypeId > 0) { searchQuery = searchQuery.IsProductType((ProductType)model.ProductTypeId); } if (model.ManufacturerId != 0) { searchQuery = searchQuery.WithManufacturerIds(null, model.ManufacturerId); } if (model.CategoryId != 0) { var node = await _categoryService.GetCategoryTreeAsync(model.CategoryId, true); if (node != null) { searchQuery = searchQuery.WithCategoryIds(null, node.Flatten(true).Select(x => x.Id).ToArray()); } } List <EntityPickerProduct> products; var skip = model.PageIndex * model.PageSize; if (_searchSettings.UseCatalogSearchInBackend) { searchQuery = searchQuery .Slice(skip, model.PageSize) .SortBy(ProductSortingEnum.NameAsc); var searchResult = await _catalogSearchService.SearchAsync(searchQuery); products = (await searchResult.GetHitsAsync()) .Select(x => new EntityPickerProduct { Id = x.Id, Sku = x.Sku, Name = x.Name, Published = x.Published, ProductTypeId = x.ProductTypeId, MainPictureId = x.MainPictureId }) .ToList(); } else { var query = _catalogSearchService.PrepareQuery(searchQuery).AsNoTracking(); products = await query .Select(x => new EntityPickerProduct { Id = x.Id, Sku = x.Sku, Name = x.Name, Published = x.Published, ProductTypeId = x.ProductTypeId, MainPictureId = x.MainPictureId }) .OrderBy(x => x.Name) .Skip(skip) .Take(model.PageSize) .ToListAsync(); } var fileIds = products .Select(x => x.MainPictureId ?? 0) .Where(x => x != 0) .Distinct() .ToArray(); var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id); model.SearchResult = products .Select(x => { var item = new EntityPickerModel.SearchResultModel { Id = x.Id, Title = x.Name, Summary = x.Sku, SummaryTitle = $"{sku}: {x.Sku.NaIfEmpty()}", Published = hasPermission ? x.Published : null, ReturnValue = returnSku ? x.Sku : x.Id.ToString() }; item.Selected = selected.Contains(item.ReturnValue); if (disableIfNotSimpleProduct) { item.Disable = x.ProductTypeId != (int)ProductType.SimpleProduct; } else if (disableIfGroupedProduct) { item.Disable = x.ProductTypeId == (int)ProductType.GroupedProduct; } if (!item.Disable && disableIds.Contains(x.Id)) { item.Disable = true; } if (x.ProductTypeId == (int)ProductType.GroupedProduct) { item.LabelText = labelTextGrouped; item.LabelClassName = "badge-success"; } else if (x.ProductTypeId == (int)ProductType.BundledProduct) { item.LabelText = labelTextBundled; item.LabelClassName = "badge-info"; } files.TryGetValue(x.MainPictureId ?? 0, out var file); item.ImageUrl = _mediaService.GetUrl(file, _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, null, !_catalogSettings.HideProductDefaultPictures); return(item); }) .ToList(); } else if (model.EntityType.EqualsNoCase("category")) { var categoryQuery = _db.Categories .AsNoTracking() .ApplyStandardFilter(includeHidden: true) .AsQueryable(); if (model.SearchTerm.HasValue()) { categoryQuery = categoryQuery.Where(c => c.Name.Contains(model.SearchTerm) || c.FullName.Contains(model.SearchTerm)); } var categories = await categoryQuery.ToListAsync(); var fileIds = categories .Select(x => x.MediaFileId ?? 0) .Where(x => x != 0) .Distinct() .ToArray(); var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id); model.SearchResult = await categories .SelectAsync(async x => { var path = await _categoryService.GetCategoryPathAsync(x, Services.WorkContext.WorkingLanguage.Id, "({0})"); var item = new EntityPickerModel.SearchResultModel { Id = x.Id, Title = x.Name, Summary = path, SummaryTitle = path, Published = x.Published, ReturnValue = x.Id.ToString(), Selected = selected.Contains(x.Id.ToString()), Disable = disableIds.Contains(x.Id) }; if (x.Alias.HasValue()) { item.LabelText = x.Alias; item.LabelClassName = "badge-secondary"; } files.TryGetValue(x.MediaFileId ?? 0, out var file); item.ImageUrl = _mediaService.GetUrl(file, _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, null, !_catalogSettings.HideProductDefaultPictures); return(item); }).AsyncToList(); } else if (model.EntityType.EqualsNoCase("manufacturer")) { var manufacturerQuery = _db.Manufacturers .AsNoTracking() .ApplyStandardFilter(includeHidden: true) .AsQueryable(); if (model.SearchTerm.HasValue()) { manufacturerQuery = manufacturerQuery.Where(c => c.Name.Contains(model.SearchTerm)); } var manufacturers = await manufacturerQuery .ApplyPaging(model.PageIndex, model.PageSize) .ToListAsync(); var fileIds = manufacturers .Select(x => x.MediaFileId ?? 0) .Where(x => x != 0) .Distinct() .ToArray(); var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id); model.SearchResult = manufacturers .Select(x => { var item = new EntityPickerModel.SearchResultModel { Id = x.Id, Title = x.Name, Published = x.Published, ReturnValue = x.Id.ToString(), Selected = selected.Contains(x.Id.ToString()), Disable = disableIds.Contains(x.Id) }; files.TryGetValue(x.MediaFileId ?? 0, out var file); item.ImageUrl = _mediaService.GetUrl(file, _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, null, !_catalogSettings.HideProductDefaultPictures); return(item); }) .ToList(); } else if (model.EntityType.EqualsNoCase("customer")) { var registeredRole = await _db.CustomerRoles .AsNoTracking() .FirstOrDefaultAsync(x => x.SystemName == SystemCustomerRoleNames.Registered); var registeredRoleId = registeredRole.Id; var customerQuery = _db.Customers .AsNoTracking() .AsQueryable(); if (model.SearchTerm.HasValue()) { if (model.CustomerSearchType.EqualsNoCase("Name")) { customerQuery = customerQuery.ApplySearchTermFilter(model.SearchTerm); } else if (model.CustomerSearchType.EqualsNoCase("Email")) { customerQuery = customerQuery.ApplyIdentFilter(email: model.SearchTerm, userName: model.SearchTerm); } else if (model.CustomerSearchType.EqualsNoCase("CustomerNumber")) { customerQuery = customerQuery.ApplyIdentFilter(customerNumber: model.SearchTerm); } } var customers = await customerQuery .ApplyRolesFilter(new[] { registeredRoleId }) .ApplyPaging(model.PageIndex, model.PageSize) .ToListAsync(); model.SearchResult = customers .Select(x => { var fullName = x.GetFullName(); var item = new EntityPickerModel.SearchResultModel { Id = x.Id, ReturnValue = x.Id.ToString(), Title = x.Username.NullEmpty() ?? x.Email, Summary = fullName, SummaryTitle = fullName, Published = true, Selected = selected.Contains(x.Id.ToString()), Disable = disableIds.Contains(x.Id) }; return(item); }) .ToList(); } } catch (Exception ex) { NotifyError(ex.ToAllMessages()); } return(PartialView("Picker.List", model)); }