Offerings: layout (card|banner) op aanbod, max 1 banner, admin-keuze, additief in GET /api/v1/offerings

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 22:57:36 +01:00
co-authored by Claude Sonnet 5.5
parent 60ed9f4bad
commit 69871ad6f4
20 changed files with 395 additions and 13 deletions
@@ -42,6 +42,7 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
featured: false,
slug: '',
categoryId: null,
layout: 'card',
},
});
@@ -50,6 +51,7 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
const NO_CATEGORY = 'none';
const { data: categories, isFetching: isFetchingCategories } = useOfferingCategories();
const categoryId = useWatch({ control, name: 'categoryId' });
const layout = useWatch({ control, name: 'layout' });
const selectedCategory =
categoryId != null && categories?.some((c) => c.id === categoryId) ? categoryId : NO_CATEGORY;
@@ -291,6 +293,24 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
</div>
<div className="space-y-2">
<Label htmlFor="offering-layout">{t('offerings.form.layoutLabel')}</Label>
<select
id="offering-layout"
data-testid="offering-layout"
className="h-11 w-full rounded-md border border-input bg-background px-3 text-sm"
{...register('layout')}
>
<option value="card">{t('offerings.form.layoutCard')}</option>
<option value="banner">{t('offerings.form.layoutBanner')}</option>
</select>
{layout === 'banner' && (
<p className="text-sm text-muted-foreground" data-testid="offering-layout-banner-hint">
{t('offerings.form.layoutBannerHint')}
</p>
)}
</div>
<Button type="submit" disabled={isSubmitting} data-testid="offering-form-submit">
{isSubmitting ? '…' : t('offerings.form.submitButton')}
</Button>
@@ -100,6 +100,7 @@ export const offeringsHandlers = [
const newOffering: OfferingDto = {
id: crypto.randomUUID(),
...body,
layout: body.layout ?? 'card',
slug,
displayOrder: mockOfferings.length,
};
@@ -189,8 +190,17 @@ export const offeringsHandlers = [
}
// PUT replaces the offering: an absent categoryId clears the category, as in the real API.
const updated: OfferingDto = { ...existing, ...body, slug, categoryId: body.categoryId ?? null };
mockOfferings = mockOfferings.map((o) => (o.id === id ? updated : o));
const updated: OfferingDto = {
...existing,
...body,
slug,
categoryId: body.categoryId ?? null,
layout: body.layout ?? existing.layout ?? 'card',
};
// At most one banner: promoting this one turns the current banner back into a card.
mockOfferings = mockOfferings.map((o) =>
o.id === id ? updated : updated.layout === 'banner' && o.layout === 'banner' ? { ...o, layout: 'card' } : o,
);
return HttpResponse.json(withCategoryName(updated));
}),
@@ -1,8 +1,8 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { screen } from '@testing-library/react';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderApp, mockAuthenticated } from '@/test/utils';
import { resetMockOfferings } from '@/features/offerings/mocks/handlers';
import { getMockOfferings, resetMockOfferings } from '@/features/offerings/mocks/handlers';
import { _resetSetupStatusCache } from '@/router';
beforeEach(() => {
@@ -119,4 +119,34 @@ describe('OfferingFormPage', () => {
expect(await screen.findByText(/pro.*al in gebruik|already.*taken/i)).toBeInTheDocument();
});
it('defaults the layout to card and shows a hint only when banner is chosen', async () => {
mockAuthenticated();
renderApp('/offerings/new');
const select = await screen.findByTestId('offering-layout', {}, { timeout: 10000 });
expect(select).toHaveValue('card');
expect(screen.queryByTestId('offering-layout-banner-hint')).not.toBeInTheDocument();
await userEvent.selectOptions(select, 'banner');
expect(await screen.findByTestId('offering-layout-banner-hint')).toBeInTheDocument();
});
it('saves a banner and turns the previous banner back into a card', async () => {
mockAuthenticated();
const first = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
const second = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
renderApp(`/offerings/${first}/edit`);
await userEvent.selectOptions(await screen.findByTestId('offering-layout', {}, { timeout: 10000 }), 'banner');
await userEvent.click(screen.getByTestId('offering-form-submit'));
await waitFor(() => expect(getMockOfferings().find((o) => o.id === first)?.layout).toBe('banner'));
await screen.findByTestId('offerings-title', {}, { timeout: 10000 });
renderApp(`/offerings/${second}/edit`);
await userEvent.selectOptions(await screen.findByTestId('offering-layout', {}, { timeout: 10000 }), 'banner');
await userEvent.click(screen.getByTestId('offering-form-submit'));
await waitFor(() => expect(getMockOfferings().find((o) => o.id === second)?.layout).toBe('banner'));
expect(getMockOfferings().find((o) => o.id === first)?.layout).toBe('card');
});
});
@@ -25,6 +25,8 @@ export const offeringFormSchema = z.object({
.or(z.literal('')),
/** Id of the chosen category; null/absent = no category. */
categoryId: z.string().nullable().optional(),
/** 'banner' = the wide strip under the cards; at most one per site. */
layout: z.enum(['card', 'banner']).optional(),
});
export type OfferingFormData = z.infer<typeof offeringFormSchema>;
@@ -1,3 +1,5 @@
export type OfferingLayout = 'card' | 'banner';
export interface OfferingDto {
id: string;
slug: string;
@@ -13,6 +15,8 @@ export interface OfferingDto {
categoryId?: string | null;
/** Name of the category (renames show up here automatically). */
category?: string | null;
/** Presentation on the website; absent (older API) means 'card'. */
layout?: OfferingLayout;
}
export interface CreateOfferingRequest {
@@ -27,6 +31,8 @@ export interface CreateOfferingRequest {
slug?: string;
/** Category id; null clears the category. */
categoryId?: string | null;
/** Omit to keep the current value (older clients do). */
layout?: OfferingLayout;
}
export type UpdateOfferingRequest = CreateOfferingRequest;
@@ -386,6 +386,10 @@
"addFeatureButton": "Add feature",
"removeFeatureButton": "Remove",
"ctaLabelLabel": "Button text",
"layoutLabel": "Display",
"layoutCard": "Card",
"layoutBanner": "Banner (wide strip below the cards)",
"layoutBannerHint": "Only one banner is allowed: an existing banner turns back into a regular card.",
"featuredLabel": "Featured",
"categoryLabel": "Category",
"noCategory": "No category",
@@ -386,6 +386,10 @@
"addFeatureButton": "Kenmerk toevoegen",
"removeFeatureButton": "Verwijderen",
"ctaLabelLabel": "Knoptekst",
"layoutLabel": "Weergave",
"layoutCard": "Kaart",
"layoutBanner": "Banner (brede strook onder de kaarten)",
"layoutBannerHint": "Er kan maar één banner zijn: een bestaande banner wordt weer een gewone kaart.",
"featuredLabel": "Uitgelicht",
"categoryLabel": "Categorie",
"noCategory": "Geen categorie",
@@ -1,4 +1,4 @@
using FluentAssertions;
using FluentAssertions;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using NSubstitute;
@@ -267,4 +267,95 @@ public class OfferingsServiceTests
offering.DeletedAt.Should().NotBeNull();
}
// --- 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);
}
}
@@ -11,6 +11,9 @@ 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,7 @@
namespace SlpModularCms.Modules.Offerings.Data.Entities;
public static class OfferingLayouts
{
public const string Card = "card";
public const string Banner = "banner";
}
@@ -24,6 +24,7 @@ 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();
@@ -0,0 +1,142 @@
// <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("20261111100000_AddOfferingLayout")]
partial class AddOfferingLayout
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid?>("CategoryId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<string>("CtaLabel")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<DateTimeOffset?>("DeletedAt")
.HasColumnType("datetime");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<bool>("Featured")
.HasColumnType("tinyint(1)");
b.Property<string>("Features")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsDeleted")
.HasColumnType("tinyint(1)");
b.Property<string>("Layout")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.HasColumnType("varchar(10)")
.HasDefaultValue("card");
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,30 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Offerings.Migrations
{
/// <inheritdoc />
public partial class AddOfferingLayout : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Layout",
table: "OfferingsOfferings",
type: "varchar(10)",
maxLength: 10,
nullable: false,
defaultValue: "card");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Layout",
table: "OfferingsOfferings");
}
}
}
@@ -57,6 +57,13 @@ 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,5 +11,6 @@ public record CreateOfferingRequest(
[Required, MaxLength(50)] string CtaLabel,
bool Featured = false,
[MaxLength(130)] string? Slug = null,
Guid? CategoryId = null
Guid? CategoryId = null,
[RegularExpression("^(card|banner)$", ErrorMessage = "Layout must be 'card' or 'banner'.")] string? Layout = null
);
@@ -19,5 +19,6 @@ public record OfferingDto(
bool Featured,
int DisplayOrder,
string? CategoryId = null,
string? Category = null
string? Category = null,
string Layout = "card"
);
@@ -11,5 +11,6 @@ public record UpdateOfferingRequest(
[Required, MaxLength(50)] string CtaLabel,
bool Featured = false,
[MaxLength(130)] string? Slug = null,
Guid? CategoryId = null
Guid? CategoryId = null,
[RegularExpression("^(card|banner)$", ErrorMessage = "Layout must be 'card' or 'banner'.")] string? Layout = null
);
@@ -12,6 +12,7 @@ public interface IOfferingRepository
void Update(Offering offering);
Task<int> GetMaxDisplayOrderAsync();
Task<Offering?> GetFeaturedAsync();
Task<Offering?> GetBannerAsync();
Task SaveChangesAsync();
Task<IDbContextTransaction> BeginTransactionAsync();
}
@@ -28,6 +28,9 @@ 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();
@@ -33,6 +33,7 @@ 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,
@@ -43,10 +44,11 @@ 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)
if (request.Featured || offering.Layout == OfferingLayouts.Banner)
{
await using var transaction = await repository.BeginTransactionAsync();
await UnfeatureCurrentAsync();
if (request.Featured) await UnfeatureCurrentAsync();
if (offering.Layout == OfferingLayouts.Banner) await DemoteCurrentBannerAsync();
await repository.AddAsync(offering);
await repository.SaveChangesAsync();
await transaction.CommitAsync();
@@ -90,13 +92,16 @@ 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)
if (request.Featured || offering.Layout == OfferingLayouts.Banner)
{
await using var transaction = await repository.BeginTransactionAsync();
await UnfeatureCurrentAsync(exceptId: offering.Id);
if (request.Featured) await UnfeatureCurrentAsync(exceptId: offering.Id);
if (offering.Layout == OfferingLayouts.Banner) await DemoteCurrentBannerAsync(exceptId: offering.Id);
repository.Update(offering);
await repository.SaveChangesAsync();
await transaction.CommitAsync();
@@ -182,6 +187,18 @@ 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)
@@ -237,6 +254,7 @@ public class OfferingsService(
o.Featured,
o.DisplayOrder,
o.CategoryId?.ToString(),
o.Category?.Name
o.Category?.Name,
o.Layout
);
}