Aanbod: RESTful routes zonder /admin, één OfferingDto en herordenen via PUT /offerings/order

Admin en bezoeker gebruiken dezelfde resource; alleen GET is anoniem, de rest vereist AdminOnly. OfferingAdminDto vervalt (displayOrder zit nu in OfferingDto), move-up/move-down zijn vervangen door de order-route die een onbekende of onvolledige lijst met 400 afwijst. De admin-frontend en alle tests zijn mee aangepast.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:06:08 +01:00
co-authored by Claude Sonnet 5.5
parent e6710781e5
commit bc763c8ef6
39 changed files with 968 additions and 395 deletions
@@ -24,10 +24,7 @@ public class OfferingsControllerTests
return new OfferingsController(_service) { ControllerContext = new ControllerContext { HttpContext = httpContext } };
}
private static OfferingDto PublicDto() => new(
Guid.NewGuid().ToString(), "title", "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false);
private static OfferingAdminDto AdminDto(int displayOrder = 0) => new(
private static OfferingDto Dto(int displayOrder = 0) => new(
Guid.NewGuid().ToString(), "title", "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false, displayOrder);
private static CreateOfferingRequest CreateRequest() => new(
@@ -41,35 +38,23 @@ public class OfferingsControllerTests
[Fact]
public async Task GetOfferings_Returns200_WithList()
{
_service.GetPublicOfferingsAsync().Returns([PublicDto()]);
_service.GetOfferingsAsync().Returns([Dto()]);
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());
_service.CreateAsync(Arg.Any<CreateOfferingRequest>(), Arg.Any<Guid>()).Returns(Dto());
var result = await CreateSut().Create(CreateRequest());
result.Should().BeOfType<CreatedAtActionResult>().Which.StatusCode.Should().Be(201);
result.Should().BeOfType<CreatedResult>().Which.StatusCode.Should().Be(201);
}
[Fact]
@@ -88,7 +73,7 @@ public class OfferingsControllerTests
[Fact]
public async Task Update_Returns200_WhenFound()
{
_service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>()).Returns(AdminDto());
_service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>()).Returns(Dto());
var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest());
@@ -99,7 +84,7 @@ public class OfferingsControllerTests
public async Task Update_Returns404_WhenNotFound()
{
_service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>())
.Returns((OfferingAdminDto?)null);
.Returns((OfferingDto?)null);
var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest());
@@ -139,29 +124,4 @@ public class OfferingsControllerTests
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,106 @@
using System.Reflection;
using System.Security.Claims;
using FluentAssertions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
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 OfferingsRoutesTests
{
private readonly IOfferingsService _service = Substitute.For<IOfferingsService>();
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 IEnumerable<(MethodInfo Action, HttpMethodAttribute Http)> Actions() =>
typeof(OfferingsController)
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Select(m => (Action: m, Http: m.GetCustomAttributes<HttpMethodAttribute>().SingleOrDefault()))
.Where(x => x.Http is not null)
.Select(x => (x.Action, x.Http!));
[Fact]
public void OnlyGet_IsAnonymous_AndTheClassRequiresAdminOnly()
{
var classPolicy = typeof(OfferingsController).GetCustomAttribute<AuthorizeAttribute>();
classPolicy.Should().NotBeNull();
classPolicy!.Policy.Should().Be("AdminOnly");
foreach (var (action, http) in Actions())
{
var anonymous = action.GetCustomAttribute<AllowAnonymousAttribute>() is not null;
anonymous.Should().Be(
http.HttpMethods.Single() == "GET",
$"{http.HttpMethods.Single()} {http.Template} must be anonymous only when it is a GET");
}
}
[Fact]
public void NoRouteContainsAnAdminSegment_AndTheMoveActionsAreGone()
{
foreach (var (_, http) in Actions())
{
(http.Template ?? string.Empty).Should().NotContainEquivalentOf("admin");
}
typeof(OfferingsController).GetMethods().Select(m => m.Name)
.Should().NotContain(["MoveUp", "MoveDown", "GetAllForAdmin"]);
}
[Fact]
public void RouteTable_IsTheRestfulSet()
{
Actions().Select(a => $"{a.Http.HttpMethods.Single()} {a.Http.Template}".Trim())
.Should().BeEquivalentTo(
[
"GET",
"POST",
"PUT {id:guid}",
"DELETE {id:guid}",
"PUT order",
]);
}
[Fact]
public async Task Create_Returns201_WithLocationOfTheNewResource()
{
var dto = new OfferingDto(Guid.NewGuid().ToString(), "t", "T", "D", "p", "n", ["f"], "c", false, 0);
_service.CreateAsync(Arg.Any<CreateOfferingRequest>(), Arg.Any<Guid>()).Returns(dto);
var result = await CreateSut().Create(new CreateOfferingRequest("T", "D", "p", "n", ["f"], "c"));
var created = result.Should().BeOfType<CreatedResult>().Subject;
created.StatusCode.Should().Be(201);
created.Location.Should().Be($"/api/v1/offerings/{dto.Id}");
created.Value.Should().Be(dto);
}
[Fact]
public async Task Reorder_Returns400_WhenTheListIsUnknownOrIncomplete()
{
_service.ReorderAsync(Arg.Any<IReadOnlyList<Guid>>(), Arg.Any<Guid>())
.ThrowsAsync(new OfferingOrderInvalidException());
var result = await CreateSut().Reorder(new ReorderOfferingsRequest([Guid.NewGuid()]));
var bad = result.Should().BeOfType<BadRequestObjectResult>().Subject;
bad.Value.Should().BeOfType<ProblemDetails>().Which.Status.Should().Be(400);
}
}
@@ -105,53 +105,6 @@ public class OfferingRepositoryTests : IDisposable
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 ExistsBySlugAsync_ReturnsTrue_WhenSlugTaken()
{
@@ -0,0 +1,99 @@
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 OfferingsServiceOrderTests
{
private readonly IOfferingRepository _repo = Substitute.For<IOfferingRepository>();
public OfferingsServiceOrderTests()
{
_repo.BeginTransactionAsync().Returns(Substitute.For<IDbContextTransaction>());
}
private OfferingsService CreateSut() => new(_repo, Substitute.For<ILogger<OfferingsService>>());
private static Offering New(int order) => new()
{
Id = Guid.NewGuid(),
Slug = $"s{order}",
Title = $"T{order}",
Description = "d",
Price = "p",
PriceNote = "n",
Features = ["f"],
CtaLabel = "c",
DisplayOrder = order,
};
[Fact]
public async Task ReorderAsync_AssignsSequentialOrder_FromTheGivenList()
{
var a = New(0);
var b = New(1);
var c = New(2);
_repo.GetAllAsync().Returns([a, b, c]);
await CreateSut().ReorderAsync([c.Id, a.Id, b.Id], Guid.NewGuid());
c.DisplayOrder.Should().Be(0);
a.DisplayOrder.Should().Be(1);
b.DisplayOrder.Should().Be(2);
await _repo.Received(1).SaveChangesAsync();
}
[Fact]
public async Task ReorderAsync_Throws_AndChangesNothing_WhenAnIdIsUnknown()
{
var a = New(0);
var b = New(1);
_repo.GetAllAsync().Returns([a, b]);
var act = () => CreateSut().ReorderAsync([a.Id, Guid.NewGuid()], Guid.NewGuid());
await act.Should().ThrowAsync<OfferingOrderInvalidException>();
a.DisplayOrder.Should().Be(0);
b.DisplayOrder.Should().Be(1);
await _repo.DidNotReceive().SaveChangesAsync();
}
[Fact]
public async Task ReorderAsync_Throws_WhenTheListIsIncomplete()
{
var a = New(0);
var b = New(1);
_repo.GetAllAsync().Returns([a, b]);
var act = () => CreateSut().ReorderAsync([a.Id], Guid.NewGuid());
await act.Should().ThrowAsync<OfferingOrderInvalidException>();
}
[Fact]
public async Task ReorderAsync_Throws_WhenTheListHoldsADuplicate()
{
var a = New(0);
var b = New(1);
_repo.GetAllAsync().Returns([a, b]);
var act = () => CreateSut().ReorderAsync([a.Id, a.Id], Guid.NewGuid());
await act.Should().ThrowAsync<OfferingOrderInvalidException>();
}
[Fact]
public async Task GetOfferingsAsync_IncludesDisplayOrder_ForEveryone()
{
_repo.GetAllAsync().Returns([New(3)]);
var result = await CreateSut().GetOfferingsAsync();
result.Should().ContainSingle().Which.DisplayOrder.Should().Be(3);
}
}
@@ -267,96 +267,4 @@ public class OfferingsServiceTests
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);
}
}
@@ -8,6 +8,11 @@ using SlpModularCms.Modules.Offerings.Services;
namespace SlpModularCms.Modules.Offerings.Controllers;
/// <summary>
/// The offerings resource. Reading is public; every write requires the AdminOnly policy.
/// There is deliberately no separate "admin" route: an administrator uses the same resource
/// and verbs, and access is decided by authorization alone.
/// </summary>
[ApiController]
[Route("offerings")]
[Authorize(Policy = "AdminOnly")]
@@ -18,24 +23,17 @@ public class OfferingsController(IOfferingsService service) : ControllerBase
[EnableRateLimiting("offerings-public")]
public async Task<IActionResult> GetOfferings()
{
var offerings = await service.GetPublicOfferingsAsync();
var offerings = await service.GetOfferingsAsync();
return Ok(offerings);
}
[HttpGet("admin")]
public async Task<IActionResult> GetAllForAdmin()
{
var offerings = await service.GetAllForAdminAsync();
return Ok(offerings);
}
[HttpPost("admin")]
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateOfferingRequest request)
{
try
{
var dto = await service.CreateAsync(request, GetCallerId());
return CreatedAtAction(nameof(GetAllForAdmin), null, dto);
return Created($"/api/v1/offerings/{dto.Id}", dto);
}
catch (OfferingSlugConflictException ex)
{
@@ -43,7 +41,7 @@ public class OfferingsController(IOfferingsService service) : ControllerBase
}
}
[HttpPut("admin/{id:guid}")]
[HttpPut("{id:guid}")]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateOfferingRequest request)
{
try
@@ -57,32 +55,29 @@ public class OfferingsController(IOfferingsService service) : ControllerBase
}
}
[HttpDelete("admin/{id:guid}")]
[HttpDelete("{id:guid}")]
public async Task<IActionResult> Delete(Guid id)
{
var deleted = await service.DeleteAsync(id, GetCallerId());
return deleted ? NoContent() : NotFound();
}
[HttpPut("admin/reorder")]
/// <summary>
/// Sets the display order of the whole collection. The list must contain every existing
/// offering exactly once.
/// </summary>
[HttpPut("order")]
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();
try
{
await service.ReorderAsync(request.OrderedIds, GetCallerId());
return NoContent();
}
catch (OfferingOrderInvalidException ex)
{
return BadRequest(new ProblemDetails { Status = StatusCodes.Status400BadRequest, Title = ex.Message });
}
}
private Guid GetCallerId()
@@ -1,17 +0,0 @@
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Modules.Offerings.Models;
[ExcludeFromCodeCoverage]
public record OfferingAdminDto(
string Id,
string Slug,
string Title,
string Description,
string Price,
string PriceNote,
IReadOnlyList<string> Features,
string CtaLabel,
bool Featured,
int DisplayOrder
);
@@ -2,6 +2,10 @@ using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Modules.Offerings.Models;
/// <summary>
/// The one representation of an offering, for anonymous visitors and administrators alike.
/// <c>DisplayOrder</c> is informational (the array order already is the display order).
/// </summary>
[ExcludeFromCodeCoverage]
public record OfferingDto(
string Id,
@@ -12,5 +16,6 @@ public record OfferingDto(
string PriceNote,
IReadOnlyList<string> Features,
string CtaLabel,
bool Featured
bool Featured,
int DisplayOrder
);
@@ -12,8 +12,6 @@ public interface IOfferingRepository
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();
}
@@ -28,18 +28,6 @@ public class OfferingRepository(OfferingsDbContext context) : IOfferingRepositor
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();
@@ -4,12 +4,14 @@ 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<IReadOnlyList<OfferingDto>> GetOfferingsAsync();
Task<OfferingDto> CreateAsync(CreateOfferingRequest request, Guid callerId);
Task<OfferingDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId);
Task<bool> DeleteAsync(Guid id, Guid callerId);
/// <summary>
/// Sets the display order of all offerings. <paramref name="orderedIds"/> must contain every
/// existing offering exactly once; otherwise <see cref="OfferingOrderInvalidException"/>.
/// </summary>
Task ReorderAsync(IReadOnlyList<Guid> orderedIds, Guid callerId);
Task MoveUpAsync(Guid id, Guid callerId);
Task MoveDownAsync(Guid id, Guid callerId);
}
@@ -0,0 +1,7 @@
namespace SlpModularCms.Modules.Offerings.Services;
/// <summary>
/// Thrown when a reorder request does not list every existing offering exactly once.
/// </summary>
public class OfferingOrderInvalidException()
: Exception("The order must list every existing offering exactly once.");
@@ -7,19 +7,13 @@ namespace SlpModularCms.Modules.Offerings.Services;
public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsService> logger) : IOfferingsService
{
public async Task<IReadOnlyList<OfferingDto>> GetPublicOfferingsAsync()
public async Task<IReadOnlyList<OfferingDto>> GetOfferingsAsync()
{
var offerings = await repository.GetAllAsync();
return offerings.Select(ToPublicDto).ToList();
return offerings.Select(ToDto).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)
public async Task<OfferingDto> CreateAsync(CreateOfferingRequest request, Guid callerId)
{
var now = DateTimeOffset.UtcNow;
var offering = new Offering
@@ -61,10 +55,10 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Created", callerId);
return ToAdminDto(offering);
return ToDto(offering);
}
public async Task<OfferingAdminDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId)
public async Task<OfferingDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId)
{
var offering = await repository.GetByIdAsync(id);
if (offering is null)
@@ -107,7 +101,7 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Updated", callerId);
return ToAdminDto(offering);
return ToDto(offering);
}
public async Task<bool> DeleteAsync(Guid id, Guid callerId)
@@ -134,15 +128,25 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
public async Task ReorderAsync(IReadOnlyList<Guid> orderedIds, Guid callerId)
{
var offerings = await repository.GetAllAsync();
// The list must be a permutation of the existing offerings: no unknown ids, no duplicates,
// none missing. Silently skipping mismatches would leave the display order half-applied.
var existingIds = offerings.Select(o => o.Id).ToHashSet();
if (orderedIds.Count != existingIds.Count
|| orderedIds.Distinct().Count() != orderedIds.Count
|| !orderedIds.All(existingIds.Contains))
{
throw new OfferingOrderInvalidException();
}
await using var transaction = await repository.BeginTransactionAsync();
var byId = offerings.ToDictionary(o => o.Id);
var now = DateTimeOffset.UtcNow;
for (var i = 0; i < orderedIds.Count; i++)
{
var offering = await repository.GetByIdAsync(orderedIds[i]);
if (offering is null)
continue;
var offering = byId[orderedIds[i]];
offering.DisplayOrder = i;
offering.UpdatedAt = now;
offering.LastModifiedByUserId = callerId;
@@ -157,50 +161,6 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
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();
@@ -246,19 +206,7 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
return slug;
}
private static OfferingDto ToPublicDto(Offering o) => new(
o.Id.ToString(),
o.Slug,
o.Title,
o.Description,
o.Price,
o.PriceNote,
o.Features,
o.CtaLabel,
o.Featured
);
private static OfferingAdminDto ToAdminDto(Offering o) => new(
private static OfferingDto ToDto(Offering o) => new(
o.Id.ToString(),
o.Slug,
o.Title,