From 29ce3b571586b996fd08075948785f42ac37114b Mon Sep 17 00:00:00 2001 From: Steve Ardalis Smith Date: Sun, 15 Nov 2026 16:19:14 -0500 Subject: [PATCH 1/2] feat(testimonials): add Testimonials module domain model and persistence Adds DevBetterWeb.Modules.Testimonials (+ .Contracts) as the first modular-monolith module: Testimonial aggregate with review state machine, AuthorProfile value object, module-owned DbContext in the testimonials schema with initial migration, ITestimonialQueries.ListAcceptedAsync, and host wiring. Includes a module test project. Refs #1489 Co-Authored-By: Claude Opus 5.5 --- ...5-issue-1489-testimonials-module-domain.md | 70 +++++ DevBetterWeb.slnx | 3 + Directory.Packages.props | 1 + efscripts.txt | 6 + ...rWeb.Modules.Testimonials.Contracts.csproj | 18 ++ .../ITestimonialQueries.cs | 13 + .../TestimonialDto.cs | 16 + .../TestimonialStatus.cs | 15 + .../Application/TestimonialQueries.cs | 46 +++ .../DevBetterWeb.Modules.Testimonials.csproj | 30 ++ .../Domain/AuthorProfile.cs | 71 +++++ .../InvalidTestimonialStateException.cs | 19 ++ .../Domain/Testimonial.cs | 158 ++++++++++ .../Data/Config/TestimonialConfig.cs | 35 +++ ...20261115211322_AddTestimonials.Designer.cs | 116 ++++++++ .../20261115211322_AddTestimonials.cs | 62 ++++ .../TestimonialsDbContextModelSnapshot.cs | 118 ++++++++ .../Data/TestimonialsDbContext.cs | 27 ++ .../Data/TestimonialsDbContextFactory.cs | 19 ++ .../TestimonialsModule.cs | 58 ++++ src/DevBetterWeb.Web/DevBetterWeb.Web.csproj | 1 + src/DevBetterWeb.Web/Program.cs | 13 + .../CustomWebApplicationFactory.cs | 11 + ...etterWeb.Modules.Testimonials.Tests.csproj | 29 ++ .../Domain/AuthorProfileTests.cs | 89 ++++++ .../Domain/TestimonialTransitionTests.cs | 280 ++++++++++++++++++ .../TestimonialsPersistenceTests.cs | 156 ++++++++++ .../TestimonialBuilder.cs | 50 ++++ 28 files changed, 1530 insertions(+) create mode 100644 .claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md create mode 100644 src/DevBetterWeb.Modules.Testimonials.Contracts/DevBetterWeb.Modules.Testimonials.Contracts.csproj create mode 100644 src/DevBetterWeb.Modules.Testimonials.Contracts/ITestimonialQueries.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialDto.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialStatus.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Application/TestimonialQueries.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj create mode 100644 src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Domain/InvalidTestimonialStateException.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Config/TestimonialConfig.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.Designer.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/TestimonialsDbContextModelSnapshot.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/TestimonialsDbContext.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/TestimonialsDbContextFactory.cs create mode 100644 src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs create mode 100644 tests/DevBetterWeb.Modules.Testimonials.Tests/DevBetterWeb.Modules.Testimonials.Tests.csproj create mode 100644 tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/AuthorProfileTests.cs create mode 100644 tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/TestimonialTransitionTests.cs create mode 100644 tests/DevBetterWeb.Modules.Testimonials.Tests/Infrastructure/TestimonialsPersistenceTests.cs create mode 100644 tests/DevBetterWeb.Modules.Testimonials.Tests/TestimonialBuilder.cs diff --git a/.claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md b/.claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md new file mode 100644 index 000000000..df56d8bf2 --- /dev/null +++ b/.claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md @@ -0,0 +1,70 @@ +# 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 absolute http/https, so dangerous + schemes like `javascript:` are rejected before they ever reach a page. +- 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 + +- [ ] Create `src/DevBetterWeb.Modules.Testimonials.Contracts` (no package deps): `TestimonialStatus`, `TestimonialDto`, `ITestimonialQueries`. +- [ ] Create `src/DevBetterWeb.Modules.Testimonials` (refs Contracts, EF Core SqlServer, GuardClauses). Types are internal by default, with `InternalsVisibleTo` for the test project. +- [ ] Public entry points: `AddTestimonialsModule(IServiceCollection, string? connectionString)` and `ApplyTestimonialsMigrationsAsync(IServiceProvider)`. +- [ ] 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. +- [ ] Register an in-memory `TestimonialsDbContext` in both `CustomWebApplicationFactory`s so the Testing host resolves. + +## Phase 2 – Domain + +- [ ] `Testimonial` aggregate with `Create`, `Edit`, `Submit`, `Accept`, `Decline`, `RequestChanges`, `Unpublish`, `CanBeDeletedByAuthor`, and timestamps (created/updated/submitted/reviewed). +- [ ] `AuthorProfile` value object (owned type) with guard clauses and max lengths. +- [ ] `InvalidTestimonialStateException` for illegal transitions. + +## Phase 3 – Persistence + +- [ ] `TestimonialsDbContext` (schema `testimonials`) with an entity configuration (owned `AuthorProfile`, enum as string, max lengths, index on `(Status)` and `(MemberId)`). +- [ ] Design-time factory and initial migration `AddTestimonials`. +- [ ] `TestimonialQueries` implementing `ITestimonialQueries` (accepted only, newest review first, no tracking). + +## Phase 4 – Automated tests (`tests/DevBetterWeb.Modules.Testimonials.Tests`, xUnit + Shouldly) + +- [ ] Unit: every valid transition and every invalid transition (theory over all statuses) for each operation. +- [ ] Unit: edit allowed only in Draft/ChangesRequested; request-changes requires feedback; resubmit clears feedback; delete allowed only in Draft. +- [ ] Unit: `AuthorProfile` validation (required name, max lengths, photo URL scheme). +- [ ] Persistence: the model uses the `testimonials` schema, and the migrations match the model (`HasPendingModelChanges` is false). +- [ ] Persistence: in-memory round trip of an owned `AuthorProfile`. `ListAcceptedAsync` returns only accepted items, in order. +- [ ] DI: `AddTestimonialsModule` resolves `ITestimonialQueries`. +- [ ] Existing functional tests still start the host. + +## Phase 5 – Independent review + +- [ ] A separate agent reviews the full diff against #1489 (correctness, missed requirements, test gaps, security, performance, accessibility). +- [ ] Address significant findings, or record the reasons here. + +## Phase 6 – Verification + +- [ ] 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. diff --git a/DevBetterWeb.slnx b/DevBetterWeb.slnx index a79f14624..95d41cea3 100644 --- a/DevBetterWeb.slnx +++ b/DevBetterWeb.slnx @@ -21,12 +21,15 @@ + + + diff --git a/Directory.Packages.props b/Directory.Packages.props index 23d2e0828..beffe9a8c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -37,6 +37,7 @@ + diff --git a/efscripts.txt b/efscripts.txt index a281d8396..e2c1e498e 100644 --- a/efscripts.txt +++ b/efscripts.txt @@ -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 - admin@test.com user + +-- TESTIMONIALS MODULE (own DbContext + "testimonials" schema). RUN FROM src/DevBetterWeb.Modules.Testimonials +dotnet ef migrations add --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 diff --git a/src/DevBetterWeb.Modules.Testimonials.Contracts/DevBetterWeb.Modules.Testimonials.Contracts.csproj b/src/DevBetterWeb.Modules.Testimonials.Contracts/DevBetterWeb.Modules.Testimonials.Contracts.csproj new file mode 100644 index 000000000..11440918b --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/DevBetterWeb.Modules.Testimonials.Contracts.csproj @@ -0,0 +1,18 @@ + + + + net11.0 + latest + enable + enable + DevBetterWeb.Modules.Testimonials.Contracts + + + + true + + + + + + diff --git a/src/DevBetterWeb.Modules.Testimonials.Contracts/ITestimonialQueries.cs b/src/DevBetterWeb.Modules.Testimonials.Contracts/ITestimonialQueries.cs new file mode 100644 index 000000000..13b71a3fb --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/ITestimonialQueries.cs @@ -0,0 +1,13 @@ +namespace DevBetterWeb.Modules.Testimonials.Contracts; + +/// +/// Public read surface of the Testimonials module. +/// +public interface ITestimonialQueries +{ + /// + /// Returns accepted testimonials, most recently accepted first. + /// + /// Optional limit; null returns all accepted testimonials. + Task> ListAcceptedAsync(int? maxCount = null, CancellationToken cancellationToken = default); +} diff --git a/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialDto.cs b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialDto.cs new file mode 100644 index 000000000..fd617f688 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialDto.cs @@ -0,0 +1,16 @@ +namespace DevBetterWeb.Modules.Testimonials.Contracts; + +/// +/// Read model of a testimonial for display outside the module. +/// +/// Optional override; when null, callers fall back to the member's avatar. +public sealed record TestimonialDto( + int Id, + int MemberId, + string Content, + string DisplayName, + string? Title, + string? Organization, + string? PhotoUrl, + TestimonialStatus Status, + DateTimeOffset? ReviewedAt); diff --git a/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialStatus.cs b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialStatus.cs new file mode 100644 index 000000000..63750215d --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialStatus.cs @@ -0,0 +1,15 @@ +namespace DevBetterWeb.Modules.Testimonials.Contracts; + +/// +/// Lifecycle of a member testimonial. +/// Draft -> PendingReview -> Accepted | Declined | ChangesRequested. +/// ChangesRequested -> PendingReview. Accepted -> Declined (unpublish). Declined is terminal. +/// +public enum TestimonialStatus +{ + Draft = 0, + PendingReview = 1, + ChangesRequested = 2, + Accepted = 3, + Declined = 4, +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialQueries.cs b/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialQueries.cs new file mode 100644 index 000000000..4b251b745 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialQueries.cs @@ -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> ListAcceptedAsync(int? maxCount = null, CancellationToken cancellationToken = default) + { + if (maxCount is <= 0) + { + return []; + } + + IQueryable 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); + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj b/src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj new file mode 100644 index 000000000..3de052bb1 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj @@ -0,0 +1,30 @@ + + + + net11.0 + latest + enable + enable + DevBetterWeb.Modules.Testimonials + + + + true + + + + + + + + + + + + + + + + + + diff --git a/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs b/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs new file mode 100644 index 000000000..5f6357126 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs @@ -0,0 +1,71 @@ +using Ardalis.GuardClauses; + +namespace DevBetterWeb.Modules.Testimonials.Domain; + +/// +/// How the member wants to be known alongside their testimonial. +/// +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; } + + /// + /// Optional absolute http(s) URL overriding the member's avatar. Null means use the avatar. + /// + 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 && !IsHttpUrl(normalizedPhotoUrl)) + { + throw new ArgumentException("Photo URL must be an absolute http or 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; + } + + private static bool IsHttpUrl(string value) => + Uri.TryCreate(value, UriKind.Absolute, out Uri? uri) + && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp); +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Domain/InvalidTestimonialStateException.cs b/src/DevBetterWeb.Modules.Testimonials/Domain/InvalidTestimonialStateException.cs new file mode 100644 index 000000000..eeec0611e --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Domain/InvalidTestimonialStateException.cs @@ -0,0 +1,19 @@ +using DevBetterWeb.Modules.Testimonials.Contracts; + +namespace DevBetterWeb.Modules.Testimonials.Domain; + +/// +/// Thrown when an operation is not allowed for a testimonial's current status. +/// +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; } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs b/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs new file mode 100644 index 000000000..eb7ac4a81 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs @@ -0,0 +1,158 @@ +using Ardalis.GuardClauses; +using DevBetterWeb.Modules.Testimonials.Contracts; + +namespace DevBetterWeb.Modules.Testimonials.Domain; + +/// +/// A member-written testimonial that must be reviewed by an admin before it is published. +/// The author is referenced by MemberId only; the Membership module owns members. +/// Authorization (who is the author / an admin) is enforced by the calling use case. +/// +internal sealed class Testimonial +{ + public const int MaxContentLength = 4000; + public const int MaxFeedbackLength = 2000; + + // EF Core + private Testimonial() + { + Content = string.Empty; + Author = null!; + } + + private Testimonial(int memberId, string content, AuthorProfile author, DateTimeOffset now) + { + MemberId = memberId; + Content = content; + Author = author; + Status = TestimonialStatus.Draft; + CreatedAt = now; + UpdatedAt = now; + } + + public int Id { get; private set; } + public int MemberId { get; private set; } + public string Content { get; private set; } + public AuthorProfile Author { get; private set; } + public TestimonialStatus Status { get; private set; } + + /// + /// Feedback from the reviewing admin (required when changes are requested, optional when declined). + /// Cleared when the author resubmits. + /// + public string? ReviewerFeedback { get; private set; } + + public DateTimeOffset CreatedAt { get; private set; } + public DateTimeOffset UpdatedAt { get; private set; } + public DateTimeOffset? SubmittedAt { get; private set; } + public DateTimeOffset? ReviewedAt { get; private set; } + + public bool CanBeEditedByAuthor => Status is TestimonialStatus.Draft or TestimonialStatus.ChangesRequested; + public bool CanBeSubmitted => CanBeEditedByAuthor; + public bool CanBeDeletedByAuthor => Status == TestimonialStatus.Draft; + + public static Testimonial CreateDraft(int memberId, string content, AuthorProfile author, DateTimeOffset now) + { + Guard.Against.NegativeOrZero(memberId); + Guard.Against.Null(author); + return new Testimonial(memberId, NormalizeContent(content), author, now); + } + + public void Edit(string content, AuthorProfile author, DateTimeOffset now) + { + EnsureStatus("edit", TestimonialStatus.Draft, TestimonialStatus.ChangesRequested); + Guard.Against.Null(author); + string normalizedContent = NormalizeContent(content); + + Content = normalizedContent; + Author = author; + UpdatedAt = now; + } + + public void Submit(DateTimeOffset now) + { + EnsureStatus("submit", TestimonialStatus.Draft, TestimonialStatus.ChangesRequested); + + Status = TestimonialStatus.PendingReview; + ReviewerFeedback = null; + SubmittedAt = now; + UpdatedAt = now; + } + + public void Accept(DateTimeOffset now) + { + EnsureStatus("accept", TestimonialStatus.PendingReview); + + Status = TestimonialStatus.Accepted; + ReviewerFeedback = null; + MarkReviewed(now); + } + + public void Decline(DateTimeOffset now, string? feedback = null) + { + EnsureStatus("decline", TestimonialStatus.PendingReview); + string? normalizedFeedback = NormalizeOptionalFeedback(feedback); + + Status = TestimonialStatus.Declined; + ReviewerFeedback = normalizedFeedback; + MarkReviewed(now); + } + + public void RequestChanges(string feedback, DateTimeOffset now) + { + EnsureStatus("request changes to", TestimonialStatus.PendingReview); + Guard.Against.NullOrWhiteSpace(feedback); + string? normalizedFeedback = NormalizeOptionalFeedback(feedback); + + Status = TestimonialStatus.ChangesRequested; + ReviewerFeedback = normalizedFeedback; + MarkReviewed(now); + } + + /// + /// Removes a previously accepted testimonial from public display. + /// + public void Unpublish(DateTimeOffset now, string? reason = null) + { + EnsureStatus("unpublish", TestimonialStatus.Accepted); + string? normalizedReason = NormalizeOptionalFeedback(reason); + + Status = TestimonialStatus.Declined; + ReviewerFeedback = normalizedReason; + MarkReviewed(now); + } + + private void MarkReviewed(DateTimeOffset now) + { + ReviewedAt = now; + UpdatedAt = now; + } + + private void EnsureStatus(string operation, params TestimonialStatus[] allowed) + { + if (!allowed.Contains(Status)) + { + throw new InvalidTestimonialStateException(operation, Status); + } + } + + private static string NormalizeContent(string content) + { + Guard.Against.NullOrWhiteSpace(content); + string trimmed = content.Trim(); + Guard.Against.StringTooLong(trimmed, MaxContentLength, nameof(content)); + return trimmed; + } + + private static string? NormalizeOptionalFeedback(string? feedback) + { + if (string.IsNullOrWhiteSpace(feedback)) + { + return null; + } + + string trimmed = feedback.Trim(); + Guard.Against.StringTooLong(trimmed, MaxFeedbackLength, nameof(feedback)); + return trimmed; + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Config/TestimonialConfig.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Config/TestimonialConfig.cs new file mode 100644 index 000000000..210fb8e82 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Config/TestimonialConfig.cs @@ -0,0 +1,35 @@ +using DevBetterWeb.Modules.Testimonials.Domain; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace DevBetterWeb.Modules.Testimonials.Infrastructure.Data.Config; + +internal sealed class TestimonialConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Testimonials"); + builder.HasKey(t => t.Id); + + builder.Property(t => t.MemberId).IsRequired(); + builder.Property(t => t.Content).IsRequired().HasMaxLength(Testimonial.MaxContentLength); + builder.Property(t => t.Status).IsRequired().HasConversion().HasMaxLength(32); + builder.Property(t => t.ReviewerFeedback).HasMaxLength(Testimonial.MaxFeedbackLength); + + builder.OwnsOne(t => t.Author, author => + { + author.Property(a => a.DisplayName).HasColumnName("AuthorDisplayName").IsRequired().HasMaxLength(AuthorProfile.MaxDisplayNameLength); + author.Property(a => a.Title).HasColumnName("AuthorTitle").HasMaxLength(AuthorProfile.MaxTitleLength); + author.Property(a => a.Organization).HasColumnName("AuthorOrganization").HasMaxLength(AuthorProfile.MaxOrganizationLength); + author.Property(a => a.PhotoUrl).HasColumnName("AuthorPhotoUrl").HasMaxLength(AuthorProfile.MaxPhotoUrlLength); + }); + builder.Navigation(t => t.Author).IsRequired(); + + builder.Ignore(t => t.CanBeEditedByAuthor); + builder.Ignore(t => t.CanBeSubmitted); + builder.Ignore(t => t.CanBeDeletedByAuthor); + + builder.HasIndex(t => t.MemberId); + builder.HasIndex(t => new { t.Status, t.ReviewedAt }); + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.Designer.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.Designer.cs new file mode 100644 index 000000000..e6efd2818 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.Designer.cs @@ -0,0 +1,116 @@ +// +using System; +using DevBetterWeb.Modules.Testimonials.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace DevBetterWeb.Modules.Testimonials.Infrastructure.Data.Migrations; + +[DbContext(typeof(TestimonialsDbContext))] +[Migration("20261115211322_AddTestimonials")] +partial class AddTestimonials +{ + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("testimonials") + .HasAnnotation("ProductVersion", "11.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("DevBetterWeb.Modules.Testimonials.Domain.Testimonial", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(id); + + b.Property("Content") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("CreatedAt") + .HasColumnType("datetimeoffset"); + + b.Property("MemberId") + .HasColumnType("int"); + + b.Property("ReviewedAt") + .HasColumnType("datetimeoffset"); + + b.Property("ReviewerFeedback") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("SubmittedAt") + .HasColumnType("datetimeoffset"); + + b.Property("UpdatedAt") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("MemberId"); + + b.HasIndex("Status", "ReviewedAt"); + + b.ToTable("Testimonials", "testimonials"); + }); + + modelBuilder.Entity("DevBetterWeb.Modules.Testimonials.Domain.Testimonial", b => + { + b.OwnsOne("DevBetterWeb.Modules.Testimonials.Domain.AuthorProfile", "Author", b1 => + { + b1.Property("TestimonialId") + .HasColumnType("int"); + + b1.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)") + .HasColumnName("AuthorDisplayName"); + + b1.Property("Organization") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)") + .HasColumnName("AuthorOrganization"); + + b1.Property("PhotoUrl") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)") + .HasColumnName("AuthorPhotoUrl"); + + b1.Property("Title") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)") + .HasColumnName("AuthorTitle"); + + b1.HasKey("TestimonialId"); + + b1.ToTable("Testimonials", "testimonials"); + + b1.WithOwner() + .HasForeignKey("TestimonialId"); + }); + + b.Navigation("Author") + .IsRequired(); + }); +#pragma warning restore 612, 618 + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.cs new file mode 100644 index 000000000..9e97bc8f7 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.cs @@ -0,0 +1,62 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DevBetterWeb.Modules.Testimonials.Infrastructure.Data.Migrations; + +/// +public partial class AddTestimonials : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.EnsureSchema( + name: "testimonials"); + + migrationBuilder.CreateTable( + name: "Testimonials", + schema: "testimonials", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + MemberId = table.Column(type: "int", nullable: false), + Content = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: false), + AuthorDisplayName = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), + AuthorTitle = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: true), + AuthorOrganization = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: true), + AuthorPhotoUrl = table.Column(type: "nvarchar(500)", maxLength: 500, nullable: true), + Status = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + ReviewerFeedback = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), + CreatedAt = table.Column(type: "datetimeoffset", nullable: false), + UpdatedAt = table.Column(type: "datetimeoffset", nullable: false), + SubmittedAt = table.Column(type: "datetimeoffset", nullable: true), + ReviewedAt = table.Column(type: "datetimeoffset", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Testimonials", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_Testimonials_MemberId", + schema: "testimonials", + table: "Testimonials", + column: "MemberId"); + + migrationBuilder.CreateIndex( + name: "IX_Testimonials_Status_ReviewedAt", + schema: "testimonials", + table: "Testimonials", + columns: new[] { "Status", "ReviewedAt" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Testimonials", + schema: "testimonials"); + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/TestimonialsDbContextModelSnapshot.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/TestimonialsDbContextModelSnapshot.cs new file mode 100644 index 000000000..cd6a636e2 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/TestimonialsDbContextModelSnapshot.cs @@ -0,0 +1,118 @@ +// +using System; +using DevBetterWeb.Modules.Testimonials.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace DevBetterWeb.Modules.Testimonials.Infrastructure.Data.Migrations; + +[DbContext(typeof(TestimonialsDbContext))] +partial class TestimonialsDbContextModelSnapshot : ModelSnapshot +{ + // If you encounter a merge conflict in the line below, it means you need to + // discard one of the migration branches and recreate its migrations on top of + // the other branch. See https://aka.ms/efcore-docs-migrations-conflicts for more info. + public override string LastMigrationId => "20261115211322_AddTestimonials"; + + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("testimonials") + .HasAnnotation("ProductVersion", "11.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("DevBetterWeb.Modules.Testimonials.Domain.Testimonial", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(id); + + b.Property("Content") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("CreatedAt") + .HasColumnType("datetimeoffset"); + + b.Property("MemberId") + .HasColumnType("int"); + + b.Property("ReviewedAt") + .HasColumnType("datetimeoffset"); + + b.Property("ReviewerFeedback") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("SubmittedAt") + .HasColumnType("datetimeoffset"); + + b.Property("UpdatedAt") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("MemberId"); + + b.HasIndex("Status", "ReviewedAt"); + + b.ToTable("Testimonials", "testimonials"); + }); + + modelBuilder.Entity("DevBetterWeb.Modules.Testimonials.Domain.Testimonial", b => + { + b.OwnsOne("DevBetterWeb.Modules.Testimonials.Domain.AuthorProfile", "Author", b1 => + { + b1.Property("TestimonialId") + .HasColumnType("int"); + + b1.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)") + .HasColumnName("AuthorDisplayName"); + + b1.Property("Organization") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)") + .HasColumnName("AuthorOrganization"); + + b1.Property("PhotoUrl") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)") + .HasColumnName("AuthorPhotoUrl"); + + b1.Property("Title") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)") + .HasColumnName("AuthorTitle"); + + b1.HasKey("TestimonialId"); + + b1.ToTable("Testimonials", "testimonials"); + + b1.WithOwner() + .HasForeignKey("TestimonialId"); + }); + + b.Navigation("Author") + .IsRequired(); + }); +#pragma warning restore 612, 618 + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/TestimonialsDbContext.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/TestimonialsDbContext.cs new file mode 100644 index 000000000..2658f4a13 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/TestimonialsDbContext.cs @@ -0,0 +1,27 @@ +using DevBetterWeb.Modules.Testimonials.Domain; +using Microsoft.EntityFrameworkCore; + +namespace DevBetterWeb.Modules.Testimonials.Infrastructure.Data; + +/// +/// Module-owned DbContext. Shares the physical database but owns the testimonials schema +/// and keeps its own migrations history table there. +/// +internal sealed class TestimonialsDbContext : DbContext +{ + public const string Schema = "testimonials"; + + public TestimonialsDbContext(DbContextOptions options) + : base(options) + { + } + + public DbSet Testimonials => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.HasDefaultSchema(Schema); + modelBuilder.ApplyConfigurationsFromAssembly(typeof(TestimonialsDbContext).Assembly); + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/TestimonialsDbContextFactory.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/TestimonialsDbContextFactory.cs new file mode 100644 index 000000000..3ab883150 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/TestimonialsDbContextFactory.cs @@ -0,0 +1,19 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace DevBetterWeb.Modules.Testimonials.Infrastructure.Data; + +/// +/// Lets dotnet ef create migrations for this module without the web host. +/// +internal sealed class TestimonialsDbContextFactory : IDesignTimeDbContextFactory +{ + public TestimonialsDbContext CreateDbContext(string[] args) + { + const string localConnectionString = @"Server=(localdb)\mssqllocaldb;TrustServerCertificate=true;Database=DevBetterWeb.App;Trusted_Connection=True;MultipleActiveResultSets=true"; + + var optionsBuilder = new DbContextOptionsBuilder(); + optionsBuilder.UseTestimonialsSqlServer(localConnectionString); + return new TestimonialsDbContext(optionsBuilder.Options); + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs b/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs new file mode 100644 index 000000000..9fd914a68 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs @@ -0,0 +1,58 @@ +using DevBetterWeb.Modules.Testimonials.Application; +using DevBetterWeb.Modules.Testimonials.Contracts; +using DevBetterWeb.Modules.Testimonials.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace DevBetterWeb.Modules.Testimonials; + +/// +/// Public entry points of the Testimonials module. Everything else in the module is internal. +/// +public static class TestimonialsModule +{ + /// + /// Registers the module's services. + /// + /// + /// Configures the module's DbContext provider, typically via . + /// Pass null to skip DbContext registration (e.g. when a test host registers its own provider). + /// + public static IServiceCollection AddTestimonialsModule( + this IServiceCollection services, + Action? configureDbContext) + { + if (configureDbContext is not null) + { + services.AddDbContext(configureDbContext); + } + + services.TryAddScoped(); + return services; + } + + /// + /// Configures SQL Server for the module, keeping its migrations and history table in the module's schema. + /// + public static DbContextOptionsBuilder UseTestimonialsSqlServer(this DbContextOptionsBuilder optionsBuilder, string? connectionString) + { + ArgumentException.ThrowIfNullOrWhiteSpace(connectionString); + + return optionsBuilder.UseSqlServer(connectionString, sql => sql + .MigrationsAssembly(typeof(TestimonialsDbContext).Assembly.GetName().Name) + .MigrationsHistoryTable("__EFMigrationsHistory", TestimonialsDbContext.Schema)); + } + + /// + /// Applies any pending migrations for the module's DbContext. + /// + public static async Task ApplyTestimonialsMigrationsAsync(this IServiceProvider services, CancellationToken cancellationToken = default) + { + var dbContext = services.GetRequiredService(); + if ((await dbContext.Database.GetPendingMigrationsAsync(cancellationToken)).Any()) + { + await dbContext.Database.MigrateAsync(cancellationToken); + } + } +} diff --git a/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj b/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj index ac851a3db..952f2d948 100644 --- a/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj +++ b/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj @@ -63,6 +63,7 @@ + diff --git a/src/DevBetterWeb.Web/Program.cs b/src/DevBetterWeb.Web/Program.cs index 95ac89303..b4b897787 100644 --- a/src/DevBetterWeb.Web/Program.cs +++ b/src/DevBetterWeb.Web/Program.cs @@ -11,6 +11,7 @@ using DevBetterWeb.Infrastructure.DiscordWebooks; using DevBetterWeb.Infrastructure.Identity.Data; using DevBetterWeb.Infrastructure.Services; +using DevBetterWeb.Modules.Testimonials; using DevBetterWeb.Web; using DevBetterWeb.Web.Areas.Identity; using DevBetterWeb.Web.Interfaces; @@ -100,6 +101,13 @@ } +// Testing hosts register their own (in-memory) provider for the module's DbContext. +builder.Services.AddTestimonialsModule(isTesting + ? null + : (provider, options) => options + .UseTestimonialsSqlServer(builder.Configuration.GetConnectionString(Constants.DEFAULT_CONNECTION_STRING_NAME)) + .AddMetronomeDbTracking(provider)); + builder.Services.AddInfrastructureServices(isDevelopment); builder.Services.AddMediator(options => @@ -301,6 +309,11 @@ async Task ApplyLocalMigrationsAsync(WebApplication webApplication) await identity.ApplyLocalMigrationAsync(environment, shouldApplyMigrations); await app.ApplyLocalMigrationAsync(environment, shouldApplyMigrations); + + if (environment == "Development" && shouldApplyMigrations) + { + await scope.ServiceProvider.ApplyTestimonialsMigrationsAsync(); + } } // Make the implicit Program.cs class public, so integration tests can reference the correct assembly for host building diff --git a/tests/DevBetterWeb.FunctionalTests/CustomWebApplicationFactory.cs b/tests/DevBetterWeb.FunctionalTests/CustomWebApplicationFactory.cs index affa95645..7a875c904 100644 --- a/tests/DevBetterWeb.FunctionalTests/CustomWebApplicationFactory.cs +++ b/tests/DevBetterWeb.FunctionalTests/CustomWebApplicationFactory.cs @@ -3,6 +3,7 @@ using DevBetterWeb.Core.Interfaces; using DevBetterWeb.Infrastructure.Data; using DevBetterWeb.Infrastructure.Identity.Data; +using DevBetterWeb.Modules.Testimonials; using DevBetterWeb.Web; using DevBetterWeb.Web.Areas.Identity; using DevBetterWeb.Web.Models; @@ -100,6 +101,16 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) .BuildServiceProvider()); }); + string inMemoryTestimonialsDb = Guid.NewGuid().ToString(); + var testimonialsEfServiceProvider = new ServiceCollection() + .AddEntityFrameworkInMemoryDatabase() + .BuildServiceProvider(); + services.AddTestimonialsModule((_, options) => + { + options.UseInMemoryDatabase(inMemoryTestimonialsDb); + options.UseInternalServiceProvider(testimonialsEfServiceProvider); + }); + services.AddIdentityCore(options => { options.User.RequireUniqueEmail = false; diff --git a/tests/DevBetterWeb.Modules.Testimonials.Tests/DevBetterWeb.Modules.Testimonials.Tests.csproj b/tests/DevBetterWeb.Modules.Testimonials.Tests/DevBetterWeb.Modules.Testimonials.Tests.csproj new file mode 100644 index 000000000..1c0138e7e --- /dev/null +++ b/tests/DevBetterWeb.Modules.Testimonials.Tests/DevBetterWeb.Modules.Testimonials.Tests.csproj @@ -0,0 +1,29 @@ + + + + net11.0 + enable + enable + false + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/AuthorProfileTests.cs b/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/AuthorProfileTests.cs new file mode 100644 index 000000000..45fb4ce65 --- /dev/null +++ b/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/AuthorProfileTests.cs @@ -0,0 +1,89 @@ +using DevBetterWeb.Modules.Testimonials.Domain; +using Shouldly; +using Xunit; + +namespace DevBetterWeb.Modules.Testimonials.Tests.Domain; + +public class AuthorProfileTests +{ + [Fact] + public void CreateTrimsValuesAndNormalizesBlanksToNull() + { + var author = AuthorProfile.Create(" Ada ", " ", "", null); + + author.DisplayName.ShouldBe("Ada"); + author.Title.ShouldBeNull(); + author.Organization.ShouldBeNull(); + author.PhotoUrl.ShouldBeNull(); + } + + [Fact] + public void CreateKeepsAllProvidedValues() + { + var author = AuthorProfile.Create("Ada", "Engineer", "Analytical Engines", "https://example.com/a.png"); + + author.DisplayName.ShouldBe("Ada"); + author.Title.ShouldBe("Engineer"); + author.Organization.ShouldBe("Analytical Engines"); + author.PhotoUrl.ShouldBe("https://example.com/a.png"); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void CreateRequiresDisplayName(string displayName) + { + Should.Throw(() => AuthorProfile.Create(displayName)); + } + + [Fact] + public void CreateRejectsNullDisplayName() + { + Should.Throw(() => AuthorProfile.Create(null!)); + } + + [Fact] + public void CreateRejectsDisplayNameOverMaxLength() + { + Should.Throw(() => AuthorProfile.Create(new string('a', AuthorProfile.MaxDisplayNameLength + 1))); + } + + [Fact] + public void CreateRejectsTitleOverMaxLength() + { + Should.Throw(() => AuthorProfile.Create("Ada", title: new string('a', AuthorProfile.MaxTitleLength + 1))); + } + + [Fact] + public void CreateRejectsOrganizationOverMaxLength() + { + Should.Throw(() => AuthorProfile.Create("Ada", organization: new string('a', AuthorProfile.MaxOrganizationLength + 1))); + } + + [Fact] + public void CreateRejectsPhotoUrlOverMaxLength() + { + string url = "https://example.com/" + new string('a', AuthorProfile.MaxPhotoUrlLength); + + Should.Throw(() => AuthorProfile.Create("Ada", photoUrl: url)); + } + + [Theory] + [InlineData("http://example.com/a.png")] + [InlineData("https://example.com/a.png")] + public void CreateAcceptsHttpPhotoUrls(string url) + { + AuthorProfile.Create("Ada", photoUrl: url).PhotoUrl.ShouldBe(url); + } + + [Theory] + [InlineData("javascript:alert(1)")] + [InlineData("data:image/png;base64,AAAA")] + [InlineData("ftp://example.com/a.png")] + [InlineData("/images/a.png")] + [InlineData("not a url")] + public void CreateRejectsNonHttpPhotoUrls(string url) + { + Should.Throw(() => AuthorProfile.Create("Ada", photoUrl: url)); + } +} diff --git a/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/TestimonialTransitionTests.cs b/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/TestimonialTransitionTests.cs new file mode 100644 index 000000000..04d3945de --- /dev/null +++ b/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/TestimonialTransitionTests.cs @@ -0,0 +1,280 @@ +using DevBetterWeb.Modules.Testimonials.Contracts; +using DevBetterWeb.Modules.Testimonials.Domain; +using Shouldly; +using Xunit; + +namespace DevBetterWeb.Modules.Testimonials.Tests.Domain; + +public class TestimonialTransitionTests +{ + private static readonly DateTimeOffset Now = TestimonialBuilder.Created.AddDays(5); + + public static TheoryData AllStatuses() => new(Enum.GetValues()); + + public static TheoryData NotEditable() => + new(Except(TestimonialStatus.Draft, TestimonialStatus.ChangesRequested)); + + public static TheoryData NotPendingReview() => + new(Except(TestimonialStatus.PendingReview)); + + public static TheoryData NotAccepted() => + new(Except(TestimonialStatus.Accepted)); + + private static IEnumerable Except(params TestimonialStatus[] allowed) => + Enum.GetValues().Except(allowed); + + [Fact] + public void CreateDraftStartsInDraftWithTimestamps() + { + var testimonial = TestimonialBuilder.Draft(); + + testimonial.Status.ShouldBe(TestimonialStatus.Draft); + testimonial.MemberId.ShouldBe(TestimonialBuilder.MemberId); + testimonial.Content.ShouldBe(TestimonialBuilder.DefaultContent); + testimonial.CreatedAt.ShouldBe(TestimonialBuilder.Created); + testimonial.UpdatedAt.ShouldBe(TestimonialBuilder.Created); + testimonial.SubmittedAt.ShouldBeNull(); + testimonial.ReviewedAt.ShouldBeNull(); + testimonial.ReviewerFeedback.ShouldBeNull(); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void CreateDraftRejectsInvalidMemberId(int memberId) + { + Should.Throw(() => TestimonialBuilder.Draft(memberId)); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void CreateDraftRejectsBlankContent(string content) + { + Should.Throw(() => + Testimonial.CreateDraft(1, content, TestimonialBuilder.Author(), Now)); + } + + [Fact] + public void CreateDraftRejectsContentOverMaxLength() + { + string content = new('x', Testimonial.MaxContentLength + 1); + + Should.Throw(() => + Testimonial.CreateDraft(1, content, TestimonialBuilder.Author(), Now)); + } + + [Fact] + public void CreateDraftTrimsContent() + { + var testimonial = Testimonial.CreateDraft(1, " Great group! ", TestimonialBuilder.Author(), Now); + + testimonial.Content.ShouldBe("Great group!"); + } + + [Theory] + [InlineData(TestimonialStatus.Draft)] + [InlineData(TestimonialStatus.ChangesRequested)] + public void EditUpdatesContentAndAuthorWhenEditable(TestimonialStatus status) + { + var testimonial = TestimonialBuilder.InStatus(status); + var newAuthor = AuthorProfile.Create("Grace Hopper", organization: "US Navy"); + + testimonial.Edit("Updated text", newAuthor, Now); + + testimonial.Content.ShouldBe("Updated text"); + testimonial.Author.ShouldBeSameAs(newAuthor); + testimonial.UpdatedAt.ShouldBe(Now); + testimonial.Status.ShouldBe(status); + } + + [Theory] + [MemberData(nameof(NotEditable))] + public void EditThrowsWhenNotEditable(TestimonialStatus status) + { + var testimonial = TestimonialBuilder.InStatus(status); + + var ex = Should.Throw(() => + testimonial.Edit("Updated text", TestimonialBuilder.Author(), Now)); + + ex.CurrentStatus.ShouldBe(status); + testimonial.Content.ShouldBe(TestimonialBuilder.DefaultContent); + } + + [Fact] + public void EditWithInvalidContentLeavesTestimonialUnchanged() + { + var testimonial = TestimonialBuilder.Draft(); + var originalAuthor = testimonial.Author; + + Should.Throw(() => testimonial.Edit(" ", AuthorProfile.Create("Someone Else"), Now)); + + testimonial.Content.ShouldBe(TestimonialBuilder.DefaultContent); + testimonial.Author.ShouldBeSameAs(originalAuthor); + testimonial.UpdatedAt.ShouldBe(TestimonialBuilder.Created); + } + + [Fact] + public void SubmitMovesDraftToPendingReview() + { + var testimonial = TestimonialBuilder.Draft(); + + testimonial.Submit(Now); + + testimonial.Status.ShouldBe(TestimonialStatus.PendingReview); + testimonial.SubmittedAt.ShouldBe(Now); + testimonial.UpdatedAt.ShouldBe(Now); + } + + [Fact] + public void ResubmitAfterChangesRequestedClearsFeedback() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.ChangesRequested); + testimonial.ReviewerFeedback.ShouldBe("Please shorten it."); + + testimonial.Submit(Now); + + testimonial.Status.ShouldBe(TestimonialStatus.PendingReview); + testimonial.ReviewerFeedback.ShouldBeNull(); + testimonial.SubmittedAt.ShouldBe(Now); + } + + [Theory] + [MemberData(nameof(NotEditable))] + public void SubmitThrowsWhenNotDraftOrChangesRequested(TestimonialStatus status) + { + var testimonial = TestimonialBuilder.InStatus(status); + + Should.Throw(() => testimonial.Submit(Now)); + testimonial.Status.ShouldBe(status); + } + + [Fact] + public void AcceptMovesPendingToAccepted() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview); + + testimonial.Accept(Now); + + testimonial.Status.ShouldBe(TestimonialStatus.Accepted); + testimonial.ReviewedAt.ShouldBe(Now); + testimonial.UpdatedAt.ShouldBe(Now); + testimonial.ReviewerFeedback.ShouldBeNull(); + } + + [Fact] + public void DeclineMovesPendingToDeclinedWithOptionalFeedback() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview); + + testimonial.Decline(Now, " Not a fit. "); + + testimonial.Status.ShouldBe(TestimonialStatus.Declined); + testimonial.ReviewerFeedback.ShouldBe("Not a fit."); + testimonial.ReviewedAt.ShouldBe(Now); + } + + [Fact] + public void DeclineWithoutFeedbackLeavesFeedbackNull() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview); + + testimonial.Decline(Now); + + testimonial.Status.ShouldBe(TestimonialStatus.Declined); + testimonial.ReviewerFeedback.ShouldBeNull(); + } + + [Fact] + public void RequestChangesMovesPendingToChangesRequestedWithFeedback() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview); + + testimonial.RequestChanges("Add your job title.", Now); + + testimonial.Status.ShouldBe(TestimonialStatus.ChangesRequested); + testimonial.ReviewerFeedback.ShouldBe("Add your job title."); + testimonial.ReviewedAt.ShouldBe(Now); + testimonial.CanBeEditedByAuthor.ShouldBeTrue(); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void RequestChangesRequiresFeedback(string feedback) + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview); + + Should.Throw(() => testimonial.RequestChanges(feedback, Now)); + testimonial.Status.ShouldBe(TestimonialStatus.PendingReview); + } + + [Fact] + public void FeedbackOverMaxLengthIsRejected() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview); + string feedback = new('x', Testimonial.MaxFeedbackLength + 1); + + Should.Throw(() => testimonial.RequestChanges(feedback, Now)); + testimonial.Status.ShouldBe(TestimonialStatus.PendingReview); + } + + [Theory] + [MemberData(nameof(NotPendingReview))] + public void ReviewActionsThrowWhenNotPendingReview(TestimonialStatus status) + { + var testimonial = TestimonialBuilder.InStatus(status); + + Should.Throw(() => testimonial.Accept(Now)); + Should.Throw(() => testimonial.Decline(Now)); + Should.Throw(() => testimonial.RequestChanges("feedback", Now)); + testimonial.Status.ShouldBe(status); + } + + [Fact] + public void UnpublishMovesAcceptedToDeclined() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.Accepted); + + testimonial.Unpublish(Now, "Member left the program."); + + testimonial.Status.ShouldBe(TestimonialStatus.Declined); + testimonial.ReviewerFeedback.ShouldBe("Member left the program."); + testimonial.ReviewedAt.ShouldBe(Now); + } + + [Theory] + [MemberData(nameof(NotAccepted))] + public void UnpublishThrowsWhenNotAccepted(TestimonialStatus status) + { + var testimonial = TestimonialBuilder.InStatus(status); + + Should.Throw(() => testimonial.Unpublish(Now)); + testimonial.Status.ShouldBe(status); + } + + [Theory] + [MemberData(nameof(AllStatuses))] + public void AuthorCapabilitiesMatchStatus(TestimonialStatus status) + { + var testimonial = TestimonialBuilder.InStatus(status); + + bool editable = status is TestimonialStatus.Draft or TestimonialStatus.ChangesRequested; + testimonial.CanBeEditedByAuthor.ShouldBe(editable); + testimonial.CanBeSubmitted.ShouldBe(editable); + testimonial.CanBeDeletedByAuthor.ShouldBe(status == TestimonialStatus.Draft); + } + + [Fact] + public void DeclinedIsTerminal() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.Declined); + + Should.Throw(() => testimonial.Edit("x", TestimonialBuilder.Author(), Now)); + Should.Throw(() => testimonial.Submit(Now)); + Should.Throw(() => testimonial.Accept(Now)); + Should.Throw(() => testimonial.Decline(Now)); + Should.Throw(() => testimonial.RequestChanges("x", Now)); + Should.Throw(() => testimonial.Unpublish(Now)); + } +} diff --git a/tests/DevBetterWeb.Modules.Testimonials.Tests/Infrastructure/TestimonialsPersistenceTests.cs b/tests/DevBetterWeb.Modules.Testimonials.Tests/Infrastructure/TestimonialsPersistenceTests.cs new file mode 100644 index 000000000..8eea0c57c --- /dev/null +++ b/tests/DevBetterWeb.Modules.Testimonials.Tests/Infrastructure/TestimonialsPersistenceTests.cs @@ -0,0 +1,156 @@ +using DevBetterWeb.Modules.Testimonials.Application; +using DevBetterWeb.Modules.Testimonials.Contracts; +using DevBetterWeb.Modules.Testimonials.Domain; +using DevBetterWeb.Modules.Testimonials.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; + +namespace DevBetterWeb.Modules.Testimonials.Tests.Infrastructure; + +public class TestimonialsPersistenceTests +{ + private static TestimonialsDbContext CreateInMemoryContext(string databaseName) + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName) + .Options; + return new TestimonialsDbContext(options); + } + + private static TestimonialsDbContext CreateSqlServerModelContext() + { + // No connection is opened; SQL Server is only used to build the relational model. + var builder = new DbContextOptionsBuilder(); + builder.UseTestimonialsSqlServer("Server=unused;Database=unused;TrustServerCertificate=true"); + return new TestimonialsDbContext(builder.Options); + } + + [Fact] + public void ModelUsesTestimonialsSchema() + { + using var context = CreateSqlServerModelContext(); + + var entityType = context.Model.FindEntityType(typeof(Testimonial))!; + + entityType.GetSchema().ShouldBe(TestimonialsDbContext.Schema); + entityType.GetTableName().ShouldBe("Testimonials"); + } + + [Fact] + public void MigrationsMatchTheModel() + { + using var context = CreateSqlServerModelContext(); + + context.Database.GetMigrations().ShouldNotBeEmpty(); + context.Database.HasPendingModelChanges().ShouldBeFalse( + "Model changed without a migration. Run: dotnet ef migrations add --context TestimonialsDbContext -o Infrastructure/Data/Migrations (from src/DevBetterWeb.Modules.Testimonials)"); + } + + [Fact] + public async Task RoundTripsTestimonialWithAuthorProfile() + { + string db = Guid.NewGuid().ToString(); + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.ChangesRequested); + + await using (var context = CreateInMemoryContext(db)) + { + context.Testimonials.Add(testimonial); + await context.SaveChangesAsync(); + } + + await using (var context = CreateInMemoryContext(db)) + { + var loaded = await context.Testimonials.SingleAsync(t => t.Id == testimonial.Id); + + loaded.MemberId.ShouldBe(TestimonialBuilder.MemberId); + loaded.Content.ShouldBe(TestimonialBuilder.DefaultContent); + loaded.Status.ShouldBe(TestimonialStatus.ChangesRequested); + loaded.ReviewerFeedback.ShouldBe("Please shorten it."); + loaded.Author.DisplayName.ShouldBe("Ada Lovelace"); + loaded.Author.Title.ShouldBe("Engineer"); + loaded.Author.Organization.ShouldBe("Analytical Engines Ltd"); + loaded.Author.PhotoUrl.ShouldBe("https://example.com/ada.png"); + } + } + + [Fact] + public async Task ListAcceptedReturnsOnlyAcceptedNewestFirst() + { + string db = Guid.NewGuid().ToString(); + var day = TestimonialBuilder.Created; + var olderAccepted = TestimonialBuilder.InStatus(TestimonialStatus.Accepted, day.AddDays(1), memberId: 1); + var newerAccepted = TestimonialBuilder.InStatus(TestimonialStatus.Accepted, day.AddDays(3), memberId: 2); + + await using (var context = CreateInMemoryContext(db)) + { + context.Testimonials.AddRange( + olderAccepted, + TestimonialBuilder.InStatus(TestimonialStatus.Draft), + TestimonialBuilder.InStatus(TestimonialStatus.PendingReview), + TestimonialBuilder.InStatus(TestimonialStatus.ChangesRequested), + TestimonialBuilder.InStatus(TestimonialStatus.Declined), + newerAccepted); + await context.SaveChangesAsync(); + } + + await using (var context = CreateInMemoryContext(db)) + { + var results = await new TestimonialQueries(context).ListAcceptedAsync(); + + results.Select(r => r.Id).ShouldBe([newerAccepted.Id, olderAccepted.Id]); + results.ShouldAllBe(r => r.Status == TestimonialStatus.Accepted); + + var first = results[0]; + first.MemberId.ShouldBe(2); + first.DisplayName.ShouldBe("Ada Lovelace"); + first.Title.ShouldBe("Engineer"); + first.Organization.ShouldBe("Analytical Engines Ltd"); + first.PhotoUrl.ShouldBe("https://example.com/ada.png"); + first.ReviewedAt.ShouldBe(day.AddDays(3)); + } + } + + [Fact] + public async Task ListAcceptedHonorsMaxCount() + { + string db = Guid.NewGuid().ToString(); + await using (var context = CreateInMemoryContext(db)) + { + for (int i = 1; i <= 3; i++) + { + context.Testimonials.Add(TestimonialBuilder.InStatus(TestimonialStatus.Accepted, TestimonialBuilder.Created.AddDays(i), memberId: i)); + } + await context.SaveChangesAsync(); + } + + await using (var context = CreateInMemoryContext(db)) + { + var queries = new TestimonialQueries(context); + + (await queries.ListAcceptedAsync(2)).Select(r => r.MemberId).ShouldBe([3, 2]); + (await queries.ListAcceptedAsync(0)).ShouldBeEmpty(); + } + } + + [Fact] + public void AddTestimonialsModuleResolvesQueries() + { + string db = Guid.NewGuid().ToString(); + var services = new ServiceCollection(); + services.AddTestimonialsModule((_, options) => options.UseInMemoryDatabase(db)); + + using var provider = services.BuildServiceProvider(); + using var scope = provider.CreateScope(); + + scope.ServiceProvider.GetRequiredService().ShouldBeOfType(); + } + + [Fact] + public void UseTestimonialsSqlServerRequiresConnectionString() + { + Should.Throw(() => + new DbContextOptionsBuilder().UseTestimonialsSqlServer("")); + } +} diff --git a/tests/DevBetterWeb.Modules.Testimonials.Tests/TestimonialBuilder.cs b/tests/DevBetterWeb.Modules.Testimonials.Tests/TestimonialBuilder.cs new file mode 100644 index 000000000..b459c14b0 --- /dev/null +++ b/tests/DevBetterWeb.Modules.Testimonials.Tests/TestimonialBuilder.cs @@ -0,0 +1,50 @@ +using DevBetterWeb.Modules.Testimonials.Contracts; +using DevBetterWeb.Modules.Testimonials.Domain; + +namespace DevBetterWeb.Modules.Testimonials.Tests; + +internal static class TestimonialBuilder +{ + public const int MemberId = 42; + public const string DefaultContent = "devBetter changed my career."; + public static readonly DateTimeOffset Created = new(2026, 11, 1, 12, 0, 0, TimeSpan.Zero); + + public static AuthorProfile Author(string name = "Ada Lovelace") => + AuthorProfile.Create(name, "Engineer", "Analytical Engines Ltd", "https://example.com/ada.png"); + + public static Testimonial Draft(int memberId = MemberId) => + Testimonial.CreateDraft(memberId, DefaultContent, Author(), Created); + + /// + /// Builds a testimonial in the given status by walking the legal transitions. + /// + public static Testimonial InStatus(TestimonialStatus status, DateTimeOffset? at = null, int memberId = MemberId) + { + var when = at ?? Created.AddDays(1); + var testimonial = Draft(memberId); + switch (status) + { + case TestimonialStatus.Draft: + break; + case TestimonialStatus.PendingReview: + testimonial.Submit(when); + break; + case TestimonialStatus.ChangesRequested: + testimonial.Submit(when); + testimonial.RequestChanges("Please shorten it.", when); + break; + case TestimonialStatus.Accepted: + testimonial.Submit(when); + testimonial.Accept(when); + break; + case TestimonialStatus.Declined: + testimonial.Submit(when); + testimonial.Decline(when); + break; + default: + throw new ArgumentOutOfRangeException(nameof(status), status, null); + } + + return testimonial; + } +} From 192c506ffa3e1dc79da23388d925f59875e33858 Mon Sep 17 00:00:00 2001 From: Steve Ardalis Smith Date: Sun, 15 Nov 2026 16:25:51 -0500 Subject: [PATCH 2/2] fix(testimonials): address review findings - Guard author deletion to drafts (EnsureCanBeDeletedByAuthor) - Add RowVersion concurrency token; regenerate migration - Require https photo URLs - Make generated migration internal - Add tests for review gaps and functional-host DI resolution Refs #1489 Co-Authored-By: Claude Opus 5.5 --- ...5-issue-1489-testimonials-module-domain.md | 61 +++++++++------ .../Domain/AuthorProfile.cs | 11 +-- .../Domain/Testimonial.cs | 13 ++++ .../Data/Config/TestimonialConfig.cs | 1 + ...0261115212332_AddTestimonials.Designer.cs} | 8 +- ...s.cs => 20261115212332_AddTestimonials.cs} | 5 +- .../TestimonialsDbContextModelSnapshot.cs | 8 +- .../TestimonialsModule.cs | 1 + .../Modules/TestimonialsModuleRegistration.cs | 27 +++++++ .../Domain/AuthorProfileTests.cs | 9 +-- .../Domain/TestimonialTransitionTests.cs | 77 ++++++++++++++++++- 11 files changed, 181 insertions(+), 40 deletions(-) rename src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/{20261115211322_AddTestimonials.Designer.cs => 20261115212332_AddTestimonials.Designer.cs} (93%) rename src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/{20261115211322_AddTestimonials.cs => 20261115212332_AddTestimonials.cs} (93%) create mode 100644 tests/DevBetterWeb.FunctionalTests/Modules/TestimonialsModuleRegistration.cs diff --git a/.claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md b/.claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md index df56d8bf2..74c6ce8ff 100644 --- a/.claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md +++ b/.claude/plans/2026-11-15-issue-1489-testimonials-module-domain.md @@ -19,8 +19,8 @@ Branch: `issue-1489-testimonials-module-domain` - `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 absolute http/https, so dangerous - schemes like `javascript:` are rejected before they ever reach a page. + 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. @@ -32,39 +32,54 @@ Branch: `issue-1489-testimonials-module-domain` ## Phase 1 – Projects and wiring -- [ ] Create `src/DevBetterWeb.Modules.Testimonials.Contracts` (no package deps): `TestimonialStatus`, `TestimonialDto`, `ITestimonialQueries`. -- [ ] Create `src/DevBetterWeb.Modules.Testimonials` (refs Contracts, EF Core SqlServer, GuardClauses). Types are internal by default, with `InternalsVisibleTo` for the test project. -- [ ] Public entry points: `AddTestimonialsModule(IServiceCollection, string? connectionString)` and `ApplyTestimonialsMigrationsAsync(IServiceProvider)`. -- [ ] 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. -- [ ] Register an in-memory `TestimonialsDbContext` in both `CustomWebApplicationFactory`s so the Testing host resolves. +- [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 -- [ ] `Testimonial` aggregate with `Create`, `Edit`, `Submit`, `Accept`, `Decline`, `RequestChanges`, `Unpublish`, `CanBeDeletedByAuthor`, and timestamps (created/updated/submitted/reviewed). -- [ ] `AuthorProfile` value object (owned type) with guard clauses and max lengths. -- [ ] `InvalidTestimonialStateException` for illegal transitions. +- [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 -- [ ] `TestimonialsDbContext` (schema `testimonials`) with an entity configuration (owned `AuthorProfile`, enum as string, max lengths, index on `(Status)` and `(MemberId)`). -- [ ] Design-time factory and initial migration `AddTestimonials`. -- [ ] `TestimonialQueries` implementing `ITestimonialQueries` (accepted only, newest review first, no tracking). +- [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) -- [ ] Unit: every valid transition and every invalid transition (theory over all statuses) for each operation. -- [ ] Unit: edit allowed only in Draft/ChangesRequested; request-changes requires feedback; resubmit clears feedback; delete allowed only in Draft. -- [ ] Unit: `AuthorProfile` validation (required name, max lengths, photo URL scheme). -- [ ] Persistence: the model uses the `testimonials` schema, and the migrations match the model (`HasPendingModelChanges` is false). -- [ ] Persistence: in-memory round trip of an owned `AuthorProfile`. `ListAcceptedAsync` returns only accepted items, in order. -- [ ] DI: `AddTestimonialsModule` resolves `ITestimonialQueries`. -- [ ] Existing functional tests still start the host. +- [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 -- [ ] A separate agent reviews the full diff against #1489 (correctness, missed requirements, test gaps, security, performance, accessibility). -- [ ] Address significant findings, or record the reasons here. +- [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 -- [ ] 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. +- [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. diff --git a/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs b/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs index 5f6357126..a023782db 100644 --- a/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs +++ b/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs @@ -31,7 +31,7 @@ private AuthorProfile(string displayName, string? title, string? organization, s public string? Organization { get; private set; } /// - /// Optional absolute http(s) URL overriding the member's avatar. Null means use the avatar. + /// Optional absolute https URL overriding the member's avatar. Null means use the avatar. /// public string? PhotoUrl { get; private set; } @@ -45,9 +45,9 @@ public static AuthorProfile Create(string displayName, string? title = null, str string? normalizedOrganization = Normalize(organization, MaxOrganizationLength, nameof(organization)); string? normalizedPhotoUrl = Normalize(photoUrl, MaxPhotoUrlLength, nameof(photoUrl)); - if (normalizedPhotoUrl is not null && !IsHttpUrl(normalizedPhotoUrl)) + if (normalizedPhotoUrl is not null && !IsHttpsUrl(normalizedPhotoUrl)) { - throw new ArgumentException("Photo URL must be an absolute http or https URL.", nameof(photoUrl)); + throw new ArgumentException("Photo URL must be an absolute https URL.", nameof(photoUrl)); } return new AuthorProfile(name, normalizedTitle, normalizedOrganization, normalizedPhotoUrl); @@ -65,7 +65,8 @@ public static AuthorProfile Create(string displayName, string? title = null, str return trimmed; } - private static bool IsHttpUrl(string value) => + // 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 || uri.Scheme == Uri.UriSchemeHttp); + && uri.Scheme == Uri.UriSchemeHttps; } diff --git a/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs b/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs index eb7ac4a81..b46a7d6ec 100644 --- a/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs +++ b/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs @@ -51,6 +51,11 @@ private Testimonial(int memberId, string content, AuthorProfile author, DateTime public bool CanBeSubmitted => CanBeEditedByAuthor; public bool CanBeDeletedByAuthor => Status == TestimonialStatus.Draft; + /// + /// Concurrency token so simultaneous reviews (e.g. two admins) fail instead of silently overwriting. + /// + public byte[] RowVersion { get; private set; } = []; + public static Testimonial CreateDraft(int memberId, string content, AuthorProfile author, DateTimeOffset now) { Guard.Against.NegativeOrZero(memberId); @@ -122,6 +127,14 @@ public void Unpublish(DateTimeOffset now, string? reason = null) MarkReviewed(now); } + /// + /// Call before removing the testimonial on the author's behalf; only drafts may be deleted. + /// + public void EnsureCanBeDeletedByAuthor() + { + EnsureStatus("delete", TestimonialStatus.Draft); + } + private void MarkReviewed(DateTimeOffset now) { ReviewedAt = now; diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Config/TestimonialConfig.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Config/TestimonialConfig.cs index 210fb8e82..cfc318ab6 100644 --- a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Config/TestimonialConfig.cs +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Config/TestimonialConfig.cs @@ -15,6 +15,7 @@ public void Configure(EntityTypeBuilder builder) builder.Property(t => t.Content).IsRequired().HasMaxLength(Testimonial.MaxContentLength); builder.Property(t => t.Status).IsRequired().HasConversion().HasMaxLength(32); builder.Property(t => t.ReviewerFeedback).HasMaxLength(Testimonial.MaxFeedbackLength); + builder.Property(t => t.RowVersion).IsRowVersion(); builder.OwnsOne(t => t.Author, author => { diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.Designer.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115212332_AddTestimonials.Designer.cs similarity index 93% rename from src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.Designer.cs rename to src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115212332_AddTestimonials.Designer.cs index e6efd2818..88dfbac76 100644 --- a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.Designer.cs +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115212332_AddTestimonials.Designer.cs @@ -12,7 +12,7 @@ namespace DevBetterWeb.Modules.Testimonials.Infrastructure.Data.Migrations; [DbContext(typeof(TestimonialsDbContext))] -[Migration("20261115211322_AddTestimonials")] +[Migration("20261115212332_AddTestimonials")] partial class AddTestimonials { /// @@ -52,6 +52,12 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + b.Property("Status") .IsRequired() .HasMaxLength(32) diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115212332_AddTestimonials.cs similarity index 93% rename from src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.cs rename to src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115212332_AddTestimonials.cs index 9e97bc8f7..e2771b6af 100644 --- a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115211322_AddTestimonials.cs +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/20261115212332_AddTestimonials.cs @@ -6,7 +6,7 @@ namespace DevBetterWeb.Modules.Testimonials.Infrastructure.Data.Migrations; /// -public partial class AddTestimonials : Migration +internal partial class AddTestimonials : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -32,7 +32,8 @@ protected override void Up(MigrationBuilder migrationBuilder) CreatedAt = table.Column(type: "datetimeoffset", nullable: false), UpdatedAt = table.Column(type: "datetimeoffset", nullable: false), SubmittedAt = table.Column(type: "datetimeoffset", nullable: true), - ReviewedAt = table.Column(type: "datetimeoffset", nullable: true) + ReviewedAt = table.Column(type: "datetimeoffset", nullable: true), + RowVersion = table.Column(type: "rowversion", rowVersion: true, nullable: false) }, constraints: table => { diff --git a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/TestimonialsDbContextModelSnapshot.cs b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/TestimonialsDbContextModelSnapshot.cs index cd6a636e2..4a335d902 100644 --- a/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/TestimonialsDbContextModelSnapshot.cs +++ b/src/DevBetterWeb.Modules.Testimonials/Infrastructure/Data/Migrations/TestimonialsDbContextModelSnapshot.cs @@ -16,7 +16,7 @@ partial class TestimonialsDbContextModelSnapshot : ModelSnapshot // If you encounter a merge conflict in the line below, it means you need to // discard one of the migration branches and recreate its migrations on top of // the other branch. See https://aka.ms/efcore-docs-migrations-conflicts for more info. - public override string LastMigrationId => "20261115211322_AddTestimonials"; + public override string LastMigrationId => "20261115212332_AddTestimonials"; protected override void BuildModel(ModelBuilder modelBuilder) { @@ -54,6 +54,12 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + b.Property("Status") .IsRequired() .HasMaxLength(32) diff --git a/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs b/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs index 9fd914a68..6cdbe20d2 100644 --- a/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs +++ b/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs @@ -47,6 +47,7 @@ public static DbContextOptionsBuilder UseTestimonialsSqlServer(this DbContextOpt /// /// Applies any pending migrations for the module's DbContext. /// + /// A scoped service provider (the DbContext is scoped). public static async Task ApplyTestimonialsMigrationsAsync(this IServiceProvider services, CancellationToken cancellationToken = default) { var dbContext = services.GetRequiredService(); diff --git a/tests/DevBetterWeb.FunctionalTests/Modules/TestimonialsModuleRegistration.cs b/tests/DevBetterWeb.FunctionalTests/Modules/TestimonialsModuleRegistration.cs new file mode 100644 index 000000000..e8c3eeb4c --- /dev/null +++ b/tests/DevBetterWeb.FunctionalTests/Modules/TestimonialsModuleRegistration.cs @@ -0,0 +1,27 @@ +using System.Threading.Tasks; +using DevBetterWeb.Modules.Testimonials.Contracts; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace DevBetterWeb.FunctionalTests.Modules; + +public class TestimonialsModuleRegistration : IClassFixture> +{ + private readonly CustomWebApplicationFactory _factory; + + public TestimonialsModuleRegistration(CustomWebApplicationFactory factory) + { + _factory = factory; + } + + [Fact] + public async Task HostResolvesTestimonialQueriesAgainstItsDatabase() + { + using var scope = _factory.Services.CreateScope(); + + var queries = scope.ServiceProvider.GetRequiredService(); + var accepted = await queries.ListAcceptedAsync(); + + Assert.Empty(accepted); + } +} diff --git a/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/AuthorProfileTests.cs b/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/AuthorProfileTests.cs index 45fb4ce65..803020624 100644 --- a/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/AuthorProfileTests.cs +++ b/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/AuthorProfileTests.cs @@ -68,15 +68,14 @@ public void CreateRejectsPhotoUrlOverMaxLength() Should.Throw(() => AuthorProfile.Create("Ada", photoUrl: url)); } - [Theory] - [InlineData("http://example.com/a.png")] - [InlineData("https://example.com/a.png")] - public void CreateAcceptsHttpPhotoUrls(string url) + [Fact] + public void CreateAcceptsHttpsPhotoUrl() { - AuthorProfile.Create("Ada", photoUrl: url).PhotoUrl.ShouldBe(url); + AuthorProfile.Create("Ada", photoUrl: "https://example.com/a.png").PhotoUrl.ShouldBe("https://example.com/a.png"); } [Theory] + [InlineData("http://example.com/a.png")] [InlineData("javascript:alert(1)")] [InlineData("data:image/png;base64,AAAA")] [InlineData("ftp://example.com/a.png")] diff --git a/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/TestimonialTransitionTests.cs b/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/TestimonialTransitionTests.cs index 04d3945de..621f8977f 100644 --- a/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/TestimonialTransitionTests.cs +++ b/tests/DevBetterWeb.Modules.Testimonials.Tests/Domain/TestimonialTransitionTests.cs @@ -17,6 +17,9 @@ public static TheoryData NotEditable() => public static TheoryData NotPendingReview() => new(Except(TestimonialStatus.PendingReview)); + public static TheoryData NotDraft() => + new(Except(TestimonialStatus.Draft)); + public static TheoryData NotAccepted() => new(Except(TestimonialStatus.Accepted)); @@ -224,13 +227,67 @@ public void FeedbackOverMaxLengthIsRejected() public void ReviewActionsThrowWhenNotPendingReview(TestimonialStatus status) { var testimonial = TestimonialBuilder.InStatus(status); + var before = Snapshot(testimonial); Should.Throw(() => testimonial.Accept(Now)); - Should.Throw(() => testimonial.Decline(Now)); + Should.Throw(() => testimonial.Decline(Now, "feedback")); Should.Throw(() => testimonial.RequestChanges("feedback", Now)); - testimonial.Status.ShouldBe(status); + Snapshot(testimonial).ShouldBe(before); + } + + [Fact] + public void DeclineRejectsFeedbackOverMaxLength() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview); + var before = Snapshot(testimonial); + + Should.Throw(() => testimonial.Decline(Now, new string('x', Testimonial.MaxFeedbackLength + 1))); + Snapshot(testimonial).ShouldBe(before); + } + + [Fact] + public void UnpublishRejectsReasonOverMaxLength() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.Accepted); + var before = Snapshot(testimonial); + + Should.Throw(() => testimonial.Unpublish(Now, new string('x', Testimonial.MaxFeedbackLength + 1))); + Snapshot(testimonial).ShouldBe(before); + } + + [Fact] + public void CreateDraftRejectsNullAuthor() + { + Should.Throw(() => Testimonial.CreateDraft(1, "text", null!, Now)); } + [Fact] + public void EditRejectsNullAuthor() + { + var testimonial = TestimonialBuilder.Draft(); + + Should.Throw(() => testimonial.Edit("text", null!, Now)); + testimonial.Content.ShouldBe(TestimonialBuilder.DefaultContent); + } + + [Fact] + public void EnsureCanBeDeletedByAuthorAllowsDraft() + { + Should.NotThrow(() => TestimonialBuilder.Draft().EnsureCanBeDeletedByAuthor()); + } + + [Theory] + [MemberData(nameof(NotDraft))] + public void EnsureCanBeDeletedByAuthorThrowsWhenNotDraft(TestimonialStatus status) + { + var testimonial = TestimonialBuilder.InStatus(status); + + Should.Throw(() => testimonial.EnsureCanBeDeletedByAuthor()); + } + + private static (TestimonialStatus, string?, DateTimeOffset, DateTimeOffset?, DateTimeOffset?) Snapshot(Testimonial t) => + (t.Status, t.ReviewerFeedback, t.UpdatedAt, t.SubmittedAt, t.ReviewedAt); + [Fact] public void UnpublishMovesAcceptedToDeclined() { @@ -268,7 +325,21 @@ public void AuthorCapabilitiesMatchStatus(TestimonialStatus status) [Fact] public void DeclinedIsTerminal() { - var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.Declined); + AssertTerminal(TestimonialBuilder.InStatus(TestimonialStatus.Declined)); + } + + [Fact] + public void DeclinedViaUnpublishIsTerminal() + { + var testimonial = TestimonialBuilder.InStatus(TestimonialStatus.Accepted); + testimonial.Unpublish(Now); + + AssertTerminal(testimonial); + } + + private static void AssertTerminal(Testimonial testimonial) + { + testimonial.Status.ShouldBe(TestimonialStatus.Declined); Should.Throw(() => testimonial.Edit("x", TestimonialBuilder.Author(), Now)); Should.Throw(() => testimonial.Submit(Now));