Aanbod: categorieën als CMS-data met CRUD-routes en categoryId op het aanbod
Nieuwe tabel OfferingsCategories (unieke naam, case-insensitief) en nullable Offering.CategoryId met FK Restrict (migratie AddOfferingCategories). Routes onder /offerings/categories zijn AdminOnly; verwijderen van een gebruikte categorie geeft 409. Het aanbod neemt categoryId (moet bestaan, anders 400) en geeft category (naam) en categoryId terug; niets wordt geseed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Categories offerings can be placed in. Managed by administrators only; visitors see the
|
||||
/// category name on the offerings themselves.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("offerings/categories")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public class OfferingCategoriesController(IOfferingCategoriesService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> List() => Ok(await service.ListAsync());
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> 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<IActionResult> 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<IActionResult> 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 };
|
||||
}
|
||||
@@ -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<string, string[]> { ["categoryId"] = ["invalid"] })
|
||||
{
|
||||
Status = StatusCodes.Status400BadRequest,
|
||||
Title = "Invalid category",
|
||||
});
|
||||
|
||||
private Guid GetCallerId()
|
||||
{
|
||||
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
|
||||
|
||||
@@ -11,6 +11,8 @@ public class Offering
|
||||
public List<string> 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; }
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace SlpModularCms.Modules.Offerings.Data.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// A category an offering can be placed in. Managed in the CMS (never seeded in code).
|
||||
/// </summary>
|
||||
public class OfferingCategory
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>Display name; unique, compared case-insensitively.</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public int SortOrder { get; set; }
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public DateTimeOffset UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -8,6 +8,7 @@ namespace SlpModularCms.Modules.Offerings.Data;
|
||||
public class OfferingsDbContext(DbContextOptions<OfferingsDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<Offering> Offerings => Set<Offering>();
|
||||
public DbSet<OfferingCategory> OfferingCategories => Set<OfferingCategory>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -41,7 +42,29 @@ public class OfferingsDbContext(DbContextOptions<OfferingsDbContext> 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<OfferingCategory>(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();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+136
@@ -0,0 +1,136 @@
|
||||
// <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("20261109193305_AddOfferingCategories")]
|
||||
partial class AddOfferingCategories
|
||||
{
|
||||
/// <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<Guid?>("CategoryId")
|
||||
.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>("Slug")
|
||||
.IsRequired()
|
||||
.HasMaxLength(130)
|
||||
.HasColumnType("varchar(130)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<DateTimeOffset>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<int>("SortOrder")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTimeOffset>("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
|
||||
}
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Offerings.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddOfferingCategories : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "CategoryId",
|
||||
table: "OfferingsOfferings",
|
||||
type: "char(36)",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "OfferingsCategories",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
|
||||
SortOrder = table.Column<int>(type: "int", nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
|
||||
UpdatedAt = table.Column<DateTimeOffset>(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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,9 @@ namespace SlpModularCms.Modules.Offerings.Migrations
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid?>("CategoryId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("varchar(100)");
|
||||
|
||||
b.Property<int>("SortOrder")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTimeOffset>("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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,5 +10,6 @@ public record CreateOfferingRequest(
|
||||
[Required, FeaturesValidation] List<string> Features,
|
||||
[Required, MaxLength(50)] string CtaLabel,
|
||||
bool Featured = false,
|
||||
[MaxLength(130)] string? Slug = null
|
||||
[MaxLength(130)] string? Slug = null,
|
||||
Guid? CategoryId = null
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
@@ -17,5 +17,7 @@ public record OfferingDto(
|
||||
IReadOnlyList<string> Features,
|
||||
string CtaLabel,
|
||||
bool Featured,
|
||||
int DisplayOrder
|
||||
int DisplayOrder,
|
||||
string? CategoryId = null,
|
||||
string? Category = null
|
||||
);
|
||||
|
||||
@@ -10,5 +10,6 @@ public record UpdateOfferingRequest(
|
||||
[Required, FeaturesValidation] List<string> Features,
|
||||
[Required, MaxLength(50)] string CtaLabel,
|
||||
bool Featured = false,
|
||||
[MaxLength(130)] string? Slug = null
|
||||
[MaxLength(130)] string? Slug = null,
|
||||
Guid? CategoryId = null
|
||||
);
|
||||
|
||||
@@ -29,6 +29,8 @@ public class OfferingsModule : IModule
|
||||
|
||||
services.AddScoped<IOfferingRepository, OfferingRepository>();
|
||||
services.AddScoped<IOfferingsService, OfferingsService>();
|
||||
services.AddScoped<IOfferingCategoryRepository, OfferingCategoryRepository>();
|
||||
services.AddScoped<IOfferingCategoriesService, OfferingCategoriesService>();
|
||||
services.AddHttpContextAccessor();
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>All categories ordered by sort order then name, with the number of non-deleted offerings in each.</summary>
|
||||
Task<IReadOnlyList<CategoryWithCount>> ListAsync();
|
||||
|
||||
Task<OfferingCategory?> GetByIdAsync(Guid id);
|
||||
|
||||
/// <summary>Case-insensitive name check; <paramref name="excludeId"/> skips the category being renamed.</summary>
|
||||
Task<bool> ExistsByNameAsync(string name, Guid? excludeId = null);
|
||||
|
||||
Task<int> GetMaxSortOrderAsync();
|
||||
Task<int> CountOfferingsAsync(Guid categoryId);
|
||||
|
||||
/// <summary>Clears the category on soft-deleted offerings that still point to it (so the FK no longer blocks deletion).</summary>
|
||||
Task ClearCategoryOnDeletedOfferingsAsync(Guid categoryId);
|
||||
|
||||
Task AddAsync(OfferingCategory category);
|
||||
void Remove(OfferingCategory category);
|
||||
Task SaveChangesAsync();
|
||||
Task<IDbContextTransaction> BeginTransactionAsync();
|
||||
}
|
||||
@@ -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<IReadOnlyList<CategoryWithCount>> 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<OfferingCategory?> GetByIdAsync(Guid id)
|
||||
=> await context.OfferingCategories.FirstOrDefaultAsync(c => c.Id == id);
|
||||
|
||||
public async Task<bool> 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<int> GetMaxSortOrderAsync()
|
||||
=> await context.OfferingCategories.Select(c => (int?)c.SortOrder).MaxAsync() ?? -1;
|
||||
|
||||
public async Task<int> 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<IDbContextTransaction> BeginTransactionAsync()
|
||||
=> await context.Database.BeginTransactionAsync();
|
||||
}
|
||||
@@ -8,10 +8,10 @@ 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();
|
||||
=> await context.Offerings.Include(o => o.Category).OrderBy(o => o.DisplayOrder).ToListAsync();
|
||||
|
||||
public async Task<Offering?> 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<bool> ExistsBySlugAsync(string slug, Guid? excludeId = null)
|
||||
=> await context.Offerings.AnyAsync(o => o.Slug == slug && o.Id != (excludeId ?? Guid.Empty));
|
||||
|
||||
@@ -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<IReadOnlyList<OfferingCategoryDto>> ListAsync();
|
||||
Task<OfferingCategoryDto> CreateAsync(string name);
|
||||
Task<OfferingCategoryDto?> RenameAsync(Guid id, string name);
|
||||
Task<bool> DeleteAsync(Guid id);
|
||||
}
|
||||
|
||||
public class OfferingCategoriesService(
|
||||
IOfferingCategoryRepository repository,
|
||||
ILogger<OfferingCategoriesService> logger) : IOfferingCategoriesService
|
||||
{
|
||||
public async Task<IReadOnlyList<OfferingCategoryDto>> ListAsync()
|
||||
{
|
||||
var categories = await repository.ListAsync();
|
||||
return categories.Select(c => ToDto(c.Category, c.OfferingCount)).ToList();
|
||||
}
|
||||
|
||||
public async Task<OfferingCategoryDto> 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<OfferingCategoryDto?> 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<bool> 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);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SlpModularCms.Modules.Offerings.Services;
|
||||
|
||||
/// <summary>Thrown when an offering refers to a category that does not exist.</summary>
|
||||
public class OfferingCategoryInvalidException() : Exception("The category does not exist.");
|
||||
|
||||
/// <summary>Thrown when a category name is already taken (case-insensitive).</summary>
|
||||
public class OfferingCategoryNameConflictException(string name)
|
||||
: Exception($"A category named '{name}' already exists.");
|
||||
|
||||
/// <summary>Thrown when a category that is still used by offerings is deleted.</summary>
|
||||
public class OfferingCategoryInUseException(int offeringCount)
|
||||
: Exception($"The category is still used by {offeringCount} offering(s). Move them to another category first.");
|
||||
@@ -5,7 +5,10 @@ using SlpModularCms.Modules.Offerings.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Offerings.Services;
|
||||
|
||||
public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsService> logger) : IOfferingsService
|
||||
public class OfferingsService(
|
||||
IOfferingRepository repository,
|
||||
IOfferingCategoryRepository categories,
|
||||
ILogger<OfferingsService> logger) : IOfferingsService
|
||||
{
|
||||
public async Task<IReadOnlyList<OfferingDto>> GetOfferingsAsync()
|
||||
{
|
||||
@@ -15,6 +18,7 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
|
||||
|
||||
public async Task<OfferingDto> 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<OfferingsS
|
||||
PriceNote = request.PriceNote,
|
||||
Features = request.Features,
|
||||
CtaLabel = request.CtaLabel,
|
||||
CategoryId = category?.Id,
|
||||
Category = category,
|
||||
Featured = request.Featured,
|
||||
DisplayOrder = await repository.GetMaxDisplayOrderAsync() + 1,
|
||||
CreatedAt = now,
|
||||
@@ -64,6 +70,8 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
|
||||
if (offering is null)
|
||||
return null;
|
||||
|
||||
var category = await ResolveCategoryAsync(request.CategoryId);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Slug))
|
||||
{
|
||||
offering.Slug = await ResolveExplicitSlugAsync(request.Slug, excludeId: offering.Id);
|
||||
@@ -79,6 +87,8 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
|
||||
offering.PriceNote = request.PriceNote;
|
||||
offering.Features = request.Features;
|
||||
offering.CtaLabel = request.CtaLabel;
|
||||
offering.CategoryId = category?.Id;
|
||||
offering.Category = category;
|
||||
offering.Featured = request.Featured;
|
||||
offering.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
offering.LastModifiedByUserId = callerId;
|
||||
@@ -172,6 +182,15 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
|
||||
repository.Update(current);
|
||||
}
|
||||
|
||||
private async Task<OfferingCategory?> ResolveCategoryAsync(Guid? categoryId)
|
||||
{
|
||||
if (categoryId is null)
|
||||
return null;
|
||||
|
||||
return await categories.GetByIdAsync(categoryId.Value)
|
||||
?? throw new OfferingCategoryInvalidException();
|
||||
}
|
||||
|
||||
private async Task<string> ResolveSlugAsync(string? explicitSlug, string title)
|
||||
=> !string.IsNullOrWhiteSpace(explicitSlug)
|
||||
? await ResolveExplicitSlugAsync(explicitSlug, excludeId: null)
|
||||
@@ -216,6 +235,8 @@ public class OfferingsService(IOfferingRepository repository, ILogger<OfferingsS
|
||||
o.Features,
|
||||
o.CtaLabel,
|
||||
o.Featured,
|
||||
o.DisplayOrder
|
||||
o.DisplayOrder,
|
||||
o.CategoryId?.ToString(),
|
||||
o.Category?.Name
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user