protected virtual void ConvertManufacturer(CatalogSearchQuery query, RouteData routeData, string origin)
        {
            //List<int> ids = null;
            //int? minHitCount = null;

            //GetValueFor(query, "m", FacetGroupKind.Brand, out ids);

            //// Preselect manufacturer on manufacturer page.... and then?
            //if (origin.IsCaseInsensitiveEqual("Catalog/Manufacturer"))
            //{
            //	minHitCount = 0;

            //	var manufacturerId = routeData.Values["manufacturerid"].ToString().ToInt();
            //	if (manufacturerId != 0)
            //	{
            //		if (ids == null)
            //			ids = new List<int> { manufacturerId };
            //		else if (!ids.Contains(manufacturerId))
            //			ids.Add(manufacturerId);
            //	}
            //}

            if (origin.IsCaseInsensitiveEqual("Catalog/Manufacturer"))
            {
                // we don't need brand facetting in brand pages
                return;
            }

            List <int> ids;

            if (GetValueFor(query, "m", FacetGroupKind.Brand, out ids) && ids != null && ids.Any())
            {
                query.WithManufacturerIds(null, ids.ToArray());
            }

            AddFacet(query, FacetGroupKind.Brand, true, FacetSorting.LabelAsc, descriptor =>
            {
                if (ids != null)
                {
                    foreach (var id in ids)
                    {
                        descriptor.AddValue(new FacetValue(id, IndexTypeCode.Int32)
                        {
                            IsSelected = true
                        });
                    }
                }
            });
        }
Пример #2
0
        public async Task <IActionResult> Manufacturer(int manufacturerId, CatalogSearchQuery query)
        {
            var manufacturer = await _db.Manufacturers.FindByIdAsync(manufacturerId, false);

            if (manufacturer == null || manufacturer.Deleted)
            {
                return(NotFound());
            }

            // Check whether the current user has a "Manage catalog" permission.
            // It allows him to preview a manufacturer before publishing.
            if (!manufacturer.Published && !await Services.Permissions.AuthorizeAsync(Permissions.Catalog.Manufacturer.Read))
            {
                return(NotFound());
            }

            // ACL (access control list).
            if (!await _aclService.AuthorizeAsync(manufacturer))
            {
                return(NotFound());
            }

            // Store mapping.
            if (!await _storeMappingService.AuthorizeAsync(manufacturer))
            {
                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.PrepareBrandModelAsync(manufacturer);

            if (_seoSettings.CanonicalUrlsEnabled)
            {
                model.CanonicalUrl = _urlHelper.Value.RouteUrl("Manufacturer", new { model.SeName }, Request.Scheme);
            }

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

            model.Image = await _helper.PrepareBrandImageModelAsync(manufacturer, model.Name);

            // Featured products.
            var hideFeaturedProducts = _catalogSettings.IgnoreFeaturedProducts || (query.IsSubPage && !_catalogSettings.IncludeFeaturedProductsInSubPages);

            if (!hideFeaturedProducts)
            {
                CatalogSearchResult featuredProductsResult = null;

                var cacheKey = ModelCacheInvalidator.MANUFACTURER_HAS_FEATURED_PRODUCTS_KEY.FormatInvariant(manufacturerId, string.Join(",", customer.GetRoleIds()), storeId);
                var hasFeaturedProductsCache = await Services.Cache.GetAsync <bool?>(cacheKey);

                var featuredProductsQuery = new CatalogSearchQuery()
                                            .VisibleOnly(customer)
                                            .WithVisibility(ProductVisibility.Full)
                                            .WithManufacturerIds(true, manufacturerId)
                                            .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)
                {
                    // TODO: (mc) determine settings properly
                    var featuredProductsmappingSettings = _helper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Grid);
                    model.FeaturedProducts = await _helper.MapProductSummaryModelAsync(featuredProductsResult, featuredProductsmappingSettings);
                }
            }

            // Products
            query.WithManufacturerIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : false, manufacturerId);

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

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

            // Template.
            var templateCacheKey = string.Format(ModelCacheInvalidator.MANUFACTURER_TEMPLATE_MODEL_KEY, manufacturer.ManufacturerTemplateId);
            var templateViewPath = await Services.Cache.GetAsync(templateCacheKey, async() =>
            {
                var template = await _db.ManufacturerTemplates.FindByIdAsync(manufacturer.ManufacturerTemplateId, false)
                               ?? await _db.ManufacturerTemplates.FirstOrDefaultAsync();

                return(template.ViewPath);
            });

            // Activity log.
            Services.ActivityLogger.LogActivity("PublicStore.ViewManufacturer", T("ActivityLog.PublicStore.ViewManufacturer"), manufacturer.Name);

            Services.DisplayControl.Announce(manufacturer);

            return(View(templateViewPath, model));
        }
        public ActionResult Manufacturer(int manufacturerId, CatalogSearchQuery query)
        {
            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(Permissions.Catalog.Manufacturer.Read))
            {
                return(HttpNotFound());
            }

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

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

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

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

            var model = manufacturer.ToModel();

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

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

            // Featured products.
            var hideFeaturedProducts = _catalogSettings.IgnoreFeaturedProducts || (query.IsSubPage && !_catalogSettings.IncludeFeaturedProductsInSubPages);

            if (!hideFeaturedProducts)
            {
                CatalogSearchResult featuredProductsResult = null;

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

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

                var featuredProductsQuery = new CatalogSearchQuery()
                                            .VisibleOnly(customer)
                                            .WithVisibility(ProductVisibility.Full)
                                            .WithManufacturerIds(true, manufacturerId)
                                            .HasStoreId(store.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)
                {
                    // TODO: (mc) determine settings properly
                    var featuredProductsmappingSettings = _helper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Grid);
                    model.FeaturedProducts = _helper.MapProductSummaryModel(featuredProductsResult.Hits, featuredProductsmappingSettings);
                }
            }

            // Products
            query.WithManufacturerIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, manufacturerId);

            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, manufacturer, _catalogSettings.DefaultPageSizeOptions);

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

            Services.DisplayControl.Announce(manufacturer);

            return(View(templateViewPath, model));
        }
Пример #4
0
        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));
        }
Пример #5
0
        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));
        }
Пример #6
0
        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));
        }
Пример #7
0
        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);
            }
        }
Пример #8
0
        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));
        }