in src/Modules/SimplCommerce.Module.Catalog/Areas/Catalog/Controllers/CategoryController.cs [43:128]
public IActionResult CategoryDetail(long id, SearchOption searchOption)
{
var category = _categoryRepository.Query().FirstOrDefault(x => x.Id == id);
if (category == null)
{
return Redirect("~/Error/FindNotFound");
}
var model = new ProductsByCategory
{
CategoryId = category.Id,
ParentCategorId = category.ParentId,
CategoryName = _contentLocalizationService.GetLocalizedProperty(category, nameof(category.Name), category.Name),
CategorySlug = category.Slug,
CategoryMetaTitle = category.MetaTitle,
CategoryMetaKeywords = category.MetaKeywords,
CategoryMetaDescription = category.MetaDescription,
CurrentSearchOption = searchOption,
FilterOption = new FilterOption()
};
var query = _productRepository
.Query()
.Where(x => x.Categories.Any(c => c.CategoryId == category.Id) && x.IsPublished && x.IsVisibleIndividually);
if (query.Count() == 0)
{
model.TotalProduct = 0;
return View(model);
}
AppendFilterOptionsToModel(model, query);
if (searchOption.MinPrice.HasValue)
{
query = query.Where(x => x.Price >= searchOption.MinPrice.Value);
}
if (searchOption.MaxPrice.HasValue)
{
query = query.Where(x => x.Price <= searchOption.MaxPrice.Value);
}
var categories = searchOption.GetCategories();
if (categories.Any())
{
query = query.Where(p => p.Categories.Select(c => c.CategoryId).Intersect(_categoryRepository.Query().Where(cat => categories.Contains(cat.Slug)).Select(c => c.Id)).Any());
}
var brands = searchOption.GetBrands().ToArray();
if (brands.Any())
{
query = query.Where(x => x.BrandId != null && brands.Contains(x.Brand.Slug));
}
model.TotalProduct = query.Count();
var currentPageNum = searchOption.Page <= 0 ? 1 : searchOption.Page;
var offset = (_pageSize * currentPageNum) - _pageSize;
while (currentPageNum > 1 && offset >= model.TotalProduct)
{
currentPageNum--;
offset = (_pageSize * currentPageNum) - _pageSize;
}
query = ApplySort(searchOption, query);
var products = query
.Include(x => x.ThumbnailImage)
.Skip(offset)
.Take(_pageSize)
.Select(x => ProductThumbnail.FromProduct(x))
.ToList();
foreach (var product in products)
{
product.Name = _contentLocalizationService.GetLocalizedProperty(nameof(Product), product.Id, nameof(product.Name), product.Name);
product.ThumbnailUrl = _mediaService.GetThumbnailUrl(product.ThumbnailImage);
product.CalculatedProductPrice = _productPricingService.CalculateProductPrice(product);
}
model.Products = products;
model.CurrentSearchOption.PageSize = _pageSize;
model.CurrentSearchOption.Page = currentPageNum;
return View(model);
}