Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions .claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Issue #1489 – Testimonials module: domain model and persistence

Issue: https://github.com/DevBetterCom/DevBetterWeb/issues/1489
Parent: https://github.com/DevBetterCom/DevBetterWeb/issues/1472 (split into #1489–#1492, approved by maintainer 2026-11-15)
Branch: `issue-1489-testimonials-module-domain`

## Assumptions / scope

- This is the first real module from `2026-07-29-modular-monolith-recommendations.md` §4.4: a
`Contracts` project plus an implementation project. No `DevBetterWeb.SharedKernel` project exists yet,
so the module does **not** reference `DevBetterWeb.Core`. It is self-contained and keeps its own small
base types, so it does not pull in Core's Vimeo/Identity/AppInsights dependencies.
- The author is referenced by `MemberId` (int) only. There is no `Member` navigation and no FK across modules.
- Status rules (from the approved split):
- `Draft` → `PendingReview` (submit)
- `ChangesRequested` → `PendingReview` (resubmit)
- `PendingReview` → `Accepted` | `Declined` | `ChangesRequested` (request-changes needs feedback)
- `Accepted` → `Declined` (admin unpublish)
- `Declined` is terminal
- Editing is allowed only in `Draft` / `ChangesRequested`. Authors can delete only a `Draft`.
- Display info: display name (required), title, organization, optional photo URL override (null means
the UI later falls back to the member avatar). Photo URL must be an absolute **https** URL. That rules
out `javascript:`/`data:` schemes and mixed content.
- Admin feedback is cleared on resubmit, so a fresh review starts clean.
- Role checks (who is admin) live in the UI/application layer (#1490/#1491), not in the entity. The
entity enforces state transitions only.
- Out of scope: use-case handlers for authoring/review (#1490/#1491), UI, home page (#1492). A minimal
public read contract (`ITestimonialQueries.ListAcceptedAsync`) is included so the module has a real
public surface and #1492 has something to consume.
- The module has its own `TestimonialsDbContext`, a `testimonials` schema, and its own
`__EFMigrationsHistory` table in that schema. It shares the physical database (DefaultConnection).

## Phase 1 – Projects and wiring

- [x] Create `src/DevBetterWeb.Modules.Testimonials.Contracts` (no package deps): `TestimonialStatus`, `TestimonialDto`, `ITestimonialQueries`.
- [x] Create `src/DevBetterWeb.Modules.Testimonials` (refs Contracts, EF Core SqlServer, GuardClauses). Types are internal by default, with `InternalsVisibleTo` for the test project.
- [x] Public entry points: `AddTestimonialsModule(IServiceCollection, string? connectionString)` and `ApplyTestimonialsMigrationsAsync(IServiceProvider)`.
- [x] Add both projects to `DevBetterWeb.slnx`, reference them from Web, call `AddTestimonialsModule` in `Program.cs` (SQL Server outside Testing), and apply its migrations with the identity/app contexts.
- [x] Register an in-memory `TestimonialsDbContext` in the FunctionalTests `CustomWebApplicationFactory`, which is the Testing-environment host. The `DevBetterWeb.Tests` factory runs as Development, so `Program.cs` already registers SQL Server for the module there and nothing resolves it. It was left unchanged.

## Phase 2 – Domain

- [x] `Testimonial` aggregate with `Create`, `Edit`, `Submit`, `Accept`, `Decline`, `RequestChanges`, `Unpublish`, `CanBeDeletedByAuthor`, and timestamps (created/updated/submitted/reviewed).
- [x] `AuthorProfile` value object (owned type) with guard clauses and max lengths.
- [x] `InvalidTestimonialStateException` for illegal transitions.

## Phase 3 – Persistence

- [x] `TestimonialsDbContext` (schema `testimonials`) with an entity configuration (owned `AuthorProfile`, enum as string, max lengths, index on `(Status)` and `(MemberId)`).
- [x] Design-time factory and initial migration `AddTestimonials`.
- [x] `TestimonialQueries` implementing `ITestimonialQueries` (accepted only, newest review first, no tracking).

## Phase 4 – Automated tests (`tests/DevBetterWeb.Modules.Testimonials.Tests`, xUnit + Shouldly)

- [x] Unit: every valid transition and every invalid transition (theory over all statuses) for each operation.
- [x] Unit: edit allowed only in Draft/ChangesRequested; request-changes requires feedback; resubmit clears feedback; delete allowed only in Draft.
- [x] Unit: `AuthorProfile` validation (required name, max lengths, photo URL scheme).
- [x] Persistence: the model uses the `testimonials` schema, and the migrations match the model (`HasPendingModelChanges` is false).
- [x] Persistence: in-memory round trip of an owned `AuthorProfile`. `ListAcceptedAsync` returns only accepted items, in order.
- [x] DI: `AddTestimonialsModule` resolves `ITestimonialQueries`.
- [x] Functional: the Testing host resolves `ITestimonialQueries` against its in-memory DB (`tests/DevBetterWeb.FunctionalTests/Modules/TestimonialsModuleRegistration.cs`), and the existing functional tests still pass.

## Phase 5 – Independent review

- [x] A separate agent reviews the full diff against #1489 (correctness, missed requirements, test gaps, security, performance, accessibility).
- [x] Address significant findings, or record the reasons here.
- **Result:** no blockers or significant findings. The reviewer applied the migration to a throwaway LocalDB, rolled it back, and checked the idempotent script.
- **Applied:**
- `EnsureCanBeDeletedByAuthor()` guard, with tests across all statuses.
- `RowVersion` concurrency token, so concurrent admin reviews fail instead of last-write-wins. The migration was regenerated.
- Photo URL is now https only.
- The generated migration class is now `internal`.
- Added tests: functional-host DI resolution, Declined-via-unpublish is terminal, over-long feedback for Decline/Unpublish, null author, and failed transitions leaving feedback and timestamps unchanged.
- Documented that `ApplyTestimonialsMigrationsAsync` needs a scoped provider.
- **Left alone, with reasons:**
- No default cap on `ListAcceptedAsync(null)`. #1492 picks the limit for its pages.
- The `Decline(now, feedback?)` parameter order stays, because the optional parameter must come last.
- The unpublish reason shares `ReviewerFeedback`. #1490 decides whether members see it.
- Migration `Down` keeps the schema, which is EF's default.
- No logging in the migration helper. The host logs startup.
- **Deploy note (for the PR):** production migrations are manual. Run `dotnet ef migrations script --idempotent --context TestimonialsDbContext` (see `efscripts.txt`). The DB login needs CREATE SCHEMA permission.

## Phase 6 – Verification

- [x] Run `dotnet build && dotnet test && dotnet format --verify-no-changes`. Known: repo-wide format failures already exist on `main`, so check that the new or touched files add none.
3 changes: 3 additions & 0 deletions DevBetterWeb.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@
<Project Path="src/DevBetterWeb.AppHost/DevBetterWeb.AppHost.csproj" />
<Project Path="src/DevBetterWeb.Core/DevBetterWeb.Core.csproj" />
<Project Path="src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj" />
<Project Path="src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj" />
<Project Path="src/DevBetterWeb.Modules.Testimonials.Contracts/DevBetterWeb.Modules.Testimonials.Contracts.csproj" />
<Project Path="src/DevBetterWeb.ServiceDefaults/DevBetterWeb.ServiceDefaults.csproj" />
<Project Path="src/DevBetterWeb.Web/DevBetterWeb.Web.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/DevBetterWeb.AppHost.Tests/DevBetterWeb.AppHost.Tests.csproj" />
<Project Path="tests/DevBetterWeb.FunctionalTests/DevBetterWeb.FunctionalTests.csproj" />
<Project Path="tests/DevBetterWeb.Modules.Testimonials.Tests/DevBetterWeb.Modules.Testimonials.Tests.csproj" />
<Project Path="tests/DevBetterWeb.Tests/DevBetterWeb.Tests.csproj" />
<Project Path="tests/DevBetterWeb.UnitTests/DevBetterWeb.UnitTests.csproj" />
</Folder>
Expand Down
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
<PackageVersion Include="Microsoft.AspNetCore.Identity.UI" Version="11.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="11.0.0" />
<PackageVersion Include="Microsoft.CodeCoverage" Version="18.12.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="11.0.0" />
Expand Down
6 changes: 6 additions & 0 deletions efscripts.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,9 @@ dotnet ef migrations script --context appdbcontext -p ../DevBetterWeb.Infrastru

76040fbe-b7e4-452a-b2aa-e48520c771cf - admin role
be21ba0d-47b0-45c0-aa15-02fa22e5d7f6 - [email protected] user

-- TESTIMONIALS MODULE (own DbContext + "testimonials" schema). RUN FROM src/DevBetterWeb.Modules.Testimonials
dotnet ef migrations add <Name> --context TestimonialsDbContext -o Infrastructure/Data/Migrations
dotnet ef database update --context TestimonialsDbContext
-- GENERATE SCRIPT FOR PROD DB UPDATES
dotnet ef migrations script --idempotent --context TestimonialsDbContext > testimonials-update.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>DevBetterWeb.Modules.Testimonials.Contracts</RootNamespace>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsAsErrors />
</PropertyGroup>

<!-- Contracts stay dependency-free: public interfaces, DTOs, and integration events only. -->

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace DevBetterWeb.Modules.Testimonials.Contracts;

/// <summary>
/// Public read surface of the Testimonials module.
/// </summary>
public interface ITestimonialQueries
{
/// <summary>
/// Returns accepted testimonials, most recently accepted first.
/// </summary>
/// <param name="maxCount">Optional limit; null returns all accepted testimonials.</param>
Task<IReadOnlyList<TestimonialDto>> ListAcceptedAsync(int? maxCount = null, CancellationToken cancellationToken = default);
}
16 changes: 16 additions & 0 deletions src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace DevBetterWeb.Modules.Testimonials.Contracts;

/// <summary>
/// Read model of a testimonial for display outside the module.
/// </summary>
/// <param name="PhotoUrl">Optional override; when null, callers fall back to the member's avatar.</param>
public sealed record TestimonialDto(
int Id,
int MemberId,
string Content,
string DisplayName,
string? Title,
string? Organization,
string? PhotoUrl,
TestimonialStatus Status,
DateTimeOffset? ReviewedAt);
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace DevBetterWeb.Modules.Testimonials.Contracts;

/// <summary>
/// Lifecycle of a member testimonial.
/// Draft -> PendingReview -> Accepted | Declined | ChangesRequested.
/// ChangesRequested -> PendingReview. Accepted -> Declined (unpublish). Declined is terminal.
/// </summary>
public enum TestimonialStatus
{
Draft = 0,
PendingReview = 1,
ChangesRequested = 2,
Accepted = 3,
Declined = 4,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using DevBetterWeb.Modules.Testimonials.Contracts;
using DevBetterWeb.Modules.Testimonials.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace DevBetterWeb.Modules.Testimonials.Application;

internal sealed class TestimonialQueries : ITestimonialQueries
{
private readonly TestimonialsDbContext _dbContext;

public TestimonialQueries(TestimonialsDbContext dbContext)
{
_dbContext = dbContext;
}

public async Task<IReadOnlyList<TestimonialDto>> ListAcceptedAsync(int? maxCount = null, CancellationToken cancellationToken = default)
{
if (maxCount is <= 0)
{
return [];
}

IQueryable<TestimonialDto> query = _dbContext.Testimonials
.AsNoTracking()
.Where(t => t.Status == TestimonialStatus.Accepted)
.OrderByDescending(t => t.ReviewedAt)
.ThenByDescending(t => t.Id)
.Select(t => new TestimonialDto(
t.Id,
t.MemberId,
t.Content,
t.Author.DisplayName,
t.Author.Title,
t.Author.Organization,
t.Author.PhotoUrl,
t.Status,
t.ReviewedAt));

if (maxCount is int limit)
{
query = query.Take(limit);
}

return await query.ToListAsync(cancellationToken);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>DevBetterWeb.Modules.Testimonials</RootNamespace>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsAsErrors />
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="DevBetterWeb.Modules.Testimonials.Tests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\DevBetterWeb.Modules.Testimonials.Contracts\DevBetterWeb.Modules.Testimonials.Contracts.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Ardalis.GuardClauses" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" PrivateAssets="all" />
</ItemGroup>

</Project>
72 changes: 72 additions & 0 deletions src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using Ardalis.GuardClauses;

namespace DevBetterWeb.Modules.Testimonials.Domain;

/// <summary>
/// How the member wants to be known alongside their testimonial.
/// </summary>
internal sealed class AuthorProfile
{
public const int MaxDisplayNameLength = 100;
public const int MaxTitleLength = 100;
public const int MaxOrganizationLength = 100;
public const int MaxPhotoUrlLength = 500;

// EF Core
private AuthorProfile()
{
DisplayName = string.Empty;
}

private AuthorProfile(string displayName, string? title, string? organization, string? photoUrl)
{
DisplayName = displayName;
Title = title;
Organization = organization;
PhotoUrl = photoUrl;
}

public string DisplayName { get; private set; }
public string? Title { get; private set; }
public string? Organization { get; private set; }

/// <summary>
/// Optional absolute https URL overriding the member's avatar. Null means use the avatar.
/// </summary>
public string? PhotoUrl { get; private set; }

public static AuthorProfile Create(string displayName, string? title = null, string? organization = null, string? photoUrl = null)
{
Guard.Against.NullOrWhiteSpace(displayName);
string name = displayName.Trim();
Guard.Against.StringTooLong(name, MaxDisplayNameLength);

string? normalizedTitle = Normalize(title, MaxTitleLength, nameof(title));
string? normalizedOrganization = Normalize(organization, MaxOrganizationLength, nameof(organization));
string? normalizedPhotoUrl = Normalize(photoUrl, MaxPhotoUrlLength, nameof(photoUrl));

if (normalizedPhotoUrl is not null && !IsHttpsUrl(normalizedPhotoUrl))
{
throw new ArgumentException("Photo URL must be an absolute https URL.", nameof(photoUrl));
}

return new AuthorProfile(name, normalizedTitle, normalizedOrganization, normalizedPhotoUrl);
}

private static string? Normalize(string? value, int maxLength, string parameterName)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}

string trimmed = value.Trim();
Guard.Against.StringTooLong(trimmed, maxLength, parameterName);
return trimmed;
}

// https only: avoids mixed content on the site and rules out javascript:/data: schemes.
private static bool IsHttpsUrl(string value) =>
Uri.TryCreate(value, UriKind.Absolute, out Uri? uri)
&& uri.Scheme == Uri.UriSchemeHttps;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using DevBetterWeb.Modules.Testimonials.Contracts;

namespace DevBetterWeb.Modules.Testimonials.Domain;

/// <summary>
/// Thrown when an operation is not allowed for a testimonial's current status.
/// </summary>
internal sealed class InvalidTestimonialStateException : InvalidOperationException
{
public InvalidTestimonialStateException(string operation, TestimonialStatus currentStatus)
: base($"Cannot {operation} a testimonial whose status is {currentStatus}.")
{
Operation = operation;
CurrentStatus = currentStatus;
}

public string Operation { get; }
public TestimonialStatus CurrentStatus { get; }
}
Loading
Loading