Files
mws.backend.dotnet/mws.application/Accounts/Commands/UpdateAccount.cs
T

36 lines
1.2 KiB
C#
Raw Normal View History

using AutoMapper;
using MediatR;
using Mws.Application.Common;
using Mws.Application.Permissions;
namespace Mws.Application.Accounts;
public record UpdateAccountCommand(Guid ActorUserId, Guid Id, UpdateAccountRequest Request) : IRequest<AccountDto>;
public class UpdateAccountHandler(IUnitOfWork uow, IPermissionService permissions, IMapper mapper)
: IRequestHandler<UpdateAccountCommand, AccountDto>
{
private const string Screen = "accounts";
public async Task<AccountDto> Handle(UpdateAccountCommand command, CancellationToken ct)
{
await permissions.EnsureAsync(command.ActorUserId, Screen, PermissionAction.Edit, ct);
var user = await uow.Users.GetByIdWithRoleAsync(command.Id, ct)
?? throw new NotFoundException("Account not found");
var request = command.Request;
var role = await uow.Roles.GetByIdAsync(request.RoleId, ct)
?? throw new BadRequestException("Role not found");
user.DisplayName = request.DisplayName.Trim();
user.RoleId = role.Id;
user.Role = role;
user.IsActive = request.IsActive;
user.UpdatedAt = DateTime.UtcNow;
await uow.SaveChangesAsync(ct);
return mapper.Map<AccountDto>(user);
}
}