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
43 changes: 43 additions & 0 deletions .claude/plans/2026-11-02-issue-1422-admin-address-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Issue 1422: Admin User page address validation

https://github.com/DevBetterCom/DevBetterWeb/issues/1422

Status at start: #1469 (merged) fixed the blank `userId`, inline errors, and members with no address at all, but did not close the issue. Draft #1423 conflicts with main and is superseded: it removes `[Required]` from the model shared with the member profile page, whose handler would then build an `Address` from null values.

Remaining gaps against the issue's expected behavior:

- Address validation fires for any non-blank address, even if the admin did not touch it. A member with an incomplete stored address or a legacy `Member.Address` value cannot have only their name or email changed. The issue's payload (only `Address` missing) is this case.
- The page does not load the validation scripts, so no client-side validation fires.

Assumption: "updated" means differs from the stored value, ignoring surrounding whitespace and line-ending style. Blanking every address field skips validation and leaves an existing `ShippingAddress` and `Member.Address` untouched; with no `ShippingAddress` record, it clears the legacy `Member.Address`.

## Phase 1: Server

- [x] Load the member before validating in `OnPostUpdatePersonalInfoAsync`.
- [x] Skip address validation and updates when the address is unchanged.
- [x] Leave `UserPersonalUpdateModel` and the member profile page unchanged.

## Phase 2: Client

- [x] Load the validation scripts on the Admin User page.
- [x] Make the address `required` rules conditional, matching the server rule (`wwwroot/js/admin-user.js`).
- [x] Add `Subscription.StartDate` validation messages, since those forms now also validate on the client.

## Phase 3: Tests

- [x] `tests/DevBetterWeb.Tests/Pages/AdminUserModelTests/OnPostUpdatePersonalInfoAsync.cs`: unchanged incomplete address, legacy address, CRLF, edit to incomplete address, complete new address.
- [x] `tests/DevBetterWeb.Tests/Pages/UserPersonalUpdateModelTests/AddressFieldLengths.cs`: lengths enforced before the database rejects them.
- [x] Run the client rule in jsdom against the real jQuery Validation libraries, not committed (the repo has no JS test project, and Chrome cannot start in this environment for lack of system libraries).

## Phase 4: Review

- [x] Independent review by a separate agent; address significant findings.
- Fixed: blank State stored as null (reads back as a null `ShippingAddress`); blanking all fields half-cleared the address; over-length address values reached the database; whitespace-only values passed the client rule.
- Not addressed: an invalid stored Discord username also blocks a save, but it shows inline and is not address validation. The member profile page has the same null State bug; it is outside this issue, so it is reported instead of fixed here.
- Accepted: after a server redisplay, the client compares against the submitted values rather than the stored ones. The server still decides, so nothing invalid is saved.
- [ ] `/codex:review` required by CLAUDE.md: not run, because neither the plugin nor the `codex` CLI is installed in this environment.

## Phase 5: Verification

- [x] Build and all tests pass (`NuGetAudit=false`; main fails restore locally on NU1902 for the pinned ImageSharp).
- [ ] `dotnet BuildTestFormat.cs` does not run clean: build and tests pass, but the format step fails across the repo, including untouched files. On the changed files it reports only line-ending, indentation and encoding differences (`.editorconfig` asks for CRLF, BOM and other indentation; these files are LF in git). They were left in the existing style to keep the diff reviewable.
6 changes: 5 additions & 1 deletion src/DevBetterWeb.Web/Pages/Admin/User.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@

<div class="row" style="margin-top: 20px;">
<div class="col-12">
<form asp-page-handler="UpdatePersonalInfo">
<form asp-page-handler="UpdatePersonalInfo" id="personalInfoForm">
<input type="hidden" name="userId" value="@Model.UserId" />
<div class="card">
<div class="card-header">
Expand Down Expand Up @@ -471,6 +471,7 @@
<div class="form-group">
<label asp-for="Subscription.StartDate">Start Date</label>
<input asp-for="Subscription.StartDate" type="date" value="@DateTime.Today.ToString("yyyy-MM-dd")" class="form-control" />
<span asp-validation-for="Subscription.StartDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Subscription.EndDate">End Date</label>
Expand Down Expand Up @@ -550,6 +551,7 @@
<div class="form-group">
<label asp-for="Subscription.StartDate">Start Date</label>
<input asp-for="Subscription.StartDate" type="date" id="inputEditSubscriptionStartDate" class="form-control" data-clear-button="true" />
<span asp-validation-for="Subscription.StartDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Subscription.EndDate">End Date</label>
Expand Down Expand Up @@ -593,4 +595,6 @@

@section scripts{
<script src="~/js/admin.js" asp-append-version="true"></script>
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/js/admin-user.js" asp-append-version="true"></script>
}
45 changes: 31 additions & 14 deletions src/DevBetterWeb.Web/Pages/Admin/User.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,10 +279,19 @@ public async Task<IActionResult> OnPostUpdateEmailConfirmationAsync(string userI

public async Task<IActionResult> OnPostUpdatePersonalInfoAsync(string userId)
{
// Admins often edit members who have not entered a shipping address yet, so the address
// fields are only required once any of them is filled in.
var spec = new MemberByUserIdSpec(userId);
var member = await _memberRepository.FirstOrDefaultAsync(spec);
if (member is null)
{
ModelState.AddModelError(string.Empty, $"No member record exists for user {userId}.");
return await RedisplayPersonalInfoFormAsync(userId);
}

// Admins often edit members whose stored address is missing or incomplete, so the address
// fields are only required when the admin changes the address to something non-blank.
bool hasShippingAddress = HasAnyShippingAddressField(UserPersonalUpdateModel);
if (!hasShippingAddress)
bool shippingAddressChanged = HasShippingAddressChanged(UserPersonalUpdateModel, new UserPersonalUpdateModel(member));
if (!hasShippingAddress || !shippingAddressChanged)
{
foreach (var field in ShippingAddressFields)
{
Expand All @@ -295,21 +304,18 @@ public async Task<IActionResult> OnPostUpdatePersonalInfoAsync(string userId)
return await RedisplayPersonalInfoFormAsync(userId);
}

var spec = new MemberByUserIdSpec(userId);
var member = await _memberRepository.FirstOrDefaultAsync(spec);
if (member is null)
{
ModelState.AddModelError(string.Empty, $"No member record exists for user {userId}.");
return await RedisplayPersonalInfoFormAsync(userId);
}

member.UpdateName(UserPersonalUpdateModel.FirstName, UserPersonalUpdateModel.LastName, false);
member.UpdatePEInfo(UserPersonalUpdateModel.PEFriendCode, UserPersonalUpdateModel.PEUsername, false);
member.UpdateAboutInfo(UserPersonalUpdateModel.AboutInfo, false);
member.UpdateAddress(UserPersonalUpdateModel.Address, false);
if (hasShippingAddress)
if (shippingAddressChanged && hasShippingAddress)
{
member.UpdateAddress(UserPersonalUpdateModel.Address, false);
// A null State would make EF read the whole owned ShippingAddress back as null.
member.UpdateShippingAddress(UserPersonalUpdateModel.Address!, UserPersonalUpdateModel.City!, UserPersonalUpdateModel.State ?? string.Empty, UserPersonalUpdateModel.PostalCode!, UserPersonalUpdateModel.Country!, false);
}
else if (shippingAddressChanged && member.ShippingAddress is null)
{
member.UpdateShippingAddress(UserPersonalUpdateModel.Address!, UserPersonalUpdateModel.City!, UserPersonalUpdateModel.State!, UserPersonalUpdateModel.PostalCode!, UserPersonalUpdateModel.Country!, false);
member.UpdateAddress(null, false);
}
member.UpdateDiscord(UserPersonalUpdateModel.DiscordUsername, false);
member.UpdateEmail(UserPersonalUpdateModel.Email, false);
Expand Down Expand Up @@ -342,6 +348,17 @@ private static bool HasAnyShippingAddressField(UserPersonalUpdateModel model) =>
!string.IsNullOrWhiteSpace(model.Country) ||
!string.IsNullOrWhiteSpace(model.PostalCode);

private static bool HasShippingAddressChanged(UserPersonalUpdateModel submitted, UserPersonalUpdateModel stored) =>
NormalizeAddressField(submitted.Address) != NormalizeAddressField(stored.Address) ||
NormalizeAddressField(submitted.City) != NormalizeAddressField(stored.City) ||
NormalizeAddressField(submitted.State) != NormalizeAddressField(stored.State) ||
NormalizeAddressField(submitted.Country) != NormalizeAddressField(stored.Country) ||
NormalizeAddressField(submitted.PostalCode) != NormalizeAddressField(stored.PostalCode);

// Browsers post textarea line breaks as CRLF, which must not count as an edit to a stored address.
private static string NormalizeAddressField(string? value) =>
(value ?? string.Empty).ReplaceLineEndings("\n").Trim();

// Reloads the page data but keeps the admin's submitted values so validation errors show next to the fields.
private async Task<IActionResult> RedisplayPersonalInfoFormAsync(string userId)
{
Expand Down
6 changes: 6 additions & 0 deletions src/DevBetterWeb.Web/Pages/User/UserPersonalUpdateModel.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.Metrics;
using DevBetterWeb.Core.Entities;
using DevBetterWeb.Infrastructure.Data.Config;

namespace DevBetterWeb.Web.Pages.User;

Expand All @@ -12,13 +13,18 @@ public class UserPersonalUpdateModel
[Required]
public string? LastName { get; set; }
[Required]
[StringLength(500)]
public string? Address { get; set; }
[Required]
[StringLength(DataConfigConstants.NAME_COLUMN_WIDTH)]
public string? City { get; set; }
[StringLength(DataConfigConstants.NAME_COLUMN_WIDTH)]
public string? State { get; set; }
[Required]
[StringLength(DataConfigConstants.NAME_COLUMN_WIDTH)]
public string? Country { get; set; }
[Required]
[StringLength(12)]
public string? PostalCode { get; set; }
[Range(1, 31)]
[BirthdayDay]
Expand Down
28 changes: 28 additions & 0 deletions src/DevBetterWeb.Web/wwwroot/js/admin-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
$(function () {
var form = $('#personalInfoForm');
var addressFields = form.find('[name="UserPersonalUpdateModel.Address"], [name="UserPersonalUpdateModel.City"], [name="UserPersonalUpdateModel.State"], [name="UserPersonalUpdateModel.Country"], [name="UserPersonalUpdateModel.PostalCode"]');

function normalize(value) {
return (value || '').replace(/\r\n/g, '\n').trim();
}

// Matches OnPostUpdatePersonalInfoAsync: the address is only required when the admin changes it to something non-blank.
function isAddressRequired() {
var fields = addressFields.toArray();
var hasValue = fields.some(function (field) { return normalize(field.value) !== ''; });
var isChanged = fields.some(function (field) { return normalize(field.value) !== normalize(field.defaultValue); });
return hasValue && isChanged;
}

addressFields.filter('[data-val-required]').each(function () {
$(this).rules('remove', 'required');
$(this).rules('add', { required: { depends: isAddressRequired }, normalizer: normalize });
});

// Filling in or clearing one address field can resolve errors already shown on the others.
addressFields.on('change', function () {
addressFields.filter('.input-validation-error').each(function () {
$(this).valid();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,160 @@ public async Task RedisplaysFormWithSubmittedValuesGivenPartialShippingAddress()
await _memberRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, default);
}

[Fact]
public async Task SavesNameGivenUnchangedIncompleteStoredShippingAddress()
{
_member.UpdateShippingAddress("", "Vavuniya", "", "43000", "Sri Lanka", false);
_pageModel.UserPersonalUpdateModel = new UserPersonalUpdateModel
{
FirstName = "Kajan",
LastName = "Smith",
City = "Vavuniya",
PostalCode = "43000",
Country = "Sri Lanka"
};
_pageModel.ModelState.AddModelError("UserPersonalUpdateModel.Address", "The Address field is required.");

var result = await _pageModel.OnPostUpdatePersonalInfoAsync(UserId);

Assert.IsType<RedirectToPageResult>(result);
Assert.Equal("Kajan", _member.FirstName);
Assert.Equal("", _member.ShippingAddress!.State);
await _memberRepository.Received(1).UpdateAsync(_member, Arg.Any<CancellationToken>());
}

[Fact]
public async Task SavesNameAndKeepsLegacyAddressGivenNoShippingAddressRecord()
{
_member.UpdateAddress("1 Main St, Springfield", false);
_pageModel.UserPersonalUpdateModel = new UserPersonalUpdateModel
{
FirstName = "Kajan",
LastName = "Smith",
Address = "1 Main St, Springfield"
};
GivenBindingErrorsForEmptyAddressFields();

var result = await _pageModel.OnPostUpdatePersonalInfoAsync(UserId);

Assert.IsType<RedirectToPageResult>(result);
Assert.Equal("1 Main St, Springfield", _member.Address);
Assert.Null(_member.ShippingAddress);
}

[Fact]
public async Task TreatsLineEndingDifferenceAsUnchangedShippingAddress()
{
_member.UpdateShippingAddress("1 Main St\nApt 2", "Springfield", "IL", "12345", "US", false);
_pageModel.UserPersonalUpdateModel = new UserPersonalUpdateModel
{
FirstName = "Kajan",
LastName = "Smith",
Address = "1 Main St\r\nApt 2",
City = "Springfield",
State = "IL",
PostalCode = "12345",
Country = "US"
};

var result = await _pageModel.OnPostUpdatePersonalInfoAsync(UserId);

Assert.IsType<RedirectToPageResult>(result);
Assert.Equal("1 Main St\nApt 2", _member.ShippingAddress!.Street);
}

[Fact]
public async Task RedisplaysFormGivenEditToIncompleteStoredShippingAddress()
{
_member.UpdateShippingAddress("", "Vavuniya", "", "43000", "Sri Lanka", false);
_pageModel.UserPersonalUpdateModel = new UserPersonalUpdateModel
{
FirstName = "Kajan",
LastName = "Smith",
City = "Colombo",
PostalCode = "43000",
Country = "Sri Lanka"
};
_pageModel.ModelState.AddModelError("UserPersonalUpdateModel.Address", "The Address field is required.");

var result = await _pageModel.OnPostUpdatePersonalInfoAsync(UserId);

Assert.IsType<PageResult>(result);
Assert.False(_pageModel.ModelState.IsValid);
Assert.Equal("Vavuniya", _member.ShippingAddress!.City);
await _memberRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, default);
}

[Fact]
public async Task SavesShippingAddressGivenCompleteNewAddress()
{
_pageModel.UserPersonalUpdateModel = new UserPersonalUpdateModel
{
FirstName = "Kajan",
LastName = "Smith",
Address = "1 Main St",
City = "Springfield",
State = "IL",
PostalCode = "12345",
Country = "US"
};

var result = await _pageModel.OnPostUpdatePersonalInfoAsync(UserId);

Assert.IsType<RedirectToPageResult>(result);
Assert.Equal("1 Main St", _member.ShippingAddress!.Street);
Assert.Equal("1 Main St", _member.Address);
}

[Fact]
public async Task StoresBlankStateAsEmptyStringGivenEditedShippingAddress()
{
_member.UpdateShippingAddress("1 Main St", "Springfield", "IL", "12345", "US", false);
_pageModel.UserPersonalUpdateModel = new UserPersonalUpdateModel
{
FirstName = "Kajan",
LastName = "Smith",
Address = "2 Main St",
City = "Springfield",
PostalCode = "12345",
Country = "US"
};

var result = await _pageModel.OnPostUpdatePersonalInfoAsync(UserId);

Assert.IsType<RedirectToPageResult>(result);
Assert.Equal("2 Main St", _member.ShippingAddress!.Street);
Assert.Equal("", _member.ShippingAddress.State);
}

[Fact]
public async Task LeavesAddressesUntouchedGivenAllFieldsBlankedOnExistingShippingAddress()
{
_member.UpdateAddress("1 Main St", false);
_member.UpdateShippingAddress("1 Main St", "Springfield", "IL", "12345", "US", false);
_pageModel.UserPersonalUpdateModel = new UserPersonalUpdateModel { FirstName = "Kajan", LastName = "Smith" };
GivenBindingErrorsForEmptyAddressFields();

var result = await _pageModel.OnPostUpdatePersonalInfoAsync(UserId);

Assert.IsType<RedirectToPageResult>(result);
Assert.Equal("1 Main St", _member.Address);
Assert.Equal("1 Main St", _member.ShippingAddress!.Street);
}

[Fact]
public async Task ClearsLegacyAddressGivenBlankedAndNoShippingAddressRecord()
{
_member.UpdateAddress("1 Main St", false);
_pageModel.UserPersonalUpdateModel = new UserPersonalUpdateModel { FirstName = "Kajan", LastName = "Smith" };
GivenBindingErrorsForEmptyAddressFields();

var result = await _pageModel.OnPostUpdatePersonalInfoAsync(UserId);

Assert.IsType<RedirectToPageResult>(result);
Assert.Null(_member.Address);
}

[Fact]
public async Task RedisplaysFormInsteadOfBadRequestGivenMissingLastName()
{
Expand Down
Loading
Loading