diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index e5dab64..dca1ade 100644 --- a/aidlc-docs/features/contact-forms-module/aidlc-state.md +++ b/aidlc-docs/features/contact-forms-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: contact-forms-module - **Project Type**: Brownfield - **Start Date**: 2026-11-09 -- **Current Stage**: CONSTRUCTION - CMS-U0 built and committed (awaiting review); next CMS-U1 v2 +- **Current Stage**: CONSTRUCTION - CMS-U1 built and committed (awaiting review); next CMS-U1b - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications — never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u1-offerings-category/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u1-offerings-category/code/summary.md new file mode 100644 index 0000000..2c6e7f6 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u1-offerings-category/code/summary.md @@ -0,0 +1,23 @@ +# CMS-U1 offerings-category (v2, categories are CMS data): code summary + +## Data +OfferingCategory (Id, Name unique case-insensitive, SortOrder, CreatedAt, UpdatedAt) in table OfferingsCategories; Offering.CategoryId (nullable, FK Restrict) + navigation. Migration 20261109193305_AddOfferingCategories (Offerings context). Verified on a real MariaDB: applies after InitialCreate and AddOfferingSlug, unique index rejects 'websites' when 'Websites' exists, FK delete rule RESTRICT. Nothing is seeded. + +## Routes (/api/v1/offerings/categories, class AdminOnly, no anonymous action, no admin segment) +GET list {id,name,sortOrder,offeringCount}; POST {name} 201+Location (409 duplicate name); PUT {id:guid} rename (404 unknown, 409 duplicate); DELETE {id:guid} (404 unknown, 409 ProblemDetails while live offerings use it; soft-deleted offerings are released in the same transaction). +Offerings: create/update take categoryId (Guid?, must exist, else 400 errors.categoryId=["invalid"], null clears). OfferingDto gains categoryId (string|null) and category (name|null). + +## Handoff for the SLP site +GET /api/v1/offerings: category is the name or null (shape unchanged for the site); categoryId and displayOrder are additive fields that the site ignores. A rename is visible on the next request: the name is read through the FK on every query, and the code has no response or output caching. A reverse proxy cache (nginx/IIS) is outside this repo and must not cache /api/v1/offerings for longer than acceptable for renames. + +## Handoff for CMS-U1b (admin UI) +Use the four category routes above plus categoryId on offering create/update; offeringCount is in the list for the delete dialog; the 409 delete message is the ProblemDetails title. + +## Dropped from v1 +Offerings:Categories, OfferingsOptions, appsettings values, legacy-value rule, string column and its migration (v1 stays in git stash until this commit exists). + +## Verification (real output) +Build 0 errors. Offerings.Tests 84 passed; Core.Tests 196; Availability.Tests 82; Identity.Tests 37; Master.Tests 57; Api.Tests 4 passed (MariaDB container, removed afterwards). Note: Api.Tests host (SlpModularCms.Api) does not load the Offerings module; the migration was therefore verified separately with dotnet ef database update against the container. + +## Tech debt note +prettier --check reports style warnings on 15 pre-existing files in frontend/src/features/offerings (untouched, probably line endings). Not addressed in this feature. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md index 0985249..da80be9 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md @@ -24,16 +24,16 @@ Route `categories` cannot clash with `{id:guid}` on `/offerings`. Ordering/reord - Single `OfferingDto` (from CMS-U0) gains `CategoryId` (Guid?, string in JSON like `Id`) and `Category` (name | null). Public JSON therefore carries `category` as the name or `null` (unchanged shape for the SLS frontend) plus the additive `categoryId`/`displayOrder`. ## Steps -- [ ] **Step 1 — Revert v1 leftovers**: confirm the working tree only contains CMS-U0 (stash holds v1); delete nothing committed. -- [ ] **Step 2 — Entities + DbContext**: `OfferingCategory`, `Offering.CategoryId` + navigation, mapping, unique index, FK Restrict; `Include` the category in `OfferingRepository` reads. -- [ ] **Step 3 — Repository**: `IOfferingCategoryRepository` (list with usage counts, get, add, remove, exists-by-name case-insensitive, clear category on soft-deleted offerings); transaction support as in `OfferingRepository`. -- [ ] **Step 4 — Services**: `IOfferingCategoriesService` (list/create/rename/delete with the rules above; exceptions `OfferingCategoryNameConflictException`, `OfferingCategoryInUseException`); `OfferingsService` validates `CategoryId` exists and maps `CategoryId`/`Category` into `OfferingDto`. -- [ ] **Step 5 — Controllers**: `OfferingCategoriesController` (route `offerings/categories`, class-level `AdminOnly`) with ProblemDetails mapping (409 conflict, 409 in-use, 404, 400); `OfferingsController` handles invalid `categoryId` as 400. -- [ ] **Step 6 — Migration** `AddOfferingCategories`. -- [ ] **Step 7 — Tests (Offerings.Tests)**: category service (create trims, duplicate case-insensitive => conflict, rename conflict, rename unknown, delete in use => in-use, delete unused ok, delete clears soft-deleted references, list with counts and order); offering service (unknown `categoryId` => invalid, null clears, DTO carries id+name, rename visible through DTO); controller mapping (201/404/409/400); repository (FK round trip, case-insensitive exists); route-table test from CMS-U0 extended (all `categories` actions AdminOnly, none anonymous). -- [ ] **Step 8 — Build + test (automatic)**: solution build; Offerings.Tests, Core.Tests, Availability.Tests; `Api.Tests` needs a local MySQL (fails here with "connection refused" regardless of the change). Report real output. -- [ ] **Step 9 — Docs/handoff**: summary + handoff note for the SLS frontend (public `category` = name|null; additive `categoryId`) and for CMS-U1b (route list above). -- [ ] **Step 10 — Commit** (one commit, no push). +- [x] **Step 1 — Revert v1 leftovers**: confirm the working tree only contains CMS-U0 (stash holds v1); delete nothing committed. +- [x] **Step 2 — Entities + DbContext**: `OfferingCategory`, `Offering.CategoryId` + navigation, mapping, unique index, FK Restrict; `Include` the category in `OfferingRepository` reads. +- [x] **Step 3 — Repository**: `IOfferingCategoryRepository` (list with usage counts, get, add, remove, exists-by-name case-insensitive, clear category on soft-deleted offerings); transaction support as in `OfferingRepository`. +- [x] **Step 4 — Services**: `IOfferingCategoriesService` (list/create/rename/delete with the rules above; exceptions `OfferingCategoryNameConflictException`, `OfferingCategoryInUseException`); `OfferingsService` validates `CategoryId` exists and maps `CategoryId`/`Category` into `OfferingDto`. +- [x] **Step 5 — Controllers**: `OfferingCategoriesController` (route `offerings/categories`, class-level `AdminOnly`) with ProblemDetails mapping (409 conflict, 409 in-use, 404, 400); `OfferingsController` handles invalid `categoryId` as 400. +- [x] **Step 6 — Migration** `AddOfferingCategories`. +- [x] **Step 7 — Tests (Offerings.Tests)**: category service (create trims, duplicate case-insensitive => conflict, rename conflict, rename unknown, delete in use => in-use, delete unused ok, delete clears soft-deleted references, list with counts and order); offering service (unknown `categoryId` => invalid, null clears, DTO carries id+name, rename visible through DTO); controller mapping (201/404/409/400); repository (FK round trip, case-insensitive exists); route-table test from CMS-U0 extended (all `categories` actions AdminOnly, none anonymous). +- [x] **Step 8 — Build + test (automatic)**: solution build; Offerings.Tests, Core.Tests, Availability.Tests; `Api.Tests` needs a local MySQL (fails here with "connection refused" regardless of the change). Report real output. +- [x] **Step 9 — Docs/handoff**: summary + handoff note for the SLS frontend (public `category` = name|null; additive `categoryId`) and for CMS-U1b (route list above). +- [x] **Step 10 — Commit** (one commit, no push). ## Explicitly NOT touched Core, Availability, Identity, host config/appsettings (no `Offerings:Categories` anymore), the marker (CMS-U2), OpenAPI export (CMS-U3), frontend (CMS-U1b). diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingCategoriesControllerTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingCategoriesControllerTests.cs new file mode 100644 index 0000000..45f51a6 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingCategoriesControllerTests.cs @@ -0,0 +1,110 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Modules.Offerings.Controllers; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Controllers; + +public class OfferingCategoriesControllerTests +{ + private readonly IOfferingCategoriesService _service = Substitute.For(); + + private OfferingCategoriesController CreateSut() => new(_service); + + private static OfferingCategoryDto Dto(string name = "Websites") + => new(Guid.NewGuid().ToString(), name, 0, 0); + + [Fact] + public async Task List_Returns200() + { + _service.ListAsync().Returns([Dto()]); + + var result = await CreateSut().List(); + + result.Should().BeOfType().Which.StatusCode.Should().Be(200); + } + + [Fact] + public async Task Create_Returns201_WithLocation() + { + var dto = Dto(); + _service.CreateAsync("Websites").Returns(dto); + + var result = await CreateSut().Create(new OfferingCategoryRequest("Websites")); + + var created = result.Should().BeOfType().Subject; + created.Location.Should().Be($"/api/v1/offerings/categories/{dto.Id}"); + } + + [Fact] + public async Task Create_Returns409_WhenTheNameIsTaken() + { + _service.CreateAsync(Arg.Any()).ThrowsAsync(new OfferingCategoryNameConflictException("Websites")); + + var result = await CreateSut().Create(new OfferingCategoryRequest("Websites")); + + result.Should().BeOfType().Which.StatusCode.Should().Be(409); + } + + [Fact] + public async Task Rename_Returns200_404_And409() + { + var id = Guid.NewGuid(); + _service.RenameAsync(id, "Nieuw").Returns(Dto("Nieuw")); + (await CreateSut().Rename(id, new OfferingCategoryRequest("Nieuw"))) + .Should().BeOfType(); + + _service.RenameAsync(id, "Nieuw").Returns((OfferingCategoryDto?)null); + (await CreateSut().Rename(id, new OfferingCategoryRequest("Nieuw"))) + .Should().BeOfType(); + + _service.RenameAsync(id, "Nieuw").ThrowsAsync(new OfferingCategoryNameConflictException("Nieuw")); + (await CreateSut().Rename(id, new OfferingCategoryRequest("Nieuw"))) + .Should().BeOfType(); + } + + [Fact] + public async Task Delete_Returns204_404_And409WhenInUse() + { + var id = Guid.NewGuid(); + _service.DeleteAsync(id).Returns(true); + (await CreateSut().Delete(id)).Should().BeOfType(); + + _service.DeleteAsync(id).Returns(false); + (await CreateSut().Delete(id)).Should().BeOfType(); + + _service.DeleteAsync(id).ThrowsAsync(new OfferingCategoryInUseException(2)); + var conflict = await CreateSut().Delete(id); + var problem = conflict.Should().BeOfType().Subject.Value + .Should().BeOfType().Subject; + problem.Status.Should().Be(409); + problem.Title.Should().Contain("2"); + } + + [Fact] + public void EveryAction_RequiresAdminOnly_IsNeverAnonymous_AndHasNoAdminSegment() + { + var type = typeof(OfferingCategoriesController); + type.GetCustomAttribute()!.Policy.Should().Be("AdminOnly"); + type.GetCustomAttribute()!.Template.Should().Be("offerings/categories"); + + var actions = type + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(m => m.GetCustomAttributes().Any()) + .ToList(); + + actions.Should().HaveCount(4); + foreach (var action in actions) + { + action.GetCustomAttribute().Should().BeNull(action.Name); + (action.GetCustomAttribute()!.Template ?? string.Empty) + .Should().NotContainEquivalentOf("admin"); + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerCategoryTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerCategoryTests.cs new file mode 100644 index 0000000..d0fb1ef --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerCategoryTests.cs @@ -0,0 +1,60 @@ +using System.Security.Claims; +using FluentAssertions; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Modules.Offerings.Controllers; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Controllers; + +public class OfferingsControllerCategoryTests +{ + private readonly IOfferingsService _service = Substitute.For(); + + private OfferingsController CreateSut() => new(_service) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext + { + User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuth")), + }, + }, + }; + + private static void AssertInvalidCategoryId(IActionResult result) + { + var bad = result.Should().BeOfType().Subject; + var problem = bad.Value.Should().BeOfType().Subject; + problem.Status.Should().Be(400); + problem.Errors["categoryId"].Should().Equal("invalid"); + } + + [Fact] + public async Task Create_Returns400_WithCategoryIdError_WhenTheCategoryDoesNotExist() + { + _service.CreateAsync(Arg.Any(), Arg.Any()) + .ThrowsAsync(new OfferingCategoryInvalidException()); + + var result = await CreateSut().Create( + new CreateOfferingRequest("T", "D", "p", "n", ["f"], "c", CategoryId: Guid.NewGuid())); + + AssertInvalidCategoryId(result); + } + + [Fact] + public async Task Update_Returns400_WithCategoryIdError_WhenTheCategoryDoesNotExist() + { + _service.UpdateAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .ThrowsAsync(new OfferingCategoryInvalidException()); + + var result = await CreateSut().Update( + Guid.NewGuid(), new UpdateOfferingRequest("T", "D", "p", "n", ["f"], "c", CategoryId: Guid.NewGuid())); + + AssertInvalidCategoryId(result); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingCategoryRepositoryTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingCategoryRepositoryTests.cs new file mode 100644 index 0000000..e8052b8 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingCategoryRepositoryTests.cs @@ -0,0 +1,133 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Offerings.Data; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Repositories; + +namespace SlpModularCms.Modules.Offerings.Tests.Repositories; + +public class OfferingCategoryRepositoryTests : IDisposable +{ + private readonly OfferingsDbContext _context; + private readonly OfferingCategoryRepository _sut; + + public OfferingCategoryRepositoryTests() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + _context = new OfferingsDbContext(options); + _sut = new OfferingCategoryRepository(_context); + } + + public void Dispose() => _context.Dispose(); + + private static OfferingCategory Category(string name, int order) => new() + { + Id = Guid.NewGuid(), + Name = name, + SortOrder = order, + CreatedAt = DateTimeOffset.UtcNow, + UpdatedAt = DateTimeOffset.UtcNow, + }; + + private static Offering Offering(string title, Guid? categoryId, bool deleted = false) => new() + { + Id = Guid.NewGuid(), + Slug = title.ToLowerInvariant(), + Title = title, + Description = "d", + Price = "p", + PriceNote = "n", + Features = ["f"], + CtaLabel = "c", + CategoryId = categoryId, + IsDeleted = deleted, + CreatedAt = DateTimeOffset.UtcNow, + UpdatedAt = DateTimeOffset.UtcNow, + }; + + [Fact] + public async Task ListAsync_OrdersBySortOrderThenName_AndCountsOnlyLiveOfferings() + { + var onderhoud = Category("Onderhoud", 1); + var websites = Category("Websites", 0); + await _sut.AddAsync(onderhoud); + await _sut.AddAsync(websites); + _context.Offerings.AddRange( + Offering("A", websites.Id), + Offering("B", websites.Id), + Offering("Gone", websites.Id, deleted: true), + Offering("C", null)); + await _context.SaveChangesAsync(); + + var result = await _sut.ListAsync(); + + result.Select(r => (r.Category.Name, r.OfferingCount)).Should().Equal(("Websites", 2), ("Onderhoud", 0)); + } + + [Theory] + [InlineData("websites")] + [InlineData("WEBSITES")] + [InlineData("Websites")] + public async Task ExistsByNameAsync_IsCaseInsensitive(string probe) + { + await _sut.AddAsync(Category("Websites", 0)); + await _sut.SaveChangesAsync(); + + (await _sut.ExistsByNameAsync(probe)).Should().BeTrue(); + } + + [Fact] + public async Task ExistsByNameAsync_IgnoresTheCategoryBeingRenamed() + { + var websites = Category("Websites", 0); + await _sut.AddAsync(websites); + await _sut.SaveChangesAsync(); + + (await _sut.ExistsByNameAsync("websites", excludeId: websites.Id)).Should().BeFalse(); + (await _sut.ExistsByNameAsync("Onderhoud")).Should().BeFalse(); + } + + [Fact] + public async Task GetMaxSortOrderAsync_ReturnsMinusOne_WhenEmpty_ElseTheHighest() + { + (await _sut.GetMaxSortOrderAsync()).Should().Be(-1); + + await _sut.AddAsync(Category("A", 3)); + await _sut.AddAsync(Category("B", 7)); + await _sut.SaveChangesAsync(); + + (await _sut.GetMaxSortOrderAsync()).Should().Be(7); + } + + [Fact] + public async Task ClearCategoryOnDeletedOfferingsAsync_OnlyReleasesSoftDeletedOfferings() + { + var websites = Category("Websites", 0); + await _sut.AddAsync(websites); + var live = Offering("Live", websites.Id); + var gone = Offering("Gone", websites.Id, deleted: true); + _context.Offerings.AddRange(live, gone); + await _context.SaveChangesAsync(); + + await _sut.ClearCategoryOnDeletedOfferingsAsync(websites.Id); + await _context.SaveChangesAsync(); + _context.ChangeTracker.Clear(); + + var all = await _context.Offerings.IgnoreQueryFilters().ToListAsync(); + all.Single(o => o.Title == "Live").CategoryId.Should().Be(websites.Id); + all.Single(o => o.Title == "Gone").CategoryId.Should().BeNull(); + } + + [Fact] + public async Task CountOfferingsAsync_IgnoresSoftDeletedOfferings() + { + var websites = Category("Websites", 0); + await _sut.AddAsync(websites); + _context.Offerings.AddRange(Offering("Live", websites.Id), Offering("Gone", websites.Id, deleted: true)); + await _context.SaveChangesAsync(); + + (await _sut.CountOfferingsAsync(websites.Id)).Should().Be(1); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingCategoriesServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingCategoriesServiceTests.cs new file mode 100644 index 0000000..d8a9b10 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingCategoriesServiceTests.cs @@ -0,0 +1,148 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Logging; +using NSubstitute; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Repositories; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Services; + +public class OfferingCategoriesServiceTests +{ + private readonly IOfferingCategoryRepository _repo = Substitute.For(); + + public OfferingCategoriesServiceTests() + { + _repo.BeginTransactionAsync().Returns(Substitute.For()); + _repo.GetMaxSortOrderAsync().Returns(-1); + } + + private OfferingCategoriesService CreateSut() + => new(_repo, Substitute.For>()); + + private static OfferingCategory Category(string name, int order = 0) => new() + { + Id = Guid.NewGuid(), + Name = name, + SortOrder = order, + }; + + [Fact] + public async Task ListAsync_ReturnsNamesInRepositoryOrder_WithCounts() + { + _repo.ListAsync().Returns([ + new CategoryWithCount(Category("Websites", 0), 2), + new CategoryWithCount(Category("Onderhoud", 1), 0), + ]); + + var result = await CreateSut().ListAsync(); + + result.Select(c => (c.Name, c.OfferingCount)).Should().Equal(("Websites", 2), ("Onderhoud", 0)); + } + + [Fact] + public async Task CreateAsync_TrimsTheName_AppendsToTheEnd_AndSaves() + { + _repo.GetMaxSortOrderAsync().Returns(4); + + var dto = await CreateSut().CreateAsync(" Websites "); + + dto.Name.Should().Be("Websites"); + dto.SortOrder.Should().Be(5); + dto.OfferingCount.Should().Be(0); + await _repo.Received(1).AddAsync(Arg.Is(c => c.Name == "Websites")); + await _repo.Received(1).SaveChangesAsync(); + } + + [Fact] + public async Task CreateAsync_Throws_AndSavesNothing_WhenTheNameIsTaken() + { + _repo.ExistsByNameAsync("Websites").Returns(true); + + var act = () => CreateSut().CreateAsync("Websites"); + + await act.Should().ThrowAsync(); + await _repo.DidNotReceive().AddAsync(Arg.Any()); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task RenameAsync_ReturnsNull_WhenUnknown() + { + _repo.GetByIdAsync(Arg.Any()).Returns((OfferingCategory?)null); + + var result = await CreateSut().RenameAsync(Guid.NewGuid(), "Nieuw"); + + result.Should().BeNull(); + } + + [Fact] + public async Task RenameAsync_ChangesTheName_AndReportsTheUsage() + { + var category = Category("Oud"); + _repo.GetByIdAsync(category.Id).Returns(category); + _repo.CountOfferingsAsync(category.Id).Returns(3); + + var dto = await CreateSut().RenameAsync(category.Id, " Nieuw "); + + category.Name.Should().Be("Nieuw"); + dto!.Name.Should().Be("Nieuw"); + dto.OfferingCount.Should().Be(3); + await _repo.Received(1).SaveChangesAsync(); + } + + [Fact] + public async Task RenameAsync_Throws_WhenAnotherCategoryHasTheName() + { + var category = Category("Oud"); + _repo.GetByIdAsync(category.Id).Returns(category); + _repo.ExistsByNameAsync("Websites", category.Id).Returns(true); + + var act = () => CreateSut().RenameAsync(category.Id, "Websites"); + + await act.Should().ThrowAsync(); + category.Name.Should().Be("Oud"); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task DeleteAsync_ReturnsFalse_WhenUnknown() + { + _repo.GetByIdAsync(Arg.Any()).Returns((OfferingCategory?)null); + + (await CreateSut().DeleteAsync(Guid.NewGuid())).Should().BeFalse(); + } + + [Fact] + public async Task DeleteAsync_Throws_AndDeletesNothing_WhileOfferingsUseTheCategory() + { + var category = Category("Websites"); + _repo.GetByIdAsync(category.Id).Returns(category); + _repo.CountOfferingsAsync(category.Id).Returns(2); + + var act = () => CreateSut().DeleteAsync(category.Id); + + await act.Should().ThrowAsync(); + _repo.DidNotReceive().Remove(Arg.Any()); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task DeleteAsync_ReleasesSoftDeletedOfferings_ThenRemovesTheCategory() + { + var category = Category("Websites"); + _repo.GetByIdAsync(category.Id).Returns(category); + _repo.CountOfferingsAsync(category.Id).Returns(0); + + var deleted = await CreateSut().DeleteAsync(category.Id); + + deleted.Should().BeTrue(); + Received.InOrder(() => + { + _repo.ClearCategoryOnDeletedOfferingsAsync(category.Id); + _repo.Remove(category); + _repo.SaveChangesAsync(); + }); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceCategoryTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceCategoryTests.cs new file mode 100644 index 0000000..8411677 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceCategoryTests.cs @@ -0,0 +1,139 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Logging; +using NSubstitute; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Repositories; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Services; + +public class OfferingsServiceCategoryTests +{ + private readonly IOfferingRepository _repo = Substitute.For(); + private readonly IOfferingCategoryRepository _categories = Substitute.For(); + + public OfferingsServiceCategoryTests() + { + _repo.BeginTransactionAsync().Returns(Substitute.For()); + _repo.GetMaxDisplayOrderAsync().Returns(-1); + } + + private OfferingsService CreateSut() + => new(_repo, _categories, Substitute.For>()); + + private static OfferingCategory Category(string name) => new() { Id = Guid.NewGuid(), Name = name }; + + private static CreateOfferingRequest Create(Guid? categoryId) => new( + "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", CategoryId: categoryId); + + private static UpdateOfferingRequest Update(Guid? categoryId) => new( + "Existing", "Description", "€ 100", "per month", ["Feature 1"], "Contact", CategoryId: categoryId); + + private static Offering Existing(OfferingCategory? category) => new() + { + Id = Guid.NewGuid(), + Slug = "existing", + Title = "Existing", + Description = "Description", + Price = "€ 100", + PriceNote = "per month", + Features = ["Feature 1"], + CtaLabel = "Contact", + CategoryId = category?.Id, + Category = category, + }; + + [Fact] + public async Task CreateAsync_StoresTheCategory_AndReturnsIdAndName() + { + var websites = Category("Websites"); + _categories.GetByIdAsync(websites.Id).Returns(websites); + + var dto = await CreateSut().CreateAsync(Create(websites.Id), Guid.NewGuid()); + + dto.CategoryId.Should().Be(websites.Id.ToString()); + dto.Category.Should().Be("Websites"); + await _repo.Received(1).AddAsync(Arg.Is(o => o.CategoryId == websites.Id)); + } + + [Fact] + public async Task CreateAsync_WithoutCategory_HasNullCategoryFields() + { + var dto = await CreateSut().CreateAsync(Create(null), Guid.NewGuid()); + + dto.CategoryId.Should().BeNull(); + dto.Category.Should().BeNull(); + await _categories.DidNotReceive().GetByIdAsync(Arg.Any()); + } + + [Fact] + public async Task CreateAsync_Throws_AndSavesNothing_WhenTheCategoryDoesNotExist() + { + _categories.GetByIdAsync(Arg.Any()).Returns((OfferingCategory?)null); + + var act = () => CreateSut().CreateAsync(Create(Guid.NewGuid()), Guid.NewGuid()); + + await act.Should().ThrowAsync(); + await _repo.DidNotReceive().AddAsync(Arg.Any()); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task UpdateAsync_MovesTheOfferingToAnotherCategory() + { + var websites = Category("Websites"); + var onderhoud = Category("Onderhoud"); + var target = Existing(websites); + _repo.GetByIdAsync(target.Id).Returns(target); + _categories.GetByIdAsync(onderhoud.Id).Returns(onderhoud); + + var dto = await CreateSut().UpdateAsync(target.Id, Update(onderhoud.Id), Guid.NewGuid()); + + dto!.Category.Should().Be("Onderhoud"); + target.CategoryId.Should().Be(onderhoud.Id); + } + + [Fact] + public async Task UpdateAsync_ClearsTheCategory_WhenNull() + { + var target = Existing(Category("Websites")); + _repo.GetByIdAsync(target.Id).Returns(target); + + var dto = await CreateSut().UpdateAsync(target.Id, Update(null), Guid.NewGuid()); + + dto!.CategoryId.Should().BeNull(); + dto.Category.Should().BeNull(); + target.CategoryId.Should().BeNull(); + } + + [Fact] + public async Task UpdateAsync_Throws_AndChangesNothing_WhenTheCategoryDoesNotExist() + { + var websites = Category("Websites"); + var target = Existing(websites); + _repo.GetByIdAsync(target.Id).Returns(target); + _categories.GetByIdAsync(Arg.Any()).Returns((OfferingCategory?)null); + + var act = () => CreateSut().UpdateAsync(target.Id, Update(Guid.NewGuid()), Guid.NewGuid()); + + await act.Should().ThrowAsync(); + target.CategoryId.Should().Be(websites.Id); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task GetOfferingsAsync_CarriesTheCategoryName_SoARenameShowsUpImmediately() + { + var websites = Category("Websites"); + _repo.GetAllAsync().Returns([Existing(websites)]); + var sut = CreateSut(); + + (await sut.GetOfferingsAsync())[0].Category.Should().Be("Websites"); + + websites.Name = "Webdesign"; + + (await sut.GetOfferingsAsync())[0].Category.Should().Be("Webdesign"); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs index 9fc2d87..1140bd2 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs @@ -17,7 +17,7 @@ public class OfferingsServiceOrderTests _repo.BeginTransactionAsync().Returns(Substitute.For()); } - private OfferingsService CreateSut() => new(_repo, Substitute.For>()); + private OfferingsService CreateSut() => new(_repo, Substitute.For(), Substitute.For>()); private static Offering New(int order) => new() { diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs index 2046fce..68689b8 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs @@ -19,7 +19,7 @@ public class OfferingsServiceTests _repo.BeginTransactionAsync().Returns(Substitute.For()); } - private OfferingsService CreateSut() => new(_repo, _logger); + private OfferingsService CreateSut() => new(_repo, Substitute.For(), _logger); private static CreateOfferingRequest CreateRequest(bool featured = false) => new( "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", featured); diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingCategoriesController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingCategoriesController.cs new file mode 100644 index 0000000..1a363de --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingCategoriesController.cs @@ -0,0 +1,64 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Controllers; + +/// +/// Categories offerings can be placed in. Managed by administrators only; visitors see the +/// category name on the offerings themselves. +/// +[ApiController] +[Route("offerings/categories")] +[Authorize(Policy = "AdminOnly")] +public class OfferingCategoriesController(IOfferingCategoriesService service) : ControllerBase +{ + [HttpGet] + public async Task List() => Ok(await service.ListAsync()); + + [HttpPost] + public async Task Create([FromBody] OfferingCategoryRequest request) + { + try + { + var dto = await service.CreateAsync(request.Name); + return Created($"/api/v1/offerings/categories/{dto.Id}", dto); + } + catch (OfferingCategoryNameConflictException ex) + { + return Conflict(Problem409(ex.Message)); + } + } + + [HttpPut("{id:guid}")] + public async Task Rename(Guid id, [FromBody] OfferingCategoryRequest request) + { + try + { + var dto = await service.RenameAsync(id, request.Name); + return dto is null ? NotFound() : Ok(dto); + } + catch (OfferingCategoryNameConflictException ex) + { + return Conflict(Problem409(ex.Message)); + } + } + + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id) + { + try + { + return await service.DeleteAsync(id) ? NoContent() : NotFound(); + } + catch (OfferingCategoryInUseException ex) + { + return Conflict(Problem409(ex.Message)); + } + } + + private static ProblemDetails Problem409(string title) + => new() { Status = StatusCodes.Status409Conflict, Title = title }; +} diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs index a9750ed..8d170d4 100644 --- a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs @@ -35,6 +35,10 @@ public class OfferingsController(IOfferingsService service) : ControllerBase var dto = await service.CreateAsync(request, GetCallerId()); return Created($"/api/v1/offerings/{dto.Id}", dto); } + catch (OfferingCategoryInvalidException) + { + return InvalidCategory(); + } catch (OfferingSlugConflictException ex) { return Conflict(new ProblemDetails { Status = StatusCodes.Status409Conflict, Title = ex.Message }); @@ -49,6 +53,10 @@ public class OfferingsController(IOfferingsService service) : ControllerBase var dto = await service.UpdateAsync(id, request, GetCallerId()); return dto is null ? NotFound() : Ok(dto); } + catch (OfferingCategoryInvalidException) + { + return InvalidCategory(); + } catch (OfferingSlugConflictException ex) { return Conflict(new ProblemDetails { Status = StatusCodes.Status409Conflict, Title = ex.Message }); @@ -80,6 +88,13 @@ public class OfferingsController(IOfferingsService service) : ControllerBase } } + private IActionResult InvalidCategory() => BadRequest(new ValidationProblemDetails( + new Dictionary { ["categoryId"] = ["invalid"] }) + { + Status = StatusCodes.Status400BadRequest, + Title = "Invalid category", + }); + private Guid GetCallerId() { var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"); diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs index 0825584..12f87eb 100644 --- a/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs +++ b/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs @@ -11,6 +11,8 @@ public class Offering public List Features { get; set; } = []; public string CtaLabel { get; set; } = string.Empty; public bool Featured { get; set; } + public Guid? CategoryId { get; set; } + public OfferingCategory? Category { get; set; } public int DisplayOrder { get; set; } public bool IsDeleted { get; set; } public DateTimeOffset? DeletedAt { get; set; } diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingCategory.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingCategory.cs new file mode 100644 index 0000000..5052b28 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingCategory.cs @@ -0,0 +1,16 @@ +namespace SlpModularCms.Modules.Offerings.Data.Entities; + +/// +/// A category an offering can be placed in. Managed in the CMS (never seeded in code). +/// +public class OfferingCategory +{ + public Guid Id { get; set; } + + /// Display name; unique, compared case-insensitively. + public string Name { get; set; } = string.Empty; + + public int SortOrder { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset UpdatedAt { get; set; } +} diff --git a/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs b/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs index 84444d0..d4a959e 100644 --- a/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs +++ b/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs @@ -8,6 +8,7 @@ namespace SlpModularCms.Modules.Offerings.Data; public class OfferingsDbContext(DbContextOptions options) : DbContext(options) { public DbSet Offerings => Set(); + public DbSet OfferingCategories => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -41,7 +42,29 @@ public class OfferingsDbContext(DbContextOptions options) : v => v.Aggregate(0, (hash, item) => HashCode.Combine(hash, item.GetHashCode())), v => v.ToList())); + // Restrict: a category cannot be deleted while any offering still points at it. The + // service releases soft-deleted offerings first and rejects deletion while live + // offerings use the category. + entity.HasOne(e => e.Category) + .WithMany() + .HasForeignKey(e => e.CategoryId) + .OnDelete(DeleteBehavior.Restrict); + entity.HasQueryFilter(e => !e.IsDeleted); }); + + modelBuilder.Entity(entity => + { + entity.ToTable("OfferingsCategories"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Name).IsRequired().HasMaxLength(100); + entity.Property(e => e.SortOrder).IsRequired(); + entity.Property(e => e.CreatedAt).IsRequired(); + entity.Property(e => e.UpdatedAt).IsRequired(); + + // MySQL's default collation is case-insensitive, so this also enforces + // case-insensitive uniqueness; the service checks it explicitly as well. + entity.HasIndex(e => e.Name).IsUnique(); + }); } } diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.Designer.cs b/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.Designer.cs new file mode 100644 index 0000000..9941931 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.Designer.cs @@ -0,0 +1,136 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Offerings.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Offerings.Migrations +{ + [DbContext(typeof(OfferingsDbContext))] + [Migration("20261109193305_AddOfferingCategories")] + partial class AddOfferingCategories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CategoryId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CtaLabel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("DeletedAt") + .HasColumnType("datetime"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Featured") + .HasColumnType("tinyint(1)"); + + b.Property("Features") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("Price") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("PriceNote") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(130) + .HasColumnType("varchar(130)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("CategoryId"); + + b.ToTable("OfferingsOfferings", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("OfferingsCategories", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.HasOne("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", "Category") + .WithMany() + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Category"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.cs b/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.cs new file mode 100644 index 0000000..b8dd6cc --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.cs @@ -0,0 +1,75 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Offerings.Migrations +{ + /// + public partial class AddOfferingCategories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "CategoryId", + table: "OfferingsOfferings", + type: "char(36)", + nullable: true); + + migrationBuilder.CreateTable( + name: "OfferingsCategories", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + Name = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + SortOrder = table.Column(type: "int", nullable: false), + CreatedAt = table.Column(type: "datetime", nullable: false), + UpdatedAt = table.Column(type: "datetime", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OfferingsCategories", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_OfferingsOfferings_CategoryId", + table: "OfferingsOfferings", + column: "CategoryId"); + + migrationBuilder.CreateIndex( + name: "IX_OfferingsCategories_Name", + table: "OfferingsCategories", + column: "Name", + unique: true); + + migrationBuilder.AddForeignKey( + name: "FK_OfferingsOfferings_OfferingsCategories_CategoryId", + table: "OfferingsOfferings", + column: "CategoryId", + principalTable: "OfferingsCategories", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_OfferingsOfferings_OfferingsCategories_CategoryId", + table: "OfferingsOfferings"); + + migrationBuilder.DropTable( + name: "OfferingsCategories"); + + migrationBuilder.DropIndex( + name: "IX_OfferingsOfferings_CategoryId", + table: "OfferingsOfferings"); + + migrationBuilder.DropColumn( + name: "CategoryId", + table: "OfferingsOfferings"); + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs index 9484838..48b2e91 100644 --- a/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs @@ -25,6 +25,9 @@ namespace SlpModularCms.Modules.Offerings.Migrations .ValueGeneratedOnAdd() .HasColumnType("char(36)"); + b.Property("CategoryId") + .HasColumnType("char(36)"); + b.Property("CreatedAt") .HasColumnType("datetime"); @@ -82,8 +85,48 @@ namespace SlpModularCms.Modules.Offerings.Migrations b.HasKey("Id"); + b.HasIndex("CategoryId"); + b.ToTable("OfferingsOfferings", (string)null); }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("OfferingsCategories", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.HasOne("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", "Category") + .WithMany() + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Category"); + }); #pragma warning restore 612, 618 } } diff --git a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs index fcaf2e6..05d0a63 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs @@ -10,5 +10,6 @@ public record CreateOfferingRequest( [Required, FeaturesValidation] List Features, [Required, MaxLength(50)] string CtaLabel, bool Featured = false, - [MaxLength(130)] string? Slug = null + [MaxLength(130)] string? Slug = null, + Guid? CategoryId = null ); diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingCategoryModels.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingCategoryModels.cs new file mode 100644 index 0000000..3edf5f7 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingCategoryModels.cs @@ -0,0 +1,9 @@ +using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; + +namespace SlpModularCms.Modules.Offerings.Models; + +[ExcludeFromCodeCoverage] +public record OfferingCategoryDto(string Id, string Name, int SortOrder, int OfferingCount); + +public record OfferingCategoryRequest([Required, MaxLength(100)] string Name); diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs index 13e170b..ecabd11 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs @@ -17,5 +17,7 @@ public record OfferingDto( IReadOnlyList Features, string CtaLabel, bool Featured, - int DisplayOrder + int DisplayOrder, + string? CategoryId = null, + string? Category = null ); diff --git a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs index 542d025..1daf976 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs @@ -10,5 +10,6 @@ public record UpdateOfferingRequest( [Required, FeaturesValidation] List Features, [Required, MaxLength(50)] string CtaLabel, bool Featured = false, - [MaxLength(130)] string? Slug = null + [MaxLength(130)] string? Slug = null, + Guid? CategoryId = null ); diff --git a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs index 058975d..649b6db 100644 --- a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs +++ b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs @@ -29,6 +29,8 @@ public class OfferingsModule : IModule services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddHttpContextAccessor(); } diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingCategoryRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingCategoryRepository.cs new file mode 100644 index 0000000..ef155ee --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingCategoryRepository.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Storage; +using SlpModularCms.Modules.Offerings.Data.Entities; + +namespace SlpModularCms.Modules.Offerings.Repositories; + +public record CategoryWithCount(OfferingCategory Category, int OfferingCount); + +public interface IOfferingCategoryRepository +{ + /// All categories ordered by sort order then name, with the number of non-deleted offerings in each. + Task> ListAsync(); + + Task GetByIdAsync(Guid id); + + /// Case-insensitive name check; skips the category being renamed. + Task ExistsByNameAsync(string name, Guid? excludeId = null); + + Task GetMaxSortOrderAsync(); + Task CountOfferingsAsync(Guid categoryId); + + /// Clears the category on soft-deleted offerings that still point to it (so the FK no longer blocks deletion). + Task ClearCategoryOnDeletedOfferingsAsync(Guid categoryId); + + Task AddAsync(OfferingCategory category); + void Remove(OfferingCategory category); + Task SaveChangesAsync(); + Task BeginTransactionAsync(); +} diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingCategoryRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingCategoryRepository.cs new file mode 100644 index 0000000..6bfda37 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingCategoryRepository.cs @@ -0,0 +1,69 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using SlpModularCms.Modules.Offerings.Data; +using SlpModularCms.Modules.Offerings.Data.Entities; + +namespace SlpModularCms.Modules.Offerings.Repositories; + +public class OfferingCategoryRepository(OfferingsDbContext context) : IOfferingCategoryRepository +{ + public async Task> ListAsync() + { + var categories = await context.OfferingCategories + .OrderBy(c => c.SortOrder) + .ThenBy(c => c.Name) + .ToListAsync(); + + // The Offering query filter already excludes soft-deleted offerings. + var counts = await context.Offerings + .Where(o => o.CategoryId != null) + .GroupBy(o => o.CategoryId!.Value) + .Select(g => new { CategoryId = g.Key, Count = g.Count() }) + .ToDictionaryAsync(x => x.CategoryId, x => x.Count); + + return categories + .Select(c => new CategoryWithCount(c, counts.GetValueOrDefault(c.Id))) + .ToList(); + } + + public async Task GetByIdAsync(Guid id) + => await context.OfferingCategories.FirstOrDefaultAsync(c => c.Id == id); + + public async Task ExistsByNameAsync(string name, Guid? excludeId = null) + { + var lowered = name.ToLower(); + return await context.OfferingCategories + .AnyAsync(c => c.Name.ToLower() == lowered && c.Id != (excludeId ?? Guid.Empty)); + } + + public async Task GetMaxSortOrderAsync() + => await context.OfferingCategories.Select(c => (int?)c.SortOrder).MaxAsync() ?? -1; + + public async Task CountOfferingsAsync(Guid categoryId) + => await context.Offerings.CountAsync(o => o.CategoryId == categoryId); + + public async Task ClearCategoryOnDeletedOfferingsAsync(Guid categoryId) + { + var deleted = await context.Offerings + .IgnoreQueryFilters() + .Where(o => o.IsDeleted && o.CategoryId == categoryId) + .ToListAsync(); + + foreach (var offering in deleted) + { + offering.CategoryId = null; + } + } + + public async Task AddAsync(OfferingCategory category) + => await context.OfferingCategories.AddAsync(category); + + public void Remove(OfferingCategory category) + => context.OfferingCategories.Remove(category); + + public async Task SaveChangesAsync() + => await context.SaveChangesAsync(); + + public async Task BeginTransactionAsync() + => await context.Database.BeginTransactionAsync(); +} diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs index d6de447..7a18382 100644 --- a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs @@ -8,10 +8,10 @@ namespace SlpModularCms.Modules.Offerings.Repositories; public class OfferingRepository(OfferingsDbContext context) : IOfferingRepository { public async Task> GetAllAsync() - => await context.Offerings.OrderBy(o => o.DisplayOrder).ToListAsync(); + => await context.Offerings.Include(o => o.Category).OrderBy(o => o.DisplayOrder).ToListAsync(); public async Task GetByIdAsync(Guid id) - => await context.Offerings.FirstOrDefaultAsync(o => o.Id == id); + => await context.Offerings.Include(o => o.Category).FirstOrDefaultAsync(o => o.Id == id); public async Task ExistsBySlugAsync(string slug, Guid? excludeId = null) => await context.Offerings.AnyAsync(o => o.Slug == slug && o.Id != (excludeId ?? Guid.Empty)); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoriesService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoriesService.cs new file mode 100644 index 0000000..a5df0d2 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoriesService.cs @@ -0,0 +1,91 @@ +using Microsoft.Extensions.Logging; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Repositories; + +namespace SlpModularCms.Modules.Offerings.Services; + +public interface IOfferingCategoriesService +{ + Task> ListAsync(); + Task CreateAsync(string name); + Task RenameAsync(Guid id, string name); + Task DeleteAsync(Guid id); +} + +public class OfferingCategoriesService( + IOfferingCategoryRepository repository, + ILogger logger) : IOfferingCategoriesService +{ + public async Task> ListAsync() + { + var categories = await repository.ListAsync(); + return categories.Select(c => ToDto(c.Category, c.OfferingCount)).ToList(); + } + + public async Task CreateAsync(string name) + { + var trimmed = name.Trim(); + if (await repository.ExistsByNameAsync(trimmed)) + throw new OfferingCategoryNameConflictException(trimmed); + + var now = DateTimeOffset.UtcNow; + var category = new OfferingCategory + { + Id = Guid.NewGuid(), + Name = trimmed, + SortOrder = await repository.GetMaxSortOrderAsync() + 1, + CreatedAt = now, + UpdatedAt = now, + }; + + await repository.AddAsync(category); + await repository.SaveChangesAsync(); + + logger.LogInformation("Offering category {CategoryId} created", category.Id); + return ToDto(category, 0); + } + + public async Task RenameAsync(Guid id, string name) + { + var category = await repository.GetByIdAsync(id); + if (category is null) + return null; + + var trimmed = name.Trim(); + if (await repository.ExistsByNameAsync(trimmed, excludeId: id)) + throw new OfferingCategoryNameConflictException(trimmed); + + category.Name = trimmed; + category.UpdatedAt = DateTimeOffset.UtcNow; + await repository.SaveChangesAsync(); + + logger.LogInformation("Offering category {CategoryId} renamed", category.Id); + return ToDto(category, await repository.CountOfferingsAsync(id)); + } + + public async Task DeleteAsync(Guid id) + { + var category = await repository.GetByIdAsync(id); + if (category is null) + return false; + + var inUse = await repository.CountOfferingsAsync(id); + if (inUse > 0) + throw new OfferingCategoryInUseException(inUse); + + // Soft-deleted offerings may still point at the category; release them so the FK + // (Restrict) no longer blocks the deletion. Both steps succeed or fail together. + await using var transaction = await repository.BeginTransactionAsync(); + await repository.ClearCategoryOnDeletedOfferingsAsync(id); + repository.Remove(category); + await repository.SaveChangesAsync(); + await transaction.CommitAsync(); + + logger.LogInformation("Offering category {CategoryId} deleted", id); + return true; + } + + private static OfferingCategoryDto ToDto(OfferingCategory c, int offeringCount) + => new(c.Id.ToString(), c.Name, c.SortOrder, offeringCount); +} diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoryExceptions.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoryExceptions.cs new file mode 100644 index 0000000..bcfbb5a --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoryExceptions.cs @@ -0,0 +1,12 @@ +namespace SlpModularCms.Modules.Offerings.Services; + +/// Thrown when an offering refers to a category that does not exist. +public class OfferingCategoryInvalidException() : Exception("The category does not exist."); + +/// Thrown when a category name is already taken (case-insensitive). +public class OfferingCategoryNameConflictException(string name) + : Exception($"A category named '{name}' already exists."); + +/// Thrown when a category that is still used by offerings is deleted. +public class OfferingCategoryInUseException(int offeringCount) + : Exception($"The category is still used by {offeringCount} offering(s). Move them to another category first."); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs index d1df084..bcb5196 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs @@ -5,7 +5,10 @@ using SlpModularCms.Modules.Offerings.Repositories; namespace SlpModularCms.Modules.Offerings.Services; -public class OfferingsService(IOfferingRepository repository, ILogger logger) : IOfferingsService +public class OfferingsService( + IOfferingRepository repository, + IOfferingCategoryRepository categories, + ILogger logger) : IOfferingsService { public async Task> GetOfferingsAsync() { @@ -15,6 +18,7 @@ public class OfferingsService(IOfferingRepository repository, ILogger CreateAsync(CreateOfferingRequest request, Guid callerId) { + var category = await ResolveCategoryAsync(request.CategoryId); var now = DateTimeOffset.UtcNow; var offering = new Offering { @@ -26,6 +30,8 @@ public class OfferingsService(IOfferingRepository repository, ILogger ResolveCategoryAsync(Guid? categoryId) + { + if (categoryId is null) + return null; + + return await categories.GetByIdAsync(categoryId.Value) + ?? throw new OfferingCategoryInvalidException(); + } + private async Task ResolveSlugAsync(string? explicitSlug, string title) => !string.IsNullOrWhiteSpace(explicitSlug) ? await ResolveExplicitSlugAsync(explicitSlug, excludeId: null) @@ -216,6 +235,8 @@ public class OfferingsService(IOfferingRepository repository, ILogger