Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Fix the sitemap XML task: empty page <loc> and crash without a work context (#860)

Krzysztof Pajaka8bde4b5a44d
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs
index d7aaeac93..ac9f7efd5 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs
@@ -35,7 +35,7 @@ public class GetSearchProductsQueryHandler : IRequestHandler<GetSearchProductsQu
CleanupRequestParameters(request);
// Access control list. Allowed customer groups
- var allowedCustomerGroupsIds = request.Customer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = request.CustomerGroupIds?.ToArray() ?? request.Customer.GetCustomerGroupIds();
// Build base query
var query = _productRepository.Table.AsQueryable();
diff --git a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs
index 97da98dab..4a1a3cad8 100644
--- a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs
+++ b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs
@@ -45,10 +45,16 @@ public class KnowledgebaseService : IKnowledgebaseService
}
private IQueryable<T> ApplyStandardFilter<T>(IQueryable<T> query) where T : BaseEntity, IGroupLinkEntity, IStoreLinkEntity
+ {
+ return ApplyStandardFilter(query, _contextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds(),
+ _contextAccessor.StoreContext.CurrentStore.Id);
+ }
+
+ private IQueryable<T> ApplyStandardFilter<T>(IQueryable<T> query, string[] allowedCustomerGroupsIds,
+ string storeId) where T : BaseEntity, IGroupLinkEntity, IStoreLinkEntity
{
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _contextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -57,7 +63,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
{
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_contextAccessor.StoreContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(storeId)
select p;
}
@@ -285,6 +291,25 @@ public class KnowledgebaseService : IKnowledgebaseService
});
}
+ /// <summary>
+ /// Gets public(published etc) knowledge base articles for an explicit store and customer groups
+ /// </summary>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="customerGroupIds">Customer groups the articles must be visible to</param>
+ /// <returns>List of public knowledge base articles</returns>
+ public virtual async Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticles(string storeId,
+ IList<string> customerGroupIds)
+ {
+ var query = from p in _knowledgebaseArticleRepository.Table
+ select p;
+
+ query = query.Where(x => x.Published);
+ query = ApplyStandardFilter(query, customerGroupIds?.ToArray() ?? [], storeId);
+
+ query = query.OrderBy(x => x.DisplayOrder);
+ return (await _knowledgebaseArticleRepository.ToListAsync(query)).ToList();
+ }
+
/// <summary>
/// Gets knowledge base article if it is published etc
/// </summary>
diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs
index 3977757a2..2493d401a 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs
@@ -76,6 +76,15 @@ public interface IKnowledgebaseService
/// <returns>List of public knowledge base articles</returns>
Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticles();
+ /// <summary>
+ /// Gets public(published etc) knowledge base articles for an explicit store and customer groups,
+ /// without reading the current context - for callers that have none, e.g. scheduled tasks
+ /// </summary>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="customerGroupIds">Customer groups the articles must be visible to</param>
+ /// <returns>List of public knowledge base articles</returns>
+ Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticles(string storeId, IList<string> customerGroupIds);
+
/// <summary>
/// Gets homepage knowledge base articles
/// </summary>
diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs
index 92df83218..5c2c7c387 100644
--- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs
+++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs
@@ -10,6 +10,12 @@ public class GetSearchProductsQuery : IRequest<(IPagedList<Product> products, IL
{
public Customer Customer { get; set; }
+ /// <summary>
+ /// Customer groups the ACL filter uses instead of the groups of <see cref="Customer" />;
+ /// lets callers without a customer (e.g. scheduled tasks) search as a given audience
+ /// </summary>
+ public IList<string> CustomerGroupIds { get; set; }
+
public bool LoadFilterableSpecificationAttributeOptionIds { get; set; } = false;
public int PageIndex { get; set; } = 0;
public int PageSize { get; set; } = int.MaxValue;
diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs
index 1a32101a0..746e1751a 100644
--- a/src/Business/Grand.Business.Messages/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs
+++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs
@@ -2,15 +2,18 @@
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Business.Core.Interfaces.Catalog.Categories;
-using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Cms;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Storage;
+using Grand.Business.Core.Queries.Catalog;
using Grand.Domain.Blogs;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
+using Grand.Domain.Customers;
using Grand.Domain.Knowledgebase;
using Grand.Domain.Localization;
using Grand.Domain.News;
+using Grand.Domain.Permissions;
using Grand.Domain.Stores;
using Grand.Infrastructure.Configuration;
using Grand.Mediator;
@@ -29,44 +32,53 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
private readonly BlogSettings _blogSettings;
private readonly IBrandService _brandService;
+ private readonly AccessControlConfig _accessControlConfig;
private readonly ICategoryService _categoryService;
private readonly CommonSettings _commonSettings;
+ private readonly IGroupService _groupService;
private readonly IKnowledgebaseService _knowledgebaseService;
private readonly KnowledgebaseSettings _knowledgebaseSettings;
private readonly LinkGenerator _linkGenerator;
+ private readonly IMediator _mediator;
private readonly NewsSettings _newsSettings;
private readonly IPageService _pageService;
private readonly IPictureService _pictureService;
- private readonly IProductService _productService;
+ //the sitemap is public content: it lists what a guest can see. The task runs without a request,
+ //so the audience is passed explicitly instead of coming from the (absent) work context
+ private string[] _guestGroupIds;
private GetSitemapXmlCommand _request;
public GetSitemapXmlCommandHandler(
ICategoryService categoryService,
- IProductService productService,
IBrandService brandService,
IPageService pageService,
IBlogService blogService,
IPictureService pictureService,
IKnowledgebaseService knowledgebaseService,
+ IGroupService groupService,
+ IMediator mediator,
CommonSettings commonSettings,
BlogSettings blogSettings,
KnowledgebaseSettings knowledgebaseSettings,
NewsSettings newsSettings,
+ AccessControlConfig accessControlConfig,
LinkGenerator linkGenerator,
AppConfig appConfig)
{
_categoryService = categoryService;
- _productService = productService;
_brandService = brandService;
_pageService = pageService;
_blogService = blogService;
_pictureService = pictureService;
_commonSettings = commonSettings;
_knowledgebaseService = knowledgebaseService;
+ _groupService = groupService;
+ _mediator = mediator;
_knowledgebaseSettings = knowledgebaseSettings;
_newsSettings = newsSettings;
_blogSettings = blogSettings;
+ _accessControlConfig = accessControlConfig;
_linkGenerator = linkGenerator;
_appConfig = appConfig;
}
@@ -74,9 +86,17 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
public async Task<string> Handle(GetSitemapXmlCommand request, CancellationToken cancellationToken)
{
_request = request;
+ var guests = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Guests);
+ _guestGroupIds = guests != null ? [guests.Id] : [];
return await Generate(request.Language, request.Store);
}
+ private bool IsVisibleToGuests(IGroupLinkEntity entity)
+ {
+ return _accessControlConfig.IgnoreAcl || !entity.LimitedToGroups ||
+ entity.CustomerGroups.Any(_guestGroupIds.Contains);
+ }
+
private static string RemoveBom(string p)
{
var bomMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
@@ -175,7 +195,12 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
//categories
if (_commonSettings.SitemapIncludeCategories)
- sitemapUrls.AddRange(await GetCategoryUrls("", language));
+ {
+ var categories = (await _categoryService.GetAllCategories(null, "", store.Id, showHidden: true))
+ .Where(c => c.Published && IsVisibleToGuests(c))
+ .ToLookup(c => c.ParentCategoryId ?? "");
+ sitemapUrls.AddRange(await GetCategoryUrls("", categories, language));
+ }
//brands
if (_commonSettings.SitemapIncludeBrands)
@@ -192,7 +217,7 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
sitemapUrls.AddRange(await GetBlogPostsUrls(language, store));
//knowledge base articles
- sitemapUrls.AddRange(await GetKnowledgebaseUrls(language));
+ sitemapUrls.AddRange(await GetKnowledgebaseUrls(language, store));
//custom URLs
sitemapUrls.AddRange(GetCustomUrls());
@@ -200,13 +225,13 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
return sitemapUrls;
}
- private async Task<IEnumerable<SitemapUrl>> GetCategoryUrls(string parentCategoryId, Language language)
+ private async Task<IEnumerable<SitemapUrl>> GetCategoryUrls(string parentCategoryId,
+ ILookup<string, Category> visibleCategories, Language language)
{
- var allCategoriesByParentCategoryId =
- await _categoryService.GetAllCategoriesByParentCategoryId(parentCategoryId);
+ //walks down from the visible roots, so a category under a hidden parent stays out
var categories = new List<SitemapUrl>();
var storeLocation = GetStoreLocation();
- foreach (var category in allCategoriesByParentCategoryId)
+ foreach (var category in visibleCategories[parentCategoryId])
{
var url =
_appConfig.SeoFriendlyUrlsForLanguagesEnabled
@@ -226,7 +251,7 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
categories.Add(new SitemapUrl(url, imageurl, UpdateFrequency.Weekly,
category.UpdatedOnUtc ?? category.CreatedOnUtc));
- categories.AddRange(await GetCategoryUrls(category.Id, language));
+ categories.AddRange(await GetCategoryUrls(category.Id, visibleCategories, language));
}
return categories;
@@ -234,7 +259,8 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
private async Task<IEnumerable<SitemapUrl>> GetBrandUrls(Language language, Store store)
{
- var brands = await _brandService.GetAllBrands(brandName: "", storeId: store.Id);
+ var brands = (await _brandService.GetAllBrands(brandName: "", storeId: store.Id, showHidden: true))
+ .Where(b => b.Published && IsVisibleToGuests(b));
var brandUrls = new List<SitemapUrl>();
var storeLocation = GetStoreLocation();
foreach (var brand in brands)
@@ -264,8 +290,12 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
private async Task<IEnumerable<SitemapUrl>> GetProductUrls(Language language, Store store)
{
- var search = await _productService.SearchProducts(storeId: store.Id,
- visibleIndividuallyOnly: true, orderBy: ProductSortingEnum.CreatedOn);
+ var search = await _mediator.Send(new GetSearchProductsQuery {
+ CustomerGroupIds = _guestGroupIds,
+ StoreId = store.Id,
+ VisibleIndividuallyOnly = true,
+ OrderBy = ProductSortingEnum.CreatedOn
+ });
var storeLocation = GetStoreLocation();
var products = new List<SitemapUrl>();
foreach (var product in search.products)
@@ -296,18 +326,19 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
private async Task<IEnumerable<SitemapUrl>> GetPagesUrls(Language language, Store store)
{
var now = DateTime.UtcNow;
- return (await _pageService.GetAllPages(store.Id))
+ return (await _pageService.GetAllPages(store.Id, ignoreAcl: true))
+ .Where(IsVisibleToGuests)
.PreferStoreOverrides(store.Id)
- .Where(t => t.IncludeInSitemap && (!t.StartDateUtc.HasValue || t.StartDateUtc < now) &&
+ .Where(t => t.Published && t.IncludeInSitemap && (!t.StartDateUtc.HasValue || t.StartDateUtc < now) &&
(!t.EndDateUtc.HasValue || t.EndDateUtc > now))
.Select(topic =>
{
var url =
_appConfig.SeoFriendlyUrlsForLanguagesEnabled
- ? _linkGenerator.GetUriByRouteValues("Topic",
+ ? _linkGenerator.GetUriByRouteValues("Page",
new { SeName = topic.GetSeName(language.Id), language = language.UniqueSeoCode },
GetHttpProtocol(), GetHost())
- : _linkGenerator.GetUriByRouteValues("Topic", new { SeName = topic.GetSeName(language.Id) },
+ : _linkGenerator.GetUriByRouteValues("Page", new { SeName = topic.GetSeName(language.Id) },
GetHttpProtocol(), GetHost());
return new SitemapUrl(url, string.Empty, UpdateFrequency.Weekly, DateTime.UtcNow);
@@ -343,9 +374,10 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,
return blog;
}
- private async Task<IEnumerable<SitemapUrl>> GetKnowledgebaseUrls(Language language)
+ private async Task<IEnumerable<SitemapUrl>> GetKnowledgebaseUrls(Language language, Store store)
{
- var knowledgebasearticles = await _knowledgebaseService.GetPublicKnowledgebaseArticles();
+ var knowledgebasearticles =
+ await _knowledgebaseService.GetPublicKnowledgebaseArticles(store.Id, _guestGroupIds);
return knowledgebasearticles.Select(knowledgebasearticle => _appConfig.SeoFriendlyUrlsForLanguagesEnabled
? _linkGenerator.GetUriByRouteValues("KnowledgebaseArticle",
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs
index 78dda398a..c2f20dff8 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs
@@ -39,4 +39,26 @@ public class GetSearchProductsQueryHandlerTests
//Arrange
Assert.IsNotNull(result.products);
}
+
+ [TestMethod]
+ public async Task Handle_WhenCustomerGroupIdsGivenWithoutCustomer_FiltersByThoseGroups()
+ {
+ //Arrange
+ await _repository.InsertAsync(new Product { Id = "open", Published = true, VisibleIndividually = true });
+ await _repository.InsertAsync(new Product {
+ Id = "guests", Published = true, VisibleIndividually = true, LimitedToGroups = true,
+ CustomerGroups = ["guests-group"]
+ });
+ await _repository.InsertAsync(new Product {
+ Id = "admins", Published = true, VisibleIndividually = true, LimitedToGroups = true,
+ CustomerGroups = ["admins-group"]
+ });
+ var searchProductsQuery = new GetSearchProductsQuery {
+ CustomerGroupIds = ["guests-group"]
+ };
+ //Act
+ var result = await handler.Handle(searchProductsQuery, CancellationToken.None);
+ //Assert
+ CollectionAssert.AreEquivalent(new[] { "open", "guests" }, result.products.Select(p => p.Id).ToList());
+ }
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
index ffeeef6b6..d2930791d 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
@@ -377,4 +377,28 @@ public class KnowledgebaseServiceTests
Assert.IsNull(
_repositoryKnowledgebaseArticleComment.Table.FirstOrDefault(x => x.Id == knowledgebaseArticleComment.Id));
}
+
+ [TestMethod]
+ public async Task GetPublicKnowledgebaseArticles_WhenScopeGivenWithoutContext_FiltersByStoreAndGroups()
+ {
+ //Arrange - no ambient work or store context, as in a scheduled task
+ var service = new KnowledgebaseService(_repositoryKnowledgebaseCategory,
+ _repositoryKnowledgebaseArticle, _repositoryKnowledgebaseArticleComment, _mediatorMock.Object,
+ new Mock<IContextAccessor>().Object, _cacheBase, new AccessControlConfig());
+ await _repositoryKnowledgebaseArticle.InsertAsync(new KnowledgebaseArticle { Id = "open", Published = true });
+ await _repositoryKnowledgebaseArticle.InsertAsync(new KnowledgebaseArticle {
+ Id = "guests", Published = true, LimitedToGroups = true, CustomerGroups = ["guests-group"]
+ });
+ await _repositoryKnowledgebaseArticle.InsertAsync(new KnowledgebaseArticle {
+ Id = "admins", Published = true, LimitedToGroups = true, CustomerGroups = ["admins-group"]
+ });
+ await _repositoryKnowledgebaseArticle.InsertAsync(new KnowledgebaseArticle {
+ Id = "other-store", Published = true, LimitedToStores = true, Stores = ["store2"]
+ });
+ await _repositoryKnowledgebaseArticle.InsertAsync(new KnowledgebaseArticle { Id = "unpublished" });
+ //Act
+ var result = await service.GetPublicKnowledgebaseArticles("store1", ["guests-group"]);
+ //Assert
+ CollectionAssert.AreEquivalent(new[] { "open", "guests" }, result.Select(x => x.Id).ToList());
+ }
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Commands/GetSitemapXmlCommandHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Commands/GetSitemapXmlCommandHandlerTests.cs
new file mode 100644
index 000000000..7a5cfac00
--- /dev/null
+++ b/src/Tests/Grand.Business.Messages.Tests/Commands/GetSitemapXmlCommandHandlerTests.cs
@@ -0,0 +1,228 @@
+using Grand.Business.Core.Commands.System.Common;
+using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Business.Core.Interfaces.Catalog.Categories;
+using Grand.Business.Core.Interfaces.Cms;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Storage;
+using Grand.Business.Core.Queries.Catalog;
+using Grand.Business.Messages.Commands.Handlers.Common;
+using Grand.Domain;
+using Grand.Domain.Blogs;
+using Grand.Domain.Catalog;
+using Grand.Domain.Common;
+using Grand.Domain.Customers;
+using Grand.Domain.Knowledgebase;
+using Grand.Domain.Localization;
+using Grand.Domain.News;
+using Grand.Domain.Pages;
+using Grand.Domain.Stores;
+using Grand.Infrastructure.Configuration;
+using Grand.Mediator;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+using System.Xml.Linq;
+
+namespace Grand.Business.Messages.Tests.Commands;
+
+[TestClass]
+public class GetSitemapXmlCommandHandlerTests
+{
+ private const string StoreId = "store1";
+ private const string GuestsGroupId = "guests-group";
+ private const string AdminsGroupId = "admins-group";
+ private static readonly XNamespace Sitemap = "http://www.sitemaps.org/schemas/sitemap/0.9";
+
+ //strict mocks: a call to any overload that reads the ambient work/store context fails the test
+ private Mock<IBrandService> _brandServiceMock;
+ private Mock<ICategoryService> _categoryServiceMock;
+ private CommonSettings _commonSettings;
+ private GetSitemapXmlCommandHandler _handler;
+ private Mock<IKnowledgebaseService> _knowledgebaseServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IPageService> _pageServiceMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _categoryServiceMock = new Mock<ICategoryService>(MockBehavior.Strict);
+ _brandServiceMock = new Mock<IBrandService>(MockBehavior.Strict);
+ _pageServiceMock = new Mock<IPageService>(MockBehavior.Strict);
+ _knowledgebaseServiceMock = new Mock<IKnowledgebaseService>(MockBehavior.Strict);
+ _mediatorMock = new Mock<IMediator>(MockBehavior.Strict);
+
+ var blogServiceMock = new Mock<IBlogService>();
+ blogServiceMock.Setup(x => x.GetAllBlogPosts(StoreId, null, null, 0, int.MaxValue, false, null, "", ""))
+ .ReturnsAsync(new PagedList<BlogPost>());
+
+ var groupServiceMock = new Mock<IGroupService>();
+ groupServiceMock.Setup(x => x.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Guests))
+ .ReturnsAsync(new CustomerGroup { Id = GuestsGroupId, SystemName = SystemCustomerGroupNames.Guests });
+
+ _categoryServiceMock.Setup(x => x.GetAllCategories(null, "", StoreId, 0, int.MaxValue, true))
+ .ReturnsAsync(new PagedList<Category>());
+ _brandServiceMock.Setup(x => x.GetAllBrands("", StoreId, 0, int.MaxValue, true))
+ .ReturnsAsync(new PagedList<Brand>());
+ _pageServiceMock.Setup(x => x.GetAllPages(StoreId, true)).ReturnsAsync(new List<Page>());
+ _knowledgebaseServiceMock.Setup(x => x.GetPublicKnowledgebaseArticles(StoreId,
+ It.Is<IList<string>>(g => g.SequenceEqual(new[] { GuestsGroupId }))))
+ .ReturnsAsync(new List<KnowledgebaseArticle>());
+ _mediatorMock.Setup(x => x.Send(It.IsAny<GetSearchProductsQuery>(), It.IsAny<CancellationToken>()))
+ .ReturnsAsync((new PagedList<Product>(), (IList<string>)new List<string>()));
+
+ _commonSettings = new CommonSettings {
+ SitemapIncludeCategories = true,
+ SitemapIncludeBrands = true,
+ SitemapIncludeProducts = true
+ };
+
+ _handler = new GetSitemapXmlCommandHandler(_categoryServiceMock.Object, _brandServiceMock.Object,
+ _pageServiceMock.Object, blogServiceMock.Object, new Mock<IPictureService>().Object,
+ _knowledgebaseServiceMock.Object, groupServiceMock.Object, _mediatorMock.Object, _commonSettings,
+ new BlogSettings(), new KnowledgebaseSettings(), new NewsSettings(), new AccessControlConfig(),
+ new RouteNameLinkGenerator(), new AppConfig());
+ }
+
+ private Task<string> Generate()
+ {
+ return _handler.Handle(new GetSitemapXmlCommand {
+ Store = new Store { Id = StoreId, Url = "https://shop.example.com/" },
+ Language = new Language { Id = "lang1", UniqueSeoCode = "en" }
+ }, CancellationToken.None);
+ }
+
+ private static List<string> Locations(string xml)
+ {
+ return XDocument.Parse(xml).Descendants(Sitemap + "loc").Select(x => x.Value).ToList();
+ }
+
+ [TestMethod]
+ public async Task Handle_WhenPagesIncludedInSitemap_WritesNonEmptyPageLocations()
+ {
+ //Arrange
+ _pageServiceMock.Setup(x => x.GetAllPages(StoreId, true)).ReturnsAsync(new List<Page> {
+ new() { Id = "1", SystemName = "AboutUs", SeName = "about-us", Published = true, IncludeInSitemap = true },
+ new() { Id = "2", SystemName = "Shipping", SeName = "shipping", Published = true, IncludeInSitemap = true }
+ });
+
+ //Act
+ var xml = await Generate();
+
+ //Assert
+ var locations = Locations(xml);
+ Assert.IsFalse(locations.Any(string.IsNullOrEmpty), "sitemap contains an empty <loc>");
+ CollectionAssert.Contains(locations, "https://shop.example.com/about-us");
+ CollectionAssert.Contains(locations, "https://shop.example.com/shipping");
+ }
+
+ [TestMethod]
+ public async Task Handle_WithoutWorkContext_UsesOnlyExplicitlyScopedQueries()
+ {
+ //Act - the strict mocks throw if the handler calls an overload that reads the ambient context
+ var xml = await Generate();
+
+ //Assert
+ Assert.IsFalse(Locations(xml).Any(string.IsNullOrEmpty), "sitemap contains an empty <loc>");
+ _categoryServiceMock.Verify(x => x.GetAllCategories(null, "", StoreId, 0, int.MaxValue, true), Times.Once);
+ _brandServiceMock.Verify(x => x.GetAllBrands("", StoreId, 0, int.MaxValue, true), Times.Once);
+ _pageServiceMock.Verify(x => x.GetAllPages(StoreId, true), Times.Once);
+ _mediatorMock.Verify(x => x.Send(It.Is<GetSearchProductsQuery>(q =>
+ q.Customer == null && q.StoreId == StoreId && q.VisibleIndividuallyOnly &&
+ q.CustomerGroupIds.SequenceEqual(new[] { GuestsGroupId })), It.IsAny<CancellationToken>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task Handle_ListsOnlyWhatAGuestCanSee()
+ {
+ //Arrange
+ _pageServiceMock.Setup(x => x.GetAllPages(StoreId, true)).ReturnsAsync(new List<Page> {
+ new() { Id = "1", SystemName = "Open", SeName = "open-page", Published = true, IncludeInSitemap = true },
+ new() {
+ Id = "2", SystemName = "ForGuests", SeName = "guest-page", Published = true, IncludeInSitemap = true,
+ LimitedToGroups = true, CustomerGroups = [GuestsGroupId]
+ },
+ new() {
+ Id = "3", SystemName = "ForAdmins", SeName = "admin-page", Published = true, IncludeInSitemap = true,
+ LimitedToGroups = true, CustomerGroups = [AdminsGroupId]
+ },
+ new() { Id = "4", SystemName = "Draft", SeName = "draft-page", Published = false, IncludeInSitemap = true }
+ });
+ _categoryServiceMock.Setup(x => x.GetAllCategories(null, "", StoreId, 0, int.MaxValue, true))
+ .ReturnsAsync(new PagedList<Category>(new List<Category> {
+ new() { Id = "c1", ParentCategoryId = "", SeName = "open-category", Published = true },
+ new() { Id = "c2", ParentCategoryId = "c1", SeName = "child-category", Published = true },
+ new() {
+ Id = "c3", ParentCategoryId = "", SeName = "admin-category", Published = true,
+ LimitedToGroups = true, CustomerGroups = [AdminsGroupId]
+ },
+ new() { Id = "c4", ParentCategoryId = "c3", SeName = "child-of-hidden-category", Published = true },
+ new() { Id = "c5", ParentCategoryId = "", SeName = "unpublished-category", Published = false }
+ }, 0, int.MaxValue));
+ _brandServiceMock.Setup(x => x.GetAllBrands("", StoreId, 0, int.MaxValue, true))
+ .ReturnsAsync(new PagedList<Brand>(new List<Brand> {
+ new() { Id = "b1", SeName = "open-brand", Published = true },
+ new() {
+ Id = "b2", SeName = "admin-brand", Published = true, LimitedToGroups = true,
+ CustomerGroups = [AdminsGroupId]
+ },
+ new() { Id = "b3", SeName = "unpublished-brand", Published = false }
+ }, 0, int.MaxValue));
+
+ //Act
+ var locations = Locations(await Generate()).Select(x => x.Replace("https://shop.example.com/", ""))
+ .ToList();
+
+ //Assert
+ CollectionAssert.IsSubsetOf(
+ new[] { "open-page", "guest-page", "open-category", "child-category", "open-brand" }, locations);
+ foreach (var hidden in new[] {
+ "admin-page", "draft-page", "admin-category", "child-of-hidden-category",
+ "unpublished-category", "admin-brand", "unpublished-brand"
+ })
+ CollectionAssert.DoesNotContain(locations, hidden);
+ }
+
+ /// <summary>
+ /// Resolves the storefront's named routes like the real LinkGenerator: a route name that is not
+ /// registered yields null, which the sitemap writes as an empty &lt;loc /&gt;
+ /// </summary>
+ private sealed class RouteNameLinkGenerator : LinkGenerator
+ {
+ private static readonly HashSet<string> RouteNames = [
+ "HomePage", "ProductSearch", "ContactUs", "NewsArchive", "Blog", "Knowledgebase",
+ "Product", "Category", "Brand", "BlogPost", "Page", "KnowledgebaseArticle"
+ ];
+
+ public override string GetUriByAddress<TAddress>(TAddress address, RouteValueDictionary values,
+ string scheme, HostString host, PathString pathBase = default, FragmentString fragment = default,
+ LinkOptions options = null)
+ {
+ if (address is not RouteValuesAddress routeAddress || !RouteNames.Contains(routeAddress.RouteName))
+ return null;
+
+ return $"{scheme}://{host}/{values["SeName"]}";
+ }
+
+ public override string GetUriByAddress<TAddress>(HttpContext httpContext, TAddress address,
+ RouteValueDictionary values, RouteValueDictionary ambientValues = null, string scheme = null,
+ HostString? host = null, PathString? pathBase = null, FragmentString fragment = default,
+ LinkOptions options = null)
+ {
+ throw new NotSupportedException();
+ }
+
+ public override string GetPathByAddress<TAddress>(HttpContext httpContext, TAddress address,
+ RouteValueDictionary values, RouteValueDictionary ambientValues = null, PathString? pathBase = null,
+ FragmentString fragment = default, LinkOptions options = null)
+ {
+ throw new NotSupportedException();
+ }
+
+ public override string GetPathByAddress<TAddress>(TAddress address, RouteValueDictionary values,
+ PathString pathBase = default, FragmentString fragment = default, LinkOptions options = null)
+ {
+ throw new NotSupportedException();
+ }
+ }
+}