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:
@@ -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");
|
||||
|
||||
+182
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -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
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user