Api/Brizco.Repository/Handlers/Complexes/CreateComplexUserCommandHan...

52 lines
2.4 KiB
C#

namespace Brizco.Repository.Handlers.Complexes;
public class CreateComplexUserCommandHandler(
IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
ILogger<CreateComplexUserCommandHandler> logger)
: IRequestHandler<CreateComplexUserCommand, ComplexUserSDto>
{
private readonly ILogger<CreateComplexUserCommandHandler> _logger = logger;
public async Task<ComplexUserSDto> Handle(CreateComplexUserCommand request, CancellationToken cancellationToken)
{
try
{
//await _repositoryWrapper.BeginTransaction(cancellationToken);
var complex = await repositoryWrapper.SetRepository<Complex>().TableNoTracking
.FirstOrDefaultAsync(c => c.Id == request.ComplexId, cancellationToken);
if (complex == null)
throw new AppException("Complex not found", ApiResultStatusCode.NotFound);
var user = await userManager.FindByIdAsync(request.UserId.ToString());
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking
.FirstOrDefaultAsync(f => f.ComplexId == request.ComplexId && f.UserId == request.UserId, cancellationToken);
if (complexUser != null)
throw new AppException("این کاربر در این رستوران وجود دارد");
complexUser = complex.AddComplexUser(request.UserId);
foreach (var roleId in request.RoleIds)
{
var role = await roleManager.FindByIdAsync(roleId.ToString());
var result = await userManager.AddToRoleAsync(user, role.Name);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors));
complexUser.AddRole(role.Id);
}
repositoryWrapper.SetRepository<ComplexUser>().Add(complexUser);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
//await _repositoryWrapper.CommitAsync(cancellationToken);
return complexUser.AdaptToSDto();
}
catch (Exception)
{
await repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}
}