2026-08-19 23:25:08 +07:00
|
|
|
using MediatR;
|
2026-09-20 16:21:15 +07:00
|
|
|
using mws.backend.dotnet.application.Audit;
|
2026-08-19 23:25:08 +07:00
|
|
|
using mws.backend.dotnet.application.Common;
|
|
|
|
|
using mws.backend.dotnet.application.Permissions;
|
|
|
|
|
|
|
|
|
|
namespace mws.backend.dotnet.application.Users;
|
|
|
|
|
|
2026-09-20 16:21:15 +07:00
|
|
|
public record DeleteUserCommand(Guid ActorUserId, Guid Id) : IRequest, IAuditableRequest
|
|
|
|
|
{
|
|
|
|
|
public string Action => "User.Delete";
|
|
|
|
|
public string EntityType => "User";
|
|
|
|
|
public Guid? EntityId => Id;
|
|
|
|
|
}
|
2026-08-19 23:25:08 +07:00
|
|
|
|
2026-09-20 16:21:15 +07:00
|
|
|
public class DeleteUserHandler(IUnitOfWork uow, IPermissionService permissions, IAuditContext auditContext) : IRequestHandler<DeleteUserCommand>
|
2026-08-19 23:25:08 +07:00
|
|
|
{
|
|
|
|
|
private const string Screen = "users";
|
|
|
|
|
|
|
|
|
|
public async Task Handle(DeleteUserCommand command, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
await permissions.EnsureAsync(command.ActorUserId, Screen, PermissionAction.Delete, ct);
|
|
|
|
|
|
|
|
|
|
var user = await uow.Users.GetByIdAsync(command.Id, ct)
|
|
|
|
|
?? throw new NotFoundException("User not found");
|
|
|
|
|
|
|
|
|
|
var soleOwnerProjectIds = await uow.Projects.GetOwnedProjectIdsAsync(command.Id, ct);
|
|
|
|
|
|
|
|
|
|
foreach (var projectId in soleOwnerProjectIds)
|
|
|
|
|
{
|
|
|
|
|
var ownerCount = await uow.Projects.CountOwnersAsync(projectId, ct);
|
|
|
|
|
if (ownerCount <= 1)
|
|
|
|
|
{
|
|
|
|
|
throw new BadRequestException("Cannot delete a user that is the sole owner of a project");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
uow.Users.Remove(user);
|
|
|
|
|
await uow.SaveChangesAsync(ct);
|
2026-09-20 16:21:15 +07:00
|
|
|
|
|
|
|
|
auditContext.EntityName = user.Username;
|
2026-08-19 23:25:08 +07:00
|
|
|
}
|
|
|
|
|
}
|