mirror of
https://github.com/Sea-Haven-Industries/shoc-backend.git
synced 2026-10-06 17:02:12 +00:00
Compare commits
17 commits
c8073123e3
...
77e54e64e3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77e54e64e3 | ||
|
|
a8d05776a8 | ||
|
|
5353899418 | ||
|
|
9091335ff2 | ||
|
|
e9a1d8f53f | ||
|
|
0088cffd47 | ||
|
|
236199ab7a | ||
|
|
85b7d1e1c7 | ||
|
|
1c8da7f344 | ||
|
|
227691269d | ||
|
|
27c21ec32e | ||
|
|
6bfb56f349 | ||
|
|
13fec977fa | ||
|
|
92dabbfbe3 | ||
|
|
60b1afd8e0 | ||
|
|
c3865e56ac | ||
|
|
66a49ab957 |
58 changed files with 6316 additions and 392 deletions
|
|
@ -117,11 +117,11 @@ public class AuthenticationControllerTests
|
|||
{
|
||||
var service = new Mock<IAuthenticationService>();
|
||||
service.Setup(s => s.ChangePasswordAsync("42", "old", "new", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(true);
|
||||
.ReturnsAsync(new ChangePasswordResultDTO { Status = ChangePasswordStatus.Succeeded });
|
||||
|
||||
var controller = NewController(service, "42");
|
||||
|
||||
var result = await controller.ChangePassword(new ChangePasswords { Currentpassword = "old", Confirmpassword = "new" }, CancellationToken.None);
|
||||
var result = await controller.ChangePassword(new ChangePasswords { Currentpassword = "old", Newpassword = "new", Confirmpassword = "new" }, CancellationToken.None);
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
var response = ok.Value.Should().BeOfType<Response>().Subject;
|
||||
|
|
@ -130,11 +130,11 @@ public class AuthenticationControllerTests
|
|||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_Failure_ReturnsOldPasswordIncorrectStatus()
|
||||
public async Task ChangePassword_WrongCurrentPassword_ReturnsOldPasswordIncorrectStatus()
|
||||
{
|
||||
var service = new Mock<IAuthenticationService>();
|
||||
service.Setup(s => s.ChangePasswordAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(false);
|
||||
.ReturnsAsync(new ChangePasswordResultDTO { Status = ChangePasswordStatus.CurrentPasswordIncorrect });
|
||||
|
||||
var controller = NewController(service, "42");
|
||||
|
||||
|
|
@ -143,6 +143,70 @@ public class AuthenticationControllerTests
|
|||
var bad = result.Should().BeOfType<BadRequestObjectResult>().Subject;
|
||||
var response = bad.Value.Should().BeOfType<Response>().Subject;
|
||||
response.Status.Should().Be("Old Password is incorrect");
|
||||
response.Message.Should().Be("Current password is incorrect");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_PolicyRejection_ReturnsPasswordRequirementsMessage()
|
||||
{
|
||||
var service = new Mock<IAuthenticationService>();
|
||||
service.Setup(s => s.ChangePasswordAsync("42", "Current1!", "weak", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new ChangePasswordResultDTO { Status = ChangePasswordStatus.PasswordRejected });
|
||||
|
||||
var controller = NewController(service, "42");
|
||||
|
||||
var result = await controller.ChangePassword(
|
||||
new ChangePasswords { Currentpassword = "Current1!", Newpassword = "weak", Confirmpassword = "weak" },
|
||||
CancellationToken.None);
|
||||
|
||||
var bad = result.Should().BeOfType<BadRequestObjectResult>().Subject;
|
||||
var response = bad.Value.Should().BeOfType<Response>().Subject;
|
||||
response.Status.Should().Be("Password does not meet requirements");
|
||||
response.Message.Should().Be(
|
||||
"Password must be at least 6 characters and include one uppercase letter, one number, and one special character.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_ConfirmationMismatch_IsRejectedWithoutChangingThePassword()
|
||||
{
|
||||
var service = new Mock<IAuthenticationService>();
|
||||
var controller = NewController(service, "42");
|
||||
|
||||
var result = await controller.ChangePassword(
|
||||
new ChangePasswords { Currentpassword = "Current1!", Newpassword = "Next2@x", Confirmpassword = "Next2@y" },
|
||||
CancellationToken.None);
|
||||
|
||||
var bad = result.Should().BeOfType<BadRequestObjectResult>().Subject;
|
||||
bad.Value.Should().BeOfType<Response>().Subject.Message.Should().Be("Passwords don't match");
|
||||
service.Verify(
|
||||
s => s.ChangePasswordAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_NonPolicyFailure_ReturnsTheGenericMessage()
|
||||
{
|
||||
var service = new Mock<IAuthenticationService>();
|
||||
service.Setup(s => s.ChangePasswordAsync("42", "Current1!", "Next2@x", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new ChangePasswordResultDTO { Status = ChangePasswordStatus.Failed });
|
||||
var controller = NewController(service, "42");
|
||||
|
||||
var result = await controller.ChangePassword(
|
||||
new ChangePasswords { Currentpassword = "Current1!", Newpassword = "Next2@x", Confirmpassword = "Next2@x" },
|
||||
CancellationToken.None);
|
||||
|
||||
var response = result.Should().BeOfType<BadRequestObjectResult>().Subject.Value.Should().BeOfType<Response>().Subject;
|
||||
response.Message.Should().Be("Your password could not be changed. Try again.");
|
||||
response.Message.Should().NotContain("at least 6 characters");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangePassword_RequiresAuthenticatedCaller()
|
||||
{
|
||||
var method = typeof(AuthenticationController).GetMethod(nameof(AuthenticationController.ChangePassword))!;
|
||||
|
||||
method.GetCustomAttributes(typeof(Microsoft.AspNetCore.Authorization.AuthorizeAttribute), inherit: true)
|
||||
.Should().NotBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ public class CalendarServiceTests
|
|||
StartDate = startDate,
|
||||
EndDate = startDate,
|
||||
IsDeleted = isDeleted,
|
||||
CreatedDate = DateTime.Now
|
||||
CreatedDate = DateTime.UtcNow
|
||||
};
|
||||
ctx.Events.Add(ev);
|
||||
ctx.SaveChanges();
|
||||
|
|
@ -64,6 +64,7 @@ public class CalendarServiceTests
|
|||
saved.Title.Should().Be("Standup");
|
||||
saved.IsDeleted.Should().Be(false);
|
||||
saved.CreatedDate.Should().NotBeNull();
|
||||
saved.CreatedDate!.Value.Kind.Should().Be(DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -97,6 +98,7 @@ public class CalendarServiceTests
|
|||
var updated = ctx.Events.Single();
|
||||
updated.Title.Should().Be("New");
|
||||
updated.LastModificationTime.Should().NotBeNull();
|
||||
updated.LastModificationTime!.Value.Kind.Should().Be(DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -134,6 +136,7 @@ public class CalendarServiceTests
|
|||
var row = ctx.Events.Single();
|
||||
row.IsDeleted.Should().Be(true);
|
||||
row.DeletionTime.Should().NotBeNull();
|
||||
row.DeletionTime!.Value.Kind.Should().Be(DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
|
|
@ -31,7 +31,9 @@ public class LocationControllerSitesTests
|
|||
dataService,
|
||||
new AccountDataService(ctx),
|
||||
Mock.Of<ICreateLocationValidation>(),
|
||||
Mock.Of<IUpdateLocationValidation>());
|
||||
Mock.Of<IUpdateLocationValidation>(),
|
||||
Mock.Of<SeaHaven.DataServices.Interfaces.ITeamPermissionOverrideDataService>(),
|
||||
new SeaHaven.Services.Implementation.TeamPermissionPolicy());
|
||||
|
||||
var controller = new LocationController(service, Mock.Of<ILogger<LocationController>>())
|
||||
{
|
||||
|
|
|
|||
|
|
@ -286,4 +286,80 @@ public class LocationControllerTests
|
|||
contacts[0].GetProperty("Name").GetString().Should().Be("Cara Lane");
|
||||
contacts[1].GetProperty("Name").GetString().Should().Be("Alan Ford");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLocation_DuplicateSiteCode_Returns409WithStableCode()
|
||||
{
|
||||
var service = new Mock<ILocationService>();
|
||||
service.Setup(s => s.CreateLocationFromRequestAsync(It.IsAny<LocationCreateRequestDTO>(), It.IsAny<ClaimsPrincipal>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new SeaHaven.Services.Exceptions.SiteCodeConflictException());
|
||||
|
||||
var result = await NewController(service).AddLocation(new Location_DTO { Name = "BK5" }, CancellationToken.None);
|
||||
|
||||
var conflict = result.Should().BeOfType<ConflictObjectResult>().Subject;
|
||||
Prop(conflict.Value!, "Code").Should().Be("DuplicateSiteCode");
|
||||
Prop(conflict.Value!, "Message").Should().Be("This site code already exists.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditLocation_DuplicateSiteCode_Returns409()
|
||||
{
|
||||
var service = new Mock<ILocationService>();
|
||||
service.Setup(s => s.UpdateLocationFromRequestAsync(4, It.IsAny<LocationUpdateRequestDTO>(), It.IsAny<ClaimsPrincipal>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new SeaHaven.Services.Exceptions.SiteCodeConflictException());
|
||||
|
||||
var result = await NewController(service).EditLocation(4, new EditLocation_DTO { Name = "BK5" }, CancellationToken.None);
|
||||
|
||||
result.Should().BeOfType<ConflictObjectResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteLocation_WithoutPermission_Returns403WithDeleteMessage()
|
||||
{
|
||||
var service = new Mock<ILocationService>();
|
||||
service.Setup(s => s.DeleteLocationByIdAsync(4, It.IsAny<ClaimsPrincipal>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new SeaHaven.Services.Exceptions.SiteForbiddenException(
|
||||
SeaHaven.Services.Exceptions.SiteForbiddenException.DeleteDeniedMessage));
|
||||
|
||||
var result = await NewController(service).DeleteLocation(4, CancellationToken.None);
|
||||
|
||||
var forbidden = result.Should().BeOfType<ObjectResult>().Subject;
|
||||
forbidden.StatusCode.Should().Be(403);
|
||||
forbidden.Value.Should().BeOfType<Response>().Which.Message.Should().Be("You are not allowed to delete sites.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOpenWorkOrders_ReturnsCountAndIds_Or404()
|
||||
{
|
||||
var service = new Mock<ILocationService>();
|
||||
service.Setup(s => s.GetOpenWorkOrdersAsync(4, It.IsAny<ClaimsPrincipal>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new SiteOpenWorkOrdersDTO { Count = 2, WorkOrderIds = new[] { 11, 12 } });
|
||||
|
||||
var ok = (await NewController(service).GetOpenWorkOrders(4, CancellationToken.None))
|
||||
.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new SiteOpenWorkOrdersDTO { Count = 2, WorkOrderIds = new[] { 11, 12 } });
|
||||
|
||||
(await NewController(service).GetOpenWorkOrders(5, CancellationToken.None))
|
||||
.Should().BeOfType<NotFoundObjectResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSiteContactInfo_MapsContactsAndNotesToTheService()
|
||||
{
|
||||
var service = new Mock<ILocationService>();
|
||||
SiteContactInfoRequestDTO? seen = null;
|
||||
service.Setup(s => s.UpdateSiteContactInfoAsync(4, It.IsAny<SiteContactInfoRequestDTO>(), It.IsAny<ClaimsPrincipal>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<int, SiteContactInfoRequestDTO, ClaimsPrincipal, CancellationToken>((_, request, _, _) => seen = request)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var result = await NewController(service).UpdateSiteContactInfo(4, new SiteContactInfoInput_DTO
|
||||
{
|
||||
Contacts = new List<SiteContactInput_DTO> { new() { Id = 7, Name = "Main", Phone = "555-0100" } },
|
||||
Notes = "Gate 4"
|
||||
}, CancellationToken.None);
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>();
|
||||
seen!.Notes.Should().Be("Gate 4");
|
||||
seen.Contacts.Should().ContainSingle().Which.Should().BeEquivalentTo(new SiteContactRequestDTO { Id = 7, Name = "Main", Phone = "555-0100" });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,27 @@ namespace Api.SeaHavenIndustries.Tests;
|
|||
|
||||
public class LocationServiceTests
|
||||
{
|
||||
/// <summary>Fills the fields a new site must carry (client, address, one contact) unless the test set them.</summary>
|
||||
private static LocationCreateRequestDTO WithSiteFields(ApplicationDbContext ctx, LocationCreateRequestDTO request)
|
||||
{
|
||||
if (request.AccountId == null)
|
||||
{
|
||||
if (!ctx.Accounts.Any(a => a.Id == 7))
|
||||
{
|
||||
ctx.Accounts.Add(new Accounts { Id = 7, Name = "Customer", IsDeleted = false });
|
||||
ctx.SaveChanges();
|
||||
}
|
||||
|
||||
request.AccountId = 7;
|
||||
}
|
||||
|
||||
request.Address ??= "1 Depot Rd";
|
||||
request.City ??= "Dallas";
|
||||
request.State ??= "TX";
|
||||
request.Contacts ??= new List<SiteContactRequestDTO> { new() { Name = "Main", Phone = "555-0100" } };
|
||||
return request;
|
||||
}
|
||||
|
||||
private static ApplicationDbContext NewContext()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
|
|
@ -28,7 +49,9 @@ public class LocationServiceTests
|
|||
new LocationDataService(ctx),
|
||||
new AccountDataService(ctx),
|
||||
new CreateLocationValidation(),
|
||||
new UpdateLocationValidation());
|
||||
new UpdateLocationValidation(),
|
||||
Mock.Of<SeaHaven.DataServices.Interfaces.ITeamPermissionOverrideDataService>(),
|
||||
new SeaHaven.Services.Implementation.TeamPermissionPolicy());
|
||||
|
||||
private static void SeedAccount(ApplicationDbContext ctx, int id, string name = "Customer")
|
||||
{
|
||||
|
|
@ -83,7 +106,7 @@ public class LocationServiceTests
|
|||
SeedAccount(ctx, 9);
|
||||
var service = NewService(ctx);
|
||||
|
||||
await service.CreateLocationFromRequestAsync(new LocationCreateRequestDTO
|
||||
await service.CreateLocationFromRequestAsync(WithSiteFields(ctx, new LocationCreateRequestDTO
|
||||
{
|
||||
Name = "Warehouse",
|
||||
Title = "Main WH",
|
||||
|
|
@ -95,7 +118,7 @@ public class LocationServiceTests
|
|||
ContactEmail = "wh@example.com",
|
||||
Status = "Active",
|
||||
AccountId = 9
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
}), OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
var entity = ctx.Locations.Single();
|
||||
entity.Name.Should().Be("Warehouse");
|
||||
|
|
@ -211,7 +234,9 @@ public class LocationServiceTests
|
|||
dataService,
|
||||
Mock.Of<IAccountDataService>(),
|
||||
new CreateLocationValidation(),
|
||||
new UpdateLocationValidation());
|
||||
new UpdateLocationValidation(),
|
||||
Mock.Of<SeaHaven.DataServices.Interfaces.ITeamPermissionOverrideDataService>(),
|
||||
new SeaHaven.Services.Implementation.TeamPermissionPolicy());
|
||||
|
||||
[Fact]
|
||||
public async Task GetLocationDetailAsync_ReturnsMappedDtoOrNull()
|
||||
|
|
@ -237,14 +262,14 @@ public class LocationServiceTests
|
|||
|
||||
await NewService(ctx).UpdateLocationFromRequestAsync(existing.Id, new LocationUpdateRequestDTO
|
||||
{
|
||||
Name = "New",
|
||||
Name = "Old",
|
||||
Address = "9 New St",
|
||||
City = "Plano",
|
||||
Status = "Inactive"
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
var row = ctx.Locations.Single();
|
||||
row.Name.Should().Be("New");
|
||||
row.Name.Should().Be("Old", "the site code is immutable");
|
||||
row.Address1.Should().Be("9 New St");
|
||||
row.City.Should().Be("Plano");
|
||||
row.Status.Should().Be("Inactive");
|
||||
|
|
@ -263,7 +288,7 @@ public class LocationServiceTests
|
|||
|
||||
await NewService(ctx).UpdateLocationFromRequestAsync(existing.Id, new LocationUpdateRequestDTO
|
||||
{
|
||||
Name = "New",
|
||||
Name = "Old",
|
||||
City = "Plano"
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
|
|
@ -301,12 +326,12 @@ public class LocationServiceTests
|
|||
|
||||
await NewService(ctx).UpdateLocationFromRequestAsync(
|
||||
existing.Id,
|
||||
new LocationUpdateRequestDTO { Name = "Renamed", City = "Austin" },
|
||||
new LocationUpdateRequestDTO { Name = "Owned", City = "Austin" },
|
||||
AccountUser(4),
|
||||
CancellationToken.None);
|
||||
|
||||
var row = ctx.Locations.Single();
|
||||
row.Name.Should().Be("Renamed");
|
||||
row.Name.Should().Be("Owned");
|
||||
row.City.Should().Be("Austin");
|
||||
row.AccountId.Should().Be(4);
|
||||
}
|
||||
|
|
@ -386,7 +411,7 @@ public class LocationServiceTests
|
|||
using var ctx = NewContext();
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(
|
||||
new LocationCreateRequestDTO { Name = "Warehouse", AccountId = 404 },
|
||||
WithSiteFields(ctx, new LocationCreateRequestDTO { Name = "Warehouse", AccountId = 404 }),
|
||||
OrgWideAdmin(),
|
||||
CancellationToken.None);
|
||||
|
||||
|
|
@ -402,7 +427,7 @@ public class LocationServiceTests
|
|||
ctx.SaveChanges();
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(
|
||||
new LocationCreateRequestDTO { Name = "Warehouse", AccountId = 9 },
|
||||
WithSiteFields(ctx, new LocationCreateRequestDTO { Name = "Warehouse", AccountId = 9 }),
|
||||
OrgWideAdmin(),
|
||||
CancellationToken.None);
|
||||
|
||||
|
|
@ -418,7 +443,7 @@ public class LocationServiceTests
|
|||
SeedAccount(ctx, 99);
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(
|
||||
new LocationCreateRequestDTO { Name = "Site", AccountId = 99 },
|
||||
WithSiteFields(ctx, new LocationCreateRequestDTO { Name = "Site", AccountId = 99 }),
|
||||
AccountUser(4),
|
||||
CancellationToken.None);
|
||||
|
||||
|
|
@ -453,7 +478,7 @@ public class LocationServiceTests
|
|||
SeedAccount(ctx, 9);
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(
|
||||
new LocationCreateRequestDTO { Name = "Site", AccountId = 9 },
|
||||
WithSiteFields(ctx, new LocationCreateRequestDTO { Name = "Site", AccountId = 9 }),
|
||||
MissingScope(),
|
||||
CancellationToken.None);
|
||||
|
||||
|
|
@ -476,12 +501,14 @@ public class LocationServiceTests
|
|||
new LocationDataService(ctx),
|
||||
accounts.Object,
|
||||
new CreateLocationValidation(),
|
||||
new UpdateLocationValidation());
|
||||
new UpdateLocationValidation(),
|
||||
Mock.Of<SeaHaven.DataServices.Interfaces.ITeamPermissionOverrideDataService>(),
|
||||
new SeaHaven.Services.Implementation.TeamPermissionPolicy());
|
||||
|
||||
using var cts = new CancellationTokenSource();
|
||||
|
||||
await service.CreateLocationFromRequestAsync(
|
||||
new LocationCreateRequestDTO { Name = "Site", AccountId = 9 },
|
||||
WithSiteFields(ctx, new LocationCreateRequestDTO { Name = "Site", AccountId = 9 }),
|
||||
OrgWideAdmin(),
|
||||
cts.Token);
|
||||
|
||||
|
|
@ -520,20 +547,6 @@ public class LocationServiceTests
|
|||
ctx.Locations.Single().AccountId.Should().Be(4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteLocationByIdAsync_RemovesAndReturnsFalseWhenMissing()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var existing = SeedLocation(ctx, "Gone", "Cedar Park");
|
||||
|
||||
var removed = await NewService(ctx).DeleteLocationByIdAsync(existing.Id, CancellationToken.None);
|
||||
var again = await NewService(ctx).DeleteLocationByIdAsync(existing.Id, CancellationToken.None);
|
||||
|
||||
removed.Should().BeTrue();
|
||||
again.Should().BeFalse();
|
||||
ctx.Locations.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLocationListPagedAsync_NormalizesAndForwardsSortToDataService()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -22,6 +22,27 @@ namespace Api.SeaHavenIndustries.Tests;
|
|||
|
||||
public class LocationSiteContactsTests
|
||||
{
|
||||
/// <summary>Fills the fields a new site must carry (client, address, one contact) unless the test set them.</summary>
|
||||
private static LocationCreateRequestDTO WithSiteFields(ApplicationDbContext ctx, LocationCreateRequestDTO request)
|
||||
{
|
||||
if (request.AccountId == null)
|
||||
{
|
||||
if (!ctx.Accounts.Any(a => a.Id == 7))
|
||||
{
|
||||
ctx.Accounts.Add(new Accounts { Id = 7, Name = "Customer", IsDeleted = false });
|
||||
ctx.SaveChanges();
|
||||
}
|
||||
|
||||
request.AccountId = 7;
|
||||
}
|
||||
|
||||
request.Address ??= "1 Depot Rd";
|
||||
request.City ??= "Dallas";
|
||||
request.State ??= "TX";
|
||||
request.Contacts ??= new List<SiteContactRequestDTO> { new() { Name = "Main", Phone = "555-0100" } };
|
||||
return request;
|
||||
}
|
||||
|
||||
private static ApplicationDbContext NewContext()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
|
|
@ -35,7 +56,9 @@ public class LocationSiteContactsTests
|
|||
new LocationDataService(ctx),
|
||||
new AccountDataService(ctx),
|
||||
new CreateLocationValidation(),
|
||||
new UpdateLocationValidation());
|
||||
new UpdateLocationValidation(),
|
||||
Mock.Of<SeaHaven.DataServices.Interfaces.ITeamPermissionOverrideDataService>(),
|
||||
new SeaHaven.Services.Implementation.TeamPermissionPolicy());
|
||||
|
||||
private static ClaimsPrincipal OrgWideAdmin()
|
||||
{
|
||||
|
|
@ -51,27 +74,28 @@ public class LocationSiteContactsTests
|
|||
private static async Task<Locations> SeedLocationWithContactsAsync(ApplicationDbContext ctx)
|
||||
{
|
||||
var service = NewService(ctx);
|
||||
await service.CreateLocationFromRequestAsync(new LocationCreateRequestDTO
|
||||
await service.CreateLocationFromRequestAsync(WithSiteFields(ctx, new LocationCreateRequestDTO
|
||||
{
|
||||
Name = "Depot",
|
||||
Phone = "555-9000",
|
||||
AccountId = null,
|
||||
Contacts = new List<SiteContactRequestDTO>
|
||||
{
|
||||
new() { Name = " Alice Cooper ", Phone = " 555-0100 " },
|
||||
new() { Name = "Bob Dillon", Phone = "555-0200"}
|
||||
}
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
}), OrgWideAdmin(), CancellationToken.None);
|
||||
return ctx.Locations.Include(l => l.Contacts).Single();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_WithContacts_PersistsTrimmedOrderedRows_MirrorsFirstPhone_SetsAccountFromLocation()
|
||||
public async Task Create_WithContacts_PersistsTrimmedOrderedRows_KeepsSitePhoneIndependent_SetsAccountFromLocation()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
ctx.Accounts.Add(new Accounts { Id = 7, Name = "Customer", IsDeleted = false });
|
||||
await ctx.SaveChangesAsync();
|
||||
|
||||
await NewService(ctx).CreateLocationFromRequestAsync(new LocationCreateRequestDTO
|
||||
await NewService(ctx).CreateLocationFromRequestAsync(WithSiteFields(ctx, new LocationCreateRequestDTO
|
||||
{
|
||||
Name = "Warehouse",
|
||||
AccountId = 7,
|
||||
|
|
@ -80,10 +104,10 @@ public class LocationSiteContactsTests
|
|||
new() { Name = " Alice Cooper ", Phone = " 555-0100 " },
|
||||
new() { Name = "Bob Dillon", Phone = "555-0200" }
|
||||
}
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
}), OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
var location = ctx.Locations.Include(l => l.Contacts).Single();
|
||||
location.PhoneNumber.Should().Be("555-0100", "first contact mirrors Location.PhoneNumber");
|
||||
location.PhoneNumber.Should().BeNull("Site Phone is independent of the contacts");
|
||||
|
||||
var contacts = location.Contacts.OrderBy(c => c.SiteContactOrder).ToList();
|
||||
contacts.Should().HaveCount(2);
|
||||
|
|
@ -104,11 +128,11 @@ public class LocationSiteContactsTests
|
|||
{
|
||||
using var ctx = NewContext();
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(new LocationCreateRequestDTO
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(WithSiteFields(ctx, new LocationCreateRequestDTO
|
||||
{
|
||||
Name = "Warehouse",
|
||||
Contacts = new List<SiteContactRequestDTO>()
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
}), OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
(await act.Should().ThrowAsync<FluentValidation.ValidationException>())
|
||||
.Which.Errors.Should().ContainSingle(e => e.PropertyName == "Contacts");
|
||||
|
|
@ -127,11 +151,11 @@ public class LocationSiteContactsTests
|
|||
using var ctx = NewContext();
|
||||
var contacts = new List<SiteContactRequestDTO> { new() { Name = name, Phone = phone } };
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(new LocationCreateRequestDTO
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(WithSiteFields(ctx, new LocationCreateRequestDTO
|
||||
{
|
||||
Name = "Warehouse",
|
||||
Contacts = contacts
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
}), OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
if (expectedError == null)
|
||||
{
|
||||
|
|
@ -148,14 +172,14 @@ public class LocationSiteContactsTests
|
|||
{
|
||||
using var ctx = NewContext();
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(new LocationCreateRequestDTO
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(WithSiteFields(ctx, new LocationCreateRequestDTO
|
||||
{
|
||||
Name = "Warehouse",
|
||||
Contacts = new List<SiteContactRequestDTO>
|
||||
{
|
||||
new() { Name = new string('x', 101), Phone = new string('5', 21) }
|
||||
}
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
}), OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
var thrown = (await act.Should().ThrowAsync<FluentValidation.ValidationException>()).Which;
|
||||
thrown.Errors.Should().Contain(e => e.ErrorMessage.Contains("cannot exceed 100"));
|
||||
|
|
@ -170,11 +194,11 @@ public class LocationSiteContactsTests
|
|||
.Select(i => new SiteContactRequestDTO { Name = $"C{i}", Phone = "555-0100" })
|
||||
.ToList();
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(new LocationCreateRequestDTO
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(WithSiteFields(ctx, new LocationCreateRequestDTO
|
||||
{
|
||||
Name = "Warehouse",
|
||||
Contacts = contacts
|
||||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
}), OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
(await act.Should().ThrowAsync<FluentValidation.ValidationException>())
|
||||
.Which.Errors.Should().ContainSingle(e => e.ErrorMessage.Contains("cannot exceed 20"));
|
||||
|
|
@ -220,7 +244,7 @@ public class LocationSiteContactsTests
|
|||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_ReordersAndSoftDeletes_DensifiesOrder_AndUpdatesMirror()
|
||||
public async Task Update_ReordersAndSoftDeletes_DensifiesOrder_LeavesSitePhoneToTheRequest()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var seeded = await SeedLocationWithContactsAsync(ctx);
|
||||
|
|
@ -239,7 +263,7 @@ public class LocationSiteContactsTests
|
|||
}, OrgWideAdmin(), CancellationToken.None);
|
||||
|
||||
var location = ctx.Locations.Include(l => l.Contacts).Single();
|
||||
location.PhoneNumber.Should().Be("555-0200", "reorder must update the mirror to the new first contact");
|
||||
location.PhoneNumber.Should().BeNull("Site Phone comes from the request, not the first contact");
|
||||
|
||||
var active = location.Contacts.Where(c => c.IsDeleted != true).OrderBy(c => c.SiteContactOrder).ToList();
|
||||
active.Should().HaveCount(3);
|
||||
|
|
@ -304,7 +328,7 @@ public class LocationSiteContactsTests
|
|||
after.Should().HaveCount(snapshot.Count);
|
||||
after.Should().BeEquivalentTo(snapshot, o => o.Excluding(c => c.Location));
|
||||
ctx.Locations.AsNoTracking().Single(l => l.Id == seeded.Id).PhoneNumber
|
||||
.Should().Be("555-0100", "the rejected update must not persist any change");
|
||||
.Should().Be("555-9000", "the rejected update must not persist any change");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -448,7 +472,9 @@ public class LocationSiteContactsTests
|
|||
data.Object,
|
||||
Mock.Of<IAccountDataService>(),
|
||||
new CreateLocationValidation(),
|
||||
new UpdateLocationValidation());
|
||||
new UpdateLocationValidation(),
|
||||
Mock.Of<SeaHaven.DataServices.Interfaces.ITeamPermissionOverrideDataService>(),
|
||||
new SeaHaven.Services.Implementation.TeamPermissionPolicy());
|
||||
|
||||
var page = await service.GetLocationListPagedAsync(1, 10, null, cancellationToken: CancellationToken.None);
|
||||
|
||||
|
|
@ -489,67 +515,6 @@ public class LocationSiteContactsTests
|
|||
rows.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DataService_DeleteByIdAsync_WithContacts_RemovesLocation_RetainsSoftDeletedDetachedContacts()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var seeded = await SeedLocationWithContactsAsync(ctx);
|
||||
var alice = seeded.Contacts!.Single(c => c.FirstName == "Alice Cooper");
|
||||
var bob = seeded.Contacts!.Single(c => c.FirstName == "Bob Dillon");
|
||||
|
||||
var deleted = await new LocationDataService(ctx).DeleteByIdAsync(seeded.Id, CancellationToken.None);
|
||||
|
||||
deleted.Should().BeTrue();
|
||||
ctx.Locations.Should().BeEmpty();
|
||||
|
||||
var retained = ctx.Contacts.AsNoTracking().OrderBy(c => c.Id).ToList();
|
||||
retained.Should().HaveCount(2);
|
||||
retained.Should().OnlyContain(c => c.IsDeleted == true);
|
||||
retained.Should().OnlyContain(c => c.LocationId == null);
|
||||
retained.Should().OnlyContain(c => c.DeletionTime != null);
|
||||
retained.Should().OnlyContain(c => c.DeleterUserId == null, "the delete interface carries no actor");
|
||||
retained.Single(c => c.Id == alice.Id).FirstName.Should().Be("Alice Cooper");
|
||||
retained.Single(c => c.Id == alice.Id).PhoneNumber.Should().Be("555-0100");
|
||||
retained.Single(c => c.Id == bob.Id).FirstName.Should().Be("Bob Dillon");
|
||||
retained.Single(c => c.Id == bob.Id).PhoneNumber.Should().Be("555-0200");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DataService_DeleteByIdAsync_AlreadySoftDeletedContact_IsDetachedWithoutAuditRestamp()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var seeded = await SeedLocationWithContactsAsync(ctx);
|
||||
var bob = seeded.Contacts!.Single(c => c.FirstName == "Bob Dillon");
|
||||
bob.IsDeleted = true;
|
||||
bob.DeleterUserId = "admin-1";
|
||||
bob.DeletionTime = new DateTime(2026, 1, 1);
|
||||
await ctx.SaveChangesAsync();
|
||||
var bobStamp = bob.DeletionTime;
|
||||
|
||||
var deleted = await new LocationDataService(ctx).DeleteByIdAsync(seeded.Id, CancellationToken.None);
|
||||
|
||||
deleted.Should().BeTrue();
|
||||
ctx.Locations.Should().BeEmpty();
|
||||
var retained = ctx.Contacts.AsNoTracking().Single(c => c.Id == bob.Id);
|
||||
retained.LocationId.Should().BeNull("previously soft-deleted rows must also detach or the restrict FK blocks the delete");
|
||||
retained.IsDeleted.Should().BeTrue();
|
||||
retained.DeleterUserId.Should().Be("admin-1", "original audit stamp is preserved");
|
||||
retained.DeletionTime.Should().Be(bobStamp);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DataService_DeleteByIdAsync_Missing_ReturnsFalse()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
await SeedLocationWithContactsAsync(ctx);
|
||||
|
||||
var deleted = await new LocationDataService(ctx).DeleteByIdAsync(424242, CancellationToken.None);
|
||||
|
||||
deleted.Should().BeFalse();
|
||||
ctx.Locations.Should().HaveCount(1);
|
||||
ctx.Contacts.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
private sealed class ExposedSH138Migration : Data.SeaHavenIndustries.Migrations.SH138_SiteContacts
|
||||
{
|
||||
public void UpExposed(MigrationBuilder builder) => Up(builder);
|
||||
|
|
@ -608,7 +573,7 @@ public class LocationSiteContactsTests
|
|||
using var json = JsonSerializer.SerializeToDocument(ok.Value);
|
||||
var root = json.RootElement;
|
||||
|
||||
root.GetProperty("Phone").GetString().Should().Be("555-0100", "Phone mirrors the first site contact");
|
||||
root.GetProperty("Phone").GetString().Should().Be("555-9000", "Phone is the Site Phone, independent of contacts");
|
||||
root.GetProperty("Contact").GetString().Should().Be("Alice Cooper", "Contact is the first contact display name");
|
||||
var contacts = root.GetProperty("Contacts");
|
||||
contacts.GetArrayLength().Should().Be(2);
|
||||
|
|
@ -636,7 +601,7 @@ public class LocationSiteContactsTests
|
|||
var row = json.RootElement.GetProperty("Data").EnumerateArray().Single();
|
||||
|
||||
row.GetProperty("Contact").GetString().Should().Be("Alice Cooper");
|
||||
row.GetProperty("Phone").GetString().Should().Be("555-0100");
|
||||
row.GetProperty("Phone").GetString().Should().Be("555-9000");
|
||||
row.GetProperty("Contacts").GetArrayLength().Should().Be(2);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
218
Api.SeaHavenIndustries.Tests/PasswordPolicyTests.cs
Normal file
218
Api.SeaHavenIndustries.Tests/PasswordPolicyTests.cs
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
using Api.SeaHavenIndustries.Infrastructure;
|
||||
using Data.SeaHavenIndustries;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Moq;
|
||||
using SeaHaven.DataServices.Interfaces;
|
||||
using SeaHaven.Services.Configuration;
|
||||
using SeaHaven.Services.DTOs;
|
||||
using SeaHaven.Services.Implementation;
|
||||
using SeaHaven.Services.Interfaces;
|
||||
using Xunit;
|
||||
|
||||
namespace Api.SeaHavenIndustries.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Exercises the password rule through the same Identity registration the API
|
||||
/// host uses, so these assertions describe the rule that runs in production.
|
||||
/// </summary>
|
||||
public sealed class PasswordPolicyTests : IAsyncDisposable
|
||||
{
|
||||
private const string CurrentPassword = "Current1!";
|
||||
private readonly ServiceProvider _provider;
|
||||
private readonly AsyncServiceScope _scope;
|
||||
|
||||
public PasswordPolicyTests()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddDbContext<ApplicationDbContext>(options =>
|
||||
options.UseInMemoryDatabase(Guid.NewGuid().ToString()));
|
||||
services.AddSeaHavenIdentity();
|
||||
_provider = services.BuildServiceProvider();
|
||||
_scope = _provider.CreateAsyncScope();
|
||||
}
|
||||
|
||||
private UserManager<ApplicationUser> UserManager =>
|
||||
_scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
||||
|
||||
[Theory]
|
||||
[InlineData("Ab1!x", "PasswordTooShort")]
|
||||
[InlineData("abc12!", "PasswordRequiresUpper")]
|
||||
[InlineData("Abcde!", "PasswordRequiresDigit")]
|
||||
[InlineData("Abcde1", "PasswordRequiresNonAlphanumeric")]
|
||||
public async Task Policy_RejectsPasswordMissingOneRule(string password, string expectedCode)
|
||||
{
|
||||
var user = new ApplicationUser { UserName = "policy@example.com", Email = "policy@example.com" };
|
||||
|
||||
var errors = await ValidateAsync(user, password);
|
||||
|
||||
errors.Select(error => error.Code).Should().Equal(expectedCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Abc1!x")]
|
||||
[InlineData("ABC12!")]
|
||||
public async Task Policy_AcceptsSixCharacterPasswordMeetingEveryRule(string password)
|
||||
{
|
||||
var user = new ApplicationUser { UserName = "policy@example.com", Email = "policy@example.com" };
|
||||
|
||||
var errors = await ValidateAsync(user, password);
|
||||
|
||||
errors.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Registration_AppliesSharedPolicyOptions()
|
||||
{
|
||||
var options = _scope.ServiceProvider.GetRequiredService<IOptions<IdentityOptions>>().Value.Password;
|
||||
|
||||
options.RequiredLength.Should().Be(6);
|
||||
options.RequireUppercase.Should().BeTrue();
|
||||
options.RequireDigit.Should().BeTrue();
|
||||
options.RequireNonAlphanumeric.Should().BeTrue();
|
||||
options.RequireLowercase.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WrongCurrentPassword_IsRejectedBeforeNewPasswordIsEvaluated()
|
||||
{
|
||||
var user = await CreateUserAsync();
|
||||
var service = NewAuthenticationService();
|
||||
|
||||
var result = await service.ChangePasswordAsync(user.Id, "Wrong1!", "weak", CancellationToken.None);
|
||||
|
||||
result.Status.Should().Be(ChangePasswordStatus.CurrentPasswordIncorrect);
|
||||
(await UserManager.CheckPasswordAsync(user, CurrentPassword)).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_CorrectCurrentPasswordAndWeakNewPassword_IsRejectedByPolicy()
|
||||
{
|
||||
var user = await CreateUserAsync();
|
||||
var service = NewAuthenticationService();
|
||||
|
||||
var result = await service.ChangePasswordAsync(user.Id, CurrentPassword, "abcdef", CancellationToken.None);
|
||||
|
||||
result.Status.Should().Be(ChangePasswordStatus.PasswordRejected);
|
||||
(await UserManager.CheckPasswordAsync(user, CurrentPassword)).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_CorrectCurrentPasswordAndCompliantNewPassword_ChangesPassword()
|
||||
{
|
||||
var user = await CreateUserAsync();
|
||||
var service = NewAuthenticationService();
|
||||
|
||||
var result = await service.ChangePasswordAsync(user.Id, CurrentPassword, "Next2@x", CancellationToken.None);
|
||||
|
||||
result.Status.Should().Be(ChangePasswordStatus.Succeeded);
|
||||
var reloaded = await UserManager.FindByIdAsync(user.Id);
|
||||
(await UserManager.CheckPasswordAsync(reloaded!, "Next2@x")).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("ConcurrencyFailure")]
|
||||
[InlineData("PasswordMismatch")]
|
||||
[InlineData("DefaultError")]
|
||||
public async Task ChangePassword_NonPolicyIdentityFailure_IsNotReportedAsAWeakPassword(string code)
|
||||
{
|
||||
var user = new ApplicationUser { Id = "member-1", UserName = "member@example.com" };
|
||||
var userManager = new Mock<UserManager<ApplicationUser>>(
|
||||
Mock.Of<IUserStore<ApplicationUser>>(), null!, null!, null!, null!, null!, null!, null!, null!);
|
||||
userManager.Setup(m => m.FindByIdAsync(user.Id)).ReturnsAsync(user);
|
||||
userManager.Setup(m => m.CheckPasswordAsync(user, CurrentPassword)).ReturnsAsync(true);
|
||||
userManager.Setup(m => m.ChangePasswordAsync(user, CurrentPassword, "Next2@x"))
|
||||
.ReturnsAsync(IdentityResult.Failed(new IdentityError { Code = code, Description = "failed" }));
|
||||
var service = new AuthenticationService(
|
||||
userManager.Object,
|
||||
Microsoft.Extensions.Options.Options.Create(new JwtOptions { Secret = new string('x', 64) }),
|
||||
Mock.Of<IUserDataService>(),
|
||||
Mock.Of<IForgetPasswordDataService>(),
|
||||
Mock.Of<IEmailSender>());
|
||||
|
||||
var result = await service.ChangePasswordAsync(user.Id, CurrentPassword, "Next2@x", CancellationToken.None);
|
||||
|
||||
result.Status.Should().Be(ChangePasswordStatus.Failed);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("PasswordTooShort", true)]
|
||||
[InlineData("PasswordRequiresUpper", true)]
|
||||
[InlineData("PasswordRequiresDigit", true)]
|
||||
[InlineData("PasswordRequiresNonAlphanumeric", true)]
|
||||
[InlineData("ConcurrencyFailure", false)]
|
||||
[InlineData("PasswordMismatch", false)]
|
||||
public void IsPolicyRejection_MatchesOnlyThePasswordRuleCodes(string code, bool expected)
|
||||
{
|
||||
IdentityPasswordPolicy.IsPolicyRejection(IdentityResult.Failed(new IdentityError { Code = code }))
|
||||
.Should().Be(expected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_CancelledToken_Throws()
|
||||
{
|
||||
var service = NewAuthenticationService();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
cancellation.Cancel();
|
||||
|
||||
var act = () => service.ChangePasswordAsync("any", CurrentPassword, "Next2@x", cancellation.Token);
|
||||
|
||||
await act.Should().ThrowAsync<OperationCanceledException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResetPassword_WeakPassword_IsRejectedAndKeepsCode()
|
||||
{
|
||||
var user = await CreateUserAsync();
|
||||
var forget = new Mock<IForgetPasswordDataService>();
|
||||
forget.Setup(f => f.ExistsByEmailAndCodeAsync(user.Email!, "123456", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(true);
|
||||
forget.Setup(f => f.GetByEmailAsync(user.Email!, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new ForgetPasswordCode { Email = user.Email!, UserId = user.Id, Code = "123456" });
|
||||
var service = NewAuthenticationService(forget);
|
||||
|
||||
var reset = await service.ResetPasswordAsync(user.Email!, "123456", "abcdef", CancellationToken.None);
|
||||
|
||||
reset.Should().BeFalse();
|
||||
(await UserManager.CheckPasswordAsync(user, CurrentPassword)).Should().BeTrue();
|
||||
forget.Verify(f => f.RemoveByEmailAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<IdentityError>> ValidateAsync(ApplicationUser user, string password)
|
||||
{
|
||||
var errors = new List<IdentityError>();
|
||||
foreach (var validator in UserManager.PasswordValidators)
|
||||
{
|
||||
var result = await validator.ValidateAsync(UserManager, user, password);
|
||||
errors.AddRange(result.Errors);
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
private async Task<ApplicationUser> CreateUserAsync()
|
||||
{
|
||||
var user = new ApplicationUser { UserName = "member@example.com", Email = "member@example.com" };
|
||||
var created = await UserManager.CreateAsync(user, CurrentPassword);
|
||||
created.Succeeded.Should().BeTrue();
|
||||
return user;
|
||||
}
|
||||
|
||||
private AuthenticationService NewAuthenticationService(Mock<IForgetPasswordDataService>? forget = null) =>
|
||||
new(
|
||||
UserManager,
|
||||
Microsoft.Extensions.Options.Options.Create(new JwtOptions { Secret = new string('x', 64) }),
|
||||
Mock.Of<IUserDataService>(),
|
||||
(forget ?? new Mock<IForgetPasswordDataService>()).Object,
|
||||
Mock.Of<IEmailSender>());
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _scope.DisposeAsync();
|
||||
await _provider.DisposeAsync();
|
||||
}
|
||||
}
|
||||
503
Api.SeaHavenIndustries.Tests/SiteRegistryServiceTests.cs
Normal file
503
Api.SeaHavenIndustries.Tests/SiteRegistryServiceTests.cs
Normal file
|
|
@ -0,0 +1,503 @@
|
|||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using Data.SeaHavenIndustries;
|
||||
using Data.SeaHavenIndustries.Enums;
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using SeaHaven.DataServices.Dto;
|
||||
using SeaHaven.DataServices.Implementation;
|
||||
using SeaHaven.DataServices.Interfaces;
|
||||
using SeaHaven.Services.DTOs;
|
||||
using SeaHaven.Services.Exceptions;
|
||||
using SeaHaven.Services.Helpers;
|
||||
using SeaHaven.Services.Implementation;
|
||||
using SeaHaven.Services.Validation;
|
||||
using Xunit;
|
||||
|
||||
namespace Api.SeaHavenIndustries.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Site registry rules: tenant-scoped unique site codes, immutable codes,
|
||||
/// permission-gated tombstone delete, open work order lookup and the
|
||||
/// contact/notes write used by the work-order Site dialog.
|
||||
/// </summary>
|
||||
public class SiteRegistryServiceTests
|
||||
{
|
||||
private static ApplicationDbContext NewContext()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
return new ApplicationDbContext(options);
|
||||
}
|
||||
|
||||
private static LocationService NewService(ApplicationDbContext ctx, string? role = "Admin") =>
|
||||
NewService(new LocationDataService(ctx), new AccountDataService(ctx), role);
|
||||
|
||||
private static LocationService NewService(
|
||||
ILocationDataService data,
|
||||
IAccountDataService accounts,
|
||||
string? role = "Admin")
|
||||
{
|
||||
var permissions = new Mock<ITeamPermissionOverrideDataService>();
|
||||
permissions
|
||||
.Setup(p => p.GetUserAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync((string userId, CancellationToken _) => role == null
|
||||
? null
|
||||
: new TeamPermissionUserData { UserId = userId, RoleName = role });
|
||||
|
||||
return new LocationService(
|
||||
data,
|
||||
accounts,
|
||||
new CreateLocationValidation(),
|
||||
new UpdateLocationValidation(),
|
||||
permissions.Object,
|
||||
new TeamPermissionPolicy());
|
||||
}
|
||||
|
||||
private static ClaimsPrincipal OrgWide(string role = "Admin") => Principal(role, new Claim(SeaHavenClaimTypes.OrgScope, SeaHavenClaimTypes.OrgScopeAll));
|
||||
|
||||
private static ClaimsPrincipal AccountUser(int accountId, string role = "Admin") =>
|
||||
Principal(role, new Claim(SeaHavenClaimTypes.AccountId, accountId.ToString()));
|
||||
|
||||
private static ClaimsPrincipal Principal(string role, Claim scope) =>
|
||||
new(new ClaimsIdentity(new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, "actor-1"),
|
||||
new(ClaimTypes.Role, role),
|
||||
scope
|
||||
}, "test"));
|
||||
|
||||
private static void SeedAccounts(ApplicationDbContext ctx, params int[] ids)
|
||||
{
|
||||
foreach (var id in ids)
|
||||
ctx.Accounts.Add(new Accounts { Id = id, Name = $"Client {id}", IsDeleted = false });
|
||||
ctx.SaveChanges();
|
||||
}
|
||||
|
||||
private static Locations SeedSite(ApplicationDbContext ctx, string code, int? accountId, bool deleted = false)
|
||||
{
|
||||
var site = new Locations { Name = code, AccountId = accountId, City = "Dallas", State = "TX", IsDeleted = deleted ? true : null };
|
||||
ctx.Locations.Add(site);
|
||||
ctx.SaveChanges();
|
||||
return site;
|
||||
}
|
||||
|
||||
private static WorkOrder Wo(
|
||||
int id,
|
||||
int? locationId,
|
||||
LifecycleStatus? status = LifecycleStatus.Incomplete,
|
||||
int? accountId = 1,
|
||||
string? siteCode = null,
|
||||
string? legacyStatus = null,
|
||||
bool deleted = false) => new()
|
||||
{
|
||||
Id = id,
|
||||
LocationId = locationId,
|
||||
LifecycleStatus = status,
|
||||
LegacyStatus = legacyStatus,
|
||||
AccountId = accountId,
|
||||
SiteCode = siteCode,
|
||||
IsDeleted = deleted ? true : null
|
||||
};
|
||||
|
||||
private static LocationCreateRequestDTO CreateRequest(string code, int? accountId) => new()
|
||||
{
|
||||
Name = code,
|
||||
AccountId = accountId,
|
||||
Address = "1 Depot Rd",
|
||||
City = "Dallas",
|
||||
State = "TX",
|
||||
Contacts = new List<SiteContactRequestDTO> { new() { Name = "Main", Phone = "555-0100" } }
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Create_DuplicateSiteCodeInSameClient_IsRejectedCaseInsensitively()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1);
|
||||
SeedSite(ctx, "BK5", 1);
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(CreateRequest(" bk5 ", 1), OrgWide(), CancellationToken.None);
|
||||
|
||||
await act.Should().ThrowAsync<SiteCodeConflictException>();
|
||||
ctx.Locations.Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_SameSiteCodeForAnotherClient_IsAllowed()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1, 2);
|
||||
SeedSite(ctx, "BK5", 1);
|
||||
|
||||
await NewService(ctx).CreateLocationFromRequestAsync(CreateRequest("BK5", 2), OrgWide(), CancellationToken.None);
|
||||
|
||||
ctx.Locations.Where(l => l.Name == "BK5").Select(l => l.AccountId).Should().BeEquivalentTo(new int?[] { 1, 2 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_SiteCodeOfADeletedSite_CanBeReused()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1);
|
||||
SeedSite(ctx, "BK5", 1, deleted: true);
|
||||
|
||||
await NewService(ctx).CreateLocationFromRequestAsync(CreateRequest("BK5", 1), OrgWide(), CancellationToken.None);
|
||||
|
||||
ctx.Locations.Count(l => l.Name == "BK5" && l.IsDeleted != true).Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_BlankSiteCode_IsAValidationError()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1);
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(CreateRequest(" ", 1), OrgWide(), CancellationToken.None);
|
||||
|
||||
(await act.Should().ThrowAsync<FluentValidation.ValidationException>())
|
||||
.Which.Errors.Should().ContainSingle(e => e.ErrorMessage == "Site Code is required.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_StoresTrimmedCodeNotesAndSitePhoneIndependentOfContacts()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1);
|
||||
var request = CreateRequest(" DFW8 ", 1);
|
||||
request.Phone = "555-9000";
|
||||
request.Notes = " Gate code 4411 ";
|
||||
|
||||
await NewService(ctx).CreateLocationFromRequestAsync(request, OrgWide(), CancellationToken.None);
|
||||
|
||||
var site = ctx.Locations.Single();
|
||||
site.Name.Should().Be("DFW8");
|
||||
site.PhoneNumber.Should().Be("555-9000");
|
||||
site.Notes.Should().Be("Gate code 4411");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_ChangingAnExistingSiteCode_IsRejected()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var site = SeedSite(ctx, "BK5", null);
|
||||
|
||||
var act = () => NewService(ctx).UpdateLocationFromRequestAsync(
|
||||
site.Id, new LocationUpdateRequestDTO { Name = "BK6" }, OrgWide(), CancellationToken.None);
|
||||
|
||||
(await act.Should().ThrowAsync<FluentValidation.ValidationException>())
|
||||
.Which.Errors.Should().ContainSingle(e => e.ErrorMessage == "Site Code cannot be changed.");
|
||||
ctx.Locations.AsNoTracking().Single().Name.Should().Be("BK5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_KeepsCodeAndNotesWhenTheRequestOmitsThem()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var site = SeedSite(ctx, "BK5", null);
|
||||
site.Notes = "Dock 3";
|
||||
site.Status = "Active";
|
||||
ctx.SaveChanges();
|
||||
|
||||
await NewService(ctx).UpdateLocationFromRequestAsync(
|
||||
site.Id, new LocationUpdateRequestDTO { Name = "bk5", City = "Memphis" }, OrgWide(), CancellationToken.None);
|
||||
|
||||
var saved = ctx.Locations.AsNoTracking().Single();
|
||||
saved.Name.Should().Be("BK5");
|
||||
saved.City.Should().Be("Memphis");
|
||||
saved.Notes.Should().Be("Dock 3");
|
||||
saved.Status.Should().Be("Active");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_BlankLegacyCode_CanBeFilledOnceButMustBeUniqueInTheClient()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1);
|
||||
SeedSite(ctx, "BK5", 1);
|
||||
var legacy = SeedSite(ctx, "", 1);
|
||||
|
||||
var duplicate = () => NewService(ctx).UpdateLocationFromRequestAsync(
|
||||
legacy.Id, new LocationUpdateRequestDTO { Name = "bk5" }, OrgWide(), CancellationToken.None);
|
||||
await duplicate.Should().ThrowAsync<SiteCodeConflictException>();
|
||||
|
||||
await NewService(ctx).UpdateLocationFromRequestAsync(
|
||||
legacy.Id, new LocationUpdateRequestDTO { Name = "MEM1" }, OrgWide(), CancellationToken.None);
|
||||
ctx.Locations.AsNoTracking().Single(l => l.Id == legacy.Id).Name.Should().Be("MEM1");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Admin")]
|
||||
[InlineData("Scheduler")]
|
||||
public async Task Delete_AdminOrScheduler_TombstonesTheSiteAndLeavesWorkOrdersAsTheyWere(string role)
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1);
|
||||
var site = SeedSite(ctx, "BK5", 1);
|
||||
ctx.Contacts.Add(new Contacts { LocationId = site.Id, FirstName = "Main", PhoneNumber = "555-0100" });
|
||||
ctx.workOrders.Add(Wo(10, site.Id));
|
||||
ctx.SaveChanges();
|
||||
|
||||
var deleted = await NewService(ctx, role).DeleteLocationByIdAsync(site.Id, OrgWide(role), CancellationToken.None);
|
||||
|
||||
deleted.Should().BeTrue();
|
||||
var tombstone = ctx.Locations.AsNoTracking().Single();
|
||||
tombstone.IsDeleted.Should().BeTrue();
|
||||
tombstone.DeleterUserId.Should().Be("actor-1");
|
||||
ctx.workOrders.AsNoTracking().Single().LocationId.Should().Be(site.Id, "work orders keep their site reference");
|
||||
ctx.Contacts.AsNoTracking().Single().IsDeleted.Should().NotBe(true, "contacts still back open work orders");
|
||||
|
||||
var data = new LocationDataService(ctx);
|
||||
(await data.GetDetailByIdAsync(site.Id, CancellationToken.None)).Should().BeNull();
|
||||
(await data.GetSiteOptionsAsync(null, CancellationToken.None)).Should().BeEmpty();
|
||||
(await data.GetListPagedAsync(1, 10, null, null, CancellationToken.None)).TotalCount.Should().Be(0);
|
||||
(await data.GetAccountScopeAsync(site.Id, CancellationToken.None)).Exists.Should().BeFalse("a deleted site cannot be assigned to new work orders");
|
||||
(await NewService(ctx, role).DeleteLocationByIdAsync(site.Id, OrgWide(role), CancellationToken.None)).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Dispatcher")]
|
||||
[InlineData(null)]
|
||||
public async Task Delete_WithoutDeleteSitesPermission_IsForbiddenAndKeepsTheSite(string? role)
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var site = SeedSite(ctx, "BK5", null);
|
||||
|
||||
var act = () => NewService(ctx, role).DeleteLocationByIdAsync(site.Id, OrgWide(role ?? "Dispatcher"), CancellationToken.None);
|
||||
|
||||
await act.Should().ThrowAsync<SiteForbiddenException>();
|
||||
ctx.Locations.AsNoTracking().Single().IsDeleted.Should().NotBe(true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_SiteOfAnotherClient_IsRejectedForAnAccountScopedCaller()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var site = SeedSite(ctx, "BK5", 2);
|
||||
|
||||
var act = () => NewService(ctx).DeleteLocationByIdAsync(site.Id, AccountUser(1), CancellationToken.None);
|
||||
|
||||
await act.Should().ThrowAsync<UnauthorizedAccessException>();
|
||||
ctx.Locations.AsNoTracking().Single().IsDeleted.Should().NotBe(true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenWorkOrders_ExcludeTerminalDeletedAndOtherSitesWork()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var site = SeedSite(ctx, "BK5", 1);
|
||||
var other = SeedSite(ctx, "MEM1", 1);
|
||||
ctx.workOrders.AddRange(
|
||||
Wo(1, site.Id),
|
||||
Wo(2, site.Id, LifecycleStatus.Scheduled),
|
||||
Wo(3, site.Id, LifecycleStatus.Completed),
|
||||
Wo(4, site.Id, LifecycleStatus.Canceled),
|
||||
Wo(5, site.Id, deleted: true),
|
||||
Wo(6, site.Id, status: null, legacyStatus: "Completed"),
|
||||
Wo(7, site.Id, status: null, legacyStatus: "Open"),
|
||||
Wo(8, null, siteCode: "bk5"),
|
||||
Wo(9, null, siteCode: "BK5", accountId: 2),
|
||||
Wo(10, other.Id));
|
||||
ctx.SaveChanges();
|
||||
|
||||
var result = await NewService(ctx).GetOpenWorkOrdersAsync(site.Id, OrgWide(), CancellationToken.None);
|
||||
|
||||
result!.WorkOrderIds.Should().Equal(1, 2, 7, 8);
|
||||
result.Count.Should().Be(4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenWorkOrders_AccountScopedCaller_SeesOnlyTheirClientsWork()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var site = SeedSite(ctx, "BK5", 1);
|
||||
ctx.workOrders.AddRange(Wo(1, site.Id, accountId: 1), Wo(2, site.Id, accountId: 2));
|
||||
ctx.SaveChanges();
|
||||
|
||||
var own = await NewService(ctx).GetOpenWorkOrdersAsync(site.Id, AccountUser(1), CancellationToken.None);
|
||||
own!.WorkOrderIds.Should().Equal(1);
|
||||
|
||||
var foreign = () => NewService(ctx).GetOpenWorkOrdersAsync(site.Id, AccountUser(2), CancellationToken.None);
|
||||
await foreign.Should().ThrowAsync<UnauthorizedAccessException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenWorkOrders_ReturnFullCountButCapIds()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var site = SeedSite(ctx, "BK5", 1);
|
||||
ctx.workOrders.AddRange(Enumerable.Range(1, LocationService.MaxOpenWorkOrderIds + 5).Select(id => Wo(id, site.Id)));
|
||||
ctx.SaveChanges();
|
||||
|
||||
var result = await NewService(ctx).GetOpenWorkOrdersAsync(site.Id, OrgWide(), CancellationToken.None);
|
||||
|
||||
result!.Count.Should().Be(LocationService.MaxOpenWorkOrderIds + 5);
|
||||
result.WorkOrderIds.Should().HaveCount(LocationService.MaxOpenWorkOrderIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenWorkOrders_MissingOrDeletedSite_ReturnsNull()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var deleted = SeedSite(ctx, "BK5", 1, deleted: true);
|
||||
|
||||
(await NewService(ctx).GetOpenWorkOrdersAsync(deleted.Id, OrgWide(), CancellationToken.None)).Should().BeNull();
|
||||
(await NewService(ctx).GetOpenWorkOrdersAsync(999, OrgWide(), CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSiteContactInfo_SavesContactsAndNotesToTheSiteRecord()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var site = SeedSite(ctx, "BK5", null);
|
||||
var main = new Contacts { LocationId = site.Id, FirstName = "Old Main", PhoneNumber = "555-0100", SiteContactOrder = 0 };
|
||||
ctx.Contacts.Add(main);
|
||||
ctx.SaveChanges();
|
||||
|
||||
await NewService(ctx).UpdateSiteContactInfoAsync(site.Id, new SiteContactInfoRequestDTO
|
||||
{
|
||||
Contacts = new List<SiteContactRequestDTO>
|
||||
{
|
||||
new() { Id = main.Id, Name = "New Main", Phone = "555-0199" },
|
||||
new() { Name = "Night Shift", Phone = "555-0200" }
|
||||
},
|
||||
Notes = " Call ahead "
|
||||
}, OrgWide("Dispatcher"), CancellationToken.None);
|
||||
|
||||
var saved = ctx.Locations.AsNoTracking().Include(l => l.Contacts).Single();
|
||||
saved.Notes.Should().Be("Call ahead");
|
||||
saved.Contacts!.Where(c => c.IsDeleted != true).OrderBy(c => c.SiteContactOrder)
|
||||
.Select(c => (c.Id == main.Id, c.FirstName, c.PhoneNumber))
|
||||
.Should().Equal((true, "New Main", "555-0199"), (false, "Night Shift", "555-0200"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSiteContactInfo_RejectsOutOfScopeDeletedAndContactlessRequests()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
var foreign = SeedSite(ctx, "BK5", 2);
|
||||
var deleted = SeedSite(ctx, "MEM1", 1, deleted: true);
|
||||
var request = new SiteContactInfoRequestDTO
|
||||
{
|
||||
Contacts = new List<SiteContactRequestDTO> { new() { Name = "A", Phone = "1" } }
|
||||
};
|
||||
|
||||
await ((Func<Task>)(() => NewService(ctx).UpdateSiteContactInfoAsync(foreign.Id, request, AccountUser(1), CancellationToken.None)))
|
||||
.Should().ThrowAsync<UnauthorizedAccessException>();
|
||||
await ((Func<Task>)(() => NewService(ctx).UpdateSiteContactInfoAsync(deleted.Id, request, OrgWide(), CancellationToken.None)))
|
||||
.Should().ThrowAsync<KeyNotFoundException>();
|
||||
await ((Func<Task>)(() => NewService(ctx).UpdateSiteContactInfoAsync(
|
||||
foreign.Id, new SiteContactInfoRequestDTO { Notes = "x" }, OrgWide(), CancellationToken.None)))
|
||||
.Should().ThrowAsync<FluentValidation.ValidationException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NewSiteOperations_ForwardTheCallersCancellationToken()
|
||||
{
|
||||
using var cts = new CancellationTokenSource();
|
||||
var token = cts.Token;
|
||||
var site = new Locations { Id = 5, Name = "BK5", AccountId = 1, Contacts = new List<Contacts>() };
|
||||
var data = new Mock<ILocationDataService>();
|
||||
data.Setup(d => d.GetByIdForUpdateAsync(5, token)).ReturnsAsync(site);
|
||||
data.Setup(d => d.GetDetailByIdAsync(5, token)).ReturnsAsync(site);
|
||||
data.Setup(d => d.GetOpenWorkOrderIdsAsync(5, "BK5", 1, null, LocationService.MaxOpenWorkOrderIds, token))
|
||||
.ReturnsAsync((1, new[] { 7 }));
|
||||
var service = NewService(data.Object, Mock.Of<IAccountDataService>());
|
||||
|
||||
await service.GetOpenWorkOrdersAsync(5, OrgWide(), token);
|
||||
await service.UpdateSiteContactInfoAsync(5, new SiteContactInfoRequestDTO
|
||||
{
|
||||
Contacts = new List<SiteContactRequestDTO> { new() { Name = "A", Phone = "1" } }
|
||||
}, OrgWide(), token);
|
||||
await service.DeleteLocationByIdAsync(5, OrgWide(), token);
|
||||
|
||||
data.Verify(d => d.GetOpenWorkOrderIdsAsync(5, "BK5", 1, null, LocationService.MaxOpenWorkOrderIds, token), Times.Once);
|
||||
data.Verify(d => d.UpdateAsync(site, token), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_DuplicateCheck_ForwardsTheCallersCancellationToken()
|
||||
{
|
||||
using var cts = new CancellationTokenSource();
|
||||
var token = cts.Token;
|
||||
var data = new Mock<ILocationDataService>();
|
||||
data.Setup(d => d.SiteCodeExistsAsync("BK5", 1, null, token)).ReturnsAsync(true);
|
||||
var accounts = new Mock<IAccountDataService>();
|
||||
accounts.Setup(a => a.ExistsActiveAsync(1, token)).ReturnsAsync(true);
|
||||
var service = NewService(data.Object, accounts.Object);
|
||||
|
||||
var act = () => service.CreateLocationFromRequestAsync(CreateRequest("BK5", 1), OrgWide(), token);
|
||||
|
||||
await act.Should().ThrowAsync<SiteCodeConflictException>();
|
||||
data.Verify(d => d.SiteCodeExistsAsync("BK5", 1, null, token), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompletionSnapshot_FreezesSiteNotesWhenTheWorkOrderHasNone()
|
||||
{
|
||||
var workOrder = new WorkOrder
|
||||
{
|
||||
Id = 1,
|
||||
Locations = new Locations { Id = 5, Name = "BK5", Notes = "Gate code 4411", Contacts = new List<Contacts>() }
|
||||
};
|
||||
|
||||
WorkOrderCompletionSnapshotMapper.Capture(workOrder);
|
||||
|
||||
using var frozen = JsonDocument.Parse(workOrder.FrozenPoc!);
|
||||
frozen.RootElement.GetProperty("notes").GetString().Should().Be("Gate code 4411");
|
||||
}
|
||||
|
||||
public static TheoryData<string, Action<LocationCreateRequestDTO>, string> MissingSiteFields => new()
|
||||
{
|
||||
{ "no client", r => r.AccountId = null, "Client is required." },
|
||||
{ "no street address", r => r.Address = " ", "Street Address is required." },
|
||||
{ "no city", r => r.City = null, "City is required." },
|
||||
{ "no state", r => r.State = "", "State is required." },
|
||||
{ "no contacts list", r => r.Contacts = null, "At least one contact is required." },
|
||||
{ "empty contacts list", r => r.Contacts = new List<SiteContactRequestDTO>(), "At least one contact is required." },
|
||||
{ "contact without phone", r => r.Contacts = new List<SiteContactRequestDTO> { new() { Name = "Main", Phone = " " } }, "Contact phone is required." }
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(MissingSiteFields))]
|
||||
public async Task Create_WithoutARequiredSiteField_IsAValidationErrorAndStoresNothing(
|
||||
string _,
|
||||
Action<LocationCreateRequestDTO> strip,
|
||||
string expectedMessage)
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1);
|
||||
var request = CreateRequest("BK9", 1);
|
||||
strip(request);
|
||||
|
||||
var act = () => NewService(ctx).CreateLocationFromRequestAsync(request, OrgWide(), CancellationToken.None);
|
||||
|
||||
(await act.Should().ThrowAsync<FluentValidation.ValidationException>())
|
||||
.Which.Errors.Should().Contain(e => e.ErrorMessage == expectedMessage);
|
||||
ctx.Locations.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_RemovesTheSiteFromEveryLegacyRead()
|
||||
{
|
||||
using var ctx = NewContext();
|
||||
SeedAccounts(ctx, 1);
|
||||
var deleted = SeedSite(ctx, "BK5", 1);
|
||||
var kept = SeedSite(ctx, "BK6", 1);
|
||||
var service = NewService(ctx);
|
||||
|
||||
(await service.DeleteLocationByIdAsync(deleted.Id, OrgWide(), CancellationToken.None)).Should().BeTrue();
|
||||
|
||||
(await service.GetLocationByIdAsync(deleted.Id)).Should().BeNull();
|
||||
(await service.GetLocationByIdWithDetailsAsync(deleted.Id)).Should().BeNull();
|
||||
(await service.LocationExistsAsync(deleted.Id)).Should().BeFalse();
|
||||
(await service.GetTotalLocationCountAsync()).Should().Be(1);
|
||||
(await service.GetAllLocationsAsync()).Select(l => l.Id).Should().Equal(kept.Id);
|
||||
(await service.GetLocationsByAccountIdAsync(1)).Select(l => l.Id).Should().Equal(kept.Id);
|
||||
(await service.GetLocationsPagedAsync(1, 10)).Items.Select(l => l.Id).Should().Equal(kept.Id);
|
||||
(await new LocationDataService(ctx).GetAddressbookPagedAsync(1, 10)).TotalCount.Should().Be(1);
|
||||
(await new VendorOperationsDataService(ctx, Mock.Of<IDispatchDataService>()).LocationExistsAsync(deleted.Id, CancellationToken.None)).Should().BeFalse();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
using Api.SeaHavenIndustries.Controllers;
|
||||
using Data.SeaHavenIndustries.Enums;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ActionConstraints;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.AspNetCore.Mvc.Infrastructure;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Moq;
|
||||
using SeaHaven.DataServices.Dto;
|
||||
using SeaHaven.DataServices.Interfaces;
|
||||
using SeaHaven.Services.Constants;
|
||||
using SeaHaven.Services.DTOs;
|
||||
using SeaHaven.Services.Implementation;
|
||||
using SeaHaven.Services.Interfaces;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Api.SeaHavenIndustries.Tests;
|
||||
|
||||
public sealed class TeamMemberPermissionsEndpointTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Signed_in_caller_receives_their_effective_keys_as_a_permissions_array()
|
||||
{
|
||||
var data = new Mock<ITeamPermissionOverrideDataService>();
|
||||
data.Setup(d => d.GetUserAsync("u1", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new TeamPermissionUserData
|
||||
{
|
||||
UserId = "u1",
|
||||
RoleName = "Dispatcher",
|
||||
Overrides = new Dictionary<string, UserPermissionState>
|
||||
{
|
||||
[TeamPermissionKeys.CreateCompletionDocTemplates] = UserPermissionState.Allow
|
||||
}
|
||||
});
|
||||
var controller = Controller(data.Object, new ClaimsPrincipal(new ClaimsIdentity(
|
||||
new[] { new Claim(ClaimTypes.NameIdentifier, "u1") }, "Bearer")));
|
||||
|
||||
var ok = Assert.IsType<OkObjectResult>(await controller.GetMyPermissions(CancellationToken.None));
|
||||
|
||||
var json = JsonSerializer.Serialize(ok.Value, new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var keys = document.RootElement.GetProperty("permissions").EnumerateArray()
|
||||
.Select(element => element.GetString()).ToList();
|
||||
Assert.Contains(TeamPermissionKeys.CreateCompletionDocTemplates, keys);
|
||||
Assert.DoesNotContain(TeamPermissionKeys.DeleteCompletionDocTemplates, keys);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unauthenticated_caller_gets_401_without_data_access()
|
||||
{
|
||||
var data = new Mock<ITeamPermissionOverrideDataService>(MockBehavior.Strict);
|
||||
var controller = Controller(data.Object, new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
|
||||
var result = Assert.IsType<UnauthorizedResult>(await controller.GetMyPermissions(CancellationToken.None));
|
||||
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, result.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Route_is_get_me_permissions_and_requires_authentication()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddMvcCore().AddApplicationPart(typeof(TeamMemberController).Assembly);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
var descriptor = provider
|
||||
.GetRequiredService<IActionDescriptorCollectionProvider>()
|
||||
.ActionDescriptors.Items
|
||||
.OfType<ControllerActionDescriptor>()
|
||||
.Single(d => d.ControllerTypeInfo == typeof(TeamMemberController)
|
||||
&& d.ActionName == nameof(TeamMemberController.GetMyPermissions));
|
||||
|
||||
var methods = descriptor.ActionConstraints!.OfType<HttpMethodActionConstraint>()
|
||||
.SelectMany(c => c.HttpMethods);
|
||||
Assert.Equal(new[] { "GET" }, methods);
|
||||
Assert.Equal("api/team-members/me/permissions", descriptor.AttributeRouteInfo!.Template);
|
||||
Assert.NotEmpty(typeof(TeamMemberController).GetCustomAttributes(typeof(AuthorizeAttribute), true));
|
||||
Assert.Empty(descriptor.MethodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), true));
|
||||
}
|
||||
|
||||
private static TeamMemberController Controller(
|
||||
ITeamPermissionOverrideDataService data,
|
||||
ClaimsPrincipal user) =>
|
||||
new(Mock.Of<ITeamMemberService>(), new TeamPermissionService(data, new TeamPermissionPolicy()))
|
||||
{
|
||||
ControllerContext = new ControllerContext
|
||||
{
|
||||
HttpContext = new DefaultHttpContext { User = user }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -164,6 +164,59 @@ public sealed class UpliftQueueReadTests
|
|||
new DateTime(2026, 3, 10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_RejectedStatus_OrdersMostRecentlyRejectedFirst()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var vendor = new Vendor { CompanyName = "Gateway", IsActive = true };
|
||||
var workOrder = new WorkOrder { WorkerOrderTitle = "Repair" };
|
||||
context.AddRange(vendor, workOrder);
|
||||
await context.SaveChangesAsync();
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
// Request order (3/1, 3/2, 3/3) deliberately disagrees with decision order.
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatch, "Rejected", new DateTime(2026, 3, 1), decided: new DateTime(2026, 3, 10)),
|
||||
Request(dispatch, "Rejected", new DateTime(2026, 3, 2), decided: new DateTime(2026, 3, 20)),
|
||||
Request(dispatch, "Rejected", new DateTime(2026, 3, 3), decided: new DateTime(2026, 3, 15)));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Rejected", null, 1, 25, CancellationToken.None);
|
||||
|
||||
result.Items.Select(i => i.DecidedAt).Should().Equal(
|
||||
new DateTime(2026, 3, 20),
|
||||
new DateTime(2026, 3, 15),
|
||||
new DateTime(2026, 3, 10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_RejectedStatus_ReturnsOnlyRejectedRequests_IncludingLegacyDenied()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var vendor = new Vendor { CompanyName = "Gateway", IsActive = true };
|
||||
var workOrder = new WorkOrder { WorkerOrderTitle = "Repair" };
|
||||
context.AddRange(vendor, workOrder);
|
||||
await context.SaveChangesAsync();
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 1)),
|
||||
Request(dispatch, "Approved", new DateTime(2026, 3, 2), decided: new DateTime(2026, 3, 3)),
|
||||
Request(dispatch, "Revoked", new DateTime(2026, 3, 4), decided: new DateTime(2026, 3, 5)),
|
||||
Request(dispatch, "Withdrawn", new DateTime(2026, 3, 6)),
|
||||
Request(dispatch, "Rejected", new DateTime(2026, 3, 7), decided: new DateTime(2026, 3, 8)),
|
||||
Request(dispatch, "Denied", new DateTime(2026, 2, 1), decided: new DateTime(2026, 2, 2)));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Rejected", null, 1, 25, CancellationToken.None);
|
||||
|
||||
result.Total.Should().Be(2);
|
||||
result.Items.Select(i => i.Status).Should().Equal("Rejected", "Rejected");
|
||||
result.Items.Select(i => i.DecidedAt).Should().Equal(
|
||||
new DateTime(2026, 3, 8),
|
||||
new DateTime(2026, 2, 2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_WithoutStatusFilter_KeepsHistoricalNewestRequestFirstOrder()
|
||||
{
|
||||
|
|
@ -558,6 +611,40 @@ public sealed class UpliftQueueReadTests
|
|||
result.Items.Single().DecidedByName.Should().Be("Grace Hopper");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_RejectedRow_CarriesRejecterRequesterDecisionTimeAndReason()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var (vendor, workOrder) = await SeedWorkOrderAsync(context, "WO-R", "SITE-R", "Plumbing");
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-R");
|
||||
context.Users.Add(new ApplicationUser { Id = "user-7", FirstName = "Ada", LastName = "Lovelace" });
|
||||
await context.SaveChangesAsync();
|
||||
context.DispatchUpliftRequests.Add(new DispatchUpliftRequest
|
||||
{
|
||||
DispatchId = dispatch.Id,
|
||||
Status = "Rejected",
|
||||
CreatedDate = new DateTime(2026, 3, 1),
|
||||
DecidedAt = new DateTime(2026, 3, 2, 16, 40, 0),
|
||||
DecidedByUserId = "user-7",
|
||||
DecisionNote = "Outside this work order's scope",
|
||||
RequestedByVendorName = "Gateway",
|
||||
RequiredTier = 1,
|
||||
RequestedNTE = 250m,
|
||||
NotificationStatus = "Pending"
|
||||
});
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Rejected", null, 1, 25, CancellationToken.None);
|
||||
|
||||
var row = result.Items.Single();
|
||||
row.DecidedByName.Should().Be("Ada Lovelace");
|
||||
row.RequestedByName.Should().Be("Gateway");
|
||||
row.DecidedAt.Should().Be(new DateTime(2026, 3, 2, 16, 40, 0));
|
||||
row.DecisionNote.Should().Be("Outside this work order's scope");
|
||||
row.WorkOrderNumber.Should().Be("WO-R");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_PendingExposureTotal_SumsEachPendingRequestsIncreaseAcrossTheQueue()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -0,0 +1,68 @@
|
|||
using Data.SeaHavenIndustries;
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SeaHaven.DataServices.Implementation;
|
||||
using Xunit;
|
||||
|
||||
namespace Api.SeaHavenIndustries.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The SLA clock and every "created"/"modified" display read these stamps as UTC, so the data layer
|
||||
/// must never write local server time into them.
|
||||
/// </summary>
|
||||
public class WorkOrderDataServiceTimestampTests
|
||||
{
|
||||
private static ApplicationDbContext NewContext()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
return new ApplicationDbContext(options);
|
||||
}
|
||||
|
||||
private static WorkOrder NewWorkOrder() =>
|
||||
new() { InternalWONumber = "WO-1", WorkerOrderTitle = "Leak", LocationId = 100 };
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_KeepsTheCreationTimeTheCallerSet()
|
||||
{
|
||||
await using var context = NewContext();
|
||||
var createdAt = new DateTime(2026, 9, 25, 14, 0, 0, DateTimeKind.Utc);
|
||||
var workOrder = NewWorkOrder();
|
||||
workOrder.CreatedDate = createdAt;
|
||||
|
||||
var saved = await new WorkOrderDataService(context).AddAsync(workOrder);
|
||||
|
||||
saved.CreatedDate.Should().Be(createdAt);
|
||||
saved.CreatedDate!.Value.Kind.Should().Be(DateTimeKind.Utc);
|
||||
(await context.workOrders.SingleAsync()).CreatedDate.Should().Be(createdAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_StampsUtcWhenTheCallerSetNoCreationTime()
|
||||
{
|
||||
await using var context = NewContext();
|
||||
var before = DateTime.UtcNow;
|
||||
|
||||
var saved = await new WorkOrderDataService(context).AddAsync(NewWorkOrder());
|
||||
|
||||
saved.CreatedDate.Should().NotBeNull();
|
||||
saved.CreatedDate!.Value.Kind.Should().Be(DateTimeKind.Utc);
|
||||
saved.CreatedDate.Value.Should().BeOnOrAfter(before).And.BeOnOrBefore(DateTime.UtcNow);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_StampsTheModificationTimeInUtc()
|
||||
{
|
||||
await using var context = NewContext();
|
||||
var service = new WorkOrderDataService(context);
|
||||
var saved = await service.AddAsync(NewWorkOrder());
|
||||
var before = DateTime.UtcNow;
|
||||
|
||||
await service.UpdateAsync(saved);
|
||||
|
||||
saved.LastModificationTime.Should().NotBeNull();
|
||||
saved.LastModificationTime!.Value.Kind.Should().Be(DateTimeKind.Utc);
|
||||
saved.LastModificationTime.Value.Should().BeOnOrAfter(before).And.BeOnOrBefore(DateTime.UtcNow);
|
||||
}
|
||||
}
|
||||
|
|
@ -55,20 +55,33 @@ namespace Api.SeaHavenIndustries.Controllers
|
|||
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
[Route("ChangePassword")]
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> ChangePassword(ChangePasswords usermodel, CancellationToken cancellationToken)
|
||||
{
|
||||
// [Compare] already rejects this during model validation; the check here keeps the
|
||||
// unconfirmed password from ever being set if that validation is bypassed.
|
||||
if (!string.Equals(usermodel.Newpassword, usermodel.Confirmpassword, StringComparison.Ordinal))
|
||||
return BadRequest(new Response { Status = "Password confirmation does not match", Message = "Passwords don't match" });
|
||||
|
||||
var userid = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "";
|
||||
var succeeded = await _authenticationService.ChangePasswordAsync(userid, usermodel.Currentpassword, usermodel.Confirmpassword, cancellationToken);
|
||||
if (succeeded)
|
||||
var result = await _authenticationService.ChangePasswordAsync(userid, usermodel.Currentpassword, usermodel.Newpassword, cancellationToken);
|
||||
return result.Status switch
|
||||
{
|
||||
return Ok(new Response { Status = "Success ", Message = "Password successfully changed" });
|
||||
}
|
||||
else
|
||||
return BadRequest(new Response { Status = "Old Password is incorrect" });
|
||||
ChangePasswordStatus.Succeeded =>
|
||||
Ok(new Response { Status = "Success ", Message = "Password successfully changed" }),
|
||||
ChangePasswordStatus.PasswordRejected =>
|
||||
BadRequest(new Response { Status = "Password does not meet requirements", Message = PasswordRequirementsMessage }),
|
||||
ChangePasswordStatus.Failed =>
|
||||
BadRequest(new Response { Status = "Password not changed", Message = "Your password could not be changed. Try again." }),
|
||||
_ => BadRequest(new Response { Status = "Old Password is incorrect", Message = "Current password is incorrect" })
|
||||
};
|
||||
}
|
||||
|
||||
private const string PasswordRequirementsMessage =
|
||||
"Password must be at least 6 characters and include one uppercase letter, one number, and one special character.";
|
||||
|
||||
[HttpPost]
|
||||
[Route("UpdateProfile")]
|
||||
public async Task<IActionResult> UserProfileUpdate([FromForm] User_DTO model, CancellationToken cancellationToken)
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Http;
|
|||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SeaHaven.Services.DTOs;
|
||||
using SeaHaven.Services.Exceptions;
|
||||
using SeaHaven.Services.Interfaces;
|
||||
|
||||
namespace Api.SeaHavenIndustries.Controllers
|
||||
|
|
@ -105,6 +106,9 @@ namespace Api.SeaHavenIndustries.Controllers
|
|||
ContactEmail = location.Email,
|
||||
location.Status,
|
||||
location.AccountId,
|
||||
ClientName = location.AccountName,
|
||||
location.AccountName,
|
||||
location.Notes,
|
||||
Contacts = location.Contacts?.Select(c => new { c.Id, c.Name, c.Phone }).ToList()
|
||||
};
|
||||
|
||||
|
|
@ -119,6 +123,10 @@ namespace Api.SeaHavenIndustries.Controllers
|
|||
await _locationService.CreateLocationFromRequestAsync(MapToCreateRequest(model), User, cancellationToken);
|
||||
return Ok(new DataResponse { Message = "Location Created Successfully", Status = "200" });
|
||||
}
|
||||
catch (SiteCodeConflictException)
|
||||
{
|
||||
return SiteCodeConflict();
|
||||
}
|
||||
catch (ValidationException vex)
|
||||
{
|
||||
var errors = string.Join(", ", vex.Errors.Select(e => e.ErrorMessage));
|
||||
|
|
@ -142,6 +150,10 @@ namespace Api.SeaHavenIndustries.Controllers
|
|||
await _locationService.UpdateLocationFromRequestAsync(id, MapToUpdateRequest(model), User, cancellationToken);
|
||||
return Ok(new DataResponse { Message = "Location Updated Successfully", Status = "200" });
|
||||
}
|
||||
catch (SiteCodeConflictException)
|
||||
{
|
||||
return SiteCodeConflict();
|
||||
}
|
||||
catch (ValidationException vex)
|
||||
{
|
||||
var errors = string.Join(", ", vex.Errors.Select(e => e.ErrorMessage));
|
||||
|
|
@ -161,17 +173,73 @@ namespace Api.SeaHavenIndustries.Controllers
|
|||
}
|
||||
}
|
||||
|
||||
[HttpPatch("{id}/contact-info")]
|
||||
public async Task<IActionResult> UpdateSiteContactInfo(int id, [FromBody] SiteContactInfoInput_DTO model, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _locationService.UpdateSiteContactInfoAsync(
|
||||
id,
|
||||
new SiteContactInfoRequestDTO { Contacts = MapSiteContacts(model.Contacts), Notes = model.Notes },
|
||||
User,
|
||||
cancellationToken);
|
||||
return Ok(new DataResponse { Message = "Site Updated Successfully", Status = "200" });
|
||||
}
|
||||
catch (ValidationException vex)
|
||||
{
|
||||
var errors = string.Join(", ", vex.Errors.Select(e => e.ErrorMessage));
|
||||
return BadRequest(new Response { Status = "Validation Error", Message = errors });
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new Response { Status = "Error", Message = "You are not allowed to edit this site." });
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
return NotFound(new Response { Status = "Error", Message = "Location not found" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(500, new Response { Status = "Error", Message = _logger.Sanitize(ex) });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("{id}/open-work-orders")]
|
||||
public async Task<IActionResult> GetOpenWorkOrders(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _locationService.GetOpenWorkOrdersAsync(id, User, cancellationToken);
|
||||
if (result == null)
|
||||
return NotFound(new Response { Status = "Error", Message = "Location not found" });
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new Response { Status = "Error", Message = "You are not allowed to view this site." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteLocation(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var found = await _locationService.DeleteLocationByIdAsync(id, cancellationToken);
|
||||
var found = await _locationService.DeleteLocationByIdAsync(id, User, cancellationToken);
|
||||
if (!found)
|
||||
return NotFound(new Response { Status = "Error", Message = "Location not found" });
|
||||
|
||||
return Ok(new DataResponse { Message = "Location Deleted Successfully", Status = "200" });
|
||||
}
|
||||
catch (SiteForbiddenException forbidden)
|
||||
{
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new Response { Status = "Error", Message = forbidden.Message });
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new Response { Status = "Error", Message = "You are not allowed to delete this site." });
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
return NotFound(new Response { Status = "Error", Message = "Location not found" });
|
||||
|
|
@ -188,6 +256,14 @@ namespace Api.SeaHavenIndustries.Controllers
|
|||
return await DeleteLocation(id, cancellationToken);
|
||||
}
|
||||
|
||||
private ObjectResult SiteCodeConflict() =>
|
||||
Conflict(new
|
||||
{
|
||||
Status = "Conflict",
|
||||
Message = SiteCodeConflictException.PublicMessage,
|
||||
Code = SiteCodeConflictException.ErrorCode
|
||||
});
|
||||
|
||||
private static LocationCreateRequestDTO MapToCreateRequest(Location_DTO model)
|
||||
{
|
||||
return new LocationCreateRequestDTO
|
||||
|
|
@ -202,6 +278,7 @@ namespace Api.SeaHavenIndustries.Controllers
|
|||
ContactEmail = model.ContactEmail,
|
||||
Status = model.Status,
|
||||
AccountId = model.GetAccountId(),
|
||||
Notes = model.Notes,
|
||||
Contacts = MapSiteContacts(model.Contacts)
|
||||
};
|
||||
}
|
||||
|
|
@ -220,6 +297,7 @@ namespace Api.SeaHavenIndustries.Controllers
|
|||
ContactEmail = model.ContactEmail,
|
||||
Status = model.Status,
|
||||
AccountId = model.GetAccountId(),
|
||||
Notes = model.Notes,
|
||||
Contacts = MapSiteContacts(model.Contacts)
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,10 +11,21 @@ namespace Api.SeaHavenIndustries.Controllers;
|
|||
public sealed class TeamMemberController : ControllerBase
|
||||
{
|
||||
private readonly ITeamMemberService _teamMemberService;
|
||||
private readonly ITeamPermissionService _permissionService;
|
||||
|
||||
public TeamMemberController(ITeamMemberService teamMemberService)
|
||||
public TeamMemberController(
|
||||
ITeamMemberService teamMemberService,
|
||||
ITeamPermissionService permissionService)
|
||||
{
|
||||
_teamMemberService = teamMemberService;
|
||||
_permissionService = permissionService;
|
||||
}
|
||||
|
||||
[HttpGet("me/permissions")]
|
||||
public async Task<IActionResult> GetMyPermissions(CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await _permissionService.GetEffectivePermissionsAsync(User, cancellationToken);
|
||||
return result.IsSuccess ? Ok(result.Value) : Unauthorized();
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ public sealed class TeamPermissionController : ControllerBase
|
|||
return result.Status switch
|
||||
{
|
||||
TeamPermissionResultStatus.Success => new OkObjectResult(result.Value),
|
||||
TeamPermissionResultStatus.Unauthorized => new UnauthorizedResult(),
|
||||
TeamPermissionResultStatus.Forbidden => new ForbidResult(),
|
||||
TeamPermissionResultStatus.NotFound => new NotFoundObjectResult(
|
||||
new Response { Status = "Error", Message = "User not found." }),
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ namespace Api.SeaHavenIndustries.DTOs
|
|||
public string? ContactEmail { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public string? AccountId { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public List<SiteContactInput_DTO>? Contacts { get; set; }
|
||||
|
||||
public int? GetAccountId() => LocationAccountIdMapping.ParseOptional(AccountId);
|
||||
|
|
|
|||
|
|
@ -11,6 +11,13 @@ namespace Api.SeaHavenIndustries.DTOs
|
|||
public string? Phone { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Contacts and notes edited from the work-order Site dialog.</summary>
|
||||
public class SiteContactInfoInput_DTO
|
||||
{
|
||||
public List<SiteContactInput_DTO>? Contacts { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
public class Location_DTO
|
||||
{
|
||||
public string? Title { get; set; }
|
||||
|
|
@ -24,6 +31,7 @@ namespace Api.SeaHavenIndustries.DTOs
|
|||
public string? ContactEmail { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public string? AccountId { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public List<SiteContactInput_DTO>? Contacts { get; set; }
|
||||
|
||||
public int? GetAccountId() => LocationAccountIdMapping.ParseOptional(AccountId);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
using Data.SeaHavenIndustries;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Api.SeaHavenIndustries.Infrastructure
|
||||
{
|
||||
public static class IdentityRegistration
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers ASP.NET Identity for the API with the shared password policy.
|
||||
/// Program.cs and the behavior tests both compose Identity through this
|
||||
/// method so the rule under test is the rule that runs.
|
||||
/// </summary>
|
||||
public static IdentityBuilder AddSeaHavenIdentity(this IServiceCollection services)
|
||||
{
|
||||
return services.AddIdentity<ApplicationUser, IdentityRole>(options =>
|
||||
{
|
||||
options.User.RequireUniqueEmail = false;
|
||||
IdentityPasswordPolicy.Apply(options.Password);
|
||||
})
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
using Api.SeaHavenIndustries.Helper;
|
||||
using Api.SeaHavenIndustries.HostedServices;
|
||||
using Api.SeaHavenIndustries.Infrastructure;
|
||||
using Api.SeaHavenIndustries.Middleware;
|
||||
using Api.SeaHavenIndustries.Observability;
|
||||
using Api.SeaHavenIndustries.Options;
|
||||
|
|
@ -43,12 +44,7 @@ ConfigurationManager configuration = builder.Configuration;
|
|||
|
||||
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
|
||||
|
||||
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
|
||||
{
|
||||
options.User.RequireUniqueEmail = false;
|
||||
})
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
builder.Services.AddSeaHavenIdentity();
|
||||
|
||||
builder.Services.AddControllers(options =>
|
||||
{
|
||||
|
|
|
|||
47
Data.SeaHavenIndustries/Auth/IdentityPasswordPolicy.cs
Normal file
47
Data.SeaHavenIndustries/Auth/IdentityPasswordPolicy.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Data.SeaHavenIndustries
|
||||
{
|
||||
/// <summary>
|
||||
/// The single password rule for every surface that sets a password: at least
|
||||
/// six characters with one uppercase letter, one number, and one special
|
||||
/// character. Lowercase letters are deliberately not required so the server
|
||||
/// accepts exactly what the four-item checklist in the web app marks as met.
|
||||
/// </summary>
|
||||
public static class IdentityPasswordPolicy
|
||||
{
|
||||
public const int MinimumLength = 6;
|
||||
|
||||
public static void Apply(PasswordOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
|
||||
options.RequiredLength = MinimumLength;
|
||||
options.RequireUppercase = true;
|
||||
options.RequireDigit = true;
|
||||
options.RequireNonAlphanumeric = true;
|
||||
options.RequireLowercase = false;
|
||||
options.RequiredUniqueChars = 1;
|
||||
}
|
||||
|
||||
private static readonly HashSet<string> PolicyErrorCodes = new(StringComparer.Ordinal)
|
||||
{
|
||||
nameof(IdentityErrorDescriber.PasswordTooShort),
|
||||
nameof(IdentityErrorDescriber.PasswordRequiresUpper),
|
||||
nameof(IdentityErrorDescriber.PasswordRequiresLower),
|
||||
nameof(IdentityErrorDescriber.PasswordRequiresDigit),
|
||||
nameof(IdentityErrorDescriber.PasswordRequiresNonAlphanumeric),
|
||||
nameof(IdentityErrorDescriber.PasswordRequiresUniqueChars)
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// True when Identity refused the password itself. Other failures, such as a
|
||||
/// concurrency conflict, must not be reported to the user as a weak password.
|
||||
/// </summary>
|
||||
public static bool IsPolicyRejection(IdentityResult result)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(result);
|
||||
return result.Errors.Any(error => PolicyErrorCodes.Contains(error.Code));
|
||||
}
|
||||
}
|
||||
}
|
||||
4216
Data.SeaHavenIndustries/Migrations/20260925141509_AddLocationNotes.Designer.cs
generated
Normal file
4216
Data.SeaHavenIndustries/Migrations/20260925141509_AddLocationNotes.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,28 @@
|
|||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Data.SeaHavenIndustries.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddLocationNotes : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Notes",
|
||||
table: "Locations",
|
||||
type: "nvarchar(max)",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Notes",
|
||||
table: "Locations");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1616,6 +1616,9 @@ namespace Data.SeaHavenIndustries.Migrations
|
|||
b.Property<string>("Name")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Notes")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
|
|
|
|||
|
|
@ -27,6 +27,9 @@ namespace Data.SeaHavenIndustries
|
|||
public string? ExternalSource { get; set; }
|
||||
public string? ExternalLocationId { get; set; }
|
||||
|
||||
/// <summary>Free-text site notes, edited from the work-order Site dialog.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
// Navigation Properties
|
||||
public ICollection<Template>? Templates { get; set; }
|
||||
public ICollection<WorkOrder>? workOrders { get; set; }
|
||||
|
|
|
|||
|
|
@ -21,6 +21,12 @@ Both run in `us-east-1` on the .NET 8 Amazon Linux 2023 platform. Terraform in
|
|||
`terraform/live/` owns the environments; GitHub Actions owns the application
|
||||
versions. There is no production environment yet.
|
||||
|
||||
Stored created, modified and deletion times are UTC: the API stamps them with
|
||||
`DateTime.UtcNow`, whatever the host's time zone. The API has only ever run on
|
||||
Linux Elastic Beanstalk hosts left at their UTC default (nothing in Terraform,
|
||||
`.ebextensions` or `.platform` sets a time zone), so rows written before the
|
||||
switch from `DateTime.Now` are already UTC and need no backfill.
|
||||
|
||||
## Architecture
|
||||
|
||||
```text
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ namespace SeaHaven.DataServices.Helpers
|
|||
w.ServiceNameSnapshot,
|
||||
w.SiteCode,
|
||||
LocationName = w.Locations != null ? w.Locations.Name : null,
|
||||
SiteNotes = w.Locations != null ? w.Locations.Notes : null,
|
||||
WoPocName = w.PocName,
|
||||
WoPocPhone = w.PocPhone,
|
||||
WoPocNotes = w.PocNotes,
|
||||
|
|
@ -134,7 +135,7 @@ namespace SeaHaven.DataServices.Helpers
|
|||
var pocPhone = primaryFrozenPoc?.Phone
|
||||
?? FirstNotBlank(w.WoPocPhone, w.ContactPoc?.PhoneNumber, w.SitePoc?.PhoneNumber);
|
||||
var pocNotes = frozenPoc?.Notes
|
||||
?? FirstNotBlank(w.WoPocNotes, w.ContactPoc?.Notes);
|
||||
?? FirstNotBlank(w.WoPocNotes, w.ContactPoc?.Notes, w.SiteNotes);
|
||||
var techPhone = !string.IsNullOrWhiteSpace(w.DispatchTechPhone)
|
||||
? w.DispatchTechPhone
|
||||
: (!string.IsNullOrWhiteSpace(w.WoTechPhone) ? w.WoTechPhone : w.VendorPhone);
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Accounts> AddAsync(Accounts account)
|
||||
{
|
||||
account.CreatedDate = DateTime.Now;
|
||||
account.CreatedDate = DateTime.UtcNow;
|
||||
await _context.Accounts.AddAsync(account);
|
||||
await _context.SaveChangesAsync();
|
||||
return account;
|
||||
|
|
@ -72,7 +72,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(Accounts account)
|
||||
{
|
||||
account.LastModificationTime = DateTime.Now;
|
||||
account.LastModificationTime = DateTime.UtcNow;
|
||||
_context.Accounts.Update(account);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Assets> AddAsync(Assets asset)
|
||||
{
|
||||
asset.CreatedDate = DateTime.Now;
|
||||
asset.CreatedDate = DateTime.UtcNow;
|
||||
await _context.Assets.AddAsync(asset);
|
||||
await _context.SaveChangesAsync();
|
||||
return asset;
|
||||
|
|
@ -80,7 +80,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(Assets asset)
|
||||
{
|
||||
asset.LastModificationTime = DateTime.Now;
|
||||
asset.LastModificationTime = DateTime.UtcNow;
|
||||
_context.Assets.Update(asset);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Category> AddAsync(Category category)
|
||||
{
|
||||
category.CreatedDate = DateTime.Now;
|
||||
category.CreatedDate = DateTime.UtcNow;
|
||||
await _context.Categories.AddAsync(category);
|
||||
await _context.SaveChangesAsync();
|
||||
return category;
|
||||
|
|
@ -33,7 +33,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(Category category)
|
||||
{
|
||||
category.LastModificationTime = DateTime.Now;
|
||||
category.LastModificationTime = DateTime.UtcNow;
|
||||
_context.Categories.Update(category);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
{
|
||||
return await _context.Locations
|
||||
.AsNoTracking()
|
||||
.Where(n => n.IsDeleted != true)
|
||||
.Select(n => new Locations
|
||||
{
|
||||
Id = n.Id,
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Contacts> AddAsync(Contacts contact)
|
||||
{
|
||||
contact.CreatedDate = DateTime.Now;
|
||||
contact.CreatedDate = DateTime.UtcNow;
|
||||
await _context.Contacts.AddAsync(contact);
|
||||
await _context.SaveChangesAsync();
|
||||
return contact;
|
||||
|
|
@ -108,7 +108,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(Contacts contact)
|
||||
{
|
||||
contact.LastModificationTime = DateTime.Now;
|
||||
contact.LastModificationTime = DateTime.UtcNow;
|
||||
_context.Contacts.Update(contact);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
@ -130,15 +130,15 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<bool> EmailExistsAsync(string email, int? excludeId = null)
|
||||
{
|
||||
return await _context.Contacts.AnyAsync(c =>
|
||||
c.Email == email &&
|
||||
return await _context.Contacts.AnyAsync(c =>
|
||||
c.Email == email &&
|
||||
(excludeId == null || c.Id != excludeId));
|
||||
}
|
||||
|
||||
public async Task<bool> PhoneExistsAsync(string phone, int? excludeId = null)
|
||||
{
|
||||
return await _context.Contacts.AnyAsync(c =>
|
||||
c.PhoneNumber == phone &&
|
||||
return await _context.Contacts.AnyAsync(c =>
|
||||
c.PhoneNumber == phone &&
|
||||
(excludeId == null || c.Id != excludeId));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Dispatch> AddAsync(Dispatch dispatch)
|
||||
{
|
||||
dispatch.CreatedDate = DateTime.Now;
|
||||
dispatch.CreatedDate = DateTime.UtcNow;
|
||||
await _context.Dispatches.AddAsync(dispatch);
|
||||
await _context.SaveChangesAsync();
|
||||
return dispatch;
|
||||
|
|
@ -93,7 +93,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(Dispatch dispatch)
|
||||
{
|
||||
dispatch.LastModificationTime = DateTime.Now;
|
||||
dispatch.LastModificationTime = DateTime.UtcNow;
|
||||
_context.Dispatches.Update(dispatch);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Employee> AddAsync(Employee employee)
|
||||
{
|
||||
employee.CreatedDate = DateTime.Now;
|
||||
employee.CreatedDate = DateTime.UtcNow;
|
||||
await _context.Employees.AddAsync(employee);
|
||||
await _context.SaveChangesAsync();
|
||||
return employee;
|
||||
|
|
@ -80,7 +80,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(Employee employee)
|
||||
{
|
||||
employee.LastModificationTime = DateTime.Now;
|
||||
employee.LastModificationTime = DateTime.UtcNow;
|
||||
_context.Employees.Update(employee);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -88,7 +88,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<FollowUps> AddAsync(FollowUps followUp)
|
||||
{
|
||||
followUp.CreatedDate = DateTime.Now;
|
||||
followUp.CreatedDate = DateTime.UtcNow;
|
||||
await _context.FollowUps.AddAsync(followUp);
|
||||
await _context.SaveChangesAsync();
|
||||
return followUp;
|
||||
|
|
@ -96,7 +96,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(FollowUps followUp)
|
||||
{
|
||||
followUp.LastModificationTime = DateTime.Now;
|
||||
followUp.LastModificationTime = DateTime.UtcNow;
|
||||
_context.FollowUps.Update(followUp);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
@ -218,7 +218,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<FollowUps> AddAsync(FollowUps followUp, CancellationToken cancellationToken)
|
||||
{
|
||||
followUp.CreatedDate = DateTime.Now;
|
||||
followUp.CreatedDate = DateTime.UtcNow;
|
||||
await _context.FollowUps.AddAsync(followUp, cancellationToken);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
return followUp;
|
||||
|
|
@ -226,7 +226,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(FollowUps followUp, CancellationToken cancellationToken)
|
||||
{
|
||||
followUp.LastModificationTime = DateTime.Now;
|
||||
followUp.LastModificationTime = DateTime.UtcNow;
|
||||
_context.FollowUps.Update(followUp);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
|
@ -238,7 +238,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
return false;
|
||||
|
||||
entity.Status = status;
|
||||
entity.LastModificationTime = DateTime.Now;
|
||||
entity.LastModificationTime = DateTime.UtcNow;
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
using Data.SeaHavenIndustries;
|
||||
using Data.SeaHavenIndustries.Enums;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SeaHaven.DataServices.Helpers;
|
||||
using SeaHaven.DataServices.Interfaces;
|
||||
|
||||
namespace SeaHaven.DataServices.Implementation
|
||||
|
|
@ -15,25 +17,25 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Locations?> GetByIdAsync(int id)
|
||||
{
|
||||
return await _context.Locations.FindAsync(id);
|
||||
return await _context.Locations.FirstOrDefaultAsync(l => l.Id == id && l.IsDeleted != true);
|
||||
}
|
||||
|
||||
public async Task<Locations?> GetByIdWithDetailsAsync(int id)
|
||||
{
|
||||
return await _context.Locations
|
||||
.FirstOrDefaultAsync(l => l.Id == id);
|
||||
.FirstOrDefaultAsync(l => l.Id == id && l.IsDeleted != true);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Locations>> GetAllAsync()
|
||||
{
|
||||
return await _context.Locations.ToListAsync();
|
||||
return await _context.Locations.Where(l => l.IsDeleted != true).ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Locations>> GetByAccountIdAsync(int accountId)
|
||||
{
|
||||
return await _context.Locations
|
||||
.AsNoTracking()
|
||||
.Where(l => l.AccountId == accountId)
|
||||
.Where(l => l.AccountId == accountId && l.IsDeleted != true)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
|
|
@ -43,7 +45,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
{
|
||||
var row = await _context.Locations
|
||||
.AsNoTracking()
|
||||
.Where(l => l.Id == locationId)
|
||||
.Where(l => l.Id == locationId && l.IsDeleted != true)
|
||||
.Select(l => new { l.AccountId })
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
|
|
@ -55,7 +57,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
int pageSize,
|
||||
string? search = null)
|
||||
{
|
||||
var query = _context.Locations.AsQueryable();
|
||||
var query = _context.Locations.Where(l => l.IsDeleted != true);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(search))
|
||||
{
|
||||
|
|
@ -80,7 +82,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
{
|
||||
var query = _context.Locations
|
||||
.AsNoTracking()
|
||||
.Where(l => l.AccountId != null);
|
||||
.Where(l => l.AccountId != null && l.IsDeleted != true);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(search))
|
||||
{
|
||||
|
|
@ -98,7 +100,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Locations> AddAsync(Locations location)
|
||||
{
|
||||
location.CreatedDate = DateTime.Now;
|
||||
location.CreatedDate = DateTime.UtcNow;
|
||||
await _context.Locations.AddAsync(location);
|
||||
await _context.SaveChangesAsync();
|
||||
return location;
|
||||
|
|
@ -106,7 +108,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(Locations location)
|
||||
{
|
||||
location.LastModificationTime = DateTime.Now;
|
||||
location.LastModificationTime = DateTime.UtcNow;
|
||||
_context.Locations.Update(location);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
@ -123,12 +125,12 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<bool> ExistsAsync(int id)
|
||||
{
|
||||
return await _context.Locations.AnyAsync(l => l.Id == id);
|
||||
return await _context.Locations.AnyAsync(l => l.Id == id && l.IsDeleted != true);
|
||||
}
|
||||
|
||||
public async Task<int> CountAsync()
|
||||
{
|
||||
return await _context.Locations.CountAsync();
|
||||
return await _context.Locations.CountAsync(l => l.IsDeleted != true);
|
||||
}
|
||||
|
||||
public async Task<(List<Locations> Items, int TotalCount)> GetListPagedAsync(
|
||||
|
|
@ -142,7 +144,8 @@ namespace SeaHaven.DataServices.Implementation
|
|||
{
|
||||
IQueryable<Locations> query = _context.Locations
|
||||
.AsNoTracking()
|
||||
.Include(l => l.Account);
|
||||
.Include(l => l.Account)
|
||||
.Where(l => l.IsDeleted != true);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(search))
|
||||
{
|
||||
|
|
@ -200,15 +203,16 @@ namespace SeaHaven.DataServices.Implementation
|
|||
{
|
||||
return await _context.Locations
|
||||
.AsNoTracking()
|
||||
.Include(l => l.Account)
|
||||
.Include(l => l.Contacts.Where(c => c.IsDeleted != true))
|
||||
.FirstOrDefaultAsync(l => l.Id == id, cancellationToken);
|
||||
.FirstOrDefaultAsync(l => l.Id == id && l.IsDeleted != true, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<Locations?> GetByIdForUpdateAsync(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.Locations
|
||||
.Include(l => l.Contacts)
|
||||
.FirstOrDefaultAsync(l => l.Id == id, cancellationToken);
|
||||
.FirstOrDefaultAsync(l => l.Id == id && l.IsDeleted != true, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Contacts>> GetSiteContactsByLocationIdsAsync(
|
||||
|
|
@ -228,7 +232,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<Locations> AddAsync(Locations location, CancellationToken cancellationToken)
|
||||
{
|
||||
location.CreatedDate = DateTime.Now;
|
||||
location.CreatedDate = DateTime.UtcNow;
|
||||
await _context.Locations.AddAsync(location, cancellationToken);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
return location;
|
||||
|
|
@ -236,36 +240,72 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(Locations location, CancellationToken cancellationToken)
|
||||
{
|
||||
location.LastModificationTime = DateTime.Now;
|
||||
location.LastModificationTime = DateTime.UtcNow;
|
||||
_context.Locations.Update(location);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteByIdAsync(int id, CancellationToken cancellationToken)
|
||||
public async Task<bool> SiteCodeExistsAsync(
|
||||
string siteCode,
|
||||
int? accountId,
|
||||
int? excludeLocationId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.Locations
|
||||
.Include(l => l.Contacts)
|
||||
.FirstOrDefaultAsync(l => l.Id == id, cancellationToken);
|
||||
if (entity == null)
|
||||
return false;
|
||||
var normalized = siteCode.Trim().ToUpperInvariant();
|
||||
|
||||
var now = DateTime.Now;
|
||||
foreach (var contact in entity.Contacts ?? Enumerable.Empty<Contacts>())
|
||||
{
|
||||
if (contact.IsDeleted != true)
|
||||
{
|
||||
contact.IsDeleted = true;
|
||||
contact.DeletionTime = now;
|
||||
}
|
||||
|
||||
contact.LocationId = null;
|
||||
}
|
||||
|
||||
_context.Locations.Remove(entity);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
return true;
|
||||
return await _context.Locations
|
||||
.AsNoTracking()
|
||||
.Where(l => l.IsDeleted != true
|
||||
&& l.AccountId == accountId
|
||||
&& l.Name != null
|
||||
&& l.Name.Trim().ToUpper() == normalized)
|
||||
.Where(l => excludeLocationId == null || l.Id != excludeLocationId)
|
||||
.AnyAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<(int Count, IReadOnlyList<int> Ids)> GetOpenWorkOrderIdsAsync(
|
||||
int locationId,
|
||||
string? siteCode,
|
||||
int? siteAccountId,
|
||||
int? callerAccountId,
|
||||
int maxIds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var code = string.IsNullOrWhiteSpace(siteCode) ? null : siteCode.Trim().ToUpper();
|
||||
|
||||
var query = _context.workOrders
|
||||
.AsNoTracking()
|
||||
.Where(w => w.IsDeleted != true
|
||||
&& (w.LocationId == locationId
|
||||
|| (code != null
|
||||
&& w.LocationId == null
|
||||
&& w.SiteCode != null
|
||||
&& w.SiteCode.Trim().ToUpper() == code
|
||||
&& (w.AccountId == null || w.AccountId == siteAccountId))));
|
||||
|
||||
if (callerAccountId is int accountId)
|
||||
query = query.Where(w => w.AccountId == accountId);
|
||||
|
||||
query = WorkOrderBoardQueryFilters.ApplyStatusFilter(query, OpenLifecycleStatuses);
|
||||
|
||||
var count = await query.CountAsync(cancellationToken);
|
||||
if (count == 0)
|
||||
return (0, Array.Empty<int>());
|
||||
|
||||
var ids = await query
|
||||
.OrderBy(w => w.Id)
|
||||
.Select(w => w.Id)
|
||||
.Take(maxIds)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return (count, ids);
|
||||
}
|
||||
|
||||
private static readonly IReadOnlyList<LifecycleStatus> OpenLifecycleStatuses = Enum
|
||||
.GetValues<LifecycleStatus>()
|
||||
.Where(status => !LifecycleStatusSets.Terminal.Contains(status))
|
||||
.ToList();
|
||||
|
||||
public async Task<(IEnumerable<object> Items, int TotalCount)> GetAddressbookPagedAsync(
|
||||
int page,
|
||||
int pageSize,
|
||||
|
|
@ -273,7 +313,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
{
|
||||
search ??= "";
|
||||
|
||||
var query = _context.Locations.AsQueryable();
|
||||
var query = _context.Locations.Where(l => l.IsDeleted != true);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(search))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -46,8 +46,8 @@ namespace SeaHaven.DataServices.Implementation
|
|||
}
|
||||
|
||||
public async Task<(IEnumerable<PMSchedules> Items, int TotalCount)> GetPagedAsync(
|
||||
int page,
|
||||
int pageSize,
|
||||
int page,
|
||||
int pageSize,
|
||||
string? search = null)
|
||||
{
|
||||
var query = _context.PMSchedules.AsQueryable();
|
||||
|
|
@ -64,7 +64,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<PMSchedules> AddAsync(PMSchedules schedule)
|
||||
{
|
||||
schedule.CreatedDate = DateTime.Now;
|
||||
schedule.CreatedDate = DateTime.UtcNow;
|
||||
await _context.PMSchedules.AddAsync(schedule);
|
||||
await _context.SaveChangesAsync();
|
||||
return schedule;
|
||||
|
|
@ -72,7 +72,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(PMSchedules schedule)
|
||||
{
|
||||
schedule.LastModificationTime = DateTime.Now;
|
||||
schedule.LastModificationTime = DateTime.UtcNow;
|
||||
_context.PMSchedules.Update(schedule);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,9 @@ namespace SeaHaven.DataServices.Implementation
|
|||
public class UpliftDataService : IUpliftDataService
|
||||
{
|
||||
private static readonly ConcurrentDictionary<int, SemaphoreSlim> WorkOrderGates = new();
|
||||
|
||||
// The Rejected queue also surfaces the legacy "Denied" spelling, which reads as Rejected.
|
||||
private static readonly string[] RejectedStatuses = { "Rejected", "Denied" };
|
||||
private readonly ApplicationDbContext _context;
|
||||
|
||||
public UpliftDataService(ApplicationDbContext context)
|
||||
|
|
@ -46,7 +49,9 @@ namespace SeaHaven.DataServices.Implementation
|
|||
&& (d.IsDeleted == null || d.IsDeleted == false)
|
||||
select new { u, d, v, ev, effectiveWorkOrderId, workOrder, reqUser, decUser };
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(status))
|
||||
if (string.Equals(status, "Rejected", StringComparison.Ordinal))
|
||||
query = query.Where(x => RejectedStatuses.Contains(x.u.Status));
|
||||
else if (!string.IsNullOrWhiteSpace(status))
|
||||
query = query.Where(x => x.u.Status == status);
|
||||
if (tier.HasValue)
|
||||
query = query.Where(x => x.u.RequiredTier == tier.Value);
|
||||
|
|
@ -54,12 +59,13 @@ namespace SeaHaven.DataServices.Implementation
|
|||
var total = await query.CountAsync(cancellationToken);
|
||||
|
||||
// Approval queue read contract: the actionable queue (Pending) surfaces the
|
||||
// oldest request first; the decision log (Approved) surfaces the most
|
||||
// recently decided first. Every other read keeps the historical
|
||||
// oldest request first; the decision logs (Approved, Rejected) surface the
|
||||
// most recently decided first. Every other read keeps the historical
|
||||
// newest-request-first order. Id is the deterministic tiebreaker.
|
||||
if (string.Equals(status, "Pending", StringComparison.Ordinal))
|
||||
query = query.OrderBy(x => x.u.CreatedDate).ThenBy(x => x.u.Id);
|
||||
else if (string.Equals(status, "Approved", StringComparison.Ordinal))
|
||||
else if (string.Equals(status, "Approved", StringComparison.Ordinal)
|
||||
|| string.Equals(status, "Rejected", StringComparison.Ordinal))
|
||||
query = query.OrderByDescending(x => x.u.DecidedAt).ThenByDescending(x => x.u.Id);
|
||||
else
|
||||
query = query.OrderByDescending(x => x.u.CreatedDate).ThenByDescending(x => x.u.Id);
|
||||
|
|
|
|||
|
|
@ -150,7 +150,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
}
|
||||
|
||||
public Task<bool> LocationExistsAsync(int locationId, CancellationToken cancellationToken)
|
||||
=> _context.Locations.AnyAsync(location => location.Id == locationId, cancellationToken);
|
||||
=> _context.Locations.AnyAsync(location => location.Id == locationId && location.IsDeleted != true, cancellationToken);
|
||||
|
||||
public async Task<Dictionary<int, Vendor>> GetVendorsByIdsAsync(IReadOnlyCollection<int> vendorIds, CancellationToken cancellationToken)
|
||||
=> await _context.Vendors.Where(vendor => vendorIds.Contains(vendor.Id))
|
||||
|
|
|
|||
|
|
@ -193,7 +193,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task<WorkOrder> AddAsync(WorkOrder workOrder)
|
||||
{
|
||||
workOrder.CreatedDate = DateTime.Now;
|
||||
workOrder.CreatedDate ??= DateTime.UtcNow;
|
||||
await _context.workOrders.AddAsync(workOrder);
|
||||
await _context.SaveChangesAsync();
|
||||
return workOrder;
|
||||
|
|
@ -201,7 +201,7 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
public async Task UpdateAsync(WorkOrder workOrder)
|
||||
{
|
||||
workOrder.LastModificationTime = DateTime.Now;
|
||||
workOrder.LastModificationTime = DateTime.UtcNow;
|
||||
_context.workOrders.Update(workOrder);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,6 +52,31 @@ namespace SeaHaven.DataServices.Interfaces
|
|||
|
||||
Task<Locations> AddAsync(Locations location, CancellationToken cancellationToken);
|
||||
Task UpdateAsync(Locations location, CancellationToken cancellationToken);
|
||||
Task<bool> DeleteByIdAsync(int id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// True when a live (not deleted) site of the same account already uses
|
||||
/// <paramref name="siteCode"/>, compared trimmed and case-insensitively.
|
||||
/// A null account matches only other sites without an account.
|
||||
/// </summary>
|
||||
Task<bool> SiteCodeExistsAsync(
|
||||
string siteCode,
|
||||
int? accountId,
|
||||
int? excludeLocationId,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Open (not Completed or Canceled, legacy status aware) and not deleted work
|
||||
/// orders that reference the site by id, or by site code when they carry no
|
||||
/// location id and no other account. <paramref name="callerAccountId"/>
|
||||
/// narrows to one account. Returns the full count and at most
|
||||
/// <paramref name="maxIds"/> ids, ascending.
|
||||
/// </summary>
|
||||
Task<(int Count, IReadOnlyList<int> Ids)> GetOpenWorkOrderIdsAsync(
|
||||
int locationId,
|
||||
string? siteCode,
|
||||
int? siteAccountId,
|
||||
int? callerAccountId,
|
||||
int maxIds,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
174
SeaHaven.Services.Tests/TeamEffectivePermissionsTests.cs
Normal file
174
SeaHaven.Services.Tests/TeamEffectivePermissionsTests.cs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
using Data.SeaHavenIndustries.Enums;
|
||||
using FluentAssertions;
|
||||
using SeaHaven.DataServices.Dto;
|
||||
using SeaHaven.DataServices.Interfaces;
|
||||
using SeaHaven.Services.Constants;
|
||||
using SeaHaven.Services.DTOs;
|
||||
using SeaHaven.Services.Implementation;
|
||||
using System.Security.Claims;
|
||||
using Xunit;
|
||||
|
||||
namespace SeaHaven.Services.Tests;
|
||||
|
||||
public sealed class TeamEffectivePermissionsTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Scheduler_Receives_Role_Defaults()
|
||||
{
|
||||
var data = new FakeUsers().Add("u1", "Scheduler");
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(Caller("u1"), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.Should().BeTrue();
|
||||
result.Value!.Permissions.Should().Contain(new[]
|
||||
{
|
||||
TeamPermissionKeys.CreateCompletionDocTemplates,
|
||||
TeamPermissionKeys.EditCompletionDocTemplates
|
||||
});
|
||||
result.Value.Permissions.Should().NotContain(TeamPermissionKeys.DeleteCompletionDocTemplates);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Grant_Override_Adds_A_Key_Outside_The_Role_Defaults()
|
||||
{
|
||||
var data = new FakeUsers().Add(
|
||||
"u1", "Dispatcher", (TeamPermissionKeys.CreateCompletionDocTemplates, UserPermissionState.Allow));
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(Caller("u1"), CancellationToken.None);
|
||||
|
||||
result.Value!.Permissions.Should().Contain(TeamPermissionKeys.CreateCompletionDocTemplates);
|
||||
result.Value.Permissions.Should().NotContain(TeamPermissionKeys.EditCompletionDocTemplates);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Revoke_Override_Removes_A_Role_Default()
|
||||
{
|
||||
var data = new FakeUsers().Add(
|
||||
"u1", "Scheduler", (TeamPermissionKeys.EditCompletionDocTemplates, UserPermissionState.Deny));
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(Caller("u1"), CancellationToken.None);
|
||||
|
||||
result.Value!.Permissions.Should().NotContain(TeamPermissionKeys.EditCompletionDocTemplates);
|
||||
result.Value.Permissions.Should().Contain(TeamPermissionKeys.CreateCompletionDocTemplates);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_Holds_Every_Key_Even_With_A_Revoke_Override()
|
||||
{
|
||||
var data = new FakeUsers().Add(
|
||||
"u1", "Admin", (TeamPermissionKeys.DeleteCompletionDocTemplates, UserPermissionState.Deny));
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(Caller("u1"), CancellationToken.None);
|
||||
|
||||
result.Value!.Permissions.Should().Equal(TeamPermissionKeys.All);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Keys_Match_What_The_Write_Path_Enforces()
|
||||
{
|
||||
var data = new FakeUsers().Add(
|
||||
"u1", "Dispatcher",
|
||||
(TeamPermissionKeys.CreateCompletionDocTemplates, UserPermissionState.Allow),
|
||||
(TeamPermissionKeys.CreateSites, UserPermissionState.Deny));
|
||||
var policy = new TeamPermissionPolicy();
|
||||
var user = await data.GetUserAsync("u1", CancellationToken.None);
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(Caller("u1"), CancellationToken.None);
|
||||
|
||||
result.Value!.Permissions.Should().Equal(
|
||||
TeamPermissionKeys.All.Where(key => policy.IsAllowed(user!.RoleName, key, user.Overrides)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reads_Only_The_Caller_Identified_By_The_Token()
|
||||
{
|
||||
var data = new FakeUsers()
|
||||
.Add("u1", "Dispatcher")
|
||||
.Add("u2", "Dispatcher", (TeamPermissionKeys.DeleteWorkOrders, UserPermissionState.Allow));
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(Caller("u1"), cancellation.Token);
|
||||
|
||||
result.Value!.Permissions.Should().NotContain(TeamPermissionKeys.DeleteWorkOrders);
|
||||
data.RequestedUserIds.Should().Equal("u1");
|
||||
data.LastToken.Should().Be(cancellation.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unauthenticated_Caller_Is_Rejected_Before_Data_Access()
|
||||
{
|
||||
var data = new FakeUsers().Add("u1", "Admin");
|
||||
var anonymous = new ClaimsPrincipal(new ClaimsIdentity(
|
||||
new[] { new Claim(ClaimTypes.NameIdentifier, "u1") }));
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(anonymous, CancellationToken.None);
|
||||
|
||||
result.Status.Should().Be(TeamPermissionResultStatus.Unauthorized);
|
||||
data.RequestedUserIds.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Token_Without_A_User_Id_Is_Rejected_Before_Data_Access()
|
||||
{
|
||||
var data = new FakeUsers().Add("u1", "Admin");
|
||||
var noId = new ClaimsPrincipal(new ClaimsIdentity(
|
||||
new[] { new Claim(ClaimTypes.Role, "Admin") }, "test"));
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(noId, CancellationToken.None);
|
||||
|
||||
result.Status.Should().Be(TeamPermissionResultStatus.Unauthorized);
|
||||
data.RequestedUserIds.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Token_For_A_Removed_User_Is_Rejected()
|
||||
{
|
||||
var data = new FakeUsers();
|
||||
|
||||
var result = await Service(data).GetEffectivePermissionsAsync(Caller("gone"), CancellationToken.None);
|
||||
|
||||
result.Status.Should().Be(TeamPermissionResultStatus.Unauthorized);
|
||||
result.Value.Should().BeNull();
|
||||
}
|
||||
|
||||
private static TeamPermissionService Service(FakeUsers data) =>
|
||||
new(data, new TeamPermissionPolicy());
|
||||
|
||||
private static ClaimsPrincipal Caller(string userId) =>
|
||||
new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) }, "test"));
|
||||
|
||||
private sealed class FakeUsers : ITeamPermissionOverrideDataService
|
||||
{
|
||||
private readonly Dictionary<string, TeamPermissionUserData> _users = new();
|
||||
|
||||
public List<string> RequestedUserIds { get; } = new();
|
||||
public CancellationToken LastToken { get; private set; }
|
||||
|
||||
public FakeUsers Add(string userId, string role, params (string Key, UserPermissionState State)[] overrides)
|
||||
{
|
||||
_users[userId] = new TeamPermissionUserData
|
||||
{
|
||||
UserId = userId,
|
||||
RoleName = role,
|
||||
Overrides = overrides.ToDictionary(o => o.Key, o => o.State, StringComparer.OrdinalIgnoreCase)
|
||||
};
|
||||
return this;
|
||||
}
|
||||
|
||||
public Task<TeamPermissionUserData?> GetUserAsync(string userId, CancellationToken cancellationToken)
|
||||
{
|
||||
RequestedUserIds.Add(userId);
|
||||
LastToken = cancellationToken;
|
||||
return Task.FromResult(_users.GetValueOrDefault(userId));
|
||||
}
|
||||
|
||||
public Task SetOverrideAsync(string userId, string permissionKey, UserPermissionState state, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException("Reading permissions must not write.");
|
||||
|
||||
public Task SetOverridesAsync(string userId, IReadOnlyDictionary<string, UserPermissionState> overrides, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException("Reading permissions must not write.");
|
||||
|
||||
public Task ClearOverridesAsync(string userId, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException("Reading permissions must not write.");
|
||||
}
|
||||
}
|
||||
|
|
@ -11,6 +11,20 @@ namespace SeaHaven.Services.DTOs
|
|||
public string Id { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public enum ChangePasswordStatus
|
||||
{
|
||||
Succeeded,
|
||||
CurrentPasswordIncorrect,
|
||||
PasswordRejected,
|
||||
/// <summary>Identity failed for a reason other than the password policy.</summary>
|
||||
Failed
|
||||
}
|
||||
|
||||
public sealed class ChangePasswordResultDTO
|
||||
{
|
||||
public ChangePasswordStatus Status { get; init; }
|
||||
}
|
||||
|
||||
public class UpdateProfileRequestDTO
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ namespace SeaHaven.Services.DTOs
|
|||
public string? Status { get; set; }
|
||||
public int? AccountId { get; set; }
|
||||
public string? AccountName { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public DateTime? CreatedDate { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
|
||||
|
|
@ -70,6 +71,7 @@ namespace SeaHaven.Services.DTOs
|
|||
public string? ContactEmail { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public int? AccountId { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>SH-138: null keeps legacy behavior; empty array is a validation error.</summary>
|
||||
public List<SiteContactRequestDTO>? Contacts { get; set; }
|
||||
|
|
@ -88,6 +90,9 @@ namespace SeaHaven.Services.DTOs
|
|||
public string? Status { get; set; }
|
||||
public int? AccountId { get; set; }
|
||||
|
||||
/// <summary>Null keeps the stored notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>SH-138: null keeps legacy behavior and must not mutate contact rows.</summary>
|
||||
public List<SiteContactRequestDTO>? Contacts { get; set; }
|
||||
}
|
||||
|
|
@ -99,4 +104,18 @@ namespace SeaHaven.Services.DTOs
|
|||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Site contacts and notes edited from the work-order Site dialog.</summary>
|
||||
public class SiteContactInfoRequestDTO
|
||||
{
|
||||
public List<SiteContactRequestDTO>? Contacts { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Open (not Completed or Canceled) work orders that reference a site.</summary>
|
||||
public class SiteOpenWorkOrdersDTO
|
||||
{
|
||||
public int Count { get; set; }
|
||||
public IReadOnlyList<int> WorkOrderIds { get; set; } = Array.Empty<int>();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,11 @@ public sealed class TeamPermissionValueDTO
|
|||
public bool IsGranted { get; init; }
|
||||
}
|
||||
|
||||
public sealed class EffectivePermissionsDTO
|
||||
{
|
||||
public required IReadOnlyList<string> Permissions { get; init; }
|
||||
}
|
||||
|
||||
public sealed class SetTeamPermissionOverrideDTO
|
||||
{
|
||||
public UserPermissionState State { get; init; }
|
||||
|
|
@ -24,6 +29,7 @@ public sealed class SetTeamPermissionOverrideDTO
|
|||
public enum TeamPermissionResultStatus
|
||||
{
|
||||
Success,
|
||||
Unauthorized,
|
||||
Forbidden,
|
||||
NotFound,
|
||||
InvalidPermissionKey
|
||||
|
|
|
|||
24
SeaHaven.Services/Exceptions/SiteExceptions.cs
Normal file
24
SeaHaven.Services/Exceptions/SiteExceptions.cs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
namespace SeaHaven.Services.Exceptions;
|
||||
|
||||
/// <summary>Another live site of the same client already uses the requested site code.</summary>
|
||||
public sealed class SiteCodeConflictException : Exception
|
||||
{
|
||||
public const string ErrorCode = "DuplicateSiteCode";
|
||||
public const string PublicMessage = "This site code already exists.";
|
||||
|
||||
public SiteCodeConflictException()
|
||||
: base(PublicMessage)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The caller lacks the permission required for a site mutation.</summary>
|
||||
public sealed class SiteForbiddenException : Exception
|
||||
{
|
||||
public const string DeleteDeniedMessage = "You are not allowed to delete sites.";
|
||||
|
||||
public SiteForbiddenException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
|
@ -25,7 +25,7 @@ namespace SeaHaven.Services.Helpers
|
|||
JoinName(contact?.POC?.FirstName, contact?.POC?.MiddleName, contact?.POC?.LastName),
|
||||
WorkOrderPocSiteContact.DisplayName(sitePrimary));
|
||||
var pocPhone = FirstNotBlank(workOrder.PocPhone, contact?.POC?.PhoneNumber, sitePrimary?.PhoneNumber);
|
||||
var pocNotes = FirstNotBlank(workOrder.PocNotes, contact?.Notes);
|
||||
var pocNotes = FirstNotBlank(workOrder.PocNotes, contact?.Notes, location?.Notes);
|
||||
|
||||
var contacts = new List<WorkOrderFrozenPocContact>();
|
||||
AddContact(contacts, pocName, pocPhone);
|
||||
|
|
|
|||
|
|
@ -80,16 +80,30 @@ namespace SeaHaven.Services.Implementation
|
|||
return null;
|
||||
}
|
||||
|
||||
public async Task<bool> ChangePasswordAsync(string userId, string? currentPassword, string? confirmPassword, CancellationToken cancellationToken)
|
||||
public async Task<ChangePasswordResultDTO> ChangePasswordAsync(string userId, string? currentPassword, string? newPassword, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
if (user == null)
|
||||
return false;
|
||||
if (user == null || user.IsDeleted == true)
|
||||
return ChangePasswordResult(ChangePasswordStatus.CurrentPasswordIncorrect);
|
||||
|
||||
var result = await _userManager.ChangePasswordAsync(user, currentPassword ?? "", confirmPassword ?? "");
|
||||
return result.Succeeded;
|
||||
// The current password is verified before the new one is evaluated, so a
|
||||
// caller without it learns nothing about the policy outcome.
|
||||
if (!await _userManager.CheckPasswordAsync(user, currentPassword ?? ""))
|
||||
return ChangePasswordResult(ChangePasswordStatus.CurrentPasswordIncorrect);
|
||||
|
||||
var result = await _userManager.ChangePasswordAsync(user, currentPassword ?? "", newPassword ?? "");
|
||||
if (result.Succeeded)
|
||||
return ChangePasswordResult(ChangePasswordStatus.Succeeded);
|
||||
|
||||
return ChangePasswordResult(IdentityPasswordPolicy.IsPolicyRejection(result)
|
||||
? ChangePasswordStatus.PasswordRejected
|
||||
: ChangePasswordStatus.Failed);
|
||||
}
|
||||
|
||||
private static ChangePasswordResultDTO ChangePasswordResult(ChangePasswordStatus status) =>
|
||||
new() { Status = status };
|
||||
|
||||
public async Task<UserProfileDTO?> UpdateProfileAsync(string userId, UpdateProfileRequestDTO dto, CancellationToken cancellationToken)
|
||||
{
|
||||
var exists = await _userDataService.UpdateProfileAsync(
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ namespace SeaHaven.Services.Implementation
|
|||
EndDate = input.EndDate,
|
||||
EndTime = input.EndTime,
|
||||
AllDay = input.AllDay,
|
||||
CreatedDate = DateTime.Now,
|
||||
CreatedDate = DateTime.UtcNow,
|
||||
IsDeleted = false
|
||||
};
|
||||
|
||||
|
|
@ -57,7 +57,7 @@ namespace SeaHaven.Services.Implementation
|
|||
model.EndDate = input.EndDate;
|
||||
model.EndTime = input.EndTime;
|
||||
model.AllDay = input.AllDay;
|
||||
model.LastModificationTime = DateTime.Now;
|
||||
model.LastModificationTime = DateTime.UtcNow;
|
||||
|
||||
await _dataService.UpdateEventAsync(model, cancellationToken);
|
||||
return true;
|
||||
|
|
@ -76,7 +76,7 @@ namespace SeaHaven.Services.Implementation
|
|||
return false;
|
||||
|
||||
model.IsDeleted = true;
|
||||
model.DeletionTime = DateTime.Now;
|
||||
model.DeletionTime = DateTime.UtcNow;
|
||||
|
||||
await _dataService.UpdateEventAsync(model, cancellationToken);
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -104,7 +104,7 @@ namespace SeaHaven.Services.Implementation
|
|||
ContactType = dto.Type,
|
||||
AccountId = dto.AccountId,
|
||||
createdby = userId,
|
||||
CreatedDate = DateTime.Now
|
||||
CreatedDate = DateTime.UtcNow
|
||||
};
|
||||
|
||||
var savedContact = await _contactDataService.AddAsync(contact);
|
||||
|
|
@ -151,7 +151,7 @@ namespace SeaHaven.Services.Implementation
|
|||
if (dto.AccountId.HasValue)
|
||||
existingContact.AccountId = dto.AccountId;
|
||||
|
||||
existingContact.LastModificationTime = DateTime.Now;
|
||||
existingContact.LastModificationTime = DateTime.UtcNow;
|
||||
|
||||
await _contactDataService.UpdateAsync(existingContact);
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ using Data.SeaHavenIndustries;
|
|||
using FluentValidation;
|
||||
using FluentValidation.Results;
|
||||
using SeaHaven.DataServices.Interfaces;
|
||||
using SeaHaven.Services.Constants;
|
||||
using SeaHaven.Services.DTOs;
|
||||
using SeaHaven.Services.Exceptions;
|
||||
using SeaHaven.Services.Helpers;
|
||||
using SeaHaven.Services.Interfaces;
|
||||
using SeaHaven.Services.Validation;
|
||||
|
|
@ -20,17 +22,26 @@ namespace SeaHaven.Services.Implementation
|
|||
private readonly IAccountDataService _accountDataService;
|
||||
private readonly ICreateLocationValidation _createValidator;
|
||||
private readonly IUpdateLocationValidation _updateValidator;
|
||||
private readonly ITeamPermissionOverrideDataService _permissionOverrideData;
|
||||
private readonly ITeamPermissionPolicy _permissionPolicy;
|
||||
|
||||
/// <summary>Upper bound on ids returned for the open work orders link.</summary>
|
||||
public const int MaxOpenWorkOrderIds = 200;
|
||||
|
||||
public LocationService(
|
||||
ILocationDataService locationDataService,
|
||||
IAccountDataService accountDataService,
|
||||
ICreateLocationValidation createValidator,
|
||||
IUpdateLocationValidation updateValidator)
|
||||
IUpdateLocationValidation updateValidator,
|
||||
ITeamPermissionOverrideDataService permissionOverrideData,
|
||||
ITeamPermissionPolicy permissionPolicy)
|
||||
{
|
||||
_locationDataService = locationDataService;
|
||||
_accountDataService = accountDataService;
|
||||
_createValidator = createValidator;
|
||||
_updateValidator = updateValidator;
|
||||
_permissionOverrideData = permissionOverrideData;
|
||||
_permissionPolicy = permissionPolicy;
|
||||
}
|
||||
|
||||
// Query operations
|
||||
|
|
@ -262,10 +273,22 @@ namespace SeaHaven.Services.Implementation
|
|||
CancellationToken cancellationToken)
|
||||
{
|
||||
await EnsureAccountAssignableAsync(user, request.AccountId, existingLocationAccountId: null, cancellationToken);
|
||||
ThrowOnMissingSiteFields(request);
|
||||
|
||||
var siteCode = request.Name?.Trim();
|
||||
if (string.IsNullOrEmpty(siteCode))
|
||||
{
|
||||
throw new ValidationException(new[]
|
||||
{
|
||||
new ValidationFailure(nameof(LocationCreateRequestDTO.Name), "Site Code is required.")
|
||||
});
|
||||
}
|
||||
|
||||
await EnsureSiteCodeAvailableAsync(siteCode, request.AccountId, excludeLocationId: null, cancellationToken);
|
||||
|
||||
var location = new Locations
|
||||
{
|
||||
Name = request.Name,
|
||||
Name = siteCode,
|
||||
Title = request.Title,
|
||||
Address1 = request.Address,
|
||||
City = request.City,
|
||||
|
|
@ -274,13 +297,11 @@ namespace SeaHaven.Services.Implementation
|
|||
PhoneNumber = request.Phone,
|
||||
Email = request.ContactEmail,
|
||||
Status = request.Status,
|
||||
AccountId = request.AccountId
|
||||
AccountId = request.AccountId,
|
||||
Notes = NormalizeNotes(request.Notes)
|
||||
};
|
||||
|
||||
if (request.Contacts is List<SiteContactRequestDTO> contacts)
|
||||
{
|
||||
ApplySiteContactsForCreate(location, contacts, GetActorId(user));
|
||||
}
|
||||
ApplySiteContactsForCreate(location, request.Contacts!, GetActorId(user));
|
||||
|
||||
await _locationDataService.AddAsync(location, cancellationToken);
|
||||
}
|
||||
|
|
@ -297,7 +318,6 @@ namespace SeaHaven.Services.Implementation
|
|||
|
||||
EnsureLocationInCallerScope(user, location.AccountId);
|
||||
|
||||
location.Name = request.Name;
|
||||
location.Title = request.Title;
|
||||
location.Address1 = request.Address;
|
||||
location.City = request.City;
|
||||
|
|
@ -305,14 +325,19 @@ namespace SeaHaven.Services.Implementation
|
|||
location.Zip = request.ZipCode;
|
||||
location.PhoneNumber = request.Phone;
|
||||
location.Email = request.ContactEmail;
|
||||
location.Status = request.Status;
|
||||
location.Status = request.Status ?? location.Status;
|
||||
if (request.Notes != null)
|
||||
location.Notes = NormalizeNotes(request.Notes);
|
||||
|
||||
var previousAccountId = location.AccountId;
|
||||
if (request.AccountId is int accountId)
|
||||
{
|
||||
await EnsureAccountAssignableAsync(user, accountId, location.AccountId, cancellationToken);
|
||||
location.AccountId = accountId;
|
||||
}
|
||||
|
||||
await ApplySiteCodeForUpdateAsync(location, request.Name, previousAccountId, cancellationToken);
|
||||
|
||||
// SH-138: null contacts keeps legacy behavior and must not mutate contact rows.
|
||||
if (request.Contacts is List<SiteContactRequestDTO> contacts)
|
||||
{
|
||||
|
|
@ -322,11 +347,147 @@ namespace SeaHaven.Services.Implementation
|
|||
await _locationDataService.UpdateAsync(location, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<bool> DeleteLocationByIdAsync(int id, CancellationToken cancellationToken)
|
||||
public async Task UpdateSiteContactInfoAsync(
|
||||
int id,
|
||||
SiteContactInfoRequestDTO request,
|
||||
ClaimsPrincipal user,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return _locationDataService.DeleteByIdAsync(id, cancellationToken);
|
||||
if (request.Contacts is not List<SiteContactRequestDTO> contacts)
|
||||
{
|
||||
throw new ValidationException(new[]
|
||||
{
|
||||
new ValidationFailure(nameof(SiteContactInfoRequestDTO.Contacts), "At least one contact is required.")
|
||||
});
|
||||
}
|
||||
|
||||
var location = await _locationDataService.GetByIdForUpdateAsync(id, cancellationToken);
|
||||
if (location == null)
|
||||
throw new KeyNotFoundException($"Location with ID {id} not found");
|
||||
|
||||
EnsureLocationInCallerScope(user, location.AccountId);
|
||||
|
||||
ApplySiteContactsForUpdate(location, contacts, GetActorId(user));
|
||||
location.Notes = NormalizeNotes(request.Notes);
|
||||
|
||||
await _locationDataService.UpdateAsync(location, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a site for good from the caller's point of view. The row is kept as
|
||||
/// a tombstone because work orders, assets and history reference it through
|
||||
/// restrict foreign keys; those references are left exactly as they were.
|
||||
/// </summary>
|
||||
public async Task<bool> DeleteLocationByIdAsync(
|
||||
int id,
|
||||
ClaimsPrincipal user,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await EnsureCanDeleteSitesAsync(user, cancellationToken);
|
||||
|
||||
var location = await _locationDataService.GetByIdForUpdateAsync(id, cancellationToken);
|
||||
if (location == null)
|
||||
return false;
|
||||
|
||||
EnsureLocationInCallerScope(user, location.AccountId);
|
||||
|
||||
location.IsDeleted = true;
|
||||
location.DeletionTime = DateTime.UtcNow;
|
||||
location.DeleterUserId = GetActorId(user);
|
||||
|
||||
await _locationDataService.UpdateAsync(location, cancellationToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<SiteOpenWorkOrdersDTO?> GetOpenWorkOrdersAsync(
|
||||
int id,
|
||||
ClaimsPrincipal user,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var location = await _locationDataService.GetDetailByIdAsync(id, cancellationToken);
|
||||
if (location == null)
|
||||
return null;
|
||||
|
||||
EnsureLocationInCallerScope(user, location.AccountId);
|
||||
|
||||
int? callerAccountId = WorkOrderMediaAuthorization.ResolveMediaScope(user) is MediaAccountScope.Account caller
|
||||
? caller.AccountId
|
||||
: null;
|
||||
|
||||
var (count, ids) = await _locationDataService.GetOpenWorkOrderIdsAsync(
|
||||
location.Id,
|
||||
location.Name,
|
||||
location.AccountId,
|
||||
callerAccountId,
|
||||
MaxOpenWorkOrderIds,
|
||||
cancellationToken);
|
||||
|
||||
return new SiteOpenWorkOrdersDTO { Count = count, WorkOrderIds = ids };
|
||||
}
|
||||
|
||||
private async Task EnsureCanDeleteSitesAsync(ClaimsPrincipal user, CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = GetActorId(user);
|
||||
var permissionUser = string.IsNullOrWhiteSpace(userId)
|
||||
? null
|
||||
: await _permissionOverrideData.GetUserAsync(userId, cancellationToken);
|
||||
|
||||
if (permissionUser is null
|
||||
|| !_permissionPolicy.IsAllowed(
|
||||
permissionUser.RoleName,
|
||||
TeamPermissionKeys.DeleteSites,
|
||||
permissionUser.Overrides))
|
||||
{
|
||||
throw new SiteForbiddenException(SiteForbiddenException.DeleteDeniedMessage);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task EnsureSiteCodeAvailableAsync(
|
||||
string siteCode,
|
||||
int? accountId,
|
||||
int? excludeLocationId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _locationDataService.SiteCodeExistsAsync(siteCode, accountId, excludeLocationId, cancellationToken))
|
||||
throw new SiteCodeConflictException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The site code is immutable once set. A blank legacy code may be filled in
|
||||
/// once; the code must stay unique within the site's account, including when
|
||||
/// the site moves to another account.
|
||||
/// </summary>
|
||||
private async Task ApplySiteCodeForUpdateAsync(
|
||||
Locations location,
|
||||
string? requestedCode,
|
||||
int? previousAccountId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var stored = location.Name?.Trim();
|
||||
var requested = requestedCode?.Trim();
|
||||
|
||||
if (!string.IsNullOrEmpty(stored)
|
||||
&& !string.IsNullOrEmpty(requested)
|
||||
&& !string.Equals(stored, requested, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new ValidationException(new[]
|
||||
{
|
||||
new ValidationFailure(nameof(LocationUpdateRequestDTO.Name), "Site Code cannot be changed.")
|
||||
});
|
||||
}
|
||||
|
||||
var fillsBlankCode = string.IsNullOrEmpty(stored) && !string.IsNullOrEmpty(requested);
|
||||
var code = fillsBlankCode ? requested : stored;
|
||||
if (!string.IsNullOrEmpty(code) && (fillsBlankCode || previousAccountId != location.AccountId))
|
||||
await EnsureSiteCodeAvailableAsync(code, location.AccountId, location.Id, cancellationToken);
|
||||
|
||||
if (fillsBlankCode)
|
||||
location.Name = requested;
|
||||
}
|
||||
|
||||
private static string? NormalizeNotes(string? notes) =>
|
||||
string.IsNullOrWhiteSpace(notes) ? null : notes.Trim();
|
||||
|
||||
private static void EnsureLocationInCallerScope(ClaimsPrincipal user, int? locationAccountId)
|
||||
{
|
||||
switch (WorkOrderMediaAuthorization.ResolveMediaScope(user))
|
||||
|
|
@ -385,6 +546,25 @@ namespace SeaHaven.Services.Implementation
|
|||
private static string? GetActorId(ClaimsPrincipal user) =>
|
||||
user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
|
||||
/// <summary>A new site needs a client, a full address and at least one point of contact.</summary>
|
||||
private static void ThrowOnMissingSiteFields(LocationCreateRequestDTO request)
|
||||
{
|
||||
var failures = new List<ValidationFailure>();
|
||||
if (request.AccountId == null)
|
||||
failures.Add(new ValidationFailure(nameof(LocationCreateRequestDTO.AccountId), "Client is required."));
|
||||
if (string.IsNullOrWhiteSpace(request.Address))
|
||||
failures.Add(new ValidationFailure(nameof(LocationCreateRequestDTO.Address), "Street Address is required."));
|
||||
if (string.IsNullOrWhiteSpace(request.City))
|
||||
failures.Add(new ValidationFailure(nameof(LocationCreateRequestDTO.City), "City is required."));
|
||||
if (string.IsNullOrWhiteSpace(request.State))
|
||||
failures.Add(new ValidationFailure(nameof(LocationCreateRequestDTO.State), "State is required."));
|
||||
if (request.Contacts == null || request.Contacts.Count == 0)
|
||||
failures.Add(new ValidationFailure(nameof(LocationCreateRequestDTO.Contacts), "At least one contact is required."));
|
||||
|
||||
if (failures.Count > 0)
|
||||
throw new ValidationException(failures);
|
||||
}
|
||||
|
||||
private static void ThrowOnInvalidContacts(List<SiteContactRequestDTO> contacts)
|
||||
{
|
||||
var failures = SiteContactsValidation.Validate(contacts);
|
||||
|
|
@ -399,7 +579,7 @@ namespace SeaHaven.Services.Implementation
|
|||
{
|
||||
ThrowOnInvalidContacts(contacts);
|
||||
|
||||
var now = DateTime.Now;
|
||||
var now = DateTime.UtcNow;
|
||||
var siteContacts = contacts
|
||||
.Select((row, index) => new Contacts
|
||||
{
|
||||
|
|
@ -414,9 +594,6 @@ namespace SeaHaven.Services.Implementation
|
|||
})
|
||||
.ToList();
|
||||
location.Contacts = siteContacts;
|
||||
|
||||
// The first site contact mirrors Location.PhoneNumber for legacy consumers.
|
||||
location.PhoneNumber = siteContacts[0].PhoneNumber;
|
||||
}
|
||||
|
||||
private static void ApplySiteContactsForUpdate(
|
||||
|
|
@ -457,7 +634,7 @@ namespace SeaHaven.Services.Implementation
|
|||
existing.PhoneNumber = phone;
|
||||
existing.SiteContactOrder = i;
|
||||
existing.AccountId = location.AccountId;
|
||||
existing.LastModificationTime = DateTime.Now;
|
||||
existing.LastModificationTime = DateTime.UtcNow;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -470,7 +647,7 @@ namespace SeaHaven.Services.Implementation
|
|||
PhoneNumber = phone,
|
||||
SiteContactOrder = i,
|
||||
AccountId = location.AccountId,
|
||||
CreatedDate = DateTime.Now,
|
||||
CreatedDate = DateTime.UtcNow,
|
||||
createdby = actorId
|
||||
});
|
||||
}
|
||||
|
|
@ -478,7 +655,7 @@ namespace SeaHaven.Services.Implementation
|
|||
|
||||
// Rows omitted from the request are soft deleted so historical
|
||||
// WorkOrderContacts keep rendering.
|
||||
var now = DateTime.Now;
|
||||
var now = DateTime.UtcNow;
|
||||
foreach (var existing in existingById.Values)
|
||||
{
|
||||
if (keptIds.Contains(existing.Id) || existing.IsDeleted == true)
|
||||
|
|
@ -489,9 +666,6 @@ namespace SeaHaven.Services.Implementation
|
|||
existing.DeletionTime = now;
|
||||
existing.LastModificationTime = now;
|
||||
}
|
||||
|
||||
// The first site contact mirrors Location.PhoneNumber for legacy consumers.
|
||||
location.PhoneNumber = contacts[0].Phone!.Trim();
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyDictionary<int, IReadOnlyList<Contacts>>> GetSiteContactsByLocationIdsAsync(
|
||||
|
|
@ -544,6 +718,7 @@ namespace SeaHaven.Services.Implementation
|
|||
Status = location.Status,
|
||||
AccountId = location.AccountId,
|
||||
AccountName = location.Account?.Name,
|
||||
Notes = location.Notes,
|
||||
CreatedDate = location.CreatedDate,
|
||||
CreatedBy = location.createdby,
|
||||
Contacts = contactsByLocation != null && contactsByLocation.TryGetValue(location.Id, out var contacts)
|
||||
|
|
|
|||
|
|
@ -35,6 +35,28 @@ public sealed class TeamPermissionService : ITeamPermissionService
|
|||
: TeamPermissionResult<TeamPermissionProfileDTO>.Success(BuildProfile(user));
|
||||
}
|
||||
|
||||
public async Task<TeamPermissionResult<EffectivePermissionsDTO>> GetEffectivePermissionsAsync(
|
||||
ClaimsPrincipal caller,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = caller?.Identity?.IsAuthenticated == true
|
||||
? caller.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||
: null;
|
||||
if (string.IsNullOrWhiteSpace(userId))
|
||||
return TeamPermissionResult<EffectivePermissionsDTO>.Failure(TeamPermissionResultStatus.Unauthorized);
|
||||
|
||||
var user = await _dataService.GetUserAsync(userId, cancellationToken);
|
||||
if (user is null)
|
||||
return TeamPermissionResult<EffectivePermissionsDTO>.Failure(TeamPermissionResultStatus.Unauthorized);
|
||||
|
||||
return TeamPermissionResult<EffectivePermissionsDTO>.Success(new EffectivePermissionsDTO
|
||||
{
|
||||
Permissions = TeamPermissionKeys.All
|
||||
.Where(key => _policy.IsAllowed(user.RoleName, key, user.Overrides))
|
||||
.ToList()
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<TeamPermissionResult<TeamPermissionProfileDTO>> SetOverrideAsync(
|
||||
string userId,
|
||||
string permissionKey,
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ namespace SeaHaven.Services.Implementation
|
|||
{
|
||||
model.EmailConfirmed = true;
|
||||
model.UserName = model.Email;
|
||||
model.CreatedDate = DateTime.Now;
|
||||
model.CreatedDate = DateTime.UtcNow;
|
||||
model.UniqueName = "Active";
|
||||
model.PhoneNumber = dto.Role;
|
||||
|
||||
|
|
@ -152,7 +152,7 @@ namespace SeaHaven.Services.Implementation
|
|||
exist.Email = dto.Email;
|
||||
exist.NormalizedEmail = dto.Email.ToUpperInvariant();
|
||||
exist.NormalizedUserName = dto.Email.ToUpperInvariant();
|
||||
exist.CreatedDate = DateTime.Now;
|
||||
exist.CreatedDate = DateTime.UtcNow;
|
||||
exist.UniqueName = "Active";
|
||||
exist.PhoneNumber = dto.Role;
|
||||
exist.AccountId = dto.AccountId;
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ namespace SeaHaven.Services.Interfaces
|
|||
public interface IAuthenticationService
|
||||
{
|
||||
Task<LoginResultDTO?> LoginAsync(string? username, string? password, CancellationToken cancellationToken);
|
||||
Task<bool> ChangePasswordAsync(string userId, string? currentPassword, string? confirmPassword, CancellationToken cancellationToken);
|
||||
Task<ChangePasswordResultDTO> ChangePasswordAsync(string userId, string? currentPassword, string? newPassword, CancellationToken cancellationToken);
|
||||
Task<UserProfileDTO?> UpdateProfileAsync(string userId, UpdateProfileRequestDTO dto, CancellationToken cancellationToken);
|
||||
Task<bool> ForgetPasswordAsync(string email, CancellationToken cancellationToken);
|
||||
Task<bool> VerifyCodeAsync(string code, CancellationToken cancellationToken);
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ namespace SeaHaven.Services.Interfaces
|
|||
Task<LocationDTO?> GetLocationDetailAsync(int id, CancellationToken cancellationToken);
|
||||
Task CreateLocationFromRequestAsync(LocationCreateRequestDTO request, ClaimsPrincipal user, CancellationToken cancellationToken);
|
||||
Task UpdateLocationFromRequestAsync(int id, LocationUpdateRequestDTO request, ClaimsPrincipal user, CancellationToken cancellationToken);
|
||||
Task<bool> DeleteLocationByIdAsync(int id, CancellationToken cancellationToken);
|
||||
Task UpdateSiteContactInfoAsync(int id, SiteContactInfoRequestDTO request, ClaimsPrincipal user, CancellationToken cancellationToken);
|
||||
Task<bool> DeleteLocationByIdAsync(int id, ClaimsPrincipal user, CancellationToken cancellationToken);
|
||||
Task<SiteOpenWorkOrdersDTO?> GetOpenWorkOrdersAsync(int id, ClaimsPrincipal user, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,14 @@ public interface ITeamPermissionService
|
|||
ClaimsPrincipal caller,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Keys the caller holds after role defaults and their own overrides. The
|
||||
/// user is read from the caller's identity, never from request input.
|
||||
/// </summary>
|
||||
Task<TeamPermissionResult<EffectivePermissionsDTO>> GetEffectivePermissionsAsync(
|
||||
ClaimsPrincipal caller,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
Task<TeamPermissionResult<TeamPermissionProfileDTO>> SetOverrideAsync(
|
||||
string userId,
|
||||
string permissionKey,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ using Microsoft.Data.SqlClient;
|
|||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using SeaHaven.DataServices.Implementation;
|
||||
|
||||
namespace SeaHavenIndustries.Tests;
|
||||
|
||||
|
|
@ -84,150 +83,6 @@ public class SH138SiteContactsSqlServerTests
|
|||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SH138_LocationDelete_DetachesSoftDeletedContacts_WithRestrictFk_WhenLocalDbAvailable()
|
||||
{
|
||||
var masterConnectionString = await ResolveMasterConnectionStringAsync();
|
||||
if (masterConnectionString == null)
|
||||
return;
|
||||
|
||||
var dbName = $"SH138LocationDelete_{Guid.NewGuid():N}";
|
||||
var connectionString = WithDatabase(masterConnectionString, dbName);
|
||||
|
||||
try
|
||||
{
|
||||
await CreateDatabaseAsync(masterConnectionString, dbName);
|
||||
|
||||
await using var connection = new SqlConnection(connectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
await using (var createTables = connection.CreateCommand())
|
||||
{
|
||||
createTables.CommandText =
|
||||
"""
|
||||
CREATE TABLE Locations (
|
||||
Id int NOT NULL IDENTITY PRIMARY KEY,
|
||||
AccountId int NULL,
|
||||
Title nvarchar(max) NULL,
|
||||
Name nvarchar(max) NULL,
|
||||
Latitude nvarchar(max) NULL,
|
||||
Longitude nvarchar(max) NULL,
|
||||
Address1 nvarchar(max) NULL,
|
||||
Address2 nvarchar(max) NULL,
|
||||
City nvarchar(max) NULL,
|
||||
State nvarchar(max) NULL,
|
||||
Zip nvarchar(max) NULL,
|
||||
PhoneNumber nvarchar(max) NULL,
|
||||
Email nvarchar(max) NULL,
|
||||
Status nvarchar(max) NULL,
|
||||
ExternalSource nvarchar(max) NULL,
|
||||
ExternalLocationId nvarchar(max) NULL,
|
||||
IsDeleted bit NULL,
|
||||
createdby nvarchar(max) NULL,
|
||||
DeleterUserId nvarchar(max) NULL,
|
||||
DeletionTime datetime2 NULL,
|
||||
CreatedDate datetime2 NULL,
|
||||
LastModificationTime datetime2 NULL,
|
||||
LastModifierUserId int NULL
|
||||
);
|
||||
CREATE TABLE Contacts (
|
||||
Id int NOT NULL IDENTITY PRIMARY KEY,
|
||||
AccountId int NULL,
|
||||
LocationId int NULL,
|
||||
Title nvarchar(max) NULL,
|
||||
Owner nvarchar(max) NULL,
|
||||
FirstName nvarchar(max) NULL,
|
||||
MiddleName nvarchar(max) NULL,
|
||||
LastName nvarchar(max) NULL,
|
||||
ContactType nvarchar(max) NULL,
|
||||
PhoneNumber nvarchar(max) NULL,
|
||||
Email nvarchar(max) NULL,
|
||||
Address1 nvarchar(max) NULL,
|
||||
Address2 nvarchar(max) NULL,
|
||||
City nvarchar(max) NULL,
|
||||
State nvarchar(max) NULL,
|
||||
Zip nvarchar(max) NULL,
|
||||
FacebookUrl nvarchar(max) NULL,
|
||||
LinkedInUrl nvarchar(max) NULL,
|
||||
TwitterUrl nvarchar(max) NULL,
|
||||
IsDeleted bit NULL,
|
||||
createdby nvarchar(max) NULL,
|
||||
DeleterUserId nvarchar(max) NULL,
|
||||
DeletionTime datetime2 NULL,
|
||||
CreatedDate datetime2 NULL,
|
||||
LastModificationTime datetime2 NULL,
|
||||
LastModifierUserId int NULL,
|
||||
SiteContactOrder int NULL,
|
||||
CONSTRAINT FK_Contacts_Locations_LocationId FOREIGN KEY (LocationId) REFERENCES Locations (Id) ON DELETE NO ACTION
|
||||
);
|
||||
SET IDENTITY_INSERT Locations ON;
|
||||
INSERT INTO Locations (Id, Name) VALUES (11, 'Depot');
|
||||
SET IDENTITY_INSERT Locations OFF;
|
||||
INSERT INTO Contacts (LocationId, FirstName, PhoneNumber, SiteContactOrder) VALUES (11, 'Alice Cooper', '555-0100', 0);
|
||||
INSERT INTO Contacts (LocationId, FirstName, PhoneNumber, IsDeleted, DeleterUserId, DeletionTime) VALUES (11, 'Bob Dillon', '555-0200', 1, 'actor-1', '2026-01-01T00:00:00');
|
||||
""";
|
||||
await createTables.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseSqlServer(connection)
|
||||
.Options;
|
||||
|
||||
await using var context = new ApplicationDbContext(options);
|
||||
var service = new LocationDataService(context);
|
||||
var deleted = await service.DeleteByIdAsync(11, CancellationToken.None);
|
||||
|
||||
Assert.True(deleted);
|
||||
|
||||
await using (var locationCmd = connection.CreateCommand())
|
||||
{
|
||||
locationCmd.CommandText = "SELECT COUNT(*) FROM Locations;";
|
||||
var locationCount = await locationCmd.ExecuteScalarAsync();
|
||||
Assert.Equal(0, Convert.ToInt32(locationCount));
|
||||
}
|
||||
|
||||
await using (var activeCmd = connection.CreateCommand())
|
||||
{
|
||||
activeCmd.CommandText =
|
||||
"""
|
||||
SELECT FirstName, PhoneNumber, LocationId, IsDeleted, DeleterUserId, DeletionTime
|
||||
FROM Contacts
|
||||
WHERE FirstName = N'Alice Cooper';
|
||||
""";
|
||||
await using var reader = await activeCmd.ExecuteReaderAsync();
|
||||
Assert.True(await reader.ReadAsync());
|
||||
Assert.Equal("Alice Cooper", reader.GetString(0));
|
||||
Assert.Equal("555-0100", reader.GetString(1));
|
||||
Assert.True(reader.IsDBNull(2));
|
||||
Assert.True(reader.GetBoolean(3));
|
||||
Assert.True(reader.IsDBNull(4), "delete carries no audit actor");
|
||||
Assert.False(reader.IsDBNull(5));
|
||||
Assert.False(await reader.ReadAsync());
|
||||
}
|
||||
|
||||
await using (var previouslyDeletedCmd = connection.CreateCommand())
|
||||
{
|
||||
previouslyDeletedCmd.CommandText =
|
||||
"""
|
||||
SELECT LocationId, IsDeleted, DeleterUserId, DeletionTime
|
||||
FROM Contacts
|
||||
WHERE FirstName = N'Bob Dillon';
|
||||
""";
|
||||
await using var reader = await previouslyDeletedCmd.ExecuteReaderAsync();
|
||||
Assert.True(await reader.ReadAsync());
|
||||
Assert.True(reader.IsDBNull(0), "already soft-deleted rows detach so the restrict FK cannot block the delete");
|
||||
Assert.True(reader.GetBoolean(1));
|
||||
Assert.Equal("actor-1", reader.GetString(2));
|
||||
Assert.Equal(new DateTime(2026, 1, 1), reader.GetDateTime(3));
|
||||
Assert.False(await reader.ReadAsync());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await DropDatabaseAsync(masterConnectionString, dbName);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ApplyMigrationUpAsync(ApplicationDbContext context, Migration migration)
|
||||
{
|
||||
var builder = new MigrationBuilder(context.Database.ProviderName!);
|
||||
|
|
|
|||
|
|
@ -849,7 +849,19 @@ public class WorkOrderAccountScopeTests
|
|||
=> _inner.AddAsync(location, cancellationToken);
|
||||
public Task UpdateAsync(Locations location, CancellationToken cancellationToken)
|
||||
=> _inner.UpdateAsync(location, cancellationToken);
|
||||
public Task<bool> DeleteByIdAsync(int id, CancellationToken cancellationToken)
|
||||
=> _inner.DeleteByIdAsync(id, cancellationToken);
|
||||
public Task<bool> SiteCodeExistsAsync(
|
||||
string siteCode,
|
||||
int? accountId,
|
||||
int? excludeLocationId,
|
||||
CancellationToken cancellationToken)
|
||||
=> _inner.SiteCodeExistsAsync(siteCode, accountId, excludeLocationId, cancellationToken);
|
||||
public Task<(int Count, IReadOnlyList<int> Ids)> GetOpenWorkOrderIdsAsync(
|
||||
int locationId,
|
||||
string? siteCode,
|
||||
int? siteAccountId,
|
||||
int? callerAccountId,
|
||||
int maxIds,
|
||||
CancellationToken cancellationToken)
|
||||
=> _inner.GetOpenWorkOrderIdsAsync(locationId, siteCode, siteAccountId, callerAccountId, maxIds, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,8 @@ builder.Services.AddAuthentication(options =>
|
|||
.AddIdentityCookies();
|
||||
|
||||
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
|
||||
builder.Services.AddDbContext<ApplicationDbContext>(options => {
|
||||
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
||||
{
|
||||
options.UseSqlServer(connectionString);
|
||||
}, ServiceLifetime.Transient);
|
||||
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
|
||||
|
|
@ -39,11 +40,7 @@ builder.Services.AddDatabaseDeveloperPageExceptionFilter();
|
|||
builder.Services.AddIdentityCore<ApplicationUser>(options =>
|
||||
{
|
||||
options.SignIn.RequireConfirmedAccount = true;
|
||||
options.Password.RequireDigit = true;
|
||||
options.Password.RequireLowercase = false;
|
||||
options.Password.RequireUppercase = false;
|
||||
options.Password.RequireNonAlphanumeric = true;
|
||||
options.Password.RequiredLength = 8;
|
||||
IdentityPasswordPolicy.Apply(options.Password);
|
||||
}).AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddSignInManager()
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue