diff --git a/Brizco.Api/AppSettings/appsettings.Development.json b/Brizco.Api/AppSettings/appsettings.Development.json index 6b8b9ac..bbc6118 100644 --- a/Brizco.Api/AppSettings/appsettings.Development.json +++ b/Brizco.Api/AppSettings/appsettings.Development.json @@ -1,7 +1,7 @@ { "ConnectionStrings": { - "PostgresServer": "Host=185.220.227.126;port=5432;Username=postgres;Password=ub0J7sFFThkSBmkc0TzSKsCfheRnQpyu;Database=BrizcoDB", - "MartenDBServer": "Host=185.228.236.40;port=5432;Username=postgres;Password=ub0J7sFFThkSBmkc0TzSKsCfheRnQpyu;Database=BrizcoMartenDB", + "PostgresServer": "Host=185.228.236.6;port=5432;Username=postgres;Password=ub0J7sFFThkSBmkc0TzSKsCfheRnQpyu;Database=BrizcoDB", + "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", "MartenDB": "Host=pg-0;Username=postgres;Password=xHTpBf4wC+bBeNg2pL6Ga7VEWKFJx7VPEUpqxwPFfOc2YYTVwFQuHfsiqoVeT9+6;Database=BrizcoMartenDB;" }, diff --git a/Brizco.Api/Services/CurrentUserService.cs b/Brizco.Api/Services/CurrentUserService.cs index 945409d..872cd21 100644 --- a/Brizco.Api/Services/CurrentUserService.cs +++ b/Brizco.Api/Services/CurrentUserService.cs @@ -2,20 +2,13 @@ namespace Brizco.Api.Services; -public class CurrentUserService : ICurrentUserService +public class CurrentUserService(IHttpContextAccessor httpContextAccessor) : ICurrentUserService { - private readonly IHttpContextAccessor _httpContextAccessor; - - public CurrentUserService(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - - 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? 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? Permissions => httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c=>c.Value)?.ToList(); } \ No newline at end of file diff --git a/Brizco.Api/WebFramework/Bases/CrudController.cs b/Brizco.Api/WebFramework/Bases/CrudController.cs index 032e168..d70825f 100644 --- a/Brizco.Api/WebFramework/Bases/CrudController.cs +++ b/Brizco.Api/WebFramework/Bases/CrudController.cs @@ -5,18 +5,13 @@ using Microsoft.AspNetCore.Routing.Patterns; namespace Brizco.Api.WebFramework.Bases; -public class CrudEndpoint where TEntity : ApiEntity, new() +public class CrudEndpoint( + string endpointName) + where TEntity : ApiEntity, new() { - private readonly string _endpointName; - - public CrudEndpoint(string endpointName) - { - _endpointName = endpointName; - } - 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) .WithDisplayName("GetAll") @@ -82,16 +77,11 @@ public class BaseController : ControllerBase } [Authorize(AuthenticationSchemes = "Bearer")] -public class CrudController : BaseController +public class CrudController(IRepositoryWrapper repositoryWrapper) : BaseController where TDto : BaseDto, new() where TEntity : ApiEntity, new() { - protected readonly IRepositoryWrapper _repositoryWrapper; - - public CrudController(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } + protected readonly IRepositoryWrapper _repositoryWrapper = repositoryWrapper; // GET:Get All Entity [HttpGet] @@ -167,15 +157,10 @@ public class CrudController : BaseController } [Authorize(AuthenticationSchemes = "Bearer")] -public class CrudController : BaseController +public class CrudController(IRepositoryWrapper repositoryWrapper) : BaseController where TEntity : ApiEntity, new() { - protected readonly IRepositoryWrapper _repositoryWrapper; - - public CrudController(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } + protected readonly IRepositoryWrapper _repositoryWrapper = repositoryWrapper; // GET:Get All Entity [HttpGet] diff --git a/Brizco.Api/WebFramework/Configurations/ServiceExtensions.cs b/Brizco.Api/WebFramework/Configurations/ServiceExtensions.cs index 399ad22..72c9339 100644 --- a/Brizco.Api/WebFramework/Configurations/ServiceExtensions.cs +++ b/Brizco.Api/WebFramework/Configurations/ServiceExtensions.cs @@ -80,7 +80,7 @@ public static class ServiceExtensions serviceCollection.AddDbContextFactory(options => { 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); //options.EnableServiceProviderCaching(true); }).BuildServiceProvider(); @@ -117,7 +117,7 @@ public static class ServiceExtensions { var marten = serviceCollection.AddMarten(options => { - options.Connection(configuration.GetConnectionString("MartenDB")!); + options.Connection(configuration.GetConnectionString("MartenDBServer")!); if (environment.IsDevelopment()) options.AutoCreateSchemaObjects = AutoCreate.All; }); diff --git a/Brizco.Api/WebFramework/MiddleWares/ExceptionHandlerMiddleware.cs b/Brizco.Api/WebFramework/MiddleWares/ExceptionHandlerMiddleware.cs index 9e8cf24..ed47480 100644 --- a/Brizco.Api/WebFramework/MiddleWares/ExceptionHandlerMiddleware.cs +++ b/Brizco.Api/WebFramework/MiddleWares/ExceptionHandlerMiddleware.cs @@ -12,22 +12,11 @@ public static class ExceptionHandlerMiddlewareExtensions } } -public class ExceptionHandlerMiddleware +public class ExceptionHandlerMiddleware( + RequestDelegate next, + IWebHostEnvironment env, + ILogger logger) { - private readonly IWebHostEnvironment _env; - private readonly ILogger _logger; - private readonly RequestDelegate _next; - - public ExceptionHandlerMiddleware( - RequestDelegate next, - IWebHostEnvironment env, - ILogger logger) - { - _next = next; - _env = env; - _logger = logger; - } - public async Task Invoke(HttpContext context) { string message = null; @@ -36,15 +25,15 @@ public class ExceptionHandlerMiddleware try { - await _next(context); + await next(context); } catch (BaseApiException exception) { - _logger.LogError(exception, exception.Message); + logger.LogError(exception, exception.Message); httpStatusCode = exception.HttpStatusCode; apiStatusCode = exception.ApiStatusCode; - if (_env.IsDevelopment()) + if (env.IsDevelopment()) { var dic = new Dictionary { @@ -82,22 +71,22 @@ public class ExceptionHandlerMiddleware } catch (SecurityTokenExpiredException exception) { - _logger.LogError(exception, exception.Message); + logger.LogError(exception, exception.Message); SetUnAuthorizeResponse(exception); await WriteToResponseAsync(); } catch (UnauthorizedAccessException exception) { - _logger.LogError(exception, exception.Message); + logger.LogError(exception, exception.Message); SetUnAuthorizeResponse(exception); await WriteToResponseAsync(); } catch (Exception exception) { - _logger.LogError(exception, exception.Message); + logger.LogError(exception, exception.Message); - if (_env.IsDevelopment()) + if (env.IsDevelopment()) { var dic = new Dictionary { @@ -170,7 +159,7 @@ public class ExceptionHandlerMiddleware httpStatusCode = HttpStatusCode.Unauthorized; apiStatusCode = ApiResultStatusCode.UnAuthorized; - if (_env.IsDevelopment()) + if (env.IsDevelopment()) { var dic = new Dictionary { diff --git a/Brizco.Api/WebFramework/MiddleWares/PerformanceMiddleware.cs b/Brizco.Api/WebFramework/MiddleWares/PerformanceMiddleware.cs index d201dc4..f8a0ad1 100644 --- a/Brizco.Api/WebFramework/MiddleWares/PerformanceMiddleware.cs +++ b/Brizco.Api/WebFramework/MiddleWares/PerformanceMiddleware.cs @@ -10,28 +10,19 @@ public static class PerformanceMiddlewareExtensions } } -public class PerformanceMiddleware +public class PerformanceMiddleware( + RequestDelegate next, + ILogger logger) { - private readonly ILogger _logger; - private readonly RequestDelegate _next; - private readonly Stopwatch _timer; - - public PerformanceMiddleware( - RequestDelegate next, - ILogger logger) - { - _next = next; - _logger = logger; - _timer = new Stopwatch(); - } + private readonly Stopwatch _timer = new(); public async System.Threading.Tasks.Task Invoke(HttpContext context) { _timer.Start(); - await _next(context); + await next(context); _timer.Stop(); var elapsedMilliseconds = _timer.ElapsedMilliseconds; - _logger.LogWarning($"REQUEST TIMER : {elapsedMilliseconds}"); + logger.LogWarning($"REQUEST TIMER : {elapsedMilliseconds}"); } } \ No newline at end of file diff --git a/Brizco.Api/WebFramework/Swagger/SwaggerConfiguration.cs b/Brizco.Api/WebFramework/Swagger/SwaggerConfiguration.cs index e7188a8..5b626f1 100644 --- a/Brizco.Api/WebFramework/Swagger/SwaggerConfiguration.cs +++ b/Brizco.Api/WebFramework/Swagger/SwaggerConfiguration.cs @@ -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; - - public UnauthorizedResponsesOperationFilter(bool includeUnauthorizedAndForbiddenResponses, - string schemeName = "Bearer") - { - this.includeUnauthorizedAndForbiddenResponses = includeUnauthorizedAndForbiddenResponses; - this.schemeName = schemeName; - } + private readonly string schemeName = schemeName; public void Apply(OpenApiOperation operation, OperationFilterContext context) { diff --git a/Brizco.Core/CoreServices/AccountService.cs b/Brizco.Core/CoreServices/AccountService.cs index e97abcc..7165787 100644 --- a/Brizco.Core/CoreServices/AccountService.cs +++ b/Brizco.Core/CoreServices/AccountService.cs @@ -6,56 +6,33 @@ using NPOI.SS.Formula.Functions; namespace Brizco.Core.CoreServices; -public class AccountService : IAccountService +public class AccountService( + UserManager userManager, + SignInManager userSignInManager, + IJwtService jwtService, + ICurrentUserService currentUserService, + IRepositoryWrapper repositoryWrapper, + ISmsService smsService, + IComplexService complexService, + IUserService userService) + : IAccountService { - - private readonly UserManager _userManager; - private readonly SignInManager _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 userManager, - SignInManager 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 ForgetPasswordAsync(string phoneNumber) { - var user = await _userManager.FindByNameAsync(phoneNumber); + var user = await userManager.FindByNameAsync(phoneNumber); if (user != null) { var rand = new Random(DateTime.Now.Millisecond); var newPass = rand.Next(1000000, 9000000).ToString(); if (!user.PhoneNumberConfirmed) throw new AppException("شماره تلفن شما تایید نشده است و قابلیت استفاده از فراموشی رمز عبور را ندارید"); - var rp = await _userManager.RemovePasswordAsync(user); + var rp = await userManager.RemovePasswordAsync(user); if (!rp.Succeeded) 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) 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; } @@ -64,7 +41,7 @@ public class AccountService : IAccountService public async Task CheckMemberShipAsync(string phoneNumber) { - var user = await _userManager.FindByNameAsync(phoneNumber); + var user = await userManager.FindByNameAsync(phoneNumber); if (user == null) return false; return true; @@ -72,17 +49,17 @@ public class AccountService : IAccountService public async Task CheckPositionPermission(string permission, CancellationToken cancellationToken=default) { - if (_currentUserService.UserId == null) + if (currentUserService.UserId == null) 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"); - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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"); - var query = from shiftPlan in _repositoryWrapper.SetRepository().Entities - join shift in _repositoryWrapper.SetRepository().Entities on shiftPlan.ShiftId equals shift.Id + var query = from shiftPlan in repositoryWrapper.SetRepository().Entities + join shift in repositoryWrapper.SetRepository().Entities on shiftPlan.ShiftId equals shift.Id where shiftPlan.PlanFor.Date == DateTime.Today.Date && shiftPlan.ComplexId == complexId && shift.EndAt >= DateTime.Now.TimeOfDay && shift.StartAt <= DateTime.Now.TimeOfDay select shiftPlan; @@ -92,10 +69,10 @@ public class AccountService : IAccountService throw new BaseApiException(ApiResultStatusCode.BadRequest, "No active shift plan"); var userCurrentPositionPermissions = - await (from positionPermission in _repositoryWrapper.SetRepository().Entities - join position in _repositoryWrapper.SetRepository().Entities on positionPermission.PositionId + await (from positionPermission in repositoryWrapper.SetRepository().Entities + join position in repositoryWrapper.SetRepository().Entities on positionPermission.PositionId equals position.Id - join shiftPlaneUser in _repositoryWrapper.SetRepository().Entities on position.Id equals + join shiftPlaneUser in repositoryWrapper.SetRepository().Entities on position.Id equals shiftPlaneUser.PositionId where shiftPlaneUser.ShiftPlanId == currentShiftPlan.Id && shiftPlaneUser.UserId == userId select positionPermission).ToListAsync(cancellationToken); @@ -108,23 +85,23 @@ public class AccountService : IAccountService var newPhoneNumber = StringExtensions.CheckPhoneNumber(phoneNumber); if (!PhoneNumberExtensions.CheckPhoneNumber(newPhoneNumber)) throw new AppException("شماره تلفن ارسالی اشتباه است"); - var user = await _userManager.FindByNameAsync(newPhoneNumber); + var user = await userManager.FindByNameAsync(newPhoneNumber); if (user == null) - user = await _userService.CreateUserAsync(phoneNumber); + user = await userService.CreateUserAsync(phoneNumber); - var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Phone"); - await _smsService.SendVerifyCodeAsync(newPhoneNumber, token); + var token = await userManager.GenerateTwoFactorTokenAsync(user, "Phone"); + await smsService.SendVerifyCodeAsync(newPhoneNumber, token); return new VerifyCodeResponseDto { SignUpStatus = SignUpStatus.StartSignOn }; } public async Task> 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) throw new AppException("رمز عبور یا نام کاربری اشتباه است"); - var admin = await _userManager.FindByNameAsync(userName); + var admin = await userManager.FindByNameAsync(userName); if (admin == null) throw new AppException("نام کاربری یا رمز عبور اشتباه است"); return await CompleteLogin(admin, cancellationToken); @@ -132,11 +109,11 @@ public class AccountService : IAccountService public async Task> LoginWithVerifyCodeAsync(string userName, string verifyCode, CancellationToken cancellationToken) { - var user = await _userManager.FindByNameAsync(userName); + var user = await userManager.FindByNameAsync(userName); if (user == null) throw new AppException("نام کاربری یا کد ارسالی اشتباه است", ApiResultStatusCode.NotFound); - var verfiyResult = await _userManager.VerifyTwoFactorTokenAsync(user, "Phone", verifyCode); + var verfiyResult = await userManager.VerifyTwoFactorTokenAsync(user, "Phone", verifyCode); if (verifyCode == "859585") verfiyResult = true; if (!verfiyResult) @@ -145,7 +122,7 @@ public class AccountService : IAccountService { user.PhoneNumberConfirmed = true; user.SignUpStatus = SignUpStatus.PhoneNumberVerified; - var result = await _userManager.UpdateAsync(user); + var result = await userManager.UpdateAsync(user); if (!result.Succeeded) throw new AppException(string.Join('|', result.Errors)); } @@ -154,9 +131,9 @@ public class AccountService : IAccountService public async Task> CompleteComplexSignUpAsync(SignUpRequestDto requestDto, CancellationToken cancellationToken) { - if (_currentUserService.UserId == null) + if (currentUserService.UserId == 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) throw new AppException("User not found", ApiResultStatusCode.NotFound); if (user.SignUpStatus == SignUpStatus.ComplexCreated) @@ -175,11 +152,11 @@ public class AccountService : IAccountService user.FirstName = requestDto.FirstName; user.LastName = requestDto.LastName; user.SignUpStatus = SignUpStatus.ComplexCreated; - var result = await _userManager.UpdateAsync(user); + var result = await userManager.UpdateAsync(user); if (!result.Succeeded) 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.SupportPhoneNumber, user.Id, @@ -193,21 +170,21 @@ public class AccountService : IAccountService AccessToken jwt; 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); if (complexUserRole == null) { complexUserRole = userComplexRoles.FirstOrDefault(); user.SelectedComplexUserRoleId = complexUserRole!.Id; - await _userManager.UpdateAsync(user); + await userManager.UpdateAsync(user); } - var complexUser = await _repositoryWrapper.SetRepository() + var complexUser = await repositoryWrapper.SetRepository() .TableNoTracking .Where(c => c.Id == complexUserRole!.ComplexUserId) .Select(ComplexUserMapper.ProjectToSDto) .FirstOrDefaultAsync( cancellationToken); - jwt = await _jwtService.Generate(user, complexUser!.ComplexId, complexUserRole!.RoleId); + jwt = await jwtService.Generate(user, complexUser!.ComplexId, complexUserRole!.RoleId); jwt.User.SelectedComplexName = complexUser.ComplexName; jwt.User.SelectedRoleName = complexUserRole.RoleName; jwt.User.SelectedRoleId = complexUserRole!.Id; @@ -215,16 +192,16 @@ public class AccountService : IAccountService } else { - var complexUser = await _repositoryWrapper.SetRepository() + var complexUser = await repositoryWrapper.SetRepository() .TableNoTracking .Where(mcu => mcu.UserId == user.Id) .OrderByDescending(o => o.CreatedAt) .Select(ComplexUserMapper.ProjectToSDto) .FirstOrDefaultAsync(cancellationToken); if (complexUser == null) - return (await _jwtService.Generate(user)).Adapt>(); + return (await jwtService.Generate(user)).Adapt>(); - var complexUserRole = await _repositoryWrapper.SetRepository() + var complexUserRole = await repositoryWrapper.SetRepository() .TableNoTracking .Where(c => c.ComplexUserId == complexUser.Id) .OrderByDescending(o => o.CreatedAt) @@ -237,8 +214,8 @@ public class AccountService : IAccountService { user.SelectedComplexUserRoleId = complexUserRole.Id; - await _userManager.UpdateAsync(user); - jwt = (await _jwtService.Generate(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt>(); + await userManager.UpdateAsync(user); + jwt = (await jwtService.Generate(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt>(); jwt.User.SelectedComplexName = complexUser.ComplexName; jwt.User.SelectedRoleName = complexUserRole.RoleName; jwt.User.SelectedRoleId = complexUserRole!.Id; diff --git a/Brizco.Core/CoreServices/JwtService.cs b/Brizco.Core/CoreServices/JwtService.cs index bdaee5a..c3b0e5d 100644 --- a/Brizco.Core/CoreServices/JwtService.cs +++ b/Brizco.Core/CoreServices/JwtService.cs @@ -5,21 +5,14 @@ using Brizco.Domain.Entities.Users; namespace Brizco.Core.CoreServices; -public class JwtService : IJwtService +public class JwtService( + IOptionsSnapshot siteSettings, + SignInManager userSignInManager, + RoleManager roleManager) + : IJwtService { - private readonly SignInManager _signInManager; - private readonly RoleManager _roleManager; - private readonly SiteSettings _siteSettings; + private readonly SiteSettings _siteSettings = siteSettings.Value; - public JwtService( - IOptionsSnapshot siteSettings, - SignInManager userSignInManager, - RoleManager roleManager) - { - _signInManager = userSignInManager; - _roleManager = roleManager; - _siteSettings = siteSettings.Value; - } public async Task> Generate(TUser user, Guid complexId, Guid roleId) where TUser : ApplicationUser { var tokenId = StringExtensions.GetId(8); @@ -150,7 +143,7 @@ public class JwtService : IJwtService private async Task> GetClaims(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(); claims.Add(new Claim("JwtID", jwtId)); claims.Add(new Claim(ClaimTypes.Name, baseUser.UserName)); @@ -166,8 +159,8 @@ public class JwtService : IJwtService private async Task> GetClaims(TUser baseUser, string jwtId, string roleId) where TUser : ApplicationUser { - var applicationRole = await _roleManager.FindByIdAsync(roleId); - var roleClaims = await _roleManager.GetClaimsAsync(applicationRole); + var applicationRole = await roleManager.FindByIdAsync(roleId); + var roleClaims = await roleManager.GetClaimsAsync(applicationRole); var claims = new List(); claims.Add(new Claim("SignUpStatus", ((int)baseUser.SignUpStatus).ToString())); claims.Add(new Claim(ClaimTypes.Name, baseUser.UserName)); diff --git a/Brizco.Core/CoreServices/PageService.cs b/Brizco.Core/CoreServices/PageService.cs index 9926ef5..ba0ed65 100644 --- a/Brizco.Core/CoreServices/PageService.cs +++ b/Brizco.Core/CoreServices/PageService.cs @@ -3,38 +3,29 @@ using Task = Brizco.Domain.Entities.Tasks.Task; namespace Brizco.Core.CoreServices; -public class PageService : IPageService +public class PageService( + ICurrentUserService currentUserService, + IRepositoryWrapper repositoryWrapper, + RoleManager roleManager, + IMediator mediator) + : IPageService { - private readonly ICurrentUserService _currentUserService; - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly RoleManager _roleManager; - private readonly IMediator _mediator; + private readonly RoleManager _roleManager = roleManager; - public PageService( - ICurrentUserService currentUserService, - IRepositoryWrapper repositoryWrapper, - RoleManager roleManager, - IMediator mediator) - { - _currentUserService = currentUserService; - _repositoryWrapper = repositoryWrapper; - _roleManager = roleManager; - _mediator = mediator; - } public async Task GetAppDashboardAsync(CancellationToken cancellationToken = default) { - if (_currentUserService.UserId == null) + if (currentUserService.UserId == 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"); - if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId)) + if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId)) throw new AppException("Complex id is wrong"); - var todayActivities = await _repositoryWrapper.SetRepository() + var todayActivities = await repositoryWrapper.SetRepository() .TableNoTracking .Where(a => a.ComplexId == complexId && a.SetFor.Date == DateTime.Today.Date) .ToListAsync(cancellationToken); - var todayShiftPlans = await _repositoryWrapper.SetRepository() + var todayShiftPlans = await repositoryWrapper.SetRepository() .TableNoTracking .Where(a => a.PlanFor.Date == DateTime.Today.Date && a.ComplexId == complexId) .Select(ShiftPlanMapper.ProjectToSDto) @@ -68,15 +59,15 @@ public class PageService : IPageService page.CurrentPosition = currentShift.Users.FirstOrDefault(f => f.UserId == userId)?.PositionName ?? string.Empty; } - if (_currentUserService.Permissions != null) + if (currentUserService.Permissions != null) { int totalStepCount = 0; int completeStepCount = 0; string currentStep = string.Empty; - if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageRoutines)) + if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageRoutines)) { totalStepCount++; - var hasRoutine = await _repositoryWrapper.SetRepository() + var hasRoutine = await repositoryWrapper.SetRepository() .TableNoTracking .AnyAsync(r => r.ComplexId == complexId, cancellationToken); if (hasRoutine) @@ -87,10 +78,10 @@ public class PageService : IPageService currentStep = "تکمیل بخش روتین ها"; } } - if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageSections)) + if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageSections)) { totalStepCount++; - var hasSection = await _repositoryWrapper.SetRepository
() + var hasSection = await repositoryWrapper.SetRepository
() .TableNoTracking .AnyAsync(r => r.ComplexId == complexId, cancellationToken); if (hasSection) @@ -101,10 +92,10 @@ public class PageService : IPageService currentStep = "تکمیل بخش سکشن ها"; } } - if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManagePositions)) + if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManagePositions)) { totalStepCount++; - var hasPosition = await _repositoryWrapper.SetRepository() + var hasPosition = await repositoryWrapper.SetRepository() .TableNoTracking .AnyAsync(r => r.ComplexId == complexId, cancellationToken); if (hasPosition) @@ -115,10 +106,10 @@ public class PageService : IPageService currentStep = "تکمیل بخش پوزیشن ها"; } } - if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageStaffs)) + if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageStaffs)) { totalStepCount++; - var hasStaff = await _repositoryWrapper.SetRepository() + var hasStaff = await repositoryWrapper.SetRepository() .TableNoTracking .AnyAsync(r => r.ComplexId == complexId, cancellationToken); if (hasStaff) @@ -129,10 +120,10 @@ public class PageService : IPageService currentStep = "تکمیل بخش کاربر ها"; } } - if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageShifts)) + if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageShifts)) { totalStepCount++; - var hasShift = await _repositoryWrapper.SetRepository() + var hasShift = await repositoryWrapper.SetRepository() .TableNoTracking .AnyAsync(r => r.ComplexId == complexId, cancellationToken); if (hasShift) @@ -143,10 +134,10 @@ public class PageService : IPageService currentStep = "تکمیل بخش شیفت ها"; } } - if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageTasks)) + if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageTasks)) { totalStepCount++; - var hasTask = await _repositoryWrapper.SetRepository() + var hasTask = await repositoryWrapper.SetRepository() .TableNoTracking .AnyAsync(r => r.ComplexId == complexId, cancellationToken); if (hasTask) @@ -157,10 +148,10 @@ public class PageService : IPageService currentStep = "تکمیل بخش تسک ها"; } } - if (_currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageShiftPlans)) + if (currentUserService.Permissions.Exists(s => s == ApplicationPermission.ManageShiftPlans)) { totalStepCount++; - var hasStaff = await _repositoryWrapper.SetRepository() + var hasStaff = await repositoryWrapper.SetRepository() .TableNoTracking .AnyAsync(r => r.ComplexId == complexId, cancellationToken); if (hasStaff) @@ -182,15 +173,15 @@ public class PageService : IPageService public async Task> GetShiftingPageAsync(Guid routineId,CancellationToken cancellationToken = default) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); var days = new List(); DateTime day = DateTime.Today; - var shifts = await _mediator.Send(new GetRoutineShiftsQuery(routineId, 0), + var shifts = await mediator.Send(new GetRoutineShiftsQuery(routineId, 0), cancellationToken); 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())); foreach (var shift in item.Shifts) { - var existedShiftPlan = await _repositoryWrapper.SetRepository() + var existedShiftPlan = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.ShiftId == shift.Id && s.PlanFor.Date == day.Date, cancellationToken); shift.CurrentShiftPlanId = existedShiftPlan?.Id ?? default; diff --git a/Brizco.Core/CoreServices/ReportServices/ShiftPlanReportCommandHandler.cs b/Brizco.Core/CoreServices/ReportServices/ShiftPlanReportCommandHandler.cs index 814ec21..4f01704 100644 --- a/Brizco.Core/CoreServices/ReportServices/ShiftPlanReportCommandHandler.cs +++ b/Brizco.Core/CoreServices/ReportServices/ShiftPlanReportCommandHandler.cs @@ -3,24 +3,19 @@ using Brizco.Domain.Entities.Tasks; using MD.PersianDateTime.Standard; namespace Brizco.Core.CoreServices.ReportServices; -public class ShiftPlanReportCommandHandler : IRequestHandler +public class ShiftPlanReportCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public ShiftPlanReportCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(ShiftPlanReportCommand request, CancellationToken cancellationToken) { - var shiftPlan = await _repositoryWrapper.SetRepository() + var shiftPlan = await repositoryWrapper.SetRepository() .TableNoTracking .Where(sp => sp.Id == request.ShiftPlanId) .Select(ShiftPlanMapper.ProjectToSDto) .FirstOrDefaultAsync(cancellationToken); if (shiftPlan == null) throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound); - var activities = await _repositoryWrapper.SetRepository() + var activities = await repositoryWrapper.SetRepository() .TableNoTracking .Where(sp => sp.ShiftPlanId == shiftPlan.ShiftId && sp.SetFor.Date == shiftPlan.PlanFor.Date) .Select(ActivityMapper.ProjectToSDto) diff --git a/Brizco.Core/CoreServices/ReportServices/TaskReportCommandHandler.cs b/Brizco.Core/CoreServices/ReportServices/TaskReportCommandHandler.cs index 0c97152..5147ab4 100644 --- a/Brizco.Core/CoreServices/ReportServices/TaskReportCommandHandler.cs +++ b/Brizco.Core/CoreServices/ReportServices/TaskReportCommandHandler.cs @@ -2,17 +2,11 @@ using Task = System.Threading.Tasks.Task; namespace Brizco.Core.CoreServices.ReportServices; -public class TaskReportCommandHandler : IRequestHandler +public class TaskReportCommandHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public TaskReportCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(TaskReportCommand request, CancellationToken cancellationToken) { - var tasks = await _repositoryWrapper.SetRepository() + var tasks = await repositoryWrapper.SetRepository() .TableNoTracking .Select(TaskMapper.ProjectToLDto) .ToListAsync(cancellationToken); @@ -50,7 +44,7 @@ public class TaskReportCommandHandler : IRequestHandler() + var position = await repositoryWrapper.SetRepository() .TableNoTracking .Where(t => t.TaskId == taskShiftSDto.TaskId) .Select(TaskPositionMapper.ProjectToSDto) @@ -123,7 +117,7 @@ public class TaskReportCommandHandler : IRequestHandler() + var position = await repositoryWrapper.SetRepository() .TableNoTracking .Where(t => t.TaskId == taskShiftSDto.TaskId) .Select(TaskPositionMapper.ProjectToSDto) diff --git a/Brizco.Core/EntityServices/ComplexService.cs b/Brizco.Core/EntityServices/ComplexService.cs index 4906fb8..2ab5932 100644 --- a/Brizco.Core/EntityServices/ComplexService.cs +++ b/Brizco.Core/EntityServices/ComplexService.cs @@ -2,16 +2,8 @@ namespace Brizco.Core.EntityServices; -public class ComplexService : IComplexService +public class ComplexService(ISender sender, RoleManager roleManager) : IComplexService { - private readonly ISender _sender; - private readonly RoleManager _roleManager; - - public ComplexService(ISender sender,RoleManager roleManager) - { - _sender = sender; - _roleManager = roleManager; - } public async Task CreateComplexAsync(string complexName, string complexAddress, string complexSuppPhone, @@ -19,7 +11,7 @@ public class ComplexService : IComplexService CancellationToken cancellationToken) { - var complex = await _sender.Send(new CreateComplexCommand(complexName, + var complex = await sender.Send(new CreateComplexCommand(complexName, complexAddress, complexSuppPhone)); @@ -31,12 +23,12 @@ public class ComplexService : IComplexService Description = "مدیریت مجموعه", Name = $"{ApplicationRoles.Manager}_{complex.Id.ToString()}" }; - var createRoleResult = await _roleManager.CreateAsync(managerRole); + var createRoleResult = await roleManager.CreateAsync(managerRole); if (!createRoleResult.Succeeded) throw new AppException(string.Join('|', createRoleResult.Errors)); 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 = "ناظر مجموعه", Name = $"{ApplicationRoles.ViewerOwner}_{complex.Id.ToString()}" }; - var createViewerResult = await _roleManager.CreateAsync(viewOwnerRole); + var createViewerResult = await roleManager.CreateAsync(viewOwnerRole); if (!createViewerResult.Succeeded) throw new AppException(string.Join('|', createViewerResult.Errors)); foreach (var claim in ApplicationClaims.ViewerOwnerClaims) - await _roleManager.AddClaimAsync(viewOwnerRole, claim); + await roleManager.AddClaimAsync(viewOwnerRole, claim); var superVisorRole = new ApplicationRole { @@ -63,12 +55,12 @@ public class ComplexService : IComplexService Description = "انجام فعالیت مدیریت کارکنان و وظیفه ها", Name = $"{ApplicationRoles.SuperVisor}_{complex.Id.ToString()}" }; - var superVisorRoleResult = await _roleManager.CreateAsync(superVisorRole); + var superVisorRoleResult = await roleManager.CreateAsync(superVisorRole); if (!superVisorRoleResult.Succeeded) throw new AppException(string.Join('|', superVisorRoleResult.Errors)); foreach (var claim in ApplicationClaims.SuperVisorClaims) - await _roleManager.AddClaimAsync(superVisorRole, claim); + await roleManager.AddClaimAsync(superVisorRole, claim); var staffRole = new ApplicationRole @@ -79,15 +71,15 @@ public class ComplexService : IComplexService Description = "انجام فعالیت ها و وظیفه ها", Name = $"{ApplicationRoles.Staff}_{complex.Id.ToString()}" }; - var staffRoleResult = await _roleManager.CreateAsync(staffRole); + var staffRoleResult = await roleManager.CreateAsync(staffRole); if (!staffRoleResult.Succeeded) throw new AppException(string.Join('|', staffRoleResult.Errors)); 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{ managerRole.Id }), cancellationToken); + var complexUser = await sender.Send(new CreateComplexUserCommand(complex.Id, managerUserId, new List{ managerRole.Id }), cancellationToken); return complex; } diff --git a/Brizco.Core/EntityServices/UserService.cs b/Brizco.Core/EntityServices/UserService.cs index afba39f..0e3eb0f 100644 --- a/Brizco.Core/EntityServices/UserService.cs +++ b/Brizco.Core/EntityServices/UserService.cs @@ -3,36 +3,20 @@ using Brizco.Domain.Entities.Users; namespace Brizco.Core.EntityServices; -public class UserService : IUserService +public class UserService( + ICurrentUserService currentUserService, + UserManager userManager, + RoleManager roleManager, + ISender sender, + IRepositoryWrapper repositoryWrapper, + IJwtService jwtService) + : IUserService { - private readonly ICurrentUserService _currentUserService; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - private readonly ISender _sender; - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly IJwtService _jwtService; - - public UserService(ICurrentUserService currentUserService, - UserManager userManager, - RoleManager roleManager, - ISender sender, - IRepositoryWrapper repositoryWrapper, - IJwtService jwtService) - { - _currentUserService = currentUserService; - _userManager = userManager; - _roleManager = roleManager; - _sender = sender; - _repositoryWrapper = repositoryWrapper; - _jwtService = jwtService; - } - - public async Task 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); - var user = await _userManager.FindByIdAsync(userId.ToString()); + var user = await userManager.FindByIdAsync(userId.ToString()); if (user == null) throw new AppException("User NotFound", ApiResultStatusCode.NotFound); if (user.SignUpStatus < SignUpStatus.ComplexCreated) @@ -51,10 +35,10 @@ public class UserService : IUserService userSDto.SelectedComplexName = complexUserRole!.ComplexName; userSDto.SelectedRoleName = complexUserRole!.RoleName; response.User.SelectedRoleId = complexUserRole!.Id; - var role = await _roleManager.FindByIdAsync(complexUserRole.RoleId.ToString()); + var role = await roleManager.FindByIdAsync(complexUserRole.RoleId.ToString()); 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(); } } @@ -64,14 +48,14 @@ public class UserService : IUserService if (complexUserRole != null) { user.SelectedComplexUserRoleId = complexUserRole.Id; - await _userManager.UpdateAsync(user); + await userManager.UpdateAsync(user); userSDto.SelectedComplexName = complexUserRole!.ComplexName; userSDto.SelectedRoleName = complexUserRole!.RoleName; response.User.SelectedRoleId = complexUserRole!.Id; - var role = await _roleManager.FindByIdAsync(complexUserRole.RoleId.ToString()); + var role = await roleManager.FindByIdAsync(complexUserRole.RoleId.ToString()); 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(); } } @@ -85,16 +69,16 @@ public class UserService : IUserService public async Task> 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); - if (!Guid.TryParse(_currentUserService.ComplexId, out var complexId)) + if (!Guid.TryParse(currentUserService.ComplexId, out var complexId)) throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized); AccessToken jwt; - var complexUser = await _repositoryWrapper.SetRepository() + var complexUser = await repositoryWrapper.SetRepository() .TableNoTracking .Where(mcu => mcu.UserId == userId && mcu.ComplexId == complexId) .Select(ComplexUserMapper.ProjectToSDto) @@ -102,7 +86,7 @@ public class UserService : IUserService if (complexUser == null) throw new AppException("User role is wrong", ApiResultStatusCode.BadRequest); - var complexUserRole = await _repositoryWrapper.SetRepository() + var complexUserRole = await repositoryWrapper.SetRepository() .TableNoTracking .Where(c => c.Id == roleId) .Select(ComplexUserRoleMapper.ProjectToSDto) @@ -111,13 +95,13 @@ public class UserService : IUserService if (complexUserRole == null) 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) throw new AppException("User not found", ApiResultStatusCode.NotFound); user.SelectedComplexUserRoleId = complexUserRole.Id; - await _userManager.UpdateAsync(user); - jwt = (await _jwtService.Generate(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt>(); + await userManager.UpdateAsync(user); + jwt = (await jwtService.Generate(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt>(); jwt.User.SelectedComplexName = complexUser.ComplexName; jwt.User.SelectedRoleName = complexUserRole.RoleName; jwt.User.SelectedRoleId = complexUserRole.Id; @@ -127,13 +111,13 @@ public class UserService : IUserService public async Task> 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); - var user = await _userManager.FindByIdAsync(userId.ToString()); + var user = await userManager.FindByIdAsync(userId.ToString()); if (user == null) throw new AppException("User NotFound", ApiResultStatusCode.NotFound); var response = new List(); - var complexUsers = await _repositoryWrapper.SetRepository() + var complexUsers = await repositoryWrapper.SetRepository() .TableNoTracking .Where(mcu => mcu.UserId == user.Id) .Select(ComplexUserMapper.ProjectToSDto) @@ -143,7 +127,7 @@ public class UserService : IUserService foreach (var complexUser in complexUsers) { - var complexUserRoles = await _repositoryWrapper.SetRepository() + var complexUserRoles = await repositoryWrapper.SetRepository() .TableNoTracking .Where(c => c.ComplexUserId == complexUser.Id) .Select(ComplexUserRoleMapper.ProjectToSDto) @@ -160,11 +144,11 @@ public class UserService : IUserService public async Task> GetUserRolesAsync(Guid userId, CancellationToken cancellationToken) { - var user = await _userManager.FindByIdAsync(userId.ToString()); + var user = await userManager.FindByIdAsync(userId.ToString()); if (user == null) throw new AppException("User NotFound", ApiResultStatusCode.NotFound); var response = new List(); - var complexUsers = await _repositoryWrapper.SetRepository() + var complexUsers = await repositoryWrapper.SetRepository() .TableNoTracking .Where(mcu => mcu.UserId == user.Id) .Select(ComplexUserMapper.ProjectToSDto) @@ -174,7 +158,7 @@ public class UserService : IUserService foreach (var complexUser in complexUsers) { - var complexUserRoles = await _repositoryWrapper.SetRepository() + var complexUserRoles = await repositoryWrapper.SetRepository() .TableNoTracking .Where(c => c.ComplexUserId == complexUser.Id) .Select(ComplexUserRoleMapper.ProjectToSDto) @@ -191,40 +175,40 @@ public class UserService : IUserService public async Task> GetUsersAsync(int page = 0, CancellationToken cancellationToken = default) { - if (_currentUserService.ComplexId.IsNullOrEmpty()) + if (currentUserService.ComplexId.IsNullOrEmpty()) 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"); - var complexUsers = await _sender.Send(new GetComplexUsersQuery(complexId.ToString(), page), cancellationToken); + var complexUsers = await sender.Send(new GetComplexUsersQuery(complexId.ToString(), page), cancellationToken); return complexUsers; } public async Task GetUserAsync(Guid userId) { - var user = await _userManager.FindByIdAsync(userId.ToString()); + var user = await userManager.FindByIdAsync(userId.ToString()); if (user == null) throw new AppException("User not found", ApiResultStatusCode.NotFound); 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) { - var role = await _roleManager.FindByNameAsync(roleName); + var role = await roleManager.FindByNameAsync(roleName); if (role != null) dto.RoleIds.Add(role.Id); } } else { - var complexUser = await _repositoryWrapper.SetRepository().TableNoTracking + var complexUser = await repositoryWrapper.SetRepository().TableNoTracking .FirstOrDefaultAsync(c => c.UserId == userId && c.ComplexId == complexId); if (complexUser == null) throw new AppException("ComplexUser not found", ApiResultStatusCode.NotFound); - var complexUserRoles = await _repositoryWrapper.SetRepository() + var complexUserRoles = await repositoryWrapper.SetRepository() .TableNoTracking .Where(cur => cur.ComplexUserId == complexUser.Id) .ToListAsync(); @@ -244,7 +228,7 @@ public class UserService : IUserService PhoneNumber = phoneNumber, SignUpStatus = SignUpStatus.StartSignOn }; - var result = await _userManager.CreateAsync(user); + var result = await userManager.CreateAsync(user); if (!result.Succeeded) throw new AppException(string.Join('|', result.Errors)); return user; @@ -252,12 +236,12 @@ public class UserService : IUserService public async Task CreateUserAsync(UserActionRequestDto request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId.IsNullOrEmpty()) + if (currentUserService.ComplexId.IsNullOrEmpty()) 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"); - var user = await _userManager.FindByNameAsync(request.PhoneNumber); + var user = await userManager.FindByNameAsync(request.PhoneNumber); if (user == null) { user = new ApplicationUser @@ -275,32 +259,32 @@ public class UserService : IUserService if (!request.Password.IsNullOrEmpty()) { - var result = await _userManager.CreateAsync(user, request.Password); + var result = await userManager.CreateAsync(user, request.Password); if (!result.Succeeded) throw new AppException(string.Join('|', result.Errors.Select(e => e.Description))); } else { - var result = await _userManager.CreateAsync(user); + var result = await userManager.CreateAsync(user); if (!result.Succeeded) 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; } public async Task EditUserAsync(UserActionRequestDto request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId.IsNullOrEmpty()) + if (currentUserService.ComplexId.IsNullOrEmpty()) 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"); if (request.UserId == Guid.Empty) 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) throw new AppException("User not found", ApiResultStatusCode.NotFound); user.LastName = request.LastName; @@ -313,29 +297,29 @@ public class UserService : IUserService user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp); user.Gender = request.Gender; - var result = await _userManager.UpdateAsync(user); + var result = await userManager.UpdateAsync(user); if (!result.Succeeded) throw new AppException(string.Join('|', result.Errors.Select(e => e.Description))); if (!request.Password.IsNullOrEmpty()) { - if (await _userManager.HasPasswordAsync(user)) - await _userManager.RemovePasswordAsync(user); + if (await userManager.HasPasswordAsync(user)) + await userManager.RemovePasswordAsync(user); - var addPassResult = await _userManager.AddPasswordAsync(user, request.Password); + var addPassResult = await userManager.AddPasswordAsync(user, request.Password); if (!addPassResult.Succeeded) 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; } public async Task EditUserProfileAsync(UserActionRequestDto request, CancellationToken cancellationToken) { - if (_currentUserService.UserId == null) + if (currentUserService.UserId == null) 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) throw new AppException("User not found", ApiResultStatusCode.NotFound); user.LastName = request.LastName; @@ -348,15 +332,15 @@ public class UserService : IUserService user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp); user.Gender = request.Gender; - var result = await _userManager.UpdateAsync(user); + var result = await userManager.UpdateAsync(user); if (!result.Succeeded) throw new AppException(string.Join('|', result.Errors.Select(e => e.Description))); if (!request.Password.IsNullOrEmpty()) { - if (await _userManager.HasPasswordAsync(user)) - await _userManager.RemovePasswordAsync(user); + if (await userManager.HasPasswordAsync(user)) + await userManager.RemovePasswordAsync(user); - var addPassResult = await _userManager.AddPasswordAsync(user, request.Password); + var addPassResult = await userManager.AddPasswordAsync(user, request.Password); if (!addPassResult.Succeeded) throw new AppException(string.Join('|', addPassResult.Errors.Select(e => e.Description))); } @@ -366,17 +350,17 @@ public class UserService : IUserService public async Task RemoveUserAsync(Guid userId, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId.IsNullOrEmpty()) + if (currentUserService.ComplexId.IsNullOrEmpty()) 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"); - var user = await _userManager.FindByIdAsync(userId.ToString()); + var user = await userManager.FindByIdAsync(userId.ToString()); if (user == null) throw new AppException("User not found", ApiResultStatusCode.NotFound); - var roles = await _userManager.GetRolesAsync(user); - await _userManager.RemoveFromRolesAsync(user, roles); - await _sender.Send(new DeleteComplexUserCommand(userId, complexId), cancellationToken); - var removeResult = await _userManager.DeleteAsync(user); + var roles = await userManager.GetRolesAsync(user); + await userManager.RemoveFromRolesAsync(user, roles); + await sender.Send(new DeleteComplexUserCommand(userId, complexId), cancellationToken); + var removeResult = await userManager.DeleteAsync(user); if (!removeResult.Succeeded) throw new AppException(string.Join('|', removeResult.Errors.Select(e => e.Description))); return true; @@ -384,14 +368,14 @@ public class UserService : IUserService public async Task RemoveUserFromComplexAsync(Guid userId, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId.IsNullOrEmpty()) + if (currentUserService.ComplexId.IsNullOrEmpty()) 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"); - var user = await _userManager.FindByIdAsync(userId.ToString()); + var user = await userManager.FindByIdAsync(userId.ToString()); if (user == null) 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; } @@ -399,12 +383,12 @@ public class UserService : IUserService public async Task> GetRolesAsync(int page = 0, CancellationToken cancellationToken = default) { - if (_currentUserService.ComplexId.IsNullOrEmpty()) + if (currentUserService.ComplexId.IsNullOrEmpty()) 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"); - var roles = await _roleManager.Roles + var roles = await roleManager.Roles .Where(r => r.ComplexId == complexId) .Skip(page * 15) .Take(15) @@ -414,13 +398,13 @@ public class UserService : IUserService public async Task GetRoleAsync(Guid roleId) { - var role = (await _roleManager.FindByIdAsync(roleId.ToString())); + var role = (await roleManager.FindByIdAsync(roleId.ToString())); if (role == null) throw new AppException("نقش پیدا نشد", ApiResultStatusCode.NotFound); var roleDto = role.Adapt(); roleDto.RoleId = roleId; - roleDto.Permissions = (await _roleManager.GetClaimsAsync(role)) + roleDto.Permissions = (await roleManager.GetClaimsAsync(role)) .Where(c => c.Type == CustomClaimType.Permission) .Select(c => c.Value) .ToList(); @@ -430,9 +414,9 @@ public class UserService : IUserService public async Task CreateRoleAsync(RoleActionRequestDto request) { - if (_currentUserService.ComplexId.IsNullOrEmpty()) + if (currentUserService.ComplexId.IsNullOrEmpty()) 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"); if (request.EnglishName.IsNullOrEmpty()) throw new AppException("لطفا نام انگلیسی را وارد کنید"); @@ -444,24 +428,24 @@ public class UserService : IUserService Description = request.Description, Name = $"{request.EnglishName}_{complexId.ToString()}" }; - var createRoleResult = await _roleManager.CreateAsync(applicationRole); + var createRoleResult = await roleManager.CreateAsync(applicationRole); if (!createRoleResult.Succeeded) throw new AppException(string.Join('|', createRoleResult.Errors)); 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; } public async Task EditRoleAsync(RoleActionRequestDto request) { - if (_currentUserService.ComplexId.IsNullOrEmpty()) + if (currentUserService.ComplexId.IsNullOrEmpty()) 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"); if (request.EnglishName.IsNullOrEmpty()) throw new AppException("لطفا نام انگلیسی را وارد کنید"); - var applicationRole = await _roleManager.FindByIdAsync(request.RoleId.ToString()); + var applicationRole = await roleManager.FindByIdAsync(request.RoleId.ToString()); if (applicationRole == null) throw new AppException("نقش پیدا نشد"); @@ -471,10 +455,10 @@ public class UserService : IUserService applicationRole.Description = request.Description; applicationRole.Name = $"{request.EnglishName}_{complexId.ToString()}"; - var createRoleResult = await _roleManager.UpdateAsync(applicationRole); + var createRoleResult = await roleManager.UpdateAsync(applicationRole); if (!createRoleResult.Succeeded) 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()) { if (request.Permissions.Contains(roleClaim.Value)) @@ -485,39 +469,39 @@ public class UserService : IUserService } 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) - await _roleManager.RemoveClaimAsync(applicationRole, claim); + await roleManager.RemoveClaimAsync(applicationRole, claim); return true; } public async Task RemoveRoleAsync(Guid roleId) { - var applicationRole = await _roleManager.FindByIdAsync(roleId.ToString()); + var applicationRole = await roleManager.FindByIdAsync(roleId.ToString()); if (applicationRole == null) 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) - await _roleManager.RemoveClaimAsync(applicationRole, claim); - var users = await _userManager.GetUsersInRoleAsync(applicationRole.Name); + await roleManager.RemoveClaimAsync(applicationRole, claim); + var users = await userManager.GetUsersInRoleAsync(applicationRole.Name); foreach (var user in users) - await _userManager.RemoveFromRoleAsync(user, applicationRole.Name); + await userManager.RemoveFromRoleAsync(user, applicationRole.Name); - var complexRoles = await _repositoryWrapper.SetRepository() + var complexRoles = await repositoryWrapper.SetRepository() .TableNoTracking .Where(r => r.RoleId == applicationRole.Id) .ToListAsync(); foreach (var complexRole in complexRoles) { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .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) throw new AppException(string.Join('|', removeResult.Errors.Select(e => e.Description))); return true; diff --git a/Brizco.Core/MartenServices/BrewService.cs b/Brizco.Core/MartenServices/BrewService.cs index 93d19fc..8939130 100644 --- a/Brizco.Core/MartenServices/BrewService.cs +++ b/Brizco.Core/MartenServices/BrewService.cs @@ -1,26 +1,19 @@ 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 GetLastBrewAsync(string recipeName, CancellationToken cancellationToken = default) { var type = Assembly.GetAssembly(typeof(DomainConfig))?.GetType($"Brizco.Domain.MartenEntities.Brews.{recipeName}"); if (type == null) 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"); - 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"); - var baseRecipe = await _martenRepositoryWrapper.SetRepository() + var baseRecipe = await martenRepositoryWrapper.SetRepository() .GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken); object? recipe; if (baseRecipe == null) @@ -39,12 +32,12 @@ public class BrewService : IBrewService var type = Assembly.GetAssembly(typeof(DomainConfig))?.GetType($"Brizco.Domain.MartenEntities.Brews.{recipeName}"); if (type == null) 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"); - 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"); - var baseRecipe = await _martenRepositoryWrapper.SetRepository() + var baseRecipe = await martenRepositoryWrapper.SetRepository() .GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken); object? recipe; if (baseRecipe == null) @@ -82,15 +75,15 @@ public class BrewService : IBrewService if (type == null) 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"); - 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"); - if (_currentUserService.FullName == null) + if (currentUserService.FullName == null) throw new BaseApiException(ApiResultStatusCode.BadRequest, "Full name is null"); - var baseRecipe = await _martenRepositoryWrapper.SetRepository() + var baseRecipe = await martenRepositoryWrapper.SetRepository() .GetEntityAsync(s => s.ComplexId == complexId && s.Name == recipeName, cancellationToken); if (baseRecipe == null) @@ -105,7 +98,7 @@ public class BrewService : IBrewService if (current is IBaseBrew brew) { brew.LogAt = DateTime.Now; - brew.LogBy = _currentUserService.FullName; + brew.LogBy = currentUserService.FullName; baseRecipe.CurrentBrewJson = JsonConvert.SerializeObject(current); } } @@ -115,13 +108,13 @@ public class BrewService : IBrewService if (current is IBaseBrew brew) { brew.LogAt = DateTime.Now; - brew.LogBy = _currentUserService.FullName; + brew.LogBy = currentUserService.FullName; baseRecipe.PastBrewsJson.Insert(0,baseRecipe.CurrentBrewJson); baseRecipe.CurrentBrewJson = JsonConvert.SerializeObject(current); } } - await _martenRepositoryWrapper.SetRepository() + await martenRepositoryWrapper.SetRepository() .AddOrUpdateEntityAsync(baseRecipe, cancellationToken); } } \ No newline at end of file diff --git a/Brizco.Core/Models/Api/ApiResult.cs b/Brizco.Core/Models/Api/ApiResult.cs index ff7babc..e249045 100644 --- a/Brizco.Core/Models/Api/ApiResult.cs +++ b/Brizco.Core/Models/Api/ApiResult.cs @@ -4,20 +4,13 @@ using Newtonsoft.Json; 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) - { - IsSuccess = isSuccess; - StatusCode = statusCode; - Message = message ?? statusCode.ToDisplay(); - } - - public bool IsSuccess { get; set; } - public ApiResultStatusCode StatusCode { get; set; } + public bool IsSuccess { get; set; } = isSuccess; + public ApiResultStatusCode StatusCode { get; set; } = statusCode; [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] - public string Message { get; set; } + public string Message { get; set; } = message ?? statusCode.ToDisplay(); #region Implicit Operators @@ -66,17 +59,12 @@ public class ApiResult #endregion } -public class ApiResult : ApiResult +public class ApiResult(bool isSuccess, ApiResultStatusCode statusCode, TData data, string message = null) + : ApiResult(isSuccess, statusCode, message) where TData : class { - public ApiResult(bool isSuccess, ApiResultStatusCode statusCode, TData data, string message = null) - : base(isSuccess, statusCode, message) - { - Data = data; - } - [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] - public TData Data { get; set; } + public TData Data { get; set; } = data; #region Implicit Operators diff --git a/Brizco.Core/QuartzServices/Handlers/SetShiftPlanNotificationScheduleCommandHandler.cs b/Brizco.Core/QuartzServices/Handlers/SetShiftPlanNotificationScheduleCommandHandler.cs index c38bfee..4b31dd3 100644 --- a/Brizco.Core/QuartzServices/Handlers/SetShiftPlanNotificationScheduleCommandHandler.cs +++ b/Brizco.Core/QuartzServices/Handlers/SetShiftPlanNotificationScheduleCommandHandler.cs @@ -1,11 +1,11 @@ -using Brizco.Core.QuartzServices.Commands; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; using Quartz; namespace Brizco.Core.QuartzServices.Handlers; -public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper repositoryWrapper,IScheduler scheduler,IMediator mediator,ILogger logger) - : IRequestHandler +public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper repositoryWrapper, IScheduler scheduler, IMediator mediator, + ILogger logger) + : IRequestHandler { public async Task Handle(SetShiftPlanNotificationScheduleCommand request, CancellationToken cancellationToken) { @@ -19,7 +19,7 @@ public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper r .TableNoTracking .FirstOrDefaultAsync(s => s.Id == shiftPlan.ShiftId, cancellationToken); - if(shift == null) + if (shift == null) throw new BaseApiException(ApiResultStatusCode.NotFound, "Shift not found in set schedule"); var shiftPlanUsers = await repositoryWrapper.SetRepository() @@ -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 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, shiftPlanStartAt.Minute, shiftPlanStartAt.Second, TimeSpan.Zero); 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 seTimeOffsetB = await scheduler.ScheduleJob(endOfShift, endOfShiftTrigger, 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; diff --git a/Brizco.Core/QuartzServices/JobScheduler.cs b/Brizco.Core/QuartzServices/JobScheduler.cs index 8254d3b..8cbfd51 100644 --- a/Brizco.Core/QuartzServices/JobScheduler.cs +++ b/Brizco.Core/QuartzServices/JobScheduler.cs @@ -3,22 +3,13 @@ using Quartz; namespace Brizco.Core.QuartzServices; -public class JobScheduler +public class JobScheduler(IScheduler scheduler, ILogger logger) { - private readonly IScheduler _scheduler; - private readonly ILogger _logger; - - public JobScheduler(IScheduler scheduler, ILogger logger) - { - _scheduler = scheduler; - _logger = logger; - } - public void Start() { - _scheduler.Start(); + scheduler.Start(); - _logger.LogInformation($"======== Scheduler Start ==========="); + logger.LogInformation($"======== Scheduler Start ==========="); } } \ No newline at end of file diff --git a/Brizco.Core/QuartzServices/ShiftPlanNotificationScheduledJob.cs b/Brizco.Core/QuartzServices/ShiftPlanNotificationScheduledJob.cs index 1b7e8a9..1f6af7b 100644 --- a/Brizco.Core/QuartzServices/ShiftPlanNotificationScheduledJob.cs +++ b/Brizco.Core/QuartzServices/ShiftPlanNotificationScheduledJob.cs @@ -5,32 +5,25 @@ using Task = System.Threading.Tasks.Task; namespace Brizco.Core.QuartzServices; -public class ShiftPlanNotificationScheduledJob : IJob +public class ShiftPlanNotificationScheduledJob( + ILogger logger, + IRepositoryWrapper repositoryWrapper, + IMediator mediator) + : IJob { - private readonly ILogger _logger; - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly IMediator _mediator; - - public ShiftPlanNotificationScheduledJob(ILogger logger,IRepositoryWrapper repositoryWrapper,IMediator mediator) - { - _logger = logger; - _repositoryWrapper = repositoryWrapper; - _mediator = mediator; - } - public async Task Execute(IJobExecutionContext context) { try { var notifyType = (ShiftPlanNotifyType)int.Parse(context.JobDetail.Key.Name); var shiftPlanId = Guid.Parse(context.JobDetail.Key.Group); - var shiftPlan = await _repositoryWrapper.SetRepository().TableNoTracking + var shiftPlan = await repositoryWrapper.SetRepository().TableNoTracking .Where(f => f.Id == shiftPlanId) .Select(ShiftPlanMapper.ProjectToSDto) .FirstOrDefaultAsync(); if (shiftPlan == null) throw new Exception("Shift plan not found"); - var shiftPlanUsers = await _repositoryWrapper.SetRepository() + var shiftPlanUsers = await repositoryWrapper.SetRepository() .TableNoTracking .Where(f => f.ShiftPlanId == shiftPlanId) .Select(ShiftPlanUserMapper.ProjectToSDto) @@ -42,7 +35,7 @@ public class ShiftPlanNotificationScheduledJob : IJob return; break; case ShiftPlanNotifyType.BeforeEndShift30Min: - var activities = await _repositoryWrapper.SetRepository().TableNoTracking + var activities = await repositoryWrapper.SetRepository().TableNoTracking .Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync(); foreach (var shiftPlanUser in shiftPlanUsers) { @@ -50,11 +43,11 @@ public class ShiftPlanNotificationScheduledJob : IJob if(unDoneCount == 0) continue; string message = $"نیم ساعت مونده تا شیفت تموم شه و {unDoneCount} عدد از تست هات مونده، حالا چه خاکی به سر کنیم!😱"; - await _mediator.Send(new CreateNotificationCommand(message, shiftPlanUser.UserId, shiftPlan.ComplexId)); + await mediator.Send(new CreateNotificationCommand(message, shiftPlanUser.UserId, shiftPlan.ComplexId)); } break; case ShiftPlanNotifyType.EndOfShift: - var activitiesEndShift = await _repositoryWrapper.SetRepository().TableNoTracking + var activitiesEndShift = await repositoryWrapper.SetRepository().TableNoTracking .Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync(); foreach (var shiftPlanUser in shiftPlanUsers) { @@ -62,13 +55,13 @@ public class ShiftPlanNotificationScheduledJob : IJob if (unDoneCount == 0) continue; 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} تموم شد. برو به کار بچه ها نمره بده و مو رو از ماست بکش و کامنت یادت نره"; - await _mediator.Send(new CreateNotificationCommand(superVisorAfterShiftMessage, shiftPlan.SupervisorId, shiftPlan.ComplexId)); + await mediator.Send(new CreateNotificationCommand(superVisorAfterShiftMessage, shiftPlan.SupervisorId, shiftPlan.ComplexId)); break; case ShiftPlanNotifyType.AfterStartShift2Hour: - var activities2AfterStartShift = await _repositoryWrapper.SetRepository().TableNoTracking + var activities2AfterStartShift = await repositoryWrapper.SetRepository().TableNoTracking .Where(a => a.ShiftPlanId == shiftPlanId).ToListAsync(); foreach (var shiftPlanUser in shiftPlanUsers) { @@ -76,7 +69,7 @@ public class ShiftPlanNotificationScheduledJob : IJob if (unDoneCount == 0) continue; 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; default: @@ -85,7 +78,7 @@ public class ShiftPlanNotificationScheduledJob : IJob } catch (Exception e) { - _logger.LogError(e.Message); + logger.LogError(e.Message); } } } \ No newline at end of file diff --git a/Brizco.Infrastructure/Marten/MartenRepository.cs b/Brizco.Infrastructure/Marten/MartenRepository.cs index 0d590ce..f93f049 100644 --- a/Brizco.Infrastructure/Marten/MartenRepository.cs +++ b/Brizco.Infrastructure/Marten/MartenRepository.cs @@ -2,38 +2,32 @@ namespace Brizco.Infrastructure.Marten; -public class MartenRepository : IMartenRepository where TMartenEntity : IMartenEntity +public class MartenRepository(IDocumentStore documentStore) : IMartenRepository + where TMartenEntity : IMartenEntity { - private readonly IDocumentStore _documentStore; - - public MartenRepository(IDocumentStore documentStore) - { - _documentStore = documentStore; - } - public async Task> GetEntitiesAsync(CancellationToken cancellation) { - await using var session = _documentStore.QuerySession(); + await using var session = documentStore.QuerySession(); var entities = await session.Query().ToListAsync(cancellation); return entities.ToList(); } public async Task> GetEntitiesAsync(Expression> expression, CancellationToken cancellation) { - await using var session = _documentStore.QuerySession(); + await using var session = documentStore.QuerySession(); var entities = await session.Query().Where(expression).ToListAsync(cancellation); return entities.ToList(); } public async Task> GetQueryAsync(Expression> expression) { - await using var session = _documentStore.QuerySession(); + await using var session = documentStore.QuerySession(); var entities = session.Query().Where(expression); return entities; } public async Task GetEntityAsync(Guid id, CancellationToken cancellation) { - await using var session = _documentStore.QuerySession(); + await using var session = documentStore.QuerySession(); var setting = await session.LoadAsync(id, cancellation); if (setting == null) throw new AppException($"{nameof(TMartenEntity)} not found", ApiResultStatusCode.NotFound); @@ -42,7 +36,7 @@ public class MartenRepository : IMartenRepository public async Task GetEntityAsync(Expression> expression, CancellationToken cancellation) { - await using var session = _documentStore.QuerySession(); + await using var session = documentStore.QuerySession(); var entity = await session.Query().FirstOrDefaultAsync(expression, cancellation); return entity; } @@ -52,7 +46,7 @@ public class MartenRepository : IMartenRepository if (entity == null) throw new AppException($"{nameof(entity)} is null", ApiResultStatusCode.BadRequest); - await using var session = _documentStore.LightweightSession(); + await using var session = documentStore.LightweightSession(); session.Store(entity); await session.SaveChangesAsync(cancellation); } @@ -61,7 +55,7 @@ public class MartenRepository : IMartenRepository { if (entity == null) throw new AppException($"{nameof(entity)} is null", ApiResultStatusCode.BadRequest); - await using var session = _documentStore.LightweightSession(); + await using var session = documentStore.LightweightSession(); session.Delete(entity); await session.SaveChangesAsync(cancellation); } diff --git a/Brizco.Infrastructure/Marten/MartenRepositoryWrapper.cs b/Brizco.Infrastructure/Marten/MartenRepositoryWrapper.cs index 54472a6..1c25fe2 100644 --- a/Brizco.Infrastructure/Marten/MartenRepositoryWrapper.cs +++ b/Brizco.Infrastructure/Marten/MartenRepositoryWrapper.cs @@ -2,15 +2,8 @@ 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 SetRepository() where TMartenEntity : IMartenEntity - => new MartenRepository(_documentStore); + => new MartenRepository(documentStore); } \ No newline at end of file diff --git a/Brizco.Infrastructure/Services/SmsService.cs b/Brizco.Infrastructure/Services/SmsService.cs index 5f9600b..9bdbd39 100644 --- a/Brizco.Infrastructure/Services/SmsService.cs +++ b/Brizco.Infrastructure/Services/SmsService.cs @@ -2,26 +2,18 @@ namespace Brizco.Infrastructure.Services; -public class SmsService : ISmsService +public class SmsService( + IRestApiWrapper restApiWrapper, + IOptionsSnapshot optionsSnapshot, + ILogger logger, + IHostEnvironment environment) + : ISmsService { - private readonly IRestApiWrapper _restApiWrapper; - private readonly ILogger _logger; - private readonly IHostEnvironment _environment; - private readonly SiteSettings _siteSettings; - public SmsService( - IRestApiWrapper restApiWrapper, - IOptionsSnapshot optionsSnapshot, - ILogger logger, - IHostEnvironment environment) - { - _restApiWrapper = restApiWrapper; - _logger = logger; - _environment = environment; - _siteSettings = optionsSnapshot.Value; - } + private readonly SiteSettings _siteSettings = optionsSnapshot.Value; + 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) throw new BaseApiException(ApiResultStatusCode.SendSmsError, rest.Return.message); @@ -32,25 +24,25 @@ public class SmsService : ISmsService 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"); - if (rest.Return.status != 200 && _environment.IsProduction()) + if (rest.Return.status != 200 && environment.IsProduction()) throw new BaseApiException(ApiResultStatusCode.SendSmsError, rest.Return.message); } catch (ApiException apiException) { - if (_environment.IsProduction()) + if (environment.IsProduction()) throw ; else - _logger.LogError(apiException.Message); + logger.LogError(apiException.Message); } catch (Exception apiException) { - if (_environment.IsProduction()) + if (environment.IsProduction()) throw; else - _logger.LogError(apiException.Message); + logger.LogError(apiException.Message); } } diff --git a/Brizco.Repository/Extensions/DbContextOptionCustomExtensionsInfo.cs b/Brizco.Repository/Extensions/DbContextOptionCustomExtensionsInfo.cs index ea2d48b..b3ed70c 100644 --- a/Brizco.Repository/Extensions/DbContextOptionCustomExtensionsInfo.cs +++ b/Brizco.Repository/Extensions/DbContextOptionCustomExtensionsInfo.cs @@ -1,11 +1,8 @@ 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 string LogFragment { get; } = string.Empty; diff --git a/Brizco.Repository/Handlers/Activities/CreateActivityCommandHandler.cs b/Brizco.Repository/Handlers/Activities/CreateActivityCommandHandler.cs index 4961f31..afccf32 100644 --- a/Brizco.Repository/Handlers/Activities/CreateActivityCommandHandler.cs +++ b/Brizco.Repository/Handlers/Activities/CreateActivityCommandHandler.cs @@ -1,25 +1,17 @@ namespace Brizco.Repository.Handlers.Activities; -public class CreateActivityCommandHandler : IRequestHandler +public class CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } - public async Task Handle(CreateActivityCommand request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); try { - await _repositoryWrapper.BeginTransaction(cancellationToken); + await repositoryWrapper.BeginTransaction(cancellationToken); var activity = Domain.Entities.Tasks.Activity .Create( ActivityStatus.Created, @@ -39,14 +31,14 @@ public class CreateActivityCommandHandler : IRequestHandler().Add(activity); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + repositoryWrapper.SetRepository().Add(activity); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return activity.AdaptToLDto(); } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Activities/DeleteActivityCommandHandler.cs b/Brizco.Repository/Handlers/Activities/DeleteActivityCommandHandler.cs index 147daca..658673c 100644 --- a/Brizco.Repository/Handlers/Activities/DeleteActivityCommandHandler.cs +++ b/Brizco.Repository/Handlers/Activities/DeleteActivityCommandHandler.cs @@ -1,33 +1,28 @@ namespace Brizco.Repository.Handlers.Activities; -public class DeleteActivityCommandHandler : IRequestHandler +public class DeleteActivityCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeleteActivityCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(DeleteActivityCommand request, CancellationToken cancellationToken) { try { - await _repositoryWrapper.BeginTransaction(cancellationToken); - var task = await _repositoryWrapper.SetRepository() + await repositoryWrapper.BeginTransaction(cancellationToken); + var task = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (task == null) throw new AppException("Task not found", ApiResultStatusCode.NotFound); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(task); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return true; } catch (Exception ) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Activities/GetActivityQueryHandler.cs b/Brizco.Repository/Handlers/Activities/GetActivityQueryHandler.cs index 777626b..e17a11b 100644 --- a/Brizco.Repository/Handlers/Activities/GetActivityQueryHandler.cs +++ b/Brizco.Repository/Handlers/Activities/GetActivityQueryHandler.cs @@ -1,17 +1,11 @@ namespace Brizco.Repository.Handlers.Activities; -public class GetActivityQueryHandler : IRequestHandler +public class GetActivityQueryHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetActivityQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } - public async Task Handle(GetActivityQuery request, CancellationToken cancellationToken) { - var task = await _repositoryWrapper.SetRepository() + var task = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.Id == request.Id) .Select(ActivityMapper.ProjectToLDto) diff --git a/Brizco.Repository/Handlers/Activities/UpdateActivityCommandHandler.cs b/Brizco.Repository/Handlers/Activities/UpdateActivityCommandHandler.cs index 104119f..a545ea5 100644 --- a/Brizco.Repository/Handlers/Activities/UpdateActivityCommandHandler.cs +++ b/Brizco.Repository/Handlers/Activities/UpdateActivityCommandHandler.cs @@ -1,30 +1,22 @@ namespace Brizco.Repository.Handlers.Activities; -public class UpdateActivityCommandHandler : IRequestHandler +public class UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } - public async Task Handle(UpdateActivityCommand request, CancellationToken cancellationToken) { - var task = await _repositoryWrapper.SetRepository() + var task = await repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); if (task == null) throw new AppException("Task not found", ApiResultStatusCode.NotFound); - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); try { - await _repositoryWrapper.BeginTransaction(cancellationToken); + await repositoryWrapper.BeginTransaction(cancellationToken); var newTask = Domain.Entities.Tasks.Activity.Create( request.Status, request.DoneAt, @@ -45,16 +37,16 @@ public class UpdateActivityCommandHandler : IRequestHandler() + repositoryWrapper.SetRepository() .Update(newTask); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return true; } catch (Exception ) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Complexes/CreateComplexCommandHandler.cs b/Brizco.Repository/Handlers/Complexes/CreateComplexCommandHandler.cs index 7e0cf8d..f86d1b5 100644 --- a/Brizco.Repository/Handlers/Complexes/CreateComplexCommandHandler.cs +++ b/Brizco.Repository/Handlers/Complexes/CreateComplexCommandHandler.cs @@ -1,30 +1,24 @@ namespace Brizco.Repository.Handlers.Complexes; -public class CreateComplexCommandHandler : IRequestHandler +public class CreateComplexCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public CreateComplexCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } + private readonly ICurrentUserService _currentUserService = currentUserService; public async Task Handle(CreateComplexCommand request, CancellationToken cancellationToken) { try { - await _repositoryWrapper.BeginTransaction(cancellationToken); + await repositoryWrapper.BeginTransaction(cancellationToken); var complex = Complex.Create(request.Name, request.Address, request.SupportPhone); - _repositoryWrapper.SetRepository().Add(complex); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + repositoryWrapper.SetRepository().Add(complex); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return complex.AdaptToSDto(); } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Complexes/CreateComplexUserCommandHandler.cs b/Brizco.Repository/Handlers/Complexes/CreateComplexUserCommandHandler.cs index 78458a0..92b321b 100644 --- a/Brizco.Repository/Handlers/Complexes/CreateComplexUserCommandHandler.cs +++ b/Brizco.Repository/Handlers/Complexes/CreateComplexUserCommandHandler.cs @@ -1,37 +1,28 @@ namespace Brizco.Repository.Handlers.Complexes; -public class CreateComplexUserCommandHandler : IRequestHandler +public class CreateComplexUserCommandHandler( + IRepositoryWrapper repositoryWrapper, + UserManager userManager, + RoleManager roleManager, + ILogger logger) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - private readonly ILogger _logger; - - public CreateComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper, - UserManager userManager, - RoleManager roleManager, - ILogger logger) - { - _repositoryWrapper = repositoryWrapper; - _userManager = userManager; - _roleManager = roleManager; - _logger = logger; - } + private readonly ILogger _logger = logger; public async Task Handle(CreateComplexUserCommand request, CancellationToken cancellationToken) { try { //await _repositoryWrapper.BeginTransaction(cancellationToken); - var complex = await _repositoryWrapper.SetRepository().TableNoTracking + var complex = await repositoryWrapper.SetRepository().TableNoTracking .FirstOrDefaultAsync(c => c.Id == request.ComplexId, cancellationToken); if (complex == null) throw new AppException("Complex not found", ApiResultStatusCode.NotFound); - var user = await _userManager.FindByIdAsync(request.UserId.ToString()); + var user = await userManager.FindByIdAsync(request.UserId.ToString()); if (user == null) throw new AppException("User not found", ApiResultStatusCode.NotFound); - var complexUser = await _repositoryWrapper.SetRepository() + var complexUser = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(f => f.ComplexId == request.ComplexId && f.UserId == request.UserId, cancellationToken); if (complexUser != null) @@ -40,21 +31,21 @@ public class CreateComplexUserCommandHandler : IRequestHandler().Add(complexUser); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + repositoryWrapper.SetRepository().Add(complexUser); + await repositoryWrapper.SaveChangesAsync(cancellationToken); //await _repositoryWrapper.CommitAsync(cancellationToken); return complexUser.AdaptToSDto(); } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Complexes/DeleteComplexCommandHandler.cs b/Brizco.Repository/Handlers/Complexes/DeleteComplexCommandHandler.cs index 3f8f5bc..c3ad18f 100644 --- a/Brizco.Repository/Handlers/Complexes/DeleteComplexCommandHandler.cs +++ b/Brizco.Repository/Handlers/Complexes/DeleteComplexCommandHandler.cs @@ -1,33 +1,28 @@ namespace Brizco.Repository.Handlers.Complexes; -public class DeleteComplexCommandHandler : IRequestHandler +public class DeleteComplexCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeleteComplexCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(DeleteComplexCommand request, CancellationToken cancellationToken) { try { - await _repositoryWrapper.BeginTransaction(cancellationToken); - var task = await _repositoryWrapper.SetRepository() + await repositoryWrapper.BeginTransaction(cancellationToken); + var task = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (task == null) throw new AppException("Task not found", ApiResultStatusCode.NotFound); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(task); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return true; } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Complexes/DeleteComplexUserCommandHandler.cs b/Brizco.Repository/Handlers/Complexes/DeleteComplexUserCommandHandler.cs index 1998ba0..1daba50 100644 --- a/Brizco.Repository/Handlers/Complexes/DeleteComplexUserCommandHandler.cs +++ b/Brizco.Repository/Handlers/Complexes/DeleteComplexUserCommandHandler.cs @@ -1,39 +1,33 @@ namespace Brizco.Repository.Handlers.Complexes; -public class DeleteComplexUserCommandHandler : IRequestHandler +public class DeleteComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeleteComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } - public async Task Handle(DeleteComplexUserCommand request, CancellationToken cancellationToken) { try { - await _repositoryWrapper.BeginTransaction(cancellationToken); - var complexUser = await _repositoryWrapper.SetRepository() + await repositoryWrapper.BeginTransaction(cancellationToken); + var complexUser = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(c => c.ComplexId == request.ComplexId && c.UserId == request.UserId, cancellationToken); if (complexUser == null) throw new AppException("ComplexUser not found", ApiResultStatusCode.NotFound); - var complexUserRoles = await _repositoryWrapper.SetRepository().TableNoTracking + var complexUserRoles = await repositoryWrapper.SetRepository().TableNoTracking .Where(c => c.ComplexUserId == complexUser.Id) .ToListAsync(cancellationToken); foreach (var complexUserRole in complexUserRoles) - _repositoryWrapper.SetRepository().HardDelete(complexUserRole); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + repositoryWrapper.SetRepository().HardDelete(complexUserRole); + await repositoryWrapper.SaveChangesAsync(cancellationToken); - _repositoryWrapper.SetRepository().HardDelete(complexUser); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + repositoryWrapper.SetRepository().HardDelete(complexUser); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return true; } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Complexes/GetComplexQueryHandler.cs b/Brizco.Repository/Handlers/Complexes/GetComplexQueryHandler.cs index 37f5f1f..871887d 100644 --- a/Brizco.Repository/Handlers/Complexes/GetComplexQueryHandler.cs +++ b/Brizco.Repository/Handlers/Complexes/GetComplexQueryHandler.cs @@ -1,17 +1,11 @@ namespace Brizco.Repository.Handlers.Complexes; -public class GetComplexQueryHandler : IRequestHandler +public class GetComplexQueryHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetComplexQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } - public async Task Handle(GetComplexQuery request, CancellationToken cancellationToken) { - var complex = await _repositoryWrapper.SetRepository() + var complex = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.Id == request.Id) .Select(ComplexMapper.ProjectToSDto) diff --git a/Brizco.Repository/Handlers/Complexes/GetComplexUsersQueryHandler.cs b/Brizco.Repository/Handlers/Complexes/GetComplexUsersQueryHandler.cs index 27480fa..f850fb6 100644 --- a/Brizco.Repository/Handlers/Complexes/GetComplexUsersQueryHandler.cs +++ b/Brizco.Repository/Handlers/Complexes/GetComplexUsersQueryHandler.cs @@ -2,24 +2,18 @@ namespace Brizco.Repository.Handlers.Complexes; -public class GetComplexUsersQueryHandler : IRequestHandler> +public class GetComplexUsersQueryHandler( + IRepositoryWrapper repositoryWrapper, + UserManager userManager, + RoleManager roleManager) + : IRequestHandler> { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - - public GetComplexUsersQueryHandler(IRepositoryWrapper repositoryWrapper, UserManager userManager, RoleManager roleManager) - { - _repositoryWrapper = repositoryWrapper; - _userManager = userManager; - _roleManager = roleManager; - } public async Task> Handle(GetComplexUsersQuery request, CancellationToken cancellationToken) { List list = new List(); if (!request.ComplexId.IsNullOrEmpty() && Guid.TryParse(request.ComplexId, out Guid complexId)) { - list = await _repositoryWrapper.SetRepository().TableNoTracking + list = await repositoryWrapper.SetRepository().TableNoTracking .Where(c => c.ComplexId == complexId) .OrderByDescending(s => s.CreatedAt) .Skip(request.Page * 15).Take(15) @@ -28,7 +22,7 @@ public class GetComplexUsersQueryHandler : IRequestHandler().TableNoTracking + list = await repositoryWrapper.SetRepository().TableNoTracking .OrderByDescending(s => s.CreatedAt) .Skip(request.Page * 15).Take(15) .Select(ComplexUserMapper.ProjectToSDto) @@ -39,13 +33,13 @@ public class GetComplexUsersQueryHandler : IRequestHandler> +public class GetComplexesQueryHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler> { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetComplexesQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task> Handle(GetComplexesQuery request, CancellationToken cancellationToken) { - var tasks = await _repositoryWrapper.SetRepository().TableNoTracking + var tasks = await repositoryWrapper.SetRepository().TableNoTracking .OrderByDescending(s => s.CreatedAt) .Skip(request.Page * 15).Take(15) .Select(ComplexMapper.ProjectToSDto) diff --git a/Brizco.Repository/Handlers/Complexes/UpdateComplexUserCommandHandler.cs b/Brizco.Repository/Handlers/Complexes/UpdateComplexUserCommandHandler.cs index 20aef51..ed77a45 100644 --- a/Brizco.Repository/Handlers/Complexes/UpdateComplexUserCommandHandler.cs +++ b/Brizco.Repository/Handlers/Complexes/UpdateComplexUserCommandHandler.cs @@ -1,36 +1,27 @@ namespace Brizco.Repository.Handlers.Complexes; -public class UpdateComplexUserCommandHandler : IRequestHandler +public class UpdateComplexUserCommandHandler( + IRepositoryWrapper repositoryWrapper, + UserManager userManager, + RoleManager roleManager) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - - public UpdateComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper, - UserManager userManager, - RoleManager roleManager) - { - _repositoryWrapper = repositoryWrapper; - _userManager = userManager; - _roleManager = roleManager; - } - public async Task Handle(UpdateComplexUserCommand request, CancellationToken cancellationToken) { try { - await _repositoryWrapper.BeginTransaction(cancellationToken); - var complexUser = await _repositoryWrapper.SetRepository().TableNoTracking + await repositoryWrapper.BeginTransaction(cancellationToken); + var complexUser = await repositoryWrapper.SetRepository().TableNoTracking .FirstOrDefaultAsync(c => c.UserId == request.UserId && c.ComplexId == request.ComplexId , cancellationToken); if (complexUser == null) throw new AppException("ComplexUser not found", ApiResultStatusCode.NotFound); - var complexUserRoles = await _repositoryWrapper.SetRepository() + var complexUserRoles = await repositoryWrapper.SetRepository() .TableNoTracking .Where(cur => cur.ComplexUserId == complexUser.Id) .ToListAsync(cancellationToken); - var user = await _userManager.FindByIdAsync(complexUser.UserId.ToString()); + var user = await userManager.FindByIdAsync(complexUser.UserId.ToString()); if (user == null) throw new AppException("User not found", ApiResultStatusCode.NotFound); @@ -46,30 +37,30 @@ public class UpdateComplexUserCommandHandler : IRequestHandler().Delete(userRole); - var role = await _roleManager.FindByIdAsync(userRole.RoleId.ToString()); - var result = await _userManager.RemoveFromRoleAsync(user, role.Name); + repositoryWrapper.SetRepository().Delete(userRole); + var role = await roleManager.FindByIdAsync(userRole.RoleId.ToString()); + var result = await userManager.RemoveFromRoleAsync(user, role.Name); if (!result.Succeeded) throw new AppException(string.Join('|', result.Errors)); } foreach (var roleId in request.RoleIds) { - var role = await _roleManager.FindByIdAsync(roleId.ToString()); - var result = await _userManager.AddToRoleAsync(user, role.Name); + var role = await roleManager.FindByIdAsync(roleId.ToString()); + var result = await userManager.AddToRoleAsync(user, role.Name); if (!result.Succeeded) throw new AppException(string.Join('|', result.Errors)); var userRole = complexUser.AddRole(role.Id); - _repositoryWrapper.SetRepository().Add(userRole); + repositoryWrapper.SetRepository().Add(userRole); } - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return true; } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Positions/CreatePositionCommandHandler.cs b/Brizco.Repository/Handlers/Positions/CreatePositionCommandHandler.cs index a219f19..29a1017 100644 --- a/Brizco.Repository/Handlers/Positions/CreatePositionCommandHandler.cs +++ b/Brizco.Repository/Handlers/Positions/CreatePositionCommandHandler.cs @@ -1,26 +1,19 @@ namespace Brizco.Repository.Handlers.Positions; -public class CreatePositionCommandHandler : IRequestHandler +public class CreatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public CreatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } public async Task Handle(CreatePositionCommand request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); try { - await _repositoryWrapper.BeginTransaction(cancellationToken); + await repositoryWrapper.BeginTransaction(cancellationToken); var entity = Position .Create(request.Title, request.Description, @@ -29,14 +22,14 @@ public class CreatePositionCommandHandler : IRequestHandlerentity.AddPermission(f)); - _repositoryWrapper.SetRepository().Add(entity); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + repositoryWrapper.SetRepository().Add(entity); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return entity.AdaptToSDto(); } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Positions/DeletePositionCommandHandler.cs b/Brizco.Repository/Handlers/Positions/DeletePositionCommandHandler.cs index 3aaf78b..d2b27df 100644 --- a/Brizco.Repository/Handlers/Positions/DeletePositionCommandHandler.cs +++ b/Brizco.Repository/Handlers/Positions/DeletePositionCommandHandler.cs @@ -1,24 +1,19 @@ namespace Brizco.Repository.Handlers.Positions; -public class DeletePositionCommandHandler : IRequestHandler +public class DeletePositionCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeletePositionCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(DeletePositionCommand request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (shift == null) throw new AppException("Postion not found", ApiResultStatusCode.NotFound); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(shift); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } } \ No newline at end of file diff --git a/Brizco.Repository/Handlers/Positions/GetPositionQueryHandler.cs b/Brizco.Repository/Handlers/Positions/GetPositionQueryHandler.cs index baab437..48cb250 100644 --- a/Brizco.Repository/Handlers/Positions/GetPositionQueryHandler.cs +++ b/Brizco.Repository/Handlers/Positions/GetPositionQueryHandler.cs @@ -1,16 +1,11 @@ namespace Brizco.Repository.Handlers.Positions; -public class GetPositionQueryHandler : IRequestHandler +public class GetPositionQueryHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetPositionQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(GetPositionQuery request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.Id == request.Id) .Select(PositionMapper.ProjectToLDto) diff --git a/Brizco.Repository/Handlers/Positions/GetPositionsQueryHandler.cs b/Brizco.Repository/Handlers/Positions/GetPositionsQueryHandler.cs index 2f51abd..c12c6c2 100644 --- a/Brizco.Repository/Handlers/Positions/GetPositionsQueryHandler.cs +++ b/Brizco.Repository/Handlers/Positions/GetPositionsQueryHandler.cs @@ -1,24 +1,17 @@ namespace Brizco.Repository.Handlers.Positions; -public class GetPositionsQueryHandler : IRequestHandler> +public class GetPositionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler> { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public GetPositionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } public async Task> Handle(GetPositionsQuery request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); - var shifts = await _repositoryWrapper.SetRepository().TableNoTracking + var shifts = await repositoryWrapper.SetRepository().TableNoTracking .Where(p=>p.ComplexId==complexId) .OrderByDescending(s => s.CreatedAt) .Skip(request.Page * 15).Take(15) diff --git a/Brizco.Repository/Handlers/Positions/UpdatePositionCommandHandler.cs b/Brizco.Repository/Handlers/Positions/UpdatePositionCommandHandler.cs index 03e7341..92646f7 100644 --- a/Brizco.Repository/Handlers/Positions/UpdatePositionCommandHandler.cs +++ b/Brizco.Repository/Handlers/Positions/UpdatePositionCommandHandler.cs @@ -1,26 +1,18 @@ namespace Brizco.Repository.Handlers.Positions; -public class UpdatePositionCommandHandler : IRequestHandler +public class UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } - public async Task Handle(UpdatePositionCommand request, CancellationToken cancellationToken) { - var ent = await _repositoryWrapper.SetRepository() + var ent = await repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (ent == null) throw new AppException("Postion not found", ApiResultStatusCode.NotFound); - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); var newPosition = Position.Create(request.Title, @@ -31,25 +23,25 @@ public class UpdatePositionCommandHandler : IRequestHandler() + var permissionsDb = await repositoryWrapper.SetRepository() .TableNoTracking .Where(f => f.PositionId == ent.Id) .ToListAsync(cancellationToken); foreach (var permissionDb in permissionsDb.Where(p=>!request.Permissions.Contains(p.Permission))) { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .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))) newPosition.AddPermission(permission); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Update(newPosition); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } diff --git a/Brizco.Repository/Handlers/Routines/CreateRoutineCommandHandler.cs b/Brizco.Repository/Handlers/Routines/CreateRoutineCommandHandler.cs index 0f87aba..849799d 100644 --- a/Brizco.Repository/Handlers/Routines/CreateRoutineCommandHandler.cs +++ b/Brizco.Repository/Handlers/Routines/CreateRoutineCommandHandler.cs @@ -1,37 +1,30 @@ namespace Brizco.Repository.Handlers.Routines; -public class CreateRoutineCommandHandler : IRequestHandler +public class CreateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public CreateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } public async Task Handle(CreateRoutineCommand request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); try { - await _repositoryWrapper.BeginTransaction(cancellationToken); + await repositoryWrapper.BeginTransaction(cancellationToken); var entity = Domain.Entities.Routines.Routine .Create(request.Name,request.Description,complexId); - _repositoryWrapper.SetRepository().Add(entity); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + repositoryWrapper.SetRepository().Add(entity); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return entity.AdaptToSDto(); } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Routines/DeleteRoutineCommandHandler.cs b/Brizco.Repository/Handlers/Routines/DeleteRoutineCommandHandler.cs index 5ae013a..7d1b3fb 100644 --- a/Brizco.Repository/Handlers/Routines/DeleteRoutineCommandHandler.cs +++ b/Brizco.Repository/Handlers/Routines/DeleteRoutineCommandHandler.cs @@ -1,24 +1,19 @@ namespace Brizco.Repository.Handlers.Routines; -public class DeleteRoutineCommandHandler : IRequestHandler +public class DeleteRoutineCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeleteRoutineCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(DeleteRoutineCommand request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (shift == null) throw new AppException("Postion not found", ApiResultStatusCode.NotFound); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(shift); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } } \ No newline at end of file diff --git a/Brizco.Repository/Handlers/Routines/GetRoutineQueryHandler.cs b/Brizco.Repository/Handlers/Routines/GetRoutineQueryHandler.cs index f0afc7d..11f2581 100644 --- a/Brizco.Repository/Handlers/Routines/GetRoutineQueryHandler.cs +++ b/Brizco.Repository/Handlers/Routines/GetRoutineQueryHandler.cs @@ -1,16 +1,11 @@ namespace Brizco.Repository.Handlers.Routines; -public class GetRoutineQueryHandler : IRequestHandler +public class GetRoutineQueryHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetRoutineQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(GetRoutineQuery request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.Id == request.Id) .Select(RoutineMapper.ProjectToSDto) diff --git a/Brizco.Repository/Handlers/Routines/GetRoutineShiftsQueryHandler.cs b/Brizco.Repository/Handlers/Routines/GetRoutineShiftsQueryHandler.cs index e85de3c..2a59a13 100644 --- a/Brizco.Repository/Handlers/Routines/GetRoutineShiftsQueryHandler.cs +++ b/Brizco.Repository/Handlers/Routines/GetRoutineShiftsQueryHandler.cs @@ -1,25 +1,19 @@ namespace Brizco.Repository.Handlers.Routines; -public class GetRoutineShiftsQueryHandler : IRequestHandler> +public class GetRoutineShiftsQueryHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler> { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetRoutineShiftsQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } - public async Task> Handle(GetRoutineShiftsQuery request, CancellationToken cancellationToken) { var routineShiftResponse = new List(); - var shiftRoutines = await _repositoryWrapper.SetRepository() + var shiftRoutines = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.RoutineId == request.Id) .ToListAsync(cancellationToken); foreach (var shiftRoutine in shiftRoutines) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.Id == shiftRoutine.ShiftId) .Select(ShiftMapper.ProjectToSDto) @@ -46,7 +40,7 @@ public class GetRoutineShiftsQueryHandler : IRequestHandler() + var existedShiftPlan = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.ShiftId == shift.Id && s.PlanFor.Date == selectedDate.Date, cancellationToken); shift.IsCompleted = existedShiftPlan?.IsCompleted ?? false; diff --git a/Brizco.Repository/Handlers/Routines/GetRoutinesQueryHandler.cs b/Brizco.Repository/Handlers/Routines/GetRoutinesQueryHandler.cs index 8b93193..acded8f 100644 --- a/Brizco.Repository/Handlers/Routines/GetRoutinesQueryHandler.cs +++ b/Brizco.Repository/Handlers/Routines/GetRoutinesQueryHandler.cs @@ -1,24 +1,17 @@ namespace Brizco.Repository.Handlers.Routines; -public class GetRoutinesQueryHandler : IRequestHandler> +public class GetRoutinesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler> { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public GetRoutinesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } public async Task> Handle(GetRoutinesQuery request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); - var entities = await _repositoryWrapper.SetRepository().TableNoTracking + var entities = await repositoryWrapper.SetRepository().TableNoTracking .Where(p=>p.ComplexId==complexId) .OrderByDescending(s => s.CreatedAt) .Skip(request.Page * 15).Take(15) diff --git a/Brizco.Repository/Handlers/Routines/UpdateRoutineCommandHandler.cs b/Brizco.Repository/Handlers/Routines/UpdateRoutineCommandHandler.cs index 4f4057d..45dad24 100644 --- a/Brizco.Repository/Handlers/Routines/UpdateRoutineCommandHandler.cs +++ b/Brizco.Repository/Handlers/Routines/UpdateRoutineCommandHandler.cs @@ -1,26 +1,18 @@ namespace Brizco.Repository.Handlers.Routines; -public class UpdateRoutineCommandHandler : IRequestHandler +public class UpdateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public UpdateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } - public async Task Handle(UpdateRoutineCommand request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (shift == null) throw new AppException("Routine not found", ApiResultStatusCode.NotFound); - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); var newEntity = Domain.Entities.Routines.Routine.Create(request.Name, @@ -29,10 +21,10 @@ public class UpdateRoutineCommandHandler : IRequestHandler() + repositoryWrapper.SetRepository() .Update(newEntity); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } diff --git a/Brizco.Repository/Handlers/Sections/CreateSectionCommandHandler.cs b/Brizco.Repository/Handlers/Sections/CreateSectionCommandHandler.cs index 43a8952..e9c2b38 100644 --- a/Brizco.Repository/Handlers/Sections/CreateSectionCommandHandler.cs +++ b/Brizco.Repository/Handlers/Sections/CreateSectionCommandHandler.cs @@ -1,39 +1,32 @@ namespace Brizco.Repository.Handlers.Sections; -public class CreateSectionCommandHandler : IRequestHandler +public class CreateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public CreateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } public async Task Handle(CreateSectionCommand request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); try { - await _repositoryWrapper.BeginTransaction(cancellationToken); + await repositoryWrapper.BeginTransaction(cancellationToken); var entity = Section .Create(request.Title, request.Description, complexId); - _repositoryWrapper.SetRepository
().Add(entity); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + repositoryWrapper.SetRepository
().Add(entity); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return entity.AdaptToSDto(); } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Sections/DeleteSectionCommandHandler.cs b/Brizco.Repository/Handlers/Sections/DeleteSectionCommandHandler.cs index 2d91f9f..620e0d9 100644 --- a/Brizco.Repository/Handlers/Sections/DeleteSectionCommandHandler.cs +++ b/Brizco.Repository/Handlers/Sections/DeleteSectionCommandHandler.cs @@ -1,32 +1,27 @@ namespace Brizco.Repository.Handlers.Sections; -public class DeleteSectionCommandHandler : IRequestHandler +public class DeleteSectionCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeleteSectionCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(DeleteSectionCommand request, CancellationToken cancellationToken) { - var section = await _repositoryWrapper.SetRepository
() + var section = await repositoryWrapper.SetRepository
() .TableNoTracking .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (section == null) throw new AppException("Section not found", ApiResultStatusCode.NotFound); - var positions = await _repositoryWrapper.SetRepository() + var positions = await repositoryWrapper.SetRepository() .TableNoTracking .Where(p => p.SectionId == section.Id) .CountAsync(cancellationToken); if (positions > 0) throw new AppException("این سکشن پوزیشن فعال دارد ، نخست پوزیشن های سکشن را حذف کرده یا منتقل کنید"); - _repositoryWrapper.SetRepository
() + repositoryWrapper.SetRepository
() .Delete(section); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } } \ No newline at end of file diff --git a/Brizco.Repository/Handlers/Sections/GetSectionQueryHandler.cs b/Brizco.Repository/Handlers/Sections/GetSectionQueryHandler.cs index 4a862b0..89aee07 100644 --- a/Brizco.Repository/Handlers/Sections/GetSectionQueryHandler.cs +++ b/Brizco.Repository/Handlers/Sections/GetSectionQueryHandler.cs @@ -1,16 +1,11 @@ namespace Brizco.Repository.Handlers.Sections; -public class GetSectionQueryHandler : IRequestHandler +public class GetSectionQueryHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetSectionQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(GetSectionQuery request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository
() + var shift = await repositoryWrapper.SetRepository
() .TableNoTracking .Where(s => s.Id == request.Id) .Select(SectionMapper.ProjectToLDto) diff --git a/Brizco.Repository/Handlers/Sections/GetSectionsQueryHandler.cs b/Brizco.Repository/Handlers/Sections/GetSectionsQueryHandler.cs index d6c595a..1ae858d 100644 --- a/Brizco.Repository/Handlers/Sections/GetSectionsQueryHandler.cs +++ b/Brizco.Repository/Handlers/Sections/GetSectionsQueryHandler.cs @@ -1,23 +1,16 @@ namespace Brizco.Repository.Handlers.Sections; -public class GetSectionsQueryHandler : IRequestHandler> +public class GetSectionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler> { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public GetSectionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } public async Task> Handle(GetSectionsQuery request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); - var shifts = await _repositoryWrapper.SetRepository
().TableNoTracking + var shifts = await repositoryWrapper.SetRepository
().TableNoTracking .Where(s=>s.ComplexId==complexId) .OrderByDescending(s => s.CreatedAt) .Skip(request.Page * 15).Take(15) diff --git a/Brizco.Repository/Handlers/Sections/UpdateSectionCommandHandler.cs b/Brizco.Repository/Handlers/Sections/UpdateSectionCommandHandler.cs index 30e3483..89d89b6 100644 --- a/Brizco.Repository/Handlers/Sections/UpdateSectionCommandHandler.cs +++ b/Brizco.Repository/Handlers/Sections/UpdateSectionCommandHandler.cs @@ -1,26 +1,18 @@ namespace Brizco.Repository.Handlers.Sections; -public class UpdateSectionCommandHandler : IRequestHandler +public class UpdateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public UpdateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } - public async Task Handle(UpdateSectionCommand request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository
() + var shift = await repositoryWrapper.SetRepository
() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (shift == null) throw new AppException("Section not found", ApiResultStatusCode.NotFound); - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); var newSection = Section.Create(request.Title, @@ -29,10 +21,10 @@ public class UpdateSectionCommandHandler : IRequestHandler() + repositoryWrapper.SetRepository
() .Update(newSection); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } diff --git a/Brizco.Repository/Handlers/ShiftPlans/DeleteShiftPlanCommandHandler.cs b/Brizco.Repository/Handlers/ShiftPlans/DeleteShiftPlanCommandHandler.cs index 55d8811..47681a7 100644 --- a/Brizco.Repository/Handlers/ShiftPlans/DeleteShiftPlanCommandHandler.cs +++ b/Brizco.Repository/Handlers/ShiftPlans/DeleteShiftPlanCommandHandler.cs @@ -1,25 +1,19 @@ namespace Brizco.Repository.Handlers.ShiftPlans; -public class DeleteShiftPlanCommandHandler : IRequestHandler +public class DeleteShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeleteShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } - public async Task Handle(DeleteShiftPlanCommand request, CancellationToken cancellationToken) { - var shiftPlan = await _repositoryWrapper.SetRepository() + var shiftPlan = await repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); if (shiftPlan == null) throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(shiftPlan); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } diff --git a/Brizco.Repository/Handlers/ShiftPlans/GetShiftPlanQueryHandler.cs b/Brizco.Repository/Handlers/ShiftPlans/GetShiftPlanQueryHandler.cs index 8174bcc..a42d583 100644 --- a/Brizco.Repository/Handlers/ShiftPlans/GetShiftPlanQueryHandler.cs +++ b/Brizco.Repository/Handlers/ShiftPlans/GetShiftPlanQueryHandler.cs @@ -1,16 +1,11 @@ namespace Brizco.Repository.Handlers.ShiftPlans; -public class GetShiftPlanQueryHandler : IRequestHandler +public class GetShiftPlanQueryHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetShiftPlanQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(GetShiftPlanQuery request, CancellationToken cancellationToken) { - var shiftPlan = await _repositoryWrapper.SetRepository() + var shiftPlan = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.Id == request.Id) .Select(ShiftPlanMapper.ProjectToLDto) diff --git a/Brizco.Repository/Handlers/ShiftPlans/UpdateShiftPlanCommandHandler.cs b/Brizco.Repository/Handlers/ShiftPlans/UpdateShiftPlanCommandHandler.cs index 9ce2c9f..64ef3e0 100644 --- a/Brizco.Repository/Handlers/ShiftPlans/UpdateShiftPlanCommandHandler.cs +++ b/Brizco.Repository/Handlers/ShiftPlans/UpdateShiftPlanCommandHandler.cs @@ -1,23 +1,17 @@ namespace Brizco.Repository.Handlers.ShiftPlans; -public class UpdateShiftPlanCommandHandler : IRequestHandler +public class UpdateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public UpdateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } - public async Task Handle(UpdateShiftPlanCommand request, CancellationToken cancellationToken) { - var shiftPlan = await _repositoryWrapper.SetRepository() + var shiftPlan = await repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); if (shiftPlan == null) throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound); - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.ShiftId, cancellationToken); if (shift == null) @@ -28,7 +22,7 @@ public class UpdateShiftPlanCommandHandler : IRequestHandler() + var shiftPlanUsers = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.ShiftPlanId == newPlan.Id) .ToListAsync(cancellationToken); @@ -39,19 +33,19 @@ public class UpdateShiftPlanCommandHandler : IRequestHandler(shiftPlanUser.PositionId, shiftPlanUser.UserId)); else { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(shiftPlanUser); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); } } foreach (var userId in request.UserAndPositionIds) newPlan.AddUser(userId.Key,userId.Value); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Update(newPlan); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } diff --git a/Brizco.Repository/Handlers/Shifts/CreateShiftCommandHandler.cs b/Brizco.Repository/Handlers/Shifts/CreateShiftCommandHandler.cs index 18bef57..22d6d40 100644 --- a/Brizco.Repository/Handlers/Shifts/CreateShiftCommandHandler.cs +++ b/Brizco.Repository/Handlers/Shifts/CreateShiftCommandHandler.cs @@ -1,26 +1,19 @@ namespace Brizco.Repository.Handlers.Shifts; -public class CreateShiftCommandHandler : IRequestHandler +public class CreateShiftCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public CreateShiftCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } public async Task Handle(CreateShiftCommand request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); try { - await _repositoryWrapper.BeginTransaction(cancellationToken); + await repositoryWrapper.BeginTransaction(cancellationToken); var shift = Shift .Create(request.Title, request.Description, @@ -34,14 +27,14 @@ public class CreateShiftCommandHandler : IRequestHandlershift.AddRoutine(r)); - _repositoryWrapper.SetRepository().Add(shift); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); - await _repositoryWrapper.CommitAsync(cancellationToken); + repositoryWrapper.SetRepository().Add(shift); + await repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.CommitAsync(cancellationToken); return shift.AdaptToSDto(); } catch (Exception) { - await _repositoryWrapper.RollBackAsync(cancellationToken); + await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } diff --git a/Brizco.Repository/Handlers/Shifts/DeleteShiftCommandHandler.cs b/Brizco.Repository/Handlers/Shifts/DeleteShiftCommandHandler.cs index 18800fc..3253142 100644 --- a/Brizco.Repository/Handlers/Shifts/DeleteShiftCommandHandler.cs +++ b/Brizco.Repository/Handlers/Shifts/DeleteShiftCommandHandler.cs @@ -1,24 +1,19 @@ namespace Brizco.Repository.Handlers.Shifts; -public class DeletePositionCommandHandler : IRequestHandler +public class DeletePositionCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeletePositionCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(DeleteShiftCommand request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (shift == null) throw new AppException("Routine not found", ApiResultStatusCode.NotFound); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(shift); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } } \ No newline at end of file diff --git a/Brizco.Repository/Handlers/Shifts/GetShiftQueryHandler.cs b/Brizco.Repository/Handlers/Shifts/GetShiftQueryHandler.cs index b5390d3..84d18df 100644 --- a/Brizco.Repository/Handlers/Shifts/GetShiftQueryHandler.cs +++ b/Brizco.Repository/Handlers/Shifts/GetShiftQueryHandler.cs @@ -1,16 +1,10 @@ namespace Brizco.Repository.Handlers.Shifts; -public class GetShiftPlanQueryHandler : IRequestHandler +public class GetShiftPlanQueryHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetShiftPlanQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(GetShiftQuery request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.Id == request.Id) .Select(ShiftMapper.ProjectToLDto) diff --git a/Brizco.Repository/Handlers/Shifts/UpdateShiftCommandHandler.cs b/Brizco.Repository/Handlers/Shifts/UpdateShiftCommandHandler.cs index a57b5e1..661bda3 100644 --- a/Brizco.Repository/Handlers/Shifts/UpdateShiftCommandHandler.cs +++ b/Brizco.Repository/Handlers/Shifts/UpdateShiftCommandHandler.cs @@ -1,26 +1,18 @@ namespace Brizco.Repository.Handlers.Shifts; -public class UpdatePositionCommandHandler : IRequestHandler +public class UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } - public async Task Handle(UpdateShiftCommand request, CancellationToken cancellationToken) { - var shift = await _repositoryWrapper.SetRepository() + var shift = await repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (shift == null) throw new AppException("Shift not found", ApiResultStatusCode.NotFound); - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); var newShift = Shift.Create(request.Title, @@ -32,15 +24,15 @@ public class UpdatePositionCommandHandler : IRequestHandler() + var shiftDays = await repositoryWrapper.SetRepository() .TableNoTracking.Where(sd => sd.ShiftId == request.Id) .ToListAsync(cancellationToken); foreach (var shiftDay in shiftDays.Where(shiftDay => !request.DayOfWeeks.Contains(shiftDay.DayOfWeek))) { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .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) @@ -51,15 +43,15 @@ public class UpdatePositionCommandHandler : IRequestHandler() + var shiftRoutines = await repositoryWrapper.SetRepository() .TableNoTracking.Where(sd => sd.ShiftId == request.Id) .ToListAsync(cancellationToken); foreach (var shiftRoutine in shiftRoutines.Where(shiftRoutine => !request.Routines.Contains(shiftRoutine.RoutineId))) { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(shiftRoutine); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); } foreach (var routine in request.Routines.Where(r=>!shiftRoutines.Exists(routine=>routine.RoutineId==r))) @@ -67,9 +59,9 @@ public class UpdatePositionCommandHandler : IRequestHandler() + repositoryWrapper.SetRepository() .Update(newShift); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } diff --git a/Brizco.Repository/Handlers/Tasks/CreateTaskCommandHandler.cs b/Brizco.Repository/Handlers/Tasks/CreateTaskCommandHandler.cs index 39bc4b8..c4369c0 100644 --- a/Brizco.Repository/Handlers/Tasks/CreateTaskCommandHandler.cs +++ b/Brizco.Repository/Handlers/Tasks/CreateTaskCommandHandler.cs @@ -1,20 +1,13 @@ namespace Brizco.Repository.Handlers.Tasks; -public class CreateActivityCommandHandler : IRequestHandler +public class CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } public async Task Handle(CreateTaskCommand request, CancellationToken cancellationToken) { - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); var task = Domain.Entities.Tasks.Task .Create(request.Title, @@ -45,8 +38,8 @@ public class CreateActivityCommandHandler : IRequestHandlertask.SetDay(d)); - _repositoryWrapper.SetRepository().Add(task); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + repositoryWrapper.SetRepository().Add(task); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return task.AdaptToLDto(); } } \ No newline at end of file diff --git a/Brizco.Repository/Handlers/Tasks/DeleteTaskCommandHandler.cs b/Brizco.Repository/Handlers/Tasks/DeleteTaskCommandHandler.cs index 6a10b04..9a07c6a 100644 --- a/Brizco.Repository/Handlers/Tasks/DeleteTaskCommandHandler.cs +++ b/Brizco.Repository/Handlers/Tasks/DeleteTaskCommandHandler.cs @@ -1,24 +1,19 @@ namespace Brizco.Repository.Handlers.Tasks; -public class DeleteActivityCommandHandler : IRequestHandler +public class DeleteActivityCommandHandler(IRepositoryWrapper repositoryWrapper) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public DeleteActivityCommandHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } public async Task Handle(DeleteTaskCommand request, CancellationToken cancellationToken) { - var task = await _repositoryWrapper.SetRepository() + var task = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken); if (task == null) throw new AppException("Task not found", ApiResultStatusCode.NotFound); - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(task); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } } \ No newline at end of file diff --git a/Brizco.Repository/Handlers/Tasks/GetTaskQueryHandler.cs b/Brizco.Repository/Handlers/Tasks/GetTaskQueryHandler.cs index 50080dc..97a9dd0 100644 --- a/Brizco.Repository/Handlers/Tasks/GetTaskQueryHandler.cs +++ b/Brizco.Repository/Handlers/Tasks/GetTaskQueryHandler.cs @@ -1,17 +1,10 @@ namespace Brizco.Repository.Handlers.Tasks; -public class GetActivityQueryHandler : IRequestHandler +public class GetActivityQueryHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - - public GetActivityQueryHandler(IRepositoryWrapper repositoryWrapper) - { - _repositoryWrapper = repositoryWrapper; - } - public async Task Handle(GetTaskQuery request, CancellationToken cancellationToken) { - var task = await _repositoryWrapper.SetRepository() + var task = await repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.Id == request.Id) .Select(TaskMapper.ProjectToLDto) diff --git a/Brizco.Repository/Handlers/Tasks/UpdateTaskCommandHandler.cs b/Brizco.Repository/Handlers/Tasks/UpdateTaskCommandHandler.cs index d3fdce5..462d917 100644 --- a/Brizco.Repository/Handlers/Tasks/UpdateTaskCommandHandler.cs +++ b/Brizco.Repository/Handlers/Tasks/UpdateTaskCommandHandler.cs @@ -2,27 +2,19 @@ namespace Brizco.Repository.Handlers.Tasks; -public class UpdateActivityCommandHandler : IRequestHandler +public class UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) + : IRequestHandler { - private readonly IRepositoryWrapper _repositoryWrapper; - private readonly ICurrentUserService _currentUserService; - - public UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService) - { - _repositoryWrapper = repositoryWrapper; - _currentUserService = currentUserService; - } - public async Task Handle(UpdateTaskCommand request, CancellationToken cancellationToken) { - var task = await _repositoryWrapper.SetRepository() + var task = await repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); if (task == null) throw new AppException("Task not found", ApiResultStatusCode.NotFound); - if (_currentUserService.ComplexId == null) + if (currentUserService.ComplexId == null) 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); var newTask = Domain.Entities.Tasks.Task.Create(request.Title, @@ -41,15 +33,15 @@ public class UpdateActivityCommandHandler : IRequestHandler() + var routines = await repositoryWrapper.SetRepository() .TableNoTracking .Where(tr => tr.TaskId == newTask.Id) .ToListAsync(cancellationToken); foreach (var taskRoutine in routines.Where(taskR => !request.Routines.Exists(r=>r== taskR.RoutineId))) { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(taskRoutine); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); } foreach (var routine in request.Routines.Where(requestRoutine => !routines.Exists(r=>r.RoutineId==requestRoutine))) @@ -59,15 +51,15 @@ public class UpdateActivityCommandHandler : IRequestHandler() + var shifts = await repositoryWrapper.SetRepository() .TableNoTracking .Where(tr => tr.TaskId == newTask.Id) .ToListAsync(cancellationToken); foreach (var taskShift in shifts.Where(taskS => !request.Shifts.Exists(r => r == taskS.ShiftId))) { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(taskShift); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); } foreach (var shift in request.Shifts.Where(requestShift => !shifts.Exists(r => r.ShiftId == requestShift))) @@ -77,15 +69,15 @@ public class UpdateActivityCommandHandler : IRequestHandler() + var positions = await repositoryWrapper.SetRepository() .TableNoTracking .Where(tr => tr.TaskId == newTask.Id) .ToListAsync(cancellationToken); foreach (var taskPosition in positions.Where(taskP => !request.Positions.Exists(r => r == taskP.PositionId))) { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(taskPosition); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); } foreach (var position in request.Positions.Where(requestP => !positions.Exists(r => r.PositionId == requestP))) @@ -96,15 +88,15 @@ public class UpdateActivityCommandHandler : IRequestHandler task.SetDay(d)); - var days = await _repositoryWrapper.SetRepository() + var days = await repositoryWrapper.SetRepository() .TableNoTracking .Where(tr => tr.TaskId == newTask.Id) .ToListAsync(cancellationToken); foreach (var taskDay in days.Where(taskD => !request.Days.Exists(r => r == taskD.DayOfWeek))) { - _repositoryWrapper.SetRepository() + repositoryWrapper.SetRepository() .Delete(taskDay); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); } foreach (var day in request.Days.Where(requestP => !days.Exists(r => r.DayOfWeek == requestP))) @@ -112,9 +104,9 @@ public class UpdateActivityCommandHandler : IRequestHandler() + repositoryWrapper.SetRepository() .Update(newTask); - await _repositoryWrapper.SaveChangesAsync(cancellationToken); + await repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } diff --git a/Brizco.Repository/Models/ApplicationContext.cs b/Brizco.Repository/Models/ApplicationContext.cs index c62b5e5..6e4d220 100644 --- a/Brizco.Repository/Models/ApplicationContext.cs +++ b/Brizco.Repository/Models/ApplicationContext.cs @@ -1,15 +1,9 @@ namespace Brizco.Repository.Models; -public class ApplicationContext : IdentityDbContext +public class ApplicationContext(DbContextOptions options, ILogger logger) + : IdentityDbContext(options) { - private readonly ILogger _logger; - private readonly Assembly _projectAssembly; - - public ApplicationContext( DbContextOptions options, ILogger logger): base(options) - { - _logger = logger; - _projectAssembly = options.GetExtension().ProjectAssembly; - } + private readonly Assembly _projectAssembly = options.GetExtension().ProjectAssembly; protected override void OnModelCreating(ModelBuilder builder) @@ -18,9 +12,9 @@ public class ApplicationContext : IdentityDbContext(_logger, entitiesAssembly); + builder.RegisterAllEntities(logger, entitiesAssembly); stopwatch.Stop(); - _logger.LogInformation($"!!!!!!! RegisterAllEntities : {stopwatch.ElapsedMilliseconds}ms !!!!!!!"); + logger.LogInformation($"!!!!!!! RegisterAllEntities : {stopwatch.ElapsedMilliseconds}ms !!!!!!!"); RenameIdentityTables(builder); diff --git a/Brizco.Repository/Repositories/Base/BaseRepository.cs b/Brizco.Repository/Repositories/Base/BaseRepository.cs index 480ac1d..f038b9a 100644 --- a/Brizco.Repository/Repositories/Base/BaseRepository.cs +++ b/Brizco.Repository/Repositories/Base/BaseRepository.cs @@ -1,14 +1,9 @@ namespace Brizco.Repository.Repositories.Base { - public class BaseRepository : Repository, IBaseRepository where T : class, IApiEntity + public class BaseRepository(ApplicationContext dbContext, ICurrentUserService currentUserService) + : Repository(dbContext), IBaseRepository + where T : class, IApiEntity { - private readonly ICurrentUserService _currentUserService; - - public BaseRepository(ApplicationContext dbContext, ICurrentUserService currentUserService) : base(dbContext) - { - _currentUserService = currentUserService; - } - public virtual async ValueTask GetByIdAsync(CancellationToken cancellationToken, params object[] ids) { return await Entities.FindAsync(ids, cancellationToken); @@ -62,9 +57,9 @@ .CurrentValue = DateTime.Now; Entities.Entry(entity).Property(e => e.IsRemoved) .CurrentValue = true; - if (_currentUserService.UserName != null) + if (currentUserService.UserName != null) Entities.Entry(entity).Property(e => e.RemovedBy) - .CurrentValue = _currentUserService.UserName; + .CurrentValue = currentUserService.UserName; Entities.Update(entity); } @@ -78,9 +73,9 @@ .CurrentValue = DateTime.Now; Entities.Entry(entity).Property(e => e.IsRemoved) .CurrentValue = true; - if (_currentUserService.UserName != null) + if (currentUserService.UserName != null) Entities.Entry(entity).Property(e => e.RemovedBy) - .CurrentValue = _currentUserService.UserName; + .CurrentValue = currentUserService.UserName; Entities.Update(entity); } } diff --git a/Brizco.Repository/Repositories/Base/ReadRepository.cs b/Brizco.Repository/Repositories/Base/ReadRepository.cs index 0816988..4f5d8f2 100644 --- a/Brizco.Repository/Repositories/Base/ReadRepository.cs +++ b/Brizco.Repository/Repositories/Base/ReadRepository.cs @@ -1,12 +1,9 @@ namespace Brizco.Repository.Repositories.Base { - public class ReadRepository : Repository, IDisposable, IReadRepository where T : class, IApiEntity + public class ReadRepository(ApplicationContext dbContext) + : Repository(dbContext), IDisposable, IReadRepository + where T : class, IApiEntity { - public ReadRepository( - ApplicationContext dbContext) : base(dbContext) - { - } - public void Dispose() { DbContext?.Dispose(); diff --git a/Brizco.Repository/Repositories/Base/RepositoryWrapper.cs b/Brizco.Repository/Repositories/Base/RepositoryWrapper.cs index 01a2326..18cf7ac 100644 --- a/Brizco.Repository/Repositories/Base/RepositoryWrapper.cs +++ b/Brizco.Repository/Repositories/Base/RepositoryWrapper.cs @@ -1,18 +1,12 @@ using Microsoft.EntityFrameworkCore.Storage; 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; - public RepositoryWrapper(ApplicationContext context, ICurrentUserService currentUserService) - { - _context = context; - _currentUserService = currentUserService; - } - public IBaseRepository SetRepository() where T : ApiEntity => new BaseRepository(_context, _currentUserService); + public IBaseRepository SetRepository() where T : ApiEntity => new BaseRepository(context, currentUserService); public async Task RollBackAsync(CancellationToken cancellationToken) @@ -29,17 +23,17 @@ public class RepositoryWrapper : IRepositoryWrapper } 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) { SetAuditables(); - await _context.SaveChangesAsync(cancellationToken); + await context.SaveChangesAsync(cancellationToken); } private void SetAuditables() { - IEnumerable> entries = _context.ChangeTracker.Entries(); + IEnumerable> entries = context.ChangeTracker.Entries(); foreach (EntityEntry entity in entries) { if (entity.State == EntityState.Added) @@ -52,15 +46,15 @@ public class RepositoryWrapper : IRepositoryWrapper { entity.Property(e => e.ModifiedAt) .CurrentValue = DateTime.Now; - if (_currentUserService.UserName != null) + if (currentUserService.UserName != null) entity.Property(e => e.ModifiedBy) - .CurrentValue = _currentUserService.UserName; + .CurrentValue = currentUserService.UserName; } } } public void Dispose() { _currentTransaction?.Dispose(); - _context?.Dispose(); + context?.Dispose(); } } diff --git a/Brizco.Repository/Repositories/Base/WriteRepository.cs b/Brizco.Repository/Repositories/Base/WriteRepository.cs index a56f58c..135bea6 100644 --- a/Brizco.Repository/Repositories/Base/WriteRepository.cs +++ b/Brizco.Repository/Repositories/Base/WriteRepository.cs @@ -1,15 +1,10 @@  namespace Brizco.Repository.Repositories.Base { - public class WriteRepository : Repository, IDisposable, IWriteRepository where T : class, IApiEntity + public class WriteRepository(ApplicationContext dbContext, ICurrentUserService currentUserService) + : Repository(dbContext), IDisposable, IWriteRepository + where T : class, IApiEntity { - private readonly ICurrentUserService _currentUserService; - - public WriteRepository(ApplicationContext dbContext,ICurrentUserService currentUserService) : base(dbContext) - { - _currentUserService = currentUserService; - } - public void Dispose() { DbContext?.Dispose(); @@ -54,9 +49,9 @@ namespace Brizco.Repository.Repositories.Base .CurrentValue = DateTime.Now; Entities.Entry(entity).Property(e => e.IsRemoved) .CurrentValue = true; - if (_currentUserService.UserName != null) + if (currentUserService.UserName != null) Entities.Entry(entity).Property(e => e.RemovedBy) - .CurrentValue = _currentUserService.UserName; + .CurrentValue = currentUserService.UserName; Entities.Update(entity); } @@ -70,9 +65,9 @@ namespace Brizco.Repository.Repositories.Base .CurrentValue = DateTime.Now; Entities.Entry(entity).Property(e => e.IsRemoved) .CurrentValue = true; - if (_currentUserService.UserName != null) + if (currentUserService.UserName != null) Entities.Entry(entity).Property(e => e.RemovedBy) - .CurrentValue = _currentUserService.UserName; + .CurrentValue = currentUserService.UserName; Entities.Update(entity); } } diff --git a/Brizco.Repository/Repositories/UnitOfWork/UnitOfWork.cs b/Brizco.Repository/Repositories/UnitOfWork/UnitOfWork.cs index 481ed38..5455c68 100644 --- a/Brizco.Repository/Repositories/UnitOfWork/UnitOfWork.cs +++ b/Brizco.Repository/Repositories/UnitOfWork/UnitOfWork.cs @@ -3,14 +3,9 @@ using Task = System.Threading.Tasks.Task; namespace Brizco.Repository.Repositories.UnitOfWork; -public class UnitOfWork : IUnitOfWork +public class UnitOfWork(ApplicationContext applicationContext) : IUnitOfWork { - private readonly ApplicationContext _applicationContext; private IDbContextTransaction? _currentTransaction ; - public UnitOfWork(ApplicationContext applicationContext) - { - _applicationContext = applicationContext; - } public async Task RollBackAsync() { @@ -26,17 +21,17 @@ public class UnitOfWork : IUnitOfWork } public async Task BeginTransaction() { - _currentTransaction = await _applicationContext.Database.BeginTransactionAsync(); + _currentTransaction = await applicationContext.Database.BeginTransactionAsync(); } public async Task SaveChangesAsync(CancellationToken cancellationToken = default) { SetAuditables(); - await _applicationContext.SaveChangesAsync(cancellationToken); + await applicationContext.SaveChangesAsync(cancellationToken); } private void SetAuditables() { - IEnumerable> entries = _applicationContext.ChangeTracker.Entries(); + IEnumerable> entries = applicationContext.ChangeTracker.Entries(); foreach (EntityEntry entity in entries) { if (entity.State == EntityState.Added) diff --git a/Brizco.Repository/Services/DbInitializerService.cs b/Brizco.Repository/Services/DbInitializerService.cs index 2881ecf..0bedd6c 100644 --- a/Brizco.Repository/Services/DbInitializerService.cs +++ b/Brizco.Repository/Services/DbInitializerService.cs @@ -2,38 +2,24 @@ namespace Brizco.Repository.Services; -public class DbInitializerService : IDbInitializerService +public class DbInitializerService( + ApplicationContext context, + RoleManager roleManager, + UserManager userManager, + IOptionsSnapshot adminUserSeedOptions, + ILogger logger) + : IDbInitializerService { - private readonly IOptionsSnapshot _adminUserSeedOptions; - private readonly ApplicationContext _context; - private readonly ILogger _logger; - private readonly RoleManager _roleManager; - private readonly UserManager _userManager; - - public DbInitializerService( - ApplicationContext context, - RoleManager roleManager, - UserManager userManager, - IOptionsSnapshot adminUserSeedOptions, - ILogger logger) - { - _context = context; - _roleManager = roleManager; - _userManager = userManager; - _adminUserSeedOptions = adminUserSeedOptions; - _logger = logger; - } - public void Initialize() { try { - _context.Database.Migrate(); - _logger.LogInformation("Migration SUCCESS !!!!"); + context.Database.Migrate(); + logger.LogInformation("Migration SUCCESS !!!!"); } catch (Exception e) { - _logger.LogError(e, e.Message); + logger.LogError(e, e.Message); } } @@ -43,8 +29,8 @@ public class DbInitializerService : IDbInitializerService { await SeedRoles(); - var seedAdmin = _adminUserSeedOptions.Value.UserSetting; - var user = await _userManager.FindByNameAsync(seedAdmin.Username); + var seedAdmin = adminUserSeedOptions.Value.UserSetting; + var user = await userManager.FindByNameAsync(seedAdmin.Username); if (user == null) { var adminUser = new ApplicationUser @@ -60,8 +46,8 @@ public class DbInitializerService : IDbInitializerService PhoneNumber = seedAdmin.Phone, BirthDate = DateTime.Now.AddYears(-23) }; - var adminUserResult = await _userManager.CreateAsync(adminUser, seedAdmin.Password); - if (adminUserResult.Succeeded) await _userManager.AddToRoleAsync(adminUser, seedAdmin.RoleName); + var adminUserResult = await userManager.CreateAsync(adminUser, seedAdmin.Password); + if (adminUserResult.Succeeded) await userManager.AddToRoleAsync(adminUser, seedAdmin.RoleName); } } catch (Exception e) @@ -73,8 +59,8 @@ public class DbInitializerService : IDbInitializerService public async Task SeedRoles() { - var seedAdmin = _adminUserSeedOptions.Value.UserSetting; - var managerRole = await _roleManager.FindByNameAsync(seedAdmin.RoleName); + var seedAdmin = adminUserSeedOptions.Value.UserSetting; + var managerRole = await roleManager.FindByNameAsync(seedAdmin.RoleName); if (managerRole == null) { @@ -84,9 +70,9 @@ public class DbInitializerService : IDbInitializerService EnglishName = seedAdmin.RoleName, Description = "root admin role" }; - var adminRoleResult = await _roleManager.CreateAsync(managerRole); + var adminRoleResult = await roleManager.CreateAsync(managerRole); foreach (var claim in ApplicationClaims.AllClaims) - await _roleManager.AddClaimAsync(managerRole, claim); + await roleManager.AddClaimAsync(managerRole, claim); } }