fix( SetNotifyCommand )

master
Amir Hossein Khademi 2024-08-09 21:42:04 +03:30
parent bca1447ad4
commit 1f99790b97
69 changed files with 654 additions and 1127 deletions

View File

@ -1,7 +1,7 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"PostgresServer": "Host=185.220.227.126;port=5432;Username=postgres;Password=ub0J7sFFThkSBmkc0TzSKsCfheRnQpyu;Database=BrizcoDB", "PostgresServer": "Host=185.228.236.6;port=5432;Username=postgres;Password=ub0J7sFFThkSBmkc0TzSKsCfheRnQpyu;Database=BrizcoDB",
"MartenDBServer": "Host=185.228.236.40;port=5432;Username=postgres;Password=ub0J7sFFThkSBmkc0TzSKsCfheRnQpyu;Database=BrizcoMartenDB", "MartenDBServer": "Host=185.228.236.6;port=5432;Username=postgres;Password=ub0J7sFFThkSBmkc0TzSKsCfheRnQpyu;Database=BrizcoMartenDB",
"Postgres": "Host=pg-0;Username=postgres;Password=xHTpBf4wC+bBeNg2pL6Ga7VEWKFJx7VPEUpqxwPFfOc2YYTVwFQuHfsiqoVeT9+6;Database=BrizcoDB;Application Name=BrizCo", "Postgres": "Host=pg-0;Username=postgres;Password=xHTpBf4wC+bBeNg2pL6Ga7VEWKFJx7VPEUpqxwPFfOc2YYTVwFQuHfsiqoVeT9+6;Database=BrizcoDB;Application Name=BrizCo",
"MartenDB": "Host=pg-0;Username=postgres;Password=xHTpBf4wC+bBeNg2pL6Ga7VEWKFJx7VPEUpqxwPFfOc2YYTVwFQuHfsiqoVeT9+6;Database=BrizcoMartenDB;" "MartenDB": "Host=pg-0;Username=postgres;Password=xHTpBf4wC+bBeNg2pL6Ga7VEWKFJx7VPEUpqxwPFfOc2YYTVwFQuHfsiqoVeT9+6;Database=BrizcoMartenDB;"
}, },

View File

@ -2,20 +2,13 @@
namespace Brizco.Api.Services; namespace Brizco.Api.Services;
public class CurrentUserService : ICurrentUserService public class CurrentUserService(IHttpContextAccessor httpContextAccessor) : ICurrentUserService
{ {
private readonly IHttpContextAccessor _httpContextAccessor; public string? UserId => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
public string? RoleName => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Role);
public CurrentUserService(IHttpContextAccessor httpContextAccessor) public string? UserName => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
{ public string? ComplexId => httpContextAccessor.HttpContext?.User?.FindFirstValue("ComplexId");
_httpContextAccessor = httpContextAccessor; public string? RoleId => httpContextAccessor.HttpContext?.User?.FindFirstValue("RoleId");
} public string? FullName => httpContextAccessor.HttpContext?.User?.FindFirstValue("FullName");
public List<string>? Permissions => httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c=>c.Value)?.ToList();
public string? UserId => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
public string? RoleName => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Role);
public string? UserName => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
public string? ComplexId => _httpContextAccessor.HttpContext?.User?.FindFirstValue("ComplexId");
public string? RoleId => _httpContextAccessor.HttpContext?.User?.FindFirstValue("RoleId");
public string? FullName => _httpContextAccessor.HttpContext?.User?.FindFirstValue("FullName");
public List<string>? Permissions => _httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c=>c.Value)?.ToList();
} }

View File

@ -5,18 +5,13 @@ using Microsoft.AspNetCore.Routing.Patterns;
namespace Brizco.Api.WebFramework.Bases; namespace Brizco.Api.WebFramework.Bases;
public class CrudEndpoint<TEntity,TGetAllQuery,TGetOneQuery,TCreateCommand,TUpdateCommand,TDeleteCommand> where TEntity : ApiEntity, new() public class CrudEndpoint<TEntity, TGetAllQuery, TGetOneQuery, TCreateCommand, TUpdateCommand, TDeleteCommand>(
string endpointName)
where TEntity : ApiEntity, new()
{ {
private readonly string _endpointName;
public CrudEndpoint(string endpointName)
{
_endpointName = endpointName;
}
public virtual void AddRoutes(IEndpointRouteBuilder app) public virtual void AddRoutes(IEndpointRouteBuilder app)
{ {
var group = app.NewVersionedApi(_endpointName).MapGroup($"api/{_endpointName}"); var group = app.NewVersionedApi(endpointName).MapGroup($"api/{endpointName}");
group.MapGet("", GetAllAsync) group.MapGet("", GetAllAsync)
.WithDisplayName("GetAll") .WithDisplayName("GetAll")
@ -82,16 +77,11 @@ public class BaseController : ControllerBase
} }
[Authorize(AuthenticationSchemes = "Bearer")] [Authorize(AuthenticationSchemes = "Bearer")]
public class CrudController<TDto, TEntity> : BaseController public class CrudController<TDto, TEntity>(IRepositoryWrapper repositoryWrapper) : BaseController
where TDto : BaseDto<TDto, TEntity>, new() where TDto : BaseDto<TDto, TEntity>, new()
where TEntity : ApiEntity, new() where TEntity : ApiEntity, new()
{ {
protected readonly IRepositoryWrapper _repositoryWrapper; protected readonly IRepositoryWrapper _repositoryWrapper = repositoryWrapper;
public CrudController(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
// GET:Get All Entity // GET:Get All Entity
[HttpGet] [HttpGet]
@ -167,15 +157,10 @@ public class CrudController<TDto, TEntity> : BaseController
} }
[Authorize(AuthenticationSchemes = "Bearer")] [Authorize(AuthenticationSchemes = "Bearer")]
public class CrudController<TEntity> : BaseController public class CrudController<TEntity>(IRepositoryWrapper repositoryWrapper) : BaseController
where TEntity : ApiEntity, new() where TEntity : ApiEntity, new()
{ {
protected readonly IRepositoryWrapper _repositoryWrapper; protected readonly IRepositoryWrapper _repositoryWrapper = repositoryWrapper;
public CrudController(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
// GET:Get All Entity // GET:Get All Entity
[HttpGet] [HttpGet]

View File

@ -80,7 +80,7 @@ public static class ServiceExtensions
serviceCollection.AddDbContextFactory<ApplicationContext>(options => serviceCollection.AddDbContextFactory<ApplicationContext>(options =>
{ {
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
options.UseNpgsql(Configuration.GetConnectionString("Postgres"), b => b.MigrationsAssembly("Brizco.Repository")) options.UseNpgsql(Configuration.GetConnectionString("PostgresServer"), b => b.MigrationsAssembly("Brizco.Repository"))
.UseProjectAssembly(typeof(ApplicationUser).Assembly); .UseProjectAssembly(typeof(ApplicationUser).Assembly);
//options.EnableServiceProviderCaching(true); //options.EnableServiceProviderCaching(true);
}).BuildServiceProvider(); }).BuildServiceProvider();
@ -117,7 +117,7 @@ public static class ServiceExtensions
{ {
var marten = serviceCollection.AddMarten(options => var marten = serviceCollection.AddMarten(options =>
{ {
options.Connection(configuration.GetConnectionString("MartenDB")!); options.Connection(configuration.GetConnectionString("MartenDBServer")!);
if (environment.IsDevelopment()) if (environment.IsDevelopment())
options.AutoCreateSchemaObjects = AutoCreate.All; options.AutoCreateSchemaObjects = AutoCreate.All;
}); });

View File

@ -12,22 +12,11 @@ public static class ExceptionHandlerMiddlewareExtensions
} }
} }
public class ExceptionHandlerMiddleware public class ExceptionHandlerMiddleware(
RequestDelegate next,
IWebHostEnvironment env,
ILogger<ExceptionHandlerMiddleware> logger)
{ {
private readonly IWebHostEnvironment _env;
private readonly ILogger<ExceptionHandlerMiddleware> _logger;
private readonly RequestDelegate _next;
public ExceptionHandlerMiddleware(
RequestDelegate next,
IWebHostEnvironment env,
ILogger<ExceptionHandlerMiddleware> logger)
{
_next = next;
_env = env;
_logger = logger;
}
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
string message = null; string message = null;
@ -36,15 +25,15 @@ public class ExceptionHandlerMiddleware
try try
{ {
await _next(context); await next(context);
} }
catch (BaseApiException exception) catch (BaseApiException exception)
{ {
_logger.LogError(exception, exception.Message); logger.LogError(exception, exception.Message);
httpStatusCode = exception.HttpStatusCode; httpStatusCode = exception.HttpStatusCode;
apiStatusCode = exception.ApiStatusCode; apiStatusCode = exception.ApiStatusCode;
if (_env.IsDevelopment()) if (env.IsDevelopment())
{ {
var dic = new Dictionary<string, string> var dic = new Dictionary<string, string>
{ {
@ -82,22 +71,22 @@ public class ExceptionHandlerMiddleware
} }
catch (SecurityTokenExpiredException exception) catch (SecurityTokenExpiredException exception)
{ {
_logger.LogError(exception, exception.Message); logger.LogError(exception, exception.Message);
SetUnAuthorizeResponse(exception); SetUnAuthorizeResponse(exception);
await WriteToResponseAsync(); await WriteToResponseAsync();
} }
catch (UnauthorizedAccessException exception) catch (UnauthorizedAccessException exception)
{ {
_logger.LogError(exception, exception.Message); logger.LogError(exception, exception.Message);
SetUnAuthorizeResponse(exception); SetUnAuthorizeResponse(exception);
await WriteToResponseAsync(); await WriteToResponseAsync();
} }
catch (Exception exception) catch (Exception exception)
{ {
_logger.LogError(exception, exception.Message); logger.LogError(exception, exception.Message);
if (_env.IsDevelopment()) if (env.IsDevelopment())
{ {
var dic = new Dictionary<string, string> var dic = new Dictionary<string, string>
{ {
@ -170,7 +159,7 @@ public class ExceptionHandlerMiddleware
httpStatusCode = HttpStatusCode.Unauthorized; httpStatusCode = HttpStatusCode.Unauthorized;
apiStatusCode = ApiResultStatusCode.UnAuthorized; apiStatusCode = ApiResultStatusCode.UnAuthorized;
if (_env.IsDevelopment()) if (env.IsDevelopment())
{ {
var dic = new Dictionary<string, string> var dic = new Dictionary<string, string>
{ {

View File

@ -10,28 +10,19 @@ public static class PerformanceMiddlewareExtensions
} }
} }
public class PerformanceMiddleware public class PerformanceMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlerMiddleware> logger)
{ {
private readonly ILogger<ExceptionHandlerMiddleware> _logger; private readonly Stopwatch _timer = new();
private readonly RequestDelegate _next;
private readonly Stopwatch _timer;
public PerformanceMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlerMiddleware> logger)
{
_next = next;
_logger = logger;
_timer = new Stopwatch();
}
public async System.Threading.Tasks.Task Invoke(HttpContext context) public async System.Threading.Tasks.Task Invoke(HttpContext context)
{ {
_timer.Start(); _timer.Start();
await _next(context); await next(context);
_timer.Stop(); _timer.Stop();
var elapsedMilliseconds = _timer.ElapsedMilliseconds; var elapsedMilliseconds = _timer.ElapsedMilliseconds;
_logger.LogWarning($"REQUEST TIMER : {elapsedMilliseconds}"); logger.LogWarning($"REQUEST TIMER : {elapsedMilliseconds}");
} }
} }

View File

@ -139,17 +139,12 @@ public class SetVersionInPaths : IDocumentFilter
} }
} }
public class UnauthorizedResponsesOperationFilter : IOperationFilter public class UnauthorizedResponsesOperationFilter(
bool includeUnauthorizedAndForbiddenResponses,
string schemeName = "Bearer")
: IOperationFilter
{ {
private readonly bool includeUnauthorizedAndForbiddenResponses; private readonly string schemeName = schemeName;
private readonly string schemeName;
public UnauthorizedResponsesOperationFilter(bool includeUnauthorizedAndForbiddenResponses,
string schemeName = "Bearer")
{
this.includeUnauthorizedAndForbiddenResponses = includeUnauthorizedAndForbiddenResponses;
this.schemeName = schemeName;
}
public void Apply(OpenApiOperation operation, OperationFilterContext context) public void Apply(OpenApiOperation operation, OperationFilterContext context)
{ {

View File

@ -6,56 +6,33 @@ using NPOI.SS.Formula.Functions;
namespace Brizco.Core.CoreServices; namespace Brizco.Core.CoreServices;
public class AccountService : IAccountService public class AccountService(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> userSignInManager,
IJwtService jwtService,
ICurrentUserService currentUserService,
IRepositoryWrapper repositoryWrapper,
ISmsService smsService,
IComplexService complexService,
IUserService userService)
: IAccountService
{ {
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _userSignInManager;
private readonly IJwtService _jwtService;
private readonly ICurrentUserService _currentUserService;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ISmsService _smsService;
private readonly IComplexService _complexService;
private readonly IUserService _userService;
public AccountService(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> userSignInManager,
IJwtService jwtService,
ICurrentUserService currentUserService,
IRepositoryWrapper repositoryWrapper,
ISmsService smsService,
IComplexService complexService,
IUserService userService)
{
_userManager = userManager;
_userSignInManager = userSignInManager;
_jwtService = jwtService;
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
_smsService = smsService;
_complexService = complexService;
_userService = userService;
}
public async Task<bool> ForgetPasswordAsync(string phoneNumber) public async Task<bool> ForgetPasswordAsync(string phoneNumber)
{ {
var user = await _userManager.FindByNameAsync(phoneNumber); var user = await userManager.FindByNameAsync(phoneNumber);
if (user != null) if (user != null)
{ {
var rand = new Random(DateTime.Now.Millisecond); var rand = new Random(DateTime.Now.Millisecond);
var newPass = rand.Next(1000000, 9000000).ToString(); var newPass = rand.Next(1000000, 9000000).ToString();
if (!user.PhoneNumberConfirmed) if (!user.PhoneNumberConfirmed)
throw new AppException("شماره تلفن شما تایید نشده است و قابلیت استفاده از فراموشی رمز عبور را ندارید"); throw new AppException("شماره تلفن شما تایید نشده است و قابلیت استفاده از فراموشی رمز عبور را ندارید");
var rp = await _userManager.RemovePasswordAsync(user); var rp = await userManager.RemovePasswordAsync(user);
if (!rp.Succeeded) if (!rp.Succeeded)
throw new AppException(string.Join('-', rp.Errors.Select(e => e.Description))); throw new AppException(string.Join('-', rp.Errors.Select(e => e.Description)));
var ap = await _userManager.AddPasswordAsync(user, newPass); var ap = await userManager.AddPasswordAsync(user, newPass);
if (!ap.Succeeded) if (!ap.Succeeded)
throw new AppException(string.Join('-', ap.Errors.Select(e => e.Description))); throw new AppException(string.Join('-', ap.Errors.Select(e => e.Description)));
await _smsService.SendForgerPasswordAsync(user.PhoneNumber, newPass); await smsService.SendForgerPasswordAsync(user.PhoneNumber, newPass);
return true; return true;
} }
@ -64,7 +41,7 @@ public class AccountService : IAccountService
public async Task<bool> CheckMemberShipAsync(string phoneNumber) public async Task<bool> CheckMemberShipAsync(string phoneNumber)
{ {
var user = await _userManager.FindByNameAsync(phoneNumber); var user = await userManager.FindByNameAsync(phoneNumber);
if (user == null) if (user == null)
return false; return false;
return true; return true;
@ -72,17 +49,17 @@ public class AccountService : IAccountService
public async Task<bool> CheckPositionPermission(string permission, CancellationToken cancellationToken=default) public async Task<bool> CheckPositionPermission(string permission, CancellationToken cancellationToken=default)
{ {
if (_currentUserService.UserId == null) if (currentUserService.UserId == null)
throw new BaseApiException(ApiResultStatusCode.BadRequest, "User id is wrong"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "User id is wrong");
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId)) if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new BaseApiException(ApiResultStatusCode.BadRequest, "User id is wrong"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "User id is wrong");
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong");
if(!Guid.TryParse(_currentUserService.ComplexId,out Guid complexId)) if(!Guid.TryParse(currentUserService.ComplexId,out Guid complexId))
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong");
var query = from shiftPlan in _repositoryWrapper.SetRepository<ShiftPlan>().Entities var query = from shiftPlan in repositoryWrapper.SetRepository<ShiftPlan>().Entities
join shift in _repositoryWrapper.SetRepository<Shift>().Entities on shiftPlan.ShiftId equals shift.Id join shift in repositoryWrapper.SetRepository<Shift>().Entities on shiftPlan.ShiftId equals shift.Id
where shiftPlan.PlanFor.Date == DateTime.Today.Date && shiftPlan.ComplexId == complexId && where shiftPlan.PlanFor.Date == DateTime.Today.Date && shiftPlan.ComplexId == complexId &&
shift.EndAt >= DateTime.Now.TimeOfDay && shift.StartAt <= DateTime.Now.TimeOfDay shift.EndAt >= DateTime.Now.TimeOfDay && shift.StartAt <= DateTime.Now.TimeOfDay
select shiftPlan; select shiftPlan;
@ -92,10 +69,10 @@ public class AccountService : IAccountService
throw new BaseApiException(ApiResultStatusCode.BadRequest, "No active shift plan"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "No active shift plan");
var userCurrentPositionPermissions = var userCurrentPositionPermissions =
await (from positionPermission in _repositoryWrapper.SetRepository<PositionPermission>().Entities await (from positionPermission in repositoryWrapper.SetRepository<PositionPermission>().Entities
join position in _repositoryWrapper.SetRepository<Position>().Entities on positionPermission.PositionId join position in repositoryWrapper.SetRepository<Position>().Entities on positionPermission.PositionId
equals position.Id equals position.Id
join shiftPlaneUser in _repositoryWrapper.SetRepository<ShiftPlanUser>().Entities on position.Id equals join shiftPlaneUser in repositoryWrapper.SetRepository<ShiftPlanUser>().Entities on position.Id equals
shiftPlaneUser.PositionId shiftPlaneUser.PositionId
where shiftPlaneUser.ShiftPlanId == currentShiftPlan.Id && shiftPlaneUser.UserId == userId where shiftPlaneUser.ShiftPlanId == currentShiftPlan.Id && shiftPlaneUser.UserId == userId
select positionPermission).ToListAsync(cancellationToken); select positionPermission).ToListAsync(cancellationToken);
@ -108,23 +85,23 @@ public class AccountService : IAccountService
var newPhoneNumber = StringExtensions.CheckPhoneNumber(phoneNumber); var newPhoneNumber = StringExtensions.CheckPhoneNumber(phoneNumber);
if (!PhoneNumberExtensions.CheckPhoneNumber(newPhoneNumber)) if (!PhoneNumberExtensions.CheckPhoneNumber(newPhoneNumber))
throw new AppException("شماره تلفن ارسالی اشتباه است"); throw new AppException("شماره تلفن ارسالی اشتباه است");
var user = await _userManager.FindByNameAsync(newPhoneNumber); var user = await userManager.FindByNameAsync(newPhoneNumber);
if (user == null) if (user == null)
user = await _userService.CreateUserAsync(phoneNumber); user = await userService.CreateUserAsync(phoneNumber);
var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Phone"); var token = await userManager.GenerateTwoFactorTokenAsync(user, "Phone");
await _smsService.SendVerifyCodeAsync(newPhoneNumber, token); await smsService.SendVerifyCodeAsync(newPhoneNumber, token);
return new VerifyCodeResponseDto { SignUpStatus = SignUpStatus.StartSignOn }; return new VerifyCodeResponseDto { SignUpStatus = SignUpStatus.StartSignOn };
} }
public async Task<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> LoginWithPasswordAsync(string userName, string password, CancellationToken cancellationToken) public async Task<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> LoginWithPasswordAsync(string userName, string password, CancellationToken cancellationToken)
{ {
var result = await _userSignInManager.PasswordSignInAsync(userName, password, false, false); var result = await userSignInManager.PasswordSignInAsync(userName, password, false, false);
if (!result.Succeeded) if (!result.Succeeded)
throw new AppException("رمز عبور یا نام کاربری اشتباه است"); throw new AppException("رمز عبور یا نام کاربری اشتباه است");
var admin = await _userManager.FindByNameAsync(userName); var admin = await userManager.FindByNameAsync(userName);
if (admin == null) if (admin == null)
throw new AppException("نام کاربری یا رمز عبور اشتباه است"); throw new AppException("نام کاربری یا رمز عبور اشتباه است");
return await CompleteLogin(admin, cancellationToken); return await CompleteLogin(admin, cancellationToken);
@ -132,11 +109,11 @@ public class AccountService : IAccountService
public async Task<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> LoginWithVerifyCodeAsync(string userName, string verifyCode, CancellationToken cancellationToken) public async Task<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> LoginWithVerifyCodeAsync(string userName, string verifyCode, CancellationToken cancellationToken)
{ {
var user = await _userManager.FindByNameAsync(userName); var user = await userManager.FindByNameAsync(userName);
if (user == null) if (user == null)
throw new AppException("نام کاربری یا کد ارسالی اشتباه است", ApiResultStatusCode.NotFound); throw new AppException("نام کاربری یا کد ارسالی اشتباه است", ApiResultStatusCode.NotFound);
var verfiyResult = await _userManager.VerifyTwoFactorTokenAsync(user, "Phone", verifyCode); var verfiyResult = await userManager.VerifyTwoFactorTokenAsync(user, "Phone", verifyCode);
if (verifyCode == "859585") if (verifyCode == "859585")
verfiyResult = true; verfiyResult = true;
if (!verfiyResult) if (!verfiyResult)
@ -145,7 +122,7 @@ public class AccountService : IAccountService
{ {
user.PhoneNumberConfirmed = true; user.PhoneNumberConfirmed = true;
user.SignUpStatus = SignUpStatus.PhoneNumberVerified; user.SignUpStatus = SignUpStatus.PhoneNumberVerified;
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));
} }
@ -154,9 +131,9 @@ public class AccountService : IAccountService
public async Task<AccessToken<ApplicationUserSDto,ComplexUserRoleSDto>> CompleteComplexSignUpAsync(SignUpRequestDto requestDto, CancellationToken cancellationToken) public async Task<AccessToken<ApplicationUserSDto,ComplexUserRoleSDto>> CompleteComplexSignUpAsync(SignUpRequestDto requestDto, CancellationToken cancellationToken)
{ {
if (_currentUserService.UserId == null) if (currentUserService.UserId == null)
throw new AppException("User Id is null"); throw new AppException("User Id is null");
var user = await _userManager.FindByIdAsync(_currentUserService.UserId); var user = await userManager.FindByIdAsync(currentUserService.UserId);
if (user == null) if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound); throw new AppException("User not found", ApiResultStatusCode.NotFound);
if (user.SignUpStatus == SignUpStatus.ComplexCreated) if (user.SignUpStatus == SignUpStatus.ComplexCreated)
@ -175,11 +152,11 @@ public class AccountService : IAccountService
user.FirstName = requestDto.FirstName; user.FirstName = requestDto.FirstName;
user.LastName = requestDto.LastName; user.LastName = requestDto.LastName;
user.SignUpStatus = SignUpStatus.ComplexCreated; user.SignUpStatus = SignUpStatus.ComplexCreated;
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.Select(e => e.Description))); throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
var complex = await _complexService.CreateComplexAsync(requestDto.ComplexName, var complex = await complexService.CreateComplexAsync(requestDto.ComplexName,
requestDto.ComplexAddress, requestDto.ComplexAddress,
requestDto.SupportPhoneNumber, requestDto.SupportPhoneNumber,
user.Id, user.Id,
@ -193,21 +170,21 @@ public class AccountService : IAccountService
AccessToken<ApplicationUserSDto,ComplexUserRoleSDto> jwt; AccessToken<ApplicationUserSDto,ComplexUserRoleSDto> jwt;
if (user.SelectedComplexUserRoleId != Guid.Empty) if (user.SelectedComplexUserRoleId != Guid.Empty)
{ {
var userComplexRoles = await _userService.GetUserRolesAsync(user.Id, cancellationToken); var userComplexRoles = await userService.GetUserRolesAsync(user.Id, cancellationToken);
var complexUserRole = userComplexRoles.FirstOrDefault(c => c.Id == user.SelectedComplexUserRoleId); var complexUserRole = userComplexRoles.FirstOrDefault(c => c.Id == user.SelectedComplexUserRoleId);
if (complexUserRole == null) if (complexUserRole == null)
{ {
complexUserRole = userComplexRoles.FirstOrDefault(); complexUserRole = userComplexRoles.FirstOrDefault();
user.SelectedComplexUserRoleId = complexUserRole!.Id; user.SelectedComplexUserRoleId = complexUserRole!.Id;
await _userManager.UpdateAsync(user); await userManager.UpdateAsync(user);
} }
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>() var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking .TableNoTracking
.Where(c => c.Id == complexUserRole!.ComplexUserId) .Where(c => c.Id == complexUserRole!.ComplexUserId)
.Select(ComplexUserMapper.ProjectToSDto) .Select(ComplexUserMapper.ProjectToSDto)
.FirstOrDefaultAsync( cancellationToken); .FirstOrDefaultAsync( cancellationToken);
jwt = await _jwtService.Generate<ApplicationUserSDto, ApplicationUser, ComplexUserRoleSDto>(user, complexUser!.ComplexId, complexUserRole!.RoleId); jwt = await jwtService.Generate<ApplicationUserSDto, ApplicationUser, ComplexUserRoleSDto>(user, complexUser!.ComplexId, complexUserRole!.RoleId);
jwt.User.SelectedComplexName = complexUser.ComplexName; jwt.User.SelectedComplexName = complexUser.ComplexName;
jwt.User.SelectedRoleName = complexUserRole.RoleName; jwt.User.SelectedRoleName = complexUserRole.RoleName;
jwt.User.SelectedRoleId = complexUserRole!.Id; jwt.User.SelectedRoleId = complexUserRole!.Id;
@ -215,16 +192,16 @@ public class AccountService : IAccountService
} }
else else
{ {
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>() var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking .TableNoTracking
.Where(mcu => mcu.UserId == user.Id) .Where(mcu => mcu.UserId == user.Id)
.OrderByDescending(o => o.CreatedAt) .OrderByDescending(o => o.CreatedAt)
.Select(ComplexUserMapper.ProjectToSDto) .Select(ComplexUserMapper.ProjectToSDto)
.FirstOrDefaultAsync(cancellationToken); .FirstOrDefaultAsync(cancellationToken);
if (complexUser == null) if (complexUser == null)
return (await _jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>(); return (await jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
var complexUserRole = await _repositoryWrapper.SetRepository<ComplexUserRole>() var complexUserRole = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking .TableNoTracking
.Where(c => c.ComplexUserId == complexUser.Id) .Where(c => c.ComplexUserId == complexUser.Id)
.OrderByDescending(o => o.CreatedAt) .OrderByDescending(o => o.CreatedAt)
@ -237,8 +214,8 @@ public class AccountService : IAccountService
{ {
user.SelectedComplexUserRoleId = complexUserRole.Id; user.SelectedComplexUserRoleId = complexUserRole.Id;
await _userManager.UpdateAsync(user); await userManager.UpdateAsync(user);
jwt = (await _jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>(); jwt = (await jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
jwt.User.SelectedComplexName = complexUser.ComplexName; jwt.User.SelectedComplexName = complexUser.ComplexName;
jwt.User.SelectedRoleName = complexUserRole.RoleName; jwt.User.SelectedRoleName = complexUserRole.RoleName;
jwt.User.SelectedRoleId = complexUserRole!.Id; jwt.User.SelectedRoleId = complexUserRole!.Id;

View File

@ -5,21 +5,14 @@ using Brizco.Domain.Entities.Users;
namespace Brizco.Core.CoreServices; namespace Brizco.Core.CoreServices;
public class JwtService : IJwtService public class JwtService(
IOptionsSnapshot<SiteSettings> siteSettings,
SignInManager<ApplicationUser> userSignInManager,
RoleManager<ApplicationRole> roleManager)
: IJwtService
{ {
private readonly SignInManager<ApplicationUser> _signInManager; private readonly SiteSettings _siteSettings = siteSettings.Value;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly SiteSettings _siteSettings;
public JwtService(
IOptionsSnapshot<SiteSettings> siteSettings,
SignInManager<ApplicationUser> userSignInManager,
RoleManager<ApplicationRole> roleManager)
{
_signInManager = userSignInManager;
_roleManager = roleManager;
_siteSettings = siteSettings.Value;
}
public async Task<AccessToken<TUser>> Generate<TUser>(TUser user, Guid complexId, Guid roleId) where TUser : ApplicationUser public async Task<AccessToken<TUser>> Generate<TUser>(TUser user, Guid complexId, Guid roleId) where TUser : ApplicationUser
{ {
var tokenId = StringExtensions.GetId(8); var tokenId = StringExtensions.GetId(8);
@ -150,7 +143,7 @@ public class JwtService : IJwtService
private async Task<List<Claim>> GetClaims<TUser>(TUser baseUser, string jwtId) where TUser : ApplicationUser private async Task<List<Claim>> GetClaims<TUser>(TUser baseUser, string jwtId) where TUser : ApplicationUser
{ {
var clFac = await _signInManager.ClaimsFactory.CreateAsync(baseUser); var clFac = await userSignInManager.ClaimsFactory.CreateAsync(baseUser);
var claims = new List<Claim>(); var claims = new List<Claim>();
claims.Add(new Claim("JwtID", jwtId)); claims.Add(new Claim("JwtID", jwtId));
claims.Add(new Claim(ClaimTypes.Name, baseUser.UserName)); claims.Add(new Claim(ClaimTypes.Name, baseUser.UserName));
@ -166,8 +159,8 @@ public class JwtService : IJwtService
private async Task<List<Claim>> GetClaims<TUser>(TUser baseUser, string jwtId, string roleId) where TUser : ApplicationUser private async Task<List<Claim>> GetClaims<TUser>(TUser baseUser, string jwtId, string roleId) where TUser : ApplicationUser
{ {
var applicationRole = await _roleManager.FindByIdAsync(roleId); var applicationRole = await roleManager.FindByIdAsync(roleId);
var roleClaims = await _roleManager.GetClaimsAsync(applicationRole); var roleClaims = await roleManager.GetClaimsAsync(applicationRole);
var claims = new List<Claim>(); var claims = new List<Claim>();
claims.Add(new Claim("SignUpStatus", ((int)baseUser.SignUpStatus).ToString())); claims.Add(new Claim("SignUpStatus", ((int)baseUser.SignUpStatus).ToString()));
claims.Add(new Claim(ClaimTypes.Name, baseUser.UserName)); claims.Add(new Claim(ClaimTypes.Name, baseUser.UserName));

View File

@ -3,38 +3,29 @@ using Task = Brizco.Domain.Entities.Tasks.Task;
namespace Brizco.Core.CoreServices; namespace Brizco.Core.CoreServices;
public class PageService : IPageService public class PageService(
ICurrentUserService currentUserService,
IRepositoryWrapper repositoryWrapper,
RoleManager<ApplicationRole> roleManager,
IMediator mediator)
: IPageService
{ {
private readonly ICurrentUserService _currentUserService; private readonly RoleManager<ApplicationRole> _roleManager = roleManager;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly IMediator _mediator;
public PageService(
ICurrentUserService currentUserService,
IRepositoryWrapper repositoryWrapper,
RoleManager<ApplicationRole> roleManager,
IMediator mediator)
{
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
_roleManager = roleManager;
_mediator = mediator;
}
public async Task<AppDashboardPageDto> GetAppDashboardAsync(CancellationToken cancellationToken = default) public async Task<AppDashboardPageDto> GetAppDashboardAsync(CancellationToken cancellationToken = default)
{ {
if (_currentUserService.UserId == null) if (currentUserService.UserId == null)
throw new AppException("User id is null "); throw new AppException("User id is null ");
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId)) if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new AppException("User id is wrong"); throw new AppException("User id is wrong");
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("Complex id is wrong"); throw new AppException("Complex id is wrong");
var todayActivities = await _repositoryWrapper.SetRepository<Activity>() var todayActivities = await repositoryWrapper.SetRepository<Activity>()
.TableNoTracking .TableNoTracking
.Where(a => a.ComplexId == complexId && a.SetFor.Date == DateTime.Today.Date) .Where(a => a.ComplexId == complexId && a.SetFor.Date == DateTime.Today.Date)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
var todayShiftPlans = await _repositoryWrapper.SetRepository<ShiftPlan>() var todayShiftPlans = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking .TableNoTracking
.Where(a => a.PlanFor.Date == DateTime.Today.Date && a.ComplexId == complexId) .Where(a => a.PlanFor.Date == DateTime.Today.Date && a.ComplexId == complexId)
.Select(ShiftPlanMapper.ProjectToSDto) .Select(ShiftPlanMapper.ProjectToSDto)
@ -68,15 +59,15 @@ public class PageService : IPageService
page.CurrentPosition = currentShift.Users.FirstOrDefault(f => f.UserId == userId)?.PositionName ?? string.Empty; page.CurrentPosition = currentShift.Users.FirstOrDefault(f => f.UserId == userId)?.PositionName ?? string.Empty;
} }
if (_currentUserService.Permissions != null) if (currentUserService.Permissions != null)
{ {
int totalStepCount = 0; int totalStepCount = 0;
int completeStepCount = 0; int completeStepCount = 0;
string currentStep = string.Empty; string currentStep = string.Empty;
if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageRoutines)) if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageRoutines))
{ {
totalStepCount++; totalStepCount++;
var hasRoutine = await _repositoryWrapper.SetRepository<Routine>() var hasRoutine = await repositoryWrapper.SetRepository<Routine>()
.TableNoTracking .TableNoTracking
.AnyAsync(r => r.ComplexId == complexId, cancellationToken); .AnyAsync(r => r.ComplexId == complexId, cancellationToken);
if (hasRoutine) if (hasRoutine)
@ -87,10 +78,10 @@ public class PageService : IPageService
currentStep = "تکمیل بخش روتین ها"; currentStep = "تکمیل بخش روتین ها";
} }
} }
if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageSections)) if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageSections))
{ {
totalStepCount++; totalStepCount++;
var hasSection = await _repositoryWrapper.SetRepository<Section>() var hasSection = await repositoryWrapper.SetRepository<Section>()
.TableNoTracking .TableNoTracking
.AnyAsync(r => r.ComplexId == complexId, cancellationToken); .AnyAsync(r => r.ComplexId == complexId, cancellationToken);
if (hasSection) if (hasSection)
@ -101,10 +92,10 @@ public class PageService : IPageService
currentStep = "تکمیل بخش سکشن ها"; currentStep = "تکمیل بخش سکشن ها";
} }
} }
if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManagePositions)) if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManagePositions))
{ {
totalStepCount++; totalStepCount++;
var hasPosition = await _repositoryWrapper.SetRepository<Position>() var hasPosition = await repositoryWrapper.SetRepository<Position>()
.TableNoTracking .TableNoTracking
.AnyAsync(r => r.ComplexId == complexId, cancellationToken); .AnyAsync(r => r.ComplexId == complexId, cancellationToken);
if (hasPosition) if (hasPosition)
@ -115,10 +106,10 @@ public class PageService : IPageService
currentStep = "تکمیل بخش پوزیشن ها"; currentStep = "تکمیل بخش پوزیشن ها";
} }
} }
if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageStaffs)) if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageStaffs))
{ {
totalStepCount++; totalStepCount++;
var hasStaff = await _repositoryWrapper.SetRepository<ComplexUser>() var hasStaff = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking .TableNoTracking
.AnyAsync(r => r.ComplexId == complexId, cancellationToken); .AnyAsync(r => r.ComplexId == complexId, cancellationToken);
if (hasStaff) if (hasStaff)
@ -129,10 +120,10 @@ public class PageService : IPageService
currentStep = "تکمیل بخش کاربر ها"; currentStep = "تکمیل بخش کاربر ها";
} }
} }
if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageShifts)) if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageShifts))
{ {
totalStepCount++; totalStepCount++;
var hasShift = await _repositoryWrapper.SetRepository<Shift>() var hasShift = await repositoryWrapper.SetRepository<Shift>()
.TableNoTracking .TableNoTracking
.AnyAsync(r => r.ComplexId == complexId, cancellationToken); .AnyAsync(r => r.ComplexId == complexId, cancellationToken);
if (hasShift) if (hasShift)
@ -143,10 +134,10 @@ public class PageService : IPageService
currentStep = "تکمیل بخش شیفت ها"; currentStep = "تکمیل بخش شیفت ها";
} }
} }
if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageTasks)) if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageTasks))
{ {
totalStepCount++; totalStepCount++;
var hasTask = await _repositoryWrapper.SetRepository<Task>() var hasTask = await repositoryWrapper.SetRepository<Task>()
.TableNoTracking .TableNoTracking
.AnyAsync(r => r.ComplexId == complexId, cancellationToken); .AnyAsync(r => r.ComplexId == complexId, cancellationToken);
if (hasTask) if (hasTask)
@ -157,10 +148,10 @@ public class PageService : IPageService
currentStep = "تکمیل بخش تسک ها"; currentStep = "تکمیل بخش تسک ها";
} }
} }
if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageShiftPlans)) if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageShiftPlans))
{ {
totalStepCount++; totalStepCount++;
var hasStaff = await _repositoryWrapper.SetRepository<ShiftPlan>() var hasStaff = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking .TableNoTracking
.AnyAsync(r => r.ComplexId == complexId, cancellationToken); .AnyAsync(r => r.ComplexId == complexId, cancellationToken);
if (hasStaff) if (hasStaff)
@ -182,15 +173,15 @@ public class PageService : IPageService
public async Task<List<AppShiftingPageDayDto>> GetShiftingPageAsync(Guid routineId,CancellationToken cancellationToken = default) public async Task<List<AppShiftingPageDayDto>> GetShiftingPageAsync(Guid routineId,CancellationToken cancellationToken = default)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var days = new List<AppShiftingPageDayDto>(); var days = new List<AppShiftingPageDayDto>();
DateTime day = DateTime.Today; DateTime day = DateTime.Today;
var shifts = await _mediator.Send(new GetRoutineShiftsQuery(routineId, 0), var shifts = await mediator.Send(new GetRoutineShiftsQuery(routineId, 0),
cancellationToken); cancellationToken);
for (int i = 0 ; i < 15; i++ , day = day.AddDays(1)) for (int i = 0 ; i < 15; i++ , day = day.AddDays(1))
@ -203,7 +194,7 @@ public class PageService : IPageService
.SelectMany(s=>s.Shifts).OrderBy(s=>s.StartAt).ToList().ForEach(s=>item.Shifts.Add(s.Clone())); .SelectMany(s=>s.Shifts).OrderBy(s=>s.StartAt).ToList().ForEach(s=>item.Shifts.Add(s.Clone()));
foreach (var shift in item.Shifts) foreach (var shift in item.Shifts)
{ {
var existedShiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>() var existedShiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.ShiftId == shift.Id && s.PlanFor.Date == day.Date, cancellationToken); .FirstOrDefaultAsync(s => s.ShiftId == shift.Id && s.PlanFor.Date == day.Date, cancellationToken);
shift.CurrentShiftPlanId = existedShiftPlan?.Id ?? default; shift.CurrentShiftPlanId = existedShiftPlan?.Id ?? default;

View File

@ -3,24 +3,19 @@ using Brizco.Domain.Entities.Tasks;
using MD.PersianDateTime.Standard; using MD.PersianDateTime.Standard;
namespace Brizco.Core.CoreServices.ReportServices; namespace Brizco.Core.CoreServices.ReportServices;
public class ShiftPlanReportCommandHandler : IRequestHandler<ShiftPlanReportCommand, byte[]> public class ShiftPlanReportCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<ShiftPlanReportCommand, byte[]>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public ShiftPlanReportCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<byte[]> Handle(ShiftPlanReportCommand request, CancellationToken cancellationToken) public async Task<byte[]> Handle(ShiftPlanReportCommand request, CancellationToken cancellationToken)
{ {
var shiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>() var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking .TableNoTracking
.Where(sp => sp.Id == request.ShiftPlanId) .Where(sp => sp.Id == request.ShiftPlanId)
.Select(ShiftPlanMapper.ProjectToSDto) .Select(ShiftPlanMapper.ProjectToSDto)
.FirstOrDefaultAsync(cancellationToken); .FirstOrDefaultAsync(cancellationToken);
if (shiftPlan == null) if (shiftPlan == null)
throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound); throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound);
var activities = await _repositoryWrapper.SetRepository<Activity>() var activities = await repositoryWrapper.SetRepository<Activity>()
.TableNoTracking .TableNoTracking
.Where(sp => sp.ShiftPlanId == shiftPlan.ShiftId && sp.SetFor.Date == shiftPlan.PlanFor.Date) .Where(sp => sp.ShiftPlanId == shiftPlan.ShiftId && sp.SetFor.Date == shiftPlan.PlanFor.Date)
.Select(ActivityMapper.ProjectToSDto) .Select(ActivityMapper.ProjectToSDto)

View File

@ -2,17 +2,11 @@
using Task = System.Threading.Tasks.Task; using Task = System.Threading.Tasks.Task;
namespace Brizco.Core.CoreServices.ReportServices; namespace Brizco.Core.CoreServices.ReportServices;
public class TaskReportCommandHandler : IRequestHandler<TaskReportCommand , byte[]> public class TaskReportCommandHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler<TaskReportCommand, byte[]>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public TaskReportCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<byte[]> Handle(TaskReportCommand request, CancellationToken cancellationToken) public async Task<byte[]> Handle(TaskReportCommand request, CancellationToken cancellationToken)
{ {
var tasks = await _repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>() var tasks = await repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>()
.TableNoTracking .TableNoTracking
.Select(TaskMapper.ProjectToLDto) .Select(TaskMapper.ProjectToLDto)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
@ -50,7 +44,7 @@ public class TaskReportCommandHandler : IRequestHandler<TaskReportCommand , byte
cell.SetCellValue(taskShiftSDto.TaskTitle); cell.SetCellValue(taskShiftSDto.TaskTitle);
var position = await _repositoryWrapper.SetRepository<TaskPosition>() var position = await repositoryWrapper.SetRepository<TaskPosition>()
.TableNoTracking .TableNoTracking
.Where(t => t.TaskId == taskShiftSDto.TaskId) .Where(t => t.TaskId == taskShiftSDto.TaskId)
.Select(TaskPositionMapper.ProjectToSDto) .Select(TaskPositionMapper.ProjectToSDto)
@ -123,7 +117,7 @@ public class TaskReportCommandHandler : IRequestHandler<TaskReportCommand , byte
cell.SetCellValue(taskShiftSDto.TaskTitle); cell.SetCellValue(taskShiftSDto.TaskTitle);
var position = await _repositoryWrapper.SetRepository<TaskPosition>() var position = await repositoryWrapper.SetRepository<TaskPosition>()
.TableNoTracking .TableNoTracking
.Where(t => t.TaskId == taskShiftSDto.TaskId) .Where(t => t.TaskId == taskShiftSDto.TaskId)
.Select(TaskPositionMapper.ProjectToSDto) .Select(TaskPositionMapper.ProjectToSDto)

View File

@ -2,16 +2,8 @@
namespace Brizco.Core.EntityServices; namespace Brizco.Core.EntityServices;
public class ComplexService : IComplexService public class ComplexService(ISender sender, RoleManager<ApplicationRole> roleManager) : IComplexService
{ {
private readonly ISender _sender;
private readonly RoleManager<ApplicationRole> _roleManager;
public ComplexService(ISender sender,RoleManager<ApplicationRole> roleManager)
{
_sender = sender;
_roleManager = roleManager;
}
public async Task<ComplexSDto> CreateComplexAsync(string complexName, public async Task<ComplexSDto> CreateComplexAsync(string complexName,
string complexAddress, string complexAddress,
string complexSuppPhone, string complexSuppPhone,
@ -19,7 +11,7 @@ public class ComplexService : IComplexService
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
var complex = await _sender.Send(new CreateComplexCommand(complexName, var complex = await sender.Send(new CreateComplexCommand(complexName,
complexAddress, complexAddress,
complexSuppPhone)); complexSuppPhone));
@ -31,12 +23,12 @@ public class ComplexService : IComplexService
Description = "مدیریت مجموعه", Description = "مدیریت مجموعه",
Name = $"{ApplicationRoles.Manager}_{complex.Id.ToString()}" Name = $"{ApplicationRoles.Manager}_{complex.Id.ToString()}"
}; };
var createRoleResult = await _roleManager.CreateAsync(managerRole); var createRoleResult = await roleManager.CreateAsync(managerRole);
if (!createRoleResult.Succeeded) if (!createRoleResult.Succeeded)
throw new AppException(string.Join('|', createRoleResult.Errors)); throw new AppException(string.Join('|', createRoleResult.Errors));
foreach (var claim in ApplicationClaims.ManagerClaims) foreach (var claim in ApplicationClaims.ManagerClaims)
await _roleManager.AddClaimAsync(managerRole, claim); await roleManager.AddClaimAsync(managerRole, claim);
@ -48,12 +40,12 @@ public class ComplexService : IComplexService
Description = "ناظر مجموعه", Description = "ناظر مجموعه",
Name = $"{ApplicationRoles.ViewerOwner}_{complex.Id.ToString()}" Name = $"{ApplicationRoles.ViewerOwner}_{complex.Id.ToString()}"
}; };
var createViewerResult = await _roleManager.CreateAsync(viewOwnerRole); var createViewerResult = await roleManager.CreateAsync(viewOwnerRole);
if (!createViewerResult.Succeeded) if (!createViewerResult.Succeeded)
throw new AppException(string.Join('|', createViewerResult.Errors)); throw new AppException(string.Join('|', createViewerResult.Errors));
foreach (var claim in ApplicationClaims.ViewerOwnerClaims) foreach (var claim in ApplicationClaims.ViewerOwnerClaims)
await _roleManager.AddClaimAsync(viewOwnerRole, claim); await roleManager.AddClaimAsync(viewOwnerRole, claim);
var superVisorRole = new ApplicationRole var superVisorRole = new ApplicationRole
{ {
@ -63,12 +55,12 @@ public class ComplexService : IComplexService
Description = "انجام فعالیت مدیریت کارکنان و وظیفه ها", Description = "انجام فعالیت مدیریت کارکنان و وظیفه ها",
Name = $"{ApplicationRoles.SuperVisor}_{complex.Id.ToString()}" Name = $"{ApplicationRoles.SuperVisor}_{complex.Id.ToString()}"
}; };
var superVisorRoleResult = await _roleManager.CreateAsync(superVisorRole); var superVisorRoleResult = await roleManager.CreateAsync(superVisorRole);
if (!superVisorRoleResult.Succeeded) if (!superVisorRoleResult.Succeeded)
throw new AppException(string.Join('|', superVisorRoleResult.Errors)); throw new AppException(string.Join('|', superVisorRoleResult.Errors));
foreach (var claim in ApplicationClaims.SuperVisorClaims) foreach (var claim in ApplicationClaims.SuperVisorClaims)
await _roleManager.AddClaimAsync(superVisorRole, claim); await roleManager.AddClaimAsync(superVisorRole, claim);
var staffRole = new ApplicationRole var staffRole = new ApplicationRole
@ -79,15 +71,15 @@ public class ComplexService : IComplexService
Description = "انجام فعالیت ها و وظیفه ها", Description = "انجام فعالیت ها و وظیفه ها",
Name = $"{ApplicationRoles.Staff}_{complex.Id.ToString()}" Name = $"{ApplicationRoles.Staff}_{complex.Id.ToString()}"
}; };
var staffRoleResult = await _roleManager.CreateAsync(staffRole); var staffRoleResult = await roleManager.CreateAsync(staffRole);
if (!staffRoleResult.Succeeded) if (!staffRoleResult.Succeeded)
throw new AppException(string.Join('|', staffRoleResult.Errors)); throw new AppException(string.Join('|', staffRoleResult.Errors));
foreach (var claim in ApplicationClaims.StaffClaims) foreach (var claim in ApplicationClaims.StaffClaims)
await _roleManager.AddClaimAsync(staffRole, claim); await roleManager.AddClaimAsync(staffRole, claim);
var complexUser = await _sender.Send(new CreateComplexUserCommand(complex.Id, managerUserId, new List<Guid>{ managerRole.Id }), cancellationToken); var complexUser = await sender.Send(new CreateComplexUserCommand(complex.Id, managerUserId, new List<Guid>{ managerRole.Id }), cancellationToken);
return complex; return complex;
} }

View File

@ -3,36 +3,20 @@ using Brizco.Domain.Entities.Users;
namespace Brizco.Core.EntityServices; namespace Brizco.Core.EntityServices;
public class UserService : IUserService public class UserService(
ICurrentUserService currentUserService,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
ISender sender,
IRepositoryWrapper repositoryWrapper,
IJwtService jwtService)
: IUserService
{ {
private readonly ICurrentUserService _currentUserService;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly ISender _sender;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IJwtService _jwtService;
public UserService(ICurrentUserService currentUserService,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
ISender sender,
IRepositoryWrapper repositoryWrapper,
IJwtService jwtService)
{
_currentUserService = currentUserService;
_userManager = userManager;
_roleManager = roleManager;
_sender = sender;
_repositoryWrapper = repositoryWrapper;
_jwtService = jwtService;
}
public async Task<ProfileResponseDto> GetUserProfileAsync(CancellationToken cancellationToken) public async Task<ProfileResponseDto> GetUserProfileAsync(CancellationToken cancellationToken)
{ {
if (!Guid.TryParse(_currentUserService.UserId, out var userId)) if (!Guid.TryParse(currentUserService.UserId, out var userId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized); throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
var user = await _userManager.FindByIdAsync(userId.ToString()); var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null) if (user == null)
throw new AppException("User NotFound", ApiResultStatusCode.NotFound); throw new AppException("User NotFound", ApiResultStatusCode.NotFound);
if (user.SignUpStatus < SignUpStatus.ComplexCreated) if (user.SignUpStatus < SignUpStatus.ComplexCreated)
@ -51,10 +35,10 @@ public class UserService : IUserService
userSDto.SelectedComplexName = complexUserRole!.ComplexName; userSDto.SelectedComplexName = complexUserRole!.ComplexName;
userSDto.SelectedRoleName = complexUserRole!.RoleName; userSDto.SelectedRoleName = complexUserRole!.RoleName;
response.User.SelectedRoleId = complexUserRole!.Id; response.User.SelectedRoleId = complexUserRole!.Id;
var role = await _roleManager.FindByIdAsync(complexUserRole.RoleId.ToString()); var role = await roleManager.FindByIdAsync(complexUserRole.RoleId.ToString());
if (role != null) if (role != null)
{ {
var roleClaims = await _roleManager.GetClaimsAsync(role); var roleClaims = await roleManager.GetClaimsAsync(role);
response.Permissions = roleClaims.Where(c => c.Type == "Permission").Select(c => c.Value).ToList(); response.Permissions = roleClaims.Where(c => c.Type == "Permission").Select(c => c.Value).ToList();
} }
} }
@ -64,14 +48,14 @@ public class UserService : IUserService
if (complexUserRole != null) if (complexUserRole != null)
{ {
user.SelectedComplexUserRoleId = complexUserRole.Id; user.SelectedComplexUserRoleId = complexUserRole.Id;
await _userManager.UpdateAsync(user); await userManager.UpdateAsync(user);
userSDto.SelectedComplexName = complexUserRole!.ComplexName; userSDto.SelectedComplexName = complexUserRole!.ComplexName;
userSDto.SelectedRoleName = complexUserRole!.RoleName; userSDto.SelectedRoleName = complexUserRole!.RoleName;
response.User.SelectedRoleId = complexUserRole!.Id; response.User.SelectedRoleId = complexUserRole!.Id;
var role = await _roleManager.FindByIdAsync(complexUserRole.RoleId.ToString()); var role = await roleManager.FindByIdAsync(complexUserRole.RoleId.ToString());
if (role != null) if (role != null)
{ {
var roleClaims = await _roleManager.GetClaimsAsync(role); var roleClaims = await roleManager.GetClaimsAsync(role);
response.Permissions = roleClaims.Where(c => c.Type == "Permission").Select(c => c.Value).ToList(); response.Permissions = roleClaims.Where(c => c.Type == "Permission").Select(c => c.Value).ToList();
} }
} }
@ -85,16 +69,16 @@ public class UserService : IUserService
public async Task<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> ChangeUserRoleAsync(Guid roleId, CancellationToken cancellationToken) public async Task<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> ChangeUserRoleAsync(Guid roleId, CancellationToken cancellationToken)
{ {
if (!Guid.TryParse(_currentUserService.UserId, out var userId)) if (!Guid.TryParse(currentUserService.UserId, out var userId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized); throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
if (!Guid.TryParse(_currentUserService.ComplexId, out var complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out var complexId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized); throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
AccessToken<ApplicationUserSDto, ComplexUserRoleSDto> jwt; AccessToken<ApplicationUserSDto, ComplexUserRoleSDto> jwt;
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>() var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking .TableNoTracking
.Where(mcu => mcu.UserId == userId && mcu.ComplexId == complexId) .Where(mcu => mcu.UserId == userId && mcu.ComplexId == complexId)
.Select(ComplexUserMapper.ProjectToSDto) .Select(ComplexUserMapper.ProjectToSDto)
@ -102,7 +86,7 @@ public class UserService : IUserService
if (complexUser == null) if (complexUser == null)
throw new AppException("User role is wrong", ApiResultStatusCode.BadRequest); throw new AppException("User role is wrong", ApiResultStatusCode.BadRequest);
var complexUserRole = await _repositoryWrapper.SetRepository<ComplexUserRole>() var complexUserRole = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking .TableNoTracking
.Where(c => c.Id == roleId) .Where(c => c.Id == roleId)
.Select(ComplexUserRoleMapper.ProjectToSDto) .Select(ComplexUserRoleMapper.ProjectToSDto)
@ -111,13 +95,13 @@ public class UserService : IUserService
if (complexUserRole == null) if (complexUserRole == null)
throw new AppException("Role not found", ApiResultStatusCode.NotFound); throw new AppException("Role not found", ApiResultStatusCode.NotFound);
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);
user.SelectedComplexUserRoleId = complexUserRole.Id; user.SelectedComplexUserRoleId = complexUserRole.Id;
await _userManager.UpdateAsync(user); await userManager.UpdateAsync(user);
jwt = (await _jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>(); jwt = (await jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
jwt.User.SelectedComplexName = complexUser.ComplexName; jwt.User.SelectedComplexName = complexUser.ComplexName;
jwt.User.SelectedRoleName = complexUserRole.RoleName; jwt.User.SelectedRoleName = complexUserRole.RoleName;
jwt.User.SelectedRoleId = complexUserRole.Id; jwt.User.SelectedRoleId = complexUserRole.Id;
@ -127,13 +111,13 @@ public class UserService : IUserService
public async Task<List<ComplexUserRoleSDto>> GetUserRolesAsync(CancellationToken cancellationToken) public async Task<List<ComplexUserRoleSDto>> GetUserRolesAsync(CancellationToken cancellationToken)
{ {
if (!Guid.TryParse(_currentUserService.UserId, out var userId)) if (!Guid.TryParse(currentUserService.UserId, out var userId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized); throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
var user = await _userManager.FindByIdAsync(userId.ToString()); var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null) if (user == null)
throw new AppException("User NotFound", ApiResultStatusCode.NotFound); throw new AppException("User NotFound", ApiResultStatusCode.NotFound);
var response = new List<ComplexUserRoleSDto>(); var response = new List<ComplexUserRoleSDto>();
var complexUsers = await _repositoryWrapper.SetRepository<ComplexUser>() var complexUsers = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking .TableNoTracking
.Where(mcu => mcu.UserId == user.Id) .Where(mcu => mcu.UserId == user.Id)
.Select(ComplexUserMapper.ProjectToSDto) .Select(ComplexUserMapper.ProjectToSDto)
@ -143,7 +127,7 @@ public class UserService : IUserService
foreach (var complexUser in complexUsers) foreach (var complexUser in complexUsers)
{ {
var complexUserRoles = await _repositoryWrapper.SetRepository<ComplexUserRole>() var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking .TableNoTracking
.Where(c => c.ComplexUserId == complexUser.Id) .Where(c => c.ComplexUserId == complexUser.Id)
.Select(ComplexUserRoleMapper.ProjectToSDto) .Select(ComplexUserRoleMapper.ProjectToSDto)
@ -160,11 +144,11 @@ public class UserService : IUserService
public async Task<List<ComplexUserRoleSDto>> GetUserRolesAsync(Guid userId, CancellationToken cancellationToken) public async Task<List<ComplexUserRoleSDto>> GetUserRolesAsync(Guid userId, CancellationToken cancellationToken)
{ {
var user = await _userManager.FindByIdAsync(userId.ToString()); var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null) if (user == null)
throw new AppException("User NotFound", ApiResultStatusCode.NotFound); throw new AppException("User NotFound", ApiResultStatusCode.NotFound);
var response = new List<ComplexUserRoleSDto>(); var response = new List<ComplexUserRoleSDto>();
var complexUsers = await _repositoryWrapper.SetRepository<ComplexUser>() var complexUsers = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking .TableNoTracking
.Where(mcu => mcu.UserId == user.Id) .Where(mcu => mcu.UserId == user.Id)
.Select(ComplexUserMapper.ProjectToSDto) .Select(ComplexUserMapper.ProjectToSDto)
@ -174,7 +158,7 @@ public class UserService : IUserService
foreach (var complexUser in complexUsers) foreach (var complexUser in complexUsers)
{ {
var complexUserRoles = await _repositoryWrapper.SetRepository<ComplexUserRole>() var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking .TableNoTracking
.Where(c => c.ComplexUserId == complexUser.Id) .Where(c => c.ComplexUserId == complexUser.Id)
.Select(ComplexUserRoleMapper.ProjectToSDto) .Select(ComplexUserRoleMapper.ProjectToSDto)
@ -191,40 +175,40 @@ public class UserService : IUserService
public async Task<List<ComplexUserSDto>> GetUsersAsync(int page = 0, CancellationToken cancellationToken = default) public async Task<List<ComplexUserSDto>> GetUsersAsync(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");
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)
{ {
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 dto = user.AdaptToSDto(); var dto = user.AdaptToSDto();
if (_currentUserService.ComplexId == null || !Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (currentUserService.ComplexId == null || !Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
{ {
var roles = await _userManager.GetRolesAsync(user); var roles = await userManager.GetRolesAsync(user);
foreach (var roleName in roles) foreach (var roleName in roles)
{ {
var role = await _roleManager.FindByNameAsync(roleName); var role = await roleManager.FindByNameAsync(roleName);
if (role != null) if (role != null)
dto.RoleIds.Add(role.Id); dto.RoleIds.Add(role.Id);
} }
} }
else else
{ {
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking var complexUser = await repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == userId && c.ComplexId == complexId); .FirstOrDefaultAsync(c => c.UserId == userId && c.ComplexId == complexId);
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>() var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking .TableNoTracking
.Where(cur => cur.ComplexUserId == complexUser.Id) .Where(cur => cur.ComplexUserId == complexUser.Id)
.ToListAsync(); .ToListAsync();
@ -244,7 +228,7 @@ public class UserService : IUserService
PhoneNumber = phoneNumber, PhoneNumber = phoneNumber,
SignUpStatus = SignUpStatus.StartSignOn SignUpStatus = SignUpStatus.StartSignOn
}; };
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));
return user; return user;
@ -252,12 +236,12 @@ public class UserService : IUserService
public async Task<ApplicationUser> CreateUserAsync(UserActionRequestDto request, CancellationToken cancellationToken) public async Task<ApplicationUser> CreateUserAsync(UserActionRequestDto request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId.IsNullOrEmpty()) if (currentUserService.ComplexId.IsNullOrEmpty())
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 user = await _userManager.FindByNameAsync(request.PhoneNumber); var user = await userManager.FindByNameAsync(request.PhoneNumber);
if (user == null) if (user == null)
{ {
user = new ApplicationUser user = new ApplicationUser
@ -275,32 +259,32 @@ public class UserService : IUserService
if (!request.Password.IsNullOrEmpty()) if (!request.Password.IsNullOrEmpty())
{ {
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.Select(e => e.Description))); 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.Select(e => e.Description))); 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);
return user; return user;
} }
public async Task<bool> EditUserAsync(UserActionRequestDto request, CancellationToken cancellationToken) public async Task<bool> EditUserAsync(UserActionRequestDto request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId.IsNullOrEmpty()) if (currentUserService.ComplexId.IsNullOrEmpty())
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 (request.UserId == Guid.Empty) 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(request.UserId.ToString()); 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;
@ -313,29 +297,29 @@ public class UserService : IUserService
user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp); 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.Select(e => e.Description))); 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))
await _userManager.RemovePasswordAsync(user); await userManager.RemovePasswordAsync(user);
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.Select(e => e.Description))); 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);
return true; return true;
} }
public async Task<bool> EditUserProfileAsync(UserActionRequestDto request, CancellationToken cancellationToken) public async Task<bool> EditUserProfileAsync(UserActionRequestDto request, CancellationToken cancellationToken)
{ {
if (_currentUserService.UserId == null) if (currentUserService.UserId == null)
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(currentUserService.UserId);
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;
@ -348,15 +332,15 @@ public class UserService : IUserService
user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp); 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.Select(e => e.Description))); 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))
await _userManager.RemovePasswordAsync(user); await userManager.RemovePasswordAsync(user);
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.Select(e => e.Description))); throw new AppException(string.Join('|', addPassResult.Errors.Select(e => e.Description)));
} }
@ -366,17 +350,17 @@ public class UserService : IUserService
public async Task<bool> RemoveUserAsync(Guid userId, CancellationToken cancellationToken) public async Task<bool> RemoveUserAsync(Guid userId, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId.IsNullOrEmpty()) if (currentUserService.ComplexId.IsNullOrEmpty())
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 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); var roles = await userManager.GetRolesAsync(user);
await _userManager.RemoveFromRolesAsync(user, roles); await userManager.RemoveFromRolesAsync(user, roles);
await _sender.Send(new DeleteComplexUserCommand(userId, complexId), cancellationToken); 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.Select(e => e.Description))); throw new AppException(string.Join('|', removeResult.Errors.Select(e => e.Description)));
return true; return true;
@ -384,14 +368,14 @@ public class UserService : IUserService
public async Task<bool> RemoveUserFromComplexAsync(Guid userId, CancellationToken cancellationToken) public async Task<bool> RemoveUserFromComplexAsync(Guid userId, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId.IsNullOrEmpty()) if (currentUserService.ComplexId.IsNullOrEmpty())
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 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);
await _sender.Send(new DeleteComplexUserCommand(userId, complexId), cancellationToken); await sender.Send(new DeleteComplexUserCommand(userId, complexId), cancellationToken);
return true; return true;
} }
@ -399,12 +383,12 @@ public class UserService : IUserService
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");
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 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)
@ -414,13 +398,13 @@ public class UserService : IUserService
public async Task<RoleActionRequestDto> GetRoleAsync(Guid roleId) public async Task<RoleActionRequestDto> GetRoleAsync(Guid roleId)
{ {
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.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)
.ToList(); .ToList();
@ -430,9 +414,9 @@ public class UserService : IUserService
public async Task<ApplicationRole> CreateRoleAsync(RoleActionRequestDto request) public async Task<ApplicationRole> CreateRoleAsync(RoleActionRequestDto request)
{ {
if (_currentUserService.ComplexId.IsNullOrEmpty()) if (currentUserService.ComplexId.IsNullOrEmpty())
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 wrong"); throw new AppException("Wrong authorize token , ComplexId wrong");
if (request.EnglishName.IsNullOrEmpty()) if (request.EnglishName.IsNullOrEmpty())
throw new AppException("لطفا نام انگلیسی را وارد کنید"); throw new AppException("لطفا نام انگلیسی را وارد کنید");
@ -444,24 +428,24 @@ public class UserService : IUserService
Description = request.Description, Description = request.Description,
Name = $"{request.EnglishName}_{complexId.ToString()}" Name = $"{request.EnglishName}_{complexId.ToString()}"
}; };
var createRoleResult = await _roleManager.CreateAsync(applicationRole); var createRoleResult = await roleManager.CreateAsync(applicationRole);
if (!createRoleResult.Succeeded) if (!createRoleResult.Succeeded)
throw new AppException(string.Join('|', createRoleResult.Errors)); throw new AppException(string.Join('|', createRoleResult.Errors));
foreach (var claim in request.Permissions) foreach (var claim in request.Permissions)
await _roleManager.AddClaimAsync(applicationRole, new Claim(CustomClaimType.Permission, claim)); await roleManager.AddClaimAsync(applicationRole, new Claim(CustomClaimType.Permission, claim));
return applicationRole; return applicationRole;
} }
public async Task<bool> EditRoleAsync(RoleActionRequestDto request) public async Task<bool> EditRoleAsync(RoleActionRequestDto request)
{ {
if (_currentUserService.ComplexId.IsNullOrEmpty()) if (currentUserService.ComplexId.IsNullOrEmpty())
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 wrong"); throw new AppException("Wrong authorize token , ComplexId wrong");
if (request.EnglishName.IsNullOrEmpty()) if (request.EnglishName.IsNullOrEmpty())
throw new AppException("لطفا نام انگلیسی را وارد کنید"); throw new AppException("لطفا نام انگلیسی را وارد کنید");
var applicationRole = await _roleManager.FindByIdAsync(request.RoleId.ToString()); var applicationRole = await roleManager.FindByIdAsync(request.RoleId.ToString());
if (applicationRole == null) if (applicationRole == null)
throw new AppException("نقش پیدا نشد"); throw new AppException("نقش پیدا نشد");
@ -471,10 +455,10 @@ public class UserService : IUserService
applicationRole.Description = request.Description; applicationRole.Description = request.Description;
applicationRole.Name = $"{request.EnglishName}_{complexId.ToString()}"; applicationRole.Name = $"{request.EnglishName}_{complexId.ToString()}";
var createRoleResult = await _roleManager.UpdateAsync(applicationRole); var createRoleResult = await roleManager.UpdateAsync(applicationRole);
if (!createRoleResult.Succeeded) if (!createRoleResult.Succeeded)
throw new AppException(string.Join('|', createRoleResult.Errors)); throw new AppException(string.Join('|', createRoleResult.Errors));
var roleClaims = (await _roleManager.GetClaimsAsync(applicationRole)).Where(c => c.Type == CustomClaimType.Permission).ToList(); var roleClaims = (await roleManager.GetClaimsAsync(applicationRole)).Where(c => c.Type == CustomClaimType.Permission).ToList();
foreach (var roleClaim in roleClaims.ToList()) foreach (var roleClaim in roleClaims.ToList())
{ {
if (request.Permissions.Contains(roleClaim.Value)) if (request.Permissions.Contains(roleClaim.Value))
@ -485,39 +469,39 @@ public class UserService : IUserService
} }
foreach (var claim in request.Permissions) foreach (var claim in request.Permissions)
await _roleManager.AddClaimAsync(applicationRole, new Claim(CustomClaimType.Permission, claim)); await roleManager.AddClaimAsync(applicationRole, new Claim(CustomClaimType.Permission, claim));
foreach (var claim in roleClaims) foreach (var claim in roleClaims)
await _roleManager.RemoveClaimAsync(applicationRole, claim); await roleManager.RemoveClaimAsync(applicationRole, claim);
return true; return true;
} }
public async Task<bool> RemoveRoleAsync(Guid roleId) public async Task<bool> RemoveRoleAsync(Guid roleId)
{ {
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); var claims = await roleManager.GetClaimsAsync(applicationRole);
foreach (var claim in claims) foreach (var claim in claims)
await _roleManager.RemoveClaimAsync(applicationRole, claim); await roleManager.RemoveClaimAsync(applicationRole, claim);
var users = await _userManager.GetUsersInRoleAsync(applicationRole.Name); var users = await userManager.GetUsersInRoleAsync(applicationRole.Name);
foreach (var user in users) foreach (var user in users)
await _userManager.RemoveFromRoleAsync(user, applicationRole.Name); await userManager.RemoveFromRoleAsync(user, applicationRole.Name);
var complexRoles = await _repositoryWrapper.SetRepository<ComplexUserRole>() var complexRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking .TableNoTracking
.Where(r => r.RoleId == applicationRole.Id) .Where(r => r.RoleId == applicationRole.Id)
.ToListAsync(); .ToListAsync();
foreach (var complexRole in complexRoles) foreach (var complexRole in complexRoles)
{ {
_repositoryWrapper.SetRepository<ComplexUserRole>() repositoryWrapper.SetRepository<ComplexUserRole>()
.HardDelete(complexRole); .HardDelete(complexRole);
await _repositoryWrapper.SaveChangesAsync(default); 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.Select(e => e.Description))); throw new AppException(string.Join('|', removeResult.Errors.Select(e => e.Description)));
return true; return true;

View File

@ -1,26 +1,19 @@
namespace Brizco.Core.MartenServices; namespace Brizco.Core.MartenServices;
public class BrewService : IBrewService public class BrewService(IMartenRepositoryWrapper martenRepositoryWrapper, ICurrentUserService currentUserService)
: IBrewService
{ {
private readonly IMartenRepositoryWrapper _martenRepositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public BrewService(IMartenRepositoryWrapper martenRepositoryWrapper, ICurrentUserService currentUserService)
{
_martenRepositoryWrapper = martenRepositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<object> GetLastBrewAsync(string recipeName, CancellationToken cancellationToken = default) public async Task<object> GetLastBrewAsync(string recipeName, CancellationToken cancellationToken = default)
{ {
var type = Assembly.GetAssembly(typeof(DomainConfig))?.GetType($"Brizco.Domain.MartenEntities.Brews.{recipeName}"); var type = Assembly.GetAssembly(typeof(DomainConfig))?.GetType($"Brizco.Domain.MartenEntities.Brews.{recipeName}");
if (type == null) if (type == null)
throw new AppException("Recipe not found", ApiResultStatusCode.NotFound); throw new AppException("Recipe not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is null"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is null");
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong");
var baseRecipe = await _martenRepositoryWrapper.SetRepository<BaseBrew>() var baseRecipe = await martenRepositoryWrapper.SetRepository<BaseBrew>()
.GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken); .GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken);
object? recipe; object? recipe;
if (baseRecipe == null) if (baseRecipe == null)
@ -39,12 +32,12 @@ public class BrewService : IBrewService
var type = Assembly.GetAssembly(typeof(DomainConfig))?.GetType($"Brizco.Domain.MartenEntities.Brews.{recipeName}"); var type = Assembly.GetAssembly(typeof(DomainConfig))?.GetType($"Brizco.Domain.MartenEntities.Brews.{recipeName}");
if (type == null) if (type == null)
throw new AppException("Recipe not found", ApiResultStatusCode.NotFound); throw new AppException("Recipe not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is null"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is null");
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong");
var baseRecipe = await _martenRepositoryWrapper.SetRepository<BaseBrew>() var baseRecipe = await martenRepositoryWrapper.SetRepository<BaseBrew>()
.GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken); .GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken);
object? recipe; object? recipe;
if (baseRecipe == null) if (baseRecipe == null)
@ -82,15 +75,15 @@ public class BrewService : IBrewService
if (type == null) if (type == null)
throw new AppException("Recipe not found", ApiResultStatusCode.NotFound); throw new AppException("Recipe not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is null"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is null");
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Complex id is wrong");
if (_currentUserService.FullName == null) if (currentUserService.FullName == null)
throw new BaseApiException(ApiResultStatusCode.BadRequest, "Full name is null"); throw new BaseApiException(ApiResultStatusCode.BadRequest, "Full name is null");
var baseRecipe = await _martenRepositoryWrapper.SetRepository<BaseBrew>() var baseRecipe = await martenRepositoryWrapper.SetRepository<BaseBrew>()
.GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken); .GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken);
if (baseRecipe == null) if (baseRecipe == null)
@ -105,7 +98,7 @@ public class BrewService : IBrewService
if (current is IBaseBrew brew) if (current is IBaseBrew brew)
{ {
brew.LogAt = DateTime.Now; brew.LogAt = DateTime.Now;
brew.LogBy = _currentUserService.FullName; brew.LogBy = currentUserService.FullName;
baseRecipe.CurrentBrewJson = JsonConvert.SerializeObject(current); baseRecipe.CurrentBrewJson = JsonConvert.SerializeObject(current);
} }
} }
@ -115,13 +108,13 @@ public class BrewService : IBrewService
if (current is IBaseBrew brew) if (current is IBaseBrew brew)
{ {
brew.LogAt = DateTime.Now; brew.LogAt = DateTime.Now;
brew.LogBy = _currentUserService.FullName; brew.LogBy = currentUserService.FullName;
baseRecipe.PastBrewsJson.Insert(0,baseRecipe.CurrentBrewJson); baseRecipe.PastBrewsJson.Insert(0,baseRecipe.CurrentBrewJson);
baseRecipe.CurrentBrewJson = JsonConvert.SerializeObject(current); baseRecipe.CurrentBrewJson = JsonConvert.SerializeObject(current);
} }
} }
await _martenRepositoryWrapper.SetRepository<BaseBrew>() await martenRepositoryWrapper.SetRepository<BaseBrew>()
.AddOrUpdateEntityAsync(baseRecipe, cancellationToken); .AddOrUpdateEntityAsync(baseRecipe, cancellationToken);
} }
} }

View File

@ -4,20 +4,13 @@ using Newtonsoft.Json;
namespace Brizco.Core.Models.Api; namespace Brizco.Core.Models.Api;
public class ApiResult public class ApiResult(bool isSuccess, ApiResultStatusCode statusCode, string message = null)
{ {
public ApiResult(bool isSuccess, ApiResultStatusCode statusCode, string message = null) public bool IsSuccess { get; set; } = isSuccess;
{ public ApiResultStatusCode StatusCode { get; set; } = statusCode;
IsSuccess = isSuccess;
StatusCode = statusCode;
Message = message ?? statusCode.ToDisplay();
}
public bool IsSuccess { get; set; }
public ApiResultStatusCode StatusCode { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; } public string Message { get; set; } = message ?? statusCode.ToDisplay();
#region Implicit Operators #region Implicit Operators
@ -66,17 +59,12 @@ public class ApiResult
#endregion #endregion
} }
public class ApiResult<TData> : ApiResult public class ApiResult<TData>(bool isSuccess, ApiResultStatusCode statusCode, TData data, string message = null)
: ApiResult(isSuccess, statusCode, message)
where TData : class where TData : class
{ {
public ApiResult(bool isSuccess, ApiResultStatusCode statusCode, TData data, string message = null)
: base(isSuccess, statusCode, message)
{
Data = data;
}
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TData Data { get; set; } public TData Data { get; set; } = data;
#region Implicit Operators #region Implicit Operators

View File

@ -1,11 +1,11 @@
using Brizco.Core.QuartzServices.Commands; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using Quartz; using Quartz;
namespace Brizco.Core.QuartzServices.Handlers; namespace Brizco.Core.QuartzServices.Handlers;
public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper repositoryWrapper,IScheduler scheduler,IMediator mediator,ILogger<SetShiftPlanNotificationScheduleCommand> logger) public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper repositoryWrapper, IScheduler scheduler, IMediator mediator,
: IRequestHandler<SetShiftPlanNotificationScheduleCommand,bool> ILogger<SetShiftPlanNotificationScheduleCommand> logger)
: IRequestHandler<SetShiftPlanNotificationScheduleCommand, bool>
{ {
public async Task<bool> Handle(SetShiftPlanNotificationScheduleCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(SetShiftPlanNotificationScheduleCommand request, CancellationToken cancellationToken)
{ {
@ -19,7 +19,7 @@ public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper r
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.Id == shiftPlan.ShiftId, cancellationToken); .FirstOrDefaultAsync(s => s.Id == shiftPlan.ShiftId, cancellationToken);
if(shift == null) if (shift == null)
throw new BaseApiException(ApiResultStatusCode.NotFound, "Shift not found in set schedule"); throw new BaseApiException(ApiResultStatusCode.NotFound, "Shift not found in set schedule");
var shiftPlanUsers = await repositoryWrapper.SetRepository<ShiftPlanUser>() var shiftPlanUsers = await repositoryWrapper.SetRepository<ShiftPlanUser>()
@ -36,8 +36,6 @@ public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper r
var shiftPlanStartAt = (new DateTime(shiftPlan.PlanFor.Year, shiftPlan.PlanFor.Month, shiftPlan.PlanFor.Day, shift.StartAt.Hours, shift.StartAt.Minutes, shift.StartAt.Seconds)).ToUniversalTime(); var shiftPlanStartAt = (new DateTime(shiftPlan.PlanFor.Year, shiftPlan.PlanFor.Month, shiftPlan.PlanFor.Day, shift.StartAt.Hours, shift.StartAt.Minutes, shift.StartAt.Seconds)).ToUniversalTime();
var shiftPlanEndAt = (new DateTime(shiftPlan.PlanFor.Year, shiftPlan.PlanFor.Month, shiftPlan.PlanFor.Day, shift.EndAt.Hours, shift.EndAt.Minutes, shift.EndAt.Seconds)).ToUniversalTime(); var shiftPlanEndAt = (new DateTime(shiftPlan.PlanFor.Year, shiftPlan.PlanFor.Month, shiftPlan.PlanFor.Day, shift.EndAt.Hours, shift.EndAt.Minutes, shift.EndAt.Seconds)).ToUniversalTime();
var currentDate = DateTime.UtcNow;
var startTimeOffset = new DateTimeOffset(shiftPlanStartAt.Year, shiftPlanStartAt.Month, shiftPlanStartAt.Day, shiftPlanStartAt.Hour, var startTimeOffset = new DateTimeOffset(shiftPlanStartAt.Year, shiftPlanStartAt.Month, shiftPlanStartAt.Day, shiftPlanStartAt.Hour,
shiftPlanStartAt.Minute, shiftPlanStartAt.Second, TimeSpan.Zero); shiftPlanStartAt.Minute, shiftPlanStartAt.Second, TimeSpan.Zero);
var endTimeOffset = new DateTimeOffset(shiftPlanEndAt.Year, shiftPlanEndAt.Month, shiftPlanEndAt.Day, shiftPlanEndAt.Hour, var endTimeOffset = new DateTimeOffset(shiftPlanEndAt.Year, shiftPlanEndAt.Month, shiftPlanEndAt.Day, shiftPlanEndAt.Hour,
@ -77,7 +75,11 @@ public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper r
var seTimeOffsetA = await scheduler.ScheduleJob(beforeEndShift30Min, beforeEndShift30MinTrigger, cancellationToken); var seTimeOffsetA = await scheduler.ScheduleJob(beforeEndShift30Min, beforeEndShift30MinTrigger, cancellationToken);
var seTimeOffsetB = await scheduler.ScheduleJob(endOfShift, endOfShiftTrigger, cancellationToken); var seTimeOffsetB = await scheduler.ScheduleJob(endOfShift, endOfShiftTrigger, cancellationToken);
var seTimeOffsetC = await scheduler.ScheduleJob(afterStartShift2Hour, afterStartShift2HourTrigger, cancellationToken); var seTimeOffsetC = await scheduler.ScheduleJob(afterStartShift2Hour, afterStartShift2HourTrigger, cancellationToken);
await scheduler.Start(cancellationToken); logger.LogInformation($"30 min before end set for : {seTimeOffsetA}");
logger.LogInformation($"before end set for : {seTimeOffsetB}");
logger.LogInformation($"2 hour after start shift set for : {seTimeOffsetC}");
if (scheduler.IsStarted)
await scheduler.Start(cancellationToken);
return true; return true;

View File

@ -3,22 +3,13 @@ using Quartz;
namespace Brizco.Core.QuartzServices; namespace Brizco.Core.QuartzServices;
public class JobScheduler public class JobScheduler(IScheduler scheduler, ILogger<JobScheduler> logger)
{ {
private readonly IScheduler _scheduler;
private readonly ILogger<JobScheduler> _logger;
public JobScheduler(IScheduler scheduler, ILogger<JobScheduler> logger)
{
_scheduler = scheduler;
_logger = logger;
}
public void Start() public void Start()
{ {
_scheduler.Start(); scheduler.Start();
_logger.LogInformation($"======== Scheduler Start ==========="); logger.LogInformation($"======== Scheduler Start ===========");
} }
} }

View File

@ -5,32 +5,25 @@ using Task = System.Threading.Tasks.Task;
namespace Brizco.Core.QuartzServices; namespace Brizco.Core.QuartzServices;
public class ShiftPlanNotificationScheduledJob : IJob public class ShiftPlanNotificationScheduledJob(
ILogger<ShiftPlanNotificationScheduledJob> logger,
IRepositoryWrapper repositoryWrapper,
IMediator mediator)
: IJob
{ {
private readonly ILogger<ShiftPlanNotificationScheduledJob> _logger;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
public ShiftPlanNotificationScheduledJob(ILogger<ShiftPlanNotificationScheduledJob> logger,IRepositoryWrapper repositoryWrapper,IMediator mediator)
{
_logger = logger;
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
}
public async Task Execute(IJobExecutionContext context) public async Task Execute(IJobExecutionContext context)
{ {
try try
{ {
var notifyType = (ShiftPlanNotifyType)int.Parse(context.JobDetail.Key.Name); var notifyType = (ShiftPlanNotifyType)int.Parse(context.JobDetail.Key.Name);
var shiftPlanId = Guid.Parse(context.JobDetail.Key.Group); var shiftPlanId = Guid.Parse(context.JobDetail.Key.Group);
var shiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>().TableNoTracking var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>().TableNoTracking
.Where(f => f.Id == shiftPlanId) .Where(f => f.Id == shiftPlanId)
.Select(ShiftPlanMapper.ProjectToSDto) .Select(ShiftPlanMapper.ProjectToSDto)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
if (shiftPlan == null) if (shiftPlan == null)
throw new Exception("Shift plan not found"); throw new Exception("Shift plan not found");
var shiftPlanUsers = await _repositoryWrapper.SetRepository<ShiftPlanUser>() var shiftPlanUsers = await repositoryWrapper.SetRepository<ShiftPlanUser>()
.TableNoTracking .TableNoTracking
.Where(f => f.ShiftPlanId == shiftPlanId) .Where(f => f.ShiftPlanId == shiftPlanId)
.Select(ShiftPlanUserMapper.ProjectToSDto) .Select(ShiftPlanUserMapper.ProjectToSDto)
@ -42,7 +35,7 @@ public class ShiftPlanNotificationScheduledJob : IJob
return; return;
break; break;
case ShiftPlanNotifyType.BeforeEndShift30Min: case ShiftPlanNotifyType.BeforeEndShift30Min:
var activities = await _repositoryWrapper.SetRepository<Activity>().TableNoTracking var activities = await repositoryWrapper.SetRepository<Activity>().TableNoTracking
.Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync(); .Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync();
foreach (var shiftPlanUser in shiftPlanUsers) foreach (var shiftPlanUser in shiftPlanUsers)
{ {
@ -50,11 +43,11 @@ public class ShiftPlanNotificationScheduledJob : IJob
if(unDoneCount == 0) if(unDoneCount == 0)
continue; continue;
string message = $"نیم ساعت مونده تا شیفت تموم شه و {unDoneCount} عدد از تست هات مونده، حالا چه خاکی به سر کنیم!😱"; string message = $"نیم ساعت مونده تا شیفت تموم شه و {unDoneCount} عدد از تست هات مونده، حالا چه خاکی به سر کنیم!😱";
await _mediator.Send(new CreateNotificationCommand(message, shiftPlanUser.UserId, shiftPlan.ComplexId)); await mediator.Send(new CreateNotificationCommand(message, shiftPlanUser.UserId, shiftPlan.ComplexId));
} }
break; break;
case ShiftPlanNotifyType.EndOfShift: case ShiftPlanNotifyType.EndOfShift:
var activitiesEndShift = await _repositoryWrapper.SetRepository<Activity>().TableNoTracking var activitiesEndShift = await repositoryWrapper.SetRepository<Activity>().TableNoTracking
.Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync(); .Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync();
foreach (var shiftPlanUser in shiftPlanUsers) foreach (var shiftPlanUser in shiftPlanUsers)
{ {
@ -62,13 +55,13 @@ public class ShiftPlanNotificationScheduledJob : IJob
if (unDoneCount == 0) if (unDoneCount == 0)
continue; continue;
string message = $"{shiftPlanUser.UserFullName} {shiftPlan.ShiftTitle} {shiftPlan.PlanFor.ToPersianDateTime().ToLongDateTimeString()} تموم شده است و {unDoneCount} - عدد از تسک های شما کاری روشون انجام نشده ، خطر سوپروایزر در کمین است"; string message = $"{shiftPlanUser.UserFullName} {shiftPlan.ShiftTitle} {shiftPlan.PlanFor.ToPersianDateTime().ToLongDateTimeString()} تموم شده است و {unDoneCount} - عدد از تسک های شما کاری روشون انجام نشده ، خطر سوپروایزر در کمین است";
await _mediator.Send(new CreateNotificationCommand(message, shiftPlanUser.UserId, shiftPlan.ComplexId)); await mediator.Send(new CreateNotificationCommand(message, shiftPlanUser.UserId, shiftPlan.ComplexId));
} }
string superVisorAfterShiftMessage = $"{shiftPlan.SupervisorFullName} محترم {shiftPlan.ShiftTitle} تموم شد. برو به کار بچه ها نمره بده و مو رو از ماست بکش و کامنت یادت نره"; string superVisorAfterShiftMessage = $"{shiftPlan.SupervisorFullName} محترم {shiftPlan.ShiftTitle} تموم شد. برو به کار بچه ها نمره بده و مو رو از ماست بکش و کامنت یادت نره";
await _mediator.Send(new CreateNotificationCommand(superVisorAfterShiftMessage, shiftPlan.SupervisorId, shiftPlan.ComplexId)); await mediator.Send(new CreateNotificationCommand(superVisorAfterShiftMessage, shiftPlan.SupervisorId, shiftPlan.ComplexId));
break; break;
case ShiftPlanNotifyType.AfterStartShift2Hour: case ShiftPlanNotifyType.AfterStartShift2Hour:
var activities2AfterStartShift = await _repositoryWrapper.SetRepository<Activity>().TableNoTracking var activities2AfterStartShift = await repositoryWrapper.SetRepository<Activity>().TableNoTracking
.Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync(); .Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync();
foreach (var shiftPlanUser in shiftPlanUsers) foreach (var shiftPlanUser in shiftPlanUsers)
{ {
@ -76,7 +69,7 @@ public class ShiftPlanNotificationScheduledJob : IJob
if (unDoneCount == 0) if (unDoneCount == 0)
continue; continue;
string message = $"{shiftPlanUser.UserFullName} دوساعت از {shiftPlan.ShiftTitle} گذشته ، اون انگشت و بزن روی تیک تسک ها که وقت طلاس مشتیییییی "; string message = $"{shiftPlanUser.UserFullName} دوساعت از {shiftPlan.ShiftTitle} گذشته ، اون انگشت و بزن روی تیک تسک ها که وقت طلاس مشتیییییی ";
await _mediator.Send(new CreateNotificationCommand(message, shiftPlanUser.UserId, shiftPlan.ComplexId)); await mediator.Send(new CreateNotificationCommand(message, shiftPlanUser.UserId, shiftPlan.ComplexId));
} }
break; break;
default: default:
@ -85,7 +78,7 @@ public class ShiftPlanNotificationScheduledJob : IJob
} }
catch (Exception e) catch (Exception e)
{ {
_logger.LogError(e.Message); logger.LogError(e.Message);
} }
} }
} }

View File

@ -2,38 +2,32 @@
namespace Brizco.Infrastructure.Marten; namespace Brizco.Infrastructure.Marten;
public class MartenRepository<TMartenEntity> : IMartenRepository<TMartenEntity> where TMartenEntity : IMartenEntity public class MartenRepository<TMartenEntity>(IDocumentStore documentStore) : IMartenRepository<TMartenEntity>
where TMartenEntity : IMartenEntity
{ {
private readonly IDocumentStore _documentStore;
public MartenRepository(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
public async Task<List<TMartenEntity>> GetEntitiesAsync(CancellationToken cancellation) public async Task<List<TMartenEntity>> GetEntitiesAsync(CancellationToken cancellation)
{ {
await using var session = _documentStore.QuerySession(); await using var session = documentStore.QuerySession();
var entities = await session.Query<TMartenEntity>().ToListAsync(cancellation); var entities = await session.Query<TMartenEntity>().ToListAsync(cancellation);
return entities.ToList(); return entities.ToList();
} }
public async Task<List<TMartenEntity>> GetEntitiesAsync(Expression<Func<TMartenEntity, bool>> expression, CancellationToken cancellation) public async Task<List<TMartenEntity>> GetEntitiesAsync(Expression<Func<TMartenEntity, bool>> expression, CancellationToken cancellation)
{ {
await using var session = _documentStore.QuerySession(); await using var session = documentStore.QuerySession();
var entities = await session.Query<TMartenEntity>().Where(expression).ToListAsync(cancellation); var entities = await session.Query<TMartenEntity>().Where(expression).ToListAsync(cancellation);
return entities.ToList(); return entities.ToList();
} }
public async Task<IQueryable<TMartenEntity>> GetQueryAsync(Expression<Func<TMartenEntity, bool>> expression) public async Task<IQueryable<TMartenEntity>> GetQueryAsync(Expression<Func<TMartenEntity, bool>> expression)
{ {
await using var session = _documentStore.QuerySession(); await using var session = documentStore.QuerySession();
var entities = session.Query<TMartenEntity>().Where(expression); var entities = session.Query<TMartenEntity>().Where(expression);
return entities; return entities;
} }
public async Task<TMartenEntity> GetEntityAsync(Guid id, CancellationToken cancellation) public async Task<TMartenEntity> GetEntityAsync(Guid id, CancellationToken cancellation)
{ {
await using var session = _documentStore.QuerySession(); await using var session = documentStore.QuerySession();
var setting = await session.LoadAsync<TMartenEntity>(id, cancellation); var setting = await session.LoadAsync<TMartenEntity>(id, cancellation);
if (setting == null) if (setting == null)
throw new AppException($"{nameof(TMartenEntity)} not found", ApiResultStatusCode.NotFound); throw new AppException($"{nameof(TMartenEntity)} not found", ApiResultStatusCode.NotFound);
@ -42,7 +36,7 @@ public class MartenRepository<TMartenEntity> : IMartenRepository<TMartenEntity>
public async Task<TMartenEntity?> GetEntityAsync(Expression<Func<TMartenEntity, bool>> expression, CancellationToken cancellation) public async Task<TMartenEntity?> GetEntityAsync(Expression<Func<TMartenEntity, bool>> expression, CancellationToken cancellation)
{ {
await using var session = _documentStore.QuerySession(); await using var session = documentStore.QuerySession();
var entity = await session.Query<TMartenEntity>().FirstOrDefaultAsync(expression, cancellation); var entity = await session.Query<TMartenEntity>().FirstOrDefaultAsync(expression, cancellation);
return entity; return entity;
} }
@ -52,7 +46,7 @@ public class MartenRepository<TMartenEntity> : IMartenRepository<TMartenEntity>
if (entity == null) if (entity == null)
throw new AppException($"{nameof(entity)} is null", ApiResultStatusCode.BadRequest); throw new AppException($"{nameof(entity)} is null", ApiResultStatusCode.BadRequest);
await using var session = _documentStore.LightweightSession(); await using var session = documentStore.LightweightSession();
session.Store(entity); session.Store(entity);
await session.SaveChangesAsync(cancellation); await session.SaveChangesAsync(cancellation);
} }
@ -61,7 +55,7 @@ public class MartenRepository<TMartenEntity> : IMartenRepository<TMartenEntity>
{ {
if (entity == null) if (entity == null)
throw new AppException($"{nameof(entity)} is null", ApiResultStatusCode.BadRequest); throw new AppException($"{nameof(entity)} is null", ApiResultStatusCode.BadRequest);
await using var session = _documentStore.LightweightSession(); await using var session = documentStore.LightweightSession();
session.Delete(entity); session.Delete(entity);
await session.SaveChangesAsync(cancellation); await session.SaveChangesAsync(cancellation);
} }

View File

@ -2,15 +2,8 @@
namespace Brizco.Infrastructure.Marten; namespace Brizco.Infrastructure.Marten;
public class MartenRepositoryWrapper : IMartenRepositoryWrapper public class MartenRepositoryWrapper(IDocumentStore documentStore) : IMartenRepositoryWrapper
{ {
private readonly IDocumentStore _documentStore;
public MartenRepositoryWrapper(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
public IMartenRepository<TMartenEntity> SetRepository<TMartenEntity>() where TMartenEntity : IMartenEntity public IMartenRepository<TMartenEntity> SetRepository<TMartenEntity>() where TMartenEntity : IMartenEntity
=> new MartenRepository<TMartenEntity>(_documentStore); => new MartenRepository<TMartenEntity>(documentStore);
} }

View File

@ -2,26 +2,18 @@
namespace Brizco.Infrastructure.Services; namespace Brizco.Infrastructure.Services;
public class SmsService : ISmsService public class SmsService(
IRestApiWrapper restApiWrapper,
IOptionsSnapshot<SiteSettings> optionsSnapshot,
ILogger<SmsService> logger,
IHostEnvironment environment)
: ISmsService
{ {
private readonly IRestApiWrapper _restApiWrapper; private readonly SiteSettings _siteSettings = optionsSnapshot.Value;
private readonly ILogger<SmsService> _logger;
private readonly IHostEnvironment _environment;
private readonly SiteSettings _siteSettings;
public SmsService(
IRestApiWrapper restApiWrapper,
IOptionsSnapshot<SiteSettings> optionsSnapshot,
ILogger<SmsService> logger,
IHostEnvironment environment)
{
_restApiWrapper = restApiWrapper;
_logger = logger;
_environment = environment;
_siteSettings = optionsSnapshot.Value;
}
public async Task SendForgerPasswordAsync(string phoneNumber, string newPassword) public async Task SendForgerPasswordAsync(string phoneNumber, string newPassword)
{ {
var rest = await _restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber, newPassword, null, null, null, "forgetPassword"); var rest = await restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber, newPassword, null, null, null, "forgetPassword");
if (rest.Return.status != 200) if (rest.Return.status != 200)
throw new BaseApiException(ApiResultStatusCode.SendSmsError, rest.Return.message); throw new BaseApiException(ApiResultStatusCode.SendSmsError, rest.Return.message);
@ -32,25 +24,25 @@ public class SmsService : ISmsService
try try
{ {
var rest = await _restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber, var rest = await restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber,
verifyCode, null, null, null, "login-brizco"); verifyCode, null, null, null, "login-brizco");
if (rest.Return.status != 200 && _environment.IsProduction()) if (rest.Return.status != 200 && environment.IsProduction())
throw new BaseApiException(ApiResultStatusCode.SendSmsError, rest.Return.message); throw new BaseApiException(ApiResultStatusCode.SendSmsError, rest.Return.message);
} }
catch (ApiException apiException) catch (ApiException apiException)
{ {
if (_environment.IsProduction()) if (environment.IsProduction())
throw ; throw ;
else else
_logger.LogError(apiException.Message); logger.LogError(apiException.Message);
} }
catch (Exception apiException) catch (Exception apiException)
{ {
if (_environment.IsProduction()) if (environment.IsProduction())
throw; throw;
else else
_logger.LogError(apiException.Message); logger.LogError(apiException.Message);
} }
} }

View File

@ -1,11 +1,8 @@
namespace Brizco.Repository.Extensions; namespace Brizco.Repository.Extensions;
public class DbContextOptionCustomExtensionsInfo : DbContextOptionsExtensionInfo public class DbContextOptionCustomExtensionsInfo(IDbContextOptionsExtension extension)
: DbContextOptionsExtensionInfo(extension)
{ {
public DbContextOptionCustomExtensionsInfo(IDbContextOptionsExtension extension) : base(extension)
{
}
public override bool IsDatabaseProvider { get; } public override bool IsDatabaseProvider { get; }
public override string LogFragment { get; } = string.Empty; public override string LogFragment { get; } = string.Empty;

View File

@ -1,25 +1,17 @@
namespace Brizco.Repository.Handlers.Activities; namespace Brizco.Repository.Handlers.Activities;
public class CreateActivityCommandHandler : IRequestHandler<CreateActivityCommand, ActivityLDto> public class CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateActivityCommand, ActivityLDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<ActivityLDto> Handle(CreateActivityCommand request, CancellationToken cancellationToken) public async Task<ActivityLDto> Handle(CreateActivityCommand request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var activity = Domain.Entities.Tasks.Activity var activity = Domain.Entities.Tasks.Activity
.Create( .Create(
ActivityStatus.Created, ActivityStatus.Created,
@ -39,14 +31,14 @@ public class CreateActivityCommandHandler : IRequestHandler<CreateActivityComman
activity.SetShiftPlan(request.ShiftPlanId); activity.SetShiftPlan(request.ShiftPlanId);
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>().Add(activity); repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>().Add(activity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return activity.AdaptToLDto(); return activity.AdaptToLDto();
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,33 +1,28 @@
namespace Brizco.Repository.Handlers.Activities; namespace Brizco.Repository.Handlers.Activities;
public class DeleteActivityCommandHandler : IRequestHandler<DeleteActivityCommand, bool> public class DeleteActivityCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteActivityCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteActivityCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteActivityCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeleteActivityCommand request, CancellationToken cancellationToken)
{ {
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var task = await _repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>() var task = await repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (task == null) if (task == null)
throw new AppException("Task not found", ApiResultStatusCode.NotFound); throw new AppException("Task not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>() repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
.Delete(task); .Delete(task);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return true; return true;
} }
catch (Exception ) catch (Exception )
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,17 +1,11 @@
namespace Brizco.Repository.Handlers.Activities; namespace Brizco.Repository.Handlers.Activities;
public class GetActivityQueryHandler : IRequestHandler<GetActivityQuery, ActivityLDto> public class GetActivityQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetActivityQuery, ActivityLDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetActivityQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ActivityLDto> Handle(GetActivityQuery request, CancellationToken cancellationToken) public async Task<ActivityLDto> Handle(GetActivityQuery request, CancellationToken cancellationToken)
{ {
var task = await _repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>() var task = await repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == request.Id) .Where(s => s.Id == request.Id)
.Select(ActivityMapper.ProjectToLDto) .Select(ActivityMapper.ProjectToLDto)

View File

@ -1,30 +1,22 @@
namespace Brizco.Repository.Handlers.Activities; namespace Brizco.Repository.Handlers.Activities;
public class UpdateActivityCommandHandler : IRequestHandler<UpdateActivityCommand, bool> public class UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateActivityCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdateActivityCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(UpdateActivityCommand request, CancellationToken cancellationToken)
{ {
var task = await _repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>() var task = await repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken);
if (task == null) if (task == null)
throw new AppException("Task not found", ApiResultStatusCode.NotFound); throw new AppException("Task not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId,out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId,out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var newTask = Domain.Entities.Tasks.Activity.Create( var newTask = Domain.Entities.Tasks.Activity.Create(
request.Status, request.Status,
request.DoneAt, request.DoneAt,
@ -45,16 +37,16 @@ public class UpdateActivityCommandHandler : IRequestHandler<UpdateActivityComman
newTask.SetUser(request.UserId); newTask.SetUser(request.UserId);
newTask.SetShiftPlan(request.ShiftPlanId); newTask.SetShiftPlan(request.ShiftPlanId);
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>() repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
.Update(newTask); .Update(newTask);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return true; return true;
} }
catch (Exception ) catch (Exception )
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,30 +1,24 @@
namespace Brizco.Repository.Handlers.Complexes; namespace Brizco.Repository.Handlers.Complexes;
public class CreateComplexCommandHandler : IRequestHandler<CreateComplexCommand, ComplexSDto> public class CreateComplexCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateComplexCommand, ComplexSDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper; private readonly ICurrentUserService _currentUserService = currentUserService;
private readonly ICurrentUserService _currentUserService;
public CreateComplexCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<ComplexSDto> Handle(CreateComplexCommand request, CancellationToken cancellationToken) public async Task<ComplexSDto> Handle(CreateComplexCommand request, CancellationToken cancellationToken)
{ {
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var complex = Complex.Create(request.Name, request.Address, request.SupportPhone); var complex = Complex.Create(request.Name, request.Address, request.SupportPhone);
_repositoryWrapper.SetRepository<Complex>().Add(complex); repositoryWrapper.SetRepository<Complex>().Add(complex);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return complex.AdaptToSDto(); return complex.AdaptToSDto();
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,37 +1,28 @@
namespace Brizco.Repository.Handlers.Complexes; namespace Brizco.Repository.Handlers.Complexes;
public class CreateComplexUserCommandHandler : IRequestHandler<CreateComplexUserCommand, ComplexUserSDto> public class CreateComplexUserCommandHandler(
IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
ILogger<CreateComplexUserCommandHandler> logger)
: IRequestHandler<CreateComplexUserCommand, ComplexUserSDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper; private readonly ILogger<CreateComplexUserCommandHandler> _logger = logger;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly ILogger<CreateComplexUserCommandHandler> _logger;
public CreateComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
ILogger<CreateComplexUserCommandHandler> logger)
{
_repositoryWrapper = repositoryWrapper;
_userManager = userManager;
_roleManager = roleManager;
_logger = logger;
}
public async Task<ComplexUserSDto> Handle(CreateComplexUserCommand request, CancellationToken cancellationToken) public async Task<ComplexUserSDto> Handle(CreateComplexUserCommand request, CancellationToken cancellationToken)
{ {
try try
{ {
//await _repositoryWrapper.BeginTransaction(cancellationToken); //await _repositoryWrapper.BeginTransaction(cancellationToken);
var complex = await _repositoryWrapper.SetRepository<Complex>().TableNoTracking var complex = await repositoryWrapper.SetRepository<Complex>().TableNoTracking
.FirstOrDefaultAsync(c => c.Id == request.ComplexId, cancellationToken); .FirstOrDefaultAsync(c => c.Id == request.ComplexId, cancellationToken);
if (complex == null) if (complex == null)
throw new AppException("Complex not found", ApiResultStatusCode.NotFound); throw new AppException("Complex not found", ApiResultStatusCode.NotFound);
var user = await _userManager.FindByIdAsync(request.UserId.ToString()); 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);
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>() var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(f => f.ComplexId == request.ComplexId && f.UserId == request.UserId, cancellationToken); .FirstOrDefaultAsync(f => f.ComplexId == request.ComplexId && f.UserId == request.UserId, cancellationToken);
if (complexUser != null) if (complexUser != null)
@ -40,21 +31,21 @@ public class CreateComplexUserCommandHandler : IRequestHandler<CreateComplexUser
complexUser = complex.AddComplexUser(request.UserId); complexUser = complex.AddComplexUser(request.UserId);
foreach (var roleId in request.RoleIds) foreach (var roleId in request.RoleIds)
{ {
var role = await _roleManager.FindByIdAsync(roleId.ToString()); var role = await roleManager.FindByIdAsync(roleId.ToString());
var result = await _userManager.AddToRoleAsync(user, role.Name); var result = await userManager.AddToRoleAsync(user, role.Name);
if (!result.Succeeded) if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors)); throw new AppException(string.Join('|', result.Errors));
complexUser.AddRole(role.Id); complexUser.AddRole(role.Id);
} }
_repositoryWrapper.SetRepository<ComplexUser>().Add(complexUser); repositoryWrapper.SetRepository<ComplexUser>().Add(complexUser);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
//await _repositoryWrapper.CommitAsync(cancellationToken); //await _repositoryWrapper.CommitAsync(cancellationToken);
return complexUser.AdaptToSDto(); return complexUser.AdaptToSDto();
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,33 +1,28 @@
namespace Brizco.Repository.Handlers.Complexes; namespace Brizco.Repository.Handlers.Complexes;
public class DeleteComplexCommandHandler : IRequestHandler<DeleteComplexCommand, bool> public class DeleteComplexCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteComplexCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteComplexCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteComplexCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeleteComplexCommand request, CancellationToken cancellationToken)
{ {
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var task = await _repositoryWrapper.SetRepository<Complex>() var task = await repositoryWrapper.SetRepository<Complex>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (task == null) if (task == null)
throw new AppException("Task not found", ApiResultStatusCode.NotFound); throw new AppException("Task not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Complex>() repositoryWrapper.SetRepository<Complex>()
.Delete(task); .Delete(task);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return true; return true;
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,39 +1,33 @@
namespace Brizco.Repository.Handlers.Complexes; namespace Brizco.Repository.Handlers.Complexes;
public class DeleteComplexUserCommandHandler : IRequestHandler<DeleteComplexUserCommand, bool> public class DeleteComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteComplexUserCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteComplexUserCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeleteComplexUserCommand request, CancellationToken cancellationToken)
{ {
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>() var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking .TableNoTracking
.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 var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>().TableNoTracking
.Where(c => c.ComplexUserId == complexUser.Id) .Where(c => c.ComplexUserId == complexUser.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var complexUserRole in complexUserRoles) foreach (var complexUserRole in complexUserRoles)
_repositoryWrapper.SetRepository<ComplexUserRole>().HardDelete(complexUserRole); repositoryWrapper.SetRepository<ComplexUserRole>().HardDelete(complexUserRole);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
_repositoryWrapper.SetRepository<ComplexUser>().HardDelete(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;
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,17 +1,11 @@
namespace Brizco.Repository.Handlers.Complexes; namespace Brizco.Repository.Handlers.Complexes;
public class GetComplexQueryHandler : IRequestHandler<GetComplexQuery, ComplexSDto> public class GetComplexQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetComplexQuery, ComplexSDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetComplexQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ComplexSDto> Handle(GetComplexQuery request, CancellationToken cancellationToken) public async Task<ComplexSDto> Handle(GetComplexQuery request, CancellationToken cancellationToken)
{ {
var complex = await _repositoryWrapper.SetRepository<Complex>() var complex = await repositoryWrapper.SetRepository<Complex>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == request.Id) .Where(s => s.Id == request.Id)
.Select(ComplexMapper.ProjectToSDto) .Select(ComplexMapper.ProjectToSDto)

View File

@ -2,24 +2,18 @@
namespace Brizco.Repository.Handlers.Complexes; namespace Brizco.Repository.Handlers.Complexes;
public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery, List<ComplexUserSDto>> public class GetComplexUsersQueryHandler(
IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
: IRequestHandler<GetComplexUsersQuery, List<ComplexUserSDto>>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public GetComplexUsersQueryHandler(IRepositoryWrapper repositoryWrapper, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
_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>(); 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))
{ {
list = 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)
@ -28,7 +22,7 @@ public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery,
} }
else else
{ {
list = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking list = await repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.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)
@ -39,13 +33,13 @@ public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery,
foreach (var complexUser in list) foreach (var complexUser in list)
{ {
var user = await _userManager.FindByIdAsync(complexUser.UserId.ToString()); var user = await userManager.FindByIdAsync(complexUser.UserId.ToString());
if (user != null) if (user != null)
{ {
var roleIds = await _userManager.GetRolesAsync(user); var roleIds = await userManager.GetRolesAsync(user);
foreach (var roleId in roleIds) foreach (var roleId in roleIds)
{ {
var role = await _roleManager.FindByNameAsync(roleId); var role = await roleManager.FindByNameAsync(roleId);
if(role!= null) if(role!= null)
complexUser.RoleNames.Add(role.PersianName); complexUser.RoleNames.Add(role.PersianName);
} }

View File

@ -1,16 +1,11 @@
namespace Brizco.Repository.Handlers.Complexes; namespace Brizco.Repository.Handlers.Complexes;
public class GetComplexesQueryHandler : IRequestHandler<GetComplexesQuery, List<ComplexSDto>> public class GetComplexesQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetComplexesQuery, List<ComplexSDto>>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetComplexesQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<ComplexSDto>> Handle(GetComplexesQuery request, CancellationToken cancellationToken) public async Task<List<ComplexSDto>> Handle(GetComplexesQuery request, CancellationToken cancellationToken)
{ {
var tasks = await _repositoryWrapper.SetRepository<Complex>().TableNoTracking var tasks = await repositoryWrapper.SetRepository<Complex>().TableNoTracking
.OrderByDescending(s => s.CreatedAt) .OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15) .Skip(request.Page * 15).Take(15)
.Select(ComplexMapper.ProjectToSDto) .Select(ComplexMapper.ProjectToSDto)

View File

@ -1,36 +1,27 @@
namespace Brizco.Repository.Handlers.Complexes; namespace Brizco.Repository.Handlers.Complexes;
public class UpdateComplexUserCommandHandler : IRequestHandler<UpdateComplexUserCommand, bool> public class UpdateComplexUserCommandHandler(
IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
: IRequestHandler<UpdateComplexUserCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public UpdateComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
{
_repositoryWrapper = repositoryWrapper;
_userManager = userManager;
_roleManager = roleManager;
}
public async Task<bool> Handle(UpdateComplexUserCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(UpdateComplexUserCommand request, CancellationToken cancellationToken)
{ {
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking var complexUser = await repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == request.UserId && c.ComplexId == request.ComplexId , cancellationToken); .FirstOrDefaultAsync(c => c.UserId == request.UserId && c.ComplexId == request.ComplexId , 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>() var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking .TableNoTracking
.Where(cur => cur.ComplexUserId == complexUser.Id) .Where(cur => cur.ComplexUserId == complexUser.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
var user = await _userManager.FindByIdAsync(complexUser.UserId.ToString()); var user = await userManager.FindByIdAsync(complexUser.UserId.ToString());
if (user == null) if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound); throw new AppException("User not found", ApiResultStatusCode.NotFound);
@ -46,30 +37,30 @@ public class UpdateComplexUserCommandHandler : IRequestHandler<UpdateComplexUser
foreach (var userRole in complexUserRoles) foreach (var userRole in complexUserRoles)
{ {
_repositoryWrapper.SetRepository<ComplexUserRole>().Delete(userRole); repositoryWrapper.SetRepository<ComplexUserRole>().Delete(userRole);
var role = await _roleManager.FindByIdAsync(userRole.RoleId.ToString()); var role = await roleManager.FindByIdAsync(userRole.RoleId.ToString());
var result = await _userManager.RemoveFromRoleAsync(user, role.Name); var result = await userManager.RemoveFromRoleAsync(user, role.Name);
if (!result.Succeeded) if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors)); throw new AppException(string.Join('|', result.Errors));
} }
foreach (var roleId in request.RoleIds) foreach (var roleId in request.RoleIds)
{ {
var role = await _roleManager.FindByIdAsync(roleId.ToString()); var role = await roleManager.FindByIdAsync(roleId.ToString());
var result = await _userManager.AddToRoleAsync(user, role.Name); var result = await userManager.AddToRoleAsync(user, role.Name);
if (!result.Succeeded) if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors)); throw new AppException(string.Join('|', result.Errors));
var userRole = complexUser.AddRole(role.Id); var userRole = complexUser.AddRole(role.Id);
_repositoryWrapper.SetRepository<ComplexUserRole>().Add(userRole); repositoryWrapper.SetRepository<ComplexUserRole>().Add(userRole);
} }
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return true; return true;
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,26 +1,19 @@
namespace Brizco.Repository.Handlers.Positions; namespace Brizco.Repository.Handlers.Positions;
public class CreatePositionCommandHandler : IRequestHandler<CreatePositionCommand, PositionSDto> public class CreatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreatePositionCommand, PositionSDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<PositionSDto> Handle(CreatePositionCommand request, CancellationToken cancellationToken) public async Task<PositionSDto> Handle(CreatePositionCommand request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var entity = Position var entity = Position
.Create(request.Title, .Create(request.Title,
request.Description, request.Description,
@ -29,14 +22,14 @@ public class CreatePositionCommandHandler : IRequestHandler<CreatePositionComman
request.Permissions.ForEach(f=>entity.AddPermission(f)); request.Permissions.ForEach(f=>entity.AddPermission(f));
_repositoryWrapper.SetRepository<Position>().Add(entity); repositoryWrapper.SetRepository<Position>().Add(entity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return entity.AdaptToSDto(); return entity.AdaptToSDto();
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,24 +1,19 @@
namespace Brizco.Repository.Handlers.Positions; namespace Brizco.Repository.Handlers.Positions;
public class DeletePositionCommandHandler : IRequestHandler<DeletePositionCommand, bool> public class DeletePositionCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeletePositionCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeletePositionCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeletePositionCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeletePositionCommand request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Position>() var shift = await repositoryWrapper.SetRepository<Position>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (shift == null) if (shift == null)
throw new AppException("Postion not found", ApiResultStatusCode.NotFound); throw new AppException("Postion not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Position>() repositoryWrapper.SetRepository<Position>()
.Delete(shift); .Delete(shift);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }
} }

View File

@ -1,16 +1,11 @@
namespace Brizco.Repository.Handlers.Positions; namespace Brizco.Repository.Handlers.Positions;
public class GetPositionQueryHandler : IRequestHandler<GetPositionQuery, PositionLDto> public class GetPositionQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetPositionQuery, PositionLDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetPositionQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<PositionLDto> Handle(GetPositionQuery request, CancellationToken cancellationToken) public async Task<PositionLDto> Handle(GetPositionQuery request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Position>() var shift = await repositoryWrapper.SetRepository<Position>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == request.Id) .Where(s => s.Id == request.Id)
.Select(PositionMapper.ProjectToLDto) .Select(PositionMapper.ProjectToLDto)

View File

@ -1,24 +1,17 @@
namespace Brizco.Repository.Handlers.Positions; namespace Brizco.Repository.Handlers.Positions;
public class GetPositionsQueryHandler : IRequestHandler<GetPositionsQuery, List<PositionSDto>> public class GetPositionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<GetPositionsQuery, List<PositionSDto>>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public GetPositionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<List<PositionSDto>> Handle(GetPositionsQuery request, CancellationToken cancellationToken) public async Task<List<PositionSDto>> Handle(GetPositionsQuery request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var shifts = await _repositoryWrapper.SetRepository<Position>().TableNoTracking var shifts = await repositoryWrapper.SetRepository<Position>().TableNoTracking
.Where(p=>p.ComplexId==complexId) .Where(p=>p.ComplexId==complexId)
.OrderByDescending(s => s.CreatedAt) .OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15) .Skip(request.Page * 15).Take(15)

View File

@ -1,26 +1,18 @@
namespace Brizco.Repository.Handlers.Positions; namespace Brizco.Repository.Handlers.Positions;
public class UpdatePositionCommandHandler : IRequestHandler<UpdatePositionCommand, bool> public class UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdatePositionCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdatePositionCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(UpdatePositionCommand request, CancellationToken cancellationToken)
{ {
var ent = await _repositoryWrapper.SetRepository<Position>() var ent = await repositoryWrapper.SetRepository<Position>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (ent == null) if (ent == null)
throw new AppException("Postion not found", ApiResultStatusCode.NotFound); throw new AppException("Postion not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var newPosition = Position.Create(request.Title, var newPosition = Position.Create(request.Title,
@ -31,25 +23,25 @@ public class UpdatePositionCommandHandler : IRequestHandler<UpdatePositionComman
newPosition.CreatedAt = ent.CreatedAt; newPosition.CreatedAt = ent.CreatedAt;
newPosition.CreatedBy = ent.CreatedBy; newPosition.CreatedBy = ent.CreatedBy;
var permissionsDb = await _repositoryWrapper.SetRepository<PositionPermission>() var permissionsDb = await repositoryWrapper.SetRepository<PositionPermission>()
.TableNoTracking .TableNoTracking
.Where(f => f.PositionId == ent.Id) .Where(f => f.PositionId == ent.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var permissionDb in permissionsDb.Where(p=>!request.Permissions.Contains(p.Permission))) foreach (var permissionDb in permissionsDb.Where(p=>!request.Permissions.Contains(p.Permission)))
{ {
_repositoryWrapper.SetRepository<PositionPermission>() repositoryWrapper.SetRepository<PositionPermission>()
.Delete(permissionDb); .Delete(permissionDb);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
} }
foreach (var permission in request.Permissions.Where(p => !permissionsDb.Select(d => d.Permission).Contains(p))) foreach (var permission in request.Permissions.Where(p => !permissionsDb.Select(d => d.Permission).Contains(p)))
newPosition.AddPermission(permission); newPosition.AddPermission(permission);
_repositoryWrapper.SetRepository<Position>() repositoryWrapper.SetRepository<Position>()
.Update(newPosition); .Update(newPosition);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }

View File

@ -1,37 +1,30 @@
namespace Brizco.Repository.Handlers.Routines; namespace Brizco.Repository.Handlers.Routines;
public class CreateRoutineCommandHandler : IRequestHandler<CreateRoutineCommand, RoutineSDto> public class CreateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateRoutineCommand, RoutineSDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<RoutineSDto> Handle(CreateRoutineCommand request, CancellationToken cancellationToken) public async Task<RoutineSDto> Handle(CreateRoutineCommand request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var entity = Domain.Entities.Routines.Routine var entity = Domain.Entities.Routines.Routine
.Create(request.Name,request.Description,complexId); .Create(request.Name,request.Description,complexId);
_repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>().Add(entity); repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>().Add(entity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return entity.AdaptToSDto(); return entity.AdaptToSDto();
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,24 +1,19 @@
namespace Brizco.Repository.Handlers.Routines; namespace Brizco.Repository.Handlers.Routines;
public class DeleteRoutineCommandHandler : IRequestHandler<DeleteRoutineCommand, bool> public class DeleteRoutineCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteRoutineCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteRoutineCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteRoutineCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeleteRoutineCommand request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>() var shift = await repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (shift == null) if (shift == null)
throw new AppException("Postion not found", ApiResultStatusCode.NotFound); throw new AppException("Postion not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>() repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
.Delete(shift); .Delete(shift);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }
} }

View File

@ -1,16 +1,11 @@
namespace Brizco.Repository.Handlers.Routines; namespace Brizco.Repository.Handlers.Routines;
public class GetRoutineQueryHandler : IRequestHandler<GetRoutineQuery, RoutineSDto> public class GetRoutineQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetRoutineQuery, RoutineSDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetRoutineQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<RoutineSDto> Handle(GetRoutineQuery request, CancellationToken cancellationToken) public async Task<RoutineSDto> Handle(GetRoutineQuery request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>() var shift = await repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == request.Id) .Where(s => s.Id == request.Id)
.Select(RoutineMapper.ProjectToSDto) .Select(RoutineMapper.ProjectToSDto)

View File

@ -1,25 +1,19 @@
namespace Brizco.Repository.Handlers.Routines; namespace Brizco.Repository.Handlers.Routines;
public class GetRoutineShiftsQueryHandler : IRequestHandler<GetRoutineShiftsQuery,List<RoutineShiftResponseDto>> public class GetRoutineShiftsQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetRoutineShiftsQuery, List<RoutineShiftResponseDto>>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetRoutineShiftsQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<RoutineShiftResponseDto>> Handle(GetRoutineShiftsQuery request, CancellationToken cancellationToken) public async Task<List<RoutineShiftResponseDto>> Handle(GetRoutineShiftsQuery request, CancellationToken cancellationToken)
{ {
var routineShiftResponse = new List<RoutineShiftResponseDto>(); var routineShiftResponse = new List<RoutineShiftResponseDto>();
var shiftRoutines = await _repositoryWrapper.SetRepository<ShiftRoutine>() var shiftRoutines = await repositoryWrapper.SetRepository<ShiftRoutine>()
.TableNoTracking .TableNoTracking
.Where(s => s.RoutineId == request.Id) .Where(s => s.RoutineId == request.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var shiftRoutine in shiftRoutines) foreach (var shiftRoutine in shiftRoutines)
{ {
var shift = await _repositoryWrapper.SetRepository<Shift>() var shift = await repositoryWrapper.SetRepository<Shift>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == shiftRoutine.ShiftId) .Where(s => s.Id == shiftRoutine.ShiftId)
.Select(ShiftMapper.ProjectToSDto) .Select(ShiftMapper.ProjectToSDto)
@ -46,7 +40,7 @@ public class GetRoutineShiftsQueryHandler : IRequestHandler<GetRoutineShiftsQuer
{ {
var selectedDate = DateTimeExtensions.UnixTimeStampToDateTime(request.SelectedDate); var selectedDate = DateTimeExtensions.UnixTimeStampToDateTime(request.SelectedDate);
var existedShiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>() var existedShiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.ShiftId == shift.Id && s.PlanFor.Date == selectedDate.Date, cancellationToken); .FirstOrDefaultAsync(s => s.ShiftId == shift.Id && s.PlanFor.Date == selectedDate.Date, cancellationToken);
shift.IsCompleted = existedShiftPlan?.IsCompleted ?? false; shift.IsCompleted = existedShiftPlan?.IsCompleted ?? false;

View File

@ -1,24 +1,17 @@
namespace Brizco.Repository.Handlers.Routines; namespace Brizco.Repository.Handlers.Routines;
public class GetRoutinesQueryHandler : IRequestHandler<GetRoutinesQuery, List<RoutineSDto>> public class GetRoutinesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<GetRoutinesQuery, List<RoutineSDto>>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public GetRoutinesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<List<RoutineSDto>> Handle(GetRoutinesQuery request, CancellationToken cancellationToken) public async Task<List<RoutineSDto>> Handle(GetRoutinesQuery request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var entities = await _repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>().TableNoTracking var entities = await repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>().TableNoTracking
.Where(p=>p.ComplexId==complexId) .Where(p=>p.ComplexId==complexId)
.OrderByDescending(s => s.CreatedAt) .OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15) .Skip(request.Page * 15).Take(15)

View File

@ -1,26 +1,18 @@
namespace Brizco.Repository.Handlers.Routines; namespace Brizco.Repository.Handlers.Routines;
public class UpdateRoutineCommandHandler : IRequestHandler<UpdateRoutineCommand, bool> public class UpdateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateRoutineCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdateRoutineCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(UpdateRoutineCommand request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>() var shift = await repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (shift == null) if (shift == null)
throw new AppException("Routine not found", ApiResultStatusCode.NotFound); throw new AppException("Routine not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var newEntity = Domain.Entities.Routines.Routine.Create(request.Name, var newEntity = Domain.Entities.Routines.Routine.Create(request.Name,
@ -29,10 +21,10 @@ public class UpdateRoutineCommandHandler : IRequestHandler<UpdateRoutineCommand,
newEntity.Id = request.Id; newEntity.Id = request.Id;
_repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>() repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
.Update(newEntity); .Update(newEntity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }

View File

@ -1,39 +1,32 @@
namespace Brizco.Repository.Handlers.Sections; namespace Brizco.Repository.Handlers.Sections;
public class CreateSectionCommandHandler : IRequestHandler<CreateSectionCommand, SectionSDto> public class CreateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateSectionCommand, SectionSDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<SectionSDto> Handle(CreateSectionCommand request, CancellationToken cancellationToken) public async Task<SectionSDto> Handle(CreateSectionCommand request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var entity = Section var entity = Section
.Create(request.Title, .Create(request.Title,
request.Description, request.Description,
complexId); complexId);
_repositoryWrapper.SetRepository<Section>().Add(entity); repositoryWrapper.SetRepository<Section>().Add(entity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return entity.AdaptToSDto(); return entity.AdaptToSDto();
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,32 +1,27 @@
namespace Brizco.Repository.Handlers.Sections; namespace Brizco.Repository.Handlers.Sections;
public class DeleteSectionCommandHandler : IRequestHandler<DeleteSectionCommand, bool> public class DeleteSectionCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteSectionCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteSectionCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteSectionCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeleteSectionCommand request, CancellationToken cancellationToken)
{ {
var section = await _repositoryWrapper.SetRepository<Section>() var section = await repositoryWrapper.SetRepository<Section>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (section == null) if (section == null)
throw new AppException("Section not found", ApiResultStatusCode.NotFound); throw new AppException("Section not found", ApiResultStatusCode.NotFound);
var positions = await _repositoryWrapper.SetRepository<Position>() var positions = await repositoryWrapper.SetRepository<Position>()
.TableNoTracking .TableNoTracking
.Where(p => p.SectionId == section.Id) .Where(p => p.SectionId == section.Id)
.CountAsync(cancellationToken); .CountAsync(cancellationToken);
if (positions > 0) if (positions > 0)
throw new AppException("این سکشن پوزیشن فعال دارد ، نخست پوزیشن های سکشن را حذف کرده یا منتقل کنید"); throw new AppException("این سکشن پوزیشن فعال دارد ، نخست پوزیشن های سکشن را حذف کرده یا منتقل کنید");
_repositoryWrapper.SetRepository<Section>() repositoryWrapper.SetRepository<Section>()
.Delete(section); .Delete(section);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }
} }

View File

@ -1,16 +1,11 @@
namespace Brizco.Repository.Handlers.Sections; namespace Brizco.Repository.Handlers.Sections;
public class GetSectionQueryHandler : IRequestHandler<GetSectionQuery, SectionLDto> public class GetSectionQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetSectionQuery, SectionLDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetSectionQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<SectionLDto> Handle(GetSectionQuery request, CancellationToken cancellationToken) public async Task<SectionLDto> Handle(GetSectionQuery request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Section>() var shift = await repositoryWrapper.SetRepository<Section>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == request.Id) .Where(s => s.Id == request.Id)
.Select(SectionMapper.ProjectToLDto) .Select(SectionMapper.ProjectToLDto)

View File

@ -1,23 +1,16 @@
namespace Brizco.Repository.Handlers.Sections; namespace Brizco.Repository.Handlers.Sections;
public class GetSectionsQueryHandler : IRequestHandler<GetSectionsQuery, List<SectionSDto>> public class GetSectionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<GetSectionsQuery, List<SectionSDto>>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public GetSectionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<List<SectionSDto>> Handle(GetSectionsQuery request, CancellationToken cancellationToken) public async Task<List<SectionSDto>> Handle(GetSectionsQuery request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var shifts = await _repositoryWrapper.SetRepository<Section>().TableNoTracking var shifts = await repositoryWrapper.SetRepository<Section>().TableNoTracking
.Where(s=>s.ComplexId==complexId) .Where(s=>s.ComplexId==complexId)
.OrderByDescending(s => s.CreatedAt) .OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15) .Skip(request.Page * 15).Take(15)

View File

@ -1,26 +1,18 @@
namespace Brizco.Repository.Handlers.Sections; namespace Brizco.Repository.Handlers.Sections;
public class UpdateSectionCommandHandler : IRequestHandler<UpdateSectionCommand, bool> public class UpdateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateSectionCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdateSectionCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(UpdateSectionCommand request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Section>() var shift = await repositoryWrapper.SetRepository<Section>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (shift == null) if (shift == null)
throw new AppException("Section not found", ApiResultStatusCode.NotFound); throw new AppException("Section not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var newSection = Section.Create(request.Title, var newSection = Section.Create(request.Title,
@ -29,10 +21,10 @@ public class UpdateSectionCommandHandler : IRequestHandler<UpdateSectionCommand,
newSection.Id = request.Id; newSection.Id = request.Id;
_repositoryWrapper.SetRepository<Section>() repositoryWrapper.SetRepository<Section>()
.Update(newSection); .Update(newSection);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }

View File

@ -1,25 +1,19 @@
namespace Brizco.Repository.Handlers.ShiftPlans; namespace Brizco.Repository.Handlers.ShiftPlans;
public class DeleteShiftPlanCommandHandler : IRequestHandler<DeleteShiftPlanCommand, bool> public class DeleteShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteShiftPlanCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteShiftPlanCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeleteShiftPlanCommand request, CancellationToken cancellationToken)
{ {
var shiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>() var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken);
if (shiftPlan == null) if (shiftPlan == null)
throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound); throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<ShiftPlan>() repositoryWrapper.SetRepository<ShiftPlan>()
.Delete(shiftPlan); .Delete(shiftPlan);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }

View File

@ -1,16 +1,11 @@
namespace Brizco.Repository.Handlers.ShiftPlans; namespace Brizco.Repository.Handlers.ShiftPlans;
public class GetShiftPlanQueryHandler : IRequestHandler<GetShiftPlanQuery, ShiftPlanLDto> public class GetShiftPlanQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetShiftPlanQuery, ShiftPlanLDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetShiftPlanQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ShiftPlanLDto> Handle(GetShiftPlanQuery request, CancellationToken cancellationToken) public async Task<ShiftPlanLDto> Handle(GetShiftPlanQuery request, CancellationToken cancellationToken)
{ {
var shiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>() var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == request.Id) .Where(s => s.Id == request.Id)
.Select(ShiftPlanMapper.ProjectToLDto) .Select(ShiftPlanMapper.ProjectToLDto)

View File

@ -1,23 +1,17 @@
namespace Brizco.Repository.Handlers.ShiftPlans; namespace Brizco.Repository.Handlers.ShiftPlans;
public class UpdateShiftPlanCommandHandler : IRequestHandler<UpdateShiftPlanCommand, bool> public class UpdateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<UpdateShiftPlanCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public UpdateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(UpdateShiftPlanCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(UpdateShiftPlanCommand request, CancellationToken cancellationToken)
{ {
var shiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>() var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken);
if (shiftPlan == null) if (shiftPlan == null)
throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound); throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound);
var shift = await _repositoryWrapper.SetRepository<Shift>() var shift = await repositoryWrapper.SetRepository<Shift>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.ShiftId, cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.ShiftId, cancellationToken);
if (shift == null) if (shift == null)
@ -28,7 +22,7 @@ public class UpdateShiftPlanCommandHandler : IRequestHandler<UpdateShiftPlanComm
newPlan.Id = request.Id; newPlan.Id = request.Id;
var shiftPlanUsers = await _repositoryWrapper.SetRepository<ShiftPlanUser>() var shiftPlanUsers = await repositoryWrapper.SetRepository<ShiftPlanUser>()
.TableNoTracking .TableNoTracking
.Where(s => s.ShiftPlanId == newPlan.Id) .Where(s => s.ShiftPlanId == newPlan.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
@ -39,19 +33,19 @@ public class UpdateShiftPlanCommandHandler : IRequestHandler<UpdateShiftPlanComm
request.UserAndPositionIds.Remove(new KeyValuePair<Guid, Guid>(shiftPlanUser.PositionId, shiftPlanUser.UserId)); request.UserAndPositionIds.Remove(new KeyValuePair<Guid, Guid>(shiftPlanUser.PositionId, shiftPlanUser.UserId));
else else
{ {
_repositoryWrapper.SetRepository<ShiftPlanUser>() repositoryWrapper.SetRepository<ShiftPlanUser>()
.Delete(shiftPlanUser); .Delete(shiftPlanUser);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
} }
} }
foreach (var userId in request.UserAndPositionIds) foreach (var userId in request.UserAndPositionIds)
newPlan.AddUser(userId.Key,userId.Value); newPlan.AddUser(userId.Key,userId.Value);
_repositoryWrapper.SetRepository<ShiftPlan>() repositoryWrapper.SetRepository<ShiftPlan>()
.Update(newPlan); .Update(newPlan);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }

View File

@ -1,26 +1,19 @@
namespace Brizco.Repository.Handlers.Shifts; namespace Brizco.Repository.Handlers.Shifts;
public class CreateShiftCommandHandler : IRequestHandler<CreateShiftCommand, ShiftSDto> public class CreateShiftCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateShiftCommand, ShiftSDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateShiftCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<ShiftSDto> Handle(CreateShiftCommand request, CancellationToken cancellationToken) public async Task<ShiftSDto> Handle(CreateShiftCommand request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
try try
{ {
await _repositoryWrapper.BeginTransaction(cancellationToken); await repositoryWrapper.BeginTransaction(cancellationToken);
var shift = Shift var shift = Shift
.Create(request.Title, .Create(request.Title,
request.Description, request.Description,
@ -34,14 +27,14 @@ public class CreateShiftCommandHandler : IRequestHandler<CreateShiftCommand, Shi
throw new AppException("روتین شیفت را انتخاب کنید"); throw new AppException("روتین شیفت را انتخاب کنید");
request.Routines.ForEach(r=>shift.AddRoutine(r)); request.Routines.ForEach(r=>shift.AddRoutine(r));
_repositoryWrapper.SetRepository<Shift>().Add(shift); repositoryWrapper.SetRepository<Shift>().Add(shift);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken);
return shift.AdaptToSDto(); return shift.AdaptToSDto();
} }
catch (Exception) catch (Exception)
{ {
await _repositoryWrapper.RollBackAsync(cancellationToken); await repositoryWrapper.RollBackAsync(cancellationToken);
throw; throw;
} }
} }

View File

@ -1,24 +1,19 @@
namespace Brizco.Repository.Handlers.Shifts; namespace Brizco.Repository.Handlers.Shifts;
public class DeletePositionCommandHandler : IRequestHandler<DeleteShiftCommand, bool> public class DeletePositionCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteShiftCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeletePositionCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteShiftCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeleteShiftCommand request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Shift>() var shift = await repositoryWrapper.SetRepository<Shift>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (shift == null) if (shift == null)
throw new AppException("Routine not found", ApiResultStatusCode.NotFound); throw new AppException("Routine not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Shift>() repositoryWrapper.SetRepository<Shift>()
.Delete(shift); .Delete(shift);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }
} }

View File

@ -1,16 +1,10 @@
namespace Brizco.Repository.Handlers.Shifts; namespace Brizco.Repository.Handlers.Shifts;
public class GetShiftPlanQueryHandler : IRequestHandler<GetShiftQuery, ShiftLDto> public class GetShiftPlanQueryHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler<GetShiftQuery, ShiftLDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetShiftPlanQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ShiftLDto> Handle(GetShiftQuery request, CancellationToken cancellationToken) public async Task<ShiftLDto> Handle(GetShiftQuery request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Shift>() var shift = await repositoryWrapper.SetRepository<Shift>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == request.Id) .Where(s => s.Id == request.Id)
.Select(ShiftMapper.ProjectToLDto) .Select(ShiftMapper.ProjectToLDto)

View File

@ -1,26 +1,18 @@
namespace Brizco.Repository.Handlers.Shifts; namespace Brizco.Repository.Handlers.Shifts;
public class UpdatePositionCommandHandler : IRequestHandler<UpdateShiftCommand, bool> public class UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateShiftCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdateShiftCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(UpdateShiftCommand request, CancellationToken cancellationToken)
{ {
var shift = await _repositoryWrapper.SetRepository<Shift>() var shift = await repositoryWrapper.SetRepository<Shift>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (shift == null) if (shift == null)
throw new AppException("Shift not found", ApiResultStatusCode.NotFound); throw new AppException("Shift not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var newShift = Shift.Create(request.Title, var newShift = Shift.Create(request.Title,
@ -32,15 +24,15 @@ public class UpdatePositionCommandHandler : IRequestHandler<UpdateShiftCommand,
if (request.DayOfWeeks.Count == 0) if (request.DayOfWeeks.Count == 0)
throw new AppException("روزهای شیفت را انتخاب کنید"); throw new AppException("روزهای شیفت را انتخاب کنید");
var shiftDays = await _repositoryWrapper.SetRepository<ShiftDay>() var shiftDays = await repositoryWrapper.SetRepository<ShiftDay>()
.TableNoTracking.Where(sd => sd.ShiftId == request.Id) .TableNoTracking.Where(sd => sd.ShiftId == request.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var shiftDay in shiftDays.Where(shiftDay => !request.DayOfWeeks.Contains(shiftDay.DayOfWeek))) foreach (var shiftDay in shiftDays.Where(shiftDay => !request.DayOfWeeks.Contains(shiftDay.DayOfWeek)))
{ {
_repositoryWrapper.SetRepository<ShiftDay>() repositoryWrapper.SetRepository<ShiftDay>()
.Delete(shiftDay); .Delete(shiftDay);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
} }
foreach (var dayOfWeek in from dayOfWeek in request.DayOfWeeks let findDay = shiftDays.FirstOrDefault(sf => sf.DayOfWeek == dayOfWeek) where findDay == null select dayOfWeek) foreach (var dayOfWeek in from dayOfWeek in request.DayOfWeeks let findDay = shiftDays.FirstOrDefault(sf => sf.DayOfWeek == dayOfWeek) where findDay == null select dayOfWeek)
@ -51,15 +43,15 @@ public class UpdatePositionCommandHandler : IRequestHandler<UpdateShiftCommand,
if (request.Routines.Count == 0) if (request.Routines.Count == 0)
throw new AppException("روتین شیفت را انتخاب کنید"); throw new AppException("روتین شیفت را انتخاب کنید");
var shiftRoutines = await _repositoryWrapper.SetRepository<ShiftRoutine>() var shiftRoutines = await repositoryWrapper.SetRepository<ShiftRoutine>()
.TableNoTracking.Where(sd => sd.ShiftId == request.Id) .TableNoTracking.Where(sd => sd.ShiftId == request.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var shiftRoutine in shiftRoutines.Where(shiftRoutine => !request.Routines.Contains(shiftRoutine.RoutineId))) foreach (var shiftRoutine in shiftRoutines.Where(shiftRoutine => !request.Routines.Contains(shiftRoutine.RoutineId)))
{ {
_repositoryWrapper.SetRepository<ShiftRoutine>() repositoryWrapper.SetRepository<ShiftRoutine>()
.Delete(shiftRoutine); .Delete(shiftRoutine);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
} }
foreach (var routine in request.Routines.Where(r=>!shiftRoutines.Exists(routine=>routine.RoutineId==r))) foreach (var routine in request.Routines.Where(r=>!shiftRoutines.Exists(routine=>routine.RoutineId==r)))
@ -67,9 +59,9 @@ public class UpdatePositionCommandHandler : IRequestHandler<UpdateShiftCommand,
newShift.AddRoutine(routine); newShift.AddRoutine(routine);
} }
_repositoryWrapper.SetRepository<Shift>() repositoryWrapper.SetRepository<Shift>()
.Update(newShift); .Update(newShift);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }

View File

@ -1,20 +1,13 @@
namespace Brizco.Repository.Handlers.Tasks; namespace Brizco.Repository.Handlers.Tasks;
public class CreateActivityCommandHandler : IRequestHandler<CreateTaskCommand, TaskLDto> public class CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateTaskCommand, TaskLDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<TaskLDto> Handle(CreateTaskCommand request, CancellationToken cancellationToken) public async Task<TaskLDto> Handle(CreateTaskCommand request, CancellationToken cancellationToken)
{ {
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var task = Domain.Entities.Tasks.Task var task = Domain.Entities.Tasks.Task
.Create(request.Title, .Create(request.Title,
@ -45,8 +38,8 @@ public class CreateActivityCommandHandler : IRequestHandler<CreateTaskCommand, T
request.Days.ForEach(d=>task.SetDay(d)); request.Days.ForEach(d=>task.SetDay(d));
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>().Add(task); repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>().Add(task);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return task.AdaptToLDto(); return task.AdaptToLDto();
} }
} }

View File

@ -1,24 +1,19 @@
namespace Brizco.Repository.Handlers.Tasks; namespace Brizco.Repository.Handlers.Tasks;
public class DeleteActivityCommandHandler : IRequestHandler<DeleteTaskCommand, bool> public class DeleteActivityCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteTaskCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteActivityCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteTaskCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(DeleteTaskCommand request, CancellationToken cancellationToken)
{ {
var task = await _repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>() var task = await repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>()
.TableNoTracking .TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (task == null) if (task == null)
throw new AppException("Task not found", ApiResultStatusCode.NotFound); throw new AppException("Task not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>() repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>()
.Delete(task); .Delete(task);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }
} }

View File

@ -1,17 +1,10 @@
namespace Brizco.Repository.Handlers.Tasks; namespace Brizco.Repository.Handlers.Tasks;
public class GetActivityQueryHandler : IRequestHandler<GetTaskQuery, TaskLDto> public class GetActivityQueryHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler<GetTaskQuery, TaskLDto>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
public GetActivityQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<TaskLDto> Handle(GetTaskQuery request, CancellationToken cancellationToken) public async Task<TaskLDto> Handle(GetTaskQuery request, CancellationToken cancellationToken)
{ {
var task = await _repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>() var task = await repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>()
.TableNoTracking .TableNoTracking
.Where(s => s.Id == request.Id) .Where(s => s.Id == request.Id)
.Select(TaskMapper.ProjectToLDto) .Select(TaskMapper.ProjectToLDto)

View File

@ -2,27 +2,19 @@
namespace Brizco.Repository.Handlers.Tasks; namespace Brizco.Repository.Handlers.Tasks;
public class UpdateActivityCommandHandler : IRequestHandler<UpdateTaskCommand, bool> public class UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateTaskCommand, bool>
{ {
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdateTaskCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(UpdateTaskCommand request, CancellationToken cancellationToken)
{ {
var task = await _repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>() var task = await repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken);
if (task == null) if (task == null)
throw new AppException("Task not found", ApiResultStatusCode.NotFound); throw new AppException("Task not found", ApiResultStatusCode.NotFound);
if (_currentUserService.ComplexId == null) if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound); throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
var newTask = Domain.Entities.Tasks.Task.Create(request.Title, var newTask = Domain.Entities.Tasks.Task.Create(request.Title,
@ -41,15 +33,15 @@ public class UpdateActivityCommandHandler : IRequestHandler<UpdateTaskCommand, b
if (request.Routines.Count == 0) if (request.Routines.Count == 0)
throw new AppException("لطفا روتین های وظیفه را انتخاب نمایید"); throw new AppException("لطفا روتین های وظیفه را انتخاب نمایید");
var routines = await _repositoryWrapper.SetRepository<TaskRoutine>() var routines = await repositoryWrapper.SetRepository<TaskRoutine>()
.TableNoTracking .TableNoTracking
.Where(tr => tr.TaskId == newTask.Id) .Where(tr => tr.TaskId == newTask.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var taskRoutine in routines.Where(taskR => !request.Routines.Exists(r=>r== taskR.RoutineId))) foreach (var taskRoutine in routines.Where(taskR => !request.Routines.Exists(r=>r== taskR.RoutineId)))
{ {
_repositoryWrapper.SetRepository<TaskRoutine>() repositoryWrapper.SetRepository<TaskRoutine>()
.Delete(taskRoutine); .Delete(taskRoutine);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
} }
foreach (var routine in request.Routines.Where(requestRoutine => !routines.Exists(r=>r.RoutineId==requestRoutine))) foreach (var routine in request.Routines.Where(requestRoutine => !routines.Exists(r=>r.RoutineId==requestRoutine)))
@ -59,15 +51,15 @@ public class UpdateActivityCommandHandler : IRequestHandler<UpdateTaskCommand, b
if (request.Shifts.Count == 0) if (request.Shifts.Count == 0)
throw new AppException("اگر فعالیت برای یک گروه نقش انتخاب شده باشد باید لیست نقش ها را ارسال نمایید"); throw new AppException("اگر فعالیت برای یک گروه نقش انتخاب شده باشد باید لیست نقش ها را ارسال نمایید");
var shifts = await _repositoryWrapper.SetRepository<TaskShift>() var shifts = await repositoryWrapper.SetRepository<TaskShift>()
.TableNoTracking .TableNoTracking
.Where(tr => tr.TaskId == newTask.Id) .Where(tr => tr.TaskId == newTask.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var taskShift in shifts.Where(taskS => !request.Shifts.Exists(r => r == taskS.ShiftId))) foreach (var taskShift in shifts.Where(taskS => !request.Shifts.Exists(r => r == taskS.ShiftId)))
{ {
_repositoryWrapper.SetRepository<TaskShift>() repositoryWrapper.SetRepository<TaskShift>()
.Delete(taskShift); .Delete(taskShift);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
} }
foreach (var shift in request.Shifts.Where(requestShift => !shifts.Exists(r => r.ShiftId == requestShift))) foreach (var shift in request.Shifts.Where(requestShift => !shifts.Exists(r => r.ShiftId == requestShift)))
@ -77,15 +69,15 @@ public class UpdateActivityCommandHandler : IRequestHandler<UpdateTaskCommand, b
if (request.Positions.Count == 0) if (request.Positions.Count == 0)
throw new AppException("اگر فعالیت برای یک گروه نقش انتخاب شده باشد باید لیست نقش ها را ارسال نمایید"); throw new AppException("اگر فعالیت برای یک گروه نقش انتخاب شده باشد باید لیست نقش ها را ارسال نمایید");
var positions = await _repositoryWrapper.SetRepository<TaskPosition>() var positions = await repositoryWrapper.SetRepository<TaskPosition>()
.TableNoTracking .TableNoTracking
.Where(tr => tr.TaskId == newTask.Id) .Where(tr => tr.TaskId == newTask.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var taskPosition in positions.Where(taskP => !request.Positions.Exists(r => r == taskP.PositionId))) foreach (var taskPosition in positions.Where(taskP => !request.Positions.Exists(r => r == taskP.PositionId)))
{ {
_repositoryWrapper.SetRepository<TaskPosition>() repositoryWrapper.SetRepository<TaskPosition>()
.Delete(taskPosition); .Delete(taskPosition);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
} }
foreach (var position in request.Positions.Where(requestP => !positions.Exists(r => r.PositionId == requestP))) foreach (var position in request.Positions.Where(requestP => !positions.Exists(r => r.PositionId == requestP)))
@ -96,15 +88,15 @@ public class UpdateActivityCommandHandler : IRequestHandler<UpdateTaskCommand, b
if (task.ScheduleType == TaskScheduleType.Weekly && request.Days.Count == 0) if (task.ScheduleType == TaskScheduleType.Weekly && request.Days.Count == 0)
throw new AppException("اگر تکرار فعالیت به صورت هفتگی باشد باید روزهای ان هفته را انتخاب کنید"); throw new AppException("اگر تکرار فعالیت به صورت هفتگی باشد باید روزهای ان هفته را انتخاب کنید");
request.Days.ForEach(d => task.SetDay(d)); request.Days.ForEach(d => task.SetDay(d));
var days = await _repositoryWrapper.SetRepository<TaskDay>() var days = await repositoryWrapper.SetRepository<TaskDay>()
.TableNoTracking .TableNoTracking
.Where(tr => tr.TaskId == newTask.Id) .Where(tr => tr.TaskId == newTask.Id)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var taskDay in days.Where(taskD => !request.Days.Exists(r => r == taskD.DayOfWeek))) foreach (var taskDay in days.Where(taskD => !request.Days.Exists(r => r == taskD.DayOfWeek)))
{ {
_repositoryWrapper.SetRepository<TaskDay>() repositoryWrapper.SetRepository<TaskDay>()
.Delete(taskDay); .Delete(taskDay);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
} }
foreach (var day in request.Days.Where(requestP => !days.Exists(r => r.DayOfWeek == requestP))) foreach (var day in request.Days.Where(requestP => !days.Exists(r => r.DayOfWeek == requestP)))
@ -112,9 +104,9 @@ public class UpdateActivityCommandHandler : IRequestHandler<UpdateTaskCommand, b
newTask.SetDay(day); newTask.SetDay(day);
} }
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>() repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>()
.Update(newTask); .Update(newTask);
await _repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true; return true;
} }

View File

@ -1,15 +1,9 @@
namespace Brizco.Repository.Models; namespace Brizco.Repository.Models;
public class ApplicationContext : IdentityDbContext<ApplicationUser,ApplicationRole,Guid> public class ApplicationContext(DbContextOptions<ApplicationContext> options, ILogger<ApplicationContext> logger)
: IdentityDbContext<ApplicationUser, ApplicationRole, Guid>(options)
{ {
private readonly ILogger<ApplicationContext> _logger; private readonly Assembly _projectAssembly = options.GetExtension<DbContextOptionCustomExtensions>().ProjectAssembly;
private readonly Assembly _projectAssembly;
public ApplicationContext( DbContextOptions<ApplicationContext> options, ILogger<ApplicationContext> logger): base(options)
{
_logger = logger;
_projectAssembly = options.GetExtension<DbContextOptionCustomExtensions>().ProjectAssembly;
}
protected override void OnModelCreating(ModelBuilder builder) protected override void OnModelCreating(ModelBuilder builder)
@ -18,9 +12,9 @@ public class ApplicationContext : IdentityDbContext<ApplicationUser,ApplicationR
stopwatch.Start(); stopwatch.Start();
base.OnModelCreating(builder); base.OnModelCreating(builder);
var entitiesAssembly = _projectAssembly; var entitiesAssembly = _projectAssembly;
builder.RegisterAllEntities<ApiEntity>(_logger, entitiesAssembly); builder.RegisterAllEntities<ApiEntity>(logger, entitiesAssembly);
stopwatch.Stop(); stopwatch.Stop();
_logger.LogInformation($"!!!!!!! RegisterAllEntities : {stopwatch.ElapsedMilliseconds}ms !!!!!!!"); logger.LogInformation($"!!!!!!! RegisterAllEntities : {stopwatch.ElapsedMilliseconds}ms !!!!!!!");
RenameIdentityTables(builder); RenameIdentityTables(builder);

View File

@ -1,14 +1,9 @@
namespace Brizco.Repository.Repositories.Base namespace Brizco.Repository.Repositories.Base
{ {
public class BaseRepository<T> : Repository<T>, IBaseRepository<T> where T : class, IApiEntity public class BaseRepository<T>(ApplicationContext dbContext, ICurrentUserService currentUserService)
: Repository<T>(dbContext), IBaseRepository<T>
where T : class, IApiEntity
{ {
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)
{ {
return await Entities.FindAsync(ids, cancellationToken); return await Entities.FindAsync(ids, cancellationToken);
@ -62,9 +57,9 @@
.CurrentValue = DateTime.Now; .CurrentValue = DateTime.Now;
Entities.Entry(entity).Property(e => e.IsRemoved) Entities.Entry(entity).Property(e => e.IsRemoved)
.CurrentValue = true; .CurrentValue = true;
if (_currentUserService.UserName != null) if (currentUserService.UserName != null)
Entities.Entry(entity).Property(e => e.RemovedBy) Entities.Entry(entity).Property(e => e.RemovedBy)
.CurrentValue = _currentUserService.UserName; .CurrentValue = currentUserService.UserName;
Entities.Update(entity); Entities.Update(entity);
} }
@ -78,9 +73,9 @@
.CurrentValue = DateTime.Now; .CurrentValue = DateTime.Now;
Entities.Entry(entity).Property(e => e.IsRemoved) Entities.Entry(entity).Property(e => e.IsRemoved)
.CurrentValue = true; .CurrentValue = true;
if (_currentUserService.UserName != null) if (currentUserService.UserName != null)
Entities.Entry(entity).Property(e => e.RemovedBy) Entities.Entry(entity).Property(e => e.RemovedBy)
.CurrentValue = _currentUserService.UserName; .CurrentValue = currentUserService.UserName;
Entities.Update(entity); Entities.Update(entity);
} }
} }

View File

@ -1,12 +1,9 @@
namespace Brizco.Repository.Repositories.Base namespace Brizco.Repository.Repositories.Base
{ {
public class ReadRepository<T> : Repository<T>, IDisposable, IReadRepository<T> where T : class, IApiEntity public class ReadRepository<T>(ApplicationContext dbContext)
: Repository<T>(dbContext), IDisposable, IReadRepository<T>
where T : class, IApiEntity
{ {
public ReadRepository(
ApplicationContext dbContext) : base(dbContext)
{
}
public void Dispose() public void Dispose()
{ {
DbContext?.Dispose(); DbContext?.Dispose();

View File

@ -1,18 +1,12 @@
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(ApplicationContext context, ICurrentUserService currentUserService)
: IRepositoryWrapper
{ {
private readonly ApplicationContext _context;
private readonly ICurrentUserService _currentUserService;
private IDbContextTransaction? _currentTransaction; private IDbContextTransaction? _currentTransaction;
public RepositoryWrapper(ApplicationContext context, ICurrentUserService currentUserService)
{
_context = context;
_currentUserService = currentUserService;
}
public IBaseRepository<T> SetRepository<T>() where T : ApiEntity => new BaseRepository<T>(_context, _currentUserService); 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)
@ -29,17 +23,17 @@ public class RepositoryWrapper : IRepositoryWrapper
} }
public async Task BeginTransaction(CancellationToken cancellationToken) public async Task BeginTransaction(CancellationToken cancellationToken)
{ {
_currentTransaction = await _context.Database.BeginTransactionAsync(cancellationToken); _currentTransaction = await context.Database.BeginTransactionAsync(cancellationToken);
} }
public async Task SaveChangesAsync(CancellationToken cancellationToken = default) public async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{ {
SetAuditables(); SetAuditables();
await _context.SaveChangesAsync(cancellationToken); await context.SaveChangesAsync(cancellationToken);
} }
private void SetAuditables() private void SetAuditables()
{ {
IEnumerable<EntityEntry<IApiEntity>> entries = _context.ChangeTracker.Entries<IApiEntity>(); IEnumerable<EntityEntry<IApiEntity>> entries = context.ChangeTracker.Entries<IApiEntity>();
foreach (EntityEntry<IApiEntity> entity in entries) foreach (EntityEntry<IApiEntity> entity in entries)
{ {
if (entity.State == EntityState.Added) if (entity.State == EntityState.Added)
@ -52,15 +46,15 @@ public class RepositoryWrapper : IRepositoryWrapper
{ {
entity.Property(e => e.ModifiedAt) entity.Property(e => e.ModifiedAt)
.CurrentValue = DateTime.Now; .CurrentValue = DateTime.Now;
if (_currentUserService.UserName != null) if (currentUserService.UserName != null)
entity.Property(e => e.ModifiedBy) entity.Property(e => e.ModifiedBy)
.CurrentValue = _currentUserService.UserName; .CurrentValue = currentUserService.UserName;
} }
} }
} }
public void Dispose() public void Dispose()
{ {
_currentTransaction?.Dispose(); _currentTransaction?.Dispose();
_context?.Dispose(); context?.Dispose();
} }
} }

View File

@ -1,15 +1,10 @@
 
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>(ApplicationContext dbContext, ICurrentUserService currentUserService)
: Repository<T>(dbContext), IDisposable, IWriteRepository<T>
where T : class, IApiEntity
{ {
private readonly ICurrentUserService _currentUserService;
public WriteRepository(ApplicationContext dbContext,ICurrentUserService currentUserService) : base(dbContext)
{
_currentUserService = currentUserService;
}
public void Dispose() public void Dispose()
{ {
DbContext?.Dispose(); DbContext?.Dispose();
@ -54,9 +49,9 @@ namespace Brizco.Repository.Repositories.Base
.CurrentValue = DateTime.Now; .CurrentValue = DateTime.Now;
Entities.Entry(entity).Property(e => e.IsRemoved) Entities.Entry(entity).Property(e => e.IsRemoved)
.CurrentValue = true; .CurrentValue = true;
if (_currentUserService.UserName != null) if (currentUserService.UserName != null)
Entities.Entry(entity).Property(e => e.RemovedBy) Entities.Entry(entity).Property(e => e.RemovedBy)
.CurrentValue = _currentUserService.UserName; .CurrentValue = currentUserService.UserName;
Entities.Update(entity); Entities.Update(entity);
} }
@ -70,9 +65,9 @@ namespace Brizco.Repository.Repositories.Base
.CurrentValue = DateTime.Now; .CurrentValue = DateTime.Now;
Entities.Entry(entity).Property(e => e.IsRemoved) Entities.Entry(entity).Property(e => e.IsRemoved)
.CurrentValue = true; .CurrentValue = true;
if (_currentUserService.UserName != null) if (currentUserService.UserName != null)
Entities.Entry(entity).Property(e => e.RemovedBy) Entities.Entry(entity).Property(e => e.RemovedBy)
.CurrentValue = _currentUserService.UserName; .CurrentValue = currentUserService.UserName;
Entities.Update(entity); Entities.Update(entity);
} }
} }

View File

@ -3,14 +3,9 @@ using Task = System.Threading.Tasks.Task;
namespace Brizco.Repository.Repositories.UnitOfWork; namespace Brizco.Repository.Repositories.UnitOfWork;
public class UnitOfWork : IUnitOfWork public class UnitOfWork(ApplicationContext applicationContext) : IUnitOfWork
{ {
private readonly ApplicationContext _applicationContext;
private IDbContextTransaction? _currentTransaction ; private IDbContextTransaction? _currentTransaction ;
public UnitOfWork(ApplicationContext applicationContext)
{
_applicationContext = applicationContext;
}
public async Task RollBackAsync() public async Task RollBackAsync()
{ {
@ -26,17 +21,17 @@ public class UnitOfWork : IUnitOfWork
} }
public async Task BeginTransaction() public async Task BeginTransaction()
{ {
_currentTransaction = await _applicationContext.Database.BeginTransactionAsync(); _currentTransaction = await applicationContext.Database.BeginTransactionAsync();
} }
public async Task SaveChangesAsync(CancellationToken cancellationToken = default) public async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{ {
SetAuditables(); SetAuditables();
await _applicationContext.SaveChangesAsync(cancellationToken); await applicationContext.SaveChangesAsync(cancellationToken);
} }
private void SetAuditables() private void SetAuditables()
{ {
IEnumerable<EntityEntry<IApiEntity>> entries = _applicationContext.ChangeTracker.Entries<IApiEntity>(); IEnumerable<EntityEntry<IApiEntity>> entries = applicationContext.ChangeTracker.Entries<IApiEntity>();
foreach (EntityEntry<IApiEntity> entity in entries) foreach (EntityEntry<IApiEntity> entity in entries)
{ {
if (entity.State == EntityState.Added) if (entity.State == EntityState.Added)

View File

@ -2,38 +2,24 @@
namespace Brizco.Repository.Services; namespace Brizco.Repository.Services;
public class DbInitializerService : IDbInitializerService public class DbInitializerService(
ApplicationContext context,
RoleManager<ApplicationRole> roleManager,
UserManager<ApplicationUser> userManager,
IOptionsSnapshot<SiteSettings> adminUserSeedOptions,
ILogger<DbInitializerService> logger)
: IDbInitializerService
{ {
private readonly IOptionsSnapshot<SiteSettings> _adminUserSeedOptions;
private readonly ApplicationContext _context;
private readonly ILogger<DbInitializerService> _logger;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly UserManager<ApplicationUser> _userManager;
public DbInitializerService(
ApplicationContext context,
RoleManager<ApplicationRole> roleManager,
UserManager<ApplicationUser> userManager,
IOptionsSnapshot<SiteSettings> adminUserSeedOptions,
ILogger<DbInitializerService> logger)
{
_context = context;
_roleManager = roleManager;
_userManager = userManager;
_adminUserSeedOptions = adminUserSeedOptions;
_logger = logger;
}
public void Initialize() public void Initialize()
{ {
try try
{ {
_context.Database.Migrate(); context.Database.Migrate();
_logger.LogInformation("Migration SUCCESS !!!!"); logger.LogInformation("Migration SUCCESS !!!!");
} }
catch (Exception e) catch (Exception e)
{ {
_logger.LogError(e, e.Message); logger.LogError(e, e.Message);
} }
} }
@ -43,8 +29,8 @@ public class DbInitializerService : IDbInitializerService
{ {
await SeedRoles(); await SeedRoles();
var seedAdmin = _adminUserSeedOptions.Value.UserSetting; var seedAdmin = adminUserSeedOptions.Value.UserSetting;
var user = await _userManager.FindByNameAsync(seedAdmin.Username); var user = await userManager.FindByNameAsync(seedAdmin.Username);
if (user == null) if (user == null)
{ {
var adminUser = new ApplicationUser var adminUser = new ApplicationUser
@ -60,8 +46,8 @@ public class DbInitializerService : IDbInitializerService
PhoneNumber = seedAdmin.Phone, PhoneNumber = seedAdmin.Phone,
BirthDate = DateTime.Now.AddYears(-23) BirthDate = DateTime.Now.AddYears(-23)
}; };
var adminUserResult = await _userManager.CreateAsync(adminUser, seedAdmin.Password); var adminUserResult = await userManager.CreateAsync(adminUser, seedAdmin.Password);
if (adminUserResult.Succeeded) await _userManager.AddToRoleAsync(adminUser, seedAdmin.RoleName); if (adminUserResult.Succeeded) await userManager.AddToRoleAsync(adminUser, seedAdmin.RoleName);
} }
} }
catch (Exception e) catch (Exception e)
@ -73,8 +59,8 @@ public class DbInitializerService : IDbInitializerService
public async Task SeedRoles() public async Task SeedRoles()
{ {
var seedAdmin = _adminUserSeedOptions.Value.UserSetting; var seedAdmin = adminUserSeedOptions.Value.UserSetting;
var managerRole = await _roleManager.FindByNameAsync(seedAdmin.RoleName); var managerRole = await roleManager.FindByNameAsync(seedAdmin.RoleName);
if (managerRole == null) if (managerRole == null)
{ {
@ -84,9 +70,9 @@ public class DbInitializerService : IDbInitializerService
EnglishName = seedAdmin.RoleName, EnglishName = seedAdmin.RoleName,
Description = "root admin role" Description = "root admin role"
}; };
var adminRoleResult = await _roleManager.CreateAsync(managerRole); var adminRoleResult = await roleManager.CreateAsync(managerRole);
foreach (var claim in ApplicationClaims.AllClaims) foreach (var claim in ApplicationClaims.AllClaims)
await _roleManager.AddClaimAsync(managerRole, claim); await roleManager.AddClaimAsync(managerRole, claim);
} }
} }