feat: introduce Shared.Contracts for account management and refactor related services
This commit is contained in:
@@ -5,6 +5,7 @@ using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.CheckoutAgg.Enums;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PersianTools.Core;
|
||||
using Shared.Contracts.Account;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Checkouts.Queries.GetUserToGropCreate;
|
||||
|
||||
@@ -14,12 +15,14 @@ namespace GozareshgirProgramManager.Application.Modules.Checkouts.Queries.GetUse
|
||||
public class GetUserToGroupCreatingQueryHandler : IBaseQueryHandler<GetUserToGroupCreatingQuery, GetUserToGroupCreatingResponse>
|
||||
{
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
private readonly IGozareshgirDbContext _gozareshgirDbContext;
|
||||
private readonly IAccountQueryService _accountQueryService;
|
||||
|
||||
public GetUserToGroupCreatingQueryHandler(IProgramManagerDbContext context, IGozareshgirDbContext gozareshgirDbContext)
|
||||
public GetUserToGroupCreatingQueryHandler(
|
||||
IProgramManagerDbContext context,
|
||||
IAccountQueryService accountQueryService)
|
||||
{
|
||||
_context = context;
|
||||
_gozareshgirDbContext = gozareshgirDbContext;
|
||||
_accountQueryService = accountQueryService;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<GetUserToGroupCreatingResponse>> Handle(GetUserToGroupCreatingQuery request, CancellationToken cancellationToken)
|
||||
@@ -50,35 +53,46 @@ public class GetUserToGroupCreatingQueryHandler : IBaseQueryHandler<GetUserToGro
|
||||
var lastMonthStart = lastMonth;
|
||||
var lastMonthEnd = lastMonth;
|
||||
|
||||
|
||||
var query =
|
||||
await (from u in _context.Users
|
||||
// دریافت لیست تنظیمات حقوق با Checkout ها
|
||||
var settingsAndCheckouts = await (
|
||||
from s in _context.SalaryPaymentSettings
|
||||
|
||||
// LEFT JOIN با Checkouts
|
||||
join ch in _context.Checkouts
|
||||
.Where(x => x.CheckoutStartDate < lastMonthStart
|
||||
&& x.CheckoutEndDate >= lastMonthStart)
|
||||
on s.AccountId equals ch.UserId into chJoin
|
||||
from ch in chJoin.DefaultIfEmpty()
|
||||
|
||||
// LEFT JOIN
|
||||
// تنظیمات حقوق
|
||||
join s in _context.SalaryPaymentSettings
|
||||
on u.Id equals s.AccountId into sJoin
|
||||
from s in sJoin.DefaultIfEmpty()
|
||||
select new
|
||||
{
|
||||
AccountId = s.AccountId,
|
||||
HasCheckout = ch != null
|
||||
})
|
||||
.GroupBy(x => x.AccountId)
|
||||
.Select(g => new
|
||||
{
|
||||
AccountId = g.Key,
|
||||
HasCheckout = g.Any(x => x.HasCheckout)
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
// LEFT JOIN
|
||||
//فیش
|
||||
join ch in _context.Checkouts
|
||||
.Where(x => x.CheckoutStartDate < lastMonthStart
|
||||
&& x.CheckoutEndDate >= lastMonthStart)
|
||||
on u.Id equals ch.UserId into chJoin
|
||||
from ch in chJoin.DefaultIfEmpty()
|
||||
// دریافت اطلاعات Account ها از AccountManagement
|
||||
var accountIds = settingsAndCheckouts.Select(x => x.AccountId).Distinct().ToList();
|
||||
var accounts = await _accountQueryService.GetProgramManagerAccountListAsync(accountIds);
|
||||
var accountsDict = accounts.ToDictionary(a => a.Id);
|
||||
|
||||
group new { s, ch } by new { u.Id, u.FullName } into g
|
||||
|
||||
select new GetUserWhoHaveSettingsAndCheckoutDto
|
||||
{
|
||||
UserId = g.Key.Id,
|
||||
FullName = g.Key.FullName,
|
||||
|
||||
HasSalarySettings = g.Any(x => x.s != null),
|
||||
HasCheckout = g.Any(x => x.ch != null)
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
// ترکیب دادهها
|
||||
var query = settingsAndCheckouts
|
||||
.Where(x => accountsDict.ContainsKey(x.AccountId))
|
||||
.Select(x => new GetUserWhoHaveSettingsAndCheckoutDto
|
||||
{
|
||||
UserId = x.AccountId,
|
||||
FullName = accountsDict[x.AccountId].Fullname,
|
||||
HasSalarySettings = true, // چون از SalaryPaymentSettings اومده پس حتماً تنظیمات داره
|
||||
HasCheckout = x.HasCheckout
|
||||
})
|
||||
.ToList();
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
|
||||
using GozareshgirProgramManager.Domain.UserAgg.Repositories;
|
||||
using Shared.Contracts.Account;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.TransferSection;
|
||||
|
||||
@@ -10,15 +10,15 @@ public class TransferSectionCommandHandler : IBaseCommandHandler<TransferSection
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ITaskSectionRepository _taskSectionRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IAccountQueryService _accountQueryService;
|
||||
|
||||
public TransferSectionCommandHandler(
|
||||
ITaskSectionRepository taskSectionRepository,
|
||||
IUserRepository userRepository,
|
||||
IAccountQueryService accountQueryService,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_taskSectionRepository = taskSectionRepository;
|
||||
_userRepository = userRepository;
|
||||
_accountQueryService = accountQueryService;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
@@ -31,16 +31,16 @@ public class TransferSectionCommandHandler : IBaseCommandHandler<TransferSection
|
||||
return OperationResult.NotFound("بخش پروژه یافت نشد");
|
||||
}
|
||||
|
||||
// بررسی وجود کاربر مبدا
|
||||
var fromUser = await _userRepository.GetByIdAsync(request.FromUserId);
|
||||
if (fromUser == null)
|
||||
// بررسی وجود حساب مبدا
|
||||
var fromAccount = await _accountQueryService.GetAccountAsync(request.FromUserId);
|
||||
if (fromAccount == null)
|
||||
{
|
||||
return OperationResult.NotFound($"کاربر مبدا با شناسه {request.FromUserId} یافت نشد");
|
||||
}
|
||||
|
||||
// بررسی وجود کاربر مقصد
|
||||
var toUser = await _userRepository.GetByIdAsync(request.ToUserId);
|
||||
if (toUser == null)
|
||||
// بررسی وجود حساب مقصد
|
||||
var toAccount = await _accountQueryService.GetAccountAsync(request.ToUserId);
|
||||
if (toAccount == null)
|
||||
{
|
||||
return OperationResult.NotFound($"کاربر مقصد با شناسه {request.ToUserId} یافت نشد");
|
||||
}
|
||||
@@ -66,4 +66,3 @@ public class TransferSectionCommandHandler : IBaseCommandHandler<TransferSection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Account;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Projects.Queries.ProjectBoardList;
|
||||
|
||||
@@ -8,11 +9,13 @@ public class ProjectBoardListQueryHandler : IBaseQueryHandler<ProjectBoardListQu
|
||||
{
|
||||
private readonly IProgramManagerDbContext _programManagerDbContext;
|
||||
private readonly IAuthHelper _authHelper;
|
||||
private readonly IAccountQueryService _accountQueryService;
|
||||
|
||||
public ProjectBoardListQueryHandler(IProgramManagerDbContext programManagerDbContext, IAuthHelper authHelper)
|
||||
public ProjectBoardListQueryHandler(IProgramManagerDbContext programManagerDbContext, IAuthHelper authHelper, IAccountQueryService accountQueryService)
|
||||
{
|
||||
_programManagerDbContext = programManagerDbContext;
|
||||
_authHelper = authHelper;
|
||||
_accountQueryService = accountQueryService;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<List<ProjectBoardListResponse>>> Handle(ProjectBoardListQuery request,
|
||||
@@ -30,10 +33,9 @@ public class ProjectBoardListQueryHandler : IBaseQueryHandler<ProjectBoardListQu
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var activityUserIds = data.SelectMany(x => x.Activities).Select(a => a.UserId).Distinct().ToList();
|
||||
var users = await _programManagerDbContext.Users.AsNoTracking()
|
||||
.Where(x => activityUserIds.Contains(x.Id))
|
||||
.Select(x => new { x.Id, x.FullName })
|
||||
.ToDictionaryAsync(x => x.Id, x => x.FullName, cancellationToken);
|
||||
// Fetch account basics in batch and map to FullName
|
||||
var accounts = await _accountQueryService.GetProgramManagerAccountListAsync(activityUserIds);
|
||||
var users = accounts.ToDictionary(a => a.Id, a => a.Fullname);
|
||||
|
||||
var result = data.Select(x =>
|
||||
{
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using DNTPersianUtils.Core;
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Application.Modules.Projects.Commands.SetTimeProject;
|
||||
using GozareshgirProgramManager.Application.Modules.Projects.DTOs;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Account;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Projects.Queries.ProjectSetTimeDetails;
|
||||
|
||||
@@ -14,10 +12,12 @@ public class ProjectSetTimeDetailsQueryHandler
|
||||
: IBaseQueryHandler<ProjectSetTimeDetailsQuery, ProjectSetTimeResponse>
|
||||
{
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
private readonly IAccountQueryService _accountQueryService;
|
||||
|
||||
public ProjectSetTimeDetailsQueryHandler(IProgramManagerDbContext context)
|
||||
public ProjectSetTimeDetailsQueryHandler(IProgramManagerDbContext context, IAccountQueryService accountQueryService)
|
||||
{
|
||||
_context = context;
|
||||
_accountQueryService = accountQueryService;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<ProjectSetTimeResponse>> Handle(ProjectSetTimeDetailsQuery request,
|
||||
@@ -36,10 +36,10 @@ public class ProjectSetTimeDetailsQueryHandler
|
||||
var userIds = task.Sections.Select(x => x.OriginalAssignedUserId)
|
||||
.Distinct().ToList();
|
||||
|
||||
var users = await _context.Users
|
||||
.Where(x => userIds.Contains(x.Id))
|
||||
.AsNoTracking()
|
||||
.ToListAsync(cancellationToken);
|
||||
// Fetch account basics in batch (instead of _context.Users)
|
||||
var accounts = await _accountQueryService.GetProgramManagerAccountListAsync(userIds);
|
||||
var accountDict = accounts.ToDictionary(a => a.Id);
|
||||
|
||||
var skillIds = task.Sections.Select(x => x.SkillId)
|
||||
.Distinct().ToList();
|
||||
|
||||
@@ -51,8 +51,8 @@ public class ProjectSetTimeDetailsQueryHandler
|
||||
var res = new ProjectSetTimeResponse(
|
||||
task.Sections.Select(ts =>
|
||||
{
|
||||
var user = users.FirstOrDefault(x => x.Id == ts.OriginalAssignedUserId);
|
||||
var skill = skills.FirstOrDefault(x => x.Id == ts.SkillId);
|
||||
var account = accountDict.GetValueOrDefault(ts.OriginalAssignedUserId);
|
||||
return new ProjectSetTimeResponseSections
|
||||
{
|
||||
AdditionalTimes = ts.AdditionalTimes
|
||||
@@ -65,7 +65,7 @@ public class ProjectSetTimeDetailsQueryHandler
|
||||
SkillName = skill?.Name ?? "",
|
||||
TotalAdditionalTime = (int)ts.GetTotalAdditionalTime().TotalHours,
|
||||
TotalEstimateTime = (int)ts.FinalEstimatedHours.TotalHours,
|
||||
UserName = user?.UserName ?? "",
|
||||
UserName = account?.Username ?? "",
|
||||
SectionId = ts.Id,
|
||||
InitialDescription = ts.InitialDescription ?? "",
|
||||
InitialTime = (int)ts.InitialEstimatedHours.TotalHours
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.PermissionAgg.Entities;
|
||||
using GozareshgirProgramManager.Domain.RoleAgg.Entities;
|
||||
using GozareshgirProgramManager.Domain.RoleAgg.Repositories;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Roles.Commands.CreateRole;
|
||||
|
||||
public class CreateRoleCommandHandler : IBaseCommandHandler<CreateRoleCommand>
|
||||
{
|
||||
private readonly IRoleRepository _roleRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public CreateRoleCommandHandler(IRoleRepository roleRepository, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_roleRepository = roleRepository;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
public async Task<OperationResult> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
if(string.IsNullOrWhiteSpace(request.RoleName))
|
||||
return OperationResult.Failure("نام نقش خالی است");
|
||||
if(!request.Permissions.Any())
|
||||
return OperationResult.Failure("هیچ دسترسی داده نشده است");
|
||||
var permissions = request.Permissions.Where(x => x > 0).Select(x => new Permission(x)).ToList();
|
||||
|
||||
var role = new Role(request.RoleName, request.GozareshgirRoleId, permissions);
|
||||
await _roleRepository.CreateAsync(role);
|
||||
await _unitOfWork.SaveChangesAsync();
|
||||
return OperationResult.Success();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public record CreateRoleCommand : IBaseCommand
|
||||
{
|
||||
public string RoleName { get; set; }
|
||||
public List<int> Permissions { get; set; }
|
||||
|
||||
public long? GozareshgirRoleId { get; set; }
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.PermissionAgg.Entities;
|
||||
using GozareshgirProgramManager.Domain.RoleAgg.Repositories;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Roles.Commands.EditRole;
|
||||
|
||||
public class EditRoleCommandHandler : IBaseCommandHandler<EditRoleCommand>
|
||||
{
|
||||
private readonly IRoleRepository _roleRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public EditRoleCommandHandler(IRoleRepository roleRepository, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_roleRepository = roleRepository;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
public async Task<OperationResult> Handle(EditRoleCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_roleRepository.Exists(x => x.RoleName == request.RoleName && x.GozareshgirRoleId != request.GozareshgirRoleId))
|
||||
return OperationResult.Failure("نام نقش تکراری است");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(request.RoleName))
|
||||
return OperationResult.Failure("نام نقش خالی است");
|
||||
|
||||
if(request.GozareshgirRoleId == null || request.GozareshgirRoleId == 0)
|
||||
return OperationResult.Failure("آی دی نقش از سمت گزارشگیر خالی است");
|
||||
|
||||
var permissions = request.Permissions.Where(x => x > 0).Select(x => new Permission(x)).ToList();
|
||||
|
||||
|
||||
var role =await _roleRepository.GetByGozareshgirRoleIdAsync(request.GozareshgirRoleId);
|
||||
|
||||
if (role != null)
|
||||
{
|
||||
role?.Edit(request.RoleName, permissions);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync();
|
||||
}
|
||||
|
||||
return OperationResult.Success();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public record EditRoleCommand : IBaseCommand
|
||||
{
|
||||
public string RoleName { get; set; }
|
||||
public List<int> Permissions { get; set; }
|
||||
|
||||
public long? GozareshgirRoleId { get; set; }
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Roles.Queries.GetRoles;
|
||||
|
||||
public class GetRolesQueryHandler : IBaseQueryHandler<GetRolesQuery, GetRolesResponse>
|
||||
{
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
|
||||
public GetRolesQueryHandler(IProgramManagerDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<GetRolesResponse>> Handle(GetRolesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = _context.Roles.AsQueryable();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.RoleName))
|
||||
query = query.Where(x => x.RoleName.Contains(request.RoleName));
|
||||
if (request.GozareshgirRoleId > 0)
|
||||
query = query.Where(x => x.GozareshgirRoleId == request.GozareshgirRoleId);
|
||||
|
||||
var roles = await query
|
||||
.Select(p => new GetRolesDto()
|
||||
{
|
||||
Id = p.Id,
|
||||
RoleName = p.RoleName,
|
||||
GozareshgirRoleId = p.GozareshgirRoleId,
|
||||
Permissions = p.Permissions.Select(x=>x.Code).ToList()
|
||||
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
if(!roles.Any())
|
||||
return OperationResult<GetRolesResponse>.NotFound("یافت نشد");
|
||||
|
||||
var response = new GetRolesResponse(
|
||||
roles
|
||||
);
|
||||
|
||||
return OperationResult<GetRolesResponse>.Success(response);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public record GetRolesQuery(string? RoleName, long? GozareshgirRoleId) : IBaseQuery<GetRolesResponse>;
|
||||
|
||||
public record GetRolesResponse(List<GetRolesDto> Role);
|
||||
|
||||
public record GetRolesDto
|
||||
{
|
||||
/// <summary>
|
||||
/// آی دی نقش
|
||||
/// </summary>
|
||||
public long Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// نام نقش
|
||||
/// </summary>
|
||||
public string RoleName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// آی دی نقش در گزارشگیر
|
||||
/// </summary>
|
||||
public long? GozareshgirRoleId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// لیست کدهای دسترسی
|
||||
/// </summary>
|
||||
public List<int> Permissions { get; set; }
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -3,60 +3,66 @@ using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Application.Modules.SalaryPaymentSettings.Commands.CreateSalarySettings;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
|
||||
using Shared.Contracts.Account;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.SalaryPaymentSettings.Queries.GetSalarySettingToEdit;
|
||||
|
||||
public class GetSalarySettingToEditQueryHandler : IBaseQueryHandler<GetSalarySettingToEditQuery, GetSalarySettingToEditResponse>
|
||||
{
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
private readonly IAccountQueryService _accountQueryService;
|
||||
|
||||
public GetSalarySettingToEditQueryHandler(IProgramManagerDbContext context)
|
||||
public GetSalarySettingToEditQueryHandler(IProgramManagerDbContext context, IAccountQueryService accountQueryService)
|
||||
{
|
||||
_context = context;
|
||||
_accountQueryService = accountQueryService;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<GetSalarySettingToEditResponse>> Handle(GetSalarySettingToEditQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user =await _context.Users.FirstOrDefaultAsync(x => x.Id == request.UserId);
|
||||
if(user == null)
|
||||
// دریافت اطلاعات حساب از AccountManagement
|
||||
var account = await _accountQueryService.GetAccountAsync(request.UserId);
|
||||
if (account == null)
|
||||
return OperationResult<GetSalarySettingToEditResponse>.NotFound("کاربر یافت نشد");
|
||||
|
||||
var editSalarySettingsList = await _context.SalaryPaymentSettings
|
||||
.Where(x => x.AccountId == request.UserId)
|
||||
.Select(x => new GetSalarySettingToEdit()
|
||||
{
|
||||
Id = x.Id,
|
||||
HolidayWorking = x.HolidayWorking,
|
||||
UserId = x.AccountId,
|
||||
MonthlySalary = x.MonthlySalary.ToMoney(),
|
||||
|
||||
WorkingHoursList = x.WorkingHoursList.Select(wh => new WorkingHoursListDto
|
||||
{
|
||||
StartShiftOne =wh.HasShiftOne ? wh.StartShiftOne.ToString(@"hh\:mm") : null,
|
||||
StartShiftOne = wh.HasShiftOne ? wh.StartShiftOne.ToString(@"hh\:mm") : null,
|
||||
EndShiftOne = wh.HasShiftOne ? wh.EndShiftOne.ToString(@"hh\:mm") : null,
|
||||
StartShiftTwo = wh.HasShiftTow ? wh.StartShiftTwo.ToString(@"hh\:mm") : null,
|
||||
EndShiftTwo = wh.HasShiftTow ? wh.EndShiftTwo.ToString(@"hh\:mm") :null,
|
||||
EndShiftTwo = wh.HasShiftTow ? wh.EndShiftTwo.ToString(@"hh\:mm") : null,
|
||||
RestTime = wh.HasRestTime ? wh.RestTime.ToString(@"hh\:mm") : null,
|
||||
HasRestTime = wh.HasRestTime,
|
||||
HasShiftOne = wh.HasShiftOne,
|
||||
HasShiftTow = wh.HasShiftTow,
|
||||
PersianDayOfWeek = wh.PersianDayOfWeek,
|
||||
IsActiveDay = wh.IsActiveDay
|
||||
}).OrderBy(wh=>wh.PersianDayOfWeek).ToList(),
|
||||
}).OrderBy(wh => wh.PersianDayOfWeek).ToList(),
|
||||
|
||||
}).FirstOrDefaultAsync(x => x.UserId == request.UserId);
|
||||
}).FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
var response = new GetSalarySettingToEditResponse(request.UserId,user.FullName,editSalarySettingsList);
|
||||
if (editSalarySettingsList == null)
|
||||
{
|
||||
return OperationResult<GetSalarySettingToEditResponse>.NotFound("تنظیمات مورد نظر یافت نشد");
|
||||
}
|
||||
|
||||
var response = new GetSalarySettingToEditResponse(request.UserId, account.Fullname, editSalarySettingsList);
|
||||
|
||||
return OperationResult<GetSalarySettingToEditResponse>.Success(response);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public record GetSalarySettingToEditResponse(long UserId, string FullName, GetSalarySettingToEdit EditSalarySettingsList);
|
||||
|
||||
public record GetSalarySettingToEditQuery(long UserId) :IBaseQuery<GetSalarySettingToEditResponse>;
|
||||
|
||||
public record GetSalarySettingToEditQuery(long UserId) : IBaseQuery<GetSalarySettingToEditResponse>;
|
||||
|
||||
public record GetSalarySettingToEdit
|
||||
{
|
||||
@@ -77,12 +83,10 @@ public record GetSalarySettingToEdit
|
||||
/// <summary>
|
||||
/// حقوق ماهانه
|
||||
/// </summary>
|
||||
public string MonthlySalary { get; set; }
|
||||
public string MonthlySalary { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// لیست روزهای هفته و ساعات کاری
|
||||
/// </summary>
|
||||
public List<WorkingHoursListDto> WorkingHoursList { get; set; }
|
||||
public List<WorkingHoursListDto> WorkingHoursList { get; set; } = new();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -4,62 +4,71 @@ using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.SalaryPaymentSettingAgg.Enums;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shared.Contracts.Account;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.SalaryPaymentSettings.Queries.GetUserListWhoHaveSettings;
|
||||
|
||||
public class GetUserListWhoHaveSettingsQueryHandler : IBaseQueryHandler<GetUserListWhoHaveSettingsQuery, GetUserListWhoHaveSettingsResponse>
|
||||
{
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
private readonly IAccountQueryService _accountQueryService;
|
||||
|
||||
public GetUserListWhoHaveSettingsQueryHandler(IProgramManagerDbContext context)
|
||||
public GetUserListWhoHaveSettingsQueryHandler(IProgramManagerDbContext context, IAccountQueryService accountQueryService)
|
||||
{
|
||||
_context = context;
|
||||
_accountQueryService = accountQueryService;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<GetUserListWhoHaveSettingsResponse>> Handle(GetUserListWhoHaveSettingsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = await (
|
||||
from u in _context.Users
|
||||
join s in _context.SalaryPaymentSettings
|
||||
on u.Id equals s.AccountId into settingsGroup
|
||||
select new GetUserWhoHaveSettingsDto
|
||||
// Get all salary settings
|
||||
var allSettings = await _context.SalaryPaymentSettings.ToListAsync(cancellationToken);
|
||||
|
||||
// Get all unique account IDs
|
||||
var accountIds = allSettings.Select(s => s.AccountId).Distinct().ToList();
|
||||
|
||||
// Get all user data in one batch through AccountQueryService
|
||||
var accounts = await _accountQueryService.GetProgramManagerAccountListAsync(accountIds);
|
||||
var accountDictionary = accounts.ToDictionary(a => a.Id, a => a);
|
||||
|
||||
// Map settings to DTOs
|
||||
var userSettingsQuery = allSettings
|
||||
.Where(setting => accountDictionary.ContainsKey(setting.AccountId))
|
||||
.Select(setting =>
|
||||
{
|
||||
UserId = u.Id,
|
||||
FullName = u.FullName,
|
||||
HasSalarySettings = settingsGroup.Any(),
|
||||
MontlySalary = settingsGroup.Any() ? settingsGroup.FirstOrDefault().MonthlySalary.ToMoney() : "",
|
||||
WeeklyWorkingTimeAvrageInt = settingsGroup
|
||||
.SelectMany(x => x.WorkingHoursList)
|
||||
.Sum(w => (int?)w.ShiftDurationInMinutes) ?? 0
|
||||
}
|
||||
).ToListAsync(cancellationToken);
|
||||
var userBasic = accountDictionary[setting.AccountId];
|
||||
return new GetUserWhoHaveSettingsDto
|
||||
{
|
||||
UserId = userBasic.Id,
|
||||
FullName = userBasic.Fullname,
|
||||
HasSalarySettings = true,
|
||||
MontlySalary = setting.MonthlySalary.ToMoney(),
|
||||
WeeklyWorkingTimeAvrageInt = setting.WorkingHoursList?.Sum(w => (int?)w.ShiftDurationInMinutes) ?? 0
|
||||
};
|
||||
})
|
||||
.ToList();
|
||||
|
||||
var list = userSettingsQuery;
|
||||
|
||||
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.FullName))
|
||||
query = query.Where(x => x.FullName.Contains(request.FullName)).ToList();
|
||||
list = list.Where(x => x.FullName.Contains(request.FullName)).ToList();
|
||||
|
||||
if (request.HasSalarySettings != HasSalarySettings.Default)
|
||||
{
|
||||
bool hasSettings = request.HasSalarySettings == HasSalarySettings.HasSettings;
|
||||
|
||||
query = query.Where(x => x.HasSalarySettings == hasSettings).ToList();
|
||||
list = list.Where(x => x.HasSalarySettings == hasSettings).ToList();
|
||||
}
|
||||
|
||||
var operationQuery = query.Select(user =>
|
||||
|
||||
var operationQuery = list.Select(user =>
|
||||
{
|
||||
var weeklyWorkingTimeAvrage = user.WeeklyWorkingTimeAvrageInt.ConvertIntDurationToHoursAndMinutes();
|
||||
|
||||
return new GetUserWhoHaveSettingsDto
|
||||
{
|
||||
UserId = user.UserId,
|
||||
FullName = user.FullName,
|
||||
HasSalarySettings = user.HasSalarySettings,
|
||||
MontlySalary = user.MontlySalary,
|
||||
WeeklyWorkingTimeAvrageInt = user.WeeklyWorkingTimeAvrageInt,
|
||||
WeeklyWorkingTimeAvrage = weeklyWorkingTimeAvrage
|
||||
};
|
||||
return user with { WeeklyWorkingTimeAvrage = weeklyWorkingTimeAvrage };
|
||||
}).ToList();
|
||||
|
||||
var response = new GetUserListWhoHaveSettingsResponse(operationQuery);
|
||||
|
||||
return OperationResult<GetUserListWhoHaveSettingsResponse>.Success(response);
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.CreateUser;
|
||||
|
||||
public record CreateUserCommand(string FullName, string UserName, string Password, string Mobile, string? Email, long? AccountId, List<long> Roles) : IBaseCommand;
|
||||
@@ -1,43 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.RoleUserAgg;
|
||||
using GozareshgirProgramManager.Domain.UserAgg.Entities;
|
||||
using GozareshgirProgramManager.Domain.UserAgg.Repositories;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.CreateUser;
|
||||
|
||||
public class CreateUserCommandHandler : IBaseCommandHandler<CreateUserCommand>
|
||||
{
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public CreateUserCommandHandler(IUnitOfWork unitOfWork, IUserRepository userRepository)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_userRepository = userRepository;
|
||||
}
|
||||
|
||||
public async Task<OperationResult> Handle(CreateUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
#region CustomValidation
|
||||
if (_userRepository.Exists(x => x.FullName == request.FullName))
|
||||
return OperationResult.Failure("نام و خانوادگی تکراری است");
|
||||
if (_userRepository.Exists(x => x.UserName == request.UserName))
|
||||
return OperationResult.Failure("نام کاربری تکراری است");
|
||||
if (_userRepository.Exists(x=> !string.IsNullOrWhiteSpace(x.Mobile) && x.Mobile == request.Mobile))
|
||||
return OperationResult.ValidationError("این شماره همراه قبلا به فرد دیگری اختصاص داده شده است");
|
||||
if(request.AccountId == 0)
|
||||
return OperationResult.Failure("آی دی اکانت، از سمت گزارشگیر صفر است");
|
||||
#endregion
|
||||
|
||||
var userRoles = request.Roles.Where(x => x > 0).Select(x => new RoleUser(x)).ToList() ;
|
||||
var create = new User(request.FullName, request.UserName, request.Password, request.Mobile,
|
||||
request.Email, request?.AccountId, userRoles);
|
||||
|
||||
await _userRepository.CreateAsync(create);
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
return OperationResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.CreateUser;
|
||||
|
||||
public class CreateUserCommandValidators : AbstractValidator<CreateUserCommand>
|
||||
{
|
||||
public CreateUserCommandValidators()
|
||||
{
|
||||
RuleFor(x => x.FullName)
|
||||
.NotEmpty()
|
||||
.NotNull()
|
||||
.WithMessage("نام و نام خانوادگی نمی تواند خالی باشد");
|
||||
|
||||
RuleFor(x => x.Mobile)
|
||||
.NotNull().NotEmpty().WithMessage("شماره همراه نمی تواند خالی باشد");
|
||||
RuleFor(x=>x.Mobile)
|
||||
.Length(11).WithMessage("طول شماره همراه می بایست 11 رقم باشد");
|
||||
RuleFor(x => x.UserName)
|
||||
.NotEmpty().NotNull().WithMessage("نام کاربری نمیتوان خالی باشد");
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.RoleUserAgg;
|
||||
using GozareshgirProgramManager.Domain.UserAgg.Repositories;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.EditUser;
|
||||
|
||||
public class EditUserCommandHandler :IBaseCommandHandler<EditUserCommand>
|
||||
{
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public EditUserCommandHandler(IUserRepository userRepository, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_userRepository = userRepository;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
public async Task<OperationResult> Handle(EditUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await _userRepository.GetByGozareshgirAccountId(request.AccountId);
|
||||
if (user != null)
|
||||
{
|
||||
var userRoles = request.Roles.Where(x => x > 0).Select(x => new RoleUser(x)).ToList();
|
||||
user.Edit(request.FullName, request.UserName, request.Mobile, userRoles, request.IsActive);
|
||||
await _unitOfWork.SaveChangesAsync();
|
||||
}
|
||||
|
||||
return OperationResult.Success();
|
||||
}
|
||||
}
|
||||
|
||||
public record EditUserCommand(string FullName, string UserName, string Mobile,long AccountId, List<long> Roles, bool IsActive) : IBaseCommand;
|
||||
@@ -1,11 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using MediatR;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.LoginUser;
|
||||
|
||||
/// <summary>
|
||||
/// دستور ورود کاربر به سیستم
|
||||
/// </summary>
|
||||
public record LoginUserCommand(long UserId) : IBaseCommand<LoginResponse>;
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.UserAgg.Entities;
|
||||
using GozareshgirProgramManager.Domain.UserAgg.Repositories;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.LoginUser;
|
||||
|
||||
/// <summary>
|
||||
/// Handler برای ورود کاربر به سیستم
|
||||
/// </summary>
|
||||
public class LoginUserCommandHandler : IRequestHandler<LoginUserCommand, OperationResult<LoginResponse>>
|
||||
{
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IUserRefreshTokenRepository _refreshTokenRepository;
|
||||
private readonly IAuthHelper _authHelper;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public LoginUserCommandHandler(
|
||||
IUserRepository userRepository,
|
||||
IAuthHelper authHelper,
|
||||
IUnitOfWork unitOfWork, IUserRefreshTokenRepository refreshTokenRepository)
|
||||
{
|
||||
_userRepository = userRepository;
|
||||
_authHelper = authHelper;
|
||||
_unitOfWork = unitOfWork;
|
||||
_refreshTokenRepository = refreshTokenRepository;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<LoginResponse>> Handle(LoginUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// اعتبارسنجی
|
||||
if (request.UserId <= 0)
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("شناسه کاربری معتبر نیست", ErrorType.BadRequest);
|
||||
}
|
||||
|
||||
// یافتن کاربر
|
||||
var user = await _userRepository.GetUserWithRolesByIdAsync(request.UserId, cancellationToken);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("کاربر یافت نشد", ErrorType.NotFound);
|
||||
}
|
||||
|
||||
// بررسی فعال بودن کاربر
|
||||
if (!user.IsActive)
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("حساب کاربری غیرفعال است", ErrorType.Unauthorized);
|
||||
}
|
||||
|
||||
// تولید توکنها با استفاده از AuthHelper
|
||||
var roles = user.RoleUser
|
||||
.Select(r => r.RoleId.ToString()).ToList();
|
||||
|
||||
var session = _authHelper.SignIn(
|
||||
user.Id,
|
||||
user.UserName,
|
||||
user.FullName,
|
||||
user.AccountId??0,
|
||||
roles);
|
||||
// دریافت اطلاعات درخواست با استفاده از AuthHelper
|
||||
var ipAddress = _authHelper.GetClientIpAddress();
|
||||
var userAgent = _authHelper.GetUserAgent();
|
||||
|
||||
// ذخیره Refresh Token در دیتابیس
|
||||
//user.AddRefreshToken(refreshToken, refreshTokenExpiration, ipAddress, userAgent);
|
||||
|
||||
var refreshTokenEntity = new UserRefreshToken(
|
||||
user.Id,
|
||||
session.RefreshToken,
|
||||
session.RefreshTokenExpiration,
|
||||
ipAddress,
|
||||
userAgent);
|
||||
|
||||
await _refreshTokenRepository.CreateAsync(refreshTokenEntity);
|
||||
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
|
||||
|
||||
// ساخت پاسخ (RefreshToken به فرانت داده نمیشود)
|
||||
var response = new LoginResponse
|
||||
{
|
||||
AccessToken = session.AccessToken,
|
||||
ExpiresAt = session.AccessTokenExpiration,
|
||||
UserId = user.Id,
|
||||
FullName = user.FullName,
|
||||
UserName = user.UserName,
|
||||
Roles = user.RoleUser.Select(r => r.RoleId).ToList()
|
||||
};
|
||||
|
||||
return OperationResult<LoginResponse>.Success(response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using MediatR;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.RefreshUserToken;
|
||||
|
||||
/// <summary>
|
||||
/// دستور تازهسازی توکن دسترسی کاربر
|
||||
/// </summary>
|
||||
public record RefreshUserTokenCommand() : IBaseCommand;
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MediatR;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.RefreshUserToken;
|
||||
|
||||
/// <summary>
|
||||
/// Handler برای تازهسازی توکن دسترسی
|
||||
/// </summary>
|
||||
public class RefreshUserTokenCommandHandler : IBaseCommandHandler<RefreshUserTokenCommand>
|
||||
{
|
||||
private readonly IAuthHelper _authHelper;
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
|
||||
public RefreshUserTokenCommandHandler(
|
||||
IAuthHelper authHelper,
|
||||
IProgramManagerDbContext context)
|
||||
{
|
||||
_authHelper = authHelper;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<OperationResult> Handle(RefreshUserTokenCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
var refreshToken = _authHelper.GetRefreshTokenFromCookie();
|
||||
|
||||
// یافتن کاربر و Refresh Token فعال از دیتابیس
|
||||
var user = await _context.Users
|
||||
.Include(u => u.RefreshTokens)
|
||||
.Include(u => u.RoleUser)
|
||||
.FirstOrDefaultAsync(u => u.RefreshTokens.Any(r=>r.Token ==refreshToken), cancellationToken);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return OperationResult<AccessTokenResponse>.Failure("کاربر یافت نشد", ErrorType.NotFound);
|
||||
}
|
||||
|
||||
// بررسی فعال بودن کاربر
|
||||
if (!user.IsActive)
|
||||
{
|
||||
return OperationResult<AccessTokenResponse>.Failure("حساب کاربری غیرفعال است", ErrorType.Unauthorized);
|
||||
}
|
||||
|
||||
// پیدا کردن Refresh Token فعال
|
||||
var activeRefreshToken = user.RefreshTokens
|
||||
.FirstOrDefault(rt => rt.Token == refreshToken && rt.IsActive);
|
||||
|
||||
if (activeRefreshToken == null)
|
||||
{
|
||||
return OperationResult<AccessTokenResponse>.Failure(
|
||||
"نشست شما منقضی شده است. لطفاً دوباره وارد شوید",
|
||||
ErrorType.Unauthorized);
|
||||
}
|
||||
|
||||
if (!activeRefreshToken.IsActive|| activeRefreshToken.IsRevoked||activeRefreshToken.IsExpired)
|
||||
{
|
||||
return OperationResult<AccessTokenResponse>.Failure(
|
||||
"نشست شما منقضی شده است. لطفاً دوباره وارد شوید",
|
||||
ErrorType.Unauthorized);
|
||||
}
|
||||
|
||||
// تولید Access Token جدید با استفاده از AuthHelper
|
||||
var roles = user.RoleUser.Select(r => r.RoleId.ToString()).ToList();
|
||||
var newAccessToken = _authHelper.GenerateAccessToken(
|
||||
user.Id,
|
||||
user.UserName,
|
||||
user.FullName,
|
||||
user.AccountId,
|
||||
roles);
|
||||
|
||||
var response = new AccessTokenResponse
|
||||
{
|
||||
AccessToken = newAccessToken,
|
||||
ExpiresAt = DateTime.UtcNow.AddMinutes(30),
|
||||
UserId = user.Id,
|
||||
FullName = user.FullName,
|
||||
UserName = user.UserName
|
||||
};
|
||||
|
||||
return OperationResult<AccessTokenResponse>.Success(response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using MediatR;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.SignOutUser;
|
||||
|
||||
/// <summary>
|
||||
/// دستور خروج کاربر از سیستم
|
||||
/// </summary>
|
||||
public record SignOutUserCommand(string RefreshToken) : IBaseCommand;
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.SignOutUser;
|
||||
|
||||
/// <summary>
|
||||
/// Handler برای خروج کاربر از سیستم
|
||||
/// </summary>
|
||||
public class SignOutUserCommandHandler : IBaseCommandHandler<SignOutUserCommand>
|
||||
{
|
||||
private readonly IAuthHelper _authHelper;
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public SignOutUserCommandHandler(
|
||||
IAuthHelper _authHelper,
|
||||
IProgramManagerDbContext context,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
this._authHelper = _authHelper;
|
||||
_context = context;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
public async Task<OperationResult> Handle(SignOutUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// دریافت UserId از Claims با استفاده از AuthHelper
|
||||
var userId = _authHelper.GetCurrentUserId();
|
||||
|
||||
if (!userId.HasValue)
|
||||
{
|
||||
return OperationResult.Failure("کاربر احراز هویت نشده است", ErrorType.Unauthorized);
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(request.RefreshToken))
|
||||
{
|
||||
return OperationResult.Failure("توکن تازهسازی یافت نشد", ErrorType.BadRequest);
|
||||
}
|
||||
|
||||
// یافتن کاربر
|
||||
var user = await _context.Users
|
||||
.Include(u => u.RefreshTokens)
|
||||
.FirstOrDefaultAsync(u => u.Id == userId.Value, cancellationToken);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return OperationResult.Failure("کاربر یافت نشد", ErrorType.NotFound);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// لغو Refresh Token
|
||||
user.RevokeRefreshToken(request.RefreshToken);
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
_authHelper.SignOut();
|
||||
|
||||
return OperationResult.Success();
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return OperationResult.Failure(ex.Message, ErrorType.BadRequest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.SsoLogin;
|
||||
|
||||
/// <summary>
|
||||
/// دستور ورود از طریق SSO با استفاده از توکن JWT
|
||||
/// </summary>
|
||||
public record SsoLoginCommand(string Token) : IBaseCommand<LoginResponse>;
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Domain._Common;
|
||||
using GozareshgirProgramManager.Domain.UserAgg.Entities;
|
||||
using GozareshgirProgramManager.Domain.UserAgg.Repositories;
|
||||
using MediatR;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Commands.SsoLogin;
|
||||
|
||||
/// <summary>
|
||||
/// Handler برای ورود از طریق SSO با استفاده از JWT Token
|
||||
/// </summary>
|
||||
public class SsoLoginCommandHandler : IRequestHandler<SsoLoginCommand, OperationResult<LoginResponse>>
|
||||
{
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IUserRefreshTokenRepository _refreshTokenRepository;
|
||||
private readonly IAuthHelper _authHelper;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public SsoLoginCommandHandler(
|
||||
IUserRepository userRepository,
|
||||
IAuthHelper authHelper,
|
||||
IUnitOfWork unitOfWork,
|
||||
IUserRefreshTokenRepository refreshTokenRepository)
|
||||
{
|
||||
_userRepository = userRepository;
|
||||
_authHelper = authHelper;
|
||||
_unitOfWork = unitOfWork;
|
||||
_refreshTokenRepository = refreshTokenRepository;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<LoginResponse>> Handle(SsoLoginCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// اعتبارسنجی
|
||||
if (string.IsNullOrWhiteSpace(request.Token))
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("توکن SSO معتبر نیست", ErrorType.BadRequest);
|
||||
}
|
||||
|
||||
// اعتبارسنجی توکن و استخراج Claims
|
||||
var principal = _authHelper.ValidateToken(request.Token);
|
||||
if (principal == null)
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("توکن SSO نامعتبر یا منقضی شده است", ErrorType.Unauthorized);
|
||||
}
|
||||
|
||||
// استخراج AccountId از Claims
|
||||
var accountIdClaim = principal.FindFirst("AccountId")?.Value;
|
||||
if (string.IsNullOrEmpty(accountIdClaim) || !long.TryParse(accountIdClaim, out var accountId))
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("AccountId در توکن یافت نشد", ErrorType.BadRequest);
|
||||
}
|
||||
|
||||
// یافتن کاربر بر اساس AccountId
|
||||
var user = await _userRepository.GetByGozareshgirAccountId(accountId);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("کاربر با AccountId مشخص شده یافت نشد", ErrorType.NotFound);
|
||||
}
|
||||
|
||||
// بررسی فعال بودن کاربر
|
||||
if (!user.IsActive)
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("حساب کاربری غیرفعال است", ErrorType.Unauthorized);
|
||||
}
|
||||
|
||||
// بارگذاری نقشهای کاربر
|
||||
user = await _userRepository.GetUserWithRolesByIdAsync(user.Id, cancellationToken);
|
||||
if (user == null)
|
||||
{
|
||||
return OperationResult<LoginResponse>.Failure("خطا در بارگذاری اطلاعات کاربر", ErrorType.InternalServerError);
|
||||
}
|
||||
|
||||
// تولید توکنهای جدید برای کاربر
|
||||
var roles = user.RoleUser
|
||||
.Select(r => r.RoleId.ToString()).ToList();
|
||||
|
||||
var session = _authHelper.SignIn(
|
||||
user.Id,
|
||||
user.UserName,
|
||||
user.FullName,
|
||||
user.AccountId ?? 0,
|
||||
roles);
|
||||
|
||||
// دریافت اطلاعات درخواست
|
||||
var ipAddress = _authHelper.GetClientIpAddress();
|
||||
var userAgent = _authHelper.GetUserAgent();
|
||||
|
||||
// ذخیره Refresh Token در دیتابیس
|
||||
var refreshTokenEntity = new UserRefreshToken(
|
||||
user.Id,
|
||||
session.RefreshToken,
|
||||
session.RefreshTokenExpiration,
|
||||
ipAddress,
|
||||
userAgent);
|
||||
|
||||
await _refreshTokenRepository.CreateAsync(refreshTokenEntity);
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// ساخت پاسخ
|
||||
var response = new LoginResponse
|
||||
{
|
||||
AccessToken = session.AccessToken,
|
||||
ExpiresAt = session.AccessTokenExpiration,
|
||||
UserId = user.Id,
|
||||
FullName = user.FullName,
|
||||
UserName = user.UserName,
|
||||
Roles = user.RoleUser.Select(r => r.RoleId).ToList()
|
||||
};
|
||||
|
||||
return OperationResult<LoginResponse>.Success(response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Queries.GetSingleUser;
|
||||
|
||||
public class GetSingleUserQueryHandler : IBaseQueryHandler<GetSingleUserQuery, GetSingleUserResponse>
|
||||
{
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
|
||||
public GetSingleUserQueryHandler(IProgramManagerDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<GetSingleUserResponse>> Handle(GetSingleUserQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.accountId))
|
||||
{
|
||||
long accountId = 0;
|
||||
try
|
||||
{
|
||||
accountId = Convert.ToInt64(request.accountId);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return (OperationResult<GetSingleUserResponse>)OperationResult.Failure("فقط عدد وارد کنید");
|
||||
}
|
||||
|
||||
|
||||
if (accountId > 0)
|
||||
{
|
||||
var user = await _context.Users
|
||||
.FirstOrDefaultAsync(x => x.AccountId == accountId);
|
||||
|
||||
|
||||
if(user != null)
|
||||
{
|
||||
List<long> roles = user.RoleUser.Select(x => x.RoleId).ToList();
|
||||
var response = new GetSingleUserResponse
|
||||
{
|
||||
FullName = user.FullName,
|
||||
UserName = user.UserName,
|
||||
ProfilePhotoPath = user.ProfilePhotoPath,
|
||||
Mobile = user.Mobile,
|
||||
IsActive = user.IsActive,
|
||||
AccountId = user.AccountId,
|
||||
Roles = roles,
|
||||
RoleListDto = await _context.Roles.Where(x => roles.Contains(x.Id)).Select(x=> new RoleListDto()
|
||||
{
|
||||
RoleName = x.RoleName,
|
||||
RoleId = x.Id,
|
||||
Permissions = x.Permissions.Select(x=>x.Code).ToList()
|
||||
}).ToListAsync(),
|
||||
};
|
||||
|
||||
return OperationResult<GetSingleUserResponse>.Success(response);
|
||||
}
|
||||
else
|
||||
{
|
||||
return (OperationResult<GetSingleUserResponse>)OperationResult.NotFound("کاربر یافت نشد");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (OperationResult<GetSingleUserResponse>)OperationResult.Failure("آی دی اکانت گزارشگیر پر نشده است");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public record GetSingleUserResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// نام و نام خانوادگی
|
||||
/// </summary>
|
||||
public string FullName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// نام کاربری
|
||||
/// </summary>
|
||||
public string UserName { get; set; }
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// مسیر عکس پروفایل
|
||||
/// </summary>
|
||||
public string ProfilePhotoPath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// شماره موبایل
|
||||
/// </summary>
|
||||
public string Mobile { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// فعال/غیر فعال بودن یوزر
|
||||
/// </summary>
|
||||
public bool IsActive { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// آی دی کاربر در گزارشگیر
|
||||
/// </summary>
|
||||
public long? AccountId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// نقش ها
|
||||
/// </summary>
|
||||
public List<long> Roles { get; set; }
|
||||
|
||||
public List<RoleListDto> RoleListDto { get; set; }
|
||||
};
|
||||
|
||||
|
||||
public record RoleListDto
|
||||
{
|
||||
public string RoleName { get; set; }
|
||||
public long RoleId { get; set; }
|
||||
public List<int> Permissions { get; set; }
|
||||
|
||||
}
|
||||
|
||||
public record GetSingleUserQuery(string? accountId) : IBaseQuery<GetSingleUserResponse>;
|
||||
@@ -1,48 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using GozareshgirProgramManager.Application.Modules.Users.Queries.GetSingleUser;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Queries.GetUserSelectList;
|
||||
|
||||
public class GetUserSelectListQueryHandler : IBaseQueryHandler<GetUserSelectListQuery, GetUserSelectListResponse>
|
||||
{
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
|
||||
public GetUserSelectListQueryHandler(IProgramManagerDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<GetUserSelectListResponse>> Handle(GetUserSelectListQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
var query = await _context.Users.Select(x => new GetUserSelectListDto()
|
||||
{
|
||||
FullName = x.FullName,
|
||||
Id = x.Id
|
||||
}).ToListAsync();
|
||||
|
||||
var response = new GetUserSelectListResponse(query);
|
||||
|
||||
|
||||
return OperationResult<GetUserSelectListResponse>.Success(response);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public record GetUserSelectListResponse(List<GetUserSelectListDto>? GetUserSelectListDto);
|
||||
|
||||
public record GetUserSelectListDto
|
||||
{
|
||||
/// <summary>
|
||||
/// نام و نام خانوادگی
|
||||
/// </summary>
|
||||
public string FullName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// آی دی کاربر
|
||||
/// </summary>
|
||||
public long Id { get; set; }
|
||||
}
|
||||
public record GetUserSelectListQuery() : IBaseQuery<GetUserSelectListResponse>;
|
||||
@@ -1,5 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Queries.GetUsers;
|
||||
|
||||
public record GetUsersQuery(string? FullName, string? UserName, string? Mobile) : IBaseQuery<GetUsersResponse>;
|
||||
@@ -1,49 +0,0 @@
|
||||
using GozareshgirProgramManager.Application._Common.Interfaces;
|
||||
using GozareshgirProgramManager.Application._Common.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Queries.GetUsers;
|
||||
|
||||
public class GetUsersQueryHandler :IBaseQueryHandler<GetUsersQuery, GetUsersResponse>
|
||||
{
|
||||
private readonly IProgramManagerDbContext _context;
|
||||
|
||||
public GetUsersQueryHandler(IProgramManagerDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<OperationResult<GetUsersResponse>> Handle(GetUsersQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = _context.Users.AsQueryable();
|
||||
|
||||
//if (request.ParentId != null)
|
||||
//{
|
||||
// query = query.Where(x => x.ParentId == request.ParentId);
|
||||
//}
|
||||
|
||||
var users = await query
|
||||
.Select(p => new GetUserDto()
|
||||
{
|
||||
|
||||
FullName = p.FullName,
|
||||
Mobile = p.Mobile,
|
||||
UserName = p.UserName,
|
||||
AccountId = p.AccountId,
|
||||
IsActive = p.IsActive,
|
||||
ProfilePhotoPath = p.ProfilePhotoPath,
|
||||
|
||||
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var response = new GetUsersResponse(
|
||||
users
|
||||
);
|
||||
|
||||
return OperationResult<GetUsersResponse>.Success(response);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
namespace GozareshgirProgramManager.Application.Modules.Users.Queries.GetUsers;
|
||||
|
||||
public record GetUsersResponse(List<GetUserDto> User);
|
||||
|
||||
public record GetUserDto
|
||||
{
|
||||
/// <summary>
|
||||
/// نام و نام خانوادگی
|
||||
/// </summary>
|
||||
public string FullName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// نام کاربری
|
||||
/// </summary>
|
||||
public string UserName { get; set; }
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// مسیر عکس پروفایل
|
||||
/// </summary>
|
||||
public string ProfilePhotoPath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// شماره موبایل
|
||||
/// </summary>
|
||||
public string Mobile { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// فعال/غیر فعال بودن یوزر
|
||||
/// </summary>
|
||||
public bool IsActive { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// آی دی کاربر در گزارشگیر
|
||||
/// </summary>
|
||||
public long? AccountId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// نقش ها
|
||||
/// </summary>
|
||||
public List<long> Roles { get; set; }
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user