Beispiel #1
0
        public virtual FilterProductContext CreateFilterProductContext(string filter, int categoryID, string path, int?pagesize, int?orderby, string viewmode)
        {
            var context = new FilterProductContext()
            {
                Filter           = filter,
                ParentCategoryID = categoryID,
                CategoryIds      = new List <int> {
                    categoryID
                },
                Path     = path,
                PageSize = pagesize ?? 12,
                ViewMode = viewmode,
                OrderBy  = orderby,
                Criteria = Deserialize(filter)
            };

            if (_catalogSettings.ShowProductsFromSubcategories)
            {
                context.CategoryIds.AddRange(
                    _categoryService.GetAllCategoriesByParentCategoryId(categoryID).Select(x => x.Id)
                    );
            }

            return(context);
        }
        public ActionResult Products(string active, string inactive, int categoryID, int? pagesize, int? orderby, string viewmode)
        {
            // TODO: needed later for ajax based filtering... see example below
            //System.Threading.Thread.Sleep(3000);

            var context = new FilterProductContext
            {
                ParentCategoryID = categoryID,
                CategoryIds = new List<int> { categoryID },
                Criteria = _filterService.Deserialize(active),
                OrderBy = orderby,
            };

            context.Criteria.AddRange(_filterService.Deserialize(inactive));

            //var query = _filterService.ProductFilter(context);
            //var products = new PagedList<Product>(query, 0, pagesize ?? 4);

            //ProductListModel model = new ProductListModel {
            //	PagingFilteringContext = new CatalogPagingFilteringModel()
            //};

            //model.Products = PrepareProductOverviewModels(products).ToList();
            //model.PagingFilteringContext.LoadPagedList(products);

            //string htmlProducts = this.RenderPartialViewToString("~/Views/Catalog/_ProductBoxContainer.cshtml", model);

            //return Json(new {
            //	products = htmlProducts
            //});

            return null;
        }
        public virtual FilterProductContext CreateFilterProductContext(string filter, int categoryID, string path, int? pagesize, int? orderby, string viewmode)
        {
            var context = new FilterProductContext
            {
                Filter = filter,
                ParentCategoryID = categoryID,
                CategoryIds = new List<int> { categoryID },
                Path = path,
                PageSize = pagesize ?? 12,
                ViewMode = viewmode,
                OrderBy = orderby,
                Criteria = Deserialize(filter)
            };

            if (_catalogSettings.ShowProductsFromSubcategories)
            {
                context.CategoryIds.AddRange(
                    _categoryService.GetAllCategoriesByParentCategoryId(categoryID).Select(x => x.Id)
                );
            }

            int languageId = _services.WorkContext.WorkingLanguage.Id;

            foreach (var criteria in context.Criteria.Where(x => x.Entity.IsCaseInsensitiveEqual(ShortcutSpecAttribute)))
            {
                if (criteria.PId.HasValue)
                    criteria.NameLocalized = _localizedEntityService.GetLocalizedValue(languageId, criteria.PId.Value, "SpecificationAttribute", "Name");

                if (criteria.ID.HasValue)
                    criteria.ValueLocalized = _localizedEntityService.GetLocalizedValue(languageId, criteria.ID.Value, "SpecificationAttributeOption", "Name");
            }

            return context;
        }
 public static bool IsActive(this FilterProductContext context, FilterCriteria criteria)
 {
     if (criteria != null && context.Criteria != null)
     {
         return(context.Criteria.FirstOrDefault(c => c.Entity == criteria.Entity && c.Name == criteria.Name && c.Value == criteria.Value && !c.IsInactive) != null);
     }
     return(false);
 }
        public static bool IsActive(this FilterProductContext context, FilterCriteria criteria)
        {
            if (criteria != null && context.Criteria != null)
            {
                var foundCriteria = context.Criteria.FirstOrDefault(c => !c.IsInactive &&
                                                                    c.Entity.IsCaseInsensitiveEqual(criteria.Entity) && c.Name.IsCaseInsensitiveEqual(criteria.Name) && c.Value.IsCaseInsensitiveEqual(criteria.Value));

                return(foundCriteria != null);
            }
            return(false);
        }
Beispiel #6
0
        private List <FilterCriteria> ProductFilterableSpecAttributes(FilterProductContext context, string attributeName = null)
        {
            var query = ProductFilter(context);

            var attributes =
                from p in query
                from sa in p.ProductSpecificationAttributes
                where sa.AllowFiltering
                orderby sa.DisplayOrder
                select sa.SpecificationAttributeOption;

            if (attributeName.HasValue())
            {
                attributes = attributes.Where(a => a.SpecificationAttribute.Name == attributeName);
            }

            var grouped =
                from a in attributes
                group a by new { a.SpecificationAttributeId, a.Id } into g
                select new FilterCriteria
            {
                Name       = g.FirstOrDefault().SpecificationAttribute.Name,
                Value      = g.FirstOrDefault().Name,
                ID         = g.Key.Id,
                ParentId   = g.FirstOrDefault().SpecificationAttribute.Id,
                MatchCount = g.Count()
            };


            var lst        = grouped.OrderByDescending(a => a.MatchCount).ToList();
            int languageId = _commonServices.WorkContext.WorkingLanguage.Id;

            lst.ForEach(c =>
            {
                c.Entity     = ShortcutSpecAttribute;
                c.IsInactive = true;

                if (c.ParentId != 0)
                {
                    c.NameLocalized = _localizedEntityService.GetLocalizedValue(languageId, c.ParentId, "SpecificationAttribute", "Name");
                }

                if (c.ID.HasValue)
                {
                    c.ValueLocalized = _localizedEntityService.GetLocalizedValue(languageId, c.ID.Value, "SpecificationAttributeOption", "Name");
                }
            });

            return(lst);
        }
Beispiel #7
0
        public virtual void ProductFilterable(FilterProductContext context)
        {
            if (context.Criteria.FirstOrDefault(c => c.Entity == FilterService.ShortcutPrice) == null)
            {
                context.Criteria.AddRange(ProductFilterablePrices(context));
            }

            if (context.Criteria.FirstOrDefault(c => c.Name == "Name" && c.Entity == "Manufacturer") == null)
            {
                context.Criteria.AddRange(ProductFilterableManufacturer(context));
            }

            context.Criteria.AddRange(ProductFilterableSpecAttributes(context));
        }
Beispiel #8
0
        public virtual void ProductFilterable(FilterProductContext context)
        {
            if (context.Criteria.FirstOrDefault(c => c.Entity.IsCaseInsensitiveEqual(FilterService.ShortcutPrice)) == null)
            {
                context.Criteria.AddRange(ProductFilterablePrices(context));
            }

            if (context.Criteria.FirstOrDefault(c => c.Name.IsCaseInsensitiveEqual("Name") && c.Entity.IsCaseInsensitiveEqual("Manufacturer")) == null)
            {
                context.Criteria.AddRange(ProductFilterableManufacturer(context));
            }

            context.Criteria.AddRange(ProductFilterableSpecAttributes(context));
        }
Beispiel #9
0
        private List <FilterCriteria> ProductFilterableManufacturer(FilterProductContext context, bool getAll = false)
        {
            var query = ProductFilter(context);

            var manus =
                from p in query
                from pm in p.ProductManufacturers
                where !pm.Manufacturer.Deleted
                select pm.Manufacturer;

            var grouped =
                from m in manus
                group m by m.Id into grp
                orderby grp.Key
                select new FilterCriteria
            {
                MatchCount   = grp.Count(),
                Value        = grp.FirstOrDefault().Name,
                DisplayOrder = grp.FirstOrDefault().DisplayOrder
            };

            if (_catalogSettings.SortFilterResultsByMatches)
            {
                grouped = grouped.OrderByDescending(m => m.MatchCount);
            }
            else
            {
                grouped = grouped.OrderBy(m => m.DisplayOrder);
            }

            if (!getAll)
            {
                grouped = grouped.Take(_catalogSettings.MaxFilterItemsToDisplay);
            }

            var lst = grouped.ToList();

            lst.ForEach(c =>
            {
                c.Name       = "Name";
                c.Entity     = "Manufacturer";
                c.IsInactive = true;
            });

            return(lst);
        }
Beispiel #10
0
        private List <FilterCriteria> ProductFilterablePrices(FilterProductContext context)
        {
            var            result = new List <FilterCriteria>();
            FilterCriteria criteria;
            Category       category;

            var tmp = new FilterProductContext
            {
                ParentCategoryID = context.ParentCategoryID,
                CategoryIds      = context.CategoryIds,
                Criteria         = new List <FilterCriteria>()
            };

            if (context.ParentCategoryID != 0 && (category = _categoryService.GetCategoryById(context.ParentCategoryID)) != null && category.PriceRanges.HasValue())
            {
                string[] ranges = category.PriceRanges.SplitSafe(";");

                foreach (string range in ranges)
                {
                    if ((criteria = range.ParsePriceString()) != null)
                    {
                        tmp.Criteria.Clear();
                        tmp.Criteria.AddRange(context.Criteria);
                        tmp.Criteria.Add(criteria);

                        try
                        {
                            criteria.MatchCount = ProductFilter(tmp).Count();
                        }
                        catch (Exception exc)
                        {
                            exc.Dump();
                        }

                        if (criteria.MatchCount > 0)
                        {
                            result.Add(criteria);
                        }
                    }
                }
            }

            result.ForEach(c => c.IsInactive = true);
            return(result);
        }
		public ActionResult Products(string filter, int categoryID, string path, int? pagesize, int? orderby, string viewmode)
		{
			var context = new FilterProductContext()
			{
				Filter = filter,
				ParentCategoryID = categoryID,
				CategoryIds = new List<int> { categoryID },
				Path = path,
				PageSize = pagesize ?? 12,
				ViewMode = viewmode,
				OrderBy = orderby,
				Criteria = _filterService.Deserialize(filter)
			};
		
			_filterService.ProductFilterable(context);

			return PartialView(new ProductFilterModel { Context = context });
		}
        public static string GetUrl(this FilterProductContext context, FilterCriteria criteriaAdd = null, FilterCriteria criteriaRemove = null)
        {
            string url = "{0}?pagesize={1}&viewmode={2}".FormatWith(context.Path, context.PageSize, context.ViewMode);

            if (context.OrderBy.HasValue)
            {
                url = "{0}&orderby={1}".FormatWith(url, context.OrderBy.Value);
            }

            try
            {
                if (criteriaAdd != null || criteriaRemove != null)
                {
                    var criterias = new List <FilterCriteria>();

                    if (context.Criteria != null && context.Criteria.Count > 0)
                    {
                        criterias.AddRange(context.Criteria.Where(c => !c.IsInactive));
                    }

                    if (criteriaAdd != null)
                    {
                        criterias.Add(criteriaAdd);
                    }
                    else
                    {
                        criterias.RemoveAll(c => c.Entity == criteriaRemove.Entity && c.Name == criteriaRemove.Name && c.Value == criteriaRemove.Value);
                    }

                    if (criterias.Count > 0)
                    {
                        url = "{0}&filter={1}".FormatWith(url, HttpUtility.UrlEncode(JsonConvert.SerializeObject(criterias)));
                    }
                }
            }
            catch (Exception exc)
            {
                exc.Dump();
            }

            return(url);
        }
Beispiel #13
0
        public virtual FilterProductContext CreateFilterProductContext(string filter, int categoryID, string path, int?pagesize, int?orderby, string viewmode)
        {
            var context = new FilterProductContext
            {
                Filter           = filter,
                ParentCategoryID = categoryID,
                CategoryIds      = new List <int> {
                    categoryID
                },
                Path     = path,
                PageSize = pagesize ?? 12,
                ViewMode = viewmode,
                OrderBy  = orderby,
                Criteria = Deserialize(filter)
            };

            if (_catalogSettings.ShowProductsFromSubcategories)
            {
                context.CategoryIds.AddRange(
                    _categoryService.GetAllCategoriesByParentCategoryId(categoryID).Select(x => x.Id)
                    );
            }

            int languageId = _services.WorkContext.WorkingLanguage.Id;

            foreach (var criteria in context.Criteria.Where(x => x.Entity.IsCaseInsensitiveEqual(ShortcutSpecAttribute)))
            {
                if (criteria.PId.HasValue)
                {
                    criteria.NameLocalized = _localizedEntityService.GetLocalizedValue(languageId, criteria.PId.Value, "SpecificationAttribute", "Name");
                }

                if (criteria.ID.HasValue)
                {
                    criteria.ValueLocalized = _localizedEntityService.GetLocalizedValue(languageId, criteria.ID.Value, "SpecificationAttributeOption", "Name");
                }
            }

            return(context);
        }
Beispiel #14
0
        private List <FilterCriteria> ProductFilterableManufacturer(FilterProductContext context, bool getAll = false)
        {
            bool includeFeatured = IncludeFeatured;
            var  query           = ProductFilter(context);

            var manus =
                from p in query
                from pm in p.ProductManufacturers
                where pm.IsFeaturedProduct == includeFeatured && !pm.Manufacturer.Deleted
                select pm.Manufacturer;

            var grouped =
                from m in manus
                orderby m.DisplayOrder
                group m by m.Id into grp
                orderby grp.Key
                select new FilterCriteria
            {
                MatchCount = grp.Count(),
                Value      = grp.FirstOrDefault().Name
            };

            grouped = grouped.OrderByDescending(m => m.MatchCount);

            if (!getAll)
            {
                grouped = grouped.Take(MaxDisplayCriteria);
            }

            var lst = grouped.ToList();

            lst.ForEach(c =>
            {
                c.Name       = "Name";
                c.Entity     = "Manufacturer";
                c.IsInactive = true;
            });

            return(lst);
        }
Beispiel #15
0
        private List <FilterCriteria> ProductFilterableSpecAttributes(FilterProductContext context, string attributeName = null)
        {
            var query = ProductFilter(context);

            var attributes =
                from p in query
                from sa in p.ProductSpecificationAttributes
                where sa.AllowFiltering && sa.ShowOnProductPage
                orderby sa.DisplayOrder
                select sa.SpecificationAttributeOption;

            if (attributeName.HasValue())
            {
                attributes = attributes.Where(a => a.SpecificationAttribute.Name == attributeName);
            }

            var grouped =
                from a in attributes
                group a by new { a.SpecificationAttributeId, a.Id } into g
                select new FilterCriteria
            {
                Name       = g.FirstOrDefault().SpecificationAttribute.Name,
                Value      = g.FirstOrDefault().Name,
                ID         = g.Key.Id,
                MatchCount = g.Count()
            };


            var lst = grouped.OrderByDescending(a => a.MatchCount).ToList();

            lst.ForEach(c =>
            {
                c.Entity     = ShortcutSpecAttribute;
                c.IsInactive = true;
            });

            return(lst);
        }
Beispiel #16
0
        public virtual FilterProductContext CreateFilterProductContext(string filter, int categoryID, string path, int? pagesize, int? orderby, string viewmode)
        {
            var context = new FilterProductContext()
            {
                Filter = filter,
                ParentCategoryID = categoryID,
                CategoryIds = new List<int> { categoryID },
                Path = path,
                PageSize = pagesize ?? 12,
                ViewMode = viewmode,
                OrderBy = orderby,
                Criteria = Deserialize(filter)
            };

            if (_catalogSettings.ShowProductsFromSubcategories)
            {
                context.CategoryIds.AddRange(
                    _categoryService.GetAllCategoriesByParentCategoryId(categoryID).Select(x => x.Id)
                );
            }

            return context;
        }
Beispiel #17
0
        public virtual void ProductFilterableMultiSelect(FilterProductContext context, string filterMultiSelect)
        {
            var criteriaMultiSelect        = Deserialize(filterMultiSelect).FirstOrDefault();
            List <FilterCriteria> inactive = null;

            if (criteriaMultiSelect != null)
            {
                context.Criteria.RemoveAll(c => c.Name == criteriaMultiSelect.Name && c.Entity == criteriaMultiSelect.Entity);

                if (criteriaMultiSelect.Name == "Name" && criteriaMultiSelect.Entity == "Manufacturer")
                {
                    inactive = ProductFilterableManufacturer(context, true);
                }
                else if (criteriaMultiSelect.Entity == FilterService.ShortcutPrice)
                {
                    inactive = ProductFilterablePrices(context);
                }
                else if (criteriaMultiSelect.Entity == FilterService.ShortcutSpecAttribute)
                {
                    inactive = ProductFilterableSpecAttributes(context, criteriaMultiSelect.Name);
                }
            }

            // filters WITHOUT the multiple selectable filters
            string excludedFilter = Serialize(context.Criteria);

            // filters WITH the multiple selectable filters (required for highlighting selected values)
            context.Criteria = Deserialize(context.Filter);

            context.Filter = excludedFilter;

            if (inactive != null)
            {
                inactive.ForEach(c => c.IsInactive = true);
                context.Criteria.AddRange(inactive);
            }
        }
Beispiel #18
0
        private List<FilterCriteria> ProductFilterableManufacturer(FilterProductContext context, bool getAll = false)
        {
            var query = ProductFilter(context);

            var manus =
                from p in query
                from pm in p.ProductManufacturers
                where !pm.Manufacturer.Deleted
                select pm.Manufacturer;

            var grouped =
                from m in manus
                orderby m.DisplayOrder
                group m by m.Id into grp
                orderby grp.Key
                select new FilterCriteria
                {
                    MatchCount = grp.Count(),
                    Value = grp.FirstOrDefault().Name
                };

            grouped = grouped.OrderByDescending(m => m.MatchCount);

            if (!getAll)
                grouped = grouped.Take(_catalogSettings.MaxFilterItemsToDisplay);

            var lst = grouped.ToList();

            lst.ForEach(c =>
            {
                c.Name = "Name";
                c.Entity = "Manufacturer";
                c.IsInactive = true;
            });

            return lst;
        }
Beispiel #19
0
        public virtual void ProductFilterableMultiSelect(FilterProductContext context, string filterMultiSelect)
        {
            var criteriaMultiSelect = Deserialize(filterMultiSelect).FirstOrDefault();
            List<FilterCriteria> inactive = null;

            if (criteriaMultiSelect != null)
            {
                context.Criteria.RemoveAll(c => c.Name == criteriaMultiSelect.Name && c.Entity == criteriaMultiSelect.Entity);

                if (criteriaMultiSelect.Name == "Name" && criteriaMultiSelect.Entity == "Manufacturer")
                    inactive = ProductFilterableManufacturer(context, true);
                else if (criteriaMultiSelect.Entity == FilterService.ShortcutPrice)
                    inactive = ProductFilterablePrices(context);
                else if (criteriaMultiSelect.Entity == FilterService.ShortcutSpecAttribute)
                    inactive = ProductFilterableSpecAttributes(context, criteriaMultiSelect.Name);
            }

            // filters WITHOUT the multiple selectable filters
            string excludedFilter = Serialize(context.Criteria);

            // filters WITH the multiple selectable filters (required for highlighting selected values)
            context.Criteria = Deserialize(context.Filter);

            context.Filter = excludedFilter;

            if (inactive != null)
            {
                inactive.ForEach(c => c.IsInactive = true);
                context.Criteria.AddRange(inactive);
            }
        }
Beispiel #20
0
        public virtual void ProductFilterable(FilterProductContext context)
        {
            if (context.Criteria.FirstOrDefault(c => c.Entity == FilterService.ShortcutPrice) == null)
                context.Criteria.AddRange(ProductFilterablePrices(context));

            if (context.Criteria.FirstOrDefault(c => c.Name == "Name" && c.Entity == "Manufacturer") == null)
                context.Criteria.AddRange(ProductFilterableManufacturer(context));

            context.Criteria.AddRange(ProductFilterableSpecAttributes(context));
        }
Beispiel #21
0
        public virtual IQueryable<Product> ProductFilter(FilterProductContext context)
        {
            var sql = new FilterSql();
            var query = AllProducts(context.CategoryIds);

            // prices
            if (ToWhereClause(sql, context.Criteria, c => !c.IsInactive && c.Entity == ShortcutPrice))
            {
                query = query.Where(sql.WhereClause.ToString(), sql.Values.ToArray());
            }

            // manufacturer
            if (ToWhereClause(sql, context.Criteria, c => !c.IsInactive && c.Entity == "Manufacturer"))
            {
                var pmq =
                    from p in query
                    from pm in p.ProductManufacturers
                    where !pm.Manufacturer.Deleted
                    select pm;

                query = pmq
                    .Where(sql.WhereClause.ToString(), sql.Values.ToArray())
                    .Select(pm => pm.Product);
            }

            // specification attribute
            if (ToWhereClause(sql, context.Criteria, c => !c.IsInactive && (c.Entity == "SpecificationAttributeOption" || c.Entity == ShortcutSpecAttribute)))
            {
                //var saq = (
                //	from p in query
                //	from sa in p.ProductSpecificationAttributes
                //	select sa).Where(a => a.AllowFiltering).Where(sql.WhereClause.ToString(), sql.Values.ToArray());

                //query = saq.Select(sa => sa.Product);

                int countSameNameAttributes = sql.Criteria
                    .Where(c => c.Entity == ShortcutSpecAttribute)
                    .GroupBy(c => c.Name)
                    .Count();

                var specRepository = EngineContext.Current.Resolve<IRepository<ProductSpecificationAttribute>>();

                var saq = specRepository.TableUntracked
                    .Where(a => a.AllowFiltering)
                    .Where(sql.WhereClause.ToString(), sql.Values.ToArray())
                    .GroupBy(a => a.ProductId)
                    .Where(grp => (grp.Count() >= countSameNameAttributes));

                query =
                    from p in query
                    join sa in saq on p.Id equals sa.Key
                    select p;
            }

            // sort
            var order = (ProductSortingEnum)(context.OrderBy ?? 0);
            switch (order)
            {
                case ProductSortingEnum.NameDesc:
                    query = query.OrderByDescending(p => p.Name);
                    break;
                case ProductSortingEnum.PriceAsc:
                    query = query.OrderBy(p => p.Price);
                    break;
                case ProductSortingEnum.PriceDesc:
                    query = query.OrderByDescending(p => p.Price);
                    break;
                case ProductSortingEnum.CreatedOn:
                    query = query.OrderByDescending(p => p.CreatedOnUtc);
                    break;
                case ProductSortingEnum.CreatedOnAsc:
                    query = query.OrderBy(p => p.CreatedOnUtc);
                    break;
                default:
                    query = query.OrderBy(p => p.Name);
                    break;
            }

            // distinct cause same products can be mapped to sub-categories... too slow
            //query =
            //	from p in query
            //	group p by p.Id into grp
            //	orderby grp.Key
            //	select grp.FirstOrDefault();

            //query.ToString().Dump();
            return query;
        }
        public virtual void ProductFilterable(FilterProductContext context)
        {
            if (context.Criteria.FirstOrDefault(c => c.Entity.IsCaseInsensitiveEqual(FilterService.ShortcutPrice)) == null)
                context.Criteria.AddRange(ProductFilterablePrices(context));

            if (context.Criteria.FirstOrDefault(c => c.Name.IsCaseInsensitiveEqual("Name") && c.Entity.IsCaseInsensitiveEqual("Manufacturer")) == null)
                context.Criteria.AddRange(ProductFilterableManufacturer(context));

            context.Criteria.AddRange(ProductFilterableSpecAttributes(context));
        }
        private List<FilterCriteria> ProductFilterableSpecAttributes(FilterProductContext context, string attributeName = null)
        {
            List<FilterCriteria> criterias = null;
            var languageId = _services.WorkContext.WorkingLanguage.Id;
            var query = ProductFilter(context);

            var attributes =
                from p in query
                from sa in p.ProductSpecificationAttributes
                where sa.AllowFiltering
                select sa.SpecificationAttributeOption;

            if (attributeName.HasValue())
            {
                attributes = attributes.Where(a => a.SpecificationAttribute.Name == attributeName);
            }

            var grouped =
                from a in attributes
                group a by new { a.SpecificationAttributeId, a.Id } into g
                select new FilterCriteria
                {
                    Name = g.FirstOrDefault().SpecificationAttribute.Name,
                    Value = g.FirstOrDefault().Name,
                    ID = g.Key.Id,
                    PId = g.FirstOrDefault().SpecificationAttribute.Id,
                    MatchCount = g.Count(),
                    DisplayOrder = g.FirstOrDefault().SpecificationAttribute.DisplayOrder,
                    DisplayOrderValues = g.FirstOrDefault().DisplayOrder
                };

            if (_catalogSettings.SortFilterResultsByMatches)
            {
                criterias = grouped
                    .OrderBy(a => a.DisplayOrder)
                    .ThenByDescending(a => a.MatchCount)
                    .ThenBy(a => a.DisplayOrderValues)
                    .ToList();
            }
            else
            {
                criterias = grouped
                    .OrderBy(a => a.DisplayOrder)
                    .ThenBy(a => a.DisplayOrderValues)
                    .ToList();
            }

            criterias.ForEach(c =>
            {
                c.Entity = ShortcutSpecAttribute;
                c.IsInactive = true;

                if (c.PId.HasValue)
                    c.NameLocalized = _localizedEntityService.GetLocalizedValue(languageId, c.PId.Value, "SpecificationAttribute", "Name");

                if (c.ID.HasValue)
                    c.ValueLocalized = _localizedEntityService.GetLocalizedValue(languageId, c.ID.Value, "SpecificationAttributeOption", "Name");
            });

            return criterias;
        }
Beispiel #24
0
        private List <FilterCriteria> ProductFilterableSpecAttributes(FilterProductContext context, string attributeName = null)
        {
            List <FilterCriteria> criterias = null;
            var languageId = _services.WorkContext.WorkingLanguage.Id;
            var query      = ProductFilter(context);

            var attributes =
                from p in query
                from sa in p.ProductSpecificationAttributes
                where sa.AllowFiltering
                select sa.SpecificationAttributeOption;

            if (attributeName.HasValue())
            {
                attributes = attributes.Where(a => a.SpecificationAttribute.Name == attributeName);
            }

            var grouped =
                from a in attributes
                group a by new { a.SpecificationAttributeId, a.Id } into g
                select new FilterCriteria
            {
                Name               = g.FirstOrDefault().SpecificationAttribute.Name,
                Value              = g.FirstOrDefault().Name,
                ID                 = g.Key.Id,
                PId                = g.FirstOrDefault().SpecificationAttribute.Id,
                MatchCount         = g.Count(),
                DisplayOrder       = g.FirstOrDefault().SpecificationAttribute.DisplayOrder,
                DisplayOrderValues = g.FirstOrDefault().DisplayOrder
            };

            if (_catalogSettings.SortFilterResultsByMatches)
            {
                criterias = grouped
                            .OrderBy(a => a.DisplayOrder)
                            .ThenByDescending(a => a.MatchCount)
                            .ThenBy(a => a.DisplayOrderValues)
                            .ToList();
            }
            else
            {
                criterias = grouped
                            .OrderBy(a => a.DisplayOrder)
                            .ThenBy(a => a.DisplayOrderValues)
                            .ToList();
            }

            criterias.ForEach(c =>
            {
                c.Entity     = ShortcutSpecAttribute;
                c.IsInactive = true;

                if (c.PId.HasValue)
                {
                    c.NameLocalized = _localizedEntityService.GetLocalizedValue(languageId, c.PId.Value, "SpecificationAttribute", "Name");
                }

                if (c.ID.HasValue)
                {
                    c.ValueLocalized = _localizedEntityService.GetLocalizedValue(languageId, c.ID.Value, "SpecificationAttributeOption", "Name");
                }
            });

            return(criterias);
        }
Beispiel #25
0
        private List<FilterCriteria> ProductFilterablePrices(FilterProductContext context)
        {
            var result = new List<FilterCriteria>();
            FilterCriteria criteria;
            Category category;

            var tmp = new FilterProductContext
            {
                ParentCategoryID = context.ParentCategoryID,
                CategoryIds = context.CategoryIds,
                Criteria = new List<FilterCriteria>()
            };

            if (context.ParentCategoryID != 0 && (category = _categoryService.GetCategoryById(context.ParentCategoryID)) != null && category.PriceRanges.HasValue())
            {
                string[] ranges = category.PriceRanges.SplitSafe(";");

                foreach (string range in ranges)
                {
                    if ((criteria = range.ParsePriceString()) != null)
                    {
                        tmp.Criteria.Clear();
                        tmp.Criteria.AddRange(context.Criteria);
                        tmp.Criteria.Add(criteria);

                        try
                        {
                            criteria.MatchCount = ProductFilter(tmp).Count();
                        }
                        catch (Exception exc)
                        {
                            exc.Dump();
                        }

                        if (criteria.MatchCount > 0)
                            result.Add(criteria);
                    }
                }
            }

            result.ForEach(c => c.IsInactive = true);
            return result;
        }
Beispiel #26
0
        public virtual IQueryable <Product> ProductFilter(FilterProductContext context)
        {
            var nowUtc = DateTime.UtcNow;
            var sql    = new FilterSql();
            var query  = AllProducts(context.CategoryIds);

            // manufacturer
            if (ToWhereClause(sql, context.Criteria, c => !c.IsInactive && c.Entity == "Manufacturer"))
            {
                bool includeFeatured = IncludeFeatured;

                var pmq = (
                    from p in query
                    from pm in p.ProductManufacturers
                    where (!includeFeatured || includeFeatured == pm.IsFeaturedProduct) && !pm.Manufacturer.Deleted
                    select pm).Where(sql.WhereClause.ToString(), sql.Values.ToArray());

                query = pmq.Select(pm => pm.Product);
            }

            // specification attribute
            if (ToWhereClause(sql, context.Criteria, c => !c.IsInactive && (c.Entity == "SpecificationAttributeOption" || c.Entity == ShortcutSpecAttribute)))
            {
                //var saq = (
                //	from p in query
                //	from sa in p.ProductSpecificationAttributes
                //	select sa).Where(a => a.AllowFiltering).Where(sql.WhereClause.ToString(), sql.Values.ToArray());

                //query = saq.Select(sa => sa.Product);

                int countSameNameAttributes = sql.Criteria
                                              .Where(c => c.Entity == ShortcutSpecAttribute)
                                              .GroupBy(c => c.Name)
                                              .Count();

                var specRepository = EngineContext.Current.Resolve <IRepository <ProductSpecificationAttribute> >();

                var saq = specRepository.Table
                          .Where(a => a.AllowFiltering && a.ShowOnProductPage)
                          .Where(sql.WhereClause.ToString(), sql.Values.ToArray())
                          .GroupBy(a => a.ProductId)
                          .Where(grp => (grp.Count() >= countSameNameAttributes));

                query =
                    from p in query
                    join sa in saq on p.Id equals sa.Key
                    select p;
            }

            // sort
            var order = (ProductSortingEnum)(context.OrderBy ?? 0);

            switch (order)
            {
            case ProductSortingEnum.NameDesc:
                query = query.OrderByDescending(p => p.Name);
                break;

            case ProductSortingEnum.PriceAsc:
                query = query.OrderBy(p => p.Price);
                break;

            case ProductSortingEnum.PriceDesc:
                query = query.OrderByDescending(p => p.Price);
                break;

            case ProductSortingEnum.CreatedOn:
                query = query.OrderByDescending(p => p.CreatedOnUtc);
                break;

            case ProductSortingEnum.CreatedOnAsc:
                query = query.OrderBy(p => p.CreatedOnUtc);
                break;

            default:
                query = query.OrderBy(p => p.Name);
                break;
            }


            // distinct (required?)
            //query =
            //	from p in query
            //	group p by p.Id into grp
            //	orderby grp.Key
            //	select grp.FirstOrDefault();

            //query.ToString().Dump();
            return(query);
        }
Beispiel #27
0
        private List<FilterCriteria> ProductFilterableSpecAttributes(FilterProductContext context, string attributeName = null)
        {
            var query = ProductFilter(context);

            var attributes =
                from p in query
                from sa in p.ProductSpecificationAttributes
                where sa.AllowFiltering
                orderby sa.DisplayOrder
                select sa.SpecificationAttributeOption;

            if (attributeName.HasValue())
                attributes = attributes.Where(a => a.SpecificationAttribute.Name == attributeName);

            var grouped =
                from a in attributes
                group a by new { a.SpecificationAttributeId, a.Id } into g
                select new FilterCriteria
                {
                    Name = g.FirstOrDefault().SpecificationAttribute.Name,
                    Value = g.FirstOrDefault().Name,
                    ID = g.Key.Id,
                    ParentId = g.FirstOrDefault().SpecificationAttribute.Id,
                    MatchCount = g.Count()
                };

            var lst = grouped.OrderByDescending(a => a.MatchCount).ToList();
            int languageId = _services.WorkContext.WorkingLanguage.Id;

            lst.ForEach(c =>
            {
                c.Entity = ShortcutSpecAttribute;
                c.IsInactive = true;

                if (c.ParentId != 0)
                    c.NameLocalized = _localizedEntityService.GetLocalizedValue(languageId, c.ParentId, "SpecificationAttribute", "Name");

                if (c.ID.HasValue)
                    c.ValueLocalized = _localizedEntityService.GetLocalizedValue(languageId, c.ID.Value, "SpecificationAttributeOption", "Name");
            });

            return lst;
        }
Beispiel #28
0
        public virtual IQueryable <Product> ProductFilter(FilterProductContext context)
        {
            var sql   = new FilterSql();
            var query = AllProducts(context.CategoryIds);

            // prices
            if (ToWhereClause(sql, context.Criteria, c => !c.IsInactive && c.Entity.IsCaseInsensitiveEqual(ShortcutPrice)))
            {
                query = query.Where(sql.WhereClause.ToString(), sql.Values.ToArray());
            }

            // manufacturer
            if (ToWhereClause(sql, context.Criteria, c => !c.IsInactive && c.Entity.IsCaseInsensitiveEqual("Manufacturer")))
            {
                var pmq =
                    from p in query
                    from pm in p.ProductManufacturers
                    where !pm.Manufacturer.Deleted
                    select pm;

                query = pmq
                        .Where(sql.WhereClause.ToString(), sql.Values.ToArray())
                        .Select(pm => pm.Product);
            }

            // specification attribute
            if (ToWhereClause(sql, context.Criteria, c => !c.IsInactive && (c.Entity.IsCaseInsensitiveEqual("SpecificationAttributeOption") || c.Entity.IsCaseInsensitiveEqual(ShortcutSpecAttribute))))
            {
                //var saq = (
                //	from p in query
                //	from sa in p.ProductSpecificationAttributes
                //	select sa).Where(a => a.AllowFiltering).Where(sql.WhereClause.ToString(), sql.Values.ToArray());

                //query = saq.Select(sa => sa.Product);

                int countSameNameAttributes = sql.Criteria
                                              .Where(c => c.Entity.IsCaseInsensitiveEqual(ShortcutSpecAttribute))
                                              .GroupBy(c => c.Name)
                                              .Count();

                var specRepository = EngineContext.Current.Resolve <IRepository <ProductSpecificationAttribute> >();

                var saq = specRepository.TableUntracked
                          .Where(a => a.AllowFiltering)
                          .Where(sql.WhereClause.ToString(), sql.Values.ToArray())
                          .GroupBy(a => a.ProductId)
                          .Where(grp => (grp.Count() >= countSameNameAttributes));

                query =
                    from p in query
                    join sa in saq on p.Id equals sa.Key
                    select p;
            }

            // sort
            var order = (ProductSortingEnum)(context.OrderBy ?? 0);

            switch (order)
            {
            case ProductSortingEnum.NameDesc:
                query = query.OrderByDescending(p => p.Name);
                break;

            case ProductSortingEnum.PriceAsc:
                query = query.OrderBy(p => p.Price);
                break;

            case ProductSortingEnum.PriceDesc:
                query = query.OrderByDescending(p => p.Price);
                break;

            case ProductSortingEnum.CreatedOn:
                query = query.OrderByDescending(p => p.CreatedOnUtc);
                break;

            case ProductSortingEnum.CreatedOnAsc:
                query = query.OrderBy(p => p.CreatedOnUtc);
                break;

            default:
                query = query.OrderBy(p => p.Name);
                break;
            }

            // distinct cause same products can be mapped to sub-categories... too slow
            //query =
            //	from p in query
            //	group p by p.Id into grp
            //	orderby grp.Key
            //	select grp.FirstOrDefault();

            //query.ToString().Dump();
            return(query);
        }
        public ActionResult Category(int categoryId, CatalogPagingFilteringModel command, string filter)
        {
            var category = _categoryService.GetCategoryById(categoryId);
            if (category == null || category.Deleted)
                return HttpNotFound();

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

            //ACL (access control list)
            if (!_aclService.Authorize(category))
                return HttpNotFound();

            //Store mapping
            if (!_storeMappingService.Authorize(category))
                return HttpNotFound();

            //'Continue shopping' URL
            _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentCustomer,
                SystemCustomerAttributeNames.LastContinueShoppingPage,
                _services.WebHelper.GetThisPageUrl(false),
                _services.StoreContext.CurrentStore.Id);

            if (command.PageNumber <= 0)
                command.PageNumber = 1;

            if (command.ViewMode.IsEmpty() && category.DefaultViewMode.HasValue())
            {
                command.ViewMode = category.DefaultViewMode;
            }

            if (command.OrderBy == (int)ProductSortingEnum.Initial)
            {
                command.OrderBy = (int)_catalogSettings.DefaultSortOrder;
            }

            var model = category.ToModel();

            _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
            {
                AllowCustomersToSelectPageSize = category.AllowCustomersToSelectPageSize,
                PageSize = category.PageSize,
                PageSizeOptions = category.PageSizeOptions
            });

            //price ranges
            model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(category.PriceRanges, _services.WebHelper, _priceFormatter);
            var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_services.WebHelper, category.PriceRanges);
            decimal? minPriceConverted = null;
            decimal? maxPriceConverted = null;

            if (selectedPriceRange != null)
            {
                if (selectedPriceRange.From.HasValue)
                    minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _services.WorkContext.WorkingCurrency);

                if (selectedPriceRange.To.HasValue)
                    maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _services.WorkContext.WorkingCurrency);
            }

            //category breadcrumb
            model.DisplayCategoryBreadcrumb = _catalogSettings.CategoryBreadcrumbEnabled;
            if (model.DisplayCategoryBreadcrumb)
            {
                model.CategoryBreadcrumb = _helper.GetCategoryBreadCrumb(category.Id, 0);
            }

            model.DisplayFilter = _catalogSettings.FilterEnabled;
            model.SubCategoryDisplayType = _catalogSettings.SubCategoryDisplayType;

            var customerRolesIds = _services.WorkContext.CurrentCustomer.CustomerRoles.Where(x => x.Active).Select(x => x.Id).ToList();

            // subcategories
            model.SubCategories = _categoryService
                .GetAllCategoriesByParentCategoryId(categoryId)
                .Select(x =>
                {
                    var subCatName = x.GetLocalized(y => y.Name);
                    var subCatModel = new CategoryModel.SubCategoryModel
                    {
                        Id = x.Id,
                        Name = subCatName,
                        SeName = x.GetSeName(),
                    };

                    //prepare picture model
                    int pictureSize = _mediaSettings.CategoryThumbPictureSize;
                    var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _services.WorkContext.WorkingLanguage.Id, _services.WebHelper.IsCurrentConnectionSecured(), _services.StoreContext.CurrentStore.Id);
                    subCatModel.PictureModel = _services.Cache.Get(categoryPictureCacheKey, () =>
                    {
                        var picture = _pictureService.GetPictureById(x.PictureId.GetValueOrDefault());
                        var pictureModel = new PictureModel()
                        {
                            PictureId = x.PictureId.GetValueOrDefault(),
                            FullSizeImageUrl = _pictureService.GetPictureUrl(picture),
                            ImageUrl = _pictureService.GetPictureUrl(picture, targetSize: pictureSize),
                            Title = string.Format(T("Media.Category.ImageLinkTitleFormat"), subCatName),
                            AlternateText = string.Format(T("Media.Category.ImageAlternateTextFormat"), subCatName)
                        };
                        return pictureModel;
                    });

                    return subCatModel;
                })
                .ToList();

            // Featured products
            if (!_catalogSettings.IgnoreFeaturedProducts)
            {
                IPagedList<Product> featuredProducts = null;

                string cacheKey = ModelCacheEventConsumer.CATEGORY_HAS_FEATURED_PRODUCTS_KEY.FormatInvariant(categoryId, string.Join(",", customerRolesIds), _services.StoreContext.CurrentStore.Id);
                var hasFeaturedProductsCache = _services.Cache.Get<bool?>(cacheKey);

                var ctx = new ProductSearchContext();
                if (category.Id > 0)
                    ctx.CategoryIds.Add(category.Id);
                ctx.FeaturedProducts = true;
                ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
                ctx.OrderBy = ProductSortingEnum.Position;
                ctx.PageSize = int.MaxValue;
                ctx.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                ctx.VisibleIndividuallyOnly = true;
                ctx.Origin = categoryId.ToString();

                if (!hasFeaturedProductsCache.HasValue)
                {
                    featuredProducts = _productService.SearchProducts(ctx);
                    hasFeaturedProductsCache = featuredProducts.TotalCount > 0;
                    _services.Cache.Set(cacheKey, hasFeaturedProductsCache, 240);
                }

                if (hasFeaturedProductsCache.Value && featuredProducts == null)
                {
                    featuredProducts = _productService.SearchProducts(ctx);
                }

                if (featuredProducts != null)
                {
                    model.FeaturedProducts = _helper.PrepareProductOverviewModels(
                        featuredProducts,
                        prepareColorAttributes: true).ToList();
                }
            }

            // Products
            if (filter.HasValue())
            {
                var context = new FilterProductContext
                {
                    ParentCategoryID = category.Id,
                    CategoryIds = new List<int> { category.Id },
                    Criteria = _filterService.Deserialize(filter),
                    OrderBy = command.OrderBy
                };

                if (_catalogSettings.ShowProductsFromSubcategories)
                    context.CategoryIds.AddRange(_helper.GetChildCategoryIds(category.Id));

                var filterQuery = _filterService.ProductFilter(context);
                var products = new PagedList<Product>(filterQuery, command.PageIndex, command.PageSize);

                model.Products = _helper.PrepareProductOverviewModels(
                    products,
                    prepareColorAttributes: true,
                    prepareManufacturers: command.ViewMode.IsCaseInsensitiveEqual("list")).ToList();
                model.PagingFilteringContext.LoadPagedList(products);
            }
            else
            {	// use old filter
                IList<int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_services.WebHelper);

                var ctx2 = new ProductSearchContext();
                if (category.Id > 0)
                {
                    ctx2.CategoryIds.Add(category.Id);
                    if (_catalogSettings.ShowProductsFromSubcategories)
                    {
                        // include subcategories
                        ctx2.CategoryIds.AddRange(_helper.GetChildCategoryIds(category.Id));
                    }
                }
                ctx2.FeaturedProducts = _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false;
                ctx2.PriceMin = minPriceConverted;
                ctx2.PriceMax = maxPriceConverted;
                ctx2.LanguageId = _services.WorkContext.WorkingLanguage.Id;
                ctx2.FilteredSpecs = alreadyFilteredSpecOptionIds;
                ctx2.OrderBy = (ProductSortingEnum)command.OrderBy; // ProductSortingEnum.Position;
                ctx2.PageIndex = command.PageNumber - 1;
                ctx2.PageSize = command.PageSize;
                ctx2.LoadFilterableSpecificationAttributeOptionIds = true;
                ctx2.StoreId = _services.StoreContext.CurrentStoreIdIfMultiStoreMode;
                ctx2.VisibleIndividuallyOnly = true;
                ctx2.Origin = categoryId.ToString();

                var products = _productService.SearchProducts(ctx2);

                model.Products = _helper.PrepareProductOverviewModels(
                    products,
                    prepareColorAttributes: true,
                    prepareManufacturers: command.ViewMode.IsCaseInsensitiveEqual("list")).ToList();

                model.PagingFilteringContext.LoadPagedList(products);
                //model.PagingFilteringContext.ViewMode = viewMode;

                //specs
                model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds,
                    ctx2.FilterableSpecificationAttributeOptionIds,
                    _specificationAttributeService, _services.WebHelper, _services.WorkContext);
            }

            // template
            var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId);
            var templateViewPath = _services.Cache.Get(templateCacheKey, () =>
            {
                var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId);
                if (template == null)
                    template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault();
                return template.ViewPath;
            });

            // activity log
            _services.CustomerActivity.InsertActivity("PublicStore.ViewCategory", T("ActivityLog.PublicStore.ViewCategory"), category.Name);

            return View(templateViewPath, model);
        }
		private List<FilterCriteria> ProductFilterableSpecAttributes(FilterProductContext context, string attributeName = null)
		{
			var query = ProductFilter(context);

			var attributes =
				from p in query
				from sa in p.ProductSpecificationAttributes
				where sa.AllowFiltering && sa.ShowOnProductPage
				orderby sa.DisplayOrder
				select sa.SpecificationAttributeOption;

			if (attributeName.HasValue())
				attributes = attributes.Where(a => a.SpecificationAttribute.Name == attributeName);

			var grouped =
				from a in attributes
				group a by new { a.SpecificationAttributeId, a.Id } into g
				select new FilterCriteria
				{
					Name = g.FirstOrDefault().SpecificationAttribute.Name,
					Value = g.FirstOrDefault().Name,
					ID = g.Key.Id,
					MatchCount = g.Count()
				};


			var lst = grouped.OrderByDescending(a => a.MatchCount).ToList();

			lst.ForEach(c =>
			{
				c.Entity = ShortcutSpecAttribute;
				c.IsInactive = true;
			});

			return lst;
		}