fix( SetNotifyCommand )

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

View File

@ -1,7 +1,7 @@
{
"ConnectionStrings": {
"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;"
},

View File

@ -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<string>? Permissions => _httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c=>c.Value)?.ToList();
public string? UserId => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
public string? RoleName => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Role);
public string? UserName => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
public string? ComplexId => httpContextAccessor.HttpContext?.User?.FindFirstValue("ComplexId");
public string? RoleId => httpContextAccessor.HttpContext?.User?.FindFirstValue("RoleId");
public string? FullName => httpContextAccessor.HttpContext?.User?.FindFirstValue("FullName");
public List<string>? Permissions => httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c=>c.Value)?.ToList();
}

View File

@ -5,18 +5,13 @@ using Microsoft.AspNetCore.Routing.Patterns;
namespace Brizco.Api.WebFramework.Bases;
public class CrudEndpoint<TEntity,TGetAllQuery,TGetOneQuery,TCreateCommand,TUpdateCommand,TDeleteCommand> where TEntity : ApiEntity, new()
public class CrudEndpoint<TEntity, TGetAllQuery, TGetOneQuery, TCreateCommand, TUpdateCommand, TDeleteCommand>(
string endpointName)
where TEntity : ApiEntity, new()
{
private readonly string _endpointName;
public CrudEndpoint(string endpointName)
{
_endpointName = endpointName;
}
public virtual void AddRoutes(IEndpointRouteBuilder app)
{
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<TDto, TEntity> : BaseController
public class CrudController<TDto, TEntity>(IRepositoryWrapper repositoryWrapper) : BaseController
where TDto : BaseDto<TDto, TEntity>, 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<TDto, TEntity> : BaseController
}
[Authorize(AuthenticationSchemes = "Bearer")]
public class CrudController<TEntity> : BaseController
public class CrudController<TEntity>(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]

View File

@ -80,7 +80,7 @@ public static class ServiceExtensions
serviceCollection.AddDbContextFactory<ApplicationContext>(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;
});

View File

@ -12,22 +12,11 @@ public static class ExceptionHandlerMiddlewareExtensions
}
}
public class ExceptionHandlerMiddleware
{
private readonly IWebHostEnvironment _env;
private readonly ILogger<ExceptionHandlerMiddleware> _logger;
private readonly RequestDelegate _next;
public ExceptionHandlerMiddleware(
public class ExceptionHandlerMiddleware(
RequestDelegate next,
IWebHostEnvironment env,
ILogger<ExceptionHandlerMiddleware> 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<string, string>
{
@ -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<string, string>
{
@ -170,7 +159,7 @@ public class ExceptionHandlerMiddleware
httpStatusCode = HttpStatusCode.Unauthorized;
apiStatusCode = ApiResultStatusCode.UnAuthorized;
if (_env.IsDevelopment())
if (env.IsDevelopment())
{
var dic = new Dictionary<string, string>
{

View File

@ -10,28 +10,19 @@ public static class PerformanceMiddlewareExtensions
}
}
public class PerformanceMiddleware
{
private readonly ILogger<ExceptionHandlerMiddleware> _logger;
private readonly RequestDelegate _next;
private readonly Stopwatch _timer;
public PerformanceMiddleware(
public class PerformanceMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlerMiddleware> 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}");
}
}

View File

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

View File

@ -6,19 +6,7 @@ using NPOI.SS.Formula.Functions;
namespace Brizco.Core.CoreServices;
public class AccountService : IAccountService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _userSignInManager;
private readonly IJwtService _jwtService;
private readonly ICurrentUserService _currentUserService;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ISmsService _smsService;
private readonly IComplexService _complexService;
private readonly IUserService _userService;
public AccountService(
public class AccountService(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> userSignInManager,
IJwtService jwtService,
@ -27,35 +15,24 @@ public class AccountService : IAccountService
ISmsService smsService,
IComplexService complexService,
IUserService userService)
{
_userManager = userManager;
_userSignInManager = userSignInManager;
_jwtService = jwtService;
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
_smsService = smsService;
_complexService = complexService;
_userService = userService;
}
: IAccountService
{
public async Task<bool> 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<bool> 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<bool> 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<ShiftPlan>().Entities
join shift in _repositoryWrapper.SetRepository<Shift>().Entities on shiftPlan.ShiftId equals shift.Id
var query = from shiftPlan in repositoryWrapper.SetRepository<ShiftPlan>().Entities
join shift in repositoryWrapper.SetRepository<Shift>().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<PositionPermission>().Entities
join position in _repositoryWrapper.SetRepository<Position>().Entities on positionPermission.PositionId
await (from positionPermission in repositoryWrapper.SetRepository<PositionPermission>().Entities
join position in repositoryWrapper.SetRepository<Position>().Entities on positionPermission.PositionId
equals position.Id
join shiftPlaneUser in _repositoryWrapper.SetRepository<ShiftPlanUser>().Entities on position.Id equals
join shiftPlaneUser in repositoryWrapper.SetRepository<ShiftPlanUser>().Entities on position.Id equals
shiftPlaneUser.PositionId
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<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> LoginWithPasswordAsync(string userName, string password, CancellationToken cancellationToken)
{
var result = await _userSignInManager.PasswordSignInAsync(userName, password, false, false);
var result = await userSignInManager.PasswordSignInAsync(userName, password, false, false);
if (!result.Succeeded)
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<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> LoginWithVerifyCodeAsync(string userName, string verifyCode, CancellationToken cancellationToken)
{
var user = await _userManager.FindByNameAsync(userName);
var user = await userManager.FindByNameAsync(userName);
if (user == null)
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<AccessToken<ApplicationUserSDto,ComplexUserRoleSDto>> 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<ApplicationUserSDto,ComplexUserRoleSDto> 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<ComplexUser>()
var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking
.Where(c => c.Id == complexUserRole!.ComplexUserId)
.Select(ComplexUserMapper.ProjectToSDto)
.FirstOrDefaultAsync( cancellationToken);
jwt = await _jwtService.Generate<ApplicationUserSDto, ApplicationUser, ComplexUserRoleSDto>(user, complexUser!.ComplexId, complexUserRole!.RoleId);
jwt = await jwtService.Generate<ApplicationUserSDto, ApplicationUser, ComplexUserRoleSDto>(user, complexUser!.ComplexId, complexUserRole!.RoleId);
jwt.User.SelectedComplexName = complexUser.ComplexName;
jwt.User.SelectedRoleName = complexUserRole.RoleName;
jwt.User.SelectedRoleId = complexUserRole!.Id;
@ -215,16 +192,16 @@ public class AccountService : IAccountService
}
else
{
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>()
var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.TableNoTracking
.Where(mcu => mcu.UserId == user.Id)
.OrderByDescending(o => o.CreatedAt)
.Select(ComplexUserMapper.ProjectToSDto)
.FirstOrDefaultAsync(cancellationToken);
if (complexUser == null)
return (await _jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
return (await jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
var complexUserRole = await _repositoryWrapper.SetRepository<ComplexUserRole>()
var complexUserRole = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking
.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<ApplicationUserSDto, ApplicationUser>(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
await userManager.UpdateAsync(user);
jwt = (await jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
jwt.User.SelectedComplexName = complexUser.ComplexName;
jwt.User.SelectedRoleName = complexUserRole.RoleName;
jwt.User.SelectedRoleId = complexUserRole!.Id;

View File

@ -5,21 +5,14 @@ using Brizco.Domain.Entities.Users;
namespace Brizco.Core.CoreServices;
public class JwtService : IJwtService
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly SiteSettings _siteSettings;
public JwtService(
public class JwtService(
IOptionsSnapshot<SiteSettings> siteSettings,
SignInManager<ApplicationUser> userSignInManager,
RoleManager<ApplicationRole> roleManager)
{
_signInManager = userSignInManager;
_roleManager = roleManager;
_siteSettings = siteSettings.Value;
}
: IJwtService
{
private readonly SiteSettings _siteSettings = siteSettings.Value;
public async Task<AccessToken<TUser>> Generate<TUser>(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<List<Claim>> GetClaims<TUser>(TUser baseUser, string jwtId) where TUser : ApplicationUser
{
var clFac = await _signInManager.ClaimsFactory.CreateAsync(baseUser);
var clFac = await userSignInManager.ClaimsFactory.CreateAsync(baseUser);
var claims = new List<Claim>();
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<List<Claim>> GetClaims<TUser>(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<Claim>();
claims.Add(new Claim("SignUpStatus", ((int)baseUser.SignUpStatus).ToString()));
claims.Add(new Claim(ClaimTypes.Name, baseUser.UserName));

View File

@ -3,38 +3,29 @@ using Task = Brizco.Domain.Entities.Tasks.Task;
namespace Brizco.Core.CoreServices;
public class PageService : IPageService
{
private readonly ICurrentUserService _currentUserService;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly IMediator _mediator;
public PageService(
public class PageService(
ICurrentUserService currentUserService,
IRepositoryWrapper repositoryWrapper,
RoleManager<ApplicationRole> roleManager,
IMediator mediator)
{
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
_roleManager = roleManager;
_mediator = mediator;
}
: IPageService
{
private readonly RoleManager<ApplicationRole> _roleManager = roleManager;
public async Task<AppDashboardPageDto> 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<Activity>()
var todayActivities = await repositoryWrapper.SetRepository<Activity>()
.TableNoTracking
.Where(a => a.ComplexId == complexId && a.SetFor.Date == DateTime.Today.Date)
.ToListAsync(cancellationToken);
var todayShiftPlans = await _repositoryWrapper.SetRepository<ShiftPlan>()
var todayShiftPlans = await repositoryWrapper.SetRepository<ShiftPlan>()
.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<Routine>()
var hasRoutine = await repositoryWrapper.SetRepository<Routine>()
.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<Section>()
var hasSection = await repositoryWrapper.SetRepository<Section>()
.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<Position>()
var hasPosition = await repositoryWrapper.SetRepository<Position>()
.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<ComplexUser>()
var hasStaff = await repositoryWrapper.SetRepository<ComplexUser>()
.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<Shift>()
var hasShift = await repositoryWrapper.SetRepository<Shift>()
.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<Task>()
var hasTask = await repositoryWrapper.SetRepository<Task>()
.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<ShiftPlan>()
var hasStaff = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking
.AnyAsync(r => r.ComplexId == complexId, cancellationToken);
if (hasStaff)
@ -182,15 +173,15 @@ public class PageService : IPageService
public async Task<List<AppShiftingPageDayDto>> GetShiftingPageAsync(Guid routineId,CancellationToken cancellationToken = default)
{
if (_currentUserService.ComplexId == null)
if (currentUserService.ComplexId == null)
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
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<AppShiftingPageDayDto>();
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<ShiftPlan>()
var existedShiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking
.FirstOrDefaultAsync(s => s.ShiftId == shift.Id && s.PlanFor.Date == day.Date, cancellationToken);
shift.CurrentShiftPlanId = existedShiftPlan?.Id ?? default;

View File

@ -3,24 +3,19 @@ using Brizco.Domain.Entities.Tasks;
using MD.PersianDateTime.Standard;
namespace Brizco.Core.CoreServices.ReportServices;
public class ShiftPlanReportCommandHandler : IRequestHandler<ShiftPlanReportCommand, byte[]>
public class ShiftPlanReportCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<ShiftPlanReportCommand, byte[]>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public ShiftPlanReportCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<byte[]> Handle(ShiftPlanReportCommand request, CancellationToken cancellationToken)
{
var shiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>()
var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.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<Activity>()
var activities = await repositoryWrapper.SetRepository<Activity>()
.TableNoTracking
.Where(sp => sp.ShiftPlanId == shiftPlan.ShiftId && sp.SetFor.Date == shiftPlan.PlanFor.Date)
.Select(ActivityMapper.ProjectToSDto)

View File

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

View File

@ -2,16 +2,8 @@
namespace Brizco.Core.EntityServices;
public class ComplexService : IComplexService
public class ComplexService(ISender sender, RoleManager<ApplicationRole> roleManager) : IComplexService
{
private readonly ISender _sender;
private readonly RoleManager<ApplicationRole> _roleManager;
public ComplexService(ISender sender,RoleManager<ApplicationRole> roleManager)
{
_sender = sender;
_roleManager = roleManager;
}
public async Task<ComplexSDto> CreateComplexAsync(string complexName,
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<Guid>{ managerRole.Id }), cancellationToken);
var complexUser = await sender.Send(new CreateComplexUserCommand(complex.Id, managerUserId, new List<Guid>{ managerRole.Id }), cancellationToken);
return complex;
}

View File

@ -3,36 +3,20 @@ using Brizco.Domain.Entities.Users;
namespace Brizco.Core.EntityServices;
public class UserService : IUserService
{
private readonly ICurrentUserService _currentUserService;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly ISender _sender;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IJwtService _jwtService;
public UserService(ICurrentUserService currentUserService,
public class UserService(
ICurrentUserService currentUserService,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
ISender sender,
IRepositoryWrapper repositoryWrapper,
IJwtService jwtService)
{
_currentUserService = currentUserService;
_userManager = userManager;
_roleManager = roleManager;
_sender = sender;
_repositoryWrapper = repositoryWrapper;
_jwtService = jwtService;
}
: IUserService
{
public async Task<ProfileResponseDto> GetUserProfileAsync(CancellationToken cancellationToken)
{
if (!Guid.TryParse(_currentUserService.UserId, out var userId))
if (!Guid.TryParse(currentUserService.UserId, out var userId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
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<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>> ChangeUserRoleAsync(Guid roleId, CancellationToken cancellationToken)
{
if (!Guid.TryParse(_currentUserService.UserId, out var userId))
if (!Guid.TryParse(currentUserService.UserId, out var userId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
if (!Guid.TryParse(_currentUserService.ComplexId, out var complexId))
if (!Guid.TryParse(currentUserService.ComplexId, out var complexId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
AccessToken<ApplicationUserSDto, ComplexUserRoleSDto> jwt;
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>()
var complexUser = await repositoryWrapper.SetRepository<ComplexUser>()
.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<ComplexUserRole>()
var complexUserRole = await repositoryWrapper.SetRepository<ComplexUserRole>()
.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<ApplicationUserSDto, ApplicationUser>(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
await userManager.UpdateAsync(user);
jwt = (await jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user, complexUser.ComplexId, complexUserRole.RoleId)).Adapt<AccessToken<ApplicationUserSDto, ComplexUserRoleSDto>>();
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<List<ComplexUserRoleSDto>> GetUserRolesAsync(CancellationToken cancellationToken)
{
if (!Guid.TryParse(_currentUserService.UserId, out var userId))
if (!Guid.TryParse(currentUserService.UserId, out var userId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
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<ComplexUserRoleSDto>();
var complexUsers = await _repositoryWrapper.SetRepository<ComplexUser>()
var complexUsers = await repositoryWrapper.SetRepository<ComplexUser>()
.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<ComplexUserRole>()
var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking
.Where(c => c.ComplexUserId == complexUser.Id)
.Select(ComplexUserRoleMapper.ProjectToSDto)
@ -160,11 +144,11 @@ public class UserService : IUserService
public async Task<List<ComplexUserRoleSDto>> GetUserRolesAsync(Guid userId, CancellationToken cancellationToken)
{
var user = await _userManager.FindByIdAsync(userId.ToString());
var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new AppException("User NotFound", ApiResultStatusCode.NotFound);
var response = new List<ComplexUserRoleSDto>();
var complexUsers = await _repositoryWrapper.SetRepository<ComplexUser>()
var complexUsers = await repositoryWrapper.SetRepository<ComplexUser>()
.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<ComplexUserRole>()
var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking
.Where(c => c.ComplexUserId == complexUser.Id)
.Select(ComplexUserRoleMapper.ProjectToSDto)
@ -191,40 +175,40 @@ public class UserService : IUserService
public async Task<List<ComplexUserSDto>> GetUsersAsync(int page = 0, CancellationToken cancellationToken = default)
{
if (_currentUserService.ComplexId.IsNullOrEmpty())
if (currentUserService.ComplexId.IsNullOrEmpty())
throw new AppException("Wrong authorize token , ComplexId needed");
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<ApplicationUserSDto> 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<ComplexUser>().TableNoTracking
var complexUser = await repositoryWrapper.SetRepository<ComplexUser>().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<ComplexUserRole>()
var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.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<ApplicationUser> 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<bool> 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<bool> 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<bool> 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<bool> 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<List<ApplicationRole>> GetRolesAsync(int page = 0, CancellationToken cancellationToken = default)
{
if (_currentUserService.ComplexId.IsNullOrEmpty())
if (currentUserService.ComplexId.IsNullOrEmpty())
throw new AppException("Wrong authorize token , ComplexId needed");
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<RoleActionRequestDto> 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<RoleActionRequestDto>();
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<ApplicationRole> 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<bool> 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<bool> 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<ComplexUserRole>()
var complexRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking
.Where(r => r.RoleId == applicationRole.Id)
.ToListAsync();
foreach (var complexRole in complexRoles)
{
_repositoryWrapper.SetRepository<ComplexUserRole>()
repositoryWrapper.SetRepository<ComplexUserRole>()
.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;

View File

@ -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<object> 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<BaseBrew>()
var baseRecipe = await martenRepositoryWrapper.SetRepository<BaseBrew>()
.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<BaseBrew>()
var baseRecipe = await martenRepositoryWrapper.SetRepository<BaseBrew>()
.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<BaseBrew>()
var baseRecipe = await martenRepositoryWrapper.SetRepository<BaseBrew>()
.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<BaseBrew>()
await martenRepositoryWrapper.SetRepository<BaseBrew>()
.AddOrUpdateEntityAsync(baseRecipe, cancellationToken);
}
}

View File

@ -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<TData> : ApiResult
public class ApiResult<TData>(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

View File

@ -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<SetShiftPlanNotificationScheduleCommand> logger)
: IRequestHandler<SetShiftPlanNotificationScheduleCommand,bool>
public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper repositoryWrapper, IScheduler scheduler, IMediator mediator,
ILogger<SetShiftPlanNotificationScheduleCommand> logger)
: IRequestHandler<SetShiftPlanNotificationScheduleCommand, bool>
{
public async Task<bool> 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<ShiftPlanUser>()
@ -36,8 +36,6 @@ public class SetShiftPlanNotificationScheduleCommandHandler(IRepositoryWrapper r
var shiftPlanStartAt = (new DateTime(shiftPlan.PlanFor.Year, shiftPlan.PlanFor.Month, shiftPlan.PlanFor.Day, shift.StartAt.Hours, shift.StartAt.Minutes, shift.StartAt.Seconds)).ToUniversalTime();
var 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,6 +75,10 @@ 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);
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);

View File

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

View File

@ -5,32 +5,25 @@ using Task = System.Threading.Tasks.Task;
namespace Brizco.Core.QuartzServices;
public class ShiftPlanNotificationScheduledJob : IJob
public class ShiftPlanNotificationScheduledJob(
ILogger<ShiftPlanNotificationScheduledJob> logger,
IRepositoryWrapper repositoryWrapper,
IMediator mediator)
: IJob
{
private readonly ILogger<ShiftPlanNotificationScheduledJob> _logger;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
public ShiftPlanNotificationScheduledJob(ILogger<ShiftPlanNotificationScheduledJob> logger,IRepositoryWrapper repositoryWrapper,IMediator mediator)
{
_logger = logger;
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
}
public async Task Execute(IJobExecutionContext context)
{
try
{
var notifyType = (ShiftPlanNotifyType)int.Parse(context.JobDetail.Key.Name);
var shiftPlanId = Guid.Parse(context.JobDetail.Key.Group);
var shiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>().TableNoTracking
var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>().TableNoTracking
.Where(f => f.Id == shiftPlanId)
.Select(ShiftPlanMapper.ProjectToSDto)
.FirstOrDefaultAsync();
if (shiftPlan == null)
throw new Exception("Shift plan not found");
var shiftPlanUsers = await _repositoryWrapper.SetRepository<ShiftPlanUser>()
var shiftPlanUsers = await repositoryWrapper.SetRepository<ShiftPlanUser>()
.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<Activity>().TableNoTracking
var activities = await repositoryWrapper.SetRepository<Activity>().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<Activity>().TableNoTracking
var activitiesEndShift = await repositoryWrapper.SetRepository<Activity>().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<Activity>().TableNoTracking
var activities2AfterStartShift = await repositoryWrapper.SetRepository<Activity>().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);
}
}
}

View File

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

View File

@ -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<TMartenEntity> SetRepository<TMartenEntity>() where TMartenEntity : IMartenEntity
=> new MartenRepository<TMartenEntity>(_documentStore);
=> new MartenRepository<TMartenEntity>(documentStore);
}

View File

@ -2,26 +2,18 @@
namespace Brizco.Infrastructure.Services;
public class SmsService : ISmsService
{
private readonly IRestApiWrapper _restApiWrapper;
private readonly ILogger<SmsService> _logger;
private readonly IHostEnvironment _environment;
private readonly SiteSettings _siteSettings;
public SmsService(
public class SmsService(
IRestApiWrapper restApiWrapper,
IOptionsSnapshot<SiteSettings> optionsSnapshot,
ILogger<SmsService> logger,
IHostEnvironment environment)
{
_restApiWrapper = restApiWrapper;
_logger = logger;
_environment = environment;
_siteSettings = optionsSnapshot.Value;
}
: ISmsService
{
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);
}
}

View File

@ -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;

View File

@ -1,25 +1,17 @@
namespace Brizco.Repository.Handlers.Activities;
public class CreateActivityCommandHandler : IRequestHandler<CreateActivityCommand, ActivityLDto>
public class CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateActivityCommand, ActivityLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<ActivityLDto> Handle(CreateActivityCommand request, CancellationToken cancellationToken)
{
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<CreateActivityComman
activity.SetShiftPlan(request.ShiftPlanId);
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>().Add(activity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken);
repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>().Add(activity);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.CommitAsync(cancellationToken);
return activity.AdaptToLDto();
}
catch (Exception)
{
await _repositoryWrapper.RollBackAsync(cancellationToken);
await repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}

View File

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

View File

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

View File

@ -1,30 +1,22 @@
namespace Brizco.Repository.Handlers.Activities;
public class UpdateActivityCommandHandler : IRequestHandler<UpdateActivityCommand, bool>
public class UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateActivityCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdateActivityCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdateActivityCommand request, CancellationToken cancellationToken)
{
var task = await _repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
var task = await repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken);
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<UpdateActivityComman
newTask.SetUser(request.UserId);
newTask.SetShiftPlan(request.ShiftPlanId);
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>()
.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;
}
}

View File

@ -1,30 +1,24 @@
namespace Brizco.Repository.Handlers.Complexes;
public class CreateComplexCommandHandler : IRequestHandler<CreateComplexCommand, ComplexSDto>
public class CreateComplexCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateComplexCommand, ComplexSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateComplexCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
private readonly ICurrentUserService _currentUserService = currentUserService;
public async Task<ComplexSDto> 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<Complex>().Add(complex);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken);
repositoryWrapper.SetRepository<Complex>().Add(complex);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.CommitAsync(cancellationToken);
return complex.AdaptToSDto();
}
catch (Exception)
{
await _repositoryWrapper.RollBackAsync(cancellationToken);
await repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -2,24 +2,18 @@
namespace Brizco.Repository.Handlers.Complexes;
public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery, List<ComplexUserSDto>>
public class GetComplexUsersQueryHandler(
IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
: IRequestHandler<GetComplexUsersQuery, List<ComplexUserSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public GetComplexUsersQueryHandler(IRepositoryWrapper repositoryWrapper, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
_repositoryWrapper = repositoryWrapper;
_userManager = userManager;
_roleManager = roleManager;
}
public async Task<List<ComplexUserSDto>> Handle(GetComplexUsersQuery request, CancellationToken cancellationToken)
{
List<ComplexUserSDto> list = new List<ComplexUserSDto>();
if (!request.ComplexId.IsNullOrEmpty() && Guid.TryParse(request.ComplexId, out Guid complexId))
{
list = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
list = await repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.Where(c => c.ComplexId == complexId)
.OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15)
@ -28,7 +22,7 @@ public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery,
}
else
{
list = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
list = await repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15)
.Select(ComplexUserMapper.ProjectToSDto)
@ -39,13 +33,13 @@ public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery,
foreach (var complexUser in list)
{
var user = await _userManager.FindByIdAsync(complexUser.UserId.ToString());
var user = await userManager.FindByIdAsync(complexUser.UserId.ToString());
if (user != null)
{
var roleIds = await _userManager.GetRolesAsync(user);
var roleIds = await userManager.GetRolesAsync(user);
foreach (var roleId in roleIds)
{
var role = await _roleManager.FindByNameAsync(roleId);
var role = await roleManager.FindByNameAsync(roleId);
if(role!= null)
complexUser.RoleNames.Add(role.PersianName);
}

View File

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

View File

@ -1,36 +1,27 @@
namespace Brizco.Repository.Handlers.Complexes;
public class UpdateComplexUserCommandHandler : IRequestHandler<UpdateComplexUserCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public UpdateComplexUserCommandHandler(IRepositoryWrapper repositoryWrapper,
public class UpdateComplexUserCommandHandler(
IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
{
_repositoryWrapper = repositoryWrapper;
_userManager = userManager;
_roleManager = roleManager;
}
: IRequestHandler<UpdateComplexUserCommand, bool>
{
public async Task<bool> Handle(UpdateComplexUserCommand request, CancellationToken cancellationToken)
{
try
{
await _repositoryWrapper.BeginTransaction(cancellationToken);
var complexUser = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
await repositoryWrapper.BeginTransaction(cancellationToken);
var complexUser = await repositoryWrapper.SetRepository<ComplexUser>().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<ComplexUserRole>()
var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.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<UpdateComplexUser
foreach (var userRole in complexUserRoles)
{
_repositoryWrapper.SetRepository<ComplexUserRole>().Delete(userRole);
var role = await _roleManager.FindByIdAsync(userRole.RoleId.ToString());
var result = await _userManager.RemoveFromRoleAsync(user, role.Name);
repositoryWrapper.SetRepository<ComplexUserRole>().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<ComplexUserRole>().Add(userRole);
repositoryWrapper.SetRepository<ComplexUserRole>().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;
}
}

View File

@ -1,26 +1,19 @@
namespace Brizco.Repository.Handlers.Positions;
public class CreatePositionCommandHandler : IRequestHandler<CreatePositionCommand, PositionSDto>
public class CreatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreatePositionCommand, PositionSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<PositionSDto> Handle(CreatePositionCommand request, CancellationToken cancellationToken)
{
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 : IRequestHandler<CreatePositionComman
request.Permissions.ForEach(f=>entity.AddPermission(f));
_repositoryWrapper.SetRepository<Position>().Add(entity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken);
repositoryWrapper.SetRepository<Position>().Add(entity);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.CommitAsync(cancellationToken);
return entity.AdaptToSDto();
}
catch (Exception)
{
await _repositoryWrapper.RollBackAsync(cancellationToken);
await repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}

View File

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

View File

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

View File

@ -1,24 +1,17 @@
namespace Brizco.Repository.Handlers.Positions;
public class GetPositionsQueryHandler : IRequestHandler<GetPositionsQuery, List<PositionSDto>>
public class GetPositionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<GetPositionsQuery, List<PositionSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public GetPositionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<List<PositionSDto>> Handle(GetPositionsQuery request, CancellationToken cancellationToken)
{
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<Position>().TableNoTracking
var shifts = await repositoryWrapper.SetRepository<Position>().TableNoTracking
.Where(p=>p.ComplexId==complexId)
.OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15)

View File

@ -1,26 +1,18 @@
namespace Brizco.Repository.Handlers.Positions;
public class UpdatePositionCommandHandler : IRequestHandler<UpdatePositionCommand, bool>
public class UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdatePositionCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdatePositionCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Position>()
var ent = await repositoryWrapper.SetRepository<Position>()
.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<UpdatePositionComman
newPosition.CreatedAt = ent.CreatedAt;
newPosition.CreatedBy = ent.CreatedBy;
var permissionsDb = await _repositoryWrapper.SetRepository<PositionPermission>()
var permissionsDb = await repositoryWrapper.SetRepository<PositionPermission>()
.TableNoTracking
.Where(f => f.PositionId == ent.Id)
.ToListAsync(cancellationToken);
foreach (var permissionDb in permissionsDb.Where(p=>!request.Permissions.Contains(p.Permission)))
{
_repositoryWrapper.SetRepository<PositionPermission>()
repositoryWrapper.SetRepository<PositionPermission>()
.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<Position>()
repositoryWrapper.SetRepository<Position>()
.Update(newPosition);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}

View File

@ -1,37 +1,30 @@
namespace Brizco.Repository.Handlers.Routines;
public class CreateRoutineCommandHandler : IRequestHandler<CreateRoutineCommand, RoutineSDto>
public class CreateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateRoutineCommand, RoutineSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<RoutineSDto> Handle(CreateRoutineCommand request, CancellationToken cancellationToken)
{
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<Domain.Entities.Routines.Routine>().Add(entity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken);
repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>().Add(entity);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.CommitAsync(cancellationToken);
return entity.AdaptToSDto();
}
catch (Exception)
{
await _repositoryWrapper.RollBackAsync(cancellationToken);
await repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}

View File

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

View File

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

View File

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

View File

@ -1,24 +1,17 @@
namespace Brizco.Repository.Handlers.Routines;
public class GetRoutinesQueryHandler : IRequestHandler<GetRoutinesQuery, List<RoutineSDto>>
public class GetRoutinesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<GetRoutinesQuery, List<RoutineSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public GetRoutinesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<List<RoutineSDto>> Handle(GetRoutinesQuery request, CancellationToken cancellationToken)
{
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<Domain.Entities.Routines.Routine>().TableNoTracking
var entities = await repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>().TableNoTracking
.Where(p=>p.ComplexId==complexId)
.OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15)

View File

@ -1,26 +1,18 @@
namespace Brizco.Repository.Handlers.Routines;
public class UpdateRoutineCommandHandler : IRequestHandler<UpdateRoutineCommand, bool>
public class UpdateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateRoutineCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdateRoutineCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdateRoutineCommand request, CancellationToken cancellationToken)
{
var shift = await _repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
var shift = await repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
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<UpdateRoutineCommand,
newEntity.Id = request.Id;
_repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
repositoryWrapper.SetRepository<Domain.Entities.Routines.Routine>()
.Update(newEntity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}

View File

@ -1,39 +1,32 @@
namespace Brizco.Repository.Handlers.Sections;
public class CreateSectionCommandHandler : IRequestHandler<CreateSectionCommand, SectionSDto>
public class CreateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateSectionCommand, SectionSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<SectionSDto> Handle(CreateSectionCommand request, CancellationToken cancellationToken)
{
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<Section>().Add(entity);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken);
repositoryWrapper.SetRepository<Section>().Add(entity);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.CommitAsync(cancellationToken);
return entity.AdaptToSDto();
}
catch (Exception)
{
await _repositoryWrapper.RollBackAsync(cancellationToken);
await repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}

View File

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

View File

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

View File

@ -1,23 +1,16 @@
namespace Brizco.Repository.Handlers.Sections;
public class GetSectionsQueryHandler : IRequestHandler<GetSectionsQuery, List<SectionSDto>>
public class GetSectionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<GetSectionsQuery, List<SectionSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public GetSectionsQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<List<SectionSDto>> Handle(GetSectionsQuery request, CancellationToken cancellationToken)
{
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<Section>().TableNoTracking
var shifts = await repositoryWrapper.SetRepository<Section>().TableNoTracking
.Where(s=>s.ComplexId==complexId)
.OrderByDescending(s => s.CreatedAt)
.Skip(request.Page * 15).Take(15)

View File

@ -1,26 +1,18 @@
namespace Brizco.Repository.Handlers.Sections;
public class UpdateSectionCommandHandler : IRequestHandler<UpdateSectionCommand, bool>
public class UpdateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateSectionCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public UpdateSectionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(UpdateSectionCommand request, CancellationToken cancellationToken)
{
var shift = await _repositoryWrapper.SetRepository<Section>()
var shift = await repositoryWrapper.SetRepository<Section>()
.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<UpdateSectionCommand,
newSection.Id = request.Id;
_repositoryWrapper.SetRepository<Section>()
repositoryWrapper.SetRepository<Section>()
.Update(newSection);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}

View File

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

View File

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

View File

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

View File

@ -1,26 +1,19 @@
namespace Brizco.Repository.Handlers.Shifts;
public class CreateShiftCommandHandler : IRequestHandler<CreateShiftCommand, ShiftSDto>
public class CreateShiftCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateShiftCommand, ShiftSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateShiftCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<ShiftSDto> Handle(CreateShiftCommand request, CancellationToken cancellationToken)
{
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 : IRequestHandler<CreateShiftCommand, Shi
throw new AppException("روتین شیفت را انتخاب کنید");
request.Routines.ForEach(r=>shift.AddRoutine(r));
_repositoryWrapper.SetRepository<Shift>().Add(shift);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await _repositoryWrapper.CommitAsync(cancellationToken);
repositoryWrapper.SetRepository<Shift>().Add(shift);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.CommitAsync(cancellationToken);
return shift.AdaptToSDto();
}
catch (Exception)
{
await _repositoryWrapper.RollBackAsync(cancellationToken);
await repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}

View File

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

View File

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

View File

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

View File

@ -1,20 +1,13 @@
namespace Brizco.Repository.Handlers.Tasks;
public class CreateActivityCommandHandler : IRequestHandler<CreateTaskCommand, TaskLDto>
public class CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateTaskCommand, TaskLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateActivityCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<TaskLDto> Handle(CreateTaskCommand request, CancellationToken cancellationToken)
{
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 : IRequestHandler<CreateTaskCommand, T
request.Days.ForEach(d=>task.SetDay(d));
_repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>().Add(task);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>().Add(task);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return task.AdaptToLDto();
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,9 @@
namespace Brizco.Repository.Repositories.Base
{
public class BaseRepository<T> : Repository<T>, IBaseRepository<T> where T : class, IApiEntity
public class BaseRepository<T>(ApplicationContext dbContext, ICurrentUserService currentUserService)
: Repository<T>(dbContext), IBaseRepository<T>
where T : class, IApiEntity
{
private readonly ICurrentUserService _currentUserService;
public BaseRepository(ApplicationContext dbContext, ICurrentUserService currentUserService) : base(dbContext)
{
_currentUserService = currentUserService;
}
public virtual async ValueTask<T> GetByIdAsync(CancellationToken cancellationToken, params object[] ids)
{
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);
}
}

View File

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

View File

@ -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<T> SetRepository<T>() where T : ApiEntity => new BaseRepository<T>(_context, _currentUserService);
public IBaseRepository<T> SetRepository<T>() where T : ApiEntity => new BaseRepository<T>(context, currentUserService);
public async Task RollBackAsync(CancellationToken cancellationToken)
@ -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<EntityEntry<IApiEntity>> entries = _context.ChangeTracker.Entries<IApiEntity>();
IEnumerable<EntityEntry<IApiEntity>> entries = context.ChangeTracker.Entries<IApiEntity>();
foreach (EntityEntry<IApiEntity> 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();
}
}

View File

@ -1,15 +1,10 @@

namespace Brizco.Repository.Repositories.Base
{
public class WriteRepository<T> : Repository<T>, IDisposable, IWriteRepository<T> where T : class, IApiEntity
public class WriteRepository<T>(ApplicationContext dbContext, ICurrentUserService currentUserService)
: Repository<T>(dbContext), IDisposable, IWriteRepository<T>
where T : class, IApiEntity
{
private readonly ICurrentUserService _currentUserService;
public WriteRepository(ApplicationContext dbContext,ICurrentUserService currentUserService) : base(dbContext)
{
_currentUserService = currentUserService;
}
public void Dispose()
{
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);
}
}

View File

@ -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<EntityEntry<IApiEntity>> entries = _applicationContext.ChangeTracker.Entries<IApiEntity>();
IEnumerable<EntityEntry<IApiEntity>> entries = applicationContext.ChangeTracker.Entries<IApiEntity>();
foreach (EntityEntry<IApiEntity> entity in entries)
{
if (entity.State == EntityState.Added)

View File

@ -2,38 +2,24 @@
namespace Brizco.Repository.Services;
public class DbInitializerService : IDbInitializerService
{
private readonly IOptionsSnapshot<SiteSettings> _adminUserSeedOptions;
private readonly ApplicationContext _context;
private readonly ILogger<DbInitializerService> _logger;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly UserManager<ApplicationUser> _userManager;
public DbInitializerService(
public class DbInitializerService(
ApplicationContext context,
RoleManager<ApplicationRole> roleManager,
UserManager<ApplicationUser> userManager,
IOptionsSnapshot<SiteSettings> adminUserSeedOptions,
ILogger<DbInitializerService> logger)
{
_context = context;
_roleManager = roleManager;
_userManager = userManager;
_adminUserSeedOptions = adminUserSeedOptions;
_logger = logger;
}
: IDbInitializerService
{
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);
}
}