complete role and user actions

master
Amir Hossein Khademi 2023-10-24 15:36:09 +03:30
parent 40b9b42fbd
commit 28092b0d6b
15 changed files with 287 additions and 93 deletions

View File

@ -31,7 +31,7 @@ public class RoleController : ICarterModule
group.MapPut("", Put) group.MapPut("", Put)
.HasApiVersion(1.0); .HasApiVersion(1.0);
group.MapDelete("", Delete) group.MapDelete("{id}", Delete)
.HasApiVersion(1.0); .HasApiVersion(1.0);
} }

View File

@ -1,7 +1,4 @@
using Brizco.Core.EntityServices; namespace Brizco.Api.Controllers;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Brizco.Api.Controllers;
public class UserController : ICarterModule public class UserController : ICarterModule
{ {
@ -28,7 +25,7 @@ public class UserController : ICarterModule
group.MapPut("", Put) group.MapPut("", Put)
.HasApiVersion(1.0); .HasApiVersion(1.0);
group.MapDelete("", Delete) group.MapDelete("{id}", Delete)
.HasApiVersion(1.0); .HasApiVersion(1.0);
} }

View File

@ -12,16 +12,19 @@ public class UserService : IUserService
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager; private readonly RoleManager<ApplicationRole> _roleManager;
private readonly ISender _sender; private readonly ISender _sender;
private readonly IRepositoryWrapper _repositoryWrapper;
public UserService(ICurrentUserService currentUserService, public UserService(ICurrentUserService currentUserService,
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager, RoleManager<ApplicationRole> roleManager,
ISender sender) ISender sender,
IRepositoryWrapper repositoryWrapper)
{ {
_currentUserService = currentUserService; _currentUserService = currentUserService;
_userManager = userManager; _userManager = userManager;
_roleManager = roleManager; _roleManager = roleManager;
_sender = sender; _sender = sender;
_repositoryWrapper = repositoryWrapper;
} }
public async Task<List<ComplexUserSDto>> GetUsersAsync(int page = 0, CancellationToken cancellationToken = default) public async Task<List<ComplexUserSDto>> GetUsersAsync(int page = 0, CancellationToken cancellationToken = default)
@ -30,13 +33,27 @@ public class UserService : IUserService
throw new AppException("Wrong authorize token , ComplexId needed"); throw new AppException("Wrong authorize token , ComplexId needed");
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId))
throw new AppException("Wrong authorize token , ComplexId needed"); throw new AppException("Wrong authorize token , ComplexId needed");
var complexUsers = await _sender.Send(new GetComplexUsersQuery(complexId.ToString(), page),cancellationToken); var complexUsers = await _sender.Send(new GetComplexUsersQuery(complexId.ToString(), page), cancellationToken);
return complexUsers; return complexUsers;
} }
public async Task<ApplicationUserSDto> GetUserAsync(Guid userId) public async Task<ApplicationUserSDto> GetUserAsync(Guid userId)
=> (await _userManager.FindByIdAsync(userId.ToString())).AdaptToSDto(); {
var user = await _userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
var dto = user.AdaptToSDto();
var roles = await _userManager.GetRolesAsync(user);
foreach (var roleName in roles)
{
var role = await _roleManager.FindByNameAsync(roleName);
if (role != null)
dto.RoleIds.Add(role.Id);
}
return dto;
}
public async Task<ApplicationUser> CreateUserAsync(string phoneNumber) public async Task<ApplicationUser> CreateUserAsync(string phoneNumber)
{ {
@ -66,7 +83,7 @@ public class UserService : IUserService
FirstName = request.FirstName, FirstName = request.FirstName,
LastName = request.LastName, LastName = request.LastName,
NationalId = request.NationalId, NationalId = request.NationalId,
BirthDate = request.BirthDate, BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp),
Gender = request.Gender, Gender = request.Gender,
SignUpStatus = SignUpStatus.SignUpCompleted SignUpStatus = SignUpStatus.SignUpCompleted
}; };
@ -74,13 +91,13 @@ public class UserService : IUserService
{ {
var result = await _userManager.CreateAsync(user, request.Password); var result = await _userManager.CreateAsync(user, request.Password);
if (!result.Succeeded) if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors)); throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
} }
else else
{ {
var result = await _userManager.CreateAsync(user); var result = await _userManager.CreateAsync(user);
if (!result.Succeeded) if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors)); throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
} }
await _sender.Send(new CreateComplexUserCommand(complexId, user.Id, request.RoleIds), cancellationToken); await _sender.Send(new CreateComplexUserCommand(complexId, user.Id, request.RoleIds), cancellationToken);
@ -93,10 +110,10 @@ public class UserService : IUserService
throw new AppException("Wrong authorize token , ComplexId needed"); throw new AppException("Wrong authorize token , ComplexId needed");
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId))
throw new AppException("Wrong authorize token , ComplexId needed"); throw new AppException("Wrong authorize token , ComplexId needed");
if (_currentUserService.UserId == null) if (request.UserId == Guid.Empty)
throw new AppException("Wrong authorize token , UserId needed"); throw new AppException("Wrong authorize token , UserId needed");
var user = await _userManager.FindByIdAsync(_currentUserService.UserId); var user = await _userManager.FindByIdAsync(request.UserId.ToString());
if (user == null) if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound); throw new AppException("User not found", ApiResultStatusCode.NotFound);
user.LastName = request.LastName; user.LastName = request.LastName;
@ -106,12 +123,12 @@ public class UserService : IUserService
user.FirstName = request.FirstName; user.FirstName = request.FirstName;
user.LastName = request.LastName; user.LastName = request.LastName;
user.NationalId = request.NationalId; user.NationalId = request.NationalId;
user.BirthDate = request.BirthDate; user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp);
user.Gender = request.Gender; user.Gender = request.Gender;
var result = await _userManager.UpdateAsync(user); var result = await _userManager.UpdateAsync(user);
if (!result.Succeeded) if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors)); throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
if (!request.Password.IsNullOrEmpty()) if (!request.Password.IsNullOrEmpty())
{ {
if (await _userManager.HasPasswordAsync(user)) if (await _userManager.HasPasswordAsync(user))
@ -119,7 +136,7 @@ public class UserService : IUserService
var addPassResult = await _userManager.AddPasswordAsync(user, request.Password); var addPassResult = await _userManager.AddPasswordAsync(user, request.Password);
if (!addPassResult.Succeeded) if (!addPassResult.Succeeded)
throw new AppException(string.Join('|', addPassResult.Errors)); throw new AppException(string.Join('|', addPassResult.Errors.Select(e => e.Description)));
} }
await _sender.Send(new UpdateComplexUserCommand(user.Id, complexId, request.RoleIds), cancellationToken); await _sender.Send(new UpdateComplexUserCommand(user.Id, complexId, request.RoleIds), cancellationToken);
@ -141,12 +158,12 @@ public class UserService : IUserService
user.FirstName = request.FirstName; user.FirstName = request.FirstName;
user.LastName = request.LastName; user.LastName = request.LastName;
user.NationalId = request.NationalId; user.NationalId = request.NationalId;
user.BirthDate = request.BirthDate; user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp);
user.Gender = request.Gender; user.Gender = request.Gender;
var result = await _userManager.UpdateAsync(user); var result = await _userManager.UpdateAsync(user);
if (!result.Succeeded) if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors)); throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
if (!request.Password.IsNullOrEmpty()) if (!request.Password.IsNullOrEmpty())
{ {
if (await _userManager.HasPasswordAsync(user)) if (await _userManager.HasPasswordAsync(user))
@ -154,7 +171,7 @@ public class UserService : IUserService
var addPassResult = await _userManager.AddPasswordAsync(user, request.Password); var addPassResult = await _userManager.AddPasswordAsync(user, request.Password);
if (!addPassResult.Succeeded) if (!addPassResult.Succeeded)
throw new AppException(string.Join('|', addPassResult.Errors)); throw new AppException(string.Join('|', addPassResult.Errors.Select(e => e.Description)));
} }
return true; return true;
@ -169,16 +186,18 @@ public class UserService : IUserService
var user = await _userManager.FindByIdAsync(userId.ToString()); var user = await _userManager.FindByIdAsync(userId.ToString());
if (user == null) if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound); throw new AppException("User not found", ApiResultStatusCode.NotFound);
var roles = await _userManager.GetRolesAsync(user);
await _userManager.RemoveFromRolesAsync(user, roles);
await _sender.Send(new DeleteComplexUserCommand(userId, complexId), cancellationToken);
var removeResult = await _userManager.DeleteAsync(user); var removeResult = await _userManager.DeleteAsync(user);
if (!removeResult.Succeeded) if (!removeResult.Succeeded)
throw new AppException(string.Join('|', removeResult.Errors)); throw new AppException(string.Join('|', removeResult.Errors.Select(e => e.Description)));
await _sender.Send(new DeleteComplexUserCommand(userId, complexId), cancellationToken);
return true; return true;
} }
public async Task<List<ApplicationRole>> GetRolesAsync(int page = 0,CancellationToken cancellationToken = default) public async Task<List<ApplicationRole>> GetRolesAsync(int page = 0, CancellationToken cancellationToken = default)
{ {
if (_currentUserService.ComplexId.IsNullOrEmpty()) if (_currentUserService.ComplexId.IsNullOrEmpty())
throw new AppException("Wrong authorize token , ComplexId needed"); throw new AppException("Wrong authorize token , ComplexId needed");
@ -186,7 +205,7 @@ public class UserService : IUserService
throw new AppException("Wrong authorize token , ComplexId needed"); throw new AppException("Wrong authorize token , ComplexId needed");
var roles = await _roleManager.Roles var roles = await _roleManager.Roles
.Where(r=>r.ComplexId==complexId) .Where(r => r.ComplexId == complexId)
.Skip(page * 15) .Skip(page * 15)
.Take(15) .Take(15)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
@ -197,9 +216,10 @@ public class UserService : IUserService
{ {
var role = (await _roleManager.FindByIdAsync(roleId.ToString())); var role = (await _roleManager.FindByIdAsync(roleId.ToString()));
if (role == null) if (role == null)
throw new AppException("نقش پیدا نشد",ApiResultStatusCode.NotFound); throw new AppException("نقش پیدا نشد", ApiResultStatusCode.NotFound);
var roleDto = role.Adapt<RoleActionRequestDto>(); var roleDto = role.Adapt<RoleActionRequestDto>();
roleDto.RoleId = roleId;
roleDto.Permissions = (await _roleManager.GetClaimsAsync(role)) roleDto.Permissions = (await _roleManager.GetClaimsAsync(role))
.Where(c => c.Type == CustomClaimType.Permission) .Where(c => c.Type == CustomClaimType.Permission)
.Select(c => c.Value) .Select(c => c.Value)
@ -278,9 +298,28 @@ public class UserService : IUserService
var applicationRole = await _roleManager.FindByIdAsync(roleId.ToString()); var applicationRole = await _roleManager.FindByIdAsync(roleId.ToString());
if (applicationRole == null) if (applicationRole == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound); throw new AppException("User not found", ApiResultStatusCode.NotFound);
var claims = await _roleManager.GetClaimsAsync(applicationRole);
foreach (var claim in claims)
await _roleManager.RemoveClaimAsync(applicationRole, claim);
var users = await _userManager.GetUsersInRoleAsync(applicationRole.Name);
foreach (var user in users)
await _userManager.RemoveFromRoleAsync(user, applicationRole.Name);
var complexRoles = await _repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking
.Where(r => r.RoleId == applicationRole.Id)
.ToListAsync();
foreach (var complexRole in complexRoles)
{
_repositoryWrapper.SetRepository<ComplexUserRole>()
.HardDelete(complexRole);
await _repositoryWrapper.SaveChangesAsync(default);
}
var removeResult = await _roleManager.DeleteAsync(applicationRole); var removeResult = await _roleManager.DeleteAsync(applicationRole);
if (!removeResult.Succeeded) if (!removeResult.Succeeded)
throw new AppException(string.Join('|', removeResult.Errors)); throw new AppException(string.Join('|', removeResult.Errors.Select(e => e.Description)));
return true; return true;
} }

View File

@ -48,6 +48,7 @@
<ItemGroup> <ItemGroup>
<Using Include="Brizco.Common.Extensions" />
<Using Include="Brizco.Common.Models.Entity" /> <Using Include="Brizco.Common.Models.Entity" />
<Using Include="Brizco.Common.Models.Mapper" /> <Using Include="Brizco.Common.Models.Mapper" />
<Using Include="Brizco.Domain.Dtos.LargDtos" /> <Using Include="Brizco.Domain.Dtos.LargDtos" />

View File

@ -2,10 +2,11 @@
public class UserActionRequestDto public class UserActionRequestDto
{ {
public Guid UserId { get; set; }
public string PhoneNumber { get; set; } = string.Empty; public string PhoneNumber { get; set; } = string.Empty;
public string FirstName { get; set; } = string.Empty; public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty; public string LastName { get; set; } = string.Empty;
public DateTime BirthDate { get; set; } public long BirthDateTimeStamp { get; set; }
public Gender Gender { get; set; } public Gender Gender { get; set; }
public string NationalId { get; set; } = string.Empty; public string NationalId { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;

View File

@ -13,4 +13,7 @@ public class ApplicationUserSDto : BaseDto<ApplicationUserSDto,ApplicationUser>
public string SelectedRoleName { get; set; } = string.Empty; public string SelectedRoleName { get; set; } = string.Empty;
public string SelectedComplexName { get; set; } = string.Empty; public string SelectedComplexName { get; set; } = string.Empty;
public string NationalId { get; set; } = string.Empty; public string NationalId { get; set; } = string.Empty;
public List<Guid> RoleIds { get; set; } = new();
public long BirthDateTimeStamp => DateTimeExtensions.DateTimeToUnixTimeStamp(BirthDate);
} }

View File

@ -6,9 +6,9 @@ public class ComplexUserSDto : BaseDto<ComplexUserSDto,ComplexUser>
{ {
public string FirstName { get; set; } = string.Empty; public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty; public string LastName { get; set; } = string.Empty;
public string InternationalId { get; set; } = string.Empty; public string NationalId { get; set; } = string.Empty;
public string ComplexName { get; set; } = string.Empty; public string ComplexName { get; set; } = string.Empty;
public List<string> RoleNames { get; set; } = new();
public Guid UserId { get; set; } public Guid UserId { get; set; }
public Guid ComplexId { get; set; } public Guid ComplexId { get; set; }
} }

View File

@ -5,6 +5,7 @@ using System.Linq.Expressions;
using Brizco.Domain.Dtos.LargDtos; using Brizco.Domain.Dtos.LargDtos;
using Brizco.Domain.Dtos.SmallDtos; using Brizco.Domain.Dtos.SmallDtos;
using Brizco.Domain.Entities.Complex; using Brizco.Domain.Entities.Complex;
using Brizco.Domain.Entities.User;
namespace Brizco.Domain.Mappers namespace Brizco.Domain.Mappers
{ {
@ -110,6 +111,12 @@ namespace Brizco.Domain.Mappers
{ {
UserId = p16.UserId, UserId = p16.UserId,
ComplexId = p16.ComplexId, ComplexId = p16.ComplexId,
User = new ApplicationUser() {Id = p16.UserId},
Complex = new Complex()
{
Name = p16.ComplexName,
Id = p16.ComplexId
},
Id = p16.Id Id = p16.Id
}).ToList<ComplexUser>(), }).ToList<ComplexUser>(),
Id = p15.Id Id = p15.Id
@ -148,6 +155,10 @@ namespace Brizco.Domain.Mappers
SupportPhone = p23.SupportPhone, SupportPhone = p23.SupportPhone,
Users = p23.Users.Select<ComplexUser, ComplexUserSDto>(p24 => new ComplexUserSDto() Users = p23.Users.Select<ComplexUser, ComplexUserSDto>(p24 => new ComplexUserSDto()
{ {
FirstName = p24.User != null ? p24.User.FirstName : string.Empty,
LastName = p24.User != null ? p24.User.LastName : string.Empty,
NationalId = p24.User != null ? p24.User.NationalId : string.Empty,
ComplexName = p24.Complex != null ? p24.Complex.Name : string.Empty,
UserId = p24.UserId, UserId = p24.UserId,
ComplexId = p24.ComplexId, ComplexId = p24.ComplexId,
Id = p24.Id Id = p24.Id
@ -173,6 +184,12 @@ namespace Brizco.Domain.Mappers
{ {
UserId = item.UserId, UserId = item.UserId,
ComplexId = item.ComplexId, ComplexId = item.ComplexId,
User = new ApplicationUser() {Id = item.UserId},
Complex = new Complex()
{
Name = item.ComplexName,
Id = item.ComplexId
},
Id = item.Id Id = item.Id
}); });
i++; i++;
@ -199,6 +216,12 @@ namespace Brizco.Domain.Mappers
{ {
UserId = item.UserId, UserId = item.UserId,
ComplexId = item.ComplexId, ComplexId = item.ComplexId,
User = new ApplicationUser() {Id = item.UserId},
Complex = new Complex()
{
Name = item.ComplexName,
Id = item.ComplexId
},
Id = item.Id Id = item.Id
}); });
i++; i++;
@ -223,6 +246,10 @@ namespace Brizco.Domain.Mappers
ComplexUser item = p18[i]; ComplexUser item = p18[i];
result.Add(item == null ? null : new ComplexUserSDto() result.Add(item == null ? null : new ComplexUserSDto()
{ {
FirstName = item.User != null ? item.User.FirstName : string.Empty,
LastName = item.User != null ? item.User.LastName : string.Empty,
NationalId = item.User != null ? item.User.NationalId : string.Empty,
ComplexName = item.Complex != null ? item.Complex.Name : string.Empty,
UserId = item.UserId, UserId = item.UserId,
ComplexId = item.ComplexId, ComplexId = item.ComplexId,
Id = item.Id Id = item.Id
@ -249,6 +276,10 @@ namespace Brizco.Domain.Mappers
ComplexUser item = p21[i]; ComplexUser item = p21[i];
result.Add(item == null ? null : new ComplexUserSDto() result.Add(item == null ? null : new ComplexUserSDto()
{ {
FirstName = item.User != null ? item.User.FirstName : string.Empty,
LastName = item.User != null ? item.User.LastName : string.Empty,
NationalId = item.User != null ? item.User.NationalId : string.Empty,
ComplexName = item.Complex != null ? item.Complex.Name : string.Empty,
UserId = item.UserId, UserId = item.UserId,
ComplexId = item.ComplexId, ComplexId = item.ComplexId,
Id = item.Id Id = item.Id

View File

@ -2,6 +2,8 @@ using System;
using System.Linq.Expressions; using System.Linq.Expressions;
using Brizco.Domain.Dtos.SmallDtos; using Brizco.Domain.Dtos.SmallDtos;
using Brizco.Domain.Entities.Complex; using Brizco.Domain.Entities.Complex;
using Brizco.Domain.Entities.User;
using Mapster.Models;
namespace Brizco.Domain.Mappers namespace Brizco.Domain.Mappers
{ {
@ -13,6 +15,12 @@ namespace Brizco.Domain.Mappers
{ {
UserId = p1.UserId, UserId = p1.UserId,
ComplexId = p1.ComplexId, ComplexId = p1.ComplexId,
User = new ApplicationUser() {Id = p1.UserId},
Complex = new Complex()
{
Name = p1.ComplexName,
Id = p1.ComplexId
},
Id = p1.Id Id = p1.Id
}; };
} }
@ -26,44 +34,83 @@ namespace Brizco.Domain.Mappers
result.UserId = p2.UserId; result.UserId = p2.UserId;
result.ComplexId = p2.ComplexId; result.ComplexId = p2.ComplexId;
result.User = funcMain1(new Never(), result.User, p2);
result.Complex = funcMain2(new Never(), result.Complex, p2);
result.Id = p2.Id; result.Id = p2.Id;
return result; return result;
} }
public static Expression<Func<ComplexUserSDto, ComplexUser>> ProjectToComplexUser => p4 => new ComplexUser() public static Expression<Func<ComplexUserSDto, ComplexUser>> ProjectToComplexUser => p8 => new ComplexUser()
{
UserId = p4.UserId,
ComplexId = p4.ComplexId,
Id = p4.Id
};
public static ComplexUserSDto AdaptToSDto(this ComplexUser p5)
{
return p5 == null ? null : new ComplexUserSDto()
{
UserId = p5.UserId,
ComplexId = p5.ComplexId,
Id = p5.Id
};
}
public static ComplexUserSDto AdaptTo(this ComplexUser p6, ComplexUserSDto p7)
{
if (p6 == null)
{
return null;
}
ComplexUserSDto result = p7 ?? new ComplexUserSDto();
result.UserId = p6.UserId;
result.ComplexId = p6.ComplexId;
result.Id = p6.Id;
return result;
}
public static Expression<Func<ComplexUser, ComplexUserSDto>> ProjectToSDto => p8 => new ComplexUserSDto()
{ {
UserId = p8.UserId, UserId = p8.UserId,
ComplexId = p8.ComplexId, ComplexId = p8.ComplexId,
User = new ApplicationUser() {Id = p8.UserId},
Complex = new Complex()
{
Name = p8.ComplexName,
Id = p8.ComplexId
},
Id = p8.Id Id = p8.Id
}; };
public static ComplexUserSDto AdaptToSDto(this ComplexUser p9)
{
return p9 == null ? null : new ComplexUserSDto()
{
FirstName = p9.User != null ? p9.User.FirstName : string.Empty,
LastName = p9.User != null ? p9.User.LastName : string.Empty,
NationalId = p9.User != null ? p9.User.NationalId : string.Empty,
ComplexName = p9.Complex != null ? p9.Complex.Name : string.Empty,
UserId = p9.UserId,
ComplexId = p9.ComplexId,
Id = p9.Id
};
}
public static ComplexUserSDto AdaptTo(this ComplexUser p10, ComplexUserSDto p11)
{
if (p10 == null)
{
return null;
}
ComplexUserSDto result = p11 ?? new ComplexUserSDto();
result.FirstName = p10.User != null ? p10.User.FirstName : string.Empty;
result.LastName = p10.User != null ? p10.User.LastName : string.Empty;
result.NationalId = p10.User != null ? p10.User.NationalId : string.Empty;
result.ComplexName = p10.Complex != null ? p10.Complex.Name : string.Empty;
result.UserId = p10.UserId;
result.ComplexId = p10.ComplexId;
result.Id = p10.Id;
return result;
}
public static Expression<Func<ComplexUser, ComplexUserSDto>> ProjectToSDto => p12 => new ComplexUserSDto()
{
FirstName = p12.User != null ? p12.User.FirstName : string.Empty,
LastName = p12.User != null ? p12.User.LastName : string.Empty,
NationalId = p12.User != null ? p12.User.NationalId : string.Empty,
ComplexName = p12.Complex != null ? p12.Complex.Name : string.Empty,
UserId = p12.UserId,
ComplexId = p12.ComplexId,
Id = p12.Id
};
private static ApplicationUser funcMain1(Never p4, ApplicationUser p5, ComplexUserSDto p2)
{
ApplicationUser result = p5 ?? new ApplicationUser();
result.Id = p2.UserId;
return result;
}
private static Complex funcMain2(Never p6, Complex p7, ComplexUserSDto p2)
{
Complex result = p7 ?? new Complex();
result.Name = p2.ComplexName;
result.Id = p2.ComplexId;
return result;
}
} }
} }

View File

@ -13,10 +13,10 @@ public class MapsterRegister : IRegister
.TwoWays(); .TwoWays();
config.NewConfig<ComplexUser, ComplexUserSDto>() config.NewConfig<ComplexUser, ComplexUserSDto>()
.Map(s=>s.ComplexName,o=>o.Complex!=null ? o.Complex.Name : string.Empty) .Map("ComplexName", o=>o.Complex!=null ? o.Complex.Name : string.Empty)
.Map(s=>s.FirstName,o=>o.User!=null ? o.User.FirstName : string.Empty) .Map("FirstName", o=>o.User!=null ? o.User.FirstName : string.Empty)
.Map(s=>s.LastName,o=>o.User!=null ? o.User.LastName : string.Empty) .Map("LastName", o=>o.User!=null ? o.User.LastName : string.Empty)
.Map(s=>s.InternationalId,o=>o.User!=null ? o.User.NationalId : string.Empty) .Map("NationalId", o=>o.User!=null ? o.User.NationalId : string.Empty)
.TwoWays(); .TwoWays();
} }
} }

View File

@ -21,8 +21,14 @@ public class DeleteComplexUserCommandHandler : IRequestHandler<DeleteComplexUser
.FirstOrDefaultAsync(c => c.ComplexId == request.ComplexId && c.UserId == request.UserId, cancellationToken); .FirstOrDefaultAsync(c => c.ComplexId == request.ComplexId && c.UserId == request.UserId, cancellationToken);
if (complexUser == null) if (complexUser == null)
throw new AppException("ComplexUser not found", ApiResultStatusCode.NotFound); throw new AppException("ComplexUser not found", ApiResultStatusCode.NotFound);
var complexUserRoles = await _repositoryWrapper.SetRepository<ComplexUserRole>().TableNoTracking
.Where(c => c.ComplexUserId == complexUser.Id)
.ToListAsync(cancellationToken);
foreach (var complexUserRole in complexUserRoles)
_repositoryWrapper.SetRepository<ComplexUserRole>().HardDelete(complexUserRole);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
_repositoryWrapper.SetRepository<ComplexUser>().Delete(complexUser); _repositoryWrapper.SetRepository<ComplexUser>().HardDelete(complexUser);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await _repositoryWrapper.CommitAsync(cancellationToken);
return true; return true;

View File

@ -1,4 +1,5 @@
using Brizco.Domain.Entities.Complex; using Brizco.Domain.Entities.Complex;
using Brizco.Domain.Entities.User;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
namespace Brizco.Repository.Handlers.Complex; namespace Brizco.Repository.Handlers.Complex;
@ -6,27 +7,54 @@ namespace Brizco.Repository.Handlers.Complex;
public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery, List<ComplexUserSDto>> public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery, List<ComplexUserSDto>>
{ {
private readonly IRepositoryWrapper _repositoryWrapper; private readonly IRepositoryWrapper _repositoryWrapper;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public GetComplexUsersQueryHandler(IRepositoryWrapper repositoryWrapper) public GetComplexUsersQueryHandler(IRepositoryWrapper repositoryWrapper, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{ {
_repositoryWrapper = repositoryWrapper; _repositoryWrapper = repositoryWrapper;
_userManager = userManager;
_roleManager = roleManager;
} }
public async Task<List<ComplexUserSDto>> Handle(GetComplexUsersQuery request, CancellationToken cancellationToken) public async Task<List<ComplexUserSDto>> Handle(GetComplexUsersQuery request, CancellationToken cancellationToken)
{ {
List<ComplexUserSDto> list = new List<ComplexUserSDto>();
if (!request.ComplexId.IsNullOrEmpty() && Guid.TryParse(request.ComplexId, out Guid complexId)) if (!request.ComplexId.IsNullOrEmpty() && Guid.TryParse(request.ComplexId, out Guid complexId))
return await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking {
list = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.Where(c => c.ComplexId == complexId) .Where(c => c.ComplexId == complexId)
.OrderByDescending(s => s.CreatedAt) .OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15) .Skip(request.Page * 15).Take(15)
.Select(ComplexUserMapper.ProjectToSDto) .Select(ComplexUserMapper.ProjectToSDto)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
}
else
{
list = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15)
.Select(ComplexUserMapper.ProjectToSDto)
.ToListAsync(cancellationToken);
}
return await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.OrderByDescending(s => s.CreatedAt) foreach (var complexUser in list)
.Skip(request.Page * 15).Take(15) {
.Select(ComplexUserMapper.ProjectToSDto) var user = await _userManager.FindByIdAsync(complexUser.UserId.ToString());
.ToListAsync(cancellationToken); if (user != null)
{
var roleIds = await _userManager.GetRolesAsync(user);
foreach (var roleId in roleIds)
{
var role = await _roleManager.FindByNameAsync(roleId);
if(role!= null)
complexUser.RoleNames.Add(role.PersianName);
}
}
}
return list;
} }
} }

View File

@ -4,9 +4,11 @@ namespace Brizco.Repository.Repositories.Base
{ {
public class BaseRepository<T> : Repository<T>, IBaseRepository<T> where T : class, IApiEntity public class BaseRepository<T> : Repository<T>, IBaseRepository<T> where T : class, IApiEntity
{ {
public BaseRepository(ApplicationContext dbContext) : base(dbContext) private readonly ICurrentUserService _currentUserService;
{
public BaseRepository(ApplicationContext dbContext, ICurrentUserService currentUserService) : base(dbContext)
{
_currentUserService = currentUserService;
} }
public virtual async ValueTask<T> GetByIdAsync(CancellationToken cancellationToken, params object[] ids) public virtual async ValueTask<T> GetByIdAsync(CancellationToken cancellationToken, params object[] ids)
@ -57,13 +59,32 @@ namespace Brizco.Repository.Repositories.Base
public virtual void Delete(T entity) public virtual void Delete(T entity)
{ {
AssertExtensions.NotNull(entity, nameof(entity)); AssertExtensions.NotNull(entity, nameof(entity));
Entities.Remove(entity);
Entities.Entry(entity).Property(e => e.RemovedAt)
.CurrentValue = DateTime.Now;
Entities.Entry(entity).Property(e => e.IsRemoved)
.CurrentValue = true;
if (_currentUserService.UserName != null)
Entities.Entry(entity).Property(e => e.RemovedBy)
.CurrentValue = _currentUserService.UserName;
Entities.Update(entity);
} }
public virtual void DeleteRange(IEnumerable<T> entities) public virtual void DeleteRange(IEnumerable<T> entities)
{ {
AssertExtensions.NotNull(entities, nameof(entities)); var apiEntities = entities.ToList();
Entities.RemoveRange(entities); AssertExtensions.NotNull(apiEntities, nameof(entities));
foreach (var entity in apiEntities)
{
Entities.Entry(entity).Property(e => e.RemovedAt)
.CurrentValue = DateTime.Now;
Entities.Entry(entity).Property(e => e.IsRemoved)
.CurrentValue = true;
if (_currentUserService.UserName != null)
Entities.Entry(entity).Property(e => e.RemovedBy)
.CurrentValue = _currentUserService.UserName;
Entities.Update(entity);
}
} }
#endregion #endregion

View File

@ -1,17 +1,18 @@
using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage;
namespace Brizco.Repository.Repositories.Base; namespace Brizco.Repository.Repositories.Base;
public class RepositoryWrapper : IRepositoryWrapper public class RepositoryWrapper : IRepositoryWrapper
{ {
private readonly ApplicationContext _context; private readonly ApplicationContext _context;
private readonly ICurrentUserService _currentUserService;
private IDbContextTransaction? _currentTransaction; private IDbContextTransaction? _currentTransaction;
public RepositoryWrapper(ApplicationContext context) public RepositoryWrapper(ApplicationContext context, ICurrentUserService currentUserService)
{ {
_context = context; _context = context;
_currentUserService = currentUserService;
} }
public IBaseRepository<T> SetRepository<T>() where T : ApiEntity => new BaseRepository<T>(_context); public IBaseRepository<T> SetRepository<T>() where T : ApiEntity => new BaseRepository<T>(_context, _currentUserService);
public async Task RollBackAsync(CancellationToken cancellationToken) public async Task RollBackAsync(CancellationToken cancellationToken)
@ -51,14 +52,9 @@ public class RepositoryWrapper : IRepositoryWrapper
{ {
entity.Property(e => e.ModifiedAt) entity.Property(e => e.ModifiedAt)
.CurrentValue = DateTime.Now; .CurrentValue = DateTime.Now;
} if (_currentUserService.UserName != null)
entity.Property(e => e.ModifiedBy)
if (entity.State == EntityState.Deleted) .CurrentValue = _currentUserService.UserName;
{
entity.Property(e => e.RemovedAt)
.CurrentValue = DateTime.Now;
entity.Property(e => e.IsRemoved)
.CurrentValue = true;
} }
} }
} }

View File

@ -1,10 +1,15 @@
 
using Brizco.Repository.Abstracts;
namespace Brizco.Repository.Repositories.Base namespace Brizco.Repository.Repositories.Base
{ {
public class WriteRepository<T> : Repository<T>, IDisposable, IWriteRepository<T> where T : class, IApiEntity public class WriteRepository<T> : Repository<T>, IDisposable, IWriteRepository<T> where T : class, IApiEntity
{ {
public WriteRepository(ApplicationContext dbContext) : base(dbContext) private readonly ICurrentUserService _currentUserService;
public WriteRepository(ApplicationContext dbContext,ICurrentUserService currentUserService) : base(dbContext)
{ {
_currentUserService = currentUserService;
} }
public void Dispose() public void Dispose()
@ -46,13 +51,32 @@ namespace Brizco.Repository.Repositories.Base
public virtual void Delete(T entity) public virtual void Delete(T entity)
{ {
AssertExtensions.NotNull(entity, nameof(entity)); AssertExtensions.NotNull(entity, nameof(entity));
Entities.Remove(entity);
Entities.Entry(entity).Property(e => e.RemovedAt)
.CurrentValue = DateTime.Now;
Entities.Entry(entity).Property(e => e.IsRemoved)
.CurrentValue = true;
if (_currentUserService.UserName != null)
Entities.Entry(entity).Property(e => e.RemovedBy)
.CurrentValue = _currentUserService.UserName;
Entities.Update(entity);
} }
public virtual void DeleteRange(IEnumerable<T> entities) public virtual void DeleteRange(IEnumerable<T> entities)
{ {
AssertExtensions.NotNull(entities, nameof(entities)); var apiEntities = entities.ToList();
Entities.RemoveRange(entities); AssertExtensions.NotNull(apiEntities, nameof(entities));
foreach (var entity in apiEntities)
{
Entities.Entry(entity).Property(e => e.RemovedAt)
.CurrentValue = DateTime.Now;
Entities.Entry(entity).Property(e => e.IsRemoved)
.CurrentValue = true;
if (_currentUserService.UserName != null)
Entities.Entry(entity).Property(e => e.RemovedBy)
.CurrentValue = _currentUserService.UserName;
Entities.Update(entity);
}
} }
public virtual void Detach(T entity) public virtual void Detach(T entity)