Compare commits

..

1 Commits

Author SHA1 Message Date
8faaea0a1e Add Excel export for institution contract and contracting party details
- Implement InstitutionContractDetailExcelGenerator and InstitutionContractLegalExcelGenerator for generating Excel files of contract parties (individual and legal)
- Add methods to Index.cshtml.cs to fetch and export contract party details within 6 months of contract end
- Update OnPostShiftDateNew to return contracting party Excel export
- Refactor usings to include new Excel generators
2025-11-30 15:30:43 +03:30
399 changed files with 1681 additions and 31728 deletions

View File

@@ -1,25 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_0_Framework</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="IPE.SmsIR" Version="1.2.7" />
<PackageReference Include="EPPlus" Version="8.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="10.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.3" />
<PackageReference Include="IPE.SmsIR" Version="1.0.5" />
<PackageReference Include="EPPlus" Version="7.5.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.1.34" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.4" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" />
<PackageReference Include="PersianTools.Core" Version="2.0.4" />
<PackageReference Include="System.Drawing.Common" Version="10.0.1" />
<PackageReference Include="MD.PersianDateTime.Standard" Version="2.6.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.0.1" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.1" />
<PackageReference Include="System.Drawing.Common" Version="9.0.0" />
<PackageReference Include="MD.PersianDateTime.Standard" Version="2.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="7.2.0" />

View File

@@ -198,8 +198,7 @@ public class AuthHelper : IAuthHelper
new("workshopList",workshopBson),
new("WorkshopSlug",slug),
new("WorkshopId", account.WorkshopId.ToString()),
new("WorkshopName",account.WorkshopName??""),
new("pm.userId", account.PmUserId?.ToString() ?? "0"),
new("WorkshopName",account.WorkshopName??"")
};

View File

@@ -27,12 +27,10 @@ public class AuthViewModel
#endregion
public long SubAccountId { get; set; }
public long? PmUserId { get; set; }
public AuthViewModel(long id, long roleId, string fullname, string username, string mobile,string profilePhoto,
List<int> permissions, string roleName, string adminAreaPermission, string clientAriaPermission, int? positionValue,
long subAccountId = 0,long? pmUserId = null)
List<int> permissions, string roleName, string adminAreaPermission, string clientAriaPermission, int? positionValue, long subAccountId = 0)
{
Id = id;
RoleId = roleId;
@@ -46,7 +44,6 @@ public class AuthViewModel
ClientAriaPermission = clientAriaPermission;
PositionValue = positionValue;
SubAccountId = subAccountId;
PmUserId = pmUserId;
}
public AuthViewModel()

View File

@@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _0_Framework.Application;
public static class SecretKeys
{
public static string ProgramManagerInternalApi => "JOb09$Ic3NJd0siLCJtYWMiOiI2%dmODJmNDV";
}

View File

@@ -32,7 +32,7 @@ public static class StaticWorkshopAccounts
/// 392 - عمار حسن دوست
/// 20 - سمیرا الهی نیا
/// </summary>
public static List<long> StaticAccountIds = [2, 3, 380, 381, 392, 20, 476];
public static List<long> StaticAccountIds = [2, 3, 380, 381, 392, 20];
/// <summary>
/// این تاریخ در جدول اکانت لفت ورک به این معنیست

View File

@@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using AccountManagement.Application.Contracts.Role;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace AccountManagement.Application.Contracts.Account;
@@ -36,20 +35,4 @@ public class CreateAccount
public string Email { get; set; }
public string VerifyCode { get; set; }
public string IsActiveString { get; set; }
/// <summary>
/// آیا کاربر در پروگرام منیجر فعالیت مبکند؟
/// </summary>
public bool IsProgramManagerUser { get; set; }
/// <summary>
/// لیست نقش های پروگرام منیجر
/// </summary>
public List<long> UserRoles { get; set; }
/// <summary>
/// لیست نقشهای موجود در پروگرام منیجر
/// </summary>
public SelectList RoleList { get; set; }
}

View File

@@ -1,9 +1,6 @@
using System.Collections.Generic;
namespace AccountManagement.Application.Contracts.Account;
namespace AccountManagement.Application.Contracts.Account;
public class EditAccount : CreateAccount
{
public long Id { get; set; }
}

View File

@@ -2,22 +2,15 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using AccountManagement.Application.Contracts.ProgramManager;
using Shared.Contracts.PmUser.Queries;
namespace AccountManagement.Application.Contracts.Account;
public interface IAccountApplication
{
AccountViewModel GetAccountBy(long id);
/// <summary>
/// ایجاد کاربر گزارشگیر و پروگرام منیجر
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
Task<OperationResult> Create(CreateAccount command);
OperationResult Create(CreateAccount command);
OperationResult RegisterClient(RegisterAccount command);
Task<OperationResult> Edit(EditAccount command);
OperationResult Edit(EditAccount command);
OperationResult EditClient(EditClientAccount command);
OperationResult ChangePassword(ChangePassword command);
OperationResult Login(Login command);
@@ -74,13 +67,6 @@ public interface IAccountApplication
List<AccountViewModel> GetAdminAccountsNew();
void CameraLogin(CameraLoginRequest request);
/// <summary>
/// دریافت کاربر پروگرام منیجر با اکانت آی دی
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
Task<GetPmUserDto> GetPmUserByAccountId(long accountId);
}
public class CameraLoginRequest

View File

@@ -1,20 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="10.0.1" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\0_Framework\0_Framework.csproj" />
<ProjectReference Include="..\Shared.Contracts\Shared.Contracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,28 +0,0 @@
using System.Collections.Generic;
namespace AccountManagement.Application.Contracts.ProgramManager;
public record GetPmRolesDto
{
/// <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; }
}

View File

@@ -1,11 +0,0 @@
namespace AccountManagement.Application.Contracts.ProgramManagerApiResult;
public record ApiResponse
{
public bool isSuccess { get; set; }
public string errorMessage { get; set; }
public ErrorType ErrorType { get; set; }
}

View File

@@ -1,22 +0,0 @@
using System.Collections.Generic;
namespace AccountManagement.Application.Contracts.ProgramManagerApiResult;
public record CreateProgramManagerRole
{
/// <summary>
/// نام نقش
/// </summary>
public string RoleName { get; set; }
/// <summary>
/// کدهای دسترسی
/// </summary>
public List<int> Permissions { get; set; }
/// <summary>
/// آی دی اکانت گزارشگیر
/// </summary>
public long? GozareshgirRoleId { get; set; }
};

View File

@@ -1,7 +0,0 @@
using System.Collections.Generic;
namespace AccountManagement.Application.Contracts.ProgramManagerApiResult;
public record CreateProgramManagerUser(string FullName, string UserName, string Password, string Mobile, string Email, long? AccountId, List<long> Roles);
public record EditUserCommand(string FullName, string UserName, string Mobile, long AccountId, List<long> Roles, bool IsActive);

View File

@@ -1,11 +0,0 @@
namespace AccountManagement.Application.Contracts.ProgramManagerApiResult;
public enum ErrorType
{
None,
BadRequest,
NotFound,
Unauthorized,
Validation,
InternalServerError
}

View File

@@ -1,22 +0,0 @@
using System.Collections.Generic;
namespace AccountManagement.Application.Contracts.ProgramManagerApiResult;
public class RoleResponse
{
public bool isSuccess { get; set; }
public RolesData data { get; set; }
}
public class RolesData
{
public List<RoleList> role { get; set; }
}
public class RoleList
{
public int id { get; set; }
public string roleName { get; set; }
public int gozareshgirRoleId { get; set; }
public List<int> permissions { get; set; }
}

View File

@@ -1,55 +0,0 @@
using System.Collections.Generic;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace AccountManagement.Application.Contracts.ProgramManagerApiResult;
public record SingleUserResponseResult
{
public bool isSuccess { get; set; }
public SingleUserData Data { get; set; }
};
public record SingleUserData
{
public long id { get; set; }
/// <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 string password { get; set; }
/// <summary>
/// ای دی اکانت کاربر در گزارشگیر
/// </summary>
public long? accountId { get; set; }
public List<long> Roles { get; set; }
}

View File

@@ -9,10 +9,6 @@ namespace AccountManagement.Application.Contracts.Role
[Required(ErrorMessage = ValidationMessages.IsRequired)]
public string Name { get; set; }
public List<int> Permissions { get; set; }
/// <summary>
/// لیست پرمیشن های پروگرام منیجر
/// </summary>
public List<int> PmPermissions { get; set; }
}
}

View File

@@ -1,26 +1,13 @@
using _0_Framework.Application;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Threading.Tasks;
using Shared.Contracts.PmRole.Queries;
namespace AccountManagement.Application.Contracts.Role
{
public interface IRoleApplication
{
Task<OperationResult> Create(CreateRole command);
Task<OperationResult> Edit(EditRole command);
OperationResult Create(CreateRole command);
OperationResult Edit(EditRole command);
List<RoleViewModel> List();
EditRole GetDetails(long id);
#region ProgramManager
Task<SelectList> GetPmRoleList(long? gozareshgirRoleId);
Task<List<GetPmRolesDto>> GetPmRoleListToEdit(long? gozareshgirRoleId);
#endregion
}
}

View File

@@ -1,42 +1,29 @@
using _0_Framework.Application;
using _0_Framework.Application.Sms;
using _0_Framework.Exceptions;
using System;
using System.Collections;
using _0_Framework.Application;
using AccountManagement.Application.Contracts.Account;
using AccountManagement.Application.Contracts.ProgramManagerApiResult;
using AccountManagement.Domain.AccountAgg;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using _0_Framework.Application.Sms;
using AccountManagement.Domain.AccountLeftWorkAgg;
using AccountManagement.Domain.CameraAccountAgg;
using AccountManagement.Domain.InternalApiCaller;
using AccountManagement.Domain.PmDomains.PmRoleUserAgg;
using AccountManagement.Domain.PmDomains.PmUserAgg;
using AccountManagement.Domain.PositionAgg;
using AccountManagement.Domain.RoleAgg;
using CompanyManagment.App.Contracts.Workshop;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using Company.Domain.WorkshopAgg;
using System.Security.Claims;
using _0_Framework.Exceptions;
using AccountManagement.Domain.PositionAgg;
using AccountManagement.Domain.SubAccountAgg;
using AccountManagement.Domain.SubAccountPermissionSubtitle1Agg;
using AccountManagement.Domain.SubAccountRoleAgg;
using Company.Domain._common;
using Company.Domain.WorkshopAgg;
using Company.Domain.WorkshopSubAccountAgg;
using CompanyManagment.App.Contracts.Workshop;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch.Operations;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AccountManagement.Application.Contracts.ProgramManager;
using Shared.Contracts.PmUser.Commands;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using Shared.Contracts.PmUser.Queries;
//using AccountManagement.Domain.RoleAgg;
@@ -52,19 +39,15 @@ public class AccountApplication : IAccountApplication
private readonly ISmsService _smsService;
private readonly ICameraAccountRepository _cameraAccountRepository;
private readonly IPositionRepository _positionRepository;
private readonly IAccountLeftworkRepository _accountLeftworkRepository;
private readonly IAccountLeftworkRepository _accountLeftworkRepository;
private readonly IWorkshopRepository _workshopRepository;
private readonly ISubAccountRepository _subAccountRepository;
private readonly ISubAccountRoleRepository _subAccountRoleRepository;
private readonly IWorkshopSubAccountRepository _workshopSubAccountRepository;
private readonly ISubAccountPermissionSubtitle1Repository _accountPermissionSubtitle1Repository;
private readonly IPmUserRepository _pmUserRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IPmUserQueryService _pmUserQueryService;
private readonly IPmUserCommandService _pmUserCommandService;
public AccountApplication(IAccountRepository accountRepository, IPasswordHasher passwordHasher,
IFileUploader fileUploader, IAuthHelper authHelper, IRoleRepository roleRepository, IWorker worker, ISmsService smsService, ICameraAccountRepository cameraAccountRepository, IPositionRepository positionRepository, IAccountLeftworkRepository accountLeftworkRepository, IWorkshopRepository workshopRepository, ISubAccountRepository subAccountRepository, ISubAccountRoleRepository subAccountRoleRepository, IWorkshopSubAccountRepository workshopSubAccountRepository, ISubAccountPermissionSubtitle1Repository accountPermissionSubtitle1Repository, IUnitOfWork unitOfWork, IPmUserRepository pmUserRepository, IPmUserQueryService pmUserQueryService, IPmUserCommandService pmUserCommandService)
public AccountApplication(IAccountRepository accountRepository, IPasswordHasher passwordHasher,
IFileUploader fileUploader, IAuthHelper authHelper, IRoleRepository roleRepository, IWorker worker, ISmsService smsService, ICameraAccountRepository cameraAccountRepository, IPositionRepository positionRepository, IAccountLeftworkRepository accountLeftworkRepository, IWorkshopRepository workshopRepository, ISubAccountRepository subAccountRepository, ISubAccountRoleRepository subAccountRoleRepository, IWorkshopSubAccountRepository workshopSubAccountRepository, ISubAccountPermissionSubtitle1Repository accountPermissionSubtitle1Repository)
{
_authHelper = authHelper;
_roleRepository = roleRepository;
@@ -77,14 +60,10 @@ public class AccountApplication : IAccountApplication
_subAccountRoleRepository = subAccountRoleRepository;
_workshopSubAccountRepository = workshopSubAccountRepository;
_accountPermissionSubtitle1Repository = accountPermissionSubtitle1Repository;
_unitOfWork = unitOfWork;
_pmUserRepository = pmUserRepository;
_pmUserQueryService = pmUserQueryService;
_pmUserCommandService = pmUserCommandService;
_fileUploader = fileUploader;
_passwordHasher = passwordHasher;
_accountRepository = accountRepository;
}
public OperationResult EditClient(EditClientAccount command)
@@ -113,7 +92,7 @@ public class AccountApplication : IAccountApplication
var path = $"profilePhotos";
var picturePath = _fileUploader.Upload(command.ProfilePhoto, path);
editAccount.EditClient(command.Fullname, command.Username, command.Mobile, picturePath, command.Email, command.NationalCode);
editAccount.EditClient(command.Fullname,command.Username,command.Mobile,picturePath,command.Email,command.NationalCode);
_accountRepository.SaveChanges();
return opreation.Succcedded();
}
@@ -144,7 +123,7 @@ public class AccountApplication : IAccountApplication
};
}
public async Task<OperationResult> Create(CreateAccount command)
public OperationResult Create(CreateAccount command)
{
var operation = new OperationResult();
@@ -154,57 +133,15 @@ public class AccountApplication : IAccountApplication
var password = _passwordHasher.Hash(command.Password);
var roleName = _roleRepository.GetDetails(command.RoleId);
var path = $"profilePhotos";
var picturePath = "";
if (_fileUploader != null)
{
picturePath = _fileUploader.Upload(command.ProfilePhoto, path);
var picturePath = _fileUploader.Upload(command.ProfilePhoto, path);
var account = new Account(command.Fullname, command.Username, password, command.Mobile, command.RoleId,
picturePath, roleName.Name,"true","false");
_accountRepository.Create(account);
}
var account = new Account(command.Fullname, command.Username, password, command.Mobile, command.RoleId,
picturePath, roleName.Name, "true", "false");
_unitOfWork.BeginAccountContext();
_accountRepository.Create(account);
_accountRepository.SaveChanges();
if (command.IsProgramManagerUser)
{
var pmUserRoles = command.UserRoles.Where(x => x > 0).ToList();
var createPm = await _pmUserCommandService.Create(new CreatePmUserDto(command.Fullname, command.Username, account.Password, command.Mobile,
null, account.id, pmUserRoles));
if (!createPm.isSuccess)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش کاربر پروگرام منیجر");
}
//var url = "api/user/create";
//var key = SecretKeys.ProgramManagerInternalApi;
//var response = InternalApiCaller.PostAsync<CreateProgramManagerUser, ApiResponse>(
// url,
// key,
// parameters
//);
//if (!response.Success)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Error);
//}
//if (!response.Result.isSuccess)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Result.errorMessage);
//}
}
_unitOfWork.CommitAccountContext();
return operation.Succcedded();
}
@@ -218,8 +155,8 @@ public class AccountApplication : IAccountApplication
return opreation.Failed("پر کردن تمامی فیلدها الزامی است");
if (_accountRepository.Exists(x => x.Username == command.Username))
return opreation.Failed("نام کاربری تکراری است");
if (_accountRepository.Exists(x => x.Mobile == command.Mobile && x.IsActiveString == "true"))
if (_accountRepository.Exists(x => x.Mobile == command.Mobile && x.IsActiveString =="true"))
return opreation.Failed("مقادیر وارد شده تکراری است");
//var nationalCodeValidation = command.NationalCode.NationalCodeValid();
@@ -236,14 +173,14 @@ public class AccountApplication : IAccountApplication
// break;
//}
var password = _passwordHasher.Hash(command.Password);
var register = new Account(command.Fullname, command.Username, password, command.Mobile, command.NationalCode);
var register =new Account(command.Fullname,command.Username, password, command.Mobile, command.NationalCode);
_accountRepository.Create(register);
_accountRepository.SaveChanges();
return opreation.Succcedded(register.id, message: "ثبت نام شما با موفقیت انجام شد");
return opreation.Succcedded(register.id,message: "ثبت نام شما با موفقیت انجام شد");
}
public async Task<OperationResult> Edit(EditAccount command)
public OperationResult Edit(EditAccount command)
{
var operation = new OperationResult();
var account = _accountRepository.Get(command.Id);
@@ -257,127 +194,8 @@ public class AccountApplication : IAccountApplication
var roleName = _roleRepository.GetDetails(command.RoleId);
var path = $"profilePhotos";
var picturePath = _fileUploader.Upload(command.ProfilePhoto, path);
_unitOfWork.BeginAccountContext();
account.Edit(command.Fullname, command.Username, command.Mobile, command.RoleId, picturePath, roleName.Name);
_accountRepository.SaveChanges();
var key = SecretKeys.ProgramManagerInternalApi;
//var apiResult = InternalApiCaller.GetAsync<SingleUserResponseResult>(
// $"api/user/{account.id}",
// key
//);
var userResult =await _pmUserQueryService.GetPmUserDataByAccountId(account.id);
var pmUserRoles = command.UserRoles.Where(x => x > 0).ToList();
//اگر کاربر در پروگرام منیجر قبلا ایجاد شده
if (userResult.Id >0)
{
if (!command.UserRoles.Any())
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("حداقل یک نقش باید انتخاب شود");
}
var editPm =await _pmUserCommandService.Edit(new EditPmUserDto(command.Fullname, command.Username, command.Mobile, account.id, pmUserRoles,
command.IsProgramManagerUser));
if (!editPm.isSuccess)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش کاربر پروگرام منیجر");
}
//var parameters = new EditUserCommand(
// command.Fullname,
// command.Username,
// command.Mobile,
// account.id,
// command.UserRoles,
// command.IsProgramManagerUser
//);
//var url = "api/user/edit";
//var response = InternalApiCaller.PostAsync<EditUserCommand, ApiResponse>(
// url,
// key,
// parameters
//);
//if (!response.Success)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Error);
//}
//if (!response.Result.isSuccess)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Error);
//}
}
else //اگر کاربر قبلا ایجاد نشده
{
//اگر تیک فعالیت در پروگرام منیجر روشن بود
if (command.IsProgramManagerUser)
{
if (!command.UserRoles.Any())
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("حداقل یک نقش باید انتخاب شود");
}
var createPm = await _pmUserCommandService.Create(new CreatePmUserDto(command.Fullname, command.Username, account.Password, command.Mobile,
null, account.id, pmUserRoles));
if (!createPm.isSuccess)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش کاربر پروگرام منیجر");
}
//var parameters = new CreateProgramManagerUser(
// command.Fullname,
// command.Username,
// account.Password,
// command.Mobile,
// command.Email,
// account.id,
// command.UserRoles
//);
//var url = "api/user/Create";
//var response = InternalApiCaller.PostAsync<CreateProgramManagerUser, ApiResponse>(
// url,
// key,
// parameters
//);
//if (!response.Success)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Error);
//}
//if (!response.Result.isSuccess)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Error);
//}
}
}
_unitOfWork.CommitAccountContext();
return operation.Succcedded();
}
@@ -392,18 +210,18 @@ public class AccountApplication : IAccountApplication
long idAutoriz = 0;
var operation = new OperationResult();
if (string.IsNullOrWhiteSpace(command.Password))
return operation.Failed(ApplicationMessages.EmptyPassword);
return operation.Failed(ApplicationMessages.EmptyPassword);
if (string.IsNullOrWhiteSpace(command.Username))
return operation.Failed(ApplicationMessages.EmptyUsername);
return operation.Failed(ApplicationMessages.EmptyUsername);
var account = _accountRepository.GetBy(command.Username);
var account = _accountRepository.GetBy(command.Username);
var cameraAccount = _cameraAccountRepository.GetBy(command.Username);
SubAccount subAccount = _subAccountRepository.GetBy(command.Username);
if (account == null && cameraAccount == null && subAccount == null)
return operation.Failed(ApplicationMessages.WrongUserPass);
SubAccount subAccount = _subAccountRepository.GetBy(command.Username);
if (account == null && cameraAccount == null && subAccount == null)
return operation.Failed(ApplicationMessages.WrongUserPass);
if (account != null)
if (account != null)
{
(bool Verified, bool NeedUpgrade) result = _passwordHasher.Check(account.Password, command.Password);
if (!result.Verified)
@@ -421,17 +239,14 @@ public class AccountApplication : IAccountApplication
{
positionValue = null;
}
var pmUserId = _pmUserQueryService.GetCurrentPmUserIdFromAccountId(account.id).GetAwaiter().GetResult();
var authViewModel = new AuthViewModel(account.id, account.RoleId, account.Fullname
, account.Username, account.Mobile, account.ProfilePhoto,
permissions, account.RoleName, account.AdminAreaPermission,
account.ClientAriaPermission, positionValue,0,pmUserId);
, account.Username, account.Mobile, account.ProfilePhoto, permissions, account.RoleName, account.AdminAreaPermission, account.ClientAriaPermission, positionValue);
if (account.ClientAriaPermission == "true" && account.AdminAreaPermission == "false" &&
account.IsActiveString == "true")
{
var clientPermissions = _accountPermissionSubtitle1Repository.GetAllPermissionCodes();
authViewModel.Permissions = clientPermissions;
var clientPermissions = _accountPermissionSubtitle1Repository.GetAllPermissionCodes();
authViewModel.Permissions = clientPermissions;
var workshopList = _workshopRepository.GetWorkshopsByClientAccountId(account.id).Select(x => new WorkshopClaim
{
PersonnelCount = x.PersonnelCount,
@@ -440,14 +255,14 @@ public class AccountApplication : IAccountApplication
Slug = _passwordHasher.SlugHasher(x.Id)
}).OrderByDescending(x => x.PersonnelCount).ToList();
authViewModel.WorkshopList = workshopList;
if (workshopList.Any())
{
var workshop = workshopList.First();
authViewModel.WorkshopName = workshop.Name;
authViewModel.WorkshopSlug = _passwordHasher.SlugHasher(workshop.Id);
if (workshopList.Any())
{
var workshop = workshopList.First();
authViewModel.WorkshopName = workshop.Name;
authViewModel.WorkshopSlug = _passwordHasher.SlugHasher(workshop.Id);
authViewModel.WorkshopId = workshop.Id;
}
}
}
_authHelper.Signin(authViewModel);
@@ -466,7 +281,7 @@ public class AccountApplication : IAccountApplication
var mobile = string.IsNullOrWhiteSpace(cameraAccount.Mobile) ? " " : cameraAccount.Mobile;
var authViewModel = new CameraAuthViewModel(cameraAccount.id, cameraAccount.WorkshopId,
cameraAccount.Username, mobile, cameraAccount.WorkshopName, cameraAccount.AccountId, cameraAccount.IsActiveSting);
cameraAccount.Username, mobile, cameraAccount.WorkshopName, cameraAccount.AccountId,cameraAccount.IsActiveSting);
if (cameraAccount.IsActiveSting == "true")
{
_authHelper.CameraSignIn(authViewModel);
@@ -476,41 +291,41 @@ public class AccountApplication : IAccountApplication
{
idAutoriz = 0;
}
}
if (subAccount != null)
{
(bool Verified, bool NeedUpgrade) result = _passwordHasher.Check(subAccount.Password, command.Password);
if (!result.Verified)
return operation.Failed(ApplicationMessages.WrongUserPass);
var role = _subAccountRoleRepository.Get(subAccount.SubAccountRoleId);
if (subAccount != null)
{
(bool Verified, bool NeedUpgrade) result = _passwordHasher.Check(subAccount.Password, command.Password);
if (!result.Verified)
return operation.Failed(ApplicationMessages.WrongUserPass);
var role = _subAccountRoleRepository.Get(subAccount.SubAccountRoleId);
var permissions = role.RolePermissions.Select(x => x.PermissionCode).ToList();
var authViewModel = new AuthViewModel(subAccount.AccountId, subAccount.SubAccountRoleId, subAccount.FullName
, subAccount.Username, subAccount.PhoneNumber, "", permissions, role.Title, "false",
"true", 0, subAccount.id);
var workshopList = _workshopSubAccountRepository.GetWorkshopsBySubAccountId(subAccount.id);
authViewModel.WorkshopList = workshopList.Select(x => new WorkshopClaim()
{
Slug = _passwordHasher.SlugHasher(x.WorkshopId),
Name = x.WorkshopName,
PersonnelCount = x.PersonnelCount,
Id = x.WorkshopId
}).ToList();
var permissions = role.RolePermissions.Select(x => x.PermissionCode).ToList();
var authViewModel = new AuthViewModel(subAccount.AccountId, subAccount.SubAccountRoleId, subAccount.FullName
, subAccount.Username, subAccount.PhoneNumber, "", permissions, role.Title, "false",
"true", 0, subAccount.id);
var workshopList = _workshopSubAccountRepository.GetWorkshopsBySubAccountId(subAccount.id);
authViewModel.WorkshopList = workshopList.Select(x => new WorkshopClaim()
{
Slug = _passwordHasher.SlugHasher(x.WorkshopId),
Name = x.WorkshopName,
PersonnelCount = x.PersonnelCount,
Id = x.WorkshopId
}).ToList();
if (workshopList.Any())
{
var workshop = workshopList.First();
authViewModel.WorkshopName = workshop.WorkshopName;
authViewModel.WorkshopSlug = _passwordHasher.SlugHasher(workshop.WorkshopId);
if (workshopList.Any())
{
var workshop = workshopList.First();
authViewModel.WorkshopName = workshop.WorkshopName;
authViewModel.WorkshopSlug = _passwordHasher.SlugHasher(workshop.WorkshopId);
authViewModel.WorkshopId = workshop.WorkshopId;
}
_authHelper.Signin(authViewModel);
idAutoriz = 2;
}
}
_authHelper.Signin(authViewModel);
idAutoriz = 2;
}
return operation.Succcedded(idAutoriz);
return operation.Succcedded(idAutoriz);
}
public OperationResult LoginWithMobile(long id)
{
@@ -541,24 +356,24 @@ public class AccountApplication : IAccountApplication
if (account.ClientAriaPermission == "true" && account.AdminAreaPermission == "false" &&
account.IsActiveString == "true")
{
var clientPermissions = _accountPermissionSubtitle1Repository.GetAllPermissionCodes();
authViewModel.Permissions = clientPermissions;
var workshopList = _workshopRepository.GetWorkshopsByClientAccountId(account.id).Select(x => new WorkshopClaim
{
PersonnelCount = x.PersonnelCount,
Id = x.Id,
Name = x.WorkshopFullName,
Slug = _passwordHasher.SlugHasher(x.Id)
}).OrderByDescending(x => x.PersonnelCount).ToList();
authViewModel.WorkshopList = workshopList;
if (workshopList.Any())
{
var workshop = workshopList.First();
authViewModel.WorkshopName = workshop.Name;
authViewModel.WorkshopSlug = _passwordHasher.SlugHasher(workshop.Id);
var clientPermissions = _accountPermissionSubtitle1Repository.GetAllPermissionCodes();
authViewModel.Permissions = clientPermissions;
var workshopList = _workshopRepository.GetWorkshopsByClientAccountId(account.id).Select(x => new WorkshopClaim
{
PersonnelCount = x.PersonnelCount,
Id = x.Id,
Name = x.WorkshopFullName,
Slug = _passwordHasher.SlugHasher(x.Id)
}).OrderByDescending(x => x.PersonnelCount).ToList();
authViewModel.WorkshopList = workshopList;
if (workshopList.Any())
{
var workshop = workshopList.First();
authViewModel.WorkshopName = workshop.Name;
authViewModel.WorkshopSlug = _passwordHasher.SlugHasher(workshop.Id);
authViewModel.WorkshopId = workshop.Id;
}
}
}
}
_authHelper.Signin(authViewModel);
long idAutoriz = 0;
@@ -614,7 +429,7 @@ public class AccountApplication : IAccountApplication
return _accountRepository.GetByUserNameAndId(id, username);
}
public async Task<OperationResult> SetVerifyCode(string phone, long id)
public async Task <OperationResult> SetVerifyCode(string phone, long id)
{
var operation = new OperationResult();
var account = _accountRepository.Get(id);
@@ -628,11 +443,11 @@ public class AccountApplication : IAccountApplication
_smsService.LoginSend(phone, r);
//TimeSpan delay = TimeSpan.FromSeconds(30);
await _accountRepository.RemoveCode(id);
return operation.Succcedded();
}
@@ -683,67 +498,67 @@ public class AccountApplication : IAccountApplication
.Select(x => x.Code)
.ToList();
_authHelper.SignOut();
var authViewModel = new AuthViewModel(account.id, account.RoleId, account.Fullname
, account.Username, account.Mobile, account.ProfilePhoto, permissions, account.RoleName, "false", "true", null);
var workshopList = _workshopRepository.GetWorkshopsByClientAccountId(account.id).Select(x => new WorkshopClaim
{
PersonnelCount = x.PersonnelCount,
Id = x.Id,
Name = x.WorkshopFullName,
Slug = _passwordHasher.SlugHasher(x.Id)
}).OrderByDescending(x => x.PersonnelCount).ToList();
, account.Username, account.Mobile, account.ProfilePhoto, permissions, account.RoleName, "false", "true",null);
var workshopList = _workshopRepository.GetWorkshopsByClientAccountId(account.id).Select(x => new WorkshopClaim
{
PersonnelCount = x.PersonnelCount,
Id = x.Id,
Name = x.WorkshopFullName,
Slug = _passwordHasher.SlugHasher(x.Id)
}).OrderByDescending(x => x.PersonnelCount).ToList();
authViewModel.WorkshopList = workshopList;
authViewModel.WorkshopList = workshopList;
var clientPermissions = _accountPermissionSubtitle1Repository.GetAllPermissionCodes();
var clientPermissions = _accountPermissionSubtitle1Repository.GetAllPermissionCodes();
authViewModel.Permissions = clientPermissions;
if (authViewModel.WorkshopList.Any())
{
var workshop = authViewModel.WorkshopList.First();
authViewModel.WorkshopSlug = _passwordHasher.SlugHasher(workshop.Id);
authViewModel.WorkshopName = workshop.Name;
if (authViewModel.WorkshopList.Any())
{
var workshop = authViewModel.WorkshopList.First();
authViewModel.WorkshopSlug = _passwordHasher.SlugHasher(workshop.Id);
authViewModel.WorkshopName = workshop.Name;
authViewModel.WorkshopId = workshop.Id;
}
_authHelper.Signin(authViewModel);
}
_authHelper.Signin(authViewModel);
return operation.Succcedded(2);
}
public OperationResult DirectCameraLogin(long cameraAccountId)
{
var prAcc = _authHelper.CurrentAccountInfo();
var operation = new OperationResult();
var cameraAccount = _cameraAccountRepository.GetById(cameraAccountId);
if (cameraAccount == null)
return operation.Failed("این اکانت وجود ندارد");
var prAcc = _authHelper.CurrentAccountInfo();
var operation = new OperationResult();
var cameraAccount = _cameraAccountRepository.GetById(cameraAccountId);
if (cameraAccount == null)
return operation.Failed("این اکانت وجود ندارد");
_authHelper.SignOut();
_authHelper.SignOut();
var mobile = string.IsNullOrWhiteSpace(cameraAccount.Mobile) ? " " : cameraAccount.Mobile;
var authViewModel = new CameraAuthViewModel(cameraAccount.id, cameraAccount.WorkshopId,
cameraAccount.Username, mobile, cameraAccount.WorkshopName, cameraAccount.AccountId, cameraAccount.IsActiveSting);
if (cameraAccount.IsActiveSting == "true")
{
_authHelper.CameraSignIn(authViewModel);
}
else
{
return operation.Failed("این اکانت غیر فعال شده است");
}
return operation.Succcedded(2);
var mobile = string.IsNullOrWhiteSpace(cameraAccount.Mobile) ? " " : cameraAccount.Mobile;
var authViewModel = new CameraAuthViewModel(cameraAccount.id, cameraAccount.WorkshopId,
cameraAccount.Username, mobile, cameraAccount.WorkshopName, cameraAccount.AccountId, cameraAccount.IsActiveSting);
if (cameraAccount.IsActiveSting == "true")
{
_authHelper.CameraSignIn(authViewModel);
}
else
{
return operation.Failed("این اکانت غیر فعال شده است");
}
return operation.Succcedded(2);
}
public AccountLeftWorkViewModel WorkshopList(long accountId)
{
string fullname = this._accountRepository.GetById(accountId).Fullname;
List<WorkshopAccountlistViewModel> source = _accountLeftworkRepository.WorkshopList(accountId);
List<WorkshopAccountlistViewModel> source =_accountLeftworkRepository.WorkshopList(accountId);
List<long> userWorkshopIds = source.Select(x => x.WorkshopId).ToList();
List<WorkshopSelectList> allWorkshops = this._accountLeftworkRepository.GetAllWorkshops();
List<AccountViewModel> accountSelectList = this._accountRepository.GetAdminAccountSelectList();
@@ -826,65 +641,65 @@ public class AccountApplication : IAccountApplication
#region Pooya
public OperationResult IsPhoneNumberAndPasswordValid(long accountId, string phoneNumber, string password, string rePassword)
{
OperationResult op = new();
OperationResult op = new();
var entity = _accountRepository.Get(accountId);
var entity = _accountRepository.Get(accountId);
if (entity == null)
return op.Failed(ApplicationMessages.RecordNotFound);
if (entity == null)
return op.Failed(ApplicationMessages.RecordNotFound);
if (!string.IsNullOrWhiteSpace(rePassword) || !string.IsNullOrWhiteSpace(password))
{
if (rePassword != password)
return op.Failed("تکرار رمز عبور با رمز عبور مطابقت ندارد");
if (!string.IsNullOrWhiteSpace(rePassword) || !string.IsNullOrWhiteSpace(password))
{
if (rePassword != password)
return op.Failed("تکرار رمز عبور با رمز عبور مطابقت ندارد");
if (password.Length < 8)
return op.Failed("رمز عبور نمی تواند کمتر از 8 کاراکتر باشد");
}
if (password.Length < 8)
return op.Failed("رمز عبور نمی تواند کمتر از 8 کاراکتر باشد");
}
if ((string.IsNullOrWhiteSpace(phoneNumber) || entity.Mobile == phoneNumber) && string.IsNullOrWhiteSpace(rePassword))
return op.Failed("چیزی برای تغییر وجود ندارد");
if ((string.IsNullOrWhiteSpace(phoneNumber) || entity.Mobile == phoneNumber) && string.IsNullOrWhiteSpace(rePassword))
return op.Failed("چیزی برای تغییر وجود ندارد");
if (!string.IsNullOrWhiteSpace(phoneNumber) && entity.Mobile != phoneNumber)
{
phoneNumber = phoneNumber.Trim();
if (phoneNumber.Length != 11)
return op.Failed("شماره تلفن همراه به درستی وارد نشده است");
if (_accountRepository.Exists(x => x.Mobile == phoneNumber && x.id != accountId) ||
_subAccountRepository.Exists(x => x.PhoneNumber == phoneNumber) ||
_cameraAccountRepository.Exists(x => x.Mobile == phoneNumber))
return op.Failed("قبلا یک حساب با این شماره ثبت شده است");
}
if (!string.IsNullOrWhiteSpace(phoneNumber) && entity.Mobile != phoneNumber)
{
phoneNumber = phoneNumber.Trim();
if (phoneNumber.Length != 11)
return op.Failed("شماره تلفن همراه به درستی وارد نشده است");
if (_accountRepository.Exists(x => x.Mobile == phoneNumber && x.id != accountId) ||
_subAccountRepository.Exists(x => x.PhoneNumber == phoneNumber) ||
_cameraAccountRepository.Exists(x => x.Mobile == phoneNumber))
return op.Failed("قبلا یک حساب با این شماره ثبت شده است");
}
return op.Succcedded();
}
return op.Succcedded();
}
public OperationResult ChangePasswordAndPhoneNumber(AccountChangePasswordAndPhoneNumber command)
{
OperationResult op = new();
command.PhoneNumber = command.PhoneNumber.Trim();
var entity = _accountRepository.Get(command.AccountId);
if (entity == null)
return op.Failed(ApplicationMessages.RecordNotFound);
var validationResult = IsPhoneNumberAndPasswordValid(command.AccountId, command.PhoneNumber, command.Password, command.RePassword);
if (validationResult.IsSuccedded == false)
return validationResult;
OperationResult op = new();
command.PhoneNumber = command.PhoneNumber.Trim();
var entity = _accountRepository.Get(command.AccountId);
if (entity == null)
return op.Failed(ApplicationMessages.RecordNotFound);
var validationResult = IsPhoneNumberAndPasswordValid(command.AccountId, command.PhoneNumber, command.Password, command.RePassword);
if (validationResult.IsSuccedded == false)
return validationResult;
if (!string.IsNullOrWhiteSpace(command.RePassword))
{
if (!string.IsNullOrWhiteSpace(command.RePassword))
{
entity.ChangePassword(_passwordHasher.Hash(command.Password));
}
entity.ChangePassword(_passwordHasher.Hash(command.Password));
}
if (!string.IsNullOrWhiteSpace(command.PhoneNumber))
{
entity.Edit(entity.Fullname, entity.Username, command.PhoneNumber, entity.RoleId, entity.ProfilePhoto, entity.RoleName);
}
_accountRepository.SaveChanges();
return op.Succcedded();
}
if (!string.IsNullOrWhiteSpace(command.PhoneNumber))
{
entity.Edit(entity.Fullname, entity.Username, command.PhoneNumber, entity.RoleId, entity.ProfilePhoto, entity.RoleName);
}
_accountRepository.SaveChanges();
return op.Succcedded();
}
//public UserClaimsResponseDTO GetClaimsForSignIn(Login command)
//{
// var operation = new OperationResult();
@@ -1000,12 +815,12 @@ public class AccountApplication : IAccountApplication
}
(bool Verified, bool NeedUpgrade) result = _passwordHasher.Check(cameraAccount.Password, request.Password);
if (!result.Verified)
throw new BadRequestException(ApplicationMessages.WrongUserPass);
var mobile = string.IsNullOrWhiteSpace(cameraAccount.Mobile) ? " " : cameraAccount.Mobile;
var authViewModel = new CameraAuthViewModel(cameraAccount.id, cameraAccount.WorkshopId,
cameraAccount.Username, mobile, cameraAccount.WorkshopName, cameraAccount.AccountId,
cameraAccount.IsActiveSting);
@@ -1014,9 +829,4 @@ public class AccountApplication : IAccountApplication
_authHelper.CameraSignIn(authViewModel);
}
public async Task<GetPmUserDto> GetPmUserByAccountId(long accountId)
{
return await _pmUserRepository.GetPmUserByAccountId(accountId);
}
}

View File

@@ -1,14 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AccountManagement.Application.Contracts\AccountManagement.Application.Contracts.csproj" />
<ProjectReference Include="..\AccountManagement.Domain\AccountManagement.Domain.csproj" />
<ProjectReference Include="..\Company.Domain\Company.Domain.csproj" />
<ProjectReference Include="..\Shared.Contracts\Shared.Contracts.csproj" />
</ItemGroup>

View File

@@ -2,106 +2,39 @@
using AccountManagement.Application.Contracts.Role;
using AccountManagement.Domain.RoleAgg;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AccountManagement.Application.Contracts.ProgramManagerApiResult;
using AccountManagement.Domain.InternalApiCaller;
using Company.Domain._common;
using AccountManagement.Application.Contracts.Ticket;
using AccountManagement.Domain.PmDomains.PmPermissionAgg;
using AccountManagement.Domain.PmDomains.PmRoleAgg;
using AccountManagement.Domain.PmDomains.PmUserAgg;
using Microsoft.AspNetCore.Mvc.Rendering;
using Shared.Contracts.PmRole.Commands;
using GetPmRolesDto = Shared.Contracts.PmRole.Queries.GetPmRolesDto;
using Role = AccountManagement.Domain.RoleAgg.Role;
using Shared.Contracts.PmRole.Queries;
namespace AccountManagement.Application;
public class RoleApplication : IRoleApplication
{
private readonly IRoleRepository _roleRepository;
private readonly IPmRoleRepository _pmRoleRepository;
private readonly IPmUserRepository _pmUserRepository;
private readonly IPmRoleQueryService _pmRoleQueryService;
private readonly IPmRoleCommandService _pmRoleCommandService;
private readonly IUnitOfWork _unitOfWork;
public RoleApplication(IRoleRepository roleRepository, IUnitOfWork unitOfWork, IPmRoleRepository pmRoleRepository, IPmUserRepository pmUserRepository, IPmRoleQueryService pmRoleQueryService, IPmRoleCommandService pmRoleCommandService)
public RoleApplication(IRoleRepository roleRepository)
{
_roleRepository = roleRepository;
_unitOfWork = unitOfWork;
_pmRoleRepository = pmRoleRepository;
_pmUserRepository = pmUserRepository;
_pmRoleQueryService = pmRoleQueryService;
_pmRoleCommandService = pmRoleCommandService;
}
public async Task<OperationResult> Create(CreateRole command)
public OperationResult Create(CreateRole command)
{
var operation = new OperationResult();
if (_roleRepository.Exists(x => x.Name == command.Name))
return operation.Failed(ApplicationMessages.DuplicatedRecord);
var permissions = command.Permissions.Where(x => x > 0).Select(x => new Permission(x)).ToList();
var permissions = new List<Permission>();
foreach (var code in command.Permissions)
{
if (code > 0)
{
permissions.Add(new Permission(code));
}
}
//command.Permissions.ForEach(code => permissions.Add(new Permission(code)));
var role = new Role(command.Name, permissions);
_unitOfWork.BeginAccountContext();
_roleRepository.Create(role);
_roleRepository.SaveChanges();
var pmPermissions = command.PmPermissions.Where(x => x > 0).ToList();
if (pmPermissions.Any())
{
var pmRole = new CreatePmRoleDto{ RoleName = command.Name, Permissions = pmPermissions, GozareshgirRoleId = role.id};
var res =await _pmRoleCommandService.Create(pmRole);
if (!res.Item1)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش دسترسی ها در پروگرام منیجر");
}
//var parameters = new CreateProgramManagerRole
//{
// RoleName = command.Name,
// Permissions = pmPermissions,
// GozareshgirRoleId = role.id
//};
//var url = "api/role";
//var key = SecretKeys.ProgramManagerInternalApi;
//var response = InternalApiCaller.PostAsync<CreateProgramManagerRole, ApiResponse>(
// url,
// key,
// parameters
//);
//if (!response.Success)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed("ارتباط با اپلیکیش پروگرام منیجر برقرار نشد");
//}
//if (!response.Result.isSuccess)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Result.errorMessage);
//}
}
//command.Permissions.ForEach(code => permissions.Add(new Permission(code)));
_unitOfWork.CommitAccountContext();
return operation.Succcedded();
}
public async Task<OperationResult> Edit(EditRole command)
public OperationResult Edit(EditRole command)
{
var operation = new OperationResult();
var role = _roleRepository.Get(command.Id);
@@ -114,134 +47,17 @@ public class RoleApplication : IRoleApplication
//var permissions = new List<Permission>();
//command.Permissions.ForEach(code => permissions.Add(new Permission(code)));
var permissions = command.Permissions.Where(x => x > 0).Select(x => new Permission(x)).ToList();
var permissions = new List<Permission>();
foreach (var code in command.Permissions)
{
if (code > 0)
{
permissions.Add(new Permission(code));
}
}
_unitOfWork.BeginAccountContext();
role.Edit(command.Name, permissions);
_roleRepository.SaveChanges();
var key = SecretKeys.ProgramManagerInternalApi;
var pmPermissions = command.PmPermissions.Where(x => x > 0).ToList();
//یافتن نقش در پروگرام منیجر
//var apiResult = InternalApiCaller.GetAsync<RoleResponse>(
// "api/role",
// key,
// new Dictionary<string, object>
// {
// { "RoleName", "" },
// { "GozareshgirRoleId", command.Id}
// }
//);
var pmRoleListResult = await _pmRoleQueryService.GetPmRoleList(command.Id);
var pmRoleResult = pmRoleListResult.FirstOrDefault();
//اگر این نقش در پروگرام منیجر وجود داشت ویرایش کن
if (pmRoleResult != null)
{
var edit = new CreatePmRoleDto { RoleName = command.Name, Permissions = pmPermissions, GozareshgirRoleId = role.id };
var res = await _pmRoleCommandService.Edit(edit);
if (!res.Item1)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش دسترسی ها در پروگرام منیجر");
}
//var parameters = new CreateProgramManagerRole
//{
// RoleName = command.Name,
// Permissions = pmPermissions,
// GozareshgirRoleId = role.id
//};
//var url = "api/role/edit";
//var response = InternalApiCaller.PostAsync<CreateProgramManagerRole, ApiResponse>(
// url,
// key,
// parameters
//);
//if (!response.Success)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed("ارتباط با اپلیکیش پروگرام منیجر برقرار نشد");
//}
//if (!response.Result.isSuccess)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Result.errorMessage);
//}
}
else //اگر نقش در پروگرام منیجر وجود نداشت
{
//اگر تیک پرمیشن های پروگرام منیجر زده شده
//این نقش را سمت پروگرام منیجر بساز
if (pmPermissions.Any())
{
var pmRole = new CreatePmRoleDto { RoleName = command.Name, Permissions = pmPermissions, GozareshgirRoleId = role.id };
var res = await _pmRoleCommandService.Create(pmRole);
if (!res.Item1)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش دسترسی ها در پروگرام منیجر");
}
//try
//{
// var pmPermissionsData = pmPermissions.Where(x => x > 0).Select(x => new PmPermission(x)).ToList();
// var pmRole = new PmRole(command.Name, command.Id, pmPermissionsData);
// await _pmRoleRepository.CreateAsync(pmRole);
// await _pmRoleRepository.SaveChangesAsync();
//}
//catch (System.Exception)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed("خطا در ویرایش دسترسی ها در پروگرام منیجر");
//}
//var parameters = new CreateProgramManagerRole
//{
// RoleName = command.Name,
// Permissions = pmPermissions,
// GozareshgirRoleId = role.id
//};
//var url = "api/role";
//var response = InternalApiCaller.PostAsync<CreateProgramManagerRole, ApiResponse>(
// url,
// key,
// parameters
//);
//if (!response.Success)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed("ارتباط با اپلیکیش پروگرام منیجر برقرار نشد");
//}
//if (!response.Result.isSuccess)
//{
// _unitOfWork.RollbackAccountContext();
// return operation.Failed(response.Result.errorMessage);
//}
}
}
_unitOfWork.CommitAccountContext();
return operation.Succcedded();
}
@@ -254,23 +70,4 @@ public class RoleApplication : IRoleApplication
{
return _roleRepository.List();
}
public async Task<SelectList> GetPmRoleList(long? gozareshgirRoleId)
{
var rolse = await _pmRoleQueryService.GetPmRoleList(gozareshgirRoleId);
return new SelectList(rolse, "Id", "RoleName");
}
public async Task<List<GetPmRolesDto>> GetPmRoleListToEdit(long? gozareshgirRoleId)
{
return await _pmRoleQueryService.GetPmRoleList(gozareshgirRoleId);
}
}

View File

@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

View File

@@ -1,18 +0,0 @@
using AccountManagement.Domain.PmDomains.PmRoleAgg;
using AccountManagement.Domain.PmDomains.PmUserAgg;
using AccountMangement.Infrastructure.EFCore.PmDbConetxt;
using AccountMangement.Infrastructure.EFCore.Repository.PmRepositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace AccountManagement.Configuration;
public class PmDbBootstrapper
{
public static void Configure(IServiceCollection services, string connectionString)
{
services.AddTransient<IPmRoleRepository, PmRoleRepository>();
services.AddTransient<IPmUserRepository, PmUserRepository>();
services.AddDbContext<PmDbContext>(x => x.UseSqlServer(connectionString));
}
}

View File

@@ -1,16 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="10.0.1" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\0_Framework\0_Framework.csproj" />
<ProjectReference Include="..\AccountManagement.Application.Contracts\AccountManagement.Application.Contracts.csproj" />

View File

@@ -1,155 +0,0 @@
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
namespace AccountManagement.Domain.InternalApiCaller;
public class ApiResult<T>
{
public bool Success { get; set; }
public T Result { get; set; }
public string Error { get; set; }
}
public static class InternalApiCaller
{
private static string _baseUrl = "";
public static void SetBaseUrl(string baseUrl)
{
_baseUrl = baseUrl.TrimEnd('/'); // حذف / اضافی
}
/// <summary>
///api post متد
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
/// <param name="url"></param>
/// <param name="internalKey"></param>
/// <param name="body"></param>
/// <returns></returns>
public static ApiResult<TResponse> PostAsync<TRequest, TResponse>(
string url,
string internalKey,
TRequest body
)
{
try
{
var client = new HttpClient();
// ساخت URL نهایی
var finalUrl = $"{_baseUrl}/{url.TrimStart('/')}";
var request = new HttpRequestMessage(HttpMethod.Post, finalUrl);
request.Headers.Add("X-INTERNAL-KEY", internalKey);
var json = JsonConvert.SerializeObject(body);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
var response = client.SendAsync(request).GetAwaiter().GetResult();
if (!response.IsSuccessStatusCode)
{
return new ApiResult<TResponse>
{
Success = false,
Error = $"HTTP Error: {response.StatusCode}"
};
}
var text = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var deserialized = JsonConvert.DeserializeObject<TResponse>(text);
return new ApiResult<TResponse>
{
Success = true,
Result = deserialized
};
}
catch (Exception ex)
{
return new ApiResult<TResponse>
{
Success = false,
Error = ex.Message
};
}
}
/// <summary>
/// Api Get متد
/// </summary>
/// <typeparam name="TResponse"></typeparam>
/// <param name="url"></param>
/// <param name="internalKey"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static ApiResult<TResponse> GetAsync<TResponse>(
string url,
string internalKey,
Dictionary<string, object> parameters = null
)
{
try
{
if (parameters != null && parameters.Any())
{
var query = string.Join("&",
parameters
.Where(p => p.Value != null)
.Select(p => $"{p.Key}={p.Value}")
);
url += url.Contains("?") ? "&" + query : "?" + query;
}
// ساخت URL نهایی
var finalUrl = $"{_baseUrl}/{url.TrimStart('/')}";
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, finalUrl);
request.Headers.Add("X-INTERNAL-KEY", internalKey);
var response = client.SendAsync(request).GetAwaiter().GetResult();
if (!response.IsSuccessStatusCode)
{
return new ApiResult<TResponse>
{
Success = false,
Error = $"HTTP Error: {response.StatusCode}"
};
}
var text = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var deserialized = JsonConvert.DeserializeObject<TResponse>(text);
return new ApiResult<TResponse>
{
Success = true,
Result = deserialized
};
}
catch (Exception ex)
{
return new ApiResult<TResponse>
{
Success = false,
Error = ex.Message
};
}
}
}

View File

@@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccountManagement.Domain.PmDomains.PmRoleAgg;
namespace AccountManagement.Domain.PmDomains.PmPermissionAgg;
public class PmPermission
{
public long Id { get; private set; }
public int Code { get; private set; }
public PmRole Role { get; private set; }
public PmPermission(int code)
{
Code = code;
}
}

View File

@@ -1,15 +0,0 @@
using _0_Framework.Domain;
using System.Collections.Generic;
using System.Threading.Tasks;
using AccountManagement.Application.Contracts.ProgramManager;
namespace AccountManagement.Domain.PmDomains.PmRoleAgg;
public interface IPmRoleRepository :IRepository<long, PmRole>
{
Task<List<GetPmRolesDto>> GetPmRoleList(long? gozareshgirRoleId);
Task<PmRole?> GetPmRoleToEdit(long gozareshgirRoleId);
}

View File

@@ -1,46 +0,0 @@
using System.Collections.Generic;
using _0_Framework.Domain;
using AccountManagement.Domain.PmDomains.PmPermissionAgg;
namespace AccountManagement.Domain.PmDomains.PmRoleAgg;
public class PmRole : EntityBase
{
/// <summary>
/// نام نقش
/// </summary>
public string RoleName { get; private set; }
/// <summary>
/// لیست پرمیشن کد ها
/// </summary>
public List<PmPermission> PmPermission { get; private set; }
/// <summary>
/// ای دی نقش در گزارشگیر
/// </summary>
public long? GozareshgirRoleId { get; private set; }
protected PmRole()
{
}
public PmRole(string roleName,long? gozareshgirRolId, List<PmPermission> permissions)
{
RoleName = roleName;
PmPermission = permissions;
GozareshgirRoleId = gozareshgirRolId;
}
public void Edit(string roleName, List<PmPermission> permissions)
{
RoleName = roleName;
PmPermission = permissions;
}
}

View File

@@ -1,19 +0,0 @@
using AccountManagement.Domain.PmDomains.PmUserAgg;
namespace AccountManagement.Domain.PmDomains.PmRoleUserAgg;
public class PmRoleUser
{
public PmRoleUser(long roleId)
{
RoleId = roleId;
}
public long Id { get; private set; }
public long RoleId { get; private set; }
public PmUser User { get; set; }
}

View File

@@ -1,22 +0,0 @@
using _0_Framework.Domain;
using AccountManagement.Application.Contracts.ProgramManager;
using System.Threading.Tasks;
using Shared.Contracts.PmUser.Queries;
namespace AccountManagement.Domain.PmDomains.PmUserAgg;
public interface IPmUserRepository : IRepository<long, PmUser>
{
/// <summary>
/// دریافت کاربر پروگرام منیجر جهتد ویرایش
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
Task<PmUser?> GetByPmUsertoEditbyAccountId(long accountId);
/// <summary>
/// دریافت کرابر پروگرام منیجر با اکانت آی دی در گزارشگیر
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
Task<GetPmUserDto> GetPmUserByAccountId(long accountId);
}

View File

@@ -1,127 +0,0 @@
using System;
using System.Collections.Generic;
using _0_Framework.Domain;
using AccountManagement.Domain.PmDomains.PmRoleUserAgg;
namespace AccountManagement.Domain.PmDomains.PmUserAgg;
/// <summary>
/// کاربر
/// </summary>
public class PmUser : EntityBase
{
/// <summary>
/// ایجاد
/// </summary>
/// <param name="fullName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="mobile"></param>
/// <param name="email"></param>
/// <param name="accountId"></param>
/// <param name="roles"></param>
public PmUser(string fullName, string userName, string password, string mobile, string email, long? accountId, List<PmRoleUser> roles)
{
FullName = fullName;
UserName = userName;
Password = password;
Mobile = mobile;
Email = email;
IsActive = true;
AccountId = accountId;
RoleUser = roles;
}
protected PmUser()
{
}
/// <summary>
/// نام و نام خانوادگی
/// </summary>
public string FullName { get; private set; }
/// <summary>
/// نام کاربری
/// </summary>
public string UserName { get; private set; }
/// <summary>
/// گذرواژه
/// </summary>
public string Password { get; private set; }
/// <summary>
/// مسیر عکس پروفایل
/// </summary>
public string ProfilePhotoPath { get; private set; }
/// <summary>
/// شماره موبایل
/// </summary>
public string Mobile { get; set; }
/// <summary>
/// ایمیل
/// </summary>
public string Email { get; private set; }
/// <summary>
/// فعال/غیر فعال بودن یوزر
/// </summary>
public bool IsActive { get; private set; }
/// <summary>
/// کد یکبارمصرف ورود
/// </summary>
public string VerifyCode { get; private set; }
/// <summary>
/// آی دی کاربر در گزارشگیر
/// </summary>
public long? AccountId { get; private set; }
/// <summary>
/// لیست پرمیشن کد ها
/// </summary>
public List<PmRoleUser> RoleUser { get; private set; }
/// <summary>
/// آپدیت کاربر
/// </summary>
/// <param name="fullName"></param>
/// <param name="userName"></param>
/// <param name="mobile"></param>
/// <param name="roles"></param>
/// <param name="isActive"></param>
public void Edit(string fullName, string userName, string mobile, List<PmRoleUser> roles, bool isActive)
{
FullName = fullName;
UserName = userName;
Mobile = mobile;
RoleUser = roles;
IsActive = isActive;
}
/// <summary>
/// غیرفعال سازی
/// </summary>
public void DeActive()
{
IsActive = false;
}
/// <summary>
/// فعال سازی
/// </summary>
public void ReActive()
{
IsActive = true;
}
}

View File

@@ -1,15 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
@@ -20,8 +18,4 @@
<ProjectReference Include="..\Company.Domain\Company.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\" />
</ItemGroup>
</Project>

View File

@@ -1,24 +0,0 @@
using AccountManagement.Domain.PmDomains.PmRoleAgg;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace AccountMangement.Infrastructure.EFCore.Mappings.PmMappings;
public class PmRoleMapping : IEntityTypeConfiguration<PmRole>
{
public void Configure(EntityTypeBuilder<PmRole> builder)
{
builder.ToTable("PmRoles", t => t.ExcludeFromMigrations());
builder.HasKey(x => x.id);
builder.Property(x => x.RoleName).HasMaxLength(100).IsRequired();
builder.OwnsMany(x => x.PmPermission, navigationBuilder =>
{
navigationBuilder.HasKey(x => x.Id);
navigationBuilder.ToTable("PmRolePermissions", t => t.ExcludeFromMigrations());
navigationBuilder.WithOwner(x => x.Role);
});
}
}

View File

@@ -1,30 +0,0 @@
using AccountManagement.Domain.PmDomains.PmUserAgg;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace AccountMangement.Infrastructure.EFCore.Mappings.PmMappings;
public class PmUserMapping :IEntityTypeConfiguration<PmUser>
{
public void Configure(EntityTypeBuilder<PmUser> builder)
{
builder.ToTable("Users");
builder.HasKey(x => x.id);
builder.Property(x => x.FullName).HasMaxLength(100).IsRequired();
builder.Property(x => x.UserName).HasMaxLength(100).IsRequired();
builder.Property(x => x.Password).HasMaxLength(1000).IsRequired();
builder.Property(x => x.ProfilePhotoPath).HasMaxLength(500).IsRequired(false);
builder.Property(x => x.Mobile).HasMaxLength(20).IsRequired();
builder.Property(x => x.Email).HasMaxLength(150).IsRequired(false); ;
builder.Property(x => x.VerifyCode).HasMaxLength(10).IsRequired(false);
builder.OwnsMany(x => x.RoleUser, navigationBuilder =>
{
navigationBuilder.HasKey(x => x.Id);
navigationBuilder.ToTable("RoleUsers");
navigationBuilder.WithOwner(x => x.User);
});
}
}

View File

@@ -1,31 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AccountMangement.Infrastructure.EFCore.Migrations
{
/// <inheritdoc />
public partial class addprogrammangerbooinaccount : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsProgramManagerUser",
table: "Accounts",
type: "bit",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsProgramManagerUser",
table: "Accounts");
}
}
}

View File

@@ -1,29 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AccountMangement.Infrastructure.EFCore.Migrations
{
/// <inheritdoc />
public partial class romoveIsProgramManagerUserFromAccount : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsProgramManagerUser",
table: "Accounts");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsProgramManagerUser",
table: "Accounts",
type: "bit",
nullable: false,
defaultValue: false);
}
}
}

View File

@@ -17,7 +17,7 @@ namespace AccountMangement.Infrastructure.EFCore.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.1")
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
@@ -377,87 +377,6 @@ namespace AccountMangement.Infrastructure.EFCore.Migrations
b.ToTable("Medias", (string)null);
});
modelBuilder.Entity("AccountManagement.Domain.PmDomains.PmRoleAgg.PmRole", b =>
{
b.Property<long>("id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<long?>("GozareshgirRoleId")
.HasColumnType("bigint");
b.Property<string>("RoleName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("id");
b.ToTable("PmRoles", null, t =>
{
t.ExcludeFromMigrations();
});
});
modelBuilder.Entity("AccountManagement.Domain.PmDomains.PmUserAgg.PmUser", b =>
{
b.Property<long>("id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("id"));
b.Property<long?>("AccountId")
.HasColumnType("bigint");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasMaxLength(150)
.HasColumnType("nvarchar(150)");
b.Property<string>("FullName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Mobile")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("nvarchar(20)");
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<string>("ProfilePhotoPath")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("VerifyCode")
.HasMaxLength(10)
.HasColumnType("nvarchar(10)");
b.HasKey("id");
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("AccountManagement.Domain.PositionAgg.Position", b =>
{
b.Property<long>("id")
@@ -1082,71 +1001,6 @@ namespace AccountMangement.Infrastructure.EFCore.Migrations
b.Navigation("Media");
});
modelBuilder.Entity("AccountManagement.Domain.PmDomains.PmRoleAgg.PmRole", b =>
{
b.OwnsMany("AccountManagement.Domain.PmDomains.PmPermissionAgg.PmPermission", "PmPermission", b1 =>
{
b1.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b1.Property<long>("Id"));
b1.Property<int>("Code")
.HasColumnType("int");
b1.Property<long>("Roleid")
.HasColumnType("bigint");
b1.HasKey("Id");
b1.HasIndex("Roleid");
b1.ToTable("PmRolePermissions", null, t =>
{
t.ExcludeFromMigrations();
});
b1.WithOwner("Role")
.HasForeignKey("Roleid");
b1.Navigation("Role");
});
b.Navigation("PmPermission");
});
modelBuilder.Entity("AccountManagement.Domain.PmDomains.PmUserAgg.PmUser", b =>
{
b.OwnsMany("AccountManagement.Domain.PmDomains.PmRoleUserAgg.PmRoleUser", "RoleUser", b1 =>
{
b1.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b1.Property<long>("Id"));
b1.Property<long>("RoleId")
.HasColumnType("bigint");
b1.Property<long>("Userid")
.HasColumnType("bigint");
b1.HasKey("Id");
b1.HasIndex("Userid");
b1.ToTable("RoleUsers", (string)null);
b1.WithOwner("User")
.HasForeignKey("Userid");
b1.Navigation("User");
});
b.Navigation("RoleUser");
});
modelBuilder.Entity("AccountManagement.Domain.RoleAgg.Role", b =>
{
b.OwnsMany("AccountManagement.Domain.RoleAgg.Permission", "Permissions", b1 =>

View File

@@ -1,32 +0,0 @@
using AccountManagement.Domain.PmDomains.PmRoleAgg;
using AccountManagement.Domain.PmDomains.PmUserAgg;
using AccountMangement.Infrastructure.EFCore.Mappings;
using AccountMangement.Infrastructure.EFCore.Mappings.PmMappings;
using Microsoft.EntityFrameworkCore;
namespace AccountMangement.Infrastructure.EFCore.PmDbConetxt;
public class PmDbContext : DbContext
{
public PmDbContext(DbContextOptions<PmDbContext> options) : base(options)
{
}
public DbSet<PmUser> Users { get; set; } = null!;
public DbSet<PmRole> PmRoles { get; set; } = null!;
public PmDbContext()
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var assembly = typeof(PmUserMapping).Assembly;
modelBuilder.ApplyConfigurationsFromAssembly(assembly);
//SubAccountPermissionSeeder.Seed(modelBuilder);
base.OnModelCreating(modelBuilder);
}
}

View File

@@ -1,49 +0,0 @@
using _0_Framework.InfraStructure;
using AccountManagement.Application.Contracts.ProgramManager;
using AccountManagement.Domain.PmDomains.PmRoleAgg;
using AccountMangement.Infrastructure.EFCore.PmDbConetxt;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
namespace AccountMangement.Infrastructure.EFCore.Repository.PmRepositories;
public class PmRoleRepository : RepositoryBase<long, PmRole>, IPmRoleRepository
{
private readonly PmDbContext _pmDbContext;
public PmRoleRepository(PmDbContext context) : base(context)
{
_pmDbContext = context;
}
public async Task<List<GetPmRolesDto>> GetPmRoleList(long? gozareshgirRoleId)
{
var query = _pmDbContext.PmRoles.AsQueryable();
if (gozareshgirRoleId != null && gozareshgirRoleId > 0)
query = query.Where(x => x.GozareshgirRoleId == gozareshgirRoleId);
var res = await query
.Select(p => new GetPmRolesDto()
{
Id = p.id,
RoleName = p.RoleName,
GozareshgirRoleId = p.GozareshgirRoleId,
Permissions = p.PmPermission.Select(x => x.Code).ToList()
})
.ToListAsync();
return res;
}
public async Task<PmRole?> GetPmRoleToEdit(long gozareshgirRoleId)
{
return await _pmDbContext.PmRoles.FirstOrDefaultAsync(x => x.GozareshgirRoleId == gozareshgirRoleId);
}
}

View File

@@ -1,48 +0,0 @@
using _0_Framework.InfraStructure;
using AccountManagement.Application.Contracts.ProgramManager;
using AccountManagement.Domain.PmDomains.PmUserAgg;
using AccountMangement.Infrastructure.EFCore.PmDbConetxt;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Shared.Contracts.PmUser.Queries;
namespace AccountMangement.Infrastructure.EFCore.Repository.PmRepositories;
public class PmUserRepository :RepositoryBase<long, PmUser>, IPmUserRepository
{
private readonly PmDbContext _pmDbContext;
public PmUserRepository(PmDbContext context, PmDbContext pmDbContext) : base(context)
{
_pmDbContext = pmDbContext;
}
public async Task<PmUser?> GetByPmUsertoEditbyAccountId(long accountId)
{
return await _pmDbContext.Users.FirstOrDefaultAsync(x => x.AccountId == accountId);
}
public async Task<GetPmUserDto> GetPmUserByAccountId(long accountId)
{
var query = await _pmDbContext.Users.FirstOrDefaultAsync(x => x.AccountId == accountId);
if (query == null)
return new GetPmUserDto();
List<long> roles = query.RoleUser.Select(x => x.RoleId).ToList();
return new GetPmUserDto()
{
FullName = query.FullName,
UserName = query.UserName,
ProfilePhotoPath = query.ProfilePhotoPath,
Mobile = query.Mobile,
IsActive = query.IsActive,
AccountId = query.AccountId,
Roles = roles,
RoleListDto = await _pmDbContext.PmRoles.Where(x => roles.Contains(x.id)).Select(x => new RoleListDto()
{
RoleName = x.RoleName,
RoleId = x.id,
Permissions = x.PmPermission.Select(x => x.Code).ToList()
}).ToListAsync(),
};
}
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>BackgroundInstitutionContract.Task</AssemblyName>

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
@@ -16,15 +16,10 @@
<ItemGroup>
<Folder Include="CheckoutAgg\ValueObjects\" />
<Folder Include="_common\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="10.0.1" />
<PackageReference Include="MongoDB.Bson" Version="3.5.2" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.1" />
<PackageReference Include="MongoDB.Bson" Version="3.5.0" />
</ItemGroup>
</Project>

View File

@@ -290,13 +290,4 @@ public class PersonalContractingParty : EntityBase
this.Gender = gender;
this.IsAuthenticated = true;
}
public void EditLegalPartyFromInstitution(string legalPosition, string companyName,
string registerId,string nationalId)
{
LegalPosition = legalPosition;
LName = companyName;
RegisterId = registerId;
NationalId = nationalId;
}
}

View File

@@ -37,7 +37,7 @@ namespace Company.Domain.EmployeeDocumentsAgg
{
WorkshopId = workshopId;
EmployeeId = employeeId;
Gender = gender??string.Empty;
Gender = gender;
}
private EmployeeDocuments()

View File

@@ -1,8 +0,0 @@
namespace Company.Domain._common;
public interface IUnitOfWork
{
void BeginAccountContext();
void CommitAccountContext();
void RollbackAccountContext();
}

View File

@@ -1,14 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="EPPlus" Version="8.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="EPPlus" Version="7.5.2" />
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="5.0.17" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AccountMangement.Infrastructure.EFCore\AccountMangement.Infrastructure.EFCore.csproj" />

View File

@@ -0,0 +1,86 @@
using System.Collections.Generic;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Drawing;
namespace CompanyManagement.Infrastructure.Excel.ContractingParty;
public static class InstitutionContractDetailExcelGenerator
{
public static byte[] Generate(List<InstitutionContractDetailExcelViewModel> items)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("جزئیات طرف قرارداد");
// Headers (فارسی)
worksheet.Cells[1, 1].Value = "نام";
worksheet.Cells[1, 2].Value = "نام خانوادگی";
worksheet.Cells[1, 3].Value = "کد ملی";
worksheet.Cells[1, 4].Value = "تاریخ تولد";
worksheet.Cells[1, 5].Value = "شماره تماس";
worksheet.Cells[1, 6].Value = "شماره ملی";
// Header style
using (var headerRange = worksheet.Cells[1, 1, 1, 6])
{
headerRange.Style.Font.Bold = true;
headerRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
headerRange.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
headerRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
headerRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
headerRange.Style.Border.Top.Style = ExcelBorderStyle.Thin;
headerRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
headerRange.Style.Border.Left.Style = ExcelBorderStyle.Thin;
headerRange.Style.Border.Right.Style = ExcelBorderStyle.Thin;
}
// Data rows
int row = 2;
if (items != null)
{
foreach (var it in items)
{
worksheet.Cells[row, 1].Value = it.FirstName;
worksheet.Cells[row, 2].Value = it.LastName;
worksheet.Cells[row, 3].Value = it.NationalCode;
worksheet.Cells[row, 4].Value = it.BirthDate;
worksheet.Cells[row, 5].Value = it.PhoneNumber;
worksheet.Cells[row, 6].Value = it.NationalNumber;
using (var dataRange = worksheet.Cells[row, 1, row, 6])
{
dataRange.Style.Border.Top.Style = ExcelBorderStyle.Thin;
dataRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
dataRange.Style.Border.Left.Style = ExcelBorderStyle.Thin;
dataRange.Style.Border.Right.Style = ExcelBorderStyle.Thin;
dataRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right; // راست‌چین
dataRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
dataRange.Style.WrapText = true;
}
row++;
}
}
// Auto-fit columns to largest content
if (worksheet.Dimension != null)
{
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
}
// Set sheet to RTL for Persian
worksheet.View.RightToLeft = true;
return package.GetAsByteArray();
}
}
public class InstitutionContractDetailExcelViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string NationalCode { get; set; }
public string BirthDate { get; set; } // accept Persian date strings
public string PhoneNumber { get; set; }
public string NationalNumber { get; set; }
}

View File

@@ -0,0 +1,93 @@
using System.Collections.Generic;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Drawing;
namespace CompanyManagement.Infrastructure.Excel.ContractingParty;
public static class InstitutionContractLegalExcelGenerator
{
public static byte[] Generate(List<InstitutionContractLegalExcelViewModel> items)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("جزئیات حقوقی طرف قرارداد");
// Headers (فارسی)
worksheet.Cells[1, 1].Value = "نام شرکت";
worksheet.Cells[1, 2].Value = "نام";
worksheet.Cells[1, 3].Value = "نام خانوادگی";
worksheet.Cells[1, 4].Value = "کد ملی";
worksheet.Cells[1, 5].Value = "شماره ثبت";
worksheet.Cells[1, 6].Value = "تاریخ تولد";
worksheet.Cells[1, 7].Value = "شماره تماس";
worksheet.Cells[1, 8].Value = "شماره ملی";
// Header style
using (var headerRange = worksheet.Cells[1, 1, 1, 8])
{
headerRange.Style.Font.Bold = true;
headerRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
headerRange.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
headerRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
headerRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
headerRange.Style.Border.Top.Style = ExcelBorderStyle.Thin;
headerRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
headerRange.Style.Border.Left.Style = ExcelBorderStyle.Thin;
headerRange.Style.Border.Right.Style = ExcelBorderStyle.Thin;
}
// Data rows
int row = 2;
if (items != null)
{
foreach (var it in items)
{
worksheet.Cells[row, 1].Value = it.CompanyName;
worksheet.Cells[row, 2].Value = it.FirstName;
worksheet.Cells[row, 3].Value = it.LastName;
worksheet.Cells[row, 4].Value = it.NationalCode;
worksheet.Cells[row, 5].Value = it.RegistrationNumber;
worksheet.Cells[row, 6].Value = it.BirthDate;
worksheet.Cells[row, 7].Value = it.PhoneNumber;
worksheet.Cells[row, 8].Value = it.NationalNumber;
using (var dataRange = worksheet.Cells[row, 1, row, 8])
{
dataRange.Style.Border.Top.Style = ExcelBorderStyle.Thin;
dataRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
dataRange.Style.Border.Left.Style = ExcelBorderStyle.Thin;
dataRange.Style.Border.Right.Style = ExcelBorderStyle.Thin;
dataRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right; // راست‌چین
dataRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
dataRange.Style.WrapText = true;
}
row++;
}
}
// Auto-fit columns to largest content
if (worksheet.Dimension != null)
{
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
}
// Set sheet to RTL for Persian
worksheet.View.RightToLeft = true;
return package.GetAsByteArray();
}
}
public class InstitutionContractLegalExcelViewModel
{
public string CompanyName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string NationalCode { get; set; }
public string RegistrationNumber { get; set; }
public string BirthDate { get; set; }
public string PhoneNumber { get; set; }
public string NationalNumber { get; set; }
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
@@ -11,8 +11,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="MongoDB.Driver" Version="3.5.2" />
<PackageReference Include="MongoDB.Driver" Version="3.5.0" />
</ItemGroup>
</Project>

View File

@@ -1,16 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="10.0.1" />
<PackageReference Include="PersianTools.Core" Version="2.0.4" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.1" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,13 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AndroidXml" Version="1.1.24" />
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -1585,12 +1585,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
if (employee.IsAuthorized == false)
{
var apiResult = await _uidService.GetPersonalInfo(nationalCode, birthDate);
if (apiResult == null)
{
return op.Failed("این پرسنل در بانک اطلاعات موجود میباشد");
}
if (apiResult.ResponseContext.Status.Code is 14 or 3)
if (apiResult.ResponseContext.Status.Code == 14)
{
return op.Failed("این پرسنل در بانک اطلاعات موجود میباشد");
@@ -1655,7 +1650,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید", new EmployeeDataFromApiViewModel() { AuthorizedCanceled = true });
}
if (apiResult.ResponseContext.Status.Code is 14 or 3)
if (apiResult.ResponseContext.Status.Code == 14)
{
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید", new EmployeeDataFromApiViewModel() { AuthorizedCanceled = true });

View File

@@ -888,7 +888,6 @@ public class InstitutionContractApplication : IInstitutionContractApplication
public void RemoveContract(long id)
{
_institutionContractRepository.RemoveContract(id);
}
@@ -982,12 +981,6 @@ public class InstitutionContractApplication : IInstitutionContractApplication
existingContractingParty.UnAuthenticateLegalEdit(legalCommand.FName,legalCommand.LName,legalCommand.FatherName,legalCommand.IdNumber,existingContractingParty.IdNumberSeri,existingContractingParty.IdNumberSerial,
legalCommand.BirthDateFa,legalCommand.Gender,legalCommand.PhoneNumber);
}
if (existingContractingParty != null)
{
existingContractingParty.EditLegalPartyFromInstitution(command.LegalParty.Position,command.LegalParty.CompanyName,
command.LegalParty.RegisterId,command.LegalParty.NationalId);
}
}
else if (command.ContractingPartyLegalType == LegalType.Real)
{

View File

@@ -290,34 +290,8 @@ public class LeftWorkTempApplication : ILeftWorkTempApplication
//get rollCallEmployee associated with those leftworks which have a higher end date than leftworkDate
var rollCallsEmployee = _rollCallEmployeeRepository.GetBy(employeeId, workshopId);
if (rollCallsEmployee != null)
{
var status = rollCallsEmployee.EmployeesStatus.OrderByDescending(z => z.StartDate)
.FirstOrDefault(rollCallEmployeeStatus => rollCallEmployeeStatus.StartDate.Date < maxLeftWork.LeftWorkDateGr
&& rollCallEmployeeStatus.EndDate.Date >
maxLeftWork.LeftWorkDateGr);
if (status != null)
{
var adjust = new AdjustRollCallEmployeesWithEmployeeLeftWork()
{
LeaveDate = maxLeftWork.LeftWorkDateGr,
RollCallStatusId = status.id
};
_rollCallEmployeeStatusRepository.AdjustRollCallStatusEndDates([adjust]);
}
var rollCallEmployeeStatusList = rollCallsEmployee.EmployeesStatus
.Where(x => x.StartDate >= maxLeftWork.LeftWorkDateGr).ToList();
if (rollCallEmployeeStatusList.Any())
{
_rollCallEmployeeStatusRepository.RemoveRange(rollCallEmployeeStatusList);
_rollCallEmployeeStatusRepository.SaveChanges();
}
}
// var joinedList = rollCallsEmployee.Join(leftWorks, x => x.WorkshopId, y => y.WorkshopId, (x, y) => new
// {
// x.WorkshopId,
@@ -327,6 +301,27 @@ public class LeftWorkTempApplication : ILeftWorkTempApplication
// });
var status = rollCallsEmployee.EmployeesStatus.OrderByDescending(z => z.StartDate)
.FirstOrDefault(rollCallEmployeeStatus => rollCallEmployeeStatus.StartDate.Date < maxLeftWork.LeftWorkDateGr
&& rollCallEmployeeStatus.EndDate.Date >
maxLeftWork.LeftWorkDateGr);
if (status != null)
{
var adjust = new AdjustRollCallEmployeesWithEmployeeLeftWork()
{
LeaveDate = maxLeftWork.LeftWorkDateGr,
RollCallStatusId = status.id
};
_rollCallEmployeeStatusRepository.AdjustRollCallStatusEndDates([adjust]);
}
var rollCallEmployeeStatusList = rollCallsEmployee.EmployeesStatus
.Where(x => x.StartDate >= maxLeftWork.LeftWorkDateGr).ToList();
if (rollCallEmployeeStatusList.Any())
{
_rollCallEmployeeStatusRepository.RemoveRange(rollCallEmployeeStatusList);
_rollCallEmployeeStatusRepository.SaveChanges();
}
}
}

View File

@@ -446,7 +446,7 @@ public class RollCallApplication : IRollCallApplication
return operation.Failed("کارمند در بازه انتخاب شده مرخصی ساعتی دارد");
}
if (newRollCallDates == null || !newRollCallDates.All(x => employeeStatuses.Any(y => x.StartDate.Value.Date >= y.StartDateGr.Date && x.EndDate.Value.Date <= y.EndDateGr.Date)))
if (newRollCallDates == null || !newRollCallDates.All(x => employeeStatuses.Any(y => x.StartDate >= y.StartDateGr && x.EndDate <= y.EndDateGr)))
return operation.Failed("کارمند در بازه وارد شده غیر فعال است");
@@ -486,8 +486,7 @@ public class RollCallApplication : IRollCallApplication
if (newRollCallDates == null || !newRollCallDates.All(x => employeeStatuses.Any(y => x.StartDate.Value.Date >= y.StartDateGr.Date
&& x.EndDate.Value.Date <= y.EndDateGr.Date)))
if (newRollCallDates == null || !newRollCallDates.All(x => employeeStatuses.Any(y => x.StartDate >= y.StartDateGr && x.EndDate <= y.EndDateGr)))
return operation.Failed("کارمند در بازه وارد شده غیر فعال است");
@@ -631,7 +630,7 @@ public class RollCallApplication : IRollCallApplication
return operation.Failed("کارمند در بازه انتخاب شده مرخصی ساعتی دارد");
}
if (newRollCallDates == null || !newRollCallDates.All(x => employeeStatuses.Any(y => x.StartDate.Value.Date >= y.StartDateGr.Date && x.EndDate.Value.Date <= y.EndDateGr.Date)))
if (newRollCallDates == null || !newRollCallDates.All(x => employeeStatuses.Any(y => x.StartDate >= y.StartDateGr && x.EndDate <= y.EndDateGr)))
return operation.Failed("کارمند در بازه وارد شده غیر فعال است");
@@ -663,7 +662,7 @@ public class RollCallApplication : IRollCallApplication
&& (y.StartDate.Value.Date <= x.ContractEndGr.Date))))
return operation.Failed("برای بازه های وارد شده فیش حقوقی ثبت شده است");
if (newRollCallDates == null || !newRollCallDates.All(x => employeeStatuses.Any(y => x.StartDate.Value.Date >= y.StartDateGr.Date && x.EndDate.Value.Date <= y.EndDateGr.Date)))
if (newRollCallDates == null || !newRollCallDates.All(x => employeeStatuses.Any(y => x.StartDate >= y.StartDateGr && x.EndDate <= y.EndDateGr)))
return operation.Failed("کارمند در بازه وارد شده غیر فعال است");
var currentDayRollCall = employeeRollCalls.FirstOrDefault(x => x.EndDate == null);

View File

@@ -240,8 +240,6 @@ public class TemporaryClientRegistrationApplication : ITemporaryClientRegistrati
result.IdNumberSerial = createTemp.IdNumberSerial;
result.IdNumber = idNumber;
result.NationalCode = createTemp.NationalCode;
result.Phone = createTemp.Phone;
result.IdNumberSeri = createTemp.IdNumberSeri;
return op.Succcedded(result);

View File

@@ -1,20 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.QualityTools.Testing.Fakes" Version="18.1.1" />
<PackageReference Include="MongoDB.Driver" Version="3.5.2" />
<PackageReference Include="Microsoft.QualityTools.Testing.Fakes" Version="16.11.230815" />
<PackageReference Include="MongoDB.Driver" Version="3.5.0" />
<PackageReference Include="Parbad.Gateway.Sepehr" Version="1.7.0" />
<PackageReference Include="PersianTools.Core" Version="2.0.4" />
</ItemGroup>

View File

@@ -4723,8 +4723,6 @@ public class RollCallMandatoryRepository : RepositoryBase<long, RollCall>, IRoll
#endregion
#region KebabMahdiAbsentsCaclculation
var rollCallDays = groupedRollCall.Count > mandatoryDays ? mandatoryDays : groupedRollCall.Count;
@@ -5110,45 +5108,6 @@ public class RollCallMandatoryRepository : RepositoryBase<long, RollCall>, IRoll
});
}
#endregion
#region اگر که پرسنل در روز های جمعه یا پنجشنبه غیبت داشت یک روز به غیبت اضافه شود
//این منطق زمانی برقرار هست که مرخصی در اون روز نداشته باشه
// ساخت لیست روزهای بین شروع و پایان قرارداد
var contractDaysList = Enumerable.Range(0, (contractEnd - contractStart).Days + 1)
.Select(offset => contractStart.AddDays(offset))
.ToList();
// کم کردن روزهایی که حضور دارند
var absentDaysList = contractDaysList
.Where(date => !groupedRollCall.Any(g => g.ShiftDate.Date == date.Date))
.ToList();
var absentFridaysOrThursdays = absentDaysList
.Where(date => date.DayOfWeek is DayOfWeek.Friday or DayOfWeek.Thursday)
.ToList();
var leaveList = _context.LeaveList
.Where(x => x.EmployeeId == employeeId
&& x.WorkshopId == workshopId
&& x.IsAccepted == true
&& x.StartLeave <= contractEnd
&& x.EndLeave >= contractStart
&& x.LeaveType == "استحقاقی"
&& x.PaidLeaveType =="روزانه")
.Select(x => new { x.StartLeave, x.EndLeave })
.ToList();
// بررسی کدام روزهای غایب جمعه/پنجشنبه در بازه مرخصی قرار ندارند
var absentFridaysOrThursdaysWithoutLeave = absentFridaysOrThursdays
.Where(date => !leaveList.Any(leave => date.Date >= leave.StartLeave.Date && date.Date <= leave.EndLeave.Date))
.ToList();
// تعداد روزهای غایب جمعه/پنجشنبه بدون مرخصی
int absentFridaysOrThursdaysWithoutLeaveCount = absentFridaysOrThursdaysWithoutLeave.Count;
absentsDeductionAmount += absentFridaysOrThursdaysWithoutLeaveCount * dailyWage;
#endregion
return new CustomizeCheckoutMandatoryViewModel

View File

@@ -2860,7 +2860,7 @@ public class YearlySalaryRepository : RepositoryBase<long, YearlySalary>, IYearl
var allContractsBetween = _context.Contracts.AsSplitQuery().Include(x => x.WorkingHoursList)
.Where(x => x.WorkshopIds == workshopId && x.EmployeeId == employeeId &&
x.ContractEnd >= startDate && x.ContarctStart <= endDate).ToList();
var isWorkshopStaticCheckout = _context.Workshops.FirstOrDefault(x => x.id == workshopId)!.IsStaticCheckout;
int mandatoryDays = 0;
double allCanToLeave = 0;
double canToLeave = 0;
@@ -2894,8 +2894,7 @@ public class YearlySalaryRepository : RepositoryBase<long, YearlySalary>, IYearl
var rollCallTotalHoures = GetTotalWorkingHoursIfHasRollCall(employeeId, workshopId,
contract.ContarctStart.Date, contract.ContractEnd.Date);
if (rollCallTotalHoures.hasRollCall && !isWorkshopStaticCheckout)
if (rollCallTotalHoures.hasRollCall)
{
totalWorkingHours = rollCallTotalHoures.WorkingTotalHours;
}
@@ -3376,7 +3375,6 @@ public class YearlySalaryRepository : RepositoryBase<long, YearlySalary>, IYearl
var allContractsBetween = _context.Contracts.AsSplitQuery().Include(x => x.WorkingHoursList)
.Where(x => x.WorkshopIds == workshopId && x.EmployeeId == employeeId &&
x.ContractEnd >= startDate && x.ContarctStart <= endDate).OrderBy(x => x.ContarctStart).ToList();
var isWorkshopStaticCheckout = _context.Workshops.FirstOrDefault(x => x.id == workshopId)!.IsStaticCheckout;
double canToLeave = 0;
int contractCounter = 0;
foreach (var contract in allContractsBetween)
@@ -3409,7 +3407,7 @@ public class YearlySalaryRepository : RepositoryBase<long, YearlySalary>, IYearl
var rollCallTotalHoures = GetTotalWorkingHoursIfHasRollCall(employeeId, workshopId,
contract.ContarctStart.Date, contract.ContractEnd.Date);
if (rollCallTotalHoures.hasRollCall && !isWorkshopStaticCheckout)
if (rollCallTotalHoures.hasRollCall)
{
totalWorkingHours = rollCallTotalHoures.WorkingTotalHours;
}

View File

@@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Shared.Contracts.Holidays;
namespace CompanyManagment.EFCore.Services;
public class HolidayQueryService : IHolidayQueryService
{
public Task<List<HolidayDto>> GetHolidaysInDates(DateTime startDate, DateTime endDate)
{
throw new NotImplementedException();
}
}

View File

@@ -1,31 +0,0 @@
using AccountMangement.Infrastructure.EFCore;
using Company.Domain._common;
using Microsoft.EntityFrameworkCore.Storage;
namespace CompanyManagment.EFCore._common;
public class UnitOfWork : IUnitOfWork
{
private readonly AccountContext _context;
private IDbContextTransaction _transaction;
public UnitOfWork(AccountContext context)
{
_context = context;
}
public void BeginAccountContext()
{
_transaction = _context.Database.BeginTransaction();
}
public void CommitAccountContext()
{
_transaction?.Commit();
}
public void RollbackAccountContext()
{
_transaction?.Rollback();
}
}

View File

@@ -88,24 +88,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyManagement.Infrastru
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BackgroundInstitutionContract.Task", "BackgroundInstitutionContract\BackgroundInstitutionContract.Task\BackgroundInstitutionContract.Task.csproj", "{F78FBB92-294B-88BA-168D-F0C578B0D7D6}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ProgramManager", "ProgramManager", "{67AFF7B6-4C4F-464C-A90D-9BDB644D83A9}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{48F6F6A5-7340-42F8-9216-BEB7A4B7D5A1}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Application", "Application", "{9D85672B-D48E-40B5-9804-0CE220E0E64C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Domain", "Domain", "{D74D1E3B-3BE3-47EE-9914-785A8AD536E5}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{C0AE9368-D4E7-450B-9713-929D319DE690}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GozareshgirProgramManager.Application", "ProgramManager\src\Application\GozareshgirProgramManager.Application\GozareshgirProgramManager.Application.csproj", "{B57EB542-C028-4A77-9386-9DFF1E60FDCB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GozareshgirProgramManager.Domain", "ProgramManager\src\Domain\GozareshgirProgramManager.Domain\GozareshgirProgramManager.Domain.csproj", "{D2B4F1D7-6336-4B30-910C-219F4119303F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GozareshgirProgramManager.Infrastructure", "ProgramManager\src\Infrastructure\GozareshgirProgramManager.Infrastructure\GozareshgirProgramManager.Infrastructure.csproj", "{408281FE-615F-4CBE-BD95-2E86F5ACC6C3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared.Contracts", "Shared.Contracts\Shared.Contracts.csproj", "{08B234B6-783B-44E9-9961-4F97EAD16308}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -216,22 +198,6 @@ Global
{F78FBB92-294B-88BA-168D-F0C578B0D7D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F78FBB92-294B-88BA-168D-F0C578B0D7D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F78FBB92-294B-88BA-168D-F0C578B0D7D6}.Release|Any CPU.Build.0 = Release|Any CPU
{B57EB542-C028-4A77-9386-9DFF1E60FDCB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B57EB542-C028-4A77-9386-9DFF1E60FDCB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B57EB542-C028-4A77-9386-9DFF1E60FDCB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B57EB542-C028-4A77-9386-9DFF1E60FDCB}.Release|Any CPU.Build.0 = Release|Any CPU
{D2B4F1D7-6336-4B30-910C-219F4119303F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D2B4F1D7-6336-4B30-910C-219F4119303F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D2B4F1D7-6336-4B30-910C-219F4119303F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D2B4F1D7-6336-4B30-910C-219F4119303F}.Release|Any CPU.Build.0 = Release|Any CPU
{408281FE-615F-4CBE-BD95-2E86F5ACC6C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{408281FE-615F-4CBE-BD95-2E86F5ACC6C3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{408281FE-615F-4CBE-BD95-2E86F5ACC6C3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{408281FE-615F-4CBE-BD95-2E86F5ACC6C3}.Release|Any CPU.Build.0 = Release|Any CPU
{08B234B6-783B-44E9-9961-4F97EAD16308}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{08B234B6-783B-44E9-9961-4F97EAD16308}.Debug|Any CPU.Build.0 = Debug|Any CPU
{08B234B6-783B-44E9-9961-4F97EAD16308}.Release|Any CPU.ActiveCfg = Release|Any CPU
{08B234B6-783B-44E9-9961-4F97EAD16308}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -268,13 +234,6 @@ Global
{BF98173C-42AF-4897-A7CB-4CACEB2B52A2} = {86921E1B-2AFA-4B8A-9403-EE16D58B5B26}
{97E148FA-3C36-40DD-B121-D90C1C0F3B47} = {C10E256D-7E7D-4C77-B416-E577A34AF924}
{F78FBB92-294B-88BA-168D-F0C578B0D7D6} = {C10E256D-7E7D-4C77-B416-E577A34AF924}
{48F6F6A5-7340-42F8-9216-BEB7A4B7D5A1} = {67AFF7B6-4C4F-464C-A90D-9BDB644D83A9}
{9D85672B-D48E-40B5-9804-0CE220E0E64C} = {48F6F6A5-7340-42F8-9216-BEB7A4B7D5A1}
{D74D1E3B-3BE3-47EE-9914-785A8AD536E5} = {48F6F6A5-7340-42F8-9216-BEB7A4B7D5A1}
{C0AE9368-D4E7-450B-9713-929D319DE690} = {48F6F6A5-7340-42F8-9216-BEB7A4B7D5A1}
{B57EB542-C028-4A77-9386-9DFF1E60FDCB} = {9D85672B-D48E-40B5-9804-0CE220E0E64C}
{D2B4F1D7-6336-4B30-910C-219F4119303F} = {D74D1E3B-3BE3-47EE-9914-785A8AD536E5}
{408281FE-615F-4CBE-BD95-2E86F5ACC6C3} = {C0AE9368-D4E7-450B-9713-929D319DE690}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E6CFB3A7-A7C8-4E82-8F06-F750408F0BA9}

View File

@@ -1,44 +1,18 @@
using _0_Framework.Application.FaceEmbedding;
using System;
using _0_Framework.Application.UID;
using _0_Framework.Infrastructure;
using _0_Framework.InfraStructure;
using Company.Application.Contracts.AuthorizedBankDetails;
using Company.Domain._common;
using Company.Domain.AdminMonthlyOverviewAgg;
using Company.Domain.AndroidApkVersionAgg;
using Company.Domain.AuthorizedBankDetailsAgg;
using Company.Domain.AuthorizedPersonAgg;
using Company.Domain.BankAgg;
using Company.Domain.BillAgg;
using Company.Domain.Board;
using Company.Domain.ChapterAgg;
using Company.Domain.CheckoutAgg;
using Company.Domain.ClassifiedSalaryAgg;
using Company.Domain.Contact2Agg;
using Company.Domain.ContactUsAgg;
using Company.Domain.ContarctingPartyAgg;
using Company.Domain.ContractAgg;
using Company.Domain.ContractingPartyBankAccountsAgg;
using Company.Domain.CrossJobAgg;
using Company.Domain.CrossJobGuildAgg;
using Company.Domain.CrossJobItemsAgg;
using Company.Domain.CustomizeCheckoutAgg;
using Company.Domain.CustomizeCheckoutTempAgg;
using Company.Domain.CustomizeWorkshopEmployeeSettingsAgg;
using Company.Domain.CustomizeWorkshopGroupSettingsAgg;
using Company.Domain.CustomizeWorkshopSettingsAgg;
using Company.Domain.DateSalaryAgg;
using Company.Domain.DateSalaryItemAgg;
using Company.Domain.ContarctingPartyAgg;
using Company.Domain.ContractAgg;
using Company.Domain.EmployeeAgg;
using Company.Domain.EmployeeAuthorizeTempAgg;
using Company.Domain.EmployeeBankInformationAgg;
using Company.Domain.EmployeeChildrenAgg;
using Company.Domain.EmployeeClientTempAgg;
using Company.Domain.EmployeeComputeOptionsAgg;
using Company.Domain.EmployeeDocumentItemAgg;
using Company.Domain.EmployeeDocumentsAdminSelectionAgg;
using Company.Domain.EmployeeDocumentsAgg;
using Company.Domain.EmployeeFaceEmbeddingAgg;
using Company.Domain.empolyerAgg;
using Company.Domain.Evidence;
using Company.Domain.EvidenceDetail;
@@ -49,108 +23,38 @@ using Company.Domain.FileEmployerAgg;
using Company.Domain.FileState;
using Company.Domain.FileTiming;
using Company.Domain.FileTitle;
using Company.Domain.FinancialInvoiceAgg;
using Company.Domain.FinancialStatmentAgg;
using Company.Domain.FinancialTransactionAgg;
using Company.Domain.FineAgg;
using Company.Domain.FineSubjectAgg;
using Company.Domain.GroupPlanAgg;
using Company.Domain.GroupPlanJobItemAgg;
using Company.Domain.HolidayAgg;
using Company.Domain.HolidayItemAgg;
using Company.Domain.InstitutionContractAgg;
using Company.Domain.InstitutionContractContactInfoAgg;
using Company.Domain.InstitutionContractExtensionTempAgg;
using Company.Domain.InstitutionPlanAgg;
using Company.Domain.InsuranceAgg;
using Company.Domain.InsuranceEmployeeInfoAgg;
using Company.Domain.InsuranceJobItemAgg;
using Company.Domain.InsuranceListAgg;
using Company.Domain.InsuranceYearlySalaryAgg;
using Company.Domain.InsurancJobAgg;
using Company.Domain.InsurancWorkshopInfoAgg;
using Company.Domain.JobAgg;
using Company.Domain.LawAgg;
using Company.Domain.LeaveAgg;
using Company.Domain.LeftWorkAgg;
using Company.Domain.LeftWorkInsuranceAgg;
using Company.Domain.LeftWorkTempAgg;
using Company.Domain.LoanAgg;
using Company.Domain.MandatoryHoursAgg;
using Company.Domain.MasterPenaltyTitle;
using Company.Domain.MasterPetition;
using Company.Domain.MasterWorkHistory;
using Company.Domain.ModuleAgg;
using Company.Domain.OriginalTitleAgg;
using Company.Domain.PaymentInstrumentAgg;
using Company.Domain.PaymentToEmployeeAgg;
using Company.Domain.PaymentToEmployeeItemAgg;
using Company.Domain.PaymentTransactionAgg;
using Company.Domain.PenaltyTitle;
using Company.Domain.PercentageAgg;
using Company.Domain.PersonnelCodeAgg;
using Company.Domain.Petition;
using Company.Domain.ProceedingSession;
using Company.Domain.ReportAgg;
using Company.Domain.ReportClientAgg;
using Company.Domain.RepresentativeAgg;
using Company.Domain.RewardAgg;
using Company.Domain.RollCallAgg;
using Company.Domain.RollCallAgg.DomainService;
using Company.Domain.RollCallEmployeeAgg;
using Company.Domain.RollCallEmployeeStatusAgg;
using Company.Domain.RollCallPlanAgg;
using Company.Domain.RollCallServiceAgg;
using Company.Domain.SalaryAidAgg;
using Company.Domain.SmsResultAgg;
using Company.Domain.SubtitleAgg;
using Company.Domain.TaxJobCategoryAgg;
using Company.Domain.TemporaryClientRegistrationAgg;
using Company.Domain.WorkHistory;
using Company.Domain.WorkingHoursAgg;
using Company.Domain.WorkingHoursItemsAgg;
using Company.Domain.WorkingHoursTempAgg;
using Company.Domain.WorkingHoursTempItemAgg;
using Company.Domain.WorkshopAccountAgg;
using Company.Domain.WorkshopAgg;
using Company.Domain.WorkshopPlanAgg;
using Company.Domain.WorkshopPlanEmployeeAgg;
using Company.Domain.WorkshopSubAccountAgg;
using Company.Domain.YearlySalaryAgg;
using Company.Domain.YearlySalaryItemsAgg;
using Company.Domain.YearlysSalaryTitleAgg;
using Company.Domain.ZoneAgg;
using CompanyManagement.Infrastructure.Excel.SalaryAid;
using CompanyManagement.Infrastructure.Mongo.EmployeeFaceEmbeddingRepo;
using CompanyManagement.Infrastructure.Mongo.InstitutionContractInsertTempRepo;
using CompanyManagment.App.Contracts.AdminMonthlyOverview;
using CompanyManagment.App.Contracts.AndroidApkVersion;
using CompanyManagment.App.Contracts.AuthorizedPerson;
using CompanyManagment.App.Contracts.Bank;
using CompanyManagment.App.Contracts.Board;
using CompanyManagment.App.Contracts.Chapter;
using CompanyManagment.App.Contracts.Checkout;
using CompanyManagment.App.Contracts.ClassifiedSalary;
using CompanyManagment.App.Contracts.Contact2;
using CompanyManagment.App.Contracts.ContactUs;
using CompanyManagment.App.Contracts.Contract;
using CompanyManagment.App.Contracts.ContractingPartyBankAccounts;
using CompanyManagment.App.Contracts.CrossJob;
using CompanyManagment.App.Contracts.CrossJobGuild;
using CompanyManagment.App.Contracts.CrossJobItems;
using CompanyManagment.App.Contracts.CustomizeCheckout;
using CompanyManagment.App.Contracts.CustomizeWorkshopSettings;
using CompanyManagment.App.Contracts.DateSalary;
using CompanyManagment.App.Contracts.DateSalaryItem;
using CompanyManagment.App.Contracts.Employee;
using CompanyManagment.App.Contracts.EmployeeBankInformation;
using CompanyManagment.App.Contracts.EmployeeChildren;
using CompanyManagment.App.Contracts.EmployeeClientTemp;
using CompanyManagment.App.Contracts.EmployeeComputeOptions;
using CompanyManagment.App.Contracts.EmployeeDocuments;
using CompanyManagment.App.Contracts.EmployeeDocumentsAdminSelection;
using CompanyManagment.App.Contracts.EmployeeFaceEmbedding;
using CompanyManagment.App.Contracts.EmployeeInsurancListData;
using CompanyManagment.App.Contracts.Employer;
using CompanyManagment.App.Contracts.Evidence;
using CompanyManagment.App.Contracts.EvidenceDetail;
@@ -161,82 +65,174 @@ using CompanyManagment.App.Contracts.FileEmployer;
using CompanyManagment.App.Contracts.FileState;
using CompanyManagment.App.Contracts.FileTiming;
using CompanyManagment.App.Contracts.FileTitle;
using CompanyManagment.App.Contracts.FinancialInvoice;
using CompanyManagment.App.Contracts.FinancialStatment;
using CompanyManagment.App.Contracts.FinancilTransaction;
using CompanyManagment.App.Contracts.Fine;
using CompanyManagment.App.Contracts.FineSubject;
using CompanyManagment.App.Contracts.Holiday;
using CompanyManagment.App.Contracts.HolidayItem;
using CompanyManagment.App.Contracts.InstitutionContract;
using CompanyManagment.App.Contracts.InstitutionContractContactinfo;
using CompanyManagment.App.Contracts.InstitutionPlan;
using CompanyManagment.App.Contracts.Insurance;
using CompanyManagment.App.Contracts.InsuranceEmployeeInfo;
using CompanyManagment.App.Contracts.InsuranceJob;
using CompanyManagment.App.Contracts.InsuranceList;
using CompanyManagment.App.Contracts.InsuranceWorkshopInfo;
using CompanyManagment.App.Contracts.InsuranceYearlySalary;
using CompanyManagment.App.Contracts.Job;
using CompanyManagment.App.Contracts.Law;
using CompanyManagment.App.Contracts.Leave;
using CompanyManagment.App.Contracts.LeftWork;
using CompanyManagment.App.Contracts.LeftWorkInsurance;
using CompanyManagment.App.Contracts.LeftWorkTemp;
using CompanyManagment.App.Contracts.Loan;
using CompanyManagment.App.Contracts.MandantoryHours;
using CompanyManagment.App.Contracts.MasterPenaltyTitle;
using CompanyManagment.App.Contracts.MasterPetition;
using CompanyManagment.App.Contracts.MasterWorkHistory;
using CompanyManagment.App.Contracts.Module;
using CompanyManagment.App.Contracts.OriginalTitle;
using CompanyManagment.App.Contracts.PaymentInstrument;
using CompanyManagment.App.Contracts.PaymentToEmployee;
using CompanyManagment.App.Contracts.PaymentTransaction;
using CompanyManagment.App.Contracts.PenaltyTitle;
using CompanyManagment.App.Contracts.Percentage;
using CompanyManagment.App.Contracts.PersonalContractingParty;
using CompanyManagment.App.Contracts.PersonnleCode;
using CompanyManagment.App.Contracts.Petition;
using CompanyManagment.App.Contracts.ProceedingSession;
using CompanyManagment.App.Contracts.Report;
using CompanyManagment.App.Contracts.ReportClient;
using CompanyManagment.App.Contracts.Representative;
using CompanyManagment.App.Contracts.Reward;
using CompanyManagment.App.Contracts.RollCall;
using CompanyManagment.App.Contracts.RollCallEmployee;
using CompanyManagment.App.Contracts.RollCallEmployeeStatus;
using CompanyManagment.App.Contracts.RollCallPlan;
using CompanyManagment.App.Contracts.RollCallService;
using CompanyManagment.App.Contracts.SalaryAid;
using CompanyManagment.App.Contracts.SmsResult;
using CompanyManagment.App.Contracts.Subtitle;
using CompanyManagment.App.Contracts.TaxJobCategory;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using CompanyManagment.App.Contracts.TextManager;
using CompanyManagment.App.Contracts.WorkHistory;
using CompanyManagment.App.Contracts.WorkingHours;
using CompanyManagment.App.Contracts.WorkingHoursItems;
using CompanyManagment.App.Contracts.WorkingHoursTemp;
using CompanyManagment.App.Contracts.WorkingHoursTempItem;
using CompanyManagment.App.Contracts.Workshop;
using CompanyManagment.App.Contracts.WorkshopPlan;
using CompanyManagment.App.Contracts.YearlySalary;
using CompanyManagment.App.Contracts.YearlySalaryItems;
using CompanyManagment.App.Contracts.YearlySalaryTitles;
using CompanyManagment.App.Contracts.Zone;
using CompanyManagment.Application;
using CompanyManagment.EFCore;
using CompanyManagment.EFCore._common;
using CompanyManagment.EFCore.Repository;
using CompanyManagment.EFCore.Repository;
using File.EfCore.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using P_TextManager.Domin.TextManagerAgg;
using Shared.Contracts.Holidays;
using System;
using CompanyManagment.EFCore.Services;
using CompanyManagment.App.Contracts.CrossJobItems;
using Company.Domain.CrossJobItemsAgg;
using Company.Domain.DateSalaryAgg;
using Company.Domain.DateSalaryItemAgg;
using Company.Domain.FinancialStatmentAgg;
using Company.Domain.FinancialTransactionAgg;
using Company.Domain.GroupPlanAgg;
using Company.Domain.GroupPlanJobItemAgg;
using Company.Domain.InstitutionContractAgg;
using Company.Domain.InstitutionContractContactInfoAgg;
using CompanyManagment.App.Contracts.Insurance;
using Company.Domain.InsuranceAgg;
using Company.Domain.InsuranceEmployeeInfoAgg;
using Company.Domain.InsuranceJobItemAgg;
using Company.Domain.InsuranceListAgg;
using Company.Domain.InsurancJobAgg;
using Company.Domain.InsurancWorkshopInfoAgg;
using Company.Domain.LeftWorkInsuranceAgg;
using Company.Domain.PaymentToEmployeeAgg;
using Company.Domain.PaymentToEmployeeItemAgg;
using Company.Domain.PercentageAgg;
using Company.Domain.PersonnelCodeAgg;
using Company.Domain.SmsResultAgg;
using Company.Domain.WorkingHoursTempAgg;
using Company.Domain.WorkingHoursTempItemAgg;
using Company.Domain.WorkshopPlanAgg;
using Company.Domain.WorkshopPlanEmployeeAgg;
using Company.Domain.ZoneAgg;
using CompanyManagment.App.Contracts.ClassifiedSalary;
using CompanyManagment.App.Contracts.DateSalary;
using CompanyManagment.App.Contracts.DateSalaryItem;
using CompanyManagment.App.Contracts.EmployeeInsurancListData;
using CompanyManagment.App.Contracts.FinancialStatment;
using CompanyManagment.App.Contracts.FinancilTransaction;
using CompanyManagment.App.Contracts.InstitutionContract;
using CompanyManagment.App.Contracts.InstitutionContractContactinfo;
using CompanyManagment.App.Contracts.InsuranceEmployeeInfo;
using CompanyManagment.App.Contracts.InsuranceJob;
using CompanyManagment.App.Contracts.InsuranceList;
using CompanyManagment.App.Contracts.InsuranceWorkshopInfo;
using CompanyManagment.App.Contracts.LeftWorkInsurance;
using CompanyManagment.App.Contracts.PaymentToEmployee;
using CompanyManagment.App.Contracts.Percentage;
using CompanyManagment.App.Contracts.PersonnleCode;
using CompanyManagment.App.Contracts.SmsResult;
using CompanyManagment.App.Contracts.WorkingHoursTemp;
using CompanyManagment.App.Contracts.WorkingHoursTempItem;
using CompanyManagment.App.Contracts.WorkshopPlan;
using CompanyManagment.App.Contracts.Zone;
using CompanyManagment.App.Contracts.EmployeeComputeOptions;
using Company.Domain.EmployeeComputeOptionsAgg;
using Company.Domain.InsuranceYearlySalaryAgg;
using Company.Domain.ReportAgg;
using Company.Domain.RollCallAgg;
using Company.Domain.RollCallEmployeeAgg;
using Company.Domain.RollCallPlanAgg;
using Company.Domain.RollCallServiceAgg;
using CompanyManagment.App.Contracts.InsuranceYearlySalary;
using CompanyManagment.App.Contracts.Report;
using CompanyManagment.App.Contracts.RollCall;
using CompanyManagment.App.Contracts.RollCallEmployee;
using CompanyManagment.App.Contracts.RollCallService;
using CompanyManagment.App.Contracts.RollCallPlan;
using Company.Domain.ReportClientAgg;
using Company.Domain.TaxJobCategoryAgg;
using Company.Domain.WorkshopAccountAgg;
using CompanyManagment.App.Contracts.ReportClient;
using CompanyManagment.App.Contracts.TaxJobCategory;
using Company.Domain.RollCallEmployeeStatusAgg;
using CompanyManagment.App.Contracts.RollCallEmployeeStatus;
using Company.Domain.CustomizeWorkshopEmployeeSettingsAgg;
using Company.Domain.CustomizeWorkshopGroupSettingsAgg;
using Company.Domain.CustomizeWorkshopSettingsAgg;
using Company.Domain.FineAgg;
using Company.Domain.LoanAgg;
using Company.Domain.RewardAgg;
using Company.Domain.SalaryAidAgg;
using CompanyManagment.App.Contracts.CustomizeWorkshopSettings;
using CompanyManagment.App.Contracts.Fine;
using CompanyManagment.App.Contracts.Loan;
using CompanyManagment.App.Contracts.Reward;
using CompanyManagment.App.Contracts.SalaryAid;
using Company.Domain.AndroidApkVersionAgg;
using Company.Domain.BankAgg;
using CompanyManagment.App.Contracts.AndroidApkVersion;
using Company.Domain.FineSubjectAgg;
using CompanyManagment.App.Contracts.FineSubject;
using Company.Domain.CustomizeCheckoutAgg;
using CompanyManagment.App.Contracts.CustomizeCheckout;
using Company.Domain.WorkshopSubAccountAgg;
using Company.Domain.CustomizeCheckoutTempAgg;
using Company.Domain.EmployeeBankInformationAgg;
using Company.Domain.RollCallAgg.DomainService;
using CompanyManagment.App.Contracts.Bank;
using CompanyManagment.App.Contracts.EmployeeBankInformation;
using Company.Domain.EmployeeDocumentItemAgg;
using Company.Domain.EmployeeDocumentsAdminSelectionAgg;
using Company.Domain.EmployeeDocumentsAgg;
using CompanyManagement.Infrastructure.Excel.SalaryAid;
using CompanyManagment.App.Contracts.EmployeeDocuments;
using CompanyManagment.App.Contracts.EmployeeDocumentsAdminSelection;
using Company.Domain.EmployeeClientTempAgg;
using Company.Domain.InstitutionPlanAgg;
using Company.Domain.LeftWorkTempAgg;
using Company.Domain.TemporaryClientRegistrationAgg;
using CompanyManagment.App.Contracts.EmployeeClientTemp;
using CompanyManagment.App.Contracts.InstitutionPlan;
using CompanyManagment.App.Contracts.LeftWorkTemp;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using Company.Domain.ContactUsAgg;
using CompanyManagment.App.Contracts.ContactUs;
using Company.Domain.EmployeeAuthorizeTempAgg;
using Company.Domain.AdminMonthlyOverviewAgg;
using Company.Domain.AuthorizedBankDetailsAgg;
using Company.Domain.ContractingPartyBankAccountsAgg;
using Company.Domain.PaymentInstrumentAgg;
using Company.Domain.PaymentTransactionAgg;
using Company.Domain.FinancialInvoiceAgg;
using CompanyManagment.App.Contracts.AdminMonthlyOverview;
using CompanyManagment.App.Contracts.ContractingPartyBankAccounts;
using CompanyManagment.App.Contracts.PaymentInstrument;
using CompanyManagment.App.Contracts.PaymentTransaction;
using CompanyManagment.App.Contracts.AuthorizedPerson;
using Company.Domain.AuthorizedPersonAgg;
using Company.Domain.EmployeeFaceEmbeddingAgg;
using Company.Domain.InstitutionContractExtensionTempAgg;
using Company.Domain.LawAgg;
using CompanyManagement.Infrastructure.Mongo.EmployeeFaceEmbeddingRepo;
using CompanyManagement.Infrastructure.Mongo.InstitutionContractInsertTempRepo;
using CompanyManagment.App.Contracts.EmployeeFaceEmbedding;
using CompanyManagment.App.Contracts.Law;
using CompanyManagment.EFCore.Repository;
using CompanyManagment.App.Contracts.FinancialInvoice;
using _0_Framework.Application.FaceEmbedding;
using _0_Framework.Infrastructure;
using _0_Framework.InfraStructure;
namespace PersonalContractingParty.Config;
@@ -244,12 +240,6 @@ public class PersonalBootstrapper
{
public static void Configure(IServiceCollection services, string connectionString)
{
#region Services
services.AddTransient<IHolidayQueryService, HolidayQueryService>();
#endregion
//----Task-Manager-Project---------------------------------
//services.AddTransient<ITaskApplication, TaskApplication>();
@@ -555,13 +545,6 @@ public class PersonalBootstrapper
services.AddTransient<ISmsSettingsRepository, SmsSettingsRepository>();
services.AddTransient<ISmsSettingApplication, SmsSettingApplication>();
#endregion
#region UnitOfWork
services.AddTransient<IUnitOfWork, UnitOfWork>();
#endregion
//=========End Of Main====================================

View File

@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,33 +0,0 @@
using MediatR;
using Microsoft.Extensions.Logging;
using GozareshgirProgramManager.Domain.CustomerAgg.Events;
using GozareshgirProgramManager.Application._Common.Models;
namespace GozareshgirProgramManager.Application.DomainEventHandlers;
public class CustomerRegisteredHandler : INotificationHandler<DomainEventNotification<CustomerRegistered>>
{
private readonly ILogger<CustomerRegisteredHandler> _logger;
public CustomerRegisteredHandler(ILogger<CustomerRegisteredHandler> logger)
{
_logger = logger;
}
public Task Handle(DomainEventNotification<CustomerRegistered> notification, CancellationToken cancellationToken)
{
var domainEvent = notification.DomainEvent;
_logger.LogInformation(
"Customer registered: {CustomerId}, Name: {Name}, Email: {Email}",
domainEvent.CustomerId,
domainEvent.Name,
domainEvent.Email);
// اینجا می‌توانید email ارسال کنید یا کارهای دیگر انجام دهید
return Task.CompletedTask;
}
}

View File

@@ -1,23 +0,0 @@
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Application.Interfaces;
using GozareshgirProgramManager.Domain.ProjectAgg.Events;
using MediatR;
using Microsoft.Extensions.Logging;
namespace GozareshgirProgramManager.Application.DomainEventHandlers.ProjectSection;
public class ProjectSectionAddedHandler:INotificationHandler<DomainEventNotification<ProjectSectionAddedEvent>>
{
private readonly ILogger<CustomerRegisteredHandler> _logger;
public ProjectSectionAddedHandler(ILogger<CustomerRegisteredHandler> logger)
{
_logger = logger;
}
public Task Handle(DomainEventNotification<ProjectSectionAddedEvent> notification, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}

View File

@@ -1,14 +0,0 @@
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain.ProjectAgg.Events;
using MediatR;
namespace GozareshgirProgramManager.Application.DomainEventHandlers.ProjectSection;
public class ProjectSectionAssignedHandler:INotificationHandler<DomainEventNotification<ProjectSectionAssignedEvent>>
{
public Task Handle(DomainEventNotification<ProjectSectionAssignedEvent> notification, CancellationToken cancellationToken)
{
var domainEvent = notification.DomainEvent;
return Task.CompletedTask;
}
}

View File

@@ -1,21 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="12.1.1" />
<PackageReference Include="MediatR" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\Domain\GozareshgirProgramManager.Domain\GozareshgirProgramManager.Domain.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,6 +0,0 @@
namespace GozareshgirProgramManager.Application.Interfaces;
public interface IBoardNotificationService
{
Task SendProjectAssignedAsync();
}

View File

@@ -1,267 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Application.Modules.Checkouts.Queries.GetUserToGropCreate;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.CheckoutAgg.Entities;
using GozareshgirProgramManager.Domain.CheckoutAgg.Enums;
using GozareshgirProgramManager.Domain.CheckoutAgg.Repositories;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using GozareshgirProgramManager.Domain.SalaryPaymentSettingAgg.DTOs;
using GozareshgirProgramManager.Domain.SalaryPaymentSettingAgg.Enums;
using GozareshgirProgramManager.Domain.SalaryPaymentSettingAgg.Repositories;
using GozareshgirProgramManager.Domain.UserAgg.Entities;
using MediatR;
using PersianTools.Core;
using System.Runtime.InteropServices;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Holidays;
namespace GozareshgirProgramManager.Application.Modules.Checkouts.Commands.CreateCheckout;
public class CreateOrEditCheckoutCommandHandler : IBaseCommandHandler<CreateOrEditCheckoutCommand>
{
private readonly ICheckoutRepository _checkoutRepository;
private readonly ISalaryPaymentSettingRepository _salaryPaymentSettingRepository;
private readonly ITaskSectionActivityRepository _taskSectionActivityRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IHolidayQueryService _holidayQueryService;
public CreateOrEditCheckoutCommandHandler(ICheckoutRepository checkoutRepository, IUnitOfWork unitOfWork,
ISalaryPaymentSettingRepository salaryPaymentSettingRepository,
ITaskSectionActivityRepository taskSectionActivityRepository, IHolidayQueryService holidayQueryService)
{
_checkoutRepository = checkoutRepository;
_unitOfWork = unitOfWork;
_salaryPaymentSettingRepository = salaryPaymentSettingRepository;
_taskSectionActivityRepository = taskSectionActivityRepository;
_holidayQueryService = holidayQueryService;
}
public async Task<OperationResult> Handle(CreateOrEditCheckoutCommand request, CancellationToken cancellationToken)
{
switch (request.TypeOfCheckoutHandler)
{
case TypeOfCheckoutHandler.CreateInGroup:
return await Create(request.Year, request.Month, request.UserIdList);
break;
case TypeOfCheckoutHandler.SingleEdit:
case TypeOfCheckoutHandler.GroupEditing:
return await GroupOrSingleEditing(request.CheckoutIdList);
break;
}
return OperationResult.Failure("نوع متد انتخاب نشده است");
}
/// <summary>
/// ایجاد گروهی فیش حقوقی
/// </summary>
/// <param name="Year"></param>
/// <param name="Month"></param>
/// <param name="UserIdList"></param>
/// <returns></returns>
public async Task<OperationResult> Create(string? Year, string? Month, List<long>? UserIdList)
{
if (string.IsNullOrWhiteSpace(Month))
return OperationResult.Failure("ماه خالی است");
if (string.IsNullOrWhiteSpace(Year))
return OperationResult.Failure("سال خالی است");
if (UserIdList == null)
return OperationResult.Failure("هیچ موردی برای ایجاد انتخاب نشده اشت");
if (UserIdList.Count == 0)
return OperationResult.Failure("هیچ موردی برای ایجاد انتخاب نشده اشت");
var startDateGr = new DateTime();
var EndDateGr = new DateTime();
var persianStart = new PersianDateTime();
int year = 0;
int month = 0;
try
{
year = Convert.ToInt32(Year);
month = Convert.ToInt32(Month);
persianStart = new PersianDateTime(year, month, 1);
var startDateFa = $"{persianStart}";
startDateGr = startDateFa.ToGeorgianDateTime();
var endDateFa = startDateFa.FindeEndOfMonth();
EndDateGr = endDateFa.ToGeorgianDateTime();
}
catch (Exception)
{
return OperationResult<GetUserToGroupCreatingResponse>.Failure(
"خطا در ورود سال و ماه");
}
var totalDays = Convert.ToInt32((EndDateGr - startDateGr).TotalDays + 1);
var getAllSettings = await _salaryPaymentSettingRepository.GetAllSettings(UserIdList);
var get = await _taskSectionActivityRepository.GetTotalTimeSpentPerUserInRangeAsync(startDateGr, EndDateGr);
foreach (var user in getAllSettings)
{
var totalWorked = get.FirstOrDefault(x => x.UserId == user.UserId);
var totalTimeTotalMinutes = (int)totalWorked.TotalTime.TotalMinutes;
var res = await ComputeSalary(user.WorkingHoursListDto, totalTimeTotalMinutes, user.MonthlySalary, startDateGr, EndDateGr, user.HolidayWorking);
var createCheckout = new Checkout(startDateGr, EndDateGr, year, month, user.FullName, user.UserId,
res.MandatoryHours, totalTimeTotalMinutes,
totalDays, res.RemainingHours, user.MonthlySalary, res.MonthlySalaryPay, res.DeductionFromSalary);
await _checkoutRepository.CreateAsync(createCheckout);
}
await _unitOfWork.SaveChangesAsync();
return OperationResult.Success();
}
/// <summary>
/// متد ویراش گروهی و تکی
/// </summary>
/// <param name="CheckoutIdList"></param>
/// <param name="CheckoutId"></param>
/// <param name="TypeOfCheckoutHandler"></param>
/// <returns></returns>
public async Task<OperationResult> GroupOrSingleEditing(List<Guid>? CheckoutIdList)
{
if (CheckoutIdList == null)
return OperationResult.Failure("هیچ موردی برای ویرایش انتخاب نشده اشت");
if (CheckoutIdList.Count == 0)
return OperationResult.Failure("هیچ موردی برای ویرایش انتخاب نشده اشت");
var checkouts = await _checkoutRepository.GetCheckoutListByIds(CheckoutIdList);
if (!checkouts.Any())
return OperationResult.Failure("هیچ موردی برای ویرایش انتخاب نشده اشت");
var UserIdList = checkouts.Select(x => x.UserId).ToList();
var getAllSettings = await _salaryPaymentSettingRepository.GetAllSettings(UserIdList);
if (!getAllSettings.Any())
return OperationResult.Failure("تنظیمات ساعت و حقوق یافت نشد");
foreach (var checkoutId in CheckoutIdList)
{
var checkout = checkouts.FirstOrDefault(x => x.Id == checkoutId);
if (checkout == null)
return OperationResult.Failure("فیش مورد نظر یافت نشد");
var userSetting = getAllSettings.FirstOrDefault(x => x.UserId == checkout.UserId);
var get = await _taskSectionActivityRepository.GetTotalTimeSpentByUserInRangeAsync(checkout.UserId, checkout.CheckoutStartDate, checkout.CheckoutEndDate);
var totalTimeTotalMinutes = (int)get.TotalMinutes;
var totalDays = Convert.ToInt32((checkout.CheckoutEndDate - checkout.CheckoutStartDate).TotalDays + 1);
var res = await ComputeSalary(userSetting.WorkingHoursListDto, totalTimeTotalMinutes, userSetting.MonthlySalary, checkout.CheckoutStartDate, checkout.CheckoutEndDate, userSetting.HolidayWorking);
checkout.Edit(res.MandatoryHours, totalTimeTotalMinutes, totalDays, res.RemainingHours, userSetting.MonthlySalary, res.MonthlySalaryPay, res.DeductionFromSalary);
await _unitOfWork.SaveChangesAsync();
}
return OperationResult.Success();
}
/// <summary>
/// محاسبه حقوق
/// </summary>
/// <returns></returns>
public async Task<ComputeResultDto> ComputeSalary(List<WorkingHoursListDto> workingHoursListDto, int totalHoursWorked, double monthlySalaryDefined, DateTime start, DateTime end, bool holidayWorking)
{
var startDate = start.ToFarsi();
var startYear = Convert.ToInt32(startDate.Substring(0, 4));
var startMonth = Convert.ToInt32(startDate.Substring(5, 2));
var startDay = Convert.ToInt32(startDate.Substring(8, 2));
var persianStart = new PersianDateTime(startYear, startMonth, startDay);
var endDate = end.ToFarsi();
var endYear = Convert.ToInt32(endDate.Substring(0, 4));
var endMonth = Convert.ToInt32(endDate.Substring(5, 2));
var endDay = Convert.ToInt32(endDate.Substring(8, 2));
var persianEnd = new PersianDateTime(endYear, endMonth, endDay);
var holidays = await _holidayQueryService.GetHolidaysInDates(start, end) ;
int mandatoryHours = 0;
for (var currentDay = persianStart; currentDay <= persianEnd; currentDay = currentDay.AddDays(1))
{
var currentDayOfWeek = new DNTPersianUtils.Core.PersianDateTime(currentDay.Year, currentDay.Month, currentDay.Day);
var holidayDate = currentDay.ShamsiDate.ToGeorgianDateTime();
var day = (PersianDayOfWeek)currentDayOfWeek.WeekDayNumber!;
var getDaySetting = workingHoursListDto.FirstOrDefault(x => x.PersianDayOfWeek == day);
if (getDaySetting != null)
{
if (!holidayWorking && holidays.Any(x => x.Holidaydate == holidayDate))
{
}
else
{
mandatoryHours += (int)getDaySetting.ShiftDuration.TotalMinutes;
Console.WriteLine((int)getDaySetting.ShiftDuration.TotalMinutes + " " + currentDay + " - " + day);
}
}
}
//حقوق نهایی
var monthlySalaryPay = (totalHoursWorked * monthlySalaryDefined) / mandatoryHours;
// اگر اضافه کار داشت حقوق تعین شده به عنوان حقوق نهایی در نظر گرفته میشود
monthlySalaryPay = monthlySalaryPay > monthlySalaryDefined ? monthlySalaryDefined : monthlySalaryPay;
//حقوق کسر شده
var deductionFromSalary = monthlySalaryDefined - monthlySalaryPay;
//زمان باقی مانده
var remainingTime = totalHoursWorked - mandatoryHours;
var computeResult = new ComputeResultDto
{
MandatoryHours = mandatoryHours,
MonthlySalaryPay = monthlySalaryPay,
DeductionFromSalary = deductionFromSalary,
RemainingHours = remainingTime
};
Console.WriteLine(mandatoryHours);
return computeResult;
}
}
public record CreateOrEditCheckoutCommand(TypeOfCheckoutHandler TypeOfCheckoutHandler, string? Year, string? Month, List<long>? UserIdList, List<Guid>? CheckoutIdList) : IBaseCommand;
public record ComputeResultDto
{
/// <summary>
/// ساعات باقی مانده
/// کسر کار یا اضافه کار
/// </summary>
public int RemainingHours { get; set; }
/// <summary>
/// حقوق نهایی که به پرسنل داده می شود
/// </summary>
public double MonthlySalaryPay { get; set; }
/// <summary>
/// کسر از حقوق
/// </summary>
public double DeductionFromSalary { get; set; }
/// <summary>
/// ساعت موظفی
/// </summary>
public int MandatoryHours { get; set; }
}

View File

@@ -1,130 +0,0 @@
using GozareshgirProgramManager.Application._Common.Extensions;
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Application.Modules.Checkouts.Queries.GetUserToGropCreate;
using GozareshgirProgramManager.Domain._Common;
using Microsoft.EntityFrameworkCore;
namespace GozareshgirProgramManager.Application.Modules.Checkouts.Queries.GetCheckoutList;
public class GetCheckoutListQueryHandler : IBasePaginationQueryHandler<GetCheckoutListQuery, GetCheckoutListResponse>
{
private readonly IProgramManagerDbContext _programManagerDbContext;
public GetCheckoutListQueryHandler(IProgramManagerDbContext programManagerDbContext)
{
_programManagerDbContext = programManagerDbContext;
}
public async Task<OperationResult<PaginationResult<GetCheckoutListResponse>>> Handle(GetCheckoutListQuery request, CancellationToken cancellationToken)
{
var query = _programManagerDbContext.Checkouts.AsQueryable();
if (!string.IsNullOrWhiteSpace(request.Year))
{
var year = Convert.ToInt32(request.Year);
query = query.Where(x => x.Year == year);
}
if (!string.IsNullOrWhiteSpace(request.Month))
{
var month = Convert.ToInt32(request.Month);
query = query.Where(x => x.Month == month);
}
if (!string.IsNullOrWhiteSpace(request.FullName))
query = query.Where(x => x.FullName.Contains(request.FullName));
var res =await query.Select(x => new GetCheckoutListResponse()
{
CheckoutId = x.Id,
Year = x.Year,
Month = x.PersianMonthName,
FullName = x.FullName,
MandatoryHours = x.MandatoryHours,
TotalHoursWorked = x.TotalHoursWorked,
RemainingHours = x.RemainingHours,
MonthlySalaryDefined = x.MonthlySalaryDefined.ToMoney(),
DeductionFromSalary = x.DeductionFromSalary.ToMoney(),
MonthlySalaryPay = x.MonthlySalaryPay.ToMoney()
}).ApplyPagination(request.PageIndex,request.PageSize).ToListAsync(cancellationToken: cancellationToken);
var response = new PaginationResult<GetCheckoutListResponse>
{
List = res,
TotalCount = query.Count(),
};
return OperationResult<PaginationResult<GetCheckoutListResponse>>.Success(response);
}
}
public record GetCheckoutListQuery(string? Month, string? Year, string? FullName) : PaginationRequest, IBasePaginationQuery<GetCheckoutListResponse>;
public record GetCheckoutListResponse
{
/// <summary>
/// آی دی فیش حقوقی
/// </summary>
public Guid CheckoutId { get; set; }
/// <summary>
/// سال
/// </summary>
public int Year { get; set; }
/// <summary>
/// ماه
/// </summary>
public string Month { get; set; }
/// <summary>
/// نام کامل پرسنل
/// </summary>
public string FullName { get; set; }
/// <summary>
/// ساعت موظفی
/// </summary>
public int MandatoryHours { get; set; }
/// <summary>
/// مجموع ساعات کارکرد پرسنل
/// </summary>
public int TotalHoursWorked { get; set; }
/// <summary>
/// ساعات باقی مانده
/// کسر کار یا اضافه کار
/// </summary>
public int RemainingHours { get; set; }
/// <summary>
/// حقوق ماهانه
/// تعیین شده
/// </summary>
public string MonthlySalaryDefined { get; set; }
/// <summary>
/// کسر از حقوق
/// </summary>
public string DeductionFromSalary { get; set; }
/// <summary>
/// حقوق نهایی که به پرسنل داده می شود
/// </summary>
public string MonthlySalaryPay { get; set; }
}

View File

@@ -1,174 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Application.Modules.SalaryPaymentSettings.Queries.GetUserListWhoHaveSettings;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.CheckoutAgg.Enums;
using Microsoft.EntityFrameworkCore;
using PersianTools.Core;
namespace GozareshgirProgramManager.Application.Modules.Checkouts.Queries.GetUserToGropCreate;
/// <summary>
/// دریافت کاربران برای ایجاد گروهی فیش حقوقی با سال و ماه
/// </summary>
public class GetUserToGroupCreatingQueryHandler : IBaseQueryHandler<GetUserToGroupCreatingQuery, GetUserToGroupCreatingResponse>
{
private readonly IProgramManagerDbContext _context;
public GetUserToGroupCreatingQueryHandler(IProgramManagerDbContext context)
{
_context = context;
}
public async Task<OperationResult<GetUserToGroupCreatingResponse>> Handle(GetUserToGroupCreatingQuery request, CancellationToken cancellationToken)
{
//سال و ماه انتخاب شده از فرانت
var selectedDate = new DateTime();
try
{
int year = Convert.ToInt32(request.Year);
int month = Convert.ToInt32(request.Month);
selectedDate = ($"{new PersianDateTime(year,month,1)}").ToGeorgianDateTime();
}
catch (Exception)
{
return OperationResult<GetUserToGroupCreatingResponse>.Failure(
"خطا در ورود سال و ماه");
}
//آخرین تاریخ مجاز برای ایجاد فیش
var lastMonth = ($"{DateTime.Now.ToFarsi().Substring(0, 8)}01").ToGeorgianDateTime().AddDays(-1);
if (selectedDate > lastMonth)
return OperationResult<GetUserToGroupCreatingResponse>.Failure(
"ایجاد فیش فقط برای ماه های گذشته امکان پذیر است");
var lastMonthStart = lastMonth;
var lastMonthEnd = lastMonth;
var query =
await (from u in _context.Users
// LEFT JOIN
// تنظیمات حقوق
join s in _context.SalaryPaymentSettings
on u.Id equals s.UserId into sJoin
from s in sJoin.DefaultIfEmpty()
// 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()
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 responseList = query.Select(x =>
{
bool validToCreate = x.HasSalarySettings && !x.HasCheckout;
string message = "آماده تنظیم";
CreateCheckoutStatus createCheckoutStatus = CreateCheckoutStatus.ReadyToCreate;
if (x.HasCheckout)
{
message = "موجود است";
createCheckoutStatus = CreateCheckoutStatus.AlreadyCreated;
}
if (!x.HasSalarySettings)
{
message = "فاقد تنظیمات";
createCheckoutStatus = CreateCheckoutStatus.NotSetSalaryPaymentSettings;
}
return new GetUserToGroupCreatingDto
{
UserId = x.UserId,
FullName = x.FullName,
IsValidToCreate = validToCreate,
StatusMessage = message,
CreateCheckoutStatus = createCheckoutStatus
};
}).OrderByDescending(x=>x.IsValidToCreate).ToList();
var response = new GetUserToGroupCreatingResponse(responseList);
return OperationResult<GetUserToGroupCreatingResponse>.Success(response);
}
}
public record GetUserToGroupCreatingQuery(string Year, string Month) : IBaseQuery<GetUserToGroupCreatingResponse>;
public record GetUserToGroupCreatingResponse(List<GetUserToGroupCreatingDto> GetUserToGroupCreatingDtoList);
public record GetUserToGroupCreatingDto
{
/// <summary>
/// آی دی کاربر
/// </summary>
public long UserId { get; set; }
/// <summary>
/// نام کامل پرسنل
/// </summary>
public string FullName { get; set; }
/// <summary>
/// پیام وضعیت ایجاد فیش
/// </summary>
public string StatusMessage { get; set; }
/// <summary>
/// آیا مجاز به ایجاد فیش می باشد
/// </summary>
public bool IsValidToCreate { get; set; }
public CreateCheckoutStatus CreateCheckoutStatus { get; set; }
}
public record GetUserWhoHaveSettingsAndCheckoutDto
{
/// <summary>
/// آی دی کاربر
/// </summary>
public long UserId { get; set; }
/// <summary>
/// نام کامل پرسنل
/// </summary>
public string FullName { get; set; }
/// <summary>
/// داشتن تنظیمات
/// </summary>
public bool HasSalarySettings { get; set; }
public bool HasCheckout { get; set; }
}

View File

@@ -1,13 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AddPhaseToProject;
/// <summary>
/// Command to add a phase to an existing project
/// </summary>
public record AddPhaseToProjectCommand(
Guid ProjectId,
string Name,
string? Description = null,
int OrderIndex = 0
) : IBaseCommand;

View File

@@ -1,47 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using MediatR;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AddPhaseToProject;
public class AddPhaseToProjectCommandHandler : IRequestHandler<AddPhaseToProjectCommand, OperationResult>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public AddPhaseToProjectCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository;
_unitOfWork = unitOfWork;
}
public async Task<OperationResult> Handle(AddPhaseToProjectCommand request, CancellationToken cancellationToken)
{
try
{
// Get project
var project = await _projectRepository.GetByIdAsync(request.ProjectId);
if (project == null)
{
return OperationResult.NotFound("پروژه یافت نشد");
}
// Add phase
var phase = project.AddPhase(request.Name, request.Description);
phase.SetOrderIndex(request.OrderIndex);
// Save changes
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
catch (Exception ex)
{
return OperationResult.Failure($"خطا در افزودن فاز: {ex.Message}");
}
}
}

View File

@@ -1,16 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AddTaskToPhase;
/// <summary>
/// Command to add a task to an existing phase
/// </summary>
public record AddTaskToPhaseCommand(
Guid PhaseId,
string Name,
string? Description = null,
TaskPriority Priority = TaskPriority.Medium,
int OrderIndex = 0,
DateTime? DueDate = null
) : IBaseCommand;

View File

@@ -1,53 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using MediatR;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AddTaskToPhase;
public class AddTaskToPhaseCommandHandler : IRequestHandler<AddTaskToPhaseCommand, OperationResult>
{
private readonly IProjectPhaseRepository _phaseRepository;
private readonly IUnitOfWork _unitOfWork;
public AddTaskToPhaseCommandHandler(
IProjectPhaseRepository phaseRepository,
IUnitOfWork unitOfWork)
{
_phaseRepository = phaseRepository;
_unitOfWork = unitOfWork;
}
public async Task<OperationResult> Handle(AddTaskToPhaseCommand request, CancellationToken cancellationToken)
{
try
{
// Get phase
var phase = await _phaseRepository.GetByIdAsync(request.PhaseId);
if (phase == null)
{
return OperationResult.NotFound("فاز یافت نشد");
}
// Add task
var task = phase.AddTask(request.Name, request.Description);
task.SetPriority(request.Priority);
task.SetOrderIndex(request.OrderIndex);
if (request.DueDate.HasValue)
{
task.SetDates(dueDate: request.DueDate);
}
// Save changes
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
catch (Exception ex)
{
return OperationResult.Failure($"خطا در افزودن تسک: {ex.Message}");
}
}
}

View File

@@ -1,18 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AssignProject;
public class AssignProjectCommand:IBaseCommand
{
public List<AssignProjectCommandItem> Items { get; set; }
public Guid Id { get; set; }
public ProjectHierarchyLevel Level { get; set; }
public bool CascadeToChildren { get; set; }
}
public class AssignProjectCommandItem
{
public long UserId { get; set; }
public Guid SkillId { get; set; }
}

View File

@@ -1,274 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.ProjectAgg.Entities;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using GozareshgirProgramManager.Domain.SkillAgg.Repositories;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AssignProject;
public class AssignProjectCommandHandler:IBaseCommandHandler<AssignProjectCommand>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IProjectRepository _projectRepository;
private readonly IProjectPhaseRepository _projectPhaseRepository;
private readonly IProjectTaskRepository _projectTaskRepository;
private readonly ISkillRepository _skillRepository;
private readonly IPhaseSectionRepository _phaseSectionRepository;
private readonly IProjectSectionRepository _projectSectionRepository;
private readonly ITaskSectionRepository _taskSectionRepository;
public AssignProjectCommandHandler(
IProjectRepository projectRepository,
IProjectPhaseRepository projectPhaseRepository,
IProjectTaskRepository projectTaskRepository,
IUnitOfWork unitOfWork,
ISkillRepository skillRepository,
IPhaseSectionRepository phaseSectionRepository,
IProjectSectionRepository projectSectionRepository,
ITaskSectionRepository taskSectionRepository)
{
_projectRepository = projectRepository;
_projectPhaseRepository = projectPhaseRepository;
_projectTaskRepository = projectTaskRepository;
_unitOfWork = unitOfWork;
_skillRepository = skillRepository;
_phaseSectionRepository = phaseSectionRepository;
_projectSectionRepository = projectSectionRepository;
_taskSectionRepository = taskSectionRepository;
}
public async Task<OperationResult> Handle(AssignProjectCommand request, CancellationToken cancellationToken)
{
switch (request.Level)
{
case ProjectHierarchyLevel.Project:
return await AssignProject(request);
case ProjectHierarchyLevel.Phase:
return await AssignProjectPhase(request);
case ProjectHierarchyLevel.Task:
return await AssignProjectTask(request);
default:
return OperationResult.Failure("سطح پروژه نامعتبر است");
}
}
private async Task<OperationResult> AssignProject(AssignProjectCommand request)
{
var project = await _projectRepository.GetWithFullHierarchyAsync(request.Id);
if (project is null)
{
return OperationResult.NotFound("پروژه یافت نشد");
}
// تخصیص در سطح پروژه
foreach (var item in request.Items)
{
var skill = await _skillRepository.GetByIdAsync(item.SkillId);
if (skill is null)
{
return OperationResult.NotFound($"مهارت با شناسه {item.SkillId} یافت نشد");
}
// بررسی و به‌روزرسانی یا اضافه کردن ProjectSection
var existingSection = project.ProjectSections.FirstOrDefault(s => s.SkillId == item.SkillId);
if (existingSection != null)
{
// اگر وجود داشت، فقط userId را به‌روزرسانی کن
existingSection.UpdateUser(item.UserId);
}
else
{
// اگر وجود نداشت، اضافه کن
var newSection = new ProjectSection(project.Id, item.UserId, item.SkillId);
await _projectSectionRepository.CreateAsync(newSection);
}
}
// حالا برای تمام فازها و تسک‌ها cascade کن
foreach (var phase in project.Phases)
{
// اگر CascadeToChildren true است یا فاز override ندارد
if (request.CascadeToChildren || !phase.HasAssignmentOverride)
{
// برای phase هم باید sectionها را به‌روزرسانی کنیم
foreach (var item in request.Items)
{
var existingSection = phase.PhaseSections.FirstOrDefault(s => s.SkillId == item.SkillId);
if (existingSection != null)
{
existingSection.Update(item.UserId, item.SkillId);
}
else
{
var newPhaseSection = new PhaseSection(phase.Id, item.UserId, item.SkillId);
await _phaseSectionRepository.CreateAsync(newPhaseSection);
}
}
foreach (var task in phase.Tasks)
{
// اگر CascadeToChildren true است یا تسک override ندارد
if (request.CascadeToChildren || !task.HasAssignmentOverride)
{
foreach (var item in request.Items)
{
var section = task.Sections.FirstOrDefault(s => s.SkillId == item.SkillId);
if (section != null)
{
// استفاده از TransferToUser
if (section.CurrentAssignedUserId != item.UserId)
{
if (section.CurrentAssignedUserId > 0)
{
section.TransferToUser(section.CurrentAssignedUserId, item.UserId);
}
else
{
section.AssignToUser(item.UserId);
}
}
}
else
{
var newTaskSection = new TaskSection(task.Id, item.SkillId, item.UserId);
await _taskSectionRepository.CreateAsync(newTaskSection);
}
}
}
}
}
}
await _unitOfWork.SaveChangesAsync();
return OperationResult.Success();
}
private async Task<OperationResult> AssignProjectPhase(AssignProjectCommand request)
{
var phase = await _projectPhaseRepository.GetWithTasksAsync(request.Id);
if (phase is null)
{
return OperationResult.NotFound("فاز پروژه یافت نشد");
}
// تخصیص در سطح فاز
foreach (var item in request.Items)
{
var skill = await _skillRepository.GetByIdAsync(item.SkillId);
if (skill is null)
{
return OperationResult.NotFound($"مهارت با شناسه {item.SkillId} یافت نشد");
}
}
// علامت‌گذاری که این فاز نسبت به parent متمایز است
phase.MarkAsOverridden();
// به‌روزرسانی یا اضافه کردن PhaseSection
foreach (var item in request.Items)
{
var existingSection = phase.PhaseSections.FirstOrDefault(s => s.SkillId == item.SkillId);
if (existingSection != null)
{
// اگر وجود داشت، فقط userId را به‌روزرسانی کن
existingSection.Update(item.UserId, item.SkillId);
}
else
{
// اگر وجود نداشت، اضافه کن
var newPhaseSection = new PhaseSection(phase.Id, item.UserId, item.SkillId);
await _phaseSectionRepository.CreateAsync(newPhaseSection);
}
}
// cascade به تمام تسک‌ها
foreach (var task in phase.Tasks)
{
// اگر CascadeToChildren true است یا تسک override ندارد
if (request.CascadeToChildren || !task.HasAssignmentOverride)
{
foreach (var item in request.Items)
{
var section = task.Sections.FirstOrDefault(s => s.SkillId == item.SkillId);
if (section != null)
{
// استفاده از TransferToUser
if (section.CurrentAssignedUserId != item.UserId)
{
if (section.CurrentAssignedUserId > 0)
{
section.TransferToUser(section.CurrentAssignedUserId, item.UserId);
}
else
{
section.AssignToUser(item.UserId);
}
}
}
else
{
var newTaskSection = new TaskSection(task.Id, item.SkillId, item.UserId);
await _taskSectionRepository.CreateAsync(newTaskSection);
}
}
}
}
await _unitOfWork.SaveChangesAsync();
return OperationResult.Success();
}
private async Task<OperationResult> AssignProjectTask(AssignProjectCommand request)
{
var task = await _projectTaskRepository.GetWithSectionsAsync(request.Id);
if (task is null)
{
return OperationResult.NotFound("تسک یافت نشد");
}
foreach (var item in request.Items)
{
var skill = await _skillRepository.GetByIdAsync(item.SkillId);
if (skill is null)
{
return OperationResult.NotFound($"مهارت با شناسه {item.SkillId} یافت نشد");
}
}
// علامت‌گذاری که این تسک نسبت به parent متمایز است
task.MarkAsOverridden();
// به‌روزرسانی یا اضافه کردن TaskSection
foreach (var item in request.Items)
{
var section = task.Sections.FirstOrDefault(s => s.SkillId == item.SkillId);
if (section != null)
{
// اگر وجود داشت، از TransferToUser استفاده کن
if (section.CurrentAssignedUserId != item.UserId)
{
if (section.CurrentAssignedUserId > 0)
{
section.TransferToUser(section.CurrentAssignedUserId, item.UserId);
}
else
{
section.AssignToUser(item.UserId);
}
}
}
else
{
// اگر وجود نداشت، اضافه کن
var newTaskSection = new TaskSection(task.Id, item.SkillId, item.UserId);
await _taskSectionRepository.CreateAsync(newTaskSection);
}
}
await _unitOfWork.SaveChangesAsync();
return OperationResult.Success();
}
}

View File

@@ -1,39 +0,0 @@
using FluentValidation;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AssignProject;
public class AssignProjectCommandValidator : AbstractValidator<AssignProjectCommand>
{
public AssignProjectCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty()
.NotNull()
.WithMessage("شناسه پروژه نمیتواند خالی باشد");
RuleFor(x => x.CascadeToChildren)
.NotNull()
.WithMessage("مقدار CascadeToChildren نمیتواند خالی باشد");
RuleForEach(x => x.Items)
.SetValidator(new AssignProjectItemValidator());
}
}
public class AssignProjectItemValidator : AbstractValidator<AssignProjectCommandItem>
{
public AssignProjectItemValidator()
{
RuleFor(x => x.UserId)
.NotEmpty()
.NotNull()
.GreaterThan(0)
.WithMessage("شناسه کاربر نمیتواند خالی باشد");
RuleFor(x => x.SkillId)
.NotEmpty()
.NotNull()
.WithMessage("شناسه مهارت نمیتواند خالی باشد");
}
}

View File

@@ -1,101 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain._Common.Exceptions;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.ChangeStatusSection;
public record ChangeStatusSectionCommand(Guid SectionId, TaskSectionStatus Status) : IBaseCommand;
public class ChangeStatusSectionCommandHandler : IBaseCommandHandler<ChangeStatusSectionCommand>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ITaskSectionRepository _taskSectionRepository;
private readonly IAuthHelper _authHelper;
public ChangeStatusSectionCommandHandler(ITaskSectionRepository taskSectionRepository,
IUnitOfWork unitOfWork, IAuthHelper authHelper)
{
_taskSectionRepository = taskSectionRepository;
_unitOfWork = unitOfWork;
_authHelper = authHelper;
}
public async Task<OperationResult> Handle(ChangeStatusSectionCommand request, CancellationToken cancellationToken)
{
// استفاده از متد مخصوص که Activities رو load می‌کنه
var section = await _taskSectionRepository.GetByIdWithActivitiesAsync(request.SectionId, cancellationToken);
if (section == null)
return OperationResult.NotFound("بخش مورد نظر یافت نشد");
if (section.Status == request.Status)
return OperationResult.Success();
long currentUser = _authHelper.GetCurrentUserId()
?? throw new UnAuthorizedException("کاربر احراز هویت نشده است");
// Validate state transitions
var validationResult = ValidateStateTransition(section.Status, request.Status);
if (!validationResult.IsSuccess)
return validationResult;
// Handle state machine logic
if (section.Status == TaskSectionStatus.InProgress)
{
// Coming FROM InProgress: Stop the active activity
section.StopWork(currentUser, request.Status);
}
else if (request.Status == TaskSectionStatus.InProgress)
{
// Going TO InProgress: Start work and create activity
section.StartWork(currentUser);
}
else
{
// All other transitions: Just update status
section.UpdateStatus(request.Status);
}
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
/// <summary>
/// Validates state transitions based on business rules:
/// - ReadyToStart: شروع نشده - Initial state only, cannot return to it once left
/// - InProgress: درحال انجام - Can transition from ReadyToStart, can go to Incomplete or Completed
/// - Incomplete: نیمه کاره - Can come from InProgress or other states
/// - Completed: اتمام رسیده - Can come from InProgress or other states
/// </summary>
private OperationResult ValidateStateTransition(TaskSectionStatus currentStatus, TaskSectionStatus targetStatus)
{
// Cannot transition to ReadyToStart once the section has been started
if (targetStatus == TaskSectionStatus.ReadyToStart)
return OperationResult.ValidationError("بخش نمی‌تواند به وضعیت 'آماده برای شروع' تغییر کند");
// From ReadyToStart, can only go to InProgress
if (currentStatus == TaskSectionStatus.ReadyToStart && targetStatus != TaskSectionStatus.InProgress)
return OperationResult.ValidationError("از وضعیت 'آماده برای شروع' فقط می‌توان به 'درحال انجام' رفت");
// Valid transitions matrix
var validTransitions = new Dictionary<TaskSectionStatus, List<TaskSectionStatus>>
{
{ TaskSectionStatus.ReadyToStart, new List<TaskSectionStatus> { TaskSectionStatus.InProgress } },
{ TaskSectionStatus.InProgress, new List<TaskSectionStatus> { TaskSectionStatus.Incomplete, TaskSectionStatus.Completed } },
{ TaskSectionStatus.Incomplete, new List<TaskSectionStatus> { TaskSectionStatus.InProgress, TaskSectionStatus.Completed } },
{ TaskSectionStatus.Completed, new List<TaskSectionStatus> { TaskSectionStatus.InProgress, TaskSectionStatus.Incomplete } }, // Can return to InProgress or Incomplete
{ TaskSectionStatus.NotAssigned, new List<TaskSectionStatus> { TaskSectionStatus.InProgress, TaskSectionStatus.ReadyToStart } }
};
if (!validTransitions.TryGetValue(currentStatus, out var allowedTargets))
return OperationResult.ValidationError($"وضعیت فعلی '{currentStatus}' نامعتبر است");
if (!allowedTargets.Contains(targetStatus))
return OperationResult.ValidationError(
$"نمی‌توان از وضعیت '{currentStatus}' به '{targetStatus}' رفت");
return OperationResult.Success();
}
}

View File

@@ -1,20 +0,0 @@
using FluentValidation;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.ChangeStatusSection;
public class ChangeStatusSectionCommandValidator:AbstractValidator<ChangeStatusSectionCommand>
{
public ChangeStatusSectionCommandValidator()
{
RuleFor(c => c.SectionId)
.NotEmpty()
.NotNull()
.WithMessage("شناسه بخش نمی‌تواند خالی باشد");
RuleFor(c => c.Status)
.IsInEnum()
.NotEmpty()
.NotNull()
.WithMessage("وضعیت بخش نامعتبر است");
}
}

View File

@@ -1,7 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.CreateProject;
public record CreateProjectCommand(string Name,ProjectHierarchyLevel Level,
Guid? ParentId):IBaseCommand;

View File

@@ -1,82 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain._Common.Exceptions;
using GozareshgirProgramManager.Domain.ProjectAgg.Entities;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.CreateProject;
public class CreateProjectCommandHandler : IBaseCommandHandler<CreateProjectCommand>
{
private readonly IProjectRepository _projectRepository;
private readonly IProjectPhaseRepository _projectPhaseRepository;
private readonly IProjectTaskRepository _projectTaskRepository;
private readonly IUnitOfWork _unitOfWork;
public CreateProjectCommandHandler(IProjectRepository projectRepository, IUnitOfWork unitOfWork, IProjectTaskRepository projectTaskRepository, IProjectPhaseRepository projectPhaseRepository)
{
_projectRepository = projectRepository;
_unitOfWork = unitOfWork;
_projectTaskRepository = projectTaskRepository;
_projectPhaseRepository = projectPhaseRepository;
}
public async Task<OperationResult> Handle(CreateProjectCommand request, CancellationToken cancellationToken)
{
switch (request.Level)
{
case ProjectHierarchyLevel.Project:
await CreateProject(request);
break;
case ProjectHierarchyLevel.Phase:
await CreateProjectPhase(request);
break;
case ProjectHierarchyLevel.Task:
await CreateProjectTask(request);
break;
default:
return OperationResult.Failure("سطح پروژه نامعتبر است");
}
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
private async Task CreateProject(CreateProjectCommand request)
{
var project = new Project(request.Name);
await _projectRepository.CreateAsync(project);
}
private async Task CreateProjectPhase(CreateProjectCommand request)
{
if (!request.ParentId.HasValue)
throw new BadRequestException("برای ایجاد فاز، شناسه پروژه الزامی است");
if(!_projectRepository.Exists(x=>x.Id == request.ParentId.Value))
{
throw new BadRequestException("والد پروژه یافت نشد");
}
var projectPhase = new ProjectPhase(request.Name, request.ParentId.Value);
await _projectPhaseRepository.CreateAsync(projectPhase);
}
private async Task CreateProjectTask(CreateProjectCommand request)
{
if (!request.ParentId.HasValue)
throw new BadRequestException("برای ایجاد تسک، شناسه فاز الزامی است");
if(!_projectPhaseRepository.Exists(x=>x.Id == request.ParentId.Value))
{
throw new BadRequestException("والد پروژه یافت نشد");
}
var projectTask = new ProjectTask(request.Name, request.ParentId.Value);
await _projectTaskRepository.CreateAsync(projectTask);
}
}

View File

@@ -1,26 +0,0 @@
using FluentValidation;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.CreateProject;
public class CreateProjectCommandValidator:AbstractValidator<CreateProjectCommand>
{
public CreateProjectCommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.NotNull()
.WithMessage("نام نمیتواند خالی باشد");
RuleFor(y => y.Level)
.NotNull()
.IsInEnum();
When(x=>x.Level>ProjectHierarchyLevel.Project,()=>
{
RuleFor(x => x.ParentId)
.NotNull()
.NotEmpty()
.WithMessage("شناسه والد نمیتواند خالی باشد");
});
}
}

View File

@@ -1,13 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.CreateProjectWithHierarchy;
/// <summary>
/// Command to create a new project with the new hierarchy structure
/// </summary>
public record CreateProjectWithHierarchyCommand(
string Name,
string? Description = null,
DateTime? PlannedStartDate = null,
DateTime? PlannedEndDate = null
) : IBaseCommand;

View File

@@ -1,49 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.ProjectAgg.Entities;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using MediatR;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.CreateProjectWithHierarchy;
public class CreateProjectWithHierarchyCommandHandler : IRequestHandler<CreateProjectWithHierarchyCommand, OperationResult>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public CreateProjectWithHierarchyCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository;
_unitOfWork = unitOfWork;
}
public async Task<OperationResult> Handle(CreateProjectWithHierarchyCommand request, CancellationToken cancellationToken)
{
try
{
// Create new project
var project = new Project(request.Name, request.Description);
// Set planned dates if provided
if (request.PlannedStartDate.HasValue || request.PlannedEndDate.HasValue)
{
project.SetPlannedDates(request.PlannedStartDate, request.PlannedEndDate);
}
// Add to repository
await _projectRepository.CreateAsync(project);
// Save changes
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
catch (Exception ex)
{
return OperationResult.Failure($"خطا در ایجاد پروژه: {ex.Message}");
}
}
}

View File

@@ -1,21 +0,0 @@
using FluentValidation;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.CreateProjectWithHierarchy;
public class CreateProjectWithHierarchyCommandValidator : AbstractValidator<CreateProjectWithHierarchyCommand>
{
public CreateProjectWithHierarchyCommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty().WithMessage("نام پروژه نمی‌تواند خالی باشد")
.MaximumLength(200).WithMessage("نام پروژه نمی‌تواند بیش از 200 کاراکتر باشد");
RuleFor(x => x.Description)
.MaximumLength(1000).WithMessage("توضیحات نمی‌تواند بیش از 1000 کاراکتر باشد")
.When(x => !string.IsNullOrEmpty(x.Description));
RuleFor(x => x)
.Must(x => x.PlannedStartDate == null || x.PlannedEndDate == null || x.PlannedStartDate <= x.PlannedEndDate)
.WithMessage("تاریخ شروع برنامه‌ریزی شده نمی‌تواند بعد از تاریخ پایان برنامه‌ریزی شده باشد");
}
}

View File

@@ -1,91 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain._Common.Exceptions;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.DeleteProject;
public record DeleteProjectCommand(Guid Id,ProjectHierarchyLevel Level) : IBaseCommand;
public class DeleteProjectCommandHandler : IBaseCommandHandler<DeleteProjectCommand>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IProjectRepository _projectRepository;
private readonly IProjectPhaseRepository _projectPhaseRepository;
private readonly IProjectTaskRepository _projectTaskRepository;
public DeleteProjectCommandHandler(
IUnitOfWork unitOfWork,
IProjectRepository projectRepository,
IProjectPhaseRepository projectPhaseRepository,
IProjectTaskRepository projectTaskRepository)
{
_unitOfWork = unitOfWork;
_projectRepository = projectRepository;
_projectPhaseRepository = projectPhaseRepository;
_projectTaskRepository = projectTaskRepository;
}
public async Task<OperationResult> Handle(DeleteProjectCommand request, CancellationToken cancellationToken)
{
switch (request.Level)
{
case ProjectHierarchyLevel.Project:
await DeleteProject(request.Id);
break;
case ProjectHierarchyLevel.Phase:
await DeleteProjectPhase(request.Id);
break;
case ProjectHierarchyLevel.Task:
await DeleteProjectTask(request.Id);
break;
default:
return OperationResult.Failure("سطح پروژه نامعتبر است");
}
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
private async Task DeleteProject(Guid projectId)
{
var projectWithPhases = await _projectRepository.GetWithFullHierarchyAsync(projectId);
if (projectWithPhases == null)
throw new NotFoundException("پروژه یافت نشد");
// بررسی اینکه پروژه فاز یا زیرمجموعه دارد یا نه
if (projectWithPhases.Phases != null && projectWithPhases.Phases.Any())
throw new BadRequestException("نمی‌توان پروژه‌ای را حذف کرد که دارای فاز است. ابتدا تمام فازها را حذف کنید.");
_projectRepository.Remove(projectWithPhases);
}
private async Task DeleteProjectPhase(Guid phaseId)
{
var phase = await _projectPhaseRepository.GetByIdAsync(phaseId);
if (phase == null)
throw new NotFoundException("فاز پروژه یافت نشد");
// بررسی اینکه فاز تسک یا زیرمجموعه دارد یا نه
var phaseWithTasks = await _projectPhaseRepository.GetWithTasksAsync(phaseId);
if (phaseWithTasks?.Tasks != null && phaseWithTasks.Tasks.Any())
throw new InvalidOperationException("نمی‌توان فازی را حذف کرد که دارای تسک است. ابتدا تمام تسک‌ها را حذف کنید.");
_projectPhaseRepository.Remove(phase);
}
private async Task DeleteProjectTask(Guid taskId)
{
var task = await _projectTaskRepository.GetByIdAsync(taskId);
if (task == null)
throw new NotFoundException("تسک یافت نشد");
// حذف خود تسک
_projectTaskRepository.Remove(task);
}
}

View File

@@ -1,19 +0,0 @@
using FluentValidation;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.DeleteProject;
public class DeleteProjectCommandValidator:AbstractValidator<DeleteProjectCommand>
{
public DeleteProjectCommandValidator()
{
RuleFor(x=>x.Id)
.NotEmpty()
.NotNull()
.WithMessage("شناسه پروژه نمی‌تواند خالی باشد.");
RuleFor(x=>x.Level)
.IsInEnum()
.NotNull()
.WithMessage("سطح حذف پروژه نامعتبر است.");
}
}

View File

@@ -1,80 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain._Common.Exceptions;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.EditProject;
public record EditProjectCommand(string Name, Guid Id, ProjectHierarchyLevel Level): IBaseCommand;
public class EditProjectCommandHandler: IBaseCommandHandler<EditProjectCommand>
{
private readonly IProjectRepository _projectRepository;
private readonly IProjectPhaseRepository _projectPhaseRepository;
private readonly IProjectTaskRepository _projectTaskRepository;
private readonly IUnitOfWork _unitOfWork;
public EditProjectCommandHandler(
IProjectRepository projectRepository,
IProjectPhaseRepository projectPhaseRepository,
IProjectTaskRepository projectTaskRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository;
_projectPhaseRepository = projectPhaseRepository;
_projectTaskRepository = projectTaskRepository;
_unitOfWork = unitOfWork;
}
public async Task<OperationResult> Handle(EditProjectCommand request, CancellationToken cancellationToken)
{
switch (request.Level)
{
case ProjectHierarchyLevel.Project:
await EditProject(request);
break;
case ProjectHierarchyLevel.Phase:
await EditProjectPhase(request);
break;
case ProjectHierarchyLevel.Task:
await EditProjectTask(request);
break;
default:
return OperationResult.Failure("سطح پروژه نامعتبر است");
}
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
private async Task EditProject(EditProjectCommand request)
{
var project = await _projectRepository.GetByIdAsync(request.Id);
if (project == null)
throw new NotFoundException("پروژه یافت نشد");
project.UpdateName(request.Name);
}
private async Task EditProjectPhase(EditProjectCommand request)
{
var phase = await _projectPhaseRepository.GetByIdAsync(request.Id);
if (phase == null)
throw new NotFoundException("فاز پروژه یافت نشد");
phase.UpdateName(request.Name);
}
private async Task EditProjectTask(EditProjectCommand request)
{
var task = await _projectTaskRepository.GetByIdAsync(request.Id);
if (task == null)
throw new NotFoundException("تسک یافت نشد");
task.UpdateName(request.Name);
}
}

View File

@@ -1,18 +0,0 @@
using FluentValidation;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.EditProject;
public class EditProjectCommandValidator:AbstractValidator<EditProjectCommand>
{
public EditProjectCommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.WithMessage("نام پروژه نمی‌تواند خالی باشد.");
RuleFor(x=>x.Id)
.NotEmpty()
.NotNull().WithMessage("شناسه پروژه نمی‌تواند خالی باشد.");
}
}

View File

@@ -1,13 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application.Modules.Projects.DTOs;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.SetTimeProject;
public record SetTimeProjectCommand(List<SetTimeProjectSectionItem> SectionItems, Guid Id, ProjectHierarchyLevel Level):IBaseCommand;
public class SetTimeSectionTime
{
public string Description { get; set; }
public int Hours { get; set; }
}

View File

@@ -1,164 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Application.Modules.Projects.DTOs;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.ProjectAgg.Entities;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.SetTimeProject;
public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectCommand>
{
private readonly IProjectRepository _projectRepository;
private readonly IProjectPhaseRepository _projectPhaseRepository;
private readonly IProjectTaskRepository _projectTaskRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthHelper _authHelper;
private long? _userId;
public SetTimeProjectCommandHandler(
IProjectRepository projectRepository,
IProjectPhaseRepository projectPhaseRepository,
IProjectTaskRepository projectTaskRepository,
IUnitOfWork unitOfWork, IAuthHelper authHelper)
{
_projectRepository = projectRepository;
_projectPhaseRepository = projectPhaseRepository;
_projectTaskRepository = projectTaskRepository;
_unitOfWork = unitOfWork;
_authHelper = authHelper;
_userId = authHelper.GetCurrentUserId();
}
public async Task<OperationResult> Handle(SetTimeProjectCommand request, CancellationToken cancellationToken)
{
switch (request.Level)
{
case ProjectHierarchyLevel.Task:
return await SetTimeForProjectTask(request, cancellationToken);
default:
return OperationResult.Failure("سطح پروژه نامعتبر است");
}
}
private async Task<OperationResult> SetTimeForProject(SetTimeProjectCommand request, CancellationToken cancellationToken)
{
var project = await _projectRepository.GetWithFullHierarchyAsync(request.Id);
if (project == null)
{
return OperationResult.NotFound("پروژه یافت نشد");
return OperationResult.NotFound("<22><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD>");
}
long? addedByUserId = _userId;
// تنظیم زمان برای تمام sections در تمام فازها و تسک‌های پروژه
foreach (var phase in project.Phases)
{
foreach (var task in phase.Tasks)
{
foreach (var section in task.Sections)
{
var sectionItem = request.SectionItems.FirstOrDefault(si => si.SectionId == section.Id);
if (sectionItem != null)
{
SetSectionTime(section, sectionItem, addedByUserId);
}
}
}
}
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
private async Task<OperationResult> SetTimeForProjectPhase(SetTimeProjectCommand request, CancellationToken cancellationToken)
{
var phase = await _projectPhaseRepository.GetWithTasksAsync(request.Id);
if (phase == null)
{
return OperationResult.NotFound("فاز پروژه یافت نشد");
return OperationResult.NotFound("<22><><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD>");
}
long? addedByUserId = _userId;
// تنظیم زمان برای تمام sections در تمام تسک‌های این فاز
foreach (var task in phase.Tasks)
{
foreach (var section in task.Sections)
{
var sectionItem = request.SectionItems.FirstOrDefault(si => si.SectionId == section.Id);
if (sectionItem != null)
{
SetSectionTime(section, sectionItem, addedByUserId);
}
}
}
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
private async Task<OperationResult> SetTimeForProjectTask(SetTimeProjectCommand request, CancellationToken cancellationToken)
{
var task = await _projectTaskRepository.GetWithSectionsAsync(request.Id);
if (task == null)
{
return OperationResult.NotFound("تسک یافت نشد");
return OperationResult.NotFound("<22>Ә <20><><EFBFBD><EFBFBD> <20><><EFBFBD>");
}
long? addedByUserId = _userId;
// تنظیم زمان مستقیماً برای sections این تسک
foreach (var section in task.Sections)
{
var sectionItem = request.SectionItems.FirstOrDefault(si => si.SectionId == section.Id);
if (sectionItem != null)
{
SetSectionTime(section, sectionItem, addedByUserId);
}
}
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
private void SetSectionTime(TaskSection section, SetTimeProjectSectionItem sectionItem, long? addedByUserId)
{
var initData = sectionItem.InitData;
var initialTime = TimeSpan.FromHours(initData.Hours);
// تنظیم زمان اولیه
section.UpdateInitialEstimatedHours(initialTime, initData.Description);
section.ClearAdditionalTimes();
// افزودن زمان‌های اضافی
foreach (var additionalTime in sectionItem.AdditionalTime)
{
var additionalTimeSpan = TimeSpan.FromHours(additionalTime.Hours);
section.AddAdditionalTime(additionalTimeSpan, additionalTime.Description, addedByUserId);
}
}
// private void SetSectionTime(ProjectSection section, SetTimeProjectSectionItem sectionItem, long? addedByUserId)
// {
// var initData = sectionItem.InitData;
// var initialTime = TimeSpan.FromHours(initData.Hours);
//
// // تنظیم زمان اولیه
// section.UpdateInitialEstimatedHours(initialTime, initData.Description);
//
// section.ClearAdditionalTimes();
// // افزودن زمان‌های اضافی
// foreach (var additionalTime in sectionItem.AdditionalTime)
// {
// var additionalTimeSpan = TimeSpan.FromHours(additionalTime.Hours);
// section.AddAdditionalTime(additionalTimeSpan, additionalTime.Description, addedByUserId);
// }
// }
}

View File

@@ -1,50 +0,0 @@
using FluentValidation;
using GozareshgirProgramManager.Application.Modules.Projects.DTOs;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.SetTimeProject;
public class SetTimeProjectCommandValidator:AbstractValidator<SetTimeProjectCommand>
{
public SetTimeProjectCommandValidator()
{
RuleFor(x=>x.Id)
.NotEmpty()
.NotNull()
.WithMessage("شناسه پروژه نمی‌تواند خالی باشد.");
RuleForEach(x => x.SectionItems)
.SetValidator(command => new SetTimeProjectSectionItemValidator());
}
}
public class SetTimeProjectSectionItemValidator:AbstractValidator<SetTimeProjectSectionItem>
{
public SetTimeProjectSectionItemValidator()
{
RuleFor(x=>x.SectionId)
.NotEmpty()
.NotNull()
.WithMessage("شناسه بخش نمی‌تواند خالی باشد.");
RuleFor(x=>x.InitData)
.SetValidator(new TimeDataValidator());
RuleForEach(x=>x.AdditionalTime)
.SetValidator(new TimeDataValidator());
}
}
public class TimeDataValidator : AbstractValidator<SetTimeSectionTime>
{
public TimeDataValidator()
{
RuleFor(x => x.Hours)
.GreaterThanOrEqualTo(0)
.WithMessage("ساعت نمی‌تواند منفی باشد.");
RuleFor(x=>x.Description)
.MaximumLength(500)
.WithMessage("توضیحات نمی‌تواند بیشتر از 500 کاراکتر باشد.");
}
}

View File

@@ -1,12 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.TransferSection;
public record TransferSectionCommand : IBaseCommand
{
public Guid SectionId { get; set; }
public long FromUserId { get; set; }
public long ToUserId { get; set; }
public string? Notes { get; set; }
}

View File

@@ -1,69 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using GozareshgirProgramManager.Domain.UserAgg.Repositories;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.TransferSection;
public class TransferSectionCommandHandler : IBaseCommandHandler<TransferSectionCommand>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ITaskSectionRepository _taskSectionRepository;
private readonly IUserRepository _userRepository;
public TransferSectionCommandHandler(
ITaskSectionRepository taskSectionRepository,
IUserRepository userRepository,
IUnitOfWork unitOfWork)
{
_taskSectionRepository = taskSectionRepository;
_userRepository = userRepository;
_unitOfWork = unitOfWork;
}
public async Task<OperationResult> Handle(TransferSectionCommand request, CancellationToken cancellationToken)
{
// دریافت section با activities
var section = await _taskSectionRepository.GetByIdWithActivitiesAsync(request.SectionId, cancellationToken);
if (section == null)
{
return OperationResult.NotFound("بخش پروژه یافت نشد");
}
// بررسی وجود کاربر مبدا
var fromUser = await _userRepository.GetByIdAsync(request.FromUserId);
if (fromUser == null)
{
return OperationResult.NotFound($"کاربر مبدا با شناسه {request.FromUserId} یافت نشد");
}
// بررسی وجود کاربر مقصد
var toUser = await _userRepository.GetByIdAsync(request.ToUserId);
if (toUser == null)
{
return OperationResult.NotFound($"کاربر مقصد با شناسه {request.ToUserId} یافت نشد");
}
// بررسی اینکه کاربر مبدا و مقصد یکسان نباشند
if (request.FromUserId == request.ToUserId)
{
return OperationResult.Failure("کاربر مبدا و مقصد نمی‌توانند یکسان باشند");
}
try
{
// انتقال به کاربر جدید
section.TransferToUser(request.FromUserId, request.ToUserId);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
catch (InvalidOperationException ex)
{
return OperationResult.Failure(ex.Message);
}
}
}

Some files were not shown because too many files have changed in this diff Show More