Adds the Offerings module and retargets the CI/CD pipeline to Api.SlpSoftware
Continuous Integration / config (pull_request) Successful in 12s
Continuous Integration / changes (pull_request) Successful in 22s
Continuous Integration / backend-build (pull_request) Successful in 5m53s
Continuous Integration / vulnerability-scan (pull_request) Successful in 5m46s
Continuous Integration / frontend-prepare (pull_request) Successful in 1m54s
Continuous Integration / backend-test (pull_request) Successful in 7m37s
Continuous Integration / frontend-build (pull_request) Successful in 2m14s
Continuous Integration / frontend-test (pull_request) Successful in 4m59s
Continuous Integration / frontend-lint (pull_request) Successful in 2m2s
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped
Continuous Integration / publish-test (pull_request) Successful in 7m34s
Continuous Integration / deploy-test (pull_request) Skipped

Implements Unit 2 "Offerings" (backend module, admin CRUD UI with
drag-and-drop reordering, public GET /api/v1/offerings endpoint) and
executes the feature's D-15 CI/CD cutover, switching the deploy
pipeline's build/publish target from SlpModularCms.Api to
SlpModularCms.Api.SlpSoftware.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FWyStNL2ZsjrS7FLd7xvvN
This commit is contained in:
2026-08-02 16:23:09 +02:00
co-authored by Claude Sonnet 5
parent b6e9c07c06
commit cfb06b28b6
79 changed files with 4069 additions and 94 deletions
@@ -22,6 +22,7 @@
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
</ItemGroup>
<!--
@@ -34,12 +34,19 @@
"MasterUrl": "https://localhost:7223"
},
"Cors": {
// Port 5175, not 5173: that's Api's own frontend dev port (see frontend/package.json's
// plain `pnpm dev`). This project is reached via `pnpm dev:slpsoftware`, which runs the
// frontend dev server on 5175 (see .env.slpsoftware.local / package.json).
// 5175: this repo's admin frontend, reached via `pnpm dev:slpsoftware` (see
// .env.slpsoftware.local / package.json) — NOT the same as 5173, which is Api's own
// (Master) admin frontend dev port and would be the wrong origin to allow here.
// 5173: the actual public SlpSoftware website (separate repo/workspace,
// K:\Development\SlpSoftware\Projects\SlpSoftware), calling the anonymous
// GET /api/v1/offerings endpoint from its own Vite dev server. Coincidentally the same
// port number as Api's admin frontend above, but a different codebase/origin entirely —
// both need to be allowed here since Api.SlpSoftware serves both consumers.
"AllowedOrigins": [
"http://localhost:5175",
"https://localhost:5175"
"https://localhost:5175",
"http://localhost:5173",
"https://localhost:5173"
]
},
"RateLimiting": {
@@ -48,6 +48,10 @@
"SentryTunnel": {
"PermitLimit": 60,
"WindowSeconds": 60
},
"OfferingsPublic": {
"PermitLimit": 120,
"WindowSeconds": 60
}
},
"SecurityHeaders": {
@@ -184,6 +184,17 @@ public static class ServiceCollectionExtensions
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
opt.QueueLimit = 0;
});
// Guards the anonymous public offerings listing (NFR-OFF-01) against scraping.
// Only the public GET carries this policy — admin mutation endpoints are already
// behind AdminOnly authentication (Offerings NFR Requirements Q1 = A).
options.AddFixedWindowLimiter("offerings-public", opt =>
{
var settings = configuration.GetSection("RateLimiting:OfferingsPublic");
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 120);
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
opt.QueueLimit = 0;
});
});
return services;
@@ -0,0 +1,144 @@
using System.Security.Claims;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using SlpModularCms.Modules.Offerings.Controllers;
using SlpModularCms.Modules.Offerings.Models;
using SlpModularCms.Modules.Offerings.Services;
namespace SlpModularCms.Modules.Offerings.Tests.Controllers;
public class OfferingsControllerTests
{
private readonly IOfferingsService _service = Substitute.For<IOfferingsService>();
private OfferingsController CreateSut()
{
var httpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(
[new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuth")),
};
return new OfferingsController(_service) { ControllerContext = new ControllerContext { HttpContext = httpContext } };
}
private static OfferingDto PublicDto() => new(
Guid.NewGuid().ToString(), "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false);
private static OfferingAdminDto AdminDto(int displayOrder = 0) => new(
Guid.NewGuid().ToString(), "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false, displayOrder);
private static CreateOfferingRequest CreateRequest() => new(
"Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact");
private static UpdateOfferingRequest UpdateRequest() => new(
"Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact");
// --- GetOfferings (public) ---
[Fact]
public async Task GetOfferings_Returns200_WithList()
{
_service.GetPublicOfferingsAsync().Returns([PublicDto()]);
var result = await CreateSut().GetOfferings();
result.Should().BeOfType<OkObjectResult>().Which.StatusCode.Should().Be(200);
}
// --- GetAllForAdmin ---
[Fact]
public async Task GetAllForAdmin_Returns200_WithList()
{
_service.GetAllForAdminAsync().Returns([AdminDto()]);
var result = await CreateSut().GetAllForAdmin();
result.Should().BeOfType<OkObjectResult>().Which.StatusCode.Should().Be(200);
}
// --- Create ---
[Fact]
public async Task Create_Returns201Created()
{
_service.CreateAsync(Arg.Any<CreateOfferingRequest>(), Arg.Any<Guid>()).Returns(AdminDto());
var result = await CreateSut().Create(CreateRequest());
result.Should().BeOfType<CreatedAtActionResult>().Which.StatusCode.Should().Be(201);
}
// --- Update ---
[Fact]
public async Task Update_Returns200_WhenFound()
{
_service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>()).Returns(AdminDto());
var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest());
result.Should().BeOfType<OkObjectResult>().Which.StatusCode.Should().Be(200);
}
[Fact]
public async Task Update_Returns404_WhenNotFound()
{
_service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>())
.Returns((OfferingAdminDto?)null);
var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest());
result.Should().BeOfType<NotFoundResult>();
}
// --- Delete ---
[Fact]
public async Task Delete_Returns204_WhenDeleted()
{
_service.DeleteAsync(Arg.Any<Guid>(), Arg.Any<Guid>()).Returns(true);
var result = await CreateSut().Delete(Guid.NewGuid());
result.Should().BeOfType<NoContentResult>();
}
[Fact]
public async Task Delete_Returns404_WhenNotFound()
{
_service.DeleteAsync(Arg.Any<Guid>(), Arg.Any<Guid>()).Returns(false);
var result = await CreateSut().Delete(Guid.NewGuid());
result.Should().BeOfType<NotFoundResult>();
}
// --- Reorder / MoveUp / MoveDown ---
[Fact]
public async Task Reorder_Returns204()
{
var result = await CreateSut().Reorder(new ReorderOfferingsRequest([Guid.NewGuid()]));
result.Should().BeOfType<NoContentResult>();
}
[Fact]
public async Task MoveUp_Returns204()
{
var result = await CreateSut().MoveUp(Guid.NewGuid());
result.Should().BeOfType<NoContentResult>();
}
[Fact]
public async Task MoveDown_Returns204()
{
var result = await CreateSut().MoveDown(Guid.NewGuid());
result.Should().BeOfType<NoContentResult>();
}
}
@@ -0,0 +1,186 @@
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 OfferingRepositoryTests : IDisposable
{
private readonly OfferingsDbContext _context;
private readonly OfferingRepository _sut;
public OfferingRepositoryTests()
{
var options = new DbContextOptionsBuilder<OfferingsDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
_context = new OfferingsDbContext(options);
_sut = new OfferingRepository(_context);
}
[Fact]
public async Task GetAllAsync_OrdersByDisplayOrder()
{
await _sut.AddAsync(Offering("B", displayOrder: 1));
await _sut.AddAsync(Offering("A", displayOrder: 0));
await _sut.SaveChangesAsync();
var result = await _sut.GetAllAsync();
result.Select(o => o.Title).Should().ContainInOrder("A", "B");
}
[Fact]
public async Task GetAllAsync_ExcludesSoftDeleted()
{
var deleted = Offering("Deleted", displayOrder: 0);
deleted.IsDeleted = true;
await _sut.AddAsync(deleted);
await _sut.AddAsync(Offering("Active", displayOrder: 1));
await _sut.SaveChangesAsync();
var result = await _sut.GetAllAsync();
result.Should().ContainSingle(o => o.Title == "Active");
}
[Fact]
public async Task GetByIdAsync_ReturnsNull_WhenSoftDeleted()
{
var offering = Offering("Deleted", displayOrder: 0);
offering.IsDeleted = true;
await _sut.AddAsync(offering);
await _sut.SaveChangesAsync();
var result = await _sut.GetByIdAsync(offering.Id);
result.Should().BeNull();
}
[Fact]
public async Task GetMaxDisplayOrderAsync_ReturnsMinusOne_WhenEmpty()
{
var result = await _sut.GetMaxDisplayOrderAsync();
result.Should().Be(-1);
}
[Fact]
public async Task GetMaxDisplayOrderAsync_ReturnsHighestValue()
{
await _sut.AddAsync(Offering("A", displayOrder: 3));
await _sut.AddAsync(Offering("B", displayOrder: 7));
await _sut.SaveChangesAsync();
var result = await _sut.GetMaxDisplayOrderAsync();
result.Should().Be(7);
}
[Fact]
public async Task GetFeaturedAsync_ReturnsFeaturedOffering()
{
var featured = Offering("Featured", displayOrder: 0);
featured.Featured = true;
await _sut.AddAsync(featured);
await _sut.AddAsync(Offering("Other", displayOrder: 1));
await _sut.SaveChangesAsync();
var result = await _sut.GetFeaturedAsync();
result.Should().NotBeNull();
result!.Title.Should().Be("Featured");
}
[Fact]
public async Task GetFeaturedAsync_ReturnsNull_WhenNoneFeatured()
{
await _sut.AddAsync(Offering("A", displayOrder: 0));
await _sut.SaveChangesAsync();
var result = await _sut.GetFeaturedAsync();
result.Should().BeNull();
}
[Fact]
public async Task GetPreviousAsync_ReturnsClosestLowerDisplayOrder()
{
await _sut.AddAsync(Offering("First", displayOrder: 0));
await _sut.AddAsync(Offering("Second", displayOrder: 1));
await _sut.AddAsync(Offering("Third", displayOrder: 2));
await _sut.SaveChangesAsync();
var result = await _sut.GetPreviousAsync(2);
result!.Title.Should().Be("Second");
}
[Fact]
public async Task GetPreviousAsync_ReturnsNull_WhenFirst()
{
await _sut.AddAsync(Offering("First", displayOrder: 0));
await _sut.SaveChangesAsync();
var result = await _sut.GetPreviousAsync(0);
result.Should().BeNull();
}
[Fact]
public async Task GetNextAsync_ReturnsClosestHigherDisplayOrder()
{
await _sut.AddAsync(Offering("First", displayOrder: 0));
await _sut.AddAsync(Offering("Second", displayOrder: 1));
await _sut.SaveChangesAsync();
var result = await _sut.GetNextAsync(0);
result!.Title.Should().Be("Second");
}
[Fact]
public async Task GetNextAsync_ReturnsNull_WhenLast()
{
await _sut.AddAsync(Offering("Last", displayOrder: 0));
await _sut.SaveChangesAsync();
var result = await _sut.GetNextAsync(0);
result.Should().BeNull();
}
[Fact]
public async Task Update_PersistsChanges()
{
var offering = Offering("Original", displayOrder: 0);
await _sut.AddAsync(offering);
await _sut.SaveChangesAsync();
offering.Title = "Updated";
_sut.Update(offering);
await _sut.SaveChangesAsync();
var result = await _sut.GetByIdAsync(offering.Id);
result!.Title.Should().Be("Updated");
}
private static Offering Offering(string title, int displayOrder) => new()
{
Id = Guid.NewGuid(),
Title = title,
Description = "Description",
Price = "€ 100",
PriceNote = "per month",
Features = ["Feature 1"],
CtaLabel = "Contact",
DisplayOrder = displayOrder,
CreatedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow,
LastModifiedByUserId = Guid.NewGuid(),
};
public void Dispose() => _context.Dispose();
}
@@ -0,0 +1,252 @@
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 OfferingsServiceTests
{
private readonly IOfferingRepository _repo = Substitute.For<IOfferingRepository>();
private readonly ILogger<OfferingsService> _logger = Substitute.For<ILogger<OfferingsService>>();
public OfferingsServiceTests()
{
_repo.BeginTransactionAsync().Returns(Substitute.For<IDbContextTransaction>());
}
private OfferingsService CreateSut() => new(_repo, _logger);
private static CreateOfferingRequest CreateRequest(bool featured = false) => new(
"Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", featured);
private static Offering ExistingOffering(bool featured = false, int displayOrder = 0) => new()
{
Id = Guid.NewGuid(),
Title = "Existing",
Description = "Description",
Price = "€ 100",
PriceNote = "per month",
Features = ["Feature 1"],
CtaLabel = "Contact",
Featured = featured,
DisplayOrder = displayOrder,
CreatedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow,
LastModifiedByUserId = Guid.NewGuid(),
};
// --- CreateAsync / BR-OFF-01 featured exclusivity ---
[Fact]
public async Task CreateAsync_AppendsToEndOfDisplayOrder()
{
_repo.GetMaxDisplayOrderAsync().Returns(4);
var callerId = Guid.NewGuid();
var result = await CreateSut().CreateAsync(CreateRequest(), callerId);
result.DisplayOrder.Should().Be(5);
}
[Fact]
public async Task CreateAsync_SetsLastModifiedByUserId()
{
_repo.GetMaxDisplayOrderAsync().Returns(-1);
var callerId = Guid.NewGuid();
var dto = await CreateSut().CreateAsync(CreateRequest(), callerId);
// The DTO doesn't expose LastModifiedByUserId (never shown to any caller) —
// verify via the entity actually persisted through the repository instead.
await _repo.Received(1).AddAsync(Arg.Is<Offering>(o => o.LastModifiedByUserId == callerId));
dto.Should().NotBeNull();
}
[Fact]
public async Task CreateAsync_UnfeaturesCurrentlyFeaturedOffering_WhenNewOneIsFeatured()
{
var current = ExistingOffering(featured: true);
_repo.GetFeaturedAsync().Returns(current);
_repo.GetMaxDisplayOrderAsync().Returns(-1);
await CreateSut().CreateAsync(CreateRequest(featured: true), Guid.NewGuid());
current.Featured.Should().BeFalse();
await _repo.Received(1).BeginTransactionAsync();
}
[Fact]
public async Task CreateAsync_DoesNotTouchFeatured_WhenNewOfferingNotFeatured()
{
_repo.GetMaxDisplayOrderAsync().Returns(-1);
await CreateSut().CreateAsync(CreateRequest(featured: false), Guid.NewGuid());
await _repo.DidNotReceive().GetFeaturedAsync();
await _repo.DidNotReceive().BeginTransactionAsync();
}
// --- UpdateAsync ---
[Fact]
public async Task UpdateAsync_ReturnsNull_WhenOfferingNotFound()
{
_repo.GetByIdAsync(Arg.Any<Guid>()).Returns((Offering?)null);
var request = new UpdateOfferingRequest("Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact");
var result = await CreateSut().UpdateAsync(Guid.NewGuid(), request, Guid.NewGuid());
result.Should().BeNull();
}
[Fact]
public async Task UpdateAsync_UnfeaturesOtherOffering_ExceptItself()
{
var target = ExistingOffering(featured: false);
var other = ExistingOffering(featured: true);
_repo.GetByIdAsync(target.Id).Returns(target);
_repo.GetFeaturedAsync().Returns(other);
var request = new UpdateOfferingRequest("Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", true);
await CreateSut().UpdateAsync(target.Id, request, Guid.NewGuid());
target.Featured.Should().BeTrue();
other.Featured.Should().BeFalse();
}
[Fact]
public async Task UpdateAsync_DoesNotUnfeatureItself_WhenAlreadyFeatured()
{
var target = ExistingOffering(featured: true);
_repo.GetByIdAsync(target.Id).Returns(target);
_repo.GetFeaturedAsync().Returns(target);
var request = new UpdateOfferingRequest("Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", true);
await CreateSut().UpdateAsync(target.Id, request, Guid.NewGuid());
target.Featured.Should().BeTrue();
}
// --- DeleteAsync / BR-OFF-02 ---
[Fact]
public async Task DeleteAsync_ReturnsFalse_WhenNotFound()
{
_repo.GetByIdAsync(Arg.Any<Guid>()).Returns((Offering?)null);
var result = await CreateSut().DeleteAsync(Guid.NewGuid(), Guid.NewGuid());
result.Should().BeFalse();
}
[Fact]
public async Task DeleteAsync_SoftDeletes_EvenForLastRemainingOffering()
{
var offering = ExistingOffering();
_repo.GetByIdAsync(offering.Id).Returns(offering);
var result = await CreateSut().DeleteAsync(offering.Id, Guid.NewGuid());
result.Should().BeTrue();
offering.IsDeleted.Should().BeTrue();
offering.DeletedAt.Should().NotBeNull();
}
// --- ReorderAsync / BR-OFF-03 ---
[Fact]
public async Task ReorderAsync_ReassignsDisplayOrderSequentially()
{
var first = ExistingOffering(displayOrder: 5);
var second = ExistingOffering(displayOrder: 2);
_repo.GetByIdAsync(first.Id).Returns(first);
_repo.GetByIdAsync(second.Id).Returns(second);
await CreateSut().ReorderAsync([first.Id, second.Id], Guid.NewGuid());
first.DisplayOrder.Should().Be(0);
second.DisplayOrder.Should().Be(1);
}
// --- MoveUpAsync / MoveDownAsync / BR-OFF-03 boundaries ---
[Fact]
public async Task MoveUpAsync_IsNoOp_WhenAlreadyFirst()
{
var offering = ExistingOffering(displayOrder: 0);
_repo.GetByIdAsync(offering.Id).Returns(offering);
_repo.GetPreviousAsync(0).Returns((Offering?)null);
await CreateSut().MoveUpAsync(offering.Id, Guid.NewGuid());
await _repo.DidNotReceive().BeginTransactionAsync();
}
[Fact]
public async Task MoveUpAsync_SwapsDisplayOrder_WithPrevious()
{
var offering = ExistingOffering(displayOrder: 1);
var previous = ExistingOffering(displayOrder: 0);
_repo.GetByIdAsync(offering.Id).Returns(offering);
_repo.GetPreviousAsync(1).Returns(previous);
await CreateSut().MoveUpAsync(offering.Id, Guid.NewGuid());
offering.DisplayOrder.Should().Be(0);
previous.DisplayOrder.Should().Be(1);
}
[Fact]
public async Task MoveDownAsync_IsNoOp_WhenAlreadyLast()
{
var offering = ExistingOffering(displayOrder: 0);
_repo.GetByIdAsync(offering.Id).Returns(offering);
_repo.GetNextAsync(0).Returns((Offering?)null);
await CreateSut().MoveDownAsync(offering.Id, Guid.NewGuid());
await _repo.DidNotReceive().BeginTransactionAsync();
}
[Fact]
public async Task MoveDownAsync_SwapsDisplayOrder_WithNext()
{
var offering = ExistingOffering(displayOrder: 0);
var next = ExistingOffering(displayOrder: 1);
_repo.GetByIdAsync(offering.Id).Returns(offering);
_repo.GetNextAsync(0).Returns(next);
await CreateSut().MoveDownAsync(offering.Id, Guid.NewGuid());
offering.DisplayOrder.Should().Be(1);
next.DisplayOrder.Should().Be(0);
}
// --- GetPublicOfferingsAsync / GetAllForAdminAsync ---
[Fact]
public async Task GetPublicOfferingsAsync_MapsToPublicDto()
{
_repo.GetAllAsync().Returns([ExistingOffering()]);
var result = await CreateSut().GetPublicOfferingsAsync();
result.Should().ContainSingle();
}
[Fact]
public async Task GetAllForAdminAsync_IncludesDisplayOrder()
{
var offering = ExistingOffering(displayOrder: 3);
_repo.GetAllAsync().Returns([offering]);
var result = await CreateSut().GetAllForAdminAsync();
result[0].DisplayOrder.Should().Be(3);
}
}
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="10.0.9" />
<!-- Pinned above the version DataProtection pulls transitively (FR-22, OPEN-03) — see Core.csproj -->
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.9" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Microsoft.Extensions.Options" />
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,78 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using SlpModularCms.Modules.Offerings.Models;
using SlpModularCms.Modules.Offerings.Services;
namespace SlpModularCms.Modules.Offerings.Controllers;
[ApiController]
[Route("offerings")]
[Authorize(Policy = "AdminOnly")]
public class OfferingsController(IOfferingsService service) : ControllerBase
{
[HttpGet]
[AllowAnonymous]
[EnableRateLimiting("offerings-public")]
public async Task<IActionResult> GetOfferings()
{
var offerings = await service.GetPublicOfferingsAsync();
return Ok(offerings);
}
[HttpGet("admin")]
public async Task<IActionResult> GetAllForAdmin()
{
var offerings = await service.GetAllForAdminAsync();
return Ok(offerings);
}
[HttpPost("admin")]
public async Task<IActionResult> Create([FromBody] CreateOfferingRequest request)
{
var dto = await service.CreateAsync(request, GetCallerId());
return CreatedAtAction(nameof(GetAllForAdmin), null, dto);
}
[HttpPut("admin/{id:guid}")]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateOfferingRequest request)
{
var dto = await service.UpdateAsync(id, request, GetCallerId());
return dto is null ? NotFound() : Ok(dto);
}
[HttpDelete("admin/{id:guid}")]
public async Task<IActionResult> Delete(Guid id)
{
var deleted = await service.DeleteAsync(id, GetCallerId());
return deleted ? NoContent() : NotFound();
}
[HttpPut("admin/reorder")]
public async Task<IActionResult> Reorder([FromBody] ReorderOfferingsRequest request)
{
await service.ReorderAsync(request.OrderedIds, GetCallerId());
return NoContent();
}
[HttpPost("admin/{id:guid}/move-up")]
public async Task<IActionResult> MoveUp(Guid id)
{
await service.MoveUpAsync(id, GetCallerId());
return NoContent();
}
[HttpPost("admin/{id:guid}/move-down")]
public async Task<IActionResult> MoveDown(Guid id)
{
await service.MoveDownAsync(id, GetCallerId());
return NoContent();
}
private Guid GetCallerId()
{
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
}
}
@@ -0,0 +1,19 @@
namespace SlpModularCms.Modules.Offerings.Data.Entities;
public class Offering
{
public Guid Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string Price { get; set; } = string.Empty;
public string PriceNote { get; set; } = string.Empty;
public List<string> Features { get; set; } = [];
public string CtaLabel { get; set; } = string.Empty;
public bool Featured { get; set; }
public int DisplayOrder { get; set; }
public bool IsDeleted { get; set; }
public DateTimeOffset? DeletedAt { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public Guid LastModifiedByUserId { get; set; }
}
@@ -0,0 +1,46 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using SlpModularCms.Modules.Offerings.Data.Entities;
namespace SlpModularCms.Modules.Offerings.Data;
public class OfferingsDbContext(DbContextOptions<OfferingsDbContext> options) : DbContext(options)
{
public DbSet<Offering> Offerings => Set<Offering>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Offering>(entity =>
{
entity.ToTable("OfferingsOfferings");
entity.HasKey(e => e.Id);
entity.Property(e => e.Title).IsRequired().HasMaxLength(100);
entity.Property(e => e.Description).IsRequired().HasMaxLength(500);
entity.Property(e => e.Price).IsRequired().HasMaxLength(50);
entity.Property(e => e.PriceNote).IsRequired().HasMaxLength(100);
entity.Property(e => e.CtaLabel).IsRequired().HasMaxLength(50);
entity.Property(e => e.DisplayOrder).IsRequired();
entity.Property(e => e.IsDeleted).IsRequired();
entity.Property(e => e.CreatedAt).IsRequired();
entity.Property(e => e.UpdatedAt).IsRequired();
entity.Property(e => e.LastModifiedByUserId).IsRequired();
// Features is a small, always-fully-replaced string list (max 10 items of max 200
// chars) — a JSON column is simpler than a child table for something never queried
// by individual feature value.
entity.Property(e => e.Features)
.HasConversion(
features => JsonSerializer.Serialize(features, (JsonSerializerOptions?)null),
json => JsonSerializer.Deserialize<List<string>>(json, (JsonSerializerOptions?)null) ?? new List<string>())
.Metadata.SetValueComparer(new ValueComparer<List<string>>(
(a, b) => (a ?? new List<string>()).SequenceEqual(b ?? new List<string>()),
v => v.Aggregate(0, (hash, item) => HashCode.Combine(hash, item.GetHashCode())),
v => v.ToList()));
entity.HasQueryFilter(e => !e.IsDeleted);
});
}
}
@@ -0,0 +1,88 @@
// <auto-generated />
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("20260802124751_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<string>("CtaLabel")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<DateTimeOffset?>("DeletedAt")
.HasColumnType("datetime");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<bool>("Featured")
.HasColumnType("tinyint(1)");
b.Property<string>("Features")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsDeleted")
.HasColumnType("tinyint(1)");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
b.Property<string>("Price")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("PriceNote")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.ToTable("OfferingsOfferings", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,50 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Offerings.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "OfferingsOfferings",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Title = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Description = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: false),
Price = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false),
PriceNote = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Features = table.Column<string>(type: "longtext", nullable: false),
CtaLabel = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false),
Featured = table.Column<bool>(type: "tinyint(1)", nullable: false),
DisplayOrder = table.Column<int>(type: "int", nullable: false),
IsDeleted = table.Column<bool>(type: "tinyint(1)", nullable: false),
DeletedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: true),
CreatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
LastModifiedByUserId = table.Column<Guid>(type: "char(36)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OfferingsOfferings", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "OfferingsOfferings");
}
}
}
@@ -0,0 +1,85 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Offerings.Data;
#nullable disable
namespace SlpModularCms.Modules.Offerings.Migrations
{
[DbContext(typeof(OfferingsDbContext))]
partial class OfferingsDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<string>("CtaLabel")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<DateTimeOffset?>("DeletedAt")
.HasColumnType("datetime");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<bool>("Featured")
.HasColumnType("tinyint(1)");
b.Property<string>("Features")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsDeleted")
.HasColumnType("tinyint(1)");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
b.Property<string>("Price")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("PriceNote")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.ToTable("OfferingsOfferings", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SlpModularCms.Modules.Offerings.Models;
public record CreateOfferingRequest(
[Required, MaxLength(100)] string Title,
[Required, MaxLength(500)] string Description,
[Required, MaxLength(50)] string Price,
[Required, MaxLength(100)] string PriceNote,
[Required, FeaturesValidation] List<string> Features,
[Required, MaxLength(50)] string CtaLabel,
bool Featured = false
);
@@ -0,0 +1,33 @@
using System.ComponentModel.DataAnnotations;
namespace SlpModularCms.Modules.Offerings.Models;
/// <summary>
/// DataAnnotations has no built-in way to bound both collection size and each item's
/// length (BR-OFF-04: 1-10 features, each &#8804;200 characters) — this attribute covers
/// what <see cref="MinLengthAttribute"/>/<see cref="MaxLengthAttribute"/> alone cannot.
/// </summary>
public class FeaturesValidationAttribute : ValidationAttribute
{
private const int MinItems = 1;
private const int MaxItems = 10;
private const int MaxItemLength = 200;
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is not List<string> features)
return new ValidationResult("Features must be a list of strings.", [validationContext.MemberName!]);
if (features.Count is < MinItems or > MaxItems)
return new ValidationResult(
$"Features must contain between {MinItems} and {MaxItems} items.",
[validationContext.MemberName!]);
if (features.Any(f => string.IsNullOrWhiteSpace(f) || f.Length > MaxItemLength))
return new ValidationResult(
$"Each feature must be non-empty and at most {MaxItemLength} characters.",
[validationContext.MemberName!]);
return ValidationResult.Success;
}
}
@@ -0,0 +1,16 @@
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Modules.Offerings.Models;
[ExcludeFromCodeCoverage]
public record OfferingAdminDto(
string Id,
string Title,
string Description,
string Price,
string PriceNote,
IReadOnlyList<string> Features,
string CtaLabel,
bool Featured,
int DisplayOrder
);
@@ -0,0 +1,15 @@
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Modules.Offerings.Models;
[ExcludeFromCodeCoverage]
public record OfferingDto(
string Id,
string Title,
string Description,
string Price,
string PriceNote,
IReadOnlyList<string> Features,
string CtaLabel,
bool Featured
);
@@ -0,0 +1,7 @@
using System.ComponentModel.DataAnnotations;
namespace SlpModularCms.Modules.Offerings.Models;
public record ReorderOfferingsRequest(
[Required, MinLength(1)] List<Guid> OrderedIds
);
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SlpModularCms.Modules.Offerings.Models;
public record UpdateOfferingRequest(
[Required, MaxLength(100)] string Title,
[Required, MaxLength(500)] string Description,
[Required, MaxLength(50)] string Price,
[Required, MaxLength(100)] string PriceNote,
[Required, FeaturesValidation] List<string> Features,
[Required, MaxLength(50)] string CtaLabel,
bool Featured = false
);
@@ -0,0 +1,41 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Modules;
using SlpModularCms.Modules.Offerings.Data;
using SlpModularCms.Modules.Offerings.Repositories;
using SlpModularCms.Modules.Offerings.Services;
namespace SlpModularCms.Modules.Offerings;
[ExcludeFromCodeCoverage]
public class OfferingsModule : IModule
{
public string Name => "Offerings";
public string Version => "1.0.0";
public void RegisterServices(IServiceCollection services)
{
services.AddDbContext<OfferingsDbContext>((serviceProvider, options) =>
{
var config = serviceProvider.GetRequiredService<IConfiguration>();
options.UseMySQL(config.GetConnectionString("DefaultConnection")!);
options.ReplaceService<IHistoryRepository, NonLockingMySQLHistoryRepository>();
});
services.AddScoped<IOfferingRepository, OfferingRepository>();
services.AddScoped<IOfferingsService, OfferingsService>();
services.AddHttpContextAccessor();
}
public void UseModule(IApplicationBuilder app)
{
using var scope = app.ApplicationServices.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OfferingsDbContext>();
db.Database.Migrate();
}
}
@@ -0,0 +1,18 @@
using Microsoft.EntityFrameworkCore.Storage;
using SlpModularCms.Modules.Offerings.Data.Entities;
namespace SlpModularCms.Modules.Offerings.Repositories;
public interface IOfferingRepository
{
Task<IReadOnlyList<Offering>> GetAllAsync();
Task<Offering?> GetByIdAsync(Guid id);
Task AddAsync(Offering offering);
void Update(Offering offering);
Task<int> GetMaxDisplayOrderAsync();
Task<Offering?> GetFeaturedAsync();
Task<Offering?> GetPreviousAsync(int displayOrder);
Task<Offering?> GetNextAsync(int displayOrder);
Task SaveChangesAsync();
Task<IDbContextTransaction> BeginTransactionAsync();
}
@@ -0,0 +1,45 @@
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 OfferingRepository(OfferingsDbContext context) : IOfferingRepository
{
public async Task<IReadOnlyList<Offering>> GetAllAsync()
=> await context.Offerings.OrderBy(o => o.DisplayOrder).ToListAsync();
public async Task<Offering?> GetByIdAsync(Guid id)
=> await context.Offerings.FirstOrDefaultAsync(o => o.Id == id);
public async Task AddAsync(Offering offering)
=> await context.Offerings.AddAsync(offering);
public void Update(Offering offering)
=> context.Offerings.Update(offering);
public async Task<int> GetMaxDisplayOrderAsync()
=> await context.Offerings.Select(o => (int?)o.DisplayOrder).MaxAsync() ?? -1;
public async Task<Offering?> GetFeaturedAsync()
=> await context.Offerings.FirstOrDefaultAsync(o => o.Featured);
public async Task<Offering?> GetPreviousAsync(int displayOrder)
=> await context.Offerings
.Where(o => o.DisplayOrder < displayOrder)
.OrderByDescending(o => o.DisplayOrder)
.FirstOrDefaultAsync();
public async Task<Offering?> GetNextAsync(int displayOrder)
=> await context.Offerings
.Where(o => o.DisplayOrder > displayOrder)
.OrderBy(o => o.DisplayOrder)
.FirstOrDefaultAsync();
public async Task SaveChangesAsync()
=> await context.SaveChangesAsync();
public async Task<IDbContextTransaction> BeginTransactionAsync()
=> await context.Database.BeginTransactionAsync();
}
@@ -0,0 +1,15 @@
using SlpModularCms.Modules.Offerings.Models;
namespace SlpModularCms.Modules.Offerings.Services;
public interface IOfferingsService
{
Task<IReadOnlyList<OfferingDto>> GetPublicOfferingsAsync();
Task<IReadOnlyList<OfferingAdminDto>> GetAllForAdminAsync();
Task<OfferingAdminDto> CreateAsync(CreateOfferingRequest request, Guid callerId);
Task<OfferingAdminDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId);
Task<bool> DeleteAsync(Guid id, Guid callerId);
Task ReorderAsync(IReadOnlyList<Guid> orderedIds, Guid callerId);
Task MoveUpAsync(Guid id, Guid callerId);
Task MoveDownAsync(Guid id, Guid callerId);
}
@@ -0,0 +1,227 @@
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 class OfferingsService(IOfferingRepository repository, ILogger<OfferingsService> logger) : IOfferingsService
{
public async Task<IReadOnlyList<OfferingDto>> GetPublicOfferingsAsync()
{
var offerings = await repository.GetAllAsync();
return offerings.Select(ToPublicDto).ToList();
}
public async Task<IReadOnlyList<OfferingAdminDto>> GetAllForAdminAsync()
{
var offerings = await repository.GetAllAsync();
return offerings.Select(ToAdminDto).ToList();
}
public async Task<OfferingAdminDto> CreateAsync(CreateOfferingRequest request, Guid callerId)
{
var now = DateTimeOffset.UtcNow;
var offering = new Offering
{
Id = Guid.NewGuid(),
Title = request.Title,
Description = request.Description,
Price = request.Price,
PriceNote = request.PriceNote,
Features = request.Features,
CtaLabel = request.CtaLabel,
Featured = request.Featured,
DisplayOrder = await repository.GetMaxDisplayOrderAsync() + 1,
CreatedAt = now,
UpdatedAt = now,
LastModifiedByUserId = callerId,
};
// BR-OFF-01 (featured exclusivity) touches two rows in one logical action —
// transactional per NFR Design Pattern 1 so a mid-operation failure can never
// leave two offerings both featured or the new one unsaved after the old one
// was already un-featured.
if (request.Featured)
{
await using var transaction = await repository.BeginTransactionAsync();
await UnfeatureCurrentAsync();
await repository.AddAsync(offering);
await repository.SaveChangesAsync();
await transaction.CommitAsync();
}
else
{
await repository.AddAsync(offering);
await repository.SaveChangesAsync();
}
logger.LogInformation(
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Created", callerId);
return ToAdminDto(offering);
}
public async Task<OfferingAdminDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId)
{
var offering = await repository.GetByIdAsync(id);
if (offering is null)
return null;
offering.Title = request.Title;
offering.Description = request.Description;
offering.Price = request.Price;
offering.PriceNote = request.PriceNote;
offering.Features = request.Features;
offering.CtaLabel = request.CtaLabel;
offering.Featured = request.Featured;
offering.UpdatedAt = DateTimeOffset.UtcNow;
offering.LastModifiedByUserId = callerId;
if (request.Featured)
{
await using var transaction = await repository.BeginTransactionAsync();
await UnfeatureCurrentAsync(exceptId: offering.Id);
repository.Update(offering);
await repository.SaveChangesAsync();
await transaction.CommitAsync();
}
else
{
repository.Update(offering);
await repository.SaveChangesAsync();
}
logger.LogInformation(
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Updated", callerId);
return ToAdminDto(offering);
}
public async Task<bool> DeleteAsync(Guid id, Guid callerId)
{
var offering = await repository.GetByIdAsync(id);
if (offering is null)
return false;
// BR-OFF-02: soft delete is never blocked, including for the last remaining offering.
offering.IsDeleted = true;
offering.DeletedAt = DateTimeOffset.UtcNow;
offering.UpdatedAt = offering.DeletedAt.Value;
offering.LastModifiedByUserId = callerId;
repository.Update(offering);
await repository.SaveChangesAsync();
logger.LogInformation(
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Deleted", callerId);
return true;
}
public async Task ReorderAsync(IReadOnlyList<Guid> orderedIds, Guid callerId)
{
await using var transaction = await repository.BeginTransactionAsync();
var now = DateTimeOffset.UtcNow;
for (var i = 0; i < orderedIds.Count; i++)
{
var offering = await repository.GetByIdAsync(orderedIds[i]);
if (offering is null)
continue;
offering.DisplayOrder = i;
offering.UpdatedAt = now;
offering.LastModifiedByUserId = callerId;
repository.Update(offering);
}
await repository.SaveChangesAsync();
await transaction.CommitAsync();
logger.LogInformation(
"Offerings reordered ({Count} items) by user {LastModifiedByUserId}",
orderedIds.Count, callerId);
}
public async Task MoveUpAsync(Guid id, Guid callerId)
{
var offering = await repository.GetByIdAsync(id);
if (offering is null)
return;
var previous = await repository.GetPreviousAsync(offering.DisplayOrder);
if (previous is null)
return; // BR-OFF-03: already first, no-op
await using var transaction = await repository.BeginTransactionAsync();
SwapDisplayOrder(offering, previous, callerId);
await repository.SaveChangesAsync();
await transaction.CommitAsync();
}
public async Task MoveDownAsync(Guid id, Guid callerId)
{
var offering = await repository.GetByIdAsync(id);
if (offering is null)
return;
var next = await repository.GetNextAsync(offering.DisplayOrder);
if (next is null)
return; // BR-OFF-03: already last, no-op
await using var transaction = await repository.BeginTransactionAsync();
SwapDisplayOrder(offering, next, callerId);
await repository.SaveChangesAsync();
await transaction.CommitAsync();
}
private void SwapDisplayOrder(Offering a, Offering b, Guid callerId)
{
(a.DisplayOrder, b.DisplayOrder) = (b.DisplayOrder, a.DisplayOrder);
var now = DateTimeOffset.UtcNow;
a.UpdatedAt = now;
b.UpdatedAt = now;
a.LastModifiedByUserId = callerId;
b.LastModifiedByUserId = callerId;
repository.Update(a);
repository.Update(b);
}
private async Task UnfeatureCurrentAsync(Guid? exceptId = null)
{
var current = await repository.GetFeaturedAsync();
if (current is null || current.Id == exceptId)
return;
current.Featured = false;
current.UpdatedAt = DateTimeOffset.UtcNow;
repository.Update(current);
}
private static OfferingDto ToPublicDto(Offering o) => new(
o.Id.ToString(),
o.Title,
o.Description,
o.Price,
o.PriceNote,
o.Features,
o.CtaLabel,
o.Featured
);
private static OfferingAdminDto ToAdminDto(Offering o) => new(
o.Id.ToString(),
o.Title,
o.Description,
o.Price,
o.PriceNote,
o.Features,
o.CtaLabel,
o.Featured,
o.DisplayOrder
);
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>SlpModularCms.Modules.Offerings.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
</ItemGroup>
</Project>