Offerings: OfferingBanner (planbare banner, GET /offerings/banner) en layout verwijderd (backend)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 10:47:44 +01:00
co-authored by Claude Sonnet 5.5
parent 6349d99f16
commit a2f4513205
24 changed files with 1005 additions and 161 deletions
@@ -3,6 +3,8 @@ using System.Text.Json;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace SlpModularCms.Api.AndreaSlopFotografie.Tests;
@@ -38,6 +40,28 @@ public class HostPipelineTests : IClassFixture<AsfWebApplicationFactory>
modules.Should().NotContain("Master");
}
[Fact]
public async Task OfferingBanner_Is204_WhenNoneIsActive_AndOfferingsAreListed_OnAMigratedDatabase()
{
var client = _factory.CreateClient();
var banner = await client.GetAsync("/api/v1/offerings/banner");
banner.StatusCode.Should().Be(HttpStatusCode.NoContent);
(await client.GetAsync("/api/v1/offerings")).StatusCode.Should().Be(HttpStatusCode.OK);
(await client.GetAsync("/api/v1/offerings/banners")).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public void OfferingsMigrations_MatchTheModel()
{
_ = _factory.CreateClient(); // starts the host and migrates
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<SlpModularCms.Modules.Offerings.Data.OfferingsDbContext>();
db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot");
}
[Fact]
public async Task Health_IsReachable()
{
@@ -9,7 +9,7 @@ namespace SlpModularCms.Modules.Offerings.Tests.Controllers;
public class OfferingsPublicMarkerTests
{
private static IEnumerable<MethodInfo> Actions() =>
new[] { typeof(OfferingsController), typeof(OfferingCategoriesController) }
new[] { typeof(OfferingsController), typeof(OfferingCategoriesController), typeof(OfferingBannersController), typeof(PublicOfferingBannerController) }
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly));
[Fact]
@@ -26,7 +26,18 @@ public class OfferingsPublicMarkerTests
{
Actions()
.Where(m => m.Name != nameof(OfferingsController.GetOfferings))
.Where(m => !(m.DeclaringType == typeof(PublicOfferingBannerController) && m.Name == nameof(PublicOfferingBannerController.Get)))
.Where(m => m.GetCustomAttribute<PublicSiteEndpointAttribute>() is not null)
.Should().BeEmpty("writes and the category management stay behind the availability gate");
}
[Fact]
public void TheBannerGet_IsPublicAndMarked_WhileBannerManagementIsNot()
{
var get = typeof(PublicOfferingBannerController).GetMethod(nameof(PublicOfferingBannerController.Get))!;
get.GetCustomAttribute<PublicSiteEndpointAttribute>().Should().NotBeNull();
get.GetCustomAttribute<AllowAnonymousAttribute>().Should().NotBeNull();
typeof(OfferingBannersController).GetCustomAttribute<AuthorizeAttribute>()!.Policy.Should().Be("AdminOnly");
}
}
@@ -0,0 +1,190 @@
using System.ComponentModel.DataAnnotations;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using NSubstitute;
using SlpModularCms.Core.Hosting.Website;
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 OfferingBannersServiceTests
{
private sealed class FakeTimeProvider(DateTimeOffset start) : TimeProvider
{
private DateTimeOffset _now = start;
public override DateTimeOffset GetUtcNow() => _now;
public void Advance(TimeSpan by) => _now += by;
}
private static readonly DateTimeOffset Now = new(2026, 11, 12, 12, 0, 0, TimeSpan.Zero);
private readonly IOfferingBannerRepository _repo = Substitute.For<IOfferingBannerRepository>();
private readonly FakeTimeProvider _time = new(Now);
private readonly IIndexHtmlCache _cache = Substitute.For<IIndexHtmlCache>();
private OfferingBannersService Sut() =>
new(_repo, Substitute.For<ILogger<OfferingBannersService>>(), _time, _cache);
private static OfferingBanner Banner(string title, bool active = true, DateTimeOffset? from = null, DateTimeOffset? to = null,
DateTimeOffset? updated = null) => new()
{
Id = Guid.NewGuid(), Title = title, Text = "Tekst", IsActive = active, StartsAt = from, EndsAt = to,
UpdatedAt = updated ?? Now.AddDays(-1),
};
private void Switched(params OfferingBanner[] banners) => _repo.GetSwitchedOnAsync().Returns(banners);
[Fact]
public async Task GetActive_ReturnsNull_WhenNothingIsSwitchedOn()
{
Switched();
(await Sut().GetActiveAsync()).Should().BeNull();
}
[Fact]
public async Task GetActive_ReturnsOnlyTheContent_ForABannerWithoutSchedule()
{
var banner = Banner("Actie");
banner.LinkLabel = "Bekijk";
banner.LinkUrl = "/aanbieding";
Switched(banner);
var result = await Sut().GetActiveAsync();
result.Should().Be(new PublicOfferingBannerDto("Actie", "Tekst", "Bekijk", "/aanbieding"));
}
[Fact]
public async Task GetActive_AppliesTheScheduleAtShowTime()
{
Switched(
Banner("future", from: Now.AddHours(1)),
Banner("past", to: Now.AddHours(-1)),
Banner("ended-exactly-now", to: Now));
(await Sut().GetActiveAsync()).Should().BeNull();
_time.Advance(TimeSpan.FromHours(2));
(await Sut().GetActiveAsync())!.Title.Should().Be("future");
}
[Fact]
public async Task GetActive_StartsInclusive()
{
Switched(Banner("now", from: Now));
(await Sut().GetActiveAsync())!.Title.Should().Be("now");
}
[Fact]
public async Task GetActive_PicksTheMostRecentlyChanged_WhenSeveralQualify()
{
Switched(Banner("old", updated: Now.AddDays(-5)), Banner("new", updated: Now.AddDays(-1)));
(await Sut().GetActiveAsync())!.Title.Should().Be("new");
}
[Fact]
public async Task Create_TrimsText_StoresLinkOnlyWhenComplete_AndInvalidatesTheCache()
{
OfferingBanner? saved = null;
await _repo.AddAsync(Arg.Do<OfferingBanner>(b => saved = b));
var dto = await Sut().CreateAsync(new OfferingBannerRequest(" Actie ", " Tekst ", " ", null), Guid.NewGuid());
saved!.Title.Should().Be("Actie");
saved.Text.Should().Be("Tekst");
saved.LinkLabel.Should().BeNull();
saved.LinkUrl.Should().BeNull();
dto.IsActive.Should().BeTrue();
await _repo.Received(1).SaveChangesAsync();
_cache.Received(1).Invalidate();
}
[Fact]
public async Task Update_ReplacesEverything_ReturnsNullForUnknown_AndDeleteRemoves()
{
var banner = Banner("Oud");
_repo.GetByIdAsync(banner.Id).Returns(banner);
_repo.GetByIdAsync(Arg.Is<Guid>(g => g != banner.Id)).Returns((OfferingBanner?)null);
var updated = await Sut().UpdateAsync(banner.Id, new OfferingBannerRequest("Nieuw", "T2", "Ga", "https://x.nl/a", false, Now, Now.AddDays(1)), Guid.NewGuid());
updated!.Title.Should().Be("Nieuw");
updated.LinkUrl.Should().Be("https://x.nl/a");
updated.IsActive.Should().BeFalse();
banner.UpdatedAt.Should().Be(Now);
(await Sut().UpdateAsync(Guid.NewGuid(), new OfferingBannerRequest("a", "b"), Guid.NewGuid())).Should().BeNull();
(await Sut().DeleteAsync(banner.Id)).Should().BeTrue();
_repo.Received(1).Remove(banner);
(await Sut().DeleteAsync(Guid.NewGuid())).Should().BeFalse();
}
private static List<ValidationResult> Validate(OfferingBannerRequest r)
{
var results = new List<ValidationResult>();
Validator.TryValidateObject(r, new ValidationContext(r), results, validateAllProperties: true);
return results;
}
[Theory]
[InlineData("https://slpsoftware.nl/actie", true)]
[InlineData("/aanbieding", true)]
[InlineData("/", true)]
[InlineData("http://slpsoftware.nl", false)]
[InlineData("//evil.example", false)]
[InlineData("/\evil", false)]
[InlineData("javascript:alert(1)", false)]
[InlineData("mailto:a@b.nl", false)]
[InlineData("actie", false)]
[InlineData("https://", false)]
[InlineData("/with space", false)]
public void Link_AllowsOnlyHttpsOrSiteRelativePaths(string url, bool valid)
{
var errors = Validate(new OfferingBannerRequest("T", "X", "Ga", url));
errors.Count.Should().Be(valid ? 0 : 1);
}
[Fact]
public void Link_LabelAndUrlComeTogether()
{
Validate(new OfferingBannerRequest("T", "X", "Ga", null)).Should().HaveCount(1);
Validate(new OfferingBannerRequest("T", "X", null, "/x")).Should().HaveCount(1);
Validate(new OfferingBannerRequest("T", "X")).Should().BeEmpty();
}
[Fact]
public void Schedule_EndMustBeAfterStart()
{
Validate(new OfferingBannerRequest("T", "X", StartsAt: Now, EndsAt: Now)).Should().HaveCount(1);
Validate(new OfferingBannerRequest("T", "X", StartsAt: Now, EndsAt: Now.AddMinutes(1))).Should().BeEmpty();
Validate(new OfferingBannerRequest("T", "X", EndsAt: Now)).Should().BeEmpty();
}
[Theory]
[InlineData("Title", 100)]
[InlineData("Text", 300)]
[InlineData("LinkLabel", 50)]
[InlineData("LinkUrl", 500)]
public void Fields_AreLimited(string name, int max)
{
// MVC validates record constructor parameters; the attributes sit on the parameter itself.
var parameter = typeof(OfferingBannerRequest).GetConstructors()[0].GetParameters().Single(p => p.Name == name);
var maxLength = (MaxLengthAttribute)parameter.GetCustomAttributes(typeof(MaxLengthAttribute), false).Single();
maxLength.Length.Should().Be(max);
}
[Theory]
[InlineData("Title")]
[InlineData("Text")]
public void TitleAndText_AreRequired(string name)
{
var parameter = typeof(OfferingBannerRequest).GetConstructors()[0].GetParameters().Single(p => p.Name == name);
var required = (RequiredAttribute)parameter.GetCustomAttributes(typeof(RequiredAttribute), false).Single();
required.IsValid("").Should().BeFalse();
required.IsValid("x").Should().BeTrue();
}
}
@@ -8,8 +8,8 @@ namespace SlpModularCms.Modules.Offerings.Tests.Services;
public class OfferingsIndexMarkersTests
{
private static OfferingDto Dto(string title, string price = "€ 300", string note = "eenmalig", string layout = "card") => new(
Guid.NewGuid().ToString(), "slug", title, "Beschrijving", price, note, ["a"], "Start", false, 0, null, null, layout);
private static OfferingDto Dto(string title, string price = "€ 300", string note = "eenmalig") => new(
Guid.NewGuid().ToString(), "slug", title, "Beschrijving", price, note, ["a"], "Start", false, 0, null, null);
[Theory]
[InlineData("€ 300", "300")]
@@ -25,9 +25,9 @@ public class OfferingsIndexMarkersTests
=> OfferingsIndexMarkers.ParsePrice(label).Should().Be(expected);
[Fact]
public void JsonLd_IsAnItemListOfOffers_WithPositions_AndTheBannerIncluded()
public void JsonLd_IsAnItemListOfOffers_WithPositions()
{
var json = OfferingsIndexMarkers.JsonLd([Dto("Start"), Dto("Banner", layout: "banner")], "https://slpsoftware.nl");
var json = OfferingsIndexMarkers.JsonLd([Dto("Start"), Dto("Pro")], "https://slpsoftware.nl");
json.Should().StartWith("<script type=\"application/ld+json\">").And.EndWith("</script>");
var doc = JsonDocument.Parse(json["<script type=\"application/ld+json\">".Length..^"</script>".Length]).RootElement;
@@ -267,6 +267,9 @@ public class OfferingsServiceTests
offering.DeletedAt.Should().NotBeNull();
}
private static UpdateOfferingRequest UpdateRequest() => new(
"Existing", "Description", "€ 100", "per month", ["Feature 1"], "Contact");
[Fact]
public async Task EveryChange_InvalidatesTheWebsitePageCache()
{
@@ -277,105 +280,13 @@ public class OfferingsServiceTests
_repo.GetAllAsync().Returns([offering]);
await sut.CreateAsync(CreateRequest(), Guid.NewGuid());
await sut.UpdateAsync(offering.Id, UpdateRequestWithLayout(null), Guid.NewGuid());
await sut.UpdateAsync(offering.Id, UpdateRequest(), Guid.NewGuid());
await sut.ReorderAsync([offering.Id], Guid.NewGuid());
await sut.DeleteAsync(offering.Id, Guid.NewGuid());
cache.Received(4).Invalidate();
}
// --- Layout (card/banner), at most one banner ---
private static CreateOfferingRequest CreateRequestWithLayout(string? layout) => new(
"Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", Layout: layout);
private static UpdateOfferingRequest UpdateRequestWithLayout(string? layout) => new(
"Existing", "Description", "€ 100", "per month", ["Feature 1"], "Contact", Layout: layout);
[Fact]
public async Task CreateAsync_DefaultsLayoutToCard_WhenOmitted()
{
var result = await CreateSut().CreateAsync(CreateRequestWithLayout(null), Guid.NewGuid());
result.Layout.Should().Be("card");
await _repo.DidNotReceive().GetBannerAsync();
}
[Fact]
public async Task CreateAsync_DemotesCurrentBanner_WhenNewOneIsBanner()
{
var current = ExistingOffering();
current.Layout = "banner";
_repo.GetBannerAsync().Returns(current);
var result = await CreateSut().CreateAsync(CreateRequestWithLayout("banner"), Guid.NewGuid());
result.Layout.Should().Be("banner");
current.Layout.Should().Be("card");
}
[Fact]
public async Task UpdateAsync_KeepsLayout_WhenOmitted()
{
var target = ExistingOffering();
target.Layout = "banner";
_repo.GetByIdAsync(target.Id).Returns(target);
_repo.GetBannerAsync().Returns(target);
var result = await CreateSut().UpdateAsync(target.Id, UpdateRequestWithLayout(null), Guid.NewGuid());
result!.Layout.Should().Be("banner");
}
[Fact]
public async Task UpdateAsync_DemotesOtherBanner_ButNotItself()
{
var target = ExistingOffering();
var other = ExistingOffering();
other.Layout = "banner";
_repo.GetByIdAsync(target.Id).Returns(target);
_repo.GetBannerAsync().Returns(other);
await CreateSut().UpdateAsync(target.Id, UpdateRequestWithLayout("banner"), Guid.NewGuid());
target.Layout.Should().Be("banner");
other.Layout.Should().Be("card");
// already the banner: stays one
_repo.GetBannerAsync().Returns(target);
await CreateSut().UpdateAsync(target.Id, UpdateRequestWithLayout("banner"), Guid.NewGuid());
target.Layout.Should().Be("banner");
}
[Fact]
public async Task UpdateAsync_CanReturnBannerToCard()
{
var target = ExistingOffering();
target.Layout = "banner";
_repo.GetByIdAsync(target.Id).Returns(target);
var result = await CreateSut().UpdateAsync(target.Id, UpdateRequestWithLayout("card"), Guid.NewGuid());
result!.Layout.Should().Be("card");
}
[Theory]
[InlineData("card", true)]
[InlineData("banner", true)]
[InlineData(null, true)]
[InlineData("hero", false)]
[InlineData("Card", false)]
public void Request_validates_layout_values(string? layout, bool valid)
{
// MVC validates record constructor parameters; check the attribute declared on the parameter itself.
var parameter = typeof(CreateOfferingRequest).GetConstructors()[0].GetParameters().Single(p => p.Name == "Layout");
var attribute = (System.ComponentModel.DataAnnotations.ValidationAttribute)parameter
.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.RegularExpressionAttribute), false).Single();
var ok = attribute.IsValid(layout);
ok.Should().Be(valid);
}
[Theory]
[InlineData(typeof(CreateOfferingRequest), "Description", true)]
[InlineData(typeof(CreateOfferingRequest), "PriceNote", true)]
@@ -0,0 +1,60 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using SlpModularCms.Core.Availability;
using SlpModularCms.Modules.Offerings.Models;
using SlpModularCms.Modules.Offerings.Services;
namespace SlpModularCms.Modules.Offerings.Controllers;
/// <summary>Management of offering banners. Administrators only; visitors use <c>GET /offerings/banner</c>.</summary>
[ApiController]
[Route("offerings/banners")]
[Authorize(Policy = "AdminOnly")]
public class OfferingBannersController(IOfferingBannersService service) : ControllerBase
{
[HttpGet]
public async Task<IActionResult> List() => Ok(await service.ListAsync());
[HttpPost]
public async Task<IActionResult> Create([FromBody] OfferingBannerRequest request)
{
var dto = await service.CreateAsync(request, GetCallerId());
return Created($"/api/v1/offerings/banners/{dto.Id}", dto);
}
[HttpPut("{id:guid}")]
public async Task<IActionResult> Update(Guid id, [FromBody] OfferingBannerRequest request)
{
var dto = await service.UpdateAsync(id, request, GetCallerId());
return dto is null ? NotFound() : Ok(dto);
}
[HttpDelete("{id:guid}")]
public async Task<IActionResult> Delete(Guid id)
=> await service.DeleteAsync(id) ? NoContent() : NotFound();
private Guid GetCallerId()
{
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
}
}
/// <summary>The banner visitors see: 200 with the one active banner, otherwise 204.</summary>
[ApiController]
[Route("offerings/banner")]
public class PublicOfferingBannerController(IOfferingBannersService service) : ControllerBase
{
[HttpGet]
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting("offerings-public")]
public async Task<IActionResult> Get()
{
Response.Headers.CacheControl = "public, max-age=60";
var current = await service.GetActiveAsync();
return current is null ? NoContent() : Ok(current);
}
}
@@ -11,9 +11,6 @@ public class Offering
public List<string> Features { get; set; } = [];
public string CtaLabel { get; set; } = string.Empty;
public bool Featured { get; set; }
/// <summary>Presentation on the website: "card" (default) or "banner" (at most one per site).</summary>
public string Layout { get; set; } = OfferingLayouts.Card;
public Guid? CategoryId { get; set; }
public OfferingCategory? Category { get; set; }
public int DisplayOrder { get; set; }
@@ -0,0 +1,25 @@
namespace SlpModularCms.Modules.Offerings.Data.Entities;
/// <summary>
/// A site-wide banner for offers and campaigns. Several can be stored (for example
/// planned ones with a start and end); the public API shows the one that is active right now.
/// </summary>
public class OfferingBanner
{
public Guid Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
/// <summary>Optional button; <see cref="LinkLabel"/> and <see cref="LinkUrl"/> are both set or both null.</summary>
public string? LinkLabel { get; set; }
/// <summary>An absolute https:// URL or a site-relative path starting with a single "/".</summary>
public string? LinkUrl { get; set; }
public bool IsActive { get; set; }
public DateTimeOffset? StartsAt { get; set; }
public DateTimeOffset? EndsAt { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public Guid LastModifiedByUserId { get; set; }
}
@@ -1,7 +0,0 @@
namespace SlpModularCms.Modules.Offerings.Data.Entities;
public static class OfferingLayouts
{
public const string Card = "card";
public const string Banner = "banner";
}
@@ -9,6 +9,7 @@ public class OfferingsDbContext(DbContextOptions<OfferingsDbContext> options) :
{
public DbSet<Offering> Offerings => Set<Offering>();
public DbSet<OfferingCategory> OfferingCategories => Set<OfferingCategory>();
public DbSet<OfferingBanner> OfferingBanners => Set<OfferingBanner>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -24,7 +25,6 @@ public class OfferingsDbContext(DbContextOptions<OfferingsDbContext> options) :
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.Layout).IsRequired().HasMaxLength(10).HasDefaultValue(OfferingLayouts.Card);
entity.Property(e => e.DisplayOrder).IsRequired();
entity.Property(e => e.IsDeleted).IsRequired();
entity.Property(e => e.CreatedAt).IsRequired();
@@ -54,6 +54,20 @@ public class OfferingsDbContext(DbContextOptions<OfferingsDbContext> options) :
entity.HasQueryFilter(e => !e.IsDeleted);
});
modelBuilder.Entity<OfferingBanner>(entity =>
{
entity.ToTable("OfferingsBanners");
entity.HasKey(e => e.Id);
entity.Property(e => e.Title).IsRequired().HasMaxLength(100);
entity.Property(e => e.Text).IsRequired().HasMaxLength(300);
entity.Property(e => e.LinkLabel).HasMaxLength(50);
entity.Property(e => e.LinkUrl).HasMaxLength(500);
entity.Property(e => e.IsActive).IsRequired();
entity.Property(e => e.CreatedAt).IsRequired();
entity.Property(e => e.UpdatedAt).IsRequired();
entity.Property(e => e.LastModifiedByUserId).IsRequired();
});
modelBuilder.Entity<OfferingCategory>(entity =>
{
entity.ToTable("OfferingsCategories");
@@ -0,0 +1,182 @@
// <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("20261112100000_AddOfferingBannerRemoveLayout")]
partial class AddOfferingBannerRemoveLayout
{
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.OfferingBanner", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset?>("EndsAt")
.HasColumnType("datetime");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
b.Property<string>("LinkLabel")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("LinkUrl")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<DateTimeOffset?>("StartsAt")
.HasColumnType("datetime");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(300)
.HasColumnType("varchar(300)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.ToTable("OfferingsBanners", (string)null);
});
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
}
}
}
@@ -0,0 +1,55 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Offerings.Migrations
{
/// <inheritdoc />
public partial class AddOfferingBannerRemoveLayout : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Layout",
table: "OfferingsOfferings");
migrationBuilder.CreateTable(
name: "OfferingsBanners",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Title = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Text = table.Column<string>(type: "varchar(300)", maxLength: 300, nullable: false),
LinkLabel = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true),
LinkUrl = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false),
StartsAt = table.Column<DateTimeOffset>(type: "datetime", nullable: true),
EndsAt = 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_OfferingsBanners", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "OfferingsBanners");
migrationBuilder.AddColumn<string>(
name: "Layout",
table: "OfferingsOfferings",
type: "varchar(10)",
maxLength: 10,
nullable: false,
defaultValue: "card");
}
}
}
@@ -19,6 +19,53 @@ namespace SlpModularCms.Modules.Offerings.Migrations
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingBanner", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset?>("EndsAt")
.HasColumnType("datetime");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
b.Property<string>("LinkLabel")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("LinkUrl")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<DateTimeOffset?>("StartsAt")
.HasColumnType("datetime");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(300)
.HasColumnType("varchar(300)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.ToTable("OfferingsBanners", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b =>
{
b.Property<Guid>("Id")
@@ -57,13 +104,6 @@ namespace SlpModularCms.Modules.Offerings.Migrations
b.Property<bool>("IsDeleted")
.HasColumnType("tinyint(1)");
b.Property<string>("Layout")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.HasColumnType("varchar(10)")
.HasDefaultValue("card");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
@@ -11,6 +11,5 @@ public record CreateOfferingRequest(
[Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel,
bool Featured = false,
[MaxLength(130)] string? Slug = null,
Guid? CategoryId = null,
[RegularExpression("^(card|banner)$", ErrorMessage = "Layout must be 'card' or 'banner'.")] string? Layout = null
Guid? CategoryId = null
);
@@ -0,0 +1,62 @@
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Modules.Offerings.Models;
/// <summary>Administrator view of a banner.</summary>
[ExcludeFromCodeCoverage]
public record OfferingBannerDto(
string Id,
string Title,
string Text,
string? LinkLabel,
string? LinkUrl,
bool IsActive,
DateTimeOffset? StartsAt,
DateTimeOffset? EndsAt,
DateTimeOffset UpdatedAt);
/// <summary>What visitors get: only the content to show, never the scheduling.</summary>
[ExcludeFromCodeCoverage]
public record PublicOfferingBannerDto(string Title, string Text, string? LinkLabel, string? LinkUrl);
/// <summary>Create and full-replace (PUT) body. Empty link fields are stored as null.</summary>
public record OfferingBannerRequest(
[Required, MaxLength(100)] string Title,
[Required, MaxLength(300)] string Text,
[MaxLength(50)] string? LinkLabel = null,
[MaxLength(500)] string? LinkUrl = null,
bool IsActive = true,
DateTimeOffset? StartsAt = null,
DateTimeOffset? EndsAt = null) : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var hasLabel = !string.IsNullOrWhiteSpace(LinkLabel);
var hasUrl = !string.IsNullOrWhiteSpace(LinkUrl);
if (hasLabel != hasUrl)
yield return new ValidationResult("Link label and link URL must be given together.", [nameof(LinkLabel), nameof(LinkUrl)]);
else if (hasUrl && !OfferingBannerLinks.IsAllowed(LinkUrl!.Trim()))
yield return new ValidationResult("Link URL must be an https:// address or a site path starting with '/'.", [nameof(LinkUrl)]);
if (StartsAt is not null && EndsAt is not null && EndsAt <= StartsAt)
yield return new ValidationResult("EndsAt must be after StartsAt.", [nameof(EndsAt)]);
}
}
public static class OfferingBannerLinks
{
/// <summary>https:// with a host, or a site-relative path with a single leading "/" (never "//host" or "/\").</summary>
public static bool IsAllowed(string url)
{
if (url.Any(c => char.IsWhiteSpace(c) || char.IsControl(c) || c == '\\')) return false;
if (url.StartsWith('/'))
return !url.StartsWith("//", StringComparison.Ordinal);
return Uri.TryCreate(url, UriKind.Absolute, out var uri)
&& uri.Scheme == Uri.UriSchemeHttps
&& !string.IsNullOrEmpty(uri.Host);
}
}
@@ -19,6 +19,5 @@ public record OfferingDto(
bool Featured,
int DisplayOrder,
string? CategoryId = null,
string? Category = null,
string Layout = "card"
string? Category = null
);
@@ -11,6 +11,5 @@ public record UpdateOfferingRequest(
[Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel,
bool Featured = false,
[MaxLength(130)] string? Slug = null,
Guid? CategoryId = null,
[RegularExpression("^(card|banner)$", ErrorMessage = "Layout must be 'card' or 'banner'.")] string? Layout = null
Guid? CategoryId = null
);
@@ -31,6 +31,8 @@ public class OfferingsModule : IModule
services.AddScoped<IOfferingRepository, OfferingRepository>();
services.AddScoped<IOfferingsService, OfferingsService>();
services.AddScoped<IIndexHtmlMarkerProvider, OfferingsIndexMarkers>();
services.AddScoped<IOfferingBannerRepository, OfferingBannerRepository>();
services.AddScoped<IOfferingBannersService, OfferingBannersService>();
services.AddScoped<IOfferingCategoryRepository, OfferingCategoryRepository>();
services.AddScoped<IOfferingCategoriesService, OfferingCategoriesService>();
services.AddHttpContextAccessor();
@@ -12,7 +12,6 @@ public interface IOfferingRepository
void Update(Offering offering);
Task<int> GetMaxDisplayOrderAsync();
Task<Offering?> GetFeaturedAsync();
Task<Offering?> GetBannerAsync();
Task SaveChangesAsync();
Task<IDbContextTransaction> BeginTransactionAsync();
}
@@ -0,0 +1,41 @@
using Microsoft.EntityFrameworkCore;
using SlpModularCms.Modules.Offerings.Data;
using SlpModularCms.Modules.Offerings.Data.Entities;
namespace SlpModularCms.Modules.Offerings.Repositories;
public interface IOfferingBannerRepository
{
/// <summary>All banners, most recently changed first.</summary>
Task<IReadOnlyList<OfferingBanner>> GetAllAsync();
Task<OfferingBanner?> GetByIdAsync(Guid id);
/// <summary>Banners switched on (IsActive); the schedule is applied by the caller.</summary>
Task<IReadOnlyList<OfferingBanner>> GetSwitchedOnAsync();
Task AddAsync(OfferingBanner banner);
void Update(OfferingBanner banner);
void Remove(OfferingBanner banner);
Task SaveChangesAsync();
}
public class OfferingBannerRepository(OfferingsDbContext context) : IOfferingBannerRepository
{
public async Task<IReadOnlyList<OfferingBanner>> GetAllAsync()
=> (await context.OfferingBanners.ToListAsync()).OrderByDescending(b => b.UpdatedAt).ToList();
public async Task<OfferingBanner?> GetByIdAsync(Guid id)
=> await context.OfferingBanners.FirstOrDefaultAsync(b => b.Id == id);
public async Task<IReadOnlyList<OfferingBanner>> GetSwitchedOnAsync()
=> await context.OfferingBanners.Where(b => b.IsActive).ToListAsync();
public async Task AddAsync(OfferingBanner banner) => await context.OfferingBanners.AddAsync(banner);
public void Update(OfferingBanner banner) => context.OfferingBanners.Update(banner);
public void Remove(OfferingBanner banner) => context.OfferingBanners.Remove(banner);
public async Task SaveChangesAsync() => await context.SaveChangesAsync();
}
@@ -28,9 +28,6 @@ public class OfferingRepository(OfferingsDbContext context) : IOfferingRepositor
public async Task<Offering?> GetFeaturedAsync()
=> await context.Offerings.FirstOrDefaultAsync(o => o.Featured);
public async Task<Offering?> GetBannerAsync()
=> await context.Offerings.FirstOrDefaultAsync(o => o.Layout == OfferingLayouts.Banner);
public async Task SaveChangesAsync()
=> await context.SaveChangesAsync();
@@ -0,0 +1,105 @@
using Microsoft.Extensions.Logging;
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Modules.Offerings.Data.Entities;
using SlpModularCms.Modules.Offerings.Models;
using SlpModularCms.Modules.Offerings.Repositories;
namespace SlpModularCms.Modules.Offerings.Services;
public interface IOfferingBannersService
{
Task<IReadOnlyList<OfferingBannerDto>> ListAsync();
/// <summary>The one banner that is switched on and inside its schedule right now, or null.</summary>
Task<PublicOfferingBannerDto?> GetActiveAsync();
Task<OfferingBannerDto> CreateAsync(OfferingBannerRequest request, Guid callerId);
Task<OfferingBannerDto?> UpdateAsync(Guid id, OfferingBannerRequest request, Guid callerId);
Task<bool> DeleteAsync(Guid id);
}
public class OfferingBannersService(
IOfferingBannerRepository repository,
ILogger<OfferingBannersService> logger,
TimeProvider? time = null,
IIndexHtmlCache? indexCache = null) : IOfferingBannersService
{
private readonly TimeProvider _time = time ?? TimeProvider.System;
public async Task<IReadOnlyList<OfferingBannerDto>> ListAsync()
=> (await repository.GetAllAsync()).Select(ToDto).ToList();
public async Task<PublicOfferingBannerDto?> GetActiveAsync()
{
var now = _time.GetUtcNow();
// Several can be switched on (planned ones, overlaps); the most recently changed wins.
var current = (await repository.GetSwitchedOnAsync())
.Where(b => (b.StartsAt is null || b.StartsAt <= now) && (b.EndsAt is null || now < b.EndsAt))
.OrderByDescending(b => b.UpdatedAt)
.FirstOrDefault();
return current is null ? null : new PublicOfferingBannerDto(current.Title, current.Text, current.LinkLabel, current.LinkUrl);
}
public async Task<OfferingBannerDto> CreateAsync(OfferingBannerRequest request, Guid callerId)
{
var now = _time.GetUtcNow();
var banner = new OfferingBanner { Id = Guid.NewGuid(), CreatedAt = now };
Apply(banner, request, now, callerId);
await repository.AddAsync(banner);
await repository.SaveChangesAsync();
Changed(banner.Id, "Created", callerId);
return ToDto(banner);
}
public async Task<OfferingBannerDto?> UpdateAsync(Guid id, OfferingBannerRequest request, Guid callerId)
{
var banner = await repository.GetByIdAsync(id);
if (banner is null) return null;
Apply(banner, request, _time.GetUtcNow(), callerId);
repository.Update(banner);
await repository.SaveChangesAsync();
Changed(id, "Updated", callerId);
return ToDto(banner);
}
public async Task<bool> DeleteAsync(Guid id)
{
var banner = await repository.GetByIdAsync(id);
if (banner is null) return false;
repository.Remove(banner);
await repository.SaveChangesAsync();
Changed(id, "Deleted", null);
return true;
}
private static void Apply(OfferingBanner b, OfferingBannerRequest r, DateTimeOffset now, Guid callerId)
{
var hasLink = !string.IsNullOrWhiteSpace(r.LinkUrl) && !string.IsNullOrWhiteSpace(r.LinkLabel);
b.Title = r.Title.Trim();
b.Text = r.Text.Trim();
b.LinkLabel = hasLink ? r.LinkLabel!.Trim() : null;
b.LinkUrl = hasLink ? r.LinkUrl!.Trim() : null;
b.IsActive = r.IsActive;
b.StartsAt = r.StartsAt;
b.EndsAt = r.EndsAt;
b.UpdatedAt = now;
b.LastModifiedByUserId = callerId;
}
private void Changed(Guid id, string action, Guid? callerId)
{
indexCache?.Invalidate();
logger.LogInformation("Offering banner {BannerId} {Action} by user {LastModifiedByUserId}", id, action, callerId);
}
private static OfferingBannerDto ToDto(OfferingBanner b) => new(
b.Id.ToString(), b.Title, b.Text, b.LinkLabel, b.LinkUrl, b.IsActive, b.StartsAt, b.EndsAt, b.UpdatedAt);
}
@@ -35,7 +35,6 @@ public class OfferingsService(
CategoryId = category?.Id,
Category = category,
Featured = request.Featured,
Layout = request.Layout ?? OfferingLayouts.Card,
DisplayOrder = await repository.GetMaxDisplayOrderAsync() + 1,
CreatedAt = now,
UpdatedAt = now,
@@ -46,11 +45,10 @@ public class OfferingsService(
// 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 || offering.Layout == OfferingLayouts.Banner)
if (request.Featured)
{
await using var transaction = await repository.BeginTransactionAsync();
if (request.Featured) await UnfeatureCurrentAsync();
if (offering.Layout == OfferingLayouts.Banner) await DemoteCurrentBannerAsync();
await UnfeatureCurrentAsync();
await repository.AddAsync(offering);
await repository.SaveChangesAsync();
await transaction.CommitAsync();
@@ -95,16 +93,13 @@ public class OfferingsService(
offering.CategoryId = category?.Id;
offering.Category = category;
offering.Featured = request.Featured;
// Layout is additive: older clients omit it, which keeps the stored value.
if (request.Layout is not null) offering.Layout = request.Layout;
offering.UpdatedAt = DateTimeOffset.UtcNow;
offering.LastModifiedByUserId = callerId;
if (request.Featured || offering.Layout == OfferingLayouts.Banner)
if (request.Featured)
{
await using var transaction = await repository.BeginTransactionAsync();
if (request.Featured) await UnfeatureCurrentAsync(exceptId: offering.Id);
if (offering.Layout == OfferingLayouts.Banner) await DemoteCurrentBannerAsync(exceptId: offering.Id);
await UnfeatureCurrentAsync(exceptId: offering.Id);
repository.Update(offering);
await repository.SaveChangesAsync();
await transaction.CommitAsync();
@@ -193,18 +188,6 @@ public class OfferingsService(
repository.Update(current);
}
// At most one banner per site: promoting another offering demotes the current one to a card.
private async Task DemoteCurrentBannerAsync(Guid? exceptId = null)
{
var current = await repository.GetBannerAsync();
if (current is null || current.Id == exceptId)
return;
current.Layout = OfferingLayouts.Card;
current.UpdatedAt = DateTimeOffset.UtcNow;
repository.Update(current);
}
private async Task<OfferingCategory?> ResolveCategoryAsync(Guid? categoryId)
{
if (categoryId is null)
@@ -260,7 +243,6 @@ public class OfferingsService(
o.Featured,
o.DisplayOrder,
o.CategoryId?.ToString(),
o.Category?.Name,
o.Layout
o.Category?.Name
);
}