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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace DevBetterWeb.Modules.Testimonials.Contracts;

/// <summary>
/// Member-facing use cases for writing testimonials. Every call is scoped to <c>memberId</c>:
/// a testimonial owned by another member is reported as not found.
/// The caller is responsible for passing the signed-in member's id.
/// </summary>
public interface ITestimonialAuthoring
{
/// <summary>Returns the member's testimonials, most recently updated first.</summary>
Task<IReadOnlyList<MemberTestimonialDto>> ListForMemberAsync(int memberId, CancellationToken cancellationToken = default);

/// <summary>Returns the member's testimonial, or null if it does not exist or belongs to someone else.</summary>
Task<MemberTestimonialDto?> GetForMemberAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default);

Task<TestimonialOperationResult> CreateDraftAsync(int memberId, TestimonialDraftInput input, CancellationToken cancellationToken = default);

/// <summary>Edits a testimonial in Draft or ChangesRequested.</summary>
Task<TestimonialOperationResult> UpdateAsync(int memberId, int testimonialId, TestimonialDraftInput input, CancellationToken cancellationToken = default);

/// <summary>Submits (or resubmits) a testimonial for admin review.</summary>
Task<TestimonialOperationResult> SubmitAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default);

/// <summary>Deletes a testimonial that is still a Draft.</summary>
Task<TestimonialOperationResult> DeleteDraftAsync(int memberId, int testimonialId, CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace DevBetterWeb.Modules.Testimonials.Contracts;

/// <summary>
/// A testimonial as seen by its author, including review status and feedback.
/// </summary>
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;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace DevBetterWeb.Modules.Testimonials.Contracts;

/// <summary>
/// What a member enters when writing or editing a testimonial.
/// </summary>
/// <param name="PhotoUrl">Optional absolute https URL; null or blank falls back to the member's avatar.</param>
public sealed record TestimonialDraftInput(
string Content,
string DisplayName,
string? Title,
string? Organization,
string? PhotoUrl);
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace DevBetterWeb.Modules.Testimonials.Contracts;

/// <summary>
/// Field limits for testimonials, shared with callers so their forms can validate up front.
/// </summary>
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;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
namespace DevBetterWeb.Modules.Testimonials.Contracts;

public enum TestimonialOperationStatus
{
Success = 0,

/// <summary>The testimonial does not exist or belongs to another member.</summary>
NotFound = 1,

/// <summary>The operation is not allowed in the testimonial's current status, or it changed concurrently.</summary>
NotAllowed = 2,

/// <summary>The input failed validation; see <see cref="TestimonialOperationResult.Errors"/>.</summary>
Invalid = 3,
}

/// <param name="Field">The <see cref="TestimonialDraftInput"/> property name, or null for a general error.</param>
public sealed record TestimonialValidationError(string? Field, string Message);

/// <summary>
/// Outcome of an authoring command. Contracts stay dependency-free, so this is a small local result type.
/// </summary>
public sealed record TestimonialOperationResult
{
private TestimonialOperationResult(TestimonialOperationStatus status, int? testimonialId, IReadOnlyList<TestimonialValidationError> errors)
{
Status = status;
TestimonialId = testimonialId;
Errors = errors;
}

public TestimonialOperationStatus Status { get; }

/// <summary>The affected testimonial's id when the operation succeeded.</summary>
public int? TestimonialId { get; }

public IReadOnlyList<TestimonialValidationError> 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<TestimonialValidationError> errors) =>
new(TestimonialOperationStatus.Invalid, null, errors);
}
Original file line number Diff line number Diff line change
@@ -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<IReadOnlyList<MemberTestimonialDto>> 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<MemberTestimonialDto?> 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<TestimonialOperationResult> 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<TestimonialOperationResult> 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<TestimonialOperationResult> 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<TestimonialOperationResult> 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<Testimonial?> FindOwnedAsync(int memberId, int testimonialId, CancellationToken cancellationToken) =>
_dbContext.Testimonials.SingleOrDefaultAsync(t => t.Id == testimonialId && t.MemberId == memberId, cancellationToken);

private async Task<TestimonialOperationResult> ApplyAsync(Testimonial testimonial, Action<Testimonial> 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<Func<Testimonial, MemberTestimonialDto>> 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);
}
Loading
Loading