Ejemplo n.º 1
0
        public async Task <IActionResult> SearchAsync([Required] string q, int pageIndex = 0, int pageSize = 10)
        {
            // Check to make sure that paging parameters make sense...

            var errors = ValidatePaging(pageIndex, pageSize).ToList();

            // Check to make sure search criteria was provided...

            if (string.IsNullOrEmpty(q))
            {
                errors.Add($"[q] is required.");
            }

            // If there were any validation errors, respond with [400 Bad Request] + detailed error description...

            if (errors.Any())
            {
                return(BadRequest(string.Join(' ', errors)));
            }

            var searchRequest = new CatalogSearchRequest
            {
                PageIndex  = pageIndex,
                PageLength = pageSize,
                Query      = q
            };

            // Run the search...

            var searchResults = await catalogSearchService.SearchAsync(searchRequest);

            // Always respond with [200 OK] even if there aren't any results...

            return(Ok(ToDetailApiModel(searchResults)));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> InstantSearch(CatalogSearchQuery query)
        {
            if (!query.Term.HasValue() || query.Term.Length < _searchSettings.InstantSearchTermMinLength)
            {
                return(Content(string.Empty));
            }

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

            var result = await _catalogSearchService.SearchAsync(query);

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

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

            // TODO: (mh) (core) What about scoped services?
            //using (_localizedEntityService.BeginScope(false))
            //{
            var hits = await result.GetHitsAsync();

            // InstantSearch should be REALLY very fast! No time for smart caching stuff.
            if (result.TotalHitsCount > 0)
            {
                await _localizedEntityService.PrefetchLocalizedPropertiesAsync(
                    nameof(Product),
                    Services.WorkContext.WorkingLanguage.Id,
                    hits.Select(x => x.Id).ToArray());
            }

            // Add product hits.
            model.TopProducts = await _catalogHelper.MapProductSummaryModelAsync(hits, mappingSettings);

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

            return(PartialView(model));
        }
Ejemplo n.º 3
0
        private async Task EnsureAssociatedProductsAreLoaded(Product product, CalculatorContext context)
        {
            var options = context.Options;

            if (context.AssociatedProducts == null)
            {
                // Associated products have not been preloaded unfortunately. Get 'em here for this particular product.
                var searchQuery = new CatalogSearchQuery()
                                  .PublishedOnly(true)
                                  .HasStoreId(options.Store.Id)
                                  .HasParentGroupedProduct(product.Id);

                var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

                context.AssociatedProducts = (await searchResult.GetHitsAsync()).OrderBy(x => x.DisplayOrder).ToList();
            }

            if (options.ChildProductsBatchContext == null && context.AssociatedProducts.Any())
            {
                // No batch context given for the listing batch, so create one for associated products of this particular product.
                options.ChildProductsBatchContext = _productService.CreateProductBatchContext(context.AssociatedProducts, options.Store, options.Customer, false);
            }

            // Continue pipeline with AssociatedProductsBatchContext
            options.BatchContext = options.ChildProductsBatchContext;
        }
Ejemplo n.º 4
0
        public async Task <CatalogSearchResult> SearchAsync(SearchFilterExpression[] filters, int pageIndex = 0, int pageSize = int.MaxValue)
        {
            var searchQuery = new CatalogSearchQuery()
                              .OriginatesFrom("Rule/Search")
                              .WithLanguage(_services.WorkContext.WorkingLanguage)
                              .WithCurrency(_services.WorkContext.WorkingCurrency)
                              .BuildFacetMap(false)
                              .CheckSpelling(0)
                              .Slice(pageIndex * pageSize, pageSize)
                              .SortBy(ProductSortingEnum.CreatedOn);

            if ((filters?.Length ?? 0) == 0)
            {
                return(new CatalogSearchResult(searchQuery));
            }

            SearchFilterExpressionGroup group;

            if (filters.Length == 1 && filters[0] is SearchFilterExpressionGroup group2)
            {
                group = group2;
            }
            else
            {
                group = new SearchFilterExpressionGroup();
                group.AddExpressions(filters);
            }

            searchQuery = group.ApplyFilters(searchQuery);

            var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

            return(searchResult);
        }
Ejemplo n.º 5
0
        public async Task <ActionResult> ProductDetails(string productId)
        {
            var product = await _productService.GetProductAsync(productId, Model.Catalog.ItemResponseGroup.ItemInfo | Model.Catalog.ItemResponseGroup.ItemWithPrices);

            WorkContext.CurrentProduct = product;

            WorkContext.CurrentCatalogSearchCriteria.CategoryId = product.CategoryId;
            WorkContext.CurrentCatalogSearchResult = await _searchService.SearchAsync(WorkContext.CurrentCatalogSearchCriteria);

            return(View("product", WorkContext));
        }
Ejemplo n.º 6
0
        public async Task <ActionResult> ProductDetails(string productId)
        {
            var product = (await _catalogSearchService.GetProductsAsync(new[] { productId }, Model.Catalog.ItemResponseGroup.ItemSmall | Model.Catalog.ItemResponseGroup.ItemWithPrices)).FirstOrDefault();

            WorkContext.CurrentProduct = product;

            WorkContext.CurrentCatalogSearchCriteria.CategoryId = product.CategoryId;
            WorkContext.CurrentCatalogSearchResult = await _catalogSearchService.SearchAsync(WorkContext.CurrentCatalogSearchCriteria);

            return(View("product", WorkContext));
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> Index()
        {
            //Load categories for main page (may be removed if it not necessary)
            var catalogSearchCriteria = new CatalogSearchCriteria
            {
                CatalogId     = _workContext.CurrentStore.Catalog,
                ResponseGroup = CatalogSearchResponseGroup.WithCategories
            };

            _workContext.CurrentCatalogSearchResult = await _catalogSearchService.SearchAsync(catalogSearchCriteria);

            return(View("index", _workContext));
        }
Ejemplo n.º 8
0
        public virtual async Task <int> CountComparedProductsAsync()
        {
            var productIds = GetComparedProductsIds();

            if (productIds.Any())
            {
                var searchQuery = new CatalogSearchQuery()
                                  .VisibleOnly()
                                  .WithProductIds(productIds.ToArray())
                                  .BuildHits(false);

                var result = await _catalogSearchService.SearchAsync(searchQuery);

                return(result.TotalHitsCount);
            }

            return(0);
        }
Ejemplo n.º 9
0
        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));
        }
        /// GET search
        /// This method used for search products by given criteria
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> SearchProducts()
        {
            WorkContext.CurrentCatalogSearchResult = await _searchService.SearchAsync(WorkContext.CurrentCatalogSearchCriteria);

            return(View("collection", WorkContext));
        }
        private async Task <List <RuleValueSelectListOption> > SearchProducts(RuleOptionsResult result, string term, int skip, int take)
        {
            List <RuleValueSelectListOption> products;
            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(), term);

            if (_searchSettings.UseCatalogSearchInBackend)
            {
                searchQuery = searchQuery
                              .Slice(skip, take)
                              .SortBy(ProductSortingEnum.NameAsc);

                var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

                var hits = await searchResult.GetHitsAsync();

                result.HasMoreData = hits.HasNextPage;

                products = hits
                           .AsQueryable()
                           .Select(x => new RuleValueSelectListOption
                {
                    Value = x.Id.ToString(),
                    Text  = x.Name,
                    Hint  = x.Sku
                })
                           .ToList();
            }
            else
            {
                var query = _catalogSearchService.PrepareQuery(searchQuery);

                var pageIndex = take == 0 ? 0 : Math.Max(skip / take, 0);
                result.HasMoreData = (pageIndex + 1) * take < query.Count();

                products = await query
                           .Select(x => new RuleValueSelectListOption
                {
                    Value = x.Id.ToString(),
                    Text  = x.Name,
                    Hint  = x.Sku
                })
                           .OrderBy(x => x.Text)
                           .Skip(skip)
                           .Take(take)
                           .ToListAsync();
            }

            return(products);
        }
Ejemplo n.º 12
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));
        }
Ejemplo n.º 13
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));
        }
Ejemplo n.º 14
0
        public async Task <ActionResult> SearchProducts(CatalogSearchCriteria searchCriteria)
        {
            var retVal = await _catalogSearchService.SearchAsync(searchCriteria);

            return(Json(retVal));
        }