/// <summary>
        /// Deletes a search term record
        /// </summary>
        /// <param name="searchTerm">Search term</param>
        public virtual void DeleteSearchTerm(SearchTerm searchTerm)
        {
            if (searchTerm == null)
                throw new ArgumentNullException("searchTerm");

            _searchTermRepository.Delete(searchTerm);

            //event notification
            _eventPublisher.EntityDeleted(searchTerm);
        }
        public void Can_save_and_load_searchTerm()
        {
            var searchTerm = new SearchTerm
            {
                Keyword = "Keyword 1",
                StoreId = 1,
                Count = 2,
            };

            var fromDb = SaveAndLoadEntity(searchTerm);
            fromDb.ShouldNotBeNull();

            fromDb.Keyword.ShouldEqual("Keyword 1");
            fromDb.StoreId.ShouldEqual(1);
            fromDb.Count.ShouldEqual(2);
        }
Esempio n. 3
0
        public ActionResult Search(SearchModel model, CatalogPagingFilteringModel command)
        {
            //'Continue shopping' URL
            _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                SystemCustomerAttributeNames.LastContinueShoppingPage,
                _webHelper.GetThisPageUrl(false),
                _storeContext.CurrentStore.Id);

            if (model == null)
                model = new SearchModel();

            if (model.Q == null)
                model.Q = "";
            model.Q = model.Q.Trim();



            //sorting
            PrepareSortingOptions(model.PagingFilteringContext, command);
            //view mode
            PrepareViewModes(model.PagingFilteringContext, command);
            //page size
            PreparePageSizeOptions(model.PagingFilteringContext, command,
                _catalogSettings.SearchPageAllowCustomersToSelectPageSize,
                _catalogSettings.SearchPagePageSizeOptions,
                _catalogSettings.SearchPageProductsPerPage);


            var customerRolesIds = _workContext.CurrentCustomer.CustomerRoles
                .Where(cr => cr.Active).Select(cr => cr.Id).ToList();
            string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY, _workContext.WorkingLanguage.Id, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id); 
            var categories = _cacheManager.Get(cacheKey, () =>
            {
                var categoriesModel = new List<SearchModel.CategoryModel>();
                //all categories
                foreach (var c in _categoryService.GetAllCategories())
                {
                    //generate full category name (breadcrumb)
                    string categoryBreadcrumb= "";
                    var breadcrumb = c.GetCategoryBreadCrumb(_categoryService, _aclService, _storeMappingService);
                    for (int i = 0; i <= breadcrumb.Count - 1; i++)
                    {
                        categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
                        if (i != breadcrumb.Count - 1)
                            categoryBreadcrumb += " >> ";
                    }
                    categoriesModel.Add(new SearchModel.CategoryModel()
                    {
                        Id = c.Id,
                        Breadcrumb = categoryBreadcrumb
                    });
                }
                return categoriesModel;
            });
            if (categories.Count > 0)
            {
                //first empty entry
                model.AvailableCategories.Add(new SelectListItem()
                    {
                         Value = "0",
                         Text = _localizationService.GetResource("Common.All")
                    });
                //all other categories
                foreach (var c in categories)
                {
                    model.AvailableCategories.Add(new SelectListItem()
                    {
                        Value = c.Id.ToString(),
                        Text = c.Breadcrumb,
                        Selected = model.Cid == c.Id
                    });
                }
            }

            var manufacturers = _manufacturerService.GetAllManufacturers();
            if (manufacturers.Count > 0)
            {
                model.AvailableManufacturers.Add(new SelectListItem()
                {
                    Value = "0",
                    Text = _localizationService.GetResource("Common.All")
                });
                foreach (var m in manufacturers)
                    model.AvailableManufacturers.Add(new SelectListItem()
                    {
                        Value = m.Id.ToString(),
                        Text = m.GetLocalized(x => x.Name),
                        Selected = model.Mid == m.Id
                    });
            }

            IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
            // only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
            if (Request.Params["Q"] != null)
            {
                if (model.Q.Length < _catalogSettings.ProductSearchTermMinimumLength)
                {
                    model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
                }
                else
                {
                    var categoryIds = new List<int>();
                    int manufacturerId = 0;
                    decimal? minPriceConverted = null;
                    decimal? maxPriceConverted = null;
                    bool searchInDescriptions = false;
                    if (model.As)
                    {
                        //advanced search
                        var categoryId = model.Cid;
                        if (categoryId > 0)
                        {
                            categoryIds.Add(categoryId);
                            if (model.Isc)
                            {
                                //include subcategories
                                categoryIds.AddRange(GetChildCategoryIds(categoryId));
                            }
                        }


                        manufacturerId = model.Mid;

                        //min price
                        if (!string.IsNullOrEmpty(model.Pf))
                        {
                            decimal minPrice = decimal.Zero;
                            if (decimal.TryParse(model.Pf, out minPrice))
                                minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
                        }
                        //max price
                        if (!string.IsNullOrEmpty(model.Pt))
                        {
                            decimal maxPrice = decimal.Zero;
                            if (decimal.TryParse(model.Pt, out maxPrice))
                                maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
                        }

                        searchInDescriptions = model.Sid;
                    }
                    
                    //var searchInProductTags = false;
                    var searchInProductTags = searchInDescriptions;

                    //products
                    products = _productService.SearchProducts(
                        categoryIds: categoryIds,
                        manufacturerId: manufacturerId,
                        storeId: _storeContext.CurrentStore.Id,
                        visibleIndividuallyOnly: true,
                        priceMin: minPriceConverted,
                        priceMax: maxPriceConverted,
                        keywords:model.Q,
                        searchDescriptions: searchInDescriptions,
                        searchSku: searchInDescriptions,
                        searchProductTags: searchInProductTags,
                        languageId: _workContext.WorkingLanguage.Id,
                        orderBy: (ProductSortingEnum)command.OrderBy,
                        pageIndex: command.PageNumber - 1,
                        pageSize: command.PageSize);
                    model.Products = PrepareProductOverviewModels(products).ToList();

                    model.NoResults = !model.Products.Any();

                    //search term statistics
                    if (!String.IsNullOrEmpty(model.Q))
                    {
                        var searchTerm = _searchTermService.GetSearchTermByKeyword(model.Q, _storeContext.CurrentStore.Id);
                        if (searchTerm != null)
                        {
                            searchTerm.Count++;
                            _searchTermService.UpdateSearchTerm(searchTerm);
                        }
                        else
                        {
                            searchTerm = new SearchTerm()
                            {
                                Keyword = model.Q,
                                StoreId = _storeContext.CurrentStore.Id,
                                Count = 1
                            };
                            _searchTermService.InsertSearchTerm(searchTerm);
                        }
                    }

                    //event
                    _eventPublisher.Publish(new ProductSearchEvent()
                    {
                        SearchTerm = model.Q,
                        SearchInDescriptions = searchInDescriptions,
                        CategoryIds = categoryIds,
                        ManufacturerId = manufacturerId,
                        WorkingLanguageId = _workContext.WorkingLanguage.Id
                    });
                }
            }

            model.PagingFilteringContext.LoadPagedList(products);
            return View(model);
        }
        public ActionResult Search(AUSearchModel model, CatalogPagingFilteringModel command)
        {
            //'Continue shopping' URL
            _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                SystemCustomerAttributeNames.LastContinueShoppingPage,
                _webHelper.GetThisPageUrl(false),
                _storeContext.CurrentStore.Id);

            if (model == null)
            {
                model = new AUSearchModel();
            }

            var searchTerms = model.q;
            if (searchTerms == null)
                searchTerms = "";
            searchTerms = searchTerms.Trim();

             

            //sorting
            PrepareSortingOptions(model.PagingFilteringContext, command);
            //view mode
            PrepareViewModes(model.PagingFilteringContext, command);
            //page size
            PreparePageSizeOptions(model.PagingFilteringContext, command,
                _catalogSettings.SearchPageAllowCustomersToSelectPageSize,
                _catalogSettings.SearchPagePageSizeOptions,
                _catalogSettings.SearchPageProductsPerPage);

            //TODO: only show searchable categories that have an actual lot?
            string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY,
                _workContext.WorkingLanguage.Id,
                string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
                _storeContext.CurrentStore.Id);
             var categories = _cacheManager.Get(cacheKey, () =>
            {
                var categoriesModel = new List<SearchModel.CategoryModel>();
                //all categories
                var allCategories = _categoryService.GetAllCategories();
                foreach (var c in allCategories)
                {
                    //generate full category name (breadcrumb)
                    string categoryBreadcrumb = "";
                    var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService);
                    for (int i = 0; i <= breadcrumb.Count - 1; i++)
                    {
                        categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
                        if (i != breadcrumb.Count - 1)
                            categoryBreadcrumb += " >> ";
                    }
                    categoriesModel.Add(new SearchModel.CategoryModel
                    {
                        Id = c.Id,
                        Breadcrumb = categoryBreadcrumb
                    });
                }
                return categoriesModel;
            });
            if (categories.Count > 0)
            {
                //first empty entry
                model.AvailableCategories.Add(new SelectListItem
                {
                    Value = "0",
                    Text = _localizationService.GetResource("Common.All")
                });
                //all other categories
                foreach (var c in categories)
                {
                    model.AvailableCategories.Add(new SelectListItem
                    {
                        Value = c.Id.ToString(),
                        Text = c.Breadcrumb,
                        Selected = model.cid == c.Id
                    });
                }
            }


 
            //Load up Countries dropdown only with countries assigned to lots
            string countryCacheKey = string.Format(AUConsignorCacheEventConsumer.ACTIVE_COUNTRY_NAVIGATION_PATTERN_KEY,
               _workContext.WorkingLanguage.Id,
               string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
               _storeContext.CurrentStore.Id);

            var countries = _cacheManager.Get(countryCacheKey, () =>
                {
                    var lotcountries = _consignorService.GetLotCountries();
                    return lotcountries;
                }
                );

            model.AvailableCountries.Add(new SelectListItem
            {
                Value = "0",
                Text = _localizationService.GetResource("Common.All")
            });
            //all other categories
            foreach (var co in countries)
            {
                model.AvailableCountries.Add(new SelectListItem
                {
                    Value = co.Id.ToString(),
                    Text = co.Name,
                    Selected = model.countryid == co.Id   //??
                });
            }

           
            //TODO: NEED TO CACHE THIS WITH THE COUNTRY ID
            //Load up Countries dropdown only with countries assigned to lots
            string stateprovinceCacheKey = string.Format(AUConsignorCacheEventConsumer.ACTIVE_STATEPROVINCES_BY_COUNTRY_MODEL_KEY,
               model.stateprovinceid,
               model.stateprovinceid,
                _workContext.WorkingLanguage.Id);

            var states = _cacheManager.Get(stateprovinceCacheKey, () =>
                {
                    var lotstates = model.countryid != 0 ? _consignorService.GetLotStateProvincesByCountryId(model.countryid, true).ToList() : new List<StateProvince>();
                    return lotstates;
                }
            );

           
            if (states.Count > 0)
            {
                model.AvailableStateProvinces.Add(new SelectListItem { Text = "All", Value = "0", Selected = (0 == model.stateprovinceid) });

                foreach (var s in states)
                {
                    model.AvailableStateProvinces.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString(), Selected = (s.Id == model.stateprovinceid) });
                }
            }
            else
                model.AvailableStateProvinces.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0" });



            //TODO: only show manufactureres in retail or mixed mode stores
            ////var manufacturers = _manufacturerService.GetAllManufacturers();
            ////if (manufacturers.Count > 0)
            ////{
            ////    model.AvailableManufacturers.Add(new SelectListItem
            ////    {
            ////        Value = "0",
            ////        Text = _localizationService.GetResource("Common.All")
            ////    });
            ////    foreach (var m in manufacturers)
            ////        model.AvailableManufacturers.Add(new SelectListItem
            ////        {
            ////            Value = m.Id.ToString(),
            ////            Text = m.GetLocalized(x => x.Name),
            ////            Selected = model.mid == m.Id
            ////        });
            ////}

            IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
            // only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
            //NJM: had to add && Request.Params["q"] != "" because Serge's null check was not working
            if ((Request.Params["q"] != null && Request.Params["q"] != "") || ((Request.Params["q"] == null || Request.Params["q"] == "") && model.adv && (model.cid > 0 || model.countryid > 0 || model.SoldUnsold > 0 || !string.IsNullOrEmpty(model.pf) || !string.IsNullOrEmpty(model.pt))))
            {
                if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength )
                {
                    model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
                }
                else
                {
                    var categoryIds = new List<int>();
                    int manufacturerId = 0;
                    decimal? minPriceConverted = null;
                    decimal? maxPriceConverted = null;
                    bool searchInDescriptions = false;
                    if (model.adv)
                    {
                        //advanced search
                        var categoryId = model.cid;
                        if (categoryId > 0)
                        {
                            categoryIds.Add(categoryId);
                            if (model.isc)
                            {
                                //include subcategories
                                categoryIds.AddRange(GetChildCategoryIds(categoryId));
                            }
                        }


                        manufacturerId = model.mid;

                        //min price
                        if (!string.IsNullOrEmpty(model.pf))
                        {
                            decimal minPrice;
                            if (decimal.TryParse(model.pf, out minPrice))
                                minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
                        }
                        //max price
                        if (!string.IsNullOrEmpty(model.pt))
                        {
                            decimal maxPrice;
                            if (decimal.TryParse(model.pt, out maxPrice))
                                maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
                        }

                        searchInDescriptions = model.sid;
                    }

                    //var searchInProductTags = false;
                    var searchInProductTags = searchInDescriptions;

                    //products
                    ////products = _productService.SearchProducts(
                    ////    categoryIds: categoryIds,
                    ////    manufacturerId: manufacturerId,
                    ////    storeId: _storeContext.CurrentStore.Id,
                    ////    visibleIndividuallyOnly: true,
                    ////    priceMin: minPriceConverted,
                    ////    priceMax: maxPriceConverted,
                    ////    keywords: searchTerms,
                    ////    searchDescriptions: searchInDescriptions,
                    ////    searchSku: searchInDescriptions,
                    ////    searchProductTags: searchInProductTags,
                    ////    languageId: _workContext.WorkingLanguage.Id,
                    ////    orderBy: (ProductSortingEnum)command.OrderBy,
                    ////    pageIndex: command.PageNumber - 1,
                    ////    pageSize: command.PageSize);

                    IList<int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_webHelper);
                    IList<int> filterableSpecificationAttributeOptionIds;

                   
                    var lots = _consignorService.GetAllLots2(
                        out filterableSpecificationAttributeOptionIds,
                        true,
                        //pageIndex: command.PageNumber - 1,
                        //pageSize: command.PageSize,
                        categoryIds: categoryIds,
                        //manufacturerId: manufacturerId,
                        //saleId: saleId,
                        storeId: _storeContext.CurrentStore.Id,
                        visibleIndividuallyOnly: true,
                        //featuredProducts: _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false,
                        priceMin: minPriceConverted,
                        priceMax: maxPriceConverted,
                        soldUnsold: model.SoldUnsold,
                        countryId: model.countryid,
                        stateProvinceId: model.stateprovinceid,
                        keywords: searchTerms,
                        searchDescriptions: searchInDescriptions,
                        searchSku: searchInDescriptions,
                        searchProductTags: searchInProductTags,
                        languageId: _workContext.WorkingLanguage.Id,
                        filteredSpecs: alreadyFilteredSpecOptionIds,
                        orderBy: (AUProductSortingEnum)command.OrderBy,
                        showHidden: false,
                        overridePublished: true
                        ).Select(x => x.ToProduct()).ToList();  //NJM: Important! Notice embedded "ToProduct mapping to get from AUCombLotProc to Product

                    int totalRecords = lots.Count;
                    int pageIndex = command.PageNumber - 1;
                    int pageSize = command.PageSize;

                    //NJM: need to cast lots List to IPagedList so can be used in  model.PagingFilteringContext.LoadPagedList(products); You
                    //can take this shit out when you go straight to IPagedList(AUCombLotProc) and take out ToProduct above
                    products = new PagedList<Product>(lots, pageIndex, pageSize, totalRecords);

                   
                    //products = lots.Select(x => x.ToProduct()).ToList());

                        //).Select(x => x.ToProduct().ToList()); //NJM: Important! Notice embedded "ToProduct mapping to get from AUCombLotProc to Product
                                          //  ).Select(x => x.ToProduct()).ToList(); //NJM: Important! Notice embedded "ToProduct mapping to get from AUCombLotProc to Product

                    //this is where you need to change to insert the bidding info


                    //Original: model.Products = PrepareProductOverviewModels(products).ToList();
                    //NJM: third true indicates to create specification model (default was false)
                    model.Products = PrepareProductOverviewModels(products, true, true, null, true, false).ToList();
                    model.PagingFilteringContext.SpecificationFilter.Enabled = true;    //NJM force this to allow spec filtering in search results

                    model.PagingFilteringContext.LoadPagedList(products);
                    //model.PagingFilteringContext.LoadPagedList(products);


                    //NJM: add specsto search results
                    model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds,
                        filterableSpecificationAttributeOptionIds,
                        _specificationAttributeService, _webHelper, _workContext);



                    model.NoResults = !model.Products.Any();

                    //search term statistics
                    if (!String.IsNullOrEmpty(searchTerms))
                    {
                        var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id);
                        if (searchTerm != null)
                        {
                            searchTerm.Count++;
                            _searchTermService.UpdateSearchTerm(searchTerm);
                        }
                        else
                        {
                            searchTerm = new SearchTerm
                            {
                                Keyword = searchTerms,
                                StoreId = _storeContext.CurrentStore.Id,
                                Count = 1
                            };
                            _searchTermService.InsertSearchTerm(searchTerm);
                        }
                    }

                    //event
                    _eventPublisher.Publish(new ProductSearchEvent
                    {
                        SearchTerm = searchTerms,
                        SearchInDescriptions = searchInDescriptions,
                        CategoryIds = categoryIds,
                        ManufacturerId = manufacturerId,
                        WorkingLanguageId = _workContext.WorkingLanguage.Id
                    });
                }
            }
            else
            {
               // model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
                model.Warning = "You must enter at least one search criteria";
            }


            return View(model);
        }