diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 1427866..83236be 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -437,12 +437,6 @@ }, "type": "array" }, - "layout": { - "type": [ - "null", - "string" - ] - }, "price": { "type": "string" }, @@ -535,6 +529,51 @@ ], "type": "object" }, + "OfferingBannerRequest": { + "properties": { + "endsAt": { + "format": "date-time", + "type": [ + "null", + "string" + ] + }, + "isActive": { + "default": true, + "type": "boolean" + }, + "linkLabel": { + "type": [ + "null", + "string" + ] + }, + "linkUrl": { + "type": [ + "null", + "string" + ] + }, + "startsAt": { + "format": "date-time", + "type": [ + "null", + "string" + ] + }, + "text": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "title", + "text" + ], + "type": "object" + }, "OfferingCategoryRequest": { "properties": { "name": { @@ -783,12 +822,6 @@ }, "type": "array" }, - "layout": { - "type": [ - "null", - "string" - ] - }, "price": { "type": "string" }, @@ -2223,6 +2256,124 @@ ] } }, + "/api/v1/offerings/banner": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "PublicOfferingBanner" + ] + } + }, + "/api/v1/offerings/banners": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingBanners" + ] + }, + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingBanners" + ] + } + }, + "/api/v1/offerings/banners/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingBanners" + ] + }, + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingBanners" + ] + } + }, "/api/v1/offerings/categories": { "get": { "responses": { @@ -2482,6 +2633,12 @@ { "name": "SlaveStatus" }, + { + "name": "OfferingBanners" + }, + { + "name": "PublicOfferingBanner" + }, { "name": "OfferingCategories" }, diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs index 41b42b3..a9fcb19 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs +++ b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs @@ -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 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(); + + db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot"); + } + [Fact] public async Task Health_IsReachable() { diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs index 78aed46..d26339f 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs @@ -9,7 +9,7 @@ namespace SlpModularCms.Modules.Offerings.Tests.Controllers; public class OfferingsPublicMarkerTests { private static IEnumerable 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() 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().Should().NotBeNull(); + get.GetCustomAttribute().Should().NotBeNull(); + typeof(OfferingBannersController).GetCustomAttribute()!.Policy.Should().Be("AdminOnly"); + } } diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingBannersServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingBannersServiceTests.cs new file mode 100644 index 0000000..423318c --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingBannersServiceTests.cs @@ -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(); + private readonly FakeTimeProvider _time = new(Now); + private readonly IIndexHtmlCache _cache = Substitute.For(); + + private OfferingBannersService Sut() => + new(_repo, Substitute.For>(), _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(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(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 Validate(OfferingBannerRequest r) + { + var results = new List(); + 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(); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsIndexMarkersTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsIndexMarkersTests.cs index 49595b3..9bfa942 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsIndexMarkersTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsIndexMarkersTests.cs @@ -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(""); var doc = JsonDocument.Parse(json["".Length]).RootElement; diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs index 659ca5a..9f968c2 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs @@ -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)] diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingBannersController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingBannersController.cs new file mode 100644 index 0000000..767804e --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingBannersController.cs @@ -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; + +/// Management of offering banners. Administrators only; visitors use GET /offerings/banner. +[ApiController] +[Route("offerings/banners")] +[Authorize(Policy = "AdminOnly")] +public class OfferingBannersController(IOfferingBannersService service) : ControllerBase +{ + [HttpGet] + public async Task List() => Ok(await service.ListAsync()); + + [HttpPost] + public async Task 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 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 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; + } +} + +/// The banner visitors see: 200 with the one active banner, otherwise 204. +[ApiController] +[Route("offerings/banner")] +public class PublicOfferingBannerController(IOfferingBannersService service) : ControllerBase +{ + [HttpGet] + [AllowAnonymous] + [PublicSiteEndpoint] + [EnableRateLimiting("offerings-public")] + public async Task Get() + { + Response.Headers.CacheControl = "public, max-age=60"; + var current = await service.GetActiveAsync(); + return current is null ? NoContent() : Ok(current); + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs index 1bc0383..12f87eb 100644 --- a/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs +++ b/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs @@ -11,9 +11,6 @@ public class Offering public List Features { get; set; } = []; public string CtaLabel { get; set; } = string.Empty; public bool Featured { get; set; } - - /// Presentation on the website: "card" (default) or "banner" (at most one per site). - public string Layout { get; set; } = OfferingLayouts.Card; public Guid? CategoryId { get; set; } public OfferingCategory? Category { get; set; } public int DisplayOrder { get; set; } diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingBanner.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingBanner.cs new file mode 100644 index 0000000..11d6544 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingBanner.cs @@ -0,0 +1,25 @@ +namespace SlpModularCms.Modules.Offerings.Data.Entities; + +/// +/// 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. +/// +public class OfferingBanner +{ + public Guid Id { get; set; } + public string Title { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + + /// Optional button; and are both set or both null. + public string? LinkLabel { get; set; } + + /// An absolute https:// URL or a site-relative path starting with a single "/". + 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; } +} diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingLayouts.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingLayouts.cs deleted file mode 100644 index 75fc3eb..0000000 --- a/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingLayouts.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SlpModularCms.Modules.Offerings.Data.Entities; - -public static class OfferingLayouts -{ - public const string Card = "card"; - public const string Banner = "banner"; -} diff --git a/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs b/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs index 5cab2c0..61ce8d3 100644 --- a/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs +++ b/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs @@ -9,6 +9,7 @@ public class OfferingsDbContext(DbContextOptions options) : { public DbSet Offerings => Set(); public DbSet OfferingCategories => Set(); + public DbSet OfferingBanners => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -24,7 +25,6 @@ public class OfferingsDbContext(DbContextOptions 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 options) : entity.HasQueryFilter(e => !e.IsDeleted); }); + modelBuilder.Entity(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(entity => { entity.ToTable("OfferingsCategories"); diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.Designer.cs b/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.Designer.cs new file mode 100644 index 0000000..d20ab2b --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.Designer.cs @@ -0,0 +1,182 @@ +// +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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("EndsAt") + .HasColumnType("datetime"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("LinkLabel") + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("LinkUrl") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("StartsAt") + .HasColumnType("datetime"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("varchar(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.ToTable("OfferingsBanners", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CategoryId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CtaLabel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("DeletedAt") + .HasColumnType("datetime"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Featured") + .HasColumnType("tinyint(1)"); + + b.Property("Features") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("Price") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("PriceNote") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(130) + .HasColumnType("varchar(130)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("CategoryId"); + + b.ToTable("OfferingsOfferings", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("OfferingsCategories", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.HasOne("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", "Category") + .WithMany() + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Category"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.cs b/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.cs new file mode 100644 index 0000000..dfc9823 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.cs @@ -0,0 +1,55 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Offerings.Migrations +{ + /// + public partial class AddOfferingBannerRemoveLayout : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Layout", + table: "OfferingsOfferings"); + + migrationBuilder.CreateTable( + name: "OfferingsBanners", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + Title = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Text = table.Column(type: "varchar(300)", maxLength: 300, nullable: false), + LinkLabel = table.Column(type: "varchar(50)", maxLength: 50, nullable: true), + LinkUrl = table.Column(type: "varchar(500)", maxLength: 500, nullable: true), + IsActive = table.Column(type: "tinyint(1)", nullable: false), + StartsAt = table.Column(type: "datetime", nullable: true), + EndsAt = table.Column(type: "datetime", nullable: true), + CreatedAt = table.Column(type: "datetime", nullable: false), + UpdatedAt = table.Column(type: "datetime", nullable: false), + LastModifiedByUserId = table.Column(type: "char(36)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OfferingsBanners", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OfferingsBanners"); + + migrationBuilder.AddColumn( + name: "Layout", + table: "OfferingsOfferings", + type: "varchar(10)", + maxLength: 10, + nullable: false, + defaultValue: "card"); + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs index e5043b0..6fdf5a2 100644 --- a/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs @@ -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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("EndsAt") + .HasColumnType("datetime"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("LinkLabel") + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("LinkUrl") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("StartsAt") + .HasColumnType("datetime"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("varchar(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.ToTable("OfferingsBanners", (string)null); + }); + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => { b.Property("Id") @@ -57,13 +104,6 @@ namespace SlpModularCms.Modules.Offerings.Migrations b.Property("IsDeleted") .HasColumnType("tinyint(1)"); - b.Property("Layout") - .IsRequired() - .ValueGeneratedOnAdd() - .HasMaxLength(10) - .HasColumnType("varchar(10)") - .HasDefaultValue("card"); - b.Property("LastModifiedByUserId") .HasColumnType("char(36)"); diff --git a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs index 556ccee..c1a6805 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs @@ -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 ); diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingBannerModels.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingBannerModels.cs new file mode 100644 index 0000000..facb64f --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingBannerModels.cs @@ -0,0 +1,62 @@ +using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; + +namespace SlpModularCms.Modules.Offerings.Models; + +/// Administrator view of a banner. +[ExcludeFromCodeCoverage] +public record OfferingBannerDto( + string Id, + string Title, + string Text, + string? LinkLabel, + string? LinkUrl, + bool IsActive, + DateTimeOffset? StartsAt, + DateTimeOffset? EndsAt, + DateTimeOffset UpdatedAt); + +/// What visitors get: only the content to show, never the scheduling. +[ExcludeFromCodeCoverage] +public record PublicOfferingBannerDto(string Title, string Text, string? LinkLabel, string? LinkUrl); + +/// Create and full-replace (PUT) body. Empty link fields are stored as null. +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 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 +{ + /// https:// with a host, or a site-relative path with a single leading "/" (never "//host" or "/\"). + 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); + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs index 7676147..ecabd11 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs @@ -19,6 +19,5 @@ public record OfferingDto( bool Featured, int DisplayOrder, string? CategoryId = null, - string? Category = null, - string Layout = "card" + string? Category = null ); diff --git a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs index c359c18..846ed1f 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs @@ -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 ); diff --git a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs index e5188c6..8396372 100644 --- a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs +++ b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs @@ -31,6 +31,8 @@ public class OfferingsModule : IModule services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddHttpContextAccessor(); diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs index 49c190e..28cc5a3 100644 --- a/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs +++ b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs @@ -12,7 +12,6 @@ public interface IOfferingRepository void Update(Offering offering); Task GetMaxDisplayOrderAsync(); Task GetFeaturedAsync(); - Task GetBannerAsync(); Task SaveChangesAsync(); Task BeginTransactionAsync(); } diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingBannerRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingBannerRepository.cs new file mode 100644 index 0000000..f39183d --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingBannerRepository.cs @@ -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 +{ + /// All banners, most recently changed first. + Task> GetAllAsync(); + + Task GetByIdAsync(Guid id); + + /// Banners switched on (IsActive); the schedule is applied by the caller. + Task> GetSwitchedOnAsync(); + + Task AddAsync(OfferingBanner banner); + void Update(OfferingBanner banner); + void Remove(OfferingBanner banner); + Task SaveChangesAsync(); +} + +public class OfferingBannerRepository(OfferingsDbContext context) : IOfferingBannerRepository +{ + public async Task> GetAllAsync() + => (await context.OfferingBanners.ToListAsync()).OrderByDescending(b => b.UpdatedAt).ToList(); + + public async Task GetByIdAsync(Guid id) + => await context.OfferingBanners.FirstOrDefaultAsync(b => b.Id == id); + + public async Task> 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(); +} diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs index 16aeb92..7a18382 100644 --- a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs @@ -28,9 +28,6 @@ public class OfferingRepository(OfferingsDbContext context) : IOfferingRepositor public async Task GetFeaturedAsync() => await context.Offerings.FirstOrDefaultAsync(o => o.Featured); - public async Task GetBannerAsync() - => await context.Offerings.FirstOrDefaultAsync(o => o.Layout == OfferingLayouts.Banner); - public async Task SaveChangesAsync() => await context.SaveChangesAsync(); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingBannersService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingBannersService.cs new file mode 100644 index 0000000..74f7685 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingBannersService.cs @@ -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> ListAsync(); + + /// The one banner that is switched on and inside its schedule right now, or null. + Task GetActiveAsync(); + + Task CreateAsync(OfferingBannerRequest request, Guid callerId); + Task UpdateAsync(Guid id, OfferingBannerRequest request, Guid callerId); + Task DeleteAsync(Guid id); +} + +public class OfferingBannersService( + IOfferingBannerRepository repository, + ILogger logger, + TimeProvider? time = null, + IIndexHtmlCache? indexCache = null) : IOfferingBannersService +{ + private readonly TimeProvider _time = time ?? TimeProvider.System; + + public async Task> ListAsync() + => (await repository.GetAllAsync()).Select(ToDto).ToList(); + + public async Task 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 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 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 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); +} diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs index 426f35b..166a0e2 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs @@ -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 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 ); }