diff --git a/.claude/plans/2026-11-16-issue-1490-testimonials-member-authoring.md b/.claude/plans/2026-11-16-issue-1490-testimonials-member-authoring.md new file mode 100644 index 000000000..2138a1102 --- /dev/null +++ b/.claude/plans/2026-11-16-issue-1490-testimonials-member-authoring.md @@ -0,0 +1,61 @@ +# Issue #1490 – Testimonials: member authoring UI + +Issue: https://github.com/DevBetterCom/DevBetterWeb/issues/1490 +Parent: https://github.com/DevBetterCom/DevBetterWeb/issues/1472 (the run started on the parent and pivoted here: #1489 is closed, and #1490 is the first open, unblocked sub-issue) +Branch: `issue-1490-testimonials-member-authoring` + +## Assumptions / scope + +- Pages live at `/User/MyProfile/Testimonials` (list) and `/User/MyProfile/Testimonials/Edit[/{id}]` + (create or edit). They use the same roles as the other MyProfile pages: `ADMINISTRATORS_MEMBERS_ALUMNI`. +- The module exposes a public use-case surface, `ITestimonialAuthoring`, in Contracts. It is keyed by + `memberId`, and every call filters by `memberId`, so members only see or change their own testimonials. + Someone else's id behaves exactly like a missing id (NotFound → 404). Calls return a small + `TestimonialOperationResult` (Success / NotFound / NotAllowed / Invalid with field errors). Ardalis.Result + was considered, but the Contracts project is documented as dependency-free. +- The Web layer resolves the current `Member.Id` (and a default display name from `UserFullName()`) + through Core. The module never touches Membership. +- Read-only means the edit page shows the content without a form when `CanBeEditedByAuthor` is false + (`PendingReview`, `Accepted`, `Declined`). A POST in those states is rejected by the domain + (`InvalidTestimonialStateException` → `NotAllowed`). The page shows the error and nothing changes. +- Admin feedback (`ReviewerFeedback`) is shown to the author for `ChangesRequested` and `Declined`. This + includes an unpublish reason, which settles the open question from #1489. +- Submitting is a separate action, available on the list and on the edit page for editable items. + Deleting is offered only for drafts. +- The photo URL is optional. Help text says a blank value falls back to the member avatar (#1492 renders it). +- The clock comes from `TimeProvider` (`TryAddSingleton(TimeProvider.System)` in the module). + +## Phase 1 – Module application surface + +- [x] Contracts: `ITestimonialAuthoring`, `TestimonialDraftInput`, `MemberTestimonialDto` (adds status, feedback, timestamps, and `CanEdit`/`CanSubmit`/`CanDelete` flags). +- [x] Module: `TestimonialAuthoring` implementation. It validates input into field errors and maps domain state exceptions/concurrency to `NotAllowed`, ownership misses to `NotFound`. Register it in `AddTestimonialsModule`, along with `TimeProvider`. + +## Phase 2 – Razor pages + +- [x] `Pages/User/MyProfile/Testimonials/Index` lists the member's testimonials with status and feedback, plus Submit/Delete handlers. +- [x] `Pages/User/MyProfile/Testimonials/Edit` creates or edits, with a read-only view when not editable, a Save handler, and a Save & Submit handler. +- [x] Add a "Testimonials" card/link on `MyProfile/Index`. + +## Phase 3 – Automated tests + +- [x] Unit (`DevBetterWeb.Modules.Testimonials.Tests/Application`, in-memory DB): create, edit, submit, delete; ownership (another member → NotFound); edit/submit/delete blocked after submit (NotAllowed); invalid input (Invalid); list is scoped to the member. +- [x] Functional (`DevBetterWeb.FunctionalTests/RazorPages/Testimonials`) with a test auth handler that signs in as a seeded member: create, edit, submit, edit-blocked-after-submit, cannot view another member's testimonial (404), anonymous is challenged. + +## Phase 4 – Independent review + +- [x] A separate agent reviews the full diff against #1490. +- [x] Address significant findings, or record the reasons here. + - **Result:** no blockers or significant findings. + - **Applied:** + - The "Back to My Profile" link resolved to `/User/` and now uses `asp-page`. + - Added functional tests: feedback shown and resubmitted after ChangesRequested, Accepted is read-only (409 on POST), and the blocked submit/delete error message is displayed. The functional tests get `InternalsVisibleTo` on the module so they can apply admin transitions until #1491 exists. + - Each card now has a heading, and action buttons use `aria-describedby`, so screen readers can tell the cards apart. + - The author line is joined with ", " so there is no stray space before the commas (shared `TestimonialDisplay.AuthorLine`). + - **Left alone, with reasons:** + - Client `[StringLength]` counts untrimmed text and LF vs CRLF line breaks differently from the server. Near the 4000 limit, the server's message is shown instead. It's harmless. + - Each save loads the testimonial twice (page status check, then module). It's cheap. Last write wins between two tabs editing the same draft, and admins can't act on Draft/ChangesRequested, so the RowVersion window is acceptable. + - **Also fixed (found while testing):** `CustomWebApplicationFactory` built a new EF internal service provider per scope for the app and identity DBs, so seed data was invisible to requests. The provider is now built once, matching the testimonials registration. + +## Phase 5 – Verification + +- [x] `dotnet build && dotnet test && dotnet format --verify-no-changes`. 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.Contracts/ITestimonialAuthoring.cs b/src/DevBetterWeb.Modules.Testimonials.Contracts/ITestimonialAuthoring.cs new file mode 100644 index 000000000..58295f03c --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/ITestimonialAuthoring.cs @@ -0,0 +1,26 @@ +namespace DevBetterWeb.Modules.Testimonials.Contracts; + +/// +/// Member-facing use cases for writing testimonials. Every call is scoped to memberId: +/// a testimonial owned by another member is reported as not found. +/// The caller is responsible for passing the signed-in member's id. +/// +public interface ITestimonialAuthoring +{ + /// Returns the member's testimonials, most recently updated first. + Task> ListForMemberAsync(int memberId, CancellationToken cancellationToken = default); + + /// Returns the member's testimonial, or null if it does not exist or belongs to someone else. + Task GetForMemberAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default); + + Task CreateDraftAsync(int memberId, TestimonialDraftInput input, CancellationToken cancellationToken = default); + + /// Edits a testimonial in Draft or ChangesRequested. + Task UpdateAsync(int memberId, int testimonialId, TestimonialDraftInput input, CancellationToken cancellationToken = default); + + /// Submits (or resubmits) a testimonial for admin review. + Task SubmitAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default); + + /// Deletes a testimonial that is still a Draft. + Task DeleteDraftAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default); +} diff --git a/src/DevBetterWeb.Modules.Testimonials.Contracts/MemberTestimonialDto.cs b/src/DevBetterWeb.Modules.Testimonials.Contracts/MemberTestimonialDto.cs new file mode 100644 index 000000000..168b9f140 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/MemberTestimonialDto.cs @@ -0,0 +1,23 @@ +namespace DevBetterWeb.Modules.Testimonials.Contracts; + +/// +/// A testimonial as seen by its author, including review status and feedback. +/// +public sealed record MemberTestimonialDto( + int Id, + string Content, + string DisplayName, + string? Title, + string? Organization, + string? PhotoUrl, + TestimonialStatus Status, + string? ReviewerFeedback, + DateTimeOffset CreatedAt, + DateTimeOffset UpdatedAt, + DateTimeOffset? SubmittedAt, + DateTimeOffset? ReviewedAt) +{ + public bool CanEdit => Status is TestimonialStatus.Draft or TestimonialStatus.ChangesRequested; + public bool CanSubmit => CanEdit; + public bool CanDelete => Status == TestimonialStatus.Draft; +} diff --git a/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialDraftInput.cs b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialDraftInput.cs new file mode 100644 index 000000000..1825697c6 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialDraftInput.cs @@ -0,0 +1,12 @@ +namespace DevBetterWeb.Modules.Testimonials.Contracts; + +/// +/// What a member enters when writing or editing a testimonial. +/// +/// Optional absolute https URL; null or blank falls back to the member's avatar. +public sealed record TestimonialDraftInput( + string Content, + string DisplayName, + string? Title, + string? Organization, + string? PhotoUrl); diff --git a/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialLimits.cs b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialLimits.cs new file mode 100644 index 000000000..d815e6ac3 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialLimits.cs @@ -0,0 +1,14 @@ +namespace DevBetterWeb.Modules.Testimonials.Contracts; + +/// +/// Field limits for testimonials, shared with callers so their forms can validate up front. +/// +public static class TestimonialLimits +{ + public const int MaxContentLength = 4000; + public const int MaxFeedbackLength = 2000; + public const int MaxDisplayNameLength = 100; + public const int MaxTitleLength = 100; + public const int MaxOrganizationLength = 100; + public const int MaxPhotoUrlLength = 500; +} diff --git a/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialOperationResult.cs b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialOperationResult.cs new file mode 100644 index 000000000..94806c9d1 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials.Contracts/TestimonialOperationResult.cs @@ -0,0 +1,52 @@ +namespace DevBetterWeb.Modules.Testimonials.Contracts; + +public enum TestimonialOperationStatus +{ + Success = 0, + + /// The testimonial does not exist or belongs to another member. + NotFound = 1, + + /// The operation is not allowed in the testimonial's current status, or it changed concurrently. + NotAllowed = 2, + + /// The input failed validation; see . + Invalid = 3, +} + +/// The property name, or null for a general error. +public sealed record TestimonialValidationError(string? Field, string Message); + +/// +/// Outcome of an authoring command. Contracts stay dependency-free, so this is a small local result type. +/// +public sealed record TestimonialOperationResult +{ + private TestimonialOperationResult(TestimonialOperationStatus status, int? testimonialId, IReadOnlyList errors) + { + Status = status; + TestimonialId = testimonialId; + Errors = errors; + } + + public TestimonialOperationStatus Status { get; } + + /// The affected testimonial's id when the operation succeeded. + public int? TestimonialId { get; } + + public IReadOnlyList Errors { get; } + + public bool IsSuccess => Status == TestimonialOperationStatus.Success; + + public static TestimonialOperationResult Success(int testimonialId) => + new(TestimonialOperationStatus.Success, testimonialId, []); + + public static TestimonialOperationResult NotFound() => + new(TestimonialOperationStatus.NotFound, null, []); + + public static TestimonialOperationResult NotAllowed(string message) => + new(TestimonialOperationStatus.NotAllowed, null, [new TestimonialValidationError(null, message)]); + + public static TestimonialOperationResult Invalid(IReadOnlyList errors) => + new(TestimonialOperationStatus.Invalid, null, errors); +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialAuthoring.cs b/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialAuthoring.cs new file mode 100644 index 000000000..0db4d5c5b --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialAuthoring.cs @@ -0,0 +1,164 @@ +using System.Linq.Expressions; +using DevBetterWeb.Modules.Testimonials.Contracts; +using DevBetterWeb.Modules.Testimonials.Domain; +using DevBetterWeb.Modules.Testimonials.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace DevBetterWeb.Modules.Testimonials.Application; + +internal sealed class TestimonialAuthoring : ITestimonialAuthoring +{ + internal const string ConcurrencyMessage = "This testimonial was changed by someone else. Reload the page and try again."; + + private readonly TestimonialsDbContext _dbContext; + private readonly TimeProvider _timeProvider; + + public TestimonialAuthoring(TestimonialsDbContext dbContext, TimeProvider timeProvider) + { + _dbContext = dbContext; + _timeProvider = timeProvider; + } + + public async Task> ListForMemberAsync(int memberId, CancellationToken cancellationToken = default) + { + return await _dbContext.Testimonials + .AsNoTracking() + .Where(t => t.MemberId == memberId) + .OrderByDescending(t => t.UpdatedAt) + .ThenByDescending(t => t.Id) + .Select(ToDto) + .ToListAsync(cancellationToken); + } + + public async Task GetForMemberAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default) + { + return await _dbContext.Testimonials + .AsNoTracking() + .Where(t => t.Id == testimonialId && t.MemberId == memberId) + .Select(ToDto) + .SingleOrDefaultAsync(cancellationToken); + } + + public async Task CreateDraftAsync(int memberId, TestimonialDraftInput input, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(memberId); + + var errors = TestimonialDraftInputValidator.Validate(input); + if (errors.Count > 0) + { + return TestimonialOperationResult.Invalid(errors); + } + + var testimonial = Testimonial.CreateDraft(memberId, input.Content, ToAuthor(input), Now); + _dbContext.Testimonials.Add(testimonial); + await _dbContext.SaveChangesAsync(cancellationToken); + + return TestimonialOperationResult.Success(testimonial.Id); + } + + public async Task UpdateAsync(int memberId, int testimonialId, TestimonialDraftInput input, CancellationToken cancellationToken = default) + { + var testimonial = await FindOwnedAsync(memberId, testimonialId, cancellationToken); + if (testimonial is null) + { + return TestimonialOperationResult.NotFound(); + } + + if (!testimonial.CanBeEditedByAuthor) + { + return NotAllowed("edit", testimonial.Status); + } + + var errors = TestimonialDraftInputValidator.Validate(input); + if (errors.Count > 0) + { + return TestimonialOperationResult.Invalid(errors); + } + + return await ApplyAsync(testimonial, t => t.Edit(input.Content, ToAuthor(input), Now), cancellationToken); + } + + public async Task SubmitAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default) + { + var testimonial = await FindOwnedAsync(memberId, testimonialId, cancellationToken); + if (testimonial is null) + { + return TestimonialOperationResult.NotFound(); + } + + return await ApplyAsync(testimonial, t => t.Submit(Now), cancellationToken); + } + + public async Task DeleteDraftAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default) + { + var testimonial = await FindOwnedAsync(memberId, testimonialId, cancellationToken); + if (testimonial is null) + { + return TestimonialOperationResult.NotFound(); + } + + return await ApplyAsync(testimonial, t => + { + t.EnsureCanBeDeletedByAuthor(); + _dbContext.Testimonials.Remove(t); + }, cancellationToken); + } + + private DateTimeOffset Now => _timeProvider.GetUtcNow(); + + private Task FindOwnedAsync(int memberId, int testimonialId, CancellationToken cancellationToken) => + _dbContext.Testimonials.SingleOrDefaultAsync(t => t.Id == testimonialId && t.MemberId == memberId, cancellationToken); + + private async Task ApplyAsync(Testimonial testimonial, Action change, CancellationToken cancellationToken) + { + try + { + change(testimonial); + } + catch (InvalidTestimonialStateException ex) + { + return NotAllowed(ex.Operation, ex.CurrentStatus); + } + + try + { + await _dbContext.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateConcurrencyException) + { + return TestimonialOperationResult.NotAllowed(ConcurrencyMessage); + } + + return TestimonialOperationResult.Success(testimonial.Id); + } + + private static TestimonialOperationResult NotAllowed(string operation, TestimonialStatus status) => + TestimonialOperationResult.NotAllowed($"You can't {operation} a testimonial while it is {StatusText(status)}."); + + private static string StatusText(TestimonialStatus status) => status switch + { + TestimonialStatus.PendingReview => "pending review", + TestimonialStatus.ChangesRequested => "awaiting your changes", + TestimonialStatus.Accepted => "accepted", + TestimonialStatus.Declined => "declined", + _ => "a draft", + }; + + private static AuthorProfile ToAuthor(TestimonialDraftInput input) => + AuthorProfile.Create(input.DisplayName, input.Title, input.Organization, input.PhotoUrl); + + private static readonly Expression> ToDto = t => + new MemberTestimonialDto( + t.Id, + t.Content, + t.Author.DisplayName, + t.Author.Title, + t.Author.Organization, + t.Author.PhotoUrl, + t.Status, + t.Status == TestimonialStatus.ChangesRequested || t.Status == TestimonialStatus.Declined ? t.ReviewerFeedback : null, + t.CreatedAt, + t.UpdatedAt, + t.SubmittedAt, + t.ReviewedAt); +} diff --git a/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialDraftInputValidator.cs b/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialDraftInputValidator.cs new file mode 100644 index 000000000..5130e0103 --- /dev/null +++ b/src/DevBetterWeb.Modules.Testimonials/Application/TestimonialDraftInputValidator.cs @@ -0,0 +1,67 @@ +using DevBetterWeb.Modules.Testimonials.Contracts; +using DevBetterWeb.Modules.Testimonials.Domain; + +namespace DevBetterWeb.Modules.Testimonials.Application; + +/// +/// Turns author input problems into field-level messages before the domain's guard clauses +/// (which remain the last line of defense) would throw. +/// +internal static class TestimonialDraftInputValidator +{ + public static IReadOnlyList Validate(TestimonialDraftInput? input) + { + if (input is null) + { + return [new TestimonialValidationError(null, "A testimonial is required.")]; + } + + var errors = new List(); + + Required(errors, input.Content, nameof(TestimonialDraftInput.Content), "testimonial", TestimonialLimits.MaxContentLength); + Required(errors, input.DisplayName, nameof(TestimonialDraftInput.DisplayName), "display name", TestimonialLimits.MaxDisplayNameLength); + Optional(errors, input.Title, nameof(TestimonialDraftInput.Title), "title", TestimonialLimits.MaxTitleLength); + Optional(errors, input.Organization, nameof(TestimonialDraftInput.Organization), "company or organization", TestimonialLimits.MaxOrganizationLength); + + if (Optional(errors, input.PhotoUrl, nameof(TestimonialDraftInput.PhotoUrl), "photo URL", TestimonialLimits.MaxPhotoUrlLength) is string photoUrl + && !AuthorProfile.IsHttpsUrl(photoUrl)) + { + errors.Add(new TestimonialValidationError(nameof(TestimonialDraftInput.PhotoUrl), "Photo URL must be an absolute https:// URL.")); + } + + return errors; + } + + private static void Required(List errors, string? value, string field, string label, int maxLength) + { + if (string.IsNullOrWhiteSpace(value)) + { + errors.Add(new TestimonialValidationError(field, $"The {label} is required.")); + return; + } + + CheckLength(errors, value.Trim(), field, label, maxLength); + } + + private static string? Optional(List errors, string? value, string field, string label, int maxLength) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + string trimmed = value.Trim(); + return CheckLength(errors, trimmed, field, label, maxLength) ? trimmed : null; + } + + private static bool CheckLength(List errors, string trimmed, string field, string label, int maxLength) + { + if (trimmed.Length > maxLength) + { + errors.Add(new TestimonialValidationError(field, $"The {label} must be at most {maxLength} characters.")); + return false; + } + + return true; + } +} diff --git a/src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj b/src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj index 3de052bb1..e63c7326e 100644 --- a/src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj +++ b/src/DevBetterWeb.Modules.Testimonials/DevBetterWeb.Modules.Testimonials.csproj @@ -15,6 +15,8 @@ + + diff --git a/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs b/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs index a023782db..3c30083f9 100644 --- a/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs +++ b/src/DevBetterWeb.Modules.Testimonials/Domain/AuthorProfile.cs @@ -1,4 +1,5 @@ using Ardalis.GuardClauses; +using DevBetterWeb.Modules.Testimonials.Contracts; namespace DevBetterWeb.Modules.Testimonials.Domain; @@ -7,10 +8,10 @@ namespace DevBetterWeb.Modules.Testimonials.Domain; /// internal sealed class AuthorProfile { - public const int MaxDisplayNameLength = 100; - public const int MaxTitleLength = 100; - public const int MaxOrganizationLength = 100; - public const int MaxPhotoUrlLength = 500; + public const int MaxDisplayNameLength = TestimonialLimits.MaxDisplayNameLength; + public const int MaxTitleLength = TestimonialLimits.MaxTitleLength; + public const int MaxOrganizationLength = TestimonialLimits.MaxOrganizationLength; + public const int MaxPhotoUrlLength = TestimonialLimits.MaxPhotoUrlLength; // EF Core private AuthorProfile() @@ -66,7 +67,7 @@ public static AuthorProfile Create(string displayName, string? title = null, str } // https only: avoids mixed content on the site and rules out javascript:/data: schemes. - private static bool IsHttpsUrl(string value) => + internal static bool IsHttpsUrl(string value) => Uri.TryCreate(value, UriKind.Absolute, out Uri? uri) && uri.Scheme == Uri.UriSchemeHttps; } diff --git a/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs b/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs index b46a7d6ec..e2e5c05dd 100644 --- a/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs +++ b/src/DevBetterWeb.Modules.Testimonials/Domain/Testimonial.cs @@ -10,8 +10,8 @@ namespace DevBetterWeb.Modules.Testimonials.Domain; /// internal sealed class Testimonial { - public const int MaxContentLength = 4000; - public const int MaxFeedbackLength = 2000; + public const int MaxContentLength = TestimonialLimits.MaxContentLength; + public const int MaxFeedbackLength = TestimonialLimits.MaxFeedbackLength; // EF Core private Testimonial() diff --git a/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs b/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs index 6cdbe20d2..23b3d3084 100644 --- a/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs +++ b/src/DevBetterWeb.Modules.Testimonials/TestimonialsModule.cs @@ -28,7 +28,9 @@ public static IServiceCollection AddTestimonialsModule( services.AddDbContext(configureDbContext); } + services.TryAddSingleton(TimeProvider.System); services.TryAddScoped(); + services.TryAddScoped(); return services; } diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/Index.cshtml b/src/DevBetterWeb.Web/Pages/User/MyProfile/Index.cshtml index 2fcbd77a2..0408cd212 100644 --- a/src/DevBetterWeb.Web/Pages/User/MyProfile/Index.cshtml +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/Index.cshtml @@ -189,5 +189,16 @@ View +
+ +
+
+ Testimonials +
+
+

Share what devBetter has meant to you.

+ Manage +
+
\ No newline at end of file diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Edit.cshtml b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Edit.cshtml new file mode 100644 index 000000000..9382d6039 --- /dev/null +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Edit.cshtml @@ -0,0 +1,93 @@ +@page "{id:int?}" +@using DevBetterWeb.Modules.Testimonials.Contracts +@using DevBetterWeb.Web.Pages.User.MyProfile.Testimonials +@model DevBetterWeb.Web.Pages.User.MyProfile.Testimonials.EditModel +@{ + ViewData["Title"] = Model.IsNew ? "Write a Testimonial" : Model.IsReadOnly ? "View Testimonial" : "Edit Testimonial"; +} + +

@ViewData["Title"]

+ +@if (!string.IsNullOrEmpty(Model.ErrorMessage)) +{ + +} + +
+
+ @if (Model.Testimonial is MemberTestimonialDto current) + { +

+ Status: @TestimonialDisplay.Label(current.Status) + @TestimonialDisplay.Explanation(current.Status) +

+ @if (!string.IsNullOrEmpty(current.ReviewerFeedback)) + { +
+ Feedback from the reviewer: +
@current.ReviewerFeedback
+
+ } + } + + @if (Model.IsReadOnly) + { + +
+
+

@Model.Testimonial!.Content

+

— @TestimonialDisplay.AuthorLine(Model.Testimonial!)

+
+
+ } + else + { +
+ +
+
+
+ + + Up to @TestimonialLimits.MaxContentLength characters. + +
+ +
How you want to be known
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + Optional https:// link to a photo. Leave blank to use your profile avatar. + +
+
+
+ + + +
+ } + +
+ Back to My Testimonials +
+
+ +@section Scripts { + @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} +} diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Edit.cshtml.cs b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Edit.cshtml.cs new file mode 100644 index 000000000..16420098d --- /dev/null +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Edit.cshtml.cs @@ -0,0 +1,150 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DevBetterWeb.Core.Entities; +using DevBetterWeb.Core.Interfaces; +using DevBetterWeb.Infrastructure.Identity.Data; +using DevBetterWeb.Modules.Testimonials.Contracts; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace DevBetterWeb.Web.Pages.User.MyProfile.Testimonials; + +public class EditModel : MyTestimonialsPageModel +{ + public EditModel( + ITestimonialAuthoring authoring, + UserManager userManager, + IRepository memberRepository, + IMemberRegistrationService memberRegistrationService) + : base(authoring, userManager, memberRepository, memberRegistrationService) + { + } + + [BindProperty] + public TestimonialInputModel Input { get; set; } = new(); + + /// The testimonial being edited; null when writing a new one. + public MemberTestimonialDto? Testimonial { get; private set; } + + public bool IsNew => Testimonial is null; + public bool IsReadOnly => Testimonial is { CanEdit: false }; + + public async Task OnGetAsync(int? id) + { + var member = await GetCurrentMemberAsync(); + + if (id is not int testimonialId) + { + Input = new TestimonialInputModel { DisplayName = DefaultDisplayName(member) }; + return Page(); + } + + Testimonial = await Authoring.GetForMemberAsync(member.Id, testimonialId, HttpContext.RequestAborted); + if (Testimonial is null) + { + return NotFound(); + } + + Input = TestimonialInputModel.From(Testimonial); + return Page(); + } + + public Task OnPostAsync(int? id) => SaveAsync(id, submitForReview: false); + + public Task OnPostSubmitForReviewAsync(int? id) => SaveAsync(id, submitForReview: true); + + private async Task SaveAsync(int? id, bool submitForReview) + { + var member = await GetCurrentMemberAsync(); + var cancellationToken = HttpContext.RequestAborted; + + if (id is int existingId) + { + Testimonial = await Authoring.GetForMemberAsync(member.Id, existingId, cancellationToken); + if (Testimonial is null) + { + return NotFound(); + } + + if (!Testimonial.CanEdit) + { + return ConflictPage($"You can't change a testimonial while it is {TestimonialDisplay.Label(Testimonial.Status).ToLowerInvariant()}."); + } + } + + if (!ModelState.IsValid) + { + return Page(); + } + + var input = Input.ToDraftInput(); + var saved = Testimonial is null + ? await Authoring.CreateDraftAsync(member.Id, input, cancellationToken) + : await Authoring.UpdateAsync(member.Id, Testimonial.Id, input, cancellationToken); + + if (!saved.IsSuccess) + { + return await FailureAsync(member.Id, id, saved); + } + + int savedId = saved.TestimonialId!.Value; + if (!submitForReview) + { + StatusMessage = "Your testimonial was saved."; + return RedirectToPage("./Index"); + } + + var submitted = await Authoring.SubmitAsync(member.Id, savedId, cancellationToken); + if (!submitted.IsSuccess) + { + ErrorMessage = "Your changes were saved, but the testimonial could not be submitted. " + string.Join(" ", ErrorMessages(submitted)); + return RedirectToPage("./Edit", new { id = savedId }); + } + + StatusMessage = "Your testimonial was submitted for review."; + return RedirectToPage("./Index"); + } + + private async Task FailureAsync(int memberId, int? id, TestimonialOperationResult result) + { + switch (result.Status) + { + case TestimonialOperationStatus.NotFound: + return NotFound(); + + case TestimonialOperationStatus.Invalid: + foreach (var error in result.Errors) + { + ModelState.AddModelError(error.Field is null ? string.Empty : $"{nameof(Input)}.{error.Field}", error.Message); + } + return Page(); + + default: + // Status changed since the page loaded (e.g. an admin reviewed it, or it was submitted in another tab). + if (id is int existingId) + { + Testimonial = await Authoring.GetForMemberAsync(memberId, existingId, HttpContext.RequestAborted); + } + return ConflictPage(string.Join(" ", ErrorMessages(result))); + } + } + + private PageResult ConflictPage(string message) + { + ModelState.AddModelError(string.Empty, message); + var page = Page(); + page.StatusCode = StatusCodes.Status409Conflict; + return page; + } + + private static IEnumerable ErrorMessages(TestimonialOperationResult result) => + result.Errors.Select(e => e.Message); + + private static string DefaultDisplayName(Member member) => + string.IsNullOrWhiteSpace(member.FirstName) || string.IsNullOrWhiteSpace(member.LastName) + ? string.Empty + : $"{member.FirstName} {member.LastName}"; +} diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Index.cshtml b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Index.cshtml new file mode 100644 index 000000000..63cac8c62 --- /dev/null +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Index.cshtml @@ -0,0 +1,76 @@ +@page +@using DevBetterWeb.Web.Pages.User.MyProfile.Testimonials +@model DevBetterWeb.Web.Pages.User.MyProfile.Testimonials.IndexModel +@{ + ViewData["Title"] = "My Profile: Testimonials"; +} + +

My Profile: Testimonials

+ +

+ Share what devBetter has meant to you. Testimonials are reviewed by an admin before they appear on the site. +

+ +@if (!string.IsNullOrEmpty(Model.StatusMessage)) +{ +
@Model.StatusMessage
+} +@if (!string.IsNullOrEmpty(Model.ErrorMessage)) +{ + +} + +

+ Write a testimonial +

+ +@if (!Model.Testimonials.Any()) +{ +

You haven't written any testimonials yet.

+} + +
+
+ @foreach (var testimonial in Model.Testimonials) + { + string headingId = $"testimonial-{testimonial.Id}-heading"; +
+
+

Testimonial updated @testimonial.UpdatedAt.ToString("MMM d, yyyy")

+ @TestimonialDisplay.Label(testimonial.Status) +
+
+

@testimonial.Content

+

— @TestimonialDisplay.AuthorLine(testimonial)

+

@TestimonialDisplay.Explanation(testimonial.Status)

+ @if (!string.IsNullOrEmpty(testimonial.ReviewerFeedback)) + { +
+ Feedback from the reviewer: +
@testimonial.ReviewerFeedback
+
+ } +
+ @(testimonial.CanEdit ? "Edit" : "View") + @if (testimonial.CanSubmit) + { +
+ +
+ } + @if (testimonial.CanDelete) + { +
+ +
+ } +
+
+
+ } +
+
+ +Back to My Profile + diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Index.cshtml.cs b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Index.cshtml.cs new file mode 100644 index 000000000..50e2b38fc --- /dev/null +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/Index.cshtml.cs @@ -0,0 +1,62 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DevBetterWeb.Core.Entities; +using DevBetterWeb.Core.Interfaces; +using DevBetterWeb.Infrastructure.Identity.Data; +using DevBetterWeb.Modules.Testimonials.Contracts; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; + +namespace DevBetterWeb.Web.Pages.User.MyProfile.Testimonials; + +public class IndexModel : MyTestimonialsPageModel +{ + public IndexModel( + ITestimonialAuthoring authoring, + UserManager userManager, + IRepository memberRepository, + IMemberRegistrationService memberRegistrationService) + : base(authoring, userManager, memberRepository, memberRegistrationService) + { + } + + public IReadOnlyList Testimonials { get; private set; } = []; + + public async Task OnGetAsync() + { + var member = await GetCurrentMemberAsync(); + Testimonials = await Authoring.ListForMemberAsync(member.Id, HttpContext.RequestAborted); + } + + public async Task OnPostSubmitAsync(int id) + { + var member = await GetCurrentMemberAsync(); + var result = await Authoring.SubmitAsync(member.Id, id, HttpContext.RequestAborted); + return ToResponse(result, "Your testimonial was submitted for review."); + } + + public async Task OnPostDeleteAsync(int id) + { + var member = await GetCurrentMemberAsync(); + var result = await Authoring.DeleteDraftAsync(member.Id, id, HttpContext.RequestAborted); + return ToResponse(result, "Your draft was deleted."); + } + + private IActionResult ToResponse(TestimonialOperationResult result, string successMessage) + { + switch (result.Status) + { + case TestimonialOperationStatus.NotFound: + return NotFound(); + case TestimonialOperationStatus.Success: + StatusMessage = successMessage; + break; + default: + ErrorMessage = string.Join(" ", result.Errors.Select(e => e.Message)); + break; + } + + return RedirectToPage(); + } +} diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/MyTestimonialsPageModel.cs b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/MyTestimonialsPageModel.cs new file mode 100644 index 000000000..4b4c51387 --- /dev/null +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/MyTestimonialsPageModel.cs @@ -0,0 +1,58 @@ +using System.Threading.Tasks; +using DevBetterWeb.Core; +using DevBetterWeb.Core.Entities; +using DevBetterWeb.Core.Interfaces; +using DevBetterWeb.Core.Specs; +using DevBetterWeb.Infrastructure.Identity.Data; +using DevBetterWeb.Modules.Testimonials.Contracts; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace DevBetterWeb.Web.Pages.User.MyProfile.Testimonials; + +/// +/// Shared plumbing for the member's testimonial pages: resolves the signed-in member, whose id +/// scopes every call into the Testimonials module. +/// +[Authorize(Roles = AuthConstants.Roles.ADMINISTRATORS_MEMBERS_ALUMNI)] +public abstract class MyTestimonialsPageModel : PageModel +{ + private readonly UserManager _userManager; + private readonly IRepository _memberRepository; + private readonly IMemberRegistrationService _memberRegistrationService; + + protected MyTestimonialsPageModel( + ITestimonialAuthoring authoring, + UserManager userManager, + IRepository memberRepository, + IMemberRegistrationService memberRegistrationService) + { + Authoring = authoring; + _userManager = userManager; + _memberRepository = memberRepository; + _memberRegistrationService = memberRegistrationService; + } + + protected ITestimonialAuthoring Authoring { get; } + + [TempData] + public string? StatusMessage { get; set; } + + [TempData] + public string? ErrorMessage { get; set; } + + protected async Task GetCurrentMemberAsync() + { + var userId = _userManager.GetUserId(User); + if (string.IsNullOrEmpty(userId)) + { + var applicationUser = await _userManager.FindByNameAsync(User.Identity!.Name!); + userId = applicationUser!.Id; + } + + var member = await _memberRepository.FirstOrDefaultAsync(new MemberByUserIdSpec(userId), HttpContext.RequestAborted); + return member ?? await _memberRegistrationService.RegisterMemberAsync(userId); + } +} diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/TestimonialDisplay.cs b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/TestimonialDisplay.cs new file mode 100644 index 000000000..ba3f954c3 --- /dev/null +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/TestimonialDisplay.cs @@ -0,0 +1,42 @@ +using System.Linq; +using DevBetterWeb.Modules.Testimonials.Contracts; + +namespace DevBetterWeb.Web.Pages.User.MyProfile.Testimonials; + +public static class TestimonialDisplay +{ + public static string Label(TestimonialStatus status) => status switch + { + TestimonialStatus.Draft => "Draft", + TestimonialStatus.PendingReview => "Pending review", + TestimonialStatus.ChangesRequested => "Changes requested", + TestimonialStatus.Accepted => "Accepted", + TestimonialStatus.Declined => "Declined", + _ => status.ToString(), + }; + + public static string BadgeClass(TestimonialStatus status) => status switch + { + TestimonialStatus.Draft => "badge badge-secondary", + TestimonialStatus.PendingReview => "badge badge-info", + TestimonialStatus.ChangesRequested => "badge badge-warning", + TestimonialStatus.Accepted => "badge badge-success", + TestimonialStatus.Declined => "badge badge-danger", + _ => "badge badge-light", + }; + + public static string Explanation(TestimonialStatus status) => status switch + { + TestimonialStatus.Draft => "Only you can see this draft. Submit it when you're ready for an admin to review it.", + TestimonialStatus.PendingReview => "An admin is reviewing this testimonial. You can't change it while it is pending review.", + TestimonialStatus.ChangesRequested => "An admin asked for changes. Update it and submit it again.", + TestimonialStatus.Accepted => "This testimonial is published on the site.", + TestimonialStatus.Declined => "This testimonial was not accepted for publication.", + _ => string.Empty, + }; + + /// "Name, Title, Organization", skipping blank parts. + public static string AuthorLine(MemberTestimonialDto testimonial) => + string.Join(", ", new[] { testimonial.DisplayName, testimonial.Title, testimonial.Organization } + .Where(part => !string.IsNullOrWhiteSpace(part))); +} diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/TestimonialInputModel.cs b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/TestimonialInputModel.cs new file mode 100644 index 000000000..be3b71d79 --- /dev/null +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/Testimonials/TestimonialInputModel.cs @@ -0,0 +1,43 @@ +using System.ComponentModel.DataAnnotations; +using DevBetterWeb.Modules.Testimonials.Contracts; + +namespace DevBetterWeb.Web.Pages.User.MyProfile.Testimonials; + +/// +/// Form model for writing a testimonial. The module re-validates everything server side. +/// +public class TestimonialInputModel +{ + [Required] + [StringLength(TestimonialLimits.MaxContentLength)] + [Display(Name = "Your testimonial")] + public string Content { get; set; } = string.Empty; + + [Required] + [StringLength(TestimonialLimits.MaxDisplayNameLength)] + [Display(Name = "Display name")] + public string DisplayName { get; set; } = string.Empty; + + [StringLength(TestimonialLimits.MaxTitleLength)] + [Display(Name = "Title")] + public string? Title { get; set; } + + [StringLength(TestimonialLimits.MaxOrganizationLength)] + [Display(Name = "Company or organization")] + public string? Organization { get; set; } + + [StringLength(TestimonialLimits.MaxPhotoUrlLength)] + [Display(Name = "Photo URL")] + public string? PhotoUrl { get; set; } + + public static TestimonialInputModel From(MemberTestimonialDto testimonial) => new() + { + Content = testimonial.Content, + DisplayName = testimonial.DisplayName, + Title = testimonial.Title, + Organization = testimonial.Organization, + PhotoUrl = testimonial.PhotoUrl, + }; + + public TestimonialDraftInput ToDraftInput() => new(Content, DisplayName, Title, Organization, PhotoUrl); +} diff --git a/tests/DevBetterWeb.FunctionalTests/Auth/AuthenticatedWebApplicationFactory.cs b/tests/DevBetterWeb.FunctionalTests/Auth/AuthenticatedWebApplicationFactory.cs new file mode 100644 index 000000000..2b21d65bb --- /dev/null +++ b/tests/DevBetterWeb.FunctionalTests/Auth/AuthenticatedWebApplicationFactory.cs @@ -0,0 +1,34 @@ +using System.Net.Http; +using DevBetterWeb.Core; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; + +namespace DevBetterWeb.FunctionalTests.Auth; + +/// +/// The Testing host plus a header-driven authentication scheme, for pages that require a signed-in member. +/// +public class AuthenticatedWebApplicationFactory : CustomWebApplicationFactory +{ + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.ConfigureTestServices(services => + services.AddAuthentication(TestAuthHandler.SchemeName) + .AddScheme(TestAuthHandler.SchemeName, _ => { })); + } + + public HttpClient CreateClientFor(string userName, string role = AuthConstants.Roles.MEMBERS) + { + var client = CreateAnonymousClient(); + client.DefaultRequestHeaders.Add(TestAuthHandler.UserHeader, userName); + client.DefaultRequestHeaders.Add(TestAuthHandler.RoleHeader, role); + return client; + } + + public HttpClient CreateAnonymousClient() => + CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); +} diff --git a/tests/DevBetterWeb.FunctionalTests/Auth/TestAuthHandler.cs b/tests/DevBetterWeb.FunctionalTests/Auth/TestAuthHandler.cs new file mode 100644 index 000000000..a3b20c8f0 --- /dev/null +++ b/tests/DevBetterWeb.FunctionalTests/Auth/TestAuthHandler.cs @@ -0,0 +1,43 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +#nullable enable + +namespace DevBetterWeb.FunctionalTests.Auth; + +/// +/// Signs requests in as the user named in with the role in . +/// Requests without the header are anonymous, so [Authorize] pages return 401 (the challenge). +/// +public class TestAuthHandler : AuthenticationHandler +{ + public const string SchemeName = "Test"; + public const string UserHeader = "X-Test-User"; + public const string RoleHeader = "X-Test-Role"; + + public TestAuthHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder) + : base(options, logger, encoder) + { + } + + protected override Task HandleAuthenticateAsync() + { + string? userName = Request.Headers[UserHeader]; + if (string.IsNullOrEmpty(userName)) + { + return Task.FromResult(AuthenticateResult.NoResult()); + } + + var claims = new[] + { + new Claim(ClaimTypes.Name, userName), + new Claim(ClaimTypes.Role, Request.Headers[RoleHeader].ToString()), + }; + var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName)); + return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName))); + } +} diff --git a/tests/DevBetterWeb.FunctionalTests/CustomWebApplicationFactory.cs b/tests/DevBetterWeb.FunctionalTests/CustomWebApplicationFactory.cs index 7a875c904..21b597f07 100644 --- a/tests/DevBetterWeb.FunctionalTests/CustomWebApplicationFactory.cs +++ b/tests/DevBetterWeb.FunctionalTests/CustomWebApplicationFactory.cs @@ -85,20 +85,25 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) string inMemoryAppDb = Guid.NewGuid().ToString(); string inMemoryIdentityDb = Guid.NewGuid().ToString(); + // Build each EF internal service provider once. The options callbacks run per scope, and a new + // provider per scope would give every scope its own empty in-memory database (losing the seed data). + var appEfServiceProvider = new ServiceCollection() + .AddEntityFrameworkInMemoryDatabase() + .BuildServiceProvider(); + var identityEfServiceProvider = new ServiceCollection() + .AddEntityFrameworkInMemoryDatabase() + .BuildServiceProvider(); + services.AddDbContext(options => { options.UseInMemoryDatabase(inMemoryAppDb); - options.UseInternalServiceProvider(new ServiceCollection() - .AddEntityFrameworkInMemoryDatabase() - .BuildServiceProvider()); + options.UseInternalServiceProvider(appEfServiceProvider); }); services.AddDbContext(options => { options.UseInMemoryDatabase(inMemoryIdentityDb); - options.UseInternalServiceProvider(new ServiceCollection() - .AddEntityFrameworkInMemoryDatabase() - .BuildServiceProvider()); + options.UseInternalServiceProvider(identityEfServiceProvider); }); string inMemoryTestimonialsDb = Guid.NewGuid().ToString(); diff --git a/tests/DevBetterWeb.FunctionalTests/RazorPages/Testimonials/MyTestimonialsPages.cs b/tests/DevBetterWeb.FunctionalTests/RazorPages/Testimonials/MyTestimonialsPages.cs new file mode 100644 index 000000000..9ccd2ecd5 --- /dev/null +++ b/tests/DevBetterWeb.FunctionalTests/RazorPages/Testimonials/MyTestimonialsPages.cs @@ -0,0 +1,336 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using DevBetterWeb.Core; +using DevBetterWeb.FunctionalTests.Auth; +using DevBetterWeb.Infrastructure.Data; +using DevBetterWeb.Infrastructure.Identity.Data; +using DevBetterWeb.Modules.Testimonials.Contracts; +using DevBetterWeb.Modules.Testimonials.Domain; +using DevBetterWeb.Modules.Testimonials.Infrastructure.Data; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +#nullable enable + +namespace DevBetterWeb.FunctionalTests.RazorPages.Testimonials; + +public class MyTestimonialsPages : IClassFixture +{ + private const string IndexUrl = "/User/MyProfile/Testimonials"; + private const string EditUrl = "/User/MyProfile/Testimonials/Edit"; + private const string Author = AuthConstants.Users.Demo.EMAIL; + private const string OtherMember = AuthConstants.Users.Demo2.EMAIL; + + private readonly AuthenticatedWebApplicationFactory _factory; + + public MyTestimonialsPages(AuthenticatedWebApplicationFactory factory) + { + _factory = factory; + } + + [Fact] + public async Task AnonymousUsersAreChallenged() + { + var client = _factory.CreateAnonymousClient(); + + var response = await client.GetAsync(IndexUrl); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task IndexListsOnlyTheMembersOwnTestimonials() + { + string mine = Unique("mine"); + string theirs = Unique("theirs"); + await SeedDraftAsync(Author, mine); + await SeedDraftAsync(OtherMember, theirs); + + string html = await GetSuccessHtmlAsync(_factory.CreateClientFor(Author), IndexUrl); + + Assert.Contains(mine, html); + Assert.DoesNotContain(theirs, html); + } + + [Fact] + public async Task NewTestimonialFormDefaultsDisplayNameToMemberName() + { + string html = await GetSuccessHtmlAsync(_factory.CreateClientFor(Author), EditUrl); + + Assert.Contains($"value=\"{AuthConstants.Users.Demo.FIRST_NAME} {AuthConstants.Users.Demo.LAST_NAME}\"", html); + } + + [Fact] + public async Task MemberCanCreateDraft() + { + var client = _factory.CreateClientFor(Author); + string content = Unique("created"); + + var response = await PostFormAsync(client, EditUrl, EditUrl, FormFor(content, title: "Engineer", organization: "Acme")); + + AssertRedirectsTo(IndexUrl, response); + var created = (await ListAsync(Author)).Single(t => t.Content == content); + Assert.Equal(TestimonialStatus.Draft, created.Status); + Assert.Equal("Demo User", created.DisplayName); + Assert.Equal("Engineer", created.Title); + Assert.Equal("Acme", created.Organization); + Assert.Null(created.PhotoUrl); + } + + [Fact] + public async Task InvalidInputRedisplaysFormWithErrors() + { + var client = _factory.CreateClientFor(Author); + string displayName = Unique("invalid"); + + var form = FormFor(content: "Valid text", displayName: displayName, photoUrl: "http://insecure.example.com/me.png"); + var response = await PostFormAsync(client, EditUrl, EditUrl, form); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("must be an absolute https:// URL", await response.Content.ReadAsStringAsync()); + Assert.DoesNotContain(await ListAsync(Author), t => t.DisplayName == displayName); + } + + [Fact] + public async Task MemberCanEditDraft() + { + int id = await SeedDraftAsync(Author, Unique("before")); + var client = _factory.CreateClientFor(Author); + string edited = Unique("after"); + + var response = await PostFormAsync(client, $"{EditUrl}/{id}", $"{EditUrl}/{id}", FormFor(edited)); + + AssertRedirectsTo(IndexUrl, response); + var testimonial = await GetAsync(Author, id); + Assert.Equal(edited, testimonial!.Content); + Assert.Equal(TestimonialStatus.Draft, testimonial.Status); + } + + [Fact] + public async Task MemberCanSubmitFromList() + { + int id = await SeedDraftAsync(Author, Unique("submit-list")); + var client = _factory.CreateClientFor(Author); + + var response = await PostFormAsync(client, IndexUrl, $"{IndexUrl}?handler=Submit&id={id}", []); + + AssertRedirectsTo(IndexUrl, response); + Assert.Equal(TestimonialStatus.PendingReview, (await GetAsync(Author, id))!.Status); + } + + [Fact] + public async Task MemberCanSaveAndSubmitFromEditPage() + { + int id = await SeedDraftAsync(Author, Unique("submit-edit")); + var client = _factory.CreateClientFor(Author); + string finalText = Unique("final"); + + var response = await PostFormAsync(client, $"{EditUrl}/{id}", $"{EditUrl}/{id}?handler=SubmitForReview", FormFor(finalText)); + + AssertRedirectsTo(IndexUrl, response); + var testimonial = (await GetAsync(Author, id))!; + Assert.Equal(TestimonialStatus.PendingReview, testimonial.Status); + Assert.Equal(finalText, testimonial.Content); + } + + [Fact] + public async Task EditingIsBlockedAfterSubmit() + { + string original = Unique("locked"); + int id = await SeedDraftAsync(Author, original); + await SubmitAsync(Author, id); + var client = _factory.CreateClientFor(Author); + + // The page renders read-only: content shown, no form fields. + string html = await GetSuccessHtmlAsync(client, $"{EditUrl}/{id}"); + Assert.Contains(original, html); + Assert.Contains("Pending review", html); + Assert.DoesNotContain(" t.RequestChanges(feedback, now)); + var client = _factory.CreateClientFor(Author); + + Assert.Contains(feedback, await GetSuccessHtmlAsync(client, IndexUrl)); + string editHtml = await GetSuccessHtmlAsync(client, $"{EditUrl}/{id}"); + Assert.Contains(feedback, editHtml); + Assert.Contains("Changes requested", editHtml); + Assert.Contains(" t.Accept(now)); + var client = _factory.CreateClientFor(Author); + + string html = await GetSuccessHtmlAsync(client, $"{EditUrl}/{id}"); + Assert.Contains(original, html); + Assert.Contains("Accepted", html); + Assert.DoesNotContain(" $"{label}-{Guid.NewGuid():N}"; + + private static Dictionary FormFor( + string content, + string displayName = "Demo User", + string title = "", + string organization = "", + string photoUrl = "") => new() + { + ["Input.Content"] = content, + ["Input.DisplayName"] = displayName, + ["Input.Title"] = title, + ["Input.Organization"] = organization, + ["Input.PhotoUrl"] = photoUrl, + }; + + private static async Task GetSuccessHtmlAsync(HttpClient client, string url) + { + var response = await client.GetAsync(url); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// Loads to obtain an antiforgery token, then posts the form to . + /// + private static async Task PostFormAsync(HttpClient client, string formPageUrl, string postUrl, Dictionary fields) + { + string html = await GetSuccessHtmlAsync(client, formPageUrl); + var match = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\""); + Assert.True(match.Success, $"No antiforgery token found on {formPageUrl}."); + + var form = new Dictionary(fields) { ["__RequestVerificationToken"] = match.Groups[1].Value }; + return await client.PostAsync(postUrl, new FormUrlEncodedContent(form)); + } + + private static void AssertRedirectsTo(string expectedPath, HttpResponseMessage response) + { + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal(expectedPath, response.Headers.Location!.OriginalString.Split('?')[0]); + } + + private async Task GetMemberIdAsync(IServiceProvider services, string userName) + { + var user = await services.GetRequiredService>().FindByNameAsync(userName); + return services.GetRequiredService().Members!.Single(m => m.UserId == user!.Id).Id; + } + + private async Task SeedDraftAsync(string userName, string content) + { + using var scope = _factory.Services.CreateScope(); + int memberId = await GetMemberIdAsync(scope.ServiceProvider, userName); + var result = await scope.ServiceProvider.GetRequiredService() + .CreateDraftAsync(memberId, new TestimonialDraftInput(content, "Demo User", null, null, null)); + Assert.True(result.IsSuccess); + return result.TestimonialId!.Value; + } + + private async Task SubmitAsync(string userName, int id) + { + using var scope = _factory.Services.CreateScope(); + int memberId = await GetMemberIdAsync(scope.ServiceProvider, userName); + Assert.True((await scope.ServiceProvider.GetRequiredService().SubmitAsync(memberId, id)).IsSuccess); + } + + /// + /// Stands in for the admin review queue (#1491) by applying a review transition directly. + /// + private async Task ReviewAsync(int id, Action review) + { + using var scope = _factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var testimonial = db.Testimonials.Single(t => t.Id == id); + review(testimonial, DateTimeOffset.UtcNow); + await db.SaveChangesAsync(); + } + + private async Task> ListAsync(string userName) + { + using var scope = _factory.Services.CreateScope(); + int memberId = await GetMemberIdAsync(scope.ServiceProvider, userName); + return await scope.ServiceProvider.GetRequiredService().ListForMemberAsync(memberId); + } + + private async Task GetAsync(string userName, int id) + { + using var scope = _factory.Services.CreateScope(); + int memberId = await GetMemberIdAsync(scope.ServiceProvider, userName); + return await scope.ServiceProvider.GetRequiredService().GetForMemberAsync(memberId, id); + } +} diff --git a/tests/DevBetterWeb.Modules.Testimonials.Tests/Application/TestimonialAuthoringTests.cs b/tests/DevBetterWeb.Modules.Testimonials.Tests/Application/TestimonialAuthoringTests.cs new file mode 100644 index 000000000..ed001d1c0 --- /dev/null +++ b/tests/DevBetterWeb.Modules.Testimonials.Tests/Application/TestimonialAuthoringTests.cs @@ -0,0 +1,292 @@ +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.Application; + +public class TestimonialAuthoringTests +{ + private const int MemberId = TestimonialBuilder.MemberId; + private const int OtherMemberId = 7; + + private readonly string _databaseName = Guid.NewGuid().ToString(); + private readonly FixedTimeProvider _time = new(new DateTimeOffset(2026, 11, 16, 9, 0, 0, TimeSpan.Zero)); + + private static TestimonialDraftInput ValidInput(string content = "devBetter helped me grow.") => + new(content, "Grace Hopper", "Rear Admiral", "US Navy", "https://example.com/grace.png"); + + private TestimonialsDbContext CreateContext() => + new(new DbContextOptionsBuilder().UseInMemoryDatabase(_databaseName).Options); + + private TestimonialAuthoring CreateSut(TestimonialsDbContext context) => new(context, _time); + + private async Task SeedAsync(Testimonial testimonial) + { + await using var context = CreateContext(); + context.Testimonials.Add(testimonial); + await context.SaveChangesAsync(); + return testimonial.Id; + } + + private async Task LoadAsync(int id) + { + await using var context = CreateContext(); + return await context.Testimonials.AsNoTracking().SingleOrDefaultAsync(t => t.Id == id); + } + + [Fact] + public async Task CreateDraftPersistsDraftForMember() + { + await using var context = CreateContext(); + + var result = await CreateSut(context).CreateDraftAsync(MemberId, ValidInput()); + + result.IsSuccess.ShouldBeTrue(); + var saved = (await LoadAsync(result.TestimonialId!.Value))!; + saved.MemberId.ShouldBe(MemberId); + saved.Status.ShouldBe(TestimonialStatus.Draft); + saved.Content.ShouldBe("devBetter helped me grow."); + saved.Author.DisplayName.ShouldBe("Grace Hopper"); + saved.Author.Title.ShouldBe("Rear Admiral"); + saved.Author.Organization.ShouldBe("US Navy"); + saved.Author.PhotoUrl.ShouldBe("https://example.com/grace.png"); + saved.CreatedAt.ShouldBe(_time.Now); + } + + [Theory] + [InlineData("", "Grace", null, nameof(TestimonialDraftInput.Content))] + [InlineData("Great", " ", null, nameof(TestimonialDraftInput.DisplayName))] + [InlineData("Great", "Grace", "http://example.com/a.png", nameof(TestimonialDraftInput.PhotoUrl))] + [InlineData("Great", "Grace", "javascript:alert(1)", nameof(TestimonialDraftInput.PhotoUrl))] + public async Task CreateDraftRejectsInvalidInputWithFieldErrors(string content, string displayName, string? photoUrl, string expectedField) + { + await using var context = CreateContext(); + + var result = await CreateSut(context).CreateDraftAsync(MemberId, new TestimonialDraftInput(content, displayName, null, null, photoUrl)); + + result.Status.ShouldBe(TestimonialOperationStatus.Invalid); + result.Errors.ShouldContain(e => e.Field == expectedField); + (await context.Testimonials.CountAsync()).ShouldBe(0); + } + + [Fact] + public async Task CreateDraftRejectsOverLongFields() + { + await using var context = CreateContext(); + var input = new TestimonialDraftInput( + new string('a', TestimonialLimits.MaxContentLength + 1), + new string('b', TestimonialLimits.MaxDisplayNameLength + 1), + new string('c', TestimonialLimits.MaxTitleLength + 1), + new string('d', TestimonialLimits.MaxOrganizationLength + 1), + "https://example.com/" + new string('e', TestimonialLimits.MaxPhotoUrlLength)); + + var result = await CreateSut(context).CreateDraftAsync(MemberId, input); + + result.Status.ShouldBe(TestimonialOperationStatus.Invalid); + result.Errors.Select(e => e.Field).ShouldBe( + [ + nameof(TestimonialDraftInput.Content), + nameof(TestimonialDraftInput.DisplayName), + nameof(TestimonialDraftInput.Title), + nameof(TestimonialDraftInput.Organization), + nameof(TestimonialDraftInput.PhotoUrl), + ], + ignoreOrder: true); + } + + [Theory] + [InlineData(TestimonialStatus.Draft)] + [InlineData(TestimonialStatus.ChangesRequested)] + public async Task UpdateEditsWhenEditable(TestimonialStatus status) + { + int id = await SeedAsync(TestimonialBuilder.InStatus(status)); + _time.Advance(TimeSpan.FromHours(1)); + await using var context = CreateContext(); + + var result = await CreateSut(context).UpdateAsync(MemberId, id, ValidInput("Edited text")); + + result.IsSuccess.ShouldBeTrue(); + var saved = (await LoadAsync(id))!; + saved.Content.ShouldBe("Edited text"); + saved.Author.DisplayName.ShouldBe("Grace Hopper"); + saved.Status.ShouldBe(status); + saved.UpdatedAt.ShouldBe(_time.Now); + } + + [Theory] + [InlineData(TestimonialStatus.PendingReview)] + [InlineData(TestimonialStatus.Accepted)] + [InlineData(TestimonialStatus.Declined)] + public async Task UpdateIsBlockedOnceSubmitted(TestimonialStatus status) + { + int id = await SeedAsync(TestimonialBuilder.InStatus(status)); + await using var context = CreateContext(); + + var result = await CreateSut(context).UpdateAsync(MemberId, id, ValidInput("Sneaky edit")); + + result.Status.ShouldBe(TestimonialOperationStatus.NotAllowed); + result.Errors.ShouldHaveSingleItem().Field.ShouldBeNull(); + (await LoadAsync(id))!.Content.ShouldBe(TestimonialBuilder.DefaultContent); + } + + [Fact] + public async Task UpdateChecksStatusBeforeValidatingInput() + { + int id = await SeedAsync(TestimonialBuilder.InStatus(TestimonialStatus.PendingReview)); + await using var context = CreateContext(); + + var result = await CreateSut(context).UpdateAsync(MemberId, id, new TestimonialDraftInput("", "", null, null, null)); + + result.Status.ShouldBe(TestimonialOperationStatus.NotAllowed); + } + + [Theory] + [InlineData(TestimonialStatus.Draft)] + [InlineData(TestimonialStatus.ChangesRequested)] + public async Task SubmitMovesToPendingReviewAndClearsFeedback(TestimonialStatus status) + { + int id = await SeedAsync(TestimonialBuilder.InStatus(status)); + await using var context = CreateContext(); + + var result = await CreateSut(context).SubmitAsync(MemberId, id); + + result.IsSuccess.ShouldBeTrue(); + var saved = (await LoadAsync(id))!; + saved.Status.ShouldBe(TestimonialStatus.PendingReview); + saved.ReviewerFeedback.ShouldBeNull(); + saved.SubmittedAt.ShouldBe(_time.Now); + } + + [Theory] + [InlineData(TestimonialStatus.PendingReview)] + [InlineData(TestimonialStatus.Accepted)] + [InlineData(TestimonialStatus.Declined)] + public async Task SubmitIsBlockedOnceSubmitted(TestimonialStatus status) + { + int id = await SeedAsync(TestimonialBuilder.InStatus(status)); + await using var context = CreateContext(); + + var result = await CreateSut(context).SubmitAsync(MemberId, id); + + result.Status.ShouldBe(TestimonialOperationStatus.NotAllowed); + (await LoadAsync(id))!.Status.ShouldBe(status); + } + + [Fact] + public async Task DeleteRemovesDraft() + { + int id = await SeedAsync(TestimonialBuilder.Draft()); + await using var context = CreateContext(); + + var result = await CreateSut(context).DeleteDraftAsync(MemberId, id); + + result.IsSuccess.ShouldBeTrue(); + (await LoadAsync(id)).ShouldBeNull(); + } + + [Theory] + [InlineData(TestimonialStatus.PendingReview)] + [InlineData(TestimonialStatus.ChangesRequested)] + [InlineData(TestimonialStatus.Accepted)] + [InlineData(TestimonialStatus.Declined)] + public async Task DeleteIsBlockedUnlessDraft(TestimonialStatus status) + { + int id = await SeedAsync(TestimonialBuilder.InStatus(status)); + await using var context = CreateContext(); + + var result = await CreateSut(context).DeleteDraftAsync(MemberId, id); + + result.Status.ShouldBe(TestimonialOperationStatus.NotAllowed); + (await LoadAsync(id)).ShouldNotBeNull(); + } + + [Fact] + public async Task OtherMembersTestimonialsAreNotFound() + { + int id = await SeedAsync(TestimonialBuilder.Draft(memberId: OtherMemberId)); + await using var context = CreateContext(); + var sut = CreateSut(context); + + (await sut.GetForMemberAsync(MemberId, id)).ShouldBeNull(); + (await sut.UpdateAsync(MemberId, id, ValidInput("Hijacked"))).Status.ShouldBe(TestimonialOperationStatus.NotFound); + (await sut.SubmitAsync(MemberId, id)).Status.ShouldBe(TestimonialOperationStatus.NotFound); + (await sut.DeleteDraftAsync(MemberId, id)).Status.ShouldBe(TestimonialOperationStatus.NotFound); + + var untouched = (await LoadAsync(id))!; + untouched.Content.ShouldBe(TestimonialBuilder.DefaultContent); + untouched.Status.ShouldBe(TestimonialStatus.Draft); + } + + [Fact] + public async Task ListReturnsOnlyTheMembersTestimonialsMostRecentlyUpdatedFirst() + { + var older = TestimonialBuilder.Draft(); + var newer = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview, TestimonialBuilder.Created.AddDays(5)); + await SeedAsync(older); + await SeedAsync(newer); + await SeedAsync(TestimonialBuilder.Draft(memberId: OtherMemberId)); + await using var context = CreateContext(); + + var results = await CreateSut(context).ListForMemberAsync(MemberId); + + results.Select(r => r.Id).ShouldBe([newer.Id, older.Id]); + } + + [Theory] + [InlineData(TestimonialStatus.ChangesRequested, "Please shorten it.")] + [InlineData(TestimonialStatus.Draft, null)] + public async Task GetExposesReviewerFeedbackAndPermissions(TestimonialStatus status, string? expectedFeedback) + { + int id = await SeedAsync(TestimonialBuilder.InStatus(status)); + await using var context = CreateContext(); + + var dto = (await CreateSut(context).GetForMemberAsync(MemberId, id))!; + + dto.Status.ShouldBe(status); + dto.ReviewerFeedback.ShouldBe(expectedFeedback); + dto.CanEdit.ShouldBeTrue(); + dto.CanSubmit.ShouldBeTrue(); + dto.CanDelete.ShouldBe(status == TestimonialStatus.Draft); + } + + [Fact] + public async Task GetShowsDeclineFeedbackToAuthor() + { + var declined = TestimonialBuilder.InStatus(TestimonialStatus.PendingReview); + declined.Decline(TestimonialBuilder.Created.AddDays(2), "Not a fit for the home page."); + int id = await SeedAsync(declined); + await using var context = CreateContext(); + + var dto = (await CreateSut(context).GetForMemberAsync(MemberId, id))!; + + dto.ReviewerFeedback.ShouldBe("Not a fit for the home page."); + dto.CanEdit.ShouldBeFalse(); + dto.CanDelete.ShouldBeFalse(); + } + + [Fact] + public void AddTestimonialsModuleResolvesAuthoring() + { + var services = new ServiceCollection(); + services.AddTestimonialsModule((_, options) => options.UseInMemoryDatabase(_databaseName)); + + using var provider = services.BuildServiceProvider(); + using var scope = provider.CreateScope(); + + scope.ServiceProvider.GetRequiredService().ShouldBeOfType(); + } + + private sealed class FixedTimeProvider(DateTimeOffset start) : TimeProvider + { + public DateTimeOffset Now { get; private set; } = start; + + public void Advance(TimeSpan by) => Now += by; + + public override DateTimeOffset GetUtcNow() => Now; + } +}