Compare commits

..

2 Commits

183 changed files with 4915 additions and 18580 deletions

View File

@@ -6,7 +6,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="12.1.1" />
<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" />

View File

@@ -56,11 +56,6 @@ public class AuthHelper : IAuthHelper
return Tools.DeserializeFromBsonList<int>(permissions); //Mahan
}
public bool HasPermission(int permission)
{
return GetPermissions().Any(x => x == permission);
}
public long CurrentAccountId()
{
return IsAuthenticated()
@@ -204,7 +199,7 @@ public class AuthHelper : IAuthHelper
new("WorkshopSlug",slug),
new("WorkshopId", account.WorkshopId.ToString()),
new("WorkshopName",account.WorkshopName??""),
new("pm.userId", account.PmUserId.ToString()),
new("pm.userId", account.PmUserId?.ToString() ?? "0"),
};

View File

@@ -33,9 +33,4 @@ public enum TypeOfSmsSetting
/// </summary>
LegalAction,
/// <summary>
/// پیامک تایید قراداد
/// </summary>
InstitutionContractConfirm,
}

View File

@@ -11,7 +11,6 @@ public interface IFaceEmbeddingService
Task<OperationResult> RefineEmbeddingAsync(long employeeId, long workshopId, float[] embedding, float confidence, Dictionary<string, object> metadata = null);
Task<OperationResult> DeleteEmbeddingAsync(long employeeId, long workshopId);
Task<OperationResult<FaceEmbeddingResponse>> GetEmbeddingAsync(long employeeId, long workshopId);
Task<OperationResult> UpdateEmbeddingFullNameAsync(long employeeId, long workshopId, string newFullName);
}
public class FaceEmbeddingResponse

View File

@@ -12,7 +12,6 @@ public interface IAuthHelper
string CurrentAccountRole();
AuthViewModel CurrentAccountInfo();
List<int> GetPermissions();
bool HasPermission(int permission);
long CurrentAccountId();
string CurrentAccountMobile();

View File

@@ -27,7 +27,7 @@ public interface ISmsService
Task<double> GetCreditAmount();
public Task<bool> SendInstitutionCreationVerificationLink(string number, string fullName, Guid institutionId, long contractingPartyId, long institutionContractId, string typeOfSms = null);
public Task<bool> SendInstitutionCreationVerificationLink(string number, string fullName, Guid institutionId, long contractingPartyId, long institutionContractId);
public Task<bool> SendInstitutionVerificationCode(string number, string code, string contractingPartyFullName,
long contractingPartyId, long institutionContractId);

View File

@@ -17,7 +17,7 @@ public class ExcelGenerator
{
public ExcelGenerator()
{
OfficeOpenXml.ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
}
public static byte[] GenerateExcel<T>(List<T> obj, string date = "") where T : class
{

View File

@@ -1,10 +1,7 @@
#nullable enable
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentValidation;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -30,14 +27,6 @@ public class CustomExceptionHandler : IExceptionHandler
(string Detail, string Title, int StatusCode, Dictionary<string, object>? Extra) details = exception switch
{
ValidationException validationException =>
(
validationException.Errors.FirstOrDefault()?.ErrorMessage ?? "One or more validation errors occurred.",
"Validation Error",
context.Response.StatusCode = StatusCodes.Status400BadRequest,
null
),
InternalServerException =>
(
exception.Message,
@@ -45,7 +34,6 @@ public class CustomExceptionHandler : IExceptionHandler
context.Response.StatusCode = StatusCodes.Status500InternalServerError,
null
),
BadRequestException bre =>
(
exception.Message,
@@ -53,7 +41,6 @@ public class CustomExceptionHandler : IExceptionHandler
context.Response.StatusCode = StatusCodes.Status400BadRequest,
bre.Extra
),
NotFoundException =>
(
exception.Message,
@@ -61,7 +48,6 @@ public class CustomExceptionHandler : IExceptionHandler
context.Response.StatusCode = StatusCodes.Status404NotFound,
null
),
UnAuthorizeException =>
(
exception.Message,
@@ -69,7 +55,6 @@ public class CustomExceptionHandler : IExceptionHandler
context.Response.StatusCode = StatusCodes.Status401Unauthorized,
null
),
_ =>
(
exception.Message,
@@ -88,6 +73,8 @@ public class CustomExceptionHandler : IExceptionHandler
Extensions = details.Extra ?? new Dictionary<string, object>()
};
problemDetails.Extensions.Add("traceId", context.TraceIdentifier);
await context.Response.WriteAsJsonAsync(problemDetails, cancellationToken: cancellationToken);

View File

@@ -18,387 +18,329 @@ namespace _0_Framework.Infrastructure;
/// </summary>
public class FaceEmbeddingService : IFaceEmbeddingService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<FaceEmbeddingService> _logger;
private readonly IFaceEmbeddingNotificationService _notificationService;
private readonly string _apiBaseUrl;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<FaceEmbeddingService> _logger;
private readonly IFaceEmbeddingNotificationService _notificationService;
private readonly string _apiBaseUrl;
public FaceEmbeddingService(IHttpClientFactory httpClientFactory, ILogger<FaceEmbeddingService> logger,
IFaceEmbeddingNotificationService notificationService = null)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_notificationService = notificationService;
_apiBaseUrl = "http://localhost:8000";
}
public FaceEmbeddingService(IHttpClientFactory httpClientFactory, ILogger<FaceEmbeddingService> logger,
IFaceEmbeddingNotificationService notificationService = null)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_notificationService = notificationService;
_apiBaseUrl = "http://localhost:8000";
}
public async Task<OperationResult> GenerateEmbeddingsAsync(long employeeId, long workshopId,
string employeeFullName, string picture1Path, string picture2Path)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
public async Task<OperationResult> GenerateEmbeddingsAsync(long employeeId, long workshopId,
string employeeFullName, string picture1Path, string picture2Path)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
using var content = new MultipartFormDataContent();
using var content = new MultipartFormDataContent();
// Add form fields
content.Add(new StringContent(employeeId.ToString()), "employee_id");
content.Add(new StringContent(workshopId.ToString()), "workshop_id");
content.Add(new StringContent(employeeFullName ?? ""), "employee_full_name");
// Add form fields
content.Add(new StringContent(employeeId.ToString()), "employee_id");
content.Add(new StringContent(workshopId.ToString()), "workshop_id");
content.Add(new StringContent(employeeFullName ?? ""), "employee_full_name");
// Add picture files
if (File.Exists(picture1Path))
{
var picture1Bytes = await File.ReadAllBytesAsync(picture1Path);
var picture1Content = new ByteArrayContent(picture1Bytes);
picture1Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(picture1Content, "picture1", "1.jpg");
}
else
{
_logger.LogWarning("Picture1 not found at path: {Path}", picture1Path);
return new OperationResult { IsSuccedded = false, Message = "تصویر اول یافت نشد" };
}
// Add picture files
if (File.Exists(picture1Path))
{
var picture1Bytes = await File.ReadAllBytesAsync(picture1Path);
var picture1Content = new ByteArrayContent(picture1Bytes);
picture1Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(picture1Content, "picture1", "1.jpg");
}
else
{
_logger.LogWarning("Picture1 not found at path: {Path}", picture1Path);
return new OperationResult { IsSuccedded = false, Message = "تصویر اول یافت نشد" };
}
if (File.Exists(picture2Path))
{
var picture2Bytes = await File.ReadAllBytesAsync(picture2Path);
var picture2Content = new ByteArrayContent(picture2Bytes);
picture2Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(picture2Content, "picture2", "2.jpg");
}
else
{
_logger.LogWarning("Picture2 not found at path: {Path}", picture2Path);
return new OperationResult { IsSuccedded = false, Message = "تصویر دوم یافت نشد" };
}
if (File.Exists(picture2Path))
{
var picture2Bytes = await File.ReadAllBytesAsync(picture2Path);
var picture2Content = new ByteArrayContent(picture2Bytes);
picture2Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(picture2Content, "picture2", "2.jpg");
}
else
{
_logger.LogWarning("Picture2 not found at path: {Path}", picture2Path);
return new OperationResult { IsSuccedded = false, Message = "تصویر دوم یافت نشد" };
}
// Send request to Python API
var response = await httpClient.PostAsync("embeddings", content);
// Send request to Python API
var response = await httpClient.PostAsync("embeddings", content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
_logger.LogInformation(
"Embeddings generated successfully for Employee {EmployeeId}, Workshop {WorkshopId}",
employeeId, workshopId);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
_logger.LogInformation("Embeddings generated successfully for Employee {EmployeeId}, Workshop {WorkshopId}",
employeeId, workshopId);
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingCreatedAsync(workshopId, employeeId, employeeFullName);
}
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingCreatedAsync(workshopId, employeeId, employeeFullName);
}
return new OperationResult
{
IsSuccedded = true,
Message = "Embedding با موفقیت ایجاد شد"
};
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to generate embeddings. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
return new OperationResult
{
IsSuccedded = true,
Message = "Embedding با موفقیت ایجاد شد"
};
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to generate embeddings. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در تولید Embedding: {response.StatusCode}"
};
}
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "HTTP error while calling embeddings API for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در ارتباط با سرور Embedding"
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while calling embeddings API for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطای غیرمنتظره در تولید Embedding"
};
}
}
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در تولید Embedding: {response.StatusCode}"
};
}
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "HTTP error while calling embeddings API for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در ارتباط با سرور Embedding"
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while calling embeddings API for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطای غیرمنتظره در تولید Embedding"
};
}
}
public async Task<OperationResult> GenerateEmbeddingsFromStreamAsync(long employeeId, long workshopId,
string employeeFullName, Stream picture1Stream, Stream picture2Stream)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
public async Task<OperationResult> GenerateEmbeddingsFromStreamAsync(long employeeId, long workshopId,
string employeeFullName, Stream picture1Stream, Stream picture2Stream)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
using var content = new MultipartFormDataContent();
using var content = new MultipartFormDataContent();
// Add form fields
content.Add(new StringContent(employeeId.ToString()), "employee_id");
content.Add(new StringContent(workshopId.ToString()), "workshop_id");
content.Add(new StringContent(employeeFullName ?? ""), "employee_full_name");
// Add form fields
content.Add(new StringContent(employeeId.ToString()), "employee_id");
content.Add(new StringContent(workshopId.ToString()), "workshop_id");
content.Add(new StringContent(employeeFullName ?? ""), "employee_full_name");
// Add picture streams
var picture1Content = new StreamContent(picture1Stream);
picture1Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(picture1Content, "picture1", "1.jpg");
// Add picture streams
var picture1Content = new StreamContent(picture1Stream);
picture1Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(picture1Content, "picture1", "1.jpg");
var picture2Content = new StreamContent(picture2Stream);
picture2Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(picture2Content, "picture2", "2.jpg");
var picture2Content = new StreamContent(picture2Stream);
picture2Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(picture2Content, "picture2", "2.jpg");
// Send request to Python API
var response = await httpClient.PostAsync("embeddings", content);
// Send request to Python API
var response = await httpClient.PostAsync("embeddings", content);
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embeddings generated successfully from streams for Employee {EmployeeId}",
employeeId);
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embeddings generated successfully from streams for Employee {EmployeeId}", employeeId);
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingCreatedAsync(workshopId, employeeId, employeeFullName);
}
return new OperationResult { IsSuccedded = true, Message = "Embedding با موفقیت ایجاد شد" };
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to generate embeddings from streams. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingCreatedAsync(workshopId, employeeId, employeeFullName);
}
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در تولید Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while generating embeddings from streams for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در تولید Embedding"
};
}
}
return new OperationResult { IsSuccedded = true, Message = "Embedding با موفقیت ایجاد شد" };
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to generate embeddings from streams. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
public async Task<OperationResult> RefineEmbeddingAsync(long employeeId, long workshopId, float[] embedding,
float confidence, Dictionary<string, object> metadata = null)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در تولید Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while generating embeddings from streams for Employee {EmployeeId}",
employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در تولید Embedding"
};
}
}
var requestBody = new
{
employeeId,
workshopId,
embedding,
confidence,
metadata = metadata ?? new Dictionary<string, object>()
};
public async Task<OperationResult> RefineEmbeddingAsync(long employeeId, long workshopId, float[] embedding,
float confidence, Dictionary<string, object> metadata = null)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
var response = await httpClient.PostAsJsonAsync("embeddings/refine", requestBody);
var requestBody = new
{
employeeId,
workshopId,
embedding,
confidence,
metadata = metadata ?? new Dictionary<string, object>()
};
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embedding refined successfully for Employee {EmployeeId}", employeeId);
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingRefinedAsync(workshopId, employeeId);
}
return new OperationResult { IsSuccedded = true, Message = "Embedding بهبود یافت" };
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to refine embedding. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
var response = await httpClient.PostAsJsonAsync("embeddings/refine", requestBody);
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در بهبود Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while refining embedding for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در بهبود Embedding"
};
}
}
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embedding refined successfully for Employee {EmployeeId}", employeeId);
public async Task<OperationResult> DeleteEmbeddingAsync(long employeeId, long workshopId)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingRefinedAsync(workshopId, employeeId);
}
var response = await httpClient.DeleteAsync($"embeddings/{workshopId}/{employeeId}");
return new OperationResult { IsSuccedded = true, Message = "Embedding بهبود یافت" };
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to refine embedding. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embedding deleted successfully for Employee {EmployeeId}", employeeId);
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingDeletedAsync(workshopId, employeeId);
}
return new OperationResult { IsSuccedded = true, Message = "Embedding حذف شد" };
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to delete embedding. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در بهبود Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while refining embedding for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در بهبود Embedding"
};
}
}
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در حذف Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while deleting embedding for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در حذف Embedding"
};
}
}
public async Task<OperationResult> DeleteEmbeddingAsync(long employeeId, long workshopId)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
public async Task<OperationResult<FaceEmbeddingResponse>> GetEmbeddingAsync(long employeeId, long workshopId)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
var response = await httpClient.DeleteAsync($"embeddings/{workshopId}/{employeeId}");
var response = await httpClient.GetAsync($"embeddings/{workshopId}/{employeeId}");
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embedding deleted successfully for Employee {EmployeeId}", employeeId);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var embeddingData = JsonSerializer.Deserialize<FaceEmbeddingResponse>(content,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingDeletedAsync(workshopId, employeeId);
}
_logger.LogInformation("Embedding retrieved successfully for Employee {EmployeeId}", employeeId);
return new OperationResult { IsSuccedded = true, Message = "Embedding حذف شد" };
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to delete embedding. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در حذف Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while deleting embedding for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در حذف Embedding"
};
}
}
public async Task<OperationResult<FaceEmbeddingResponse>> GetEmbeddingAsync(long employeeId, long workshopId)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
var response = await httpClient.GetAsync($"embeddings/{workshopId}/{employeeId}");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var embeddingData = JsonSerializer.Deserialize<FaceEmbeddingResponse>(content,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
_logger.LogInformation("Embedding retrieved successfully for Employee {EmployeeId}", employeeId);
return new OperationResult<FaceEmbeddingResponse>
{
IsSuccedded = true,
Message = "Embedding دریافت شد",
Data = embeddingData
};
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to get embedding. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
return new OperationResult<FaceEmbeddingResponse>
{
IsSuccedded = false,
Message = $"خطا در دریافت Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while getting embedding for Employee {EmployeeId}", employeeId);
return new OperationResult<FaceEmbeddingResponse>
{
IsSuccedded = false,
Message = "خطا در دریافت Embedding"
};
}
}
public async Task<OperationResult> UpdateEmbeddingFullNameAsync(long employeeId, long workshopId,
string newFullName)
{
try
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(30);
var requestBody = new
{
employee_id = employeeId,
workshop_id = workshopId,
employee_full_name = newFullName
};
var response = await httpClient.PutAsJsonAsync("embeddings/update-name", requestBody);
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Employee Name Changed For {EmployeeId} In workshop ={WorkshopId}", employeeId,
workshopId);
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
//await _notificationService.NotifyEmbeddingRefinedAsync(workshopId, employeeId);
}
return new OperationResult { IsSuccedded = true, Message = "عملیات با موفقیت انجام شد" };
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to refine embedding. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
return new OperationResult
{
IsSuccedded = false,
Message = $"خطا در بهبود Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while Changing EmployeeFullName for Employee {EmployeeId}", employeeId);
return new OperationResult
{
IsSuccedded = false,
Message = "خطا در بهبود Embedding"
};
}
}
}
return new OperationResult<FaceEmbeddingResponse>
{
IsSuccedded = true,
Message = "Embedding دریافت شد",
Data = embeddingData
};
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError("Failed to get embedding. Status: {StatusCode}, Error: {Error}",
response.StatusCode, errorContent);
return new OperationResult<FaceEmbeddingResponse>
{
IsSuccedded = false,
Message = $"خطا در دریافت Embedding: {response.StatusCode}"
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while getting embedding for Employee {EmployeeId}", employeeId);
return new OperationResult<FaceEmbeddingResponse>
{
IsSuccedded = false,
Message = "خطا در دریافت Embedding"
};
}
}
}

View File

@@ -1,4 +1,6 @@
namespace AccountManagement.Application.Contracts.Account;
using System.Collections.Generic;
namespace AccountManagement.Application.Contracts.Account;
public class EditAccount : CreateAccount
{

View File

@@ -1,4 +1,10 @@
namespace AccountManagement.Application.Contracts.Account;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccountManagement.Application.Contracts.Account;
public class EditClientAccount : RegisterAccount
{

View File

@@ -2,7 +2,7 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Shared.Contracts.PmUser.Queries;
using AccountManagement.Application.Contracts.ProgramManager;
namespace AccountManagement.Application.Contracts.Account;
@@ -74,8 +74,12 @@ public interface IAccountApplication
void CameraLogin(CameraLoginRequest request);
Task<GetPmUserDto> GetPmUserAsync(long accountId);
/// <summary>
/// دریافت کاربر پروگرام منیجر با اکانت آی دی
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
Task<GetPmUserDto> GetPmUserByAccountId(long accountId);
}
public class CameraLoginRequest

View File

@@ -1,4 +1,10 @@
using System.ComponentModel.DataAnnotations;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _0_Framework.Application;
using Microsoft.AspNetCore.Http;
namespace AccountManagement.Application.Contracts.Account;

View File

@@ -1,4 +1,10 @@
namespace AccountManagement.Application.Contracts.Account;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccountManagement.Application.Contracts.Account;
public class WorkshopSelectList
{

View File

@@ -1,8 +1,9 @@
namespace Shared.Contracts.PmUser.Queries;
using System.Collections.Generic;
namespace AccountManagement.Application.Contracts.ProgramManager;
public class GetPmUserDto
{
public long Id { get; set; }
/// <summary>
/// نام و نام خانوادگی
/// </summary>
@@ -42,7 +43,7 @@ public class GetPmUserDto
public List<long> Roles { get; set; }
public List<RoleListDto>? RoleListDto { get; set; }
public List<RoleListDto> RoleListDto { get; set; }
}

View File

@@ -0,0 +1,28 @@
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

@@ -2,9 +2,13 @@
using _0_Framework.Application.Sms;
using _0_Framework.Exceptions;
using AccountManagement.Application.Contracts.Account;
using AccountManagement.Application.Contracts.ProgramManagerApiResult;
using AccountManagement.Domain.AccountAgg;
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 AccountManagement.Domain.SubAccountAgg;
@@ -13,14 +17,25 @@ 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 Shared.Contracts.PmUser.Commands;
using Shared.Contracts.PmUser.Queries;
using AccountManagement.Application.Contracts.ProgramManager;
using Shared.Contracts.PmUser;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
//using AccountManagement.Domain.RoleAgg;
@@ -42,13 +57,12 @@ public class AccountApplication : IAccountApplication
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, IPmUserQueryService pmUserQueryService, IPmUserCommandService pmUserCommandService)
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)
{
_authHelper = authHelper;
_roleRepository = roleRepository;
@@ -62,9 +76,8 @@ public class AccountApplication : IAccountApplication
_workshopSubAccountRepository = workshopSubAccountRepository;
_accountPermissionSubtitle1Repository = accountPermissionSubtitle1Repository;
_unitOfWork = unitOfWork;
_pmUserRepository = pmUserRepository;
_pmUserQueryService = pmUserQueryService;
_pmUserCommandService = pmUserCommandService;
_fileUploader = fileUploader;
_passwordHasher = passwordHasher;
_accountRepository = accountRepository;
@@ -155,18 +168,40 @@ public class AccountApplication : IAccountApplication
if (command.IsProgramManagerUser)
{
if (command.UserRoles == null)
return operation.Failed("حداقل یک نقش برای کاربر مدیریت پروژه لازم است");
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)
try
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش کاربر پروگرام منیجر");
if (_pmUserRepository.Exists(x => x.FullName == command.Fullname))
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("نام و خانوادگی تکراری است");
}
if (_pmUserRepository.Exists(x => x.UserName == command.Username))
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("نام کاربری تکراری است");
}
if (_pmUserRepository.Exists(x => !string.IsNullOrWhiteSpace(x.Mobile) && x.Mobile == command.Mobile))
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("این شماره همراه قبلا به فرد دیگری اختصاص داده شده است");
}
var userRoles = command.UserRoles.Where(x => x > 0).Select(x => new PmRoleUser(x)).ToList();
var create = new PmUser(command.Fullname, command.Username, command.Password, command.Mobile,
null, account.id, userRoles);
await _pmUserRepository.CreateAsync(create);
await _pmUserRepository.SaveChangesAsync();
}
catch (Exception e)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ایجاد کاربر پروگرام منیجر");
}
//var url = "api/user/create";
//var key = SecretKeys.ProgramManagerInternalApi;
@@ -252,29 +287,31 @@ public class AccountApplication : IAccountApplication
// $"api/user/{account.id}",
// key
//);
var userResult =await _pmUserQueryService.GetPmUserDataByAccountId(account.id);
var userResult = _pmUserRepository.GetByPmUsertoEditbyAccountId(account.id).GetAwaiter().GetResult();
if (command.UserRoles == null)
return operation.Failed("حداقل یک نقش برای کاربر مدیریت پروژه لازم است");
var pmUserRoles = command.UserRoles.Where(x => x > 0).ToList();
//اگر کاربر در پروگرام منیجر قبلا ایجاد شده
if (userResult.Id >0)
if (userResult != null)
{
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)
try
{
var userRoles = command.UserRoles.Where(x => x > 0).Select(x => new PmRoleUser(x)).ToList();
userResult.Edit(command.Fullname, command.Username, command.Mobile, userRoles, command.IsProgramManagerUser);
await _pmUserRepository.SaveChangesAsync();
}
catch (Exception)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش کاربر پروگرام منیجر");
}
//var parameters = new EditUserCommand(
// command.Fullname,
// command.Username,
@@ -315,19 +352,39 @@ public class AccountApplication : IAccountApplication
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)
if (_pmUserRepository.Exists(x => x.FullName == command.Fullname))
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("نام و خانوادگی تکراری است");
}
if (_pmUserRepository.Exists(x => x.UserName == command.Username))
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("نام کاربری تکراری است");
}
if (_pmUserRepository.Exists(x => !string.IsNullOrWhiteSpace(x.Mobile) && x.Mobile == command.Mobile))
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("این شماره همراه قبلا به فرد دیگری اختصاص داده شده است");
}
try
{
var userRoles = command.UserRoles.Where(x => x > 0).Select(x => new PmRoleUser(x)).ToList();
var create = new PmUser(command.Fullname, command.Username, account.Password, command.Mobile,
null, account.id, userRoles);
await _pmUserRepository.CreateAsync(create);
await _pmUserRepository.SaveChangesAsync();
}
catch (Exception)
{
_unitOfWork.RollbackAccountContext();
return operation.Failed("خطا در ویرایش کاربر پروگرام منیجر");
}
//var parameters = new CreateProgramManagerUser(
@@ -400,23 +457,6 @@ public class AccountApplication : IAccountApplication
.Permissions
.Select(x => x.Code)
.ToList();
//PmPermission
var PmUserData = _pmUserQueryService.GetPmUserDataByAccountId(account.id).GetAwaiter().GetResult();
if (PmUserData.AccountId > 0 && PmUserData.IsActive)
{
var pmUserPermissions =
PmUserData.RoleListDto != null
? PmUserData.RoleListDto
.SelectMany(x => x.Permissions)
.Where(p => p != 99)
.Distinct()
.ToList()
: new List<int>();
permissions.AddRange(pmUserPermissions);
}
int? positionValue;
if (account.PositionId != null)
{
@@ -426,7 +466,7 @@ public class AccountApplication : IAccountApplication
{
positionValue = null;
}
var pmUserId = PmUserData.AccountId > 0 ? PmUserData.AccountId : 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,
@@ -1020,8 +1060,8 @@ public class AccountApplication : IAccountApplication
_authHelper.CameraSignIn(authViewModel);
}
public async Task<GetPmUserDto> GetPmUserAsync(long accountId)
public async Task<GetPmUserDto> GetPmUserByAccountId(long accountId)
{
return await _pmUserQueryService.GetPmUserDataByAccountId(accountId);
return await _pmUserRepository.GetPmUserByAccountId(accountId);
}
}

View File

@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _0_Framework.Application;
using AccountManagement.Application.Contracts.Account;
using AccountManagement.Application.Contracts.CameraAccount;

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using _0_Framework.Application;

View File

@@ -4,7 +4,13 @@ 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;
@@ -16,15 +22,18 @@ 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, IPmRoleQueryService pmRoleQueryService, IPmRoleCommandService pmRoleCommandService)
public RoleApplication(IRoleRepository roleRepository, IUnitOfWork unitOfWork, IPmRoleRepository pmRoleRepository, IPmUserRepository pmUserRepository, IPmRoleQueryService pmRoleQueryService, IPmRoleCommandService pmRoleCommandService)
{
_roleRepository = roleRepository;
_unitOfWork = unitOfWork;
_pmRoleRepository = pmRoleRepository;
_pmUserRepository = pmUserRepository;
_pmRoleQueryService = pmRoleQueryService;
_pmRoleCommandService = pmRoleCommandService;
}
@@ -179,28 +188,22 @@ public class RoleApplication : IRoleApplication
//این نقش را سمت پروگرام منیجر بساز
if (pmPermissions.Any())
{
var pmRole = new CreatePmRoleDto { RoleName = command.Name, Permissions = pmPermissions, GozareshgirRoleId = role.id };
var res = await _pmRoleCommandService.Create(pmRole);
if (!res.Item1)
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("خطا در ویرایش دسترسی ها در پروگرام منیجر");
}
//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,

View File

@@ -5,11 +5,14 @@ using AccountManagement.Domain.AccountAgg;
using AccountManagement.Domain.CameraAccountAgg;
using AccountManagement.Domain.SubAccountAgg;
using AccountManagement.Domain.SubAccountRoleAgg;
using Company.Domain.WorkshopAccountAgg;
using Company.Domain.WorkshopSubAccountAgg;
using CompanyManagment.App.Contracts.Workshop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
namespace AccountManagement.Application

View File

@@ -1,7 +1,9 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using _0_Framework.Application;
using AccountManagement.Application.Contracts.TaskSubject;
using AccountManagement.Domain.TaskSubjectAgg;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
namespace AccountManagement.Application;

View File

@@ -0,0 +1,18 @@
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

@@ -0,0 +1,20 @@
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

@@ -0,0 +1,15 @@
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

@@ -0,0 +1,46 @@
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

@@ -0,0 +1,19 @@
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

@@ -0,0 +1,21 @@
using _0_Framework.Domain;
using AccountManagement.Application.Contracts.ProgramManager;
using System.Threading.Tasks;
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

@@ -0,0 +1,127 @@
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

@@ -0,0 +1,24 @@
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

@@ -0,0 +1,30 @@
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

@@ -0,0 +1,32 @@
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

@@ -0,0 +1,49 @@
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

@@ -0,0 +1,47 @@
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;
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

@@ -12,7 +12,6 @@
<ProjectReference Include="..\..\0_Framework\0_Framework.csproj" />
<ProjectReference Include="..\..\AccountManagement.Configuration\AccountManagement.Configuration.csproj" />
<ProjectReference Include="..\..\PersonalContractingParty.Config\PersonalContractingParty.Config.csproj" />
<ProjectReference Include="..\..\ProgramManager\src\Infrastructure\GozareshgirProgramManager.Infrastructure\GozareshgirProgramManager.Infrastructure.csproj" />
<ProjectReference Include="..\..\Query.Bootstrapper\Query.Bootstrapper.csproj" />
<ProjectReference Include="..\..\WorkFlow\Infrastructure\WorkFlow.Infrastructure.Config\WorkFlow.Infrastructure.Config.csproj" />
</ItemGroup>

View File

@@ -47,11 +47,6 @@ public class JobSchedulerRegistrator
() => SendBlockSms(),
"*/1 * * * *" // هر 1 دقیقه یکبار چک کن
);
RecurringJob.AddOrUpdate(
"InstitutionContract.SendInstitutionContractConfirmSms",
() => SendInstitutionContractConfirmSms(),
"*/1 * * * *" // هر 1 دقیقه یکبار چک کن
);
}
@@ -151,15 +146,4 @@ public class JobSchedulerRegistrator
await _institutionContractRepository.SendBlockSmsForBackgroundTask();
}
/// <summary>
/// ارسال پیامک یادآور تایید قراداد مالی
/// </summary>
/// <returns></returns>
[DisableConcurrentExecution(timeoutInSeconds: 100)]
public async System.Threading.Tasks.Task SendInstitutionContractConfirmSms()
{
await _institutionContractRepository.SendInstitutionContractConfirmSmsTask();
}
}

View File

@@ -7,16 +7,11 @@ using BackgroundInstitutionContract.Task;
using BackgroundInstitutionContract.Task.Jobs;
using CompanyManagment.App.Contracts.Hubs;
using CompanyManagment.EFCore.Services;
using GozareshgirProgramManager.Application._Bootstrapper;
using GozareshgirProgramManager.Application.Modules.Users.Commands.CreateUser;
using GozareshgirProgramManager.Infrastructure;
using GozareshgirProgramManager.Infrastructure.Persistence.Seed;
using Hangfire;
using Microsoft.AspNetCore.Identity;
using MongoDB.Driver;
using PersonalContractingParty.Config;
using Query.Bootstrapper;
using Shared.Contracts.PmUser.Queries;
using WorkFlow.Infrastructure.Config;
var builder = WebApplication.CreateBuilder(args);
@@ -43,15 +38,10 @@ builder.Services.AddSingleton<IMongoDatabase>(mongoDatabase);
#endregion
builder.Services.AddProgramManagerApplication();
builder.Services.AddProgramManagerInfrastructure(builder.Configuration);
PersonalBootstrapper.Configure(builder.Services, connectionString);
TestDbBootStrapper.Configure(builder.Services, connectionStringTestDb);
AccountManagementBootstrapper.Configure(builder.Services, connectionString);
WorkFlowBootstrapper.Configure(builder.Services, connectionString);
QueryBootstrapper.Configure(builder.Services);
JobsBootstrapper.Configure(builder.Services);
builder.Services.AddHttpClient();

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using _0_Framework.Application;
using _0_Framework.Domain;
using Company.Domain.EmployeeInsuranceRecordAgg;
using CompanyManagment.App.Contracts.Employee;
@@ -77,6 +78,7 @@ public interface IEmployeeRepository : IRepository<long, Employee>
Task<List<EmployeeSelectListViewModel>> GetSelectList(string searchText,long id);
Task<List<GetEmployeeListViewModel>> GetList(GetEmployeeListSearchModel searchModel);
#endregion
Task<List<GetEmployeeClientListViewModel>> GetEmployeeClientList(GetEmployeeClientListSearchModel searchModel,
long workshopId);
}

View File

@@ -140,11 +140,6 @@ public interface IInstitutionContractRepository : IRepository<long, InstitutionC
/// <returns></returns>
Task SendReminderSmsToContractingParties(List<SmsListData> smsListData, string typeOfSms, string sendMessStart, string sendMessEnd);
/// <summary>
/// ارسال پیامک یادآور تایید قراداد مالی
/// </summary>
/// <returns></returns>
Task SendInstitutionContractConfirmSmsTask();
#endregion
#region CreateMontlyTransaction

View File

@@ -98,9 +98,6 @@ public class InstitutionContract : EntityBase
// مبلغ قرارداد
public double ContractAmount { get; private set; }
public double ContractAmountWithTax => !IsOldContract && IsInstallment ? ContractAmount + (ContractAmount * 0.10)
: ContractAmount;
//خسارت روزانه
public double DailyCompenseation { get; private set; }
@@ -162,10 +159,6 @@ public class InstitutionContract : EntityBase
public List<InstitutionContractAmendment> Amendments { get; private set; }
public InstitutionContractSigningType? SigningType { get; private set; }
public bool IsOldContract => LawId== 0;
public InstitutionContract()
{
ContactInfoList = [];
@@ -269,10 +262,6 @@ public class InstitutionContract : EntityBase
{
WorkshopGroup = null;
}
public void SetSigningType(InstitutionContractSigningType signingType)
{
SigningType = signingType;
}
}
public class InstitutionContractAmendment : EntityBase

View File

@@ -10,15 +10,13 @@ public class InstitutionContractWorkshopCurrent:InstitutionContractWorkshopBase
public InstitutionContractWorkshopCurrent(string workshopName, bool hasRollCallPlan,
bool hasRollCallPlanInPerson, bool hasCustomizeCheckoutPlan, bool hasContractPlan,
bool hasContractPlanInPerson, bool hasInsurancePlan, bool hasInsurancePlanInPerson,
int personnelCount, double price,long institutionContractWorkshopGroupId,
InstitutionContractWorkshopGroup workshopGroup,long workshopId,long initialWorkshopId) : base(workshopName, hasRollCallPlan,
int personnelCount, double price,long institutionContractWorkshopGroupId,InstitutionContractWorkshopGroup workshopGroup,long workshopId) : base(workshopName, hasRollCallPlan,
hasRollCallPlanInPerson, hasCustomizeCheckoutPlan, hasContractPlan,
hasContractPlanInPerson, hasInsurancePlan, hasInsurancePlanInPerson, personnelCount, price)
{
InstitutionContractWorkshopGroupId = institutionContractWorkshopGroupId;
WorkshopGroup = workshopGroup;
WorkshopId = workshopId;
InitialWorkshopId = initialWorkshopId;
}
public long InstitutionContractWorkshopGroupId { get; private set; }
public InstitutionContractWorkshopGroup WorkshopGroup { get; private set; }

View File

@@ -37,10 +37,4 @@ public class InstitutionContractWorkshopGroup : EntityBase
CurrentWorkshops = updatedDetails.ToList();
LastModifiedDate = DateTime.Now;
}
public void AddCurrentWorkshop(InstitutionContractWorkshopCurrent currentWorkshop)
{
CurrentWorkshops.Add(currentWorkshop);
LastModifiedDate = DateTime.Now;
}
}

View File

@@ -31,7 +31,7 @@ public class InstitutionContractWorkshopInitial:InstitutionContractWorkshopBase
WorkshopCreated = true;
WorkshopCurrent = new InstitutionContractWorkshopCurrent(WorkshopName,Services.RollCall,Services.RollCallInPerson,
Services.CustomizeCheckout,Services.Contract,Services.ContractInPerson,Services.Insurance,
Services.InsuranceInPerson,PersonnelCount,Price,InstitutionContractWorkshopGroupId,WorkshopGroup,workshopId,id);
Services.InsuranceInPerson,PersonnelCount,Price,InstitutionContractWorkshopGroupId,WorkshopGroup,workshopId);
WorkshopCurrent.SetEmployers(Employers.Select(x=>x.EmployerId).ToList());
}

View File

@@ -73,7 +73,6 @@ public interface IInsuranceListRepository:IRepository<long, InsuranceList>
Task<InsuranceListConfirmOperation> GetInsuranceOperationDetails(long id);
Task<InsuranceListTabsCountViewModel> GetTabCounts(InsuranceListSearchModel searchModel);
Task<PagedResult<InsuranceClientListViewModel>> GetInsuranceClientList(InsuranceClientSearchModel searchModel);
#endregion

View File

@@ -26,7 +26,7 @@ public class CustomizeWorkshopGroupSettingExcelGenerator
{
public static byte[] Generate(List<CustomizeWorkshopGroupExcelViewModel> groups)
{
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("GroupsAndEmployees");

View File

@@ -24,7 +24,7 @@ public class CaseManagementExcelGenerator
};
public static byte[] GenerateCheckoutTempExcelInfo(List<FileExcelViewModel> data)
{
OfficeOpenXml.ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
OfficeOpenXml.ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage();
CreateSheet(data, package,"همه");
CreateSheet(data.Where(x=>x.Status ==2).ToList(), package,"فعال");

View File

@@ -46,7 +46,7 @@ public class CustomizeCheckoutExcelGenerator
};
public static byte[] GenerateCheckoutTempExcelInfo(List<CustomizeCheckoutTempExcelViewModel> data, List<string> selectedParameters)
{
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
OfficeOpenXml.ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Sheet1");

View File

@@ -7,7 +7,7 @@ public class EmployeeBankInfoExcelGenerator
{
public static byte[] Generate(List<EmployeeBankInfoExcelViewModel> list)
{
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("EmployeeBankInfo");
@@ -166,7 +166,7 @@ public class EmployeeBankInfoExcelGenerator
public static byte[] Generate2(List<EmployeeBankInfoExcelViewModel> list)
{
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage();
foreach (var employee in list)
{
@@ -220,4 +220,4 @@ public class EmployeeBankInfoExcelGenerator
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
}
}
}

View File

@@ -13,7 +13,7 @@ public class InstitutionContractExcelGenerator
public static byte[] GenerateExcel(List<InstitutionContractViewModel> institutionContractViewModels)
{
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage();
var allWorksheet = package.Workbook.Worksheets.Add("همه");

View File

@@ -8,7 +8,7 @@ public class RollCallExcelGenerator : ExcelGenerator
{
public static byte[] CaseHistoryExcelForEmployee(CaseHistoryRollCallExcelForEmployeeViewModel data)
{
OfficeOpenXml.ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
OfficeOpenXml.ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new OfficeOpenXml.ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
var rollCalls = data.RollCalls;
@@ -181,7 +181,7 @@ public class RollCallExcelGenerator : ExcelGenerator
public static byte[] CaseHistoryExcelForOneDay(CaseHistoryRollCallForOneDayViewModel data)
{
OfficeOpenXml.ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
OfficeOpenXml.ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new OfficeOpenXml.ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
var rollCalls = data.RollCalls;

View File

@@ -43,7 +43,7 @@ public class SalaryAidImportExcel
ValidData = []
};
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
if (file == null || file.Length == 0)
{

View File

@@ -9,7 +9,7 @@ public class WorkshopRollCallExcelExporter
{
public static byte[] Export(List<WorkshopRollCallExcelViewModel> workshops)
{
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage())
{
var ws = package.Workbook.Worksheets.Add("Workshops");

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using _0_Framework.Application;
using CompanyManagment.App.Contracts.Employee.DTO;
@@ -60,7 +61,7 @@ public interface IEmployeeApplication
/// <returns></returns>
Task<OperationResult<EmployeeByNationalCodeInWorkshopViewModel>>
ValidateCreateEmployeeClientByNationalCodeAndWorkshopId(string nationalCode,
string birthDate,bool authorizedCanceled, long workshopId);
string birthDate, long workshopId);
/// <summary>
/// پرسنل هایی که در کارگاهی از سمت ادمین شروع به کار کرده اند
@@ -95,6 +96,41 @@ public interface IEmployeeApplication
/// <returns></returns>
Task<List<GetEmployeeListViewModel>> GetList(GetEmployeeListSearchModel searchModel);
Task<List<GetEmployeeClientListViewModel>> GetEmployeeClientList(GetEmployeeClientListSearchModel searchModel,
long workshopId);
#endregion
}
public class GetEmployeeClientListSearchModel
{
public string NationalCode { get; set; }
public string FullName { get; set; }
}
public class GetEmployeeClientListViewModel
{
public long WorkshopId { get; set; }
public long EmployeeId { get; set; }
public string FullName { get; set; }
public long PersonnelCode { get; set; }
public bool HasInsurance { get; set; }
public bool HasContract { get; set; }
public bool InsuranceLeft { get; set; }
public bool ContractLeft { get; set; }
public DateTime StartWork { get; set; }
public DateTime LeftWork { get; set; }
public string LastStartInsuranceWork { get; set; }
public string LastLeftInsuranceWork { get; set; }
public string LastStartContractWork { get; set; }
public string LastLeftContractWork { get; set; }
public string NationalCode { get; set; }
public string IdNumber { get; set; }
public string MaritalStatus { get; set; }
public string DateOfBirthFa { get; set; }
public string FatherName { get; set; }
public bool PendingCreate { get; set; }
public bool PendingLefWork { get; set; }
public int ChildrenCount { get; set; }
}

View File

@@ -13,6 +13,5 @@ namespace CompanyManagment.App.Contracts.EmployeeDocuments
public string EmployerName { get; set; }
public List<EmployeeDocumentItemViewModel> SubmittedItems { get; set; }
public int EmployeesWithoutDocumentCount { get; set; }
public long EmployeeId { get; set; }
}
}

View File

@@ -1,17 +0,0 @@
namespace CompanyManagment.App.Contracts.InstitutionContract;
public enum InstitutionContractSigningType
{
/// <summary>
/// قدیمی
/// </summary>
Legacy = 0,
/// <summary>
/// الکترونیکی با کد یکبار مصرف
/// </summary>
OtpBased = 1,
/// <summary>
/// به صورت فیزیکی
/// </summary>
Physical = 2
}

View File

@@ -7,6 +7,7 @@ using System.Threading.Tasks;
using _0_Framework.Application;
using _0_Framework.Application.Sms;
using CompanyManagment.App.Contracts.Checkout;
using CompanyManagment.App.Contracts.Law;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using CompanyManagment.App.Contracts.Workshop;
using CompanyManagment.App.Contracts.WorkshopPlan;
@@ -259,13 +260,154 @@ public interface IInstitutionContractApplication
/// <returns></returns>
Task<InstitutionContractPrintViewModel> PrintOneAsync(long id);
Task<OperationResult> SetPendingWorkflow(long entityId,InstitutionContractSigningType signingType);
Task<OperationResult> SetPendingWorkflow(long entityId);
Task<long> GetIdByInstallmentId(long installmentId);
/// <summary>
/// تایید قرارداد مالی به صورت دستی
/// </summary>
/// <param name="institutionContractId"></param>
/// <returns></returns>
Task<OperationResult> VerifyInstitutionContractManually(long institutionContractId);
}
public class InstitutionContractDiscountResponse
{
public InstitutionContractDiscountOneTimeViewModel OneTime { get; set; }
public InstitutionContractDiscountMonthlyViewModel Monthly { get; set; }
}
public class InstitutionContractDiscountMonthlyViewModel:InstitutionContractDiscountOneTimeViewModel
{
public List<MonthlyInstallment> Installments { get; set; }
}
public class InstitutionContractDiscountOneTimeViewModel
{
/// <summary>
/// مجموع مبالغ
/// </summary>
public string TotalAmount { get; set; }
/// <summary>
/// ارزش افزوده
/// </summary>
public string Tax { get; set; }
/// <summary>
/// مبلغ قابل پرداخت
/// </summary>
public string PaymentAmount { get; set; }
public string DiscountedAmount { get; set; }
public int DiscountPercetage { get; set; }
public string Obligation { get; set; }
public string OneMonthAmount { get; set; }
}
public class InstitutionContractResetDiscountForCreateRequest
{
public int DiscountPercentage { get; set; }
public double TotalAmount { get; set; }
public bool IsInstallment { get; set; }
public InstitutionContractDuration Duration { get; set; }
public double OneMonthAmount { get; set; }
}
public class InstitutionContractSetDiscountForExtensionRequest
{
public Guid TempId { get; set; }
public int DiscountPercentage { get; set; }
public double TotalAmount { get; set; }
public bool IsInstallment { get; set; }
}
public class InstitutionContractResetDiscountForExtensionRequest
{
public Guid TempId { get; set; }
public bool IsInstallment { get; set; }
}
public class InstitutionContractSetDiscountRequest
{
public int DiscountPercentage { get; set; }
public double TotalAmount { get; set; }
public InstitutionContractDuration Duration { get; set; }
public double OneMonthAmount { get; set; }
public bool IsInstallment { get; set; }
}
public class InstitutionContractPrintViewModel
{
public InstitutionContratVerificationParty FirstParty { get; set; }
public InstitutionContratVerificationParty SecondParty { get; set; }
public string ContractNo { get; set; }
public string CreationDate { get; set; }
public string ContractStart { get; set; }
public string ContractEnd { get; set; }
public List<GetInstitutionVerificationDetailsWorkshopsViewModel> Workshops { get; set; }
public string TotalPrice { get; set; }
public string TaxPrice { get; set; }
public string PaymentPrice { get; set; }
public string VerifyCode { get; set; }
public string VerifyDate { get; set; }
public string VerifyTime { get; set; }
public string VerifierFullName { get; set; }
public string VerifierPhoneNumber { get; set; }
public LawViewModel LawViewModel { get; set; }
public string Obligation { get; set; }
}
public class InsertAmendmentTempWorkshopResponse
{
public Guid WorkshopTempId { get; set; }
public string Amount { get; set; }
}
public class InstitutionContractAmendmentWorkshopsResponse
{
/// <summary>
///
/// </summary>
public List<InstitutionContractAmendmentTempWorkshopViewModel> Workshops { get; set; }
public Guid TempId { get; set; }
}
public class InstitutionContractSelectListViewModel : SelectListViewModel;
public class InstitutionContractExtensionInquiryResponse
{
public long Id { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string DateOfBirthFa { get; set; }
public string FatherName { get; set; }
public string IdNumberSerial { get; set; }
public string IdNumber { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string City { get; set; }
public string State { get; set; }
public long RepresentativeId { get; set; }
public string NationalCode { get; set; }
}
public class InstitutionContractExtensionPaymentMonthly:InstitutionContractExtensionPaymentOneTime
{
public List<MonthlyInstallment> Installments { get; set; }
}
public class InstitutionContractExtensionPaymentOneTime
{
/// <summary>
/// مجموع مبالغ
/// </summary>
public string TotalAmount { get; set; }
/// <summary>
/// ارزش افزوده
/// </summary>
public string Tax { get; set; }
/// <summary>
/// مبلغ قابل پرداخت
/// </summary>
public string PaymentAmount { get; set; }
}

View File

@@ -1,9 +0,0 @@
using System;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InsertAmendmentTempWorkshopResponse
{
public Guid WorkshopTempId { get; set; }
public string Amount { get; set; }
}

View File

@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractAmendmentWorkshopsResponse
{
/// <summary>
///
/// </summary>
public List<InstitutionContractAmendmentTempWorkshopViewModel> Workshops { get; set; }
public Guid TempId { get; set; }
}

View File

@@ -1,38 +0,0 @@
using System.Collections.Generic;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractDiscountResponse
{
public InstitutionContractDiscountOneTimeViewModel OneTime { get; set; }
public InstitutionContractDiscountMonthlyViewModel Monthly { get; set; }
}
public class InstitutionContractDiscountMonthlyViewModel:InstitutionContractDiscountOneTimeViewModel
{
public List<MonthlyInstallment> Installments { get; set; }
}
public class InstitutionContractDiscountOneTimeViewModel
{
/// <summary>
/// مجموع مبالغ
/// </summary>
public string TotalAmount { get; set; }
/// <summary>
/// ارزش افزوده
/// </summary>
public string Tax { get; set; }
/// <summary>
/// مبلغ قابل پرداخت
/// </summary>
public string PaymentAmount { get; set; }
public string DiscountedAmount { get; set; }
public int DiscountPercetage { get; set; }
public string Obligation { get; set; }
public string OneMonthAmount { get; set; }
}

View File

@@ -1,18 +0,0 @@
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractExtensionInquiryResponse
{
public long Id { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string DateOfBirthFa { get; set; }
public string FatherName { get; set; }
public string IdNumberSerial { get; set; }
public string IdNumber { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string City { get; set; }
public string State { get; set; }
public long RepresentativeId { get; set; }
public string NationalCode { get; set; }
}

View File

@@ -1,24 +0,0 @@
using System.Collections.Generic;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractExtensionPaymentMonthly:InstitutionContractExtensionPaymentOneTime
{
public List<MonthlyInstallment> Installments { get; set; }
}
public class InstitutionContractExtensionPaymentOneTime
{
/// <summary>
/// مجموع مبالغ
/// </summary>
public string TotalAmount { get; set; }
/// <summary>
/// ارزش افزوده
/// </summary>
public string Tax { get; set; }
/// <summary>
/// مبلغ قابل پرداخت
/// </summary>
public string PaymentAmount { get; set; }
}

View File

@@ -1,26 +0,0 @@
using System.Collections.Generic;
using CompanyManagment.App.Contracts.Law;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractPrintViewModel
{
public InstitutionContratVerificationParty FirstParty { get; set; }
public InstitutionContratVerificationParty SecondParty { get; set; }
public string ContractNo { get; set; }
public string CreationDate { get; set; }
public string ContractStart { get; set; }
public string ContractEnd { get; set; }
public List<GetInstitutionVerificationDetailsWorkshopsViewModel> Workshops { get; set; }
public string TotalPrice { get; set; }
public string TaxPrice { get; set; }
public string PaymentPrice { get; set; }
public string OneMonthPrice { get; set; }
public string VerifyCode { get; set; }
public string VerifyDate { get; set; }
public string VerifyTime { get; set; }
public string VerifierFullName { get; set; }
public string VerifierPhoneNumber { get; set; }
public LawViewModel LawViewModel { get; set; }
public string Obligation { get; set; }
}

View File

@@ -1,10 +0,0 @@
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractResetDiscountForCreateRequest
{
public int DiscountPercentage { get; set; }
public double TotalAmount { get; set; }
public bool IsInstallment { get; set; }
public InstitutionContractDuration Duration { get; set; }
public double OneMonthAmount { get; set; }
}

View File

@@ -1,9 +0,0 @@
using System;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractResetDiscountForExtensionRequest
{
public Guid TempId { get; set; }
public bool IsInstallment { get; set; }
}

View File

@@ -1,5 +0,0 @@
using _0_Framework.Application;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractSelectListViewModel : SelectListViewModel;

View File

@@ -1,11 +0,0 @@
using System;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractSetDiscountForExtensionRequest
{
public Guid TempId { get; set; }
public int DiscountPercentage { get; set; }
public double TotalAmount { get; set; }
public bool IsInstallment { get; set; }
}

View File

@@ -1,10 +0,0 @@
namespace CompanyManagment.App.Contracts.InstitutionContract;
public class InstitutionContractSetDiscountRequest
{
public int DiscountPercentage { get; set; }
public double TotalAmount { get; set; }
public InstitutionContractDuration Duration { get; set; }
public double OneMonthAmount { get; set; }
public bool IsInstallment { get; set; }
}

View File

@@ -1,12 +0,0 @@
using System;
namespace CompanyManagment.App.Contracts.InstitutionContract;
public record InstitutionCreationVerificationSmsDto
{
public string Number{ get; set; }
public string FullName { get; set; }
public Guid InstitutionId { get; set; }
public long ContractingPartyId { get; set; }
public long InstitutionContractId { get; set; }
};

View File

@@ -90,27 +90,8 @@ public interface IInsuranceListApplication
Task<InsuranceListConfirmOperation> GetInsuranceOperationDetails(long id);
Task<InsuranceListTabsCountViewModel> GetTabCounts(InsuranceListSearchModel searchModel);
Task<PagedResult<InsuranceClientListViewModel>> GetInsuranceClientList(InsuranceClientSearchModel searchModel);
#endregion
Task<List<InsuranceListViewModel>> GetNotCreatedWorkshop(InsuranceListSearchModel searchModel);
}
public class InsuranceClientSearchModel:PaginationRequest
{
public int Year { get; set; }
public int Month { get; set; }
public string Sorting { get; set; }
}
public class InsuranceClientListViewModel
{
public long Id { get; set; }
public string Year { get; set; }
public string Month { get; set; }
public long WorkShopId { get; set; }
public int YearInt { get; set; }
public string MonthName { get; set; }
public int MonthInt { get; set; }
}

View File

@@ -1,7 +1,6 @@
using _0_Framework.Application;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CompanyManagment.App.Contracts.RollCallEmployee;

View File

@@ -64,33 +64,49 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
private readonly ILeftWorkInsuranceRepository _leftWorkInsuranceRepository;
private readonly IFaceEmbeddingService _faceEmbeddingService;
public EmployeeAplication(IEmployeeRepository employeeRepository, CompanyContext context, IWorkshopRepository workShopRepository, IWebHostEnvironment webHostEnvironment, IRollCallEmployeeStatusApplication rollCallEmployeeStatusApplication, IRollCallEmployeeRepository rollCallEmployeeRepository, ICustomizeWorkshopSettingsApplication customizeWorkshopSettingsApplication, IEmployeeDocumentsApplication employeeDocumentsApplication, IEmployeeDocumentsRepository employeeDocumentsRepository, IEmployeeBankInformationApplication employeeBankInformationApplication, ILeftWorkTempRepository leftWorkTempRepository, IUidService uidService, ICustomizeWorkshopEmployeeSettingsRepository customizeWorkshopEmployeeSettingsRepository, IPersonnelCodeRepository personnelCodeRepository, IEmployeeClientTempRepository employeeClientTempRepository, ICustomizeWorkshopGroupSettingsRepository customizeWorkshopGroupSettingsRepository, ILeftWorkRepository leftWorkRepository, IEmployeeAuthorizeTempRepository employeeAuthorizeTempRepository, ILeftWorkInsuranceRepository leftWorkInsuranceRepository, IFaceEmbeddingService faceEmbeddingService) : base(context)
{
_context = context;
_WorkShopRepository = workShopRepository;
_webHostEnvironment = webHostEnvironment;
_rollCallEmployeeStatusApplication = rollCallEmployeeStatusApplication;
_rollCallEmployeeRepository = rollCallEmployeeRepository;
_customizeWorkshopSettingsApplication = customizeWorkshopSettingsApplication;
_employeeDocumentsApplication = employeeDocumentsApplication;
_employeeBankInformationApplication = employeeBankInformationApplication;
_leftWorkTempRepository = leftWorkTempRepository;
_uidService = uidService;
_customizeWorkshopEmployeeSettingsRepository = customizeWorkshopEmployeeSettingsRepository;
_personnelCodeRepository = personnelCodeRepository;
_employeeClientTempRepository = employeeClientTempRepository;
_leftWorkRepository = leftWorkRepository;
_employeeAuthorizeTempRepository = employeeAuthorizeTempRepository;
_leftWorkInsuranceRepository = leftWorkInsuranceRepository;
_EmployeeRepository = employeeRepository;
_faceEmbeddingService = faceEmbeddingService;
}
public EmployeeAplication(IEmployeeRepository employeeRepository, CompanyContext context,
IWorkshopRepository workShopRepository, IWebHostEnvironment webHostEnvironment,
IRollCallEmployeeStatusApplication rollCallEmployeeStatusApplication,
IRollCallEmployeeRepository rollCallEmployeeRepository,
ICustomizeWorkshopSettingsApplication customizeWorkshopSettingsApplication,
IEmployeeDocumentsApplication employeeDocumentsApplication,
IEmployeeDocumentsRepository employeeDocumentsRepository,
IEmployeeBankInformationApplication employeeBankInformationApplication,
ILeftWorkTempRepository leftWorkTempRepository, IUidService uidService,
ICustomizeWorkshopEmployeeSettingsRepository customizeWorkshopEmployeeSettingsRepository,
IPersonnelCodeRepository personnelCodeRepository, IEmployeeClientTempRepository employeeClientTempRepository,
ICustomizeWorkshopGroupSettingsRepository customizeWorkshopGroupSettingsRepository,
ILeftWorkRepository leftWorkRepository, IEmployeeAuthorizeTempRepository employeeAuthorizeTempRepository,
ILeftWorkInsuranceRepository leftWorkInsuranceRepository,
IFaceEmbeddingService faceEmbeddingService) : base(context)
{
_context = context;
_WorkShopRepository = workShopRepository;
_webHostEnvironment = webHostEnvironment;
_rollCallEmployeeStatusApplication = rollCallEmployeeStatusApplication;
_rollCallEmployeeRepository = rollCallEmployeeRepository;
_customizeWorkshopSettingsApplication = customizeWorkshopSettingsApplication;
_employeeDocumentsApplication = employeeDocumentsApplication;
_employeeBankInformationApplication = employeeBankInformationApplication;
_leftWorkTempRepository = leftWorkTempRepository;
_uidService = uidService;
_customizeWorkshopEmployeeSettingsRepository = customizeWorkshopEmployeeSettingsRepository;
_personnelCodeRepository = personnelCodeRepository;
_employeeClientTempRepository = employeeClientTempRepository;
_leftWorkRepository = leftWorkRepository;
_employeeAuthorizeTempRepository = employeeAuthorizeTempRepository;
_leftWorkInsuranceRepository = leftWorkInsuranceRepository;
_EmployeeRepository = employeeRepository;
_faceEmbeddingService = faceEmbeddingService;
}
public OperationResult Create(CreateEmployee command)
public OperationResult Create(CreateEmployee command)
{
var opration = new OperationResult();
if (_EmployeeRepository.Exists(x =>
x.LName == command.LName && x.NationalCode == command.NationalCode && !string.IsNullOrWhiteSpace(command.NationalCode) && x.NationalCode != null && x.IsActiveString == "true"))
x.LName == command.LName && x.NationalCode == command.NationalCode &&
!string.IsNullOrWhiteSpace(command.NationalCode) && x.NationalCode != null &&
x.IsActiveString == "true"))
return opration.Failed("امکان ثبت رکورد تکراری وجود ندارد");
//if (_EmployeeRepository.Exists(x => x.IdNumber == command.IdNumber && x.IdNumber !=null))
@@ -182,13 +198,13 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
else
{
nationalCodValid = false;
return opration.Failed("کد ملی وارد شده نا معتبر است");
nationalCodValid = false;
return opration.Failed("کد ملی وارد شده نا معتبر است");
}
}
catch (Exception)
@@ -198,6 +214,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return opration.Failed("لطفا کد ملی 10 رقمی وارد کنید");
}
if (_EmployeeRepository.Exists(x => x.NationalCode == command.NationalCode))
{
nationalcodeIsOk = false;
@@ -210,24 +227,31 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
string initial = "1300/10/11";
var dateOfBirth = command.DateOfBirth != null ? command.DateOfBirth.ToGeorgianDateTime() : initial.ToGeorgianDateTime();
var dateOfIssue = command.DateOfIssue != null ? command.DateOfIssue.ToGeorgianDateTime() : initial.ToGeorgianDateTime();
var dateOfBirth = command.DateOfBirth != null
? command.DateOfBirth.ToGeorgianDateTime()
: initial.ToGeorgianDateTime();
var dateOfIssue = command.DateOfIssue != null
? command.DateOfIssue.ToGeorgianDateTime()
: initial.ToGeorgianDateTime();
var employeeData = new Employee(command.FName, command.LName, command.FatherName, dateOfBirth,
dateOfIssue,
command.PlaceOfIssue, command.NationalCode, command.IdNumber, command.Gender, command.Nationality, command.IdNumberSerial, command.IdNumberSeri,
command.PlaceOfIssue, command.NationalCode, command.IdNumber, command.Gender, command.Nationality,
command.IdNumberSerial, command.IdNumberSeri,
command.Phone, command.Address,
command.State, command.City, command.MaritalStatus, command.MilitaryService, command.LevelOfEducation,
command.FieldOfStudy, command.BankCardNumber,
command.BankBranch, command.InsuranceCode, command.InsuranceHistoryByYear,
command.InsuranceHistoryByMonth, command.NumberOfChildren, command.OfficePhone, command.MclsUserName, command.MclsPassword, command.EserviceUserName, command.EservicePassword,
command.InsuranceHistoryByMonth, command.NumberOfChildren, command.OfficePhone, command.MclsUserName,
command.MclsPassword, command.EserviceUserName, command.EservicePassword,
command.TaxOfficeUserName, command.TaxOfficepassword, command.SanaUserName, command.SanaPassword);
if (command.IsAuthorized)
{
employeeData.Authorized();
}
_EmployeeRepository.Create(employeeData);
_EmployeeRepository.SaveChanges();
@@ -244,7 +268,8 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return opration.Failed("رکورد مورد نظر یافت نشد");
if (_EmployeeRepository.Exists(x =>
x.LName == command.LName && x.NationalCode == command.NationalCode && !string.IsNullOrWhiteSpace(command.NationalCode) && x.id != command.Id && x.IsActiveString == "true"))
x.LName == command.LName && x.NationalCode == command.NationalCode &&
!string.IsNullOrWhiteSpace(command.NationalCode) && x.id != command.Id && x.IsActiveString == "true"))
return opration.Failed("امکان ثبت رکورد تکراری وجود ندارد");
//if (_EmployeeRepository.Exists(x => x.IdNumber == command.IdNumber && x.IdNumber != null && x.id != command.Id))
// return opration.Failed("شماره شناسنامه وارد شده تکراری است");
@@ -339,6 +364,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return opration.Failed("لطفا کد ملی 10 رقمی وارد کنید");
}
if (_EmployeeRepository.Exists(x => x.NationalCode == command.NationalCode && x.id != command.Id))
{
nationalcodeIsOk = false;
@@ -349,8 +375,12 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
string initial = "1300/10/11";
var dateOfBirth = command.DateOfBirth != null ? command.DateOfBirth.ToGeorgianDateTime() : initial.ToGeorgianDateTime();
var dateOfIssue = command.DateOfIssue != null ? command.DateOfIssue.ToGeorgianDateTime() : initial.ToGeorgianDateTime();
var dateOfBirth = command.DateOfBirth != null
? command.DateOfBirth.ToGeorgianDateTime()
: initial.ToGeorgianDateTime();
var dateOfIssue = command.DateOfIssue != null
? command.DateOfIssue.ToGeorgianDateTime()
: initial.ToGeorgianDateTime();
employee.Edit(command.FName, command.LName, command.FatherName, dateOfBirth,
dateOfIssue,
command.PlaceOfIssue, command.NationalCode, command.IdNumber, command.Gender, command.Nationality,
@@ -435,7 +465,8 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
var opration = new OperationResult();
var employeeData = new EmployeeInsuranceRecord(command.EmployeeId, command.WorkShopId, command.DateOfStart, command.DateOfEnd);
var employeeData = new EmployeeInsuranceRecord(command.EmployeeId, command.WorkShopId, command.DateOfStart,
command.DateOfEnd);
_EmployeeRepository.CreateEmployeeInsuranceRecord(employeeData);
_EmployeeRepository.SaveChanges();
@@ -444,6 +475,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
}
public OperationResult EditEmployeeInsuranceRecord(EditEmployeeInsuranceRecord command)
{
var opration = new OperationResult();
@@ -455,6 +487,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
}
public void RemoveEmployeeInsuranceRecord(long Id)
{
_EmployeeRepository.RemoveEmployeeInsuranceRecord(Id);
@@ -468,12 +501,14 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return opration.Failed("خطا در انتخاب کارگاه");
}
var ws = _WorkShopRepository.GetDetails(eir.WorkShopId);
if (string.IsNullOrWhiteSpace(eir.DateOfStart))
{
return opration.Failed("تاریخ شروع نمی تواند خالی باشد - " + ws.WorkshopFullName);
}
if (!string.IsNullOrWhiteSpace(eir.DateOfEnd))
{
if (eir.DateOfEnd.ToGeorgianDateTime() < eir.DateOfStart.ToGeorgianDateTime())
@@ -490,6 +525,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return opration.Succcedded();
}
public OperationResult ValidationEmployeeInsuranceRecord(List<CreateEmployeeInsuranceRecord> eir_lst)
{
var opration = new OperationResult();
@@ -509,16 +545,19 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
return opration.Failed("خطا در تداخل تاریخ - " + wshop.WorkshopFullName);
}
if (string.IsNullOrEmpty(q[i].DateOfEnd.ToString()))
{
count++;
}
}
if (count > 1)
{
return opration.Failed("تاریخ ترک کار را وارد نمایید ");
}
}
return opration.Succcedded();
@@ -532,11 +571,13 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
return opration.Failed("خطا در انتخاب پرسنل");
}
var employee = _EmployeeRepository.GetDetails(employeeId);
if (string.IsNullOrWhiteSpace(employee.FName))
{
error += "(نام)" + Environment.NewLine;
}
if (string.IsNullOrWhiteSpace(employee.LName))
{
error += "(نام خانوادگی)" + Environment.NewLine;
@@ -546,22 +587,27 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
error += "(کد ملی)" + Environment.NewLine;
}
if (string.IsNullOrWhiteSpace(employee.PlaceOfIssue))
{
error += "(شهر محل تولد)" + Environment.NewLine;
}
if (string.IsNullOrWhiteSpace(employee.DateOfBirth))
{
error += "(تاریخ تولد)" + Environment.NewLine;
}
if (string.IsNullOrWhiteSpace(employee.IdNumber))
{
error += "(شماره شناسنامه)" + Environment.NewLine;
}
if (string.IsNullOrWhiteSpace(employee.InsuranceCode))
{
error += "(شماره بیمه)" + Environment.NewLine;
}
if (!string.IsNullOrWhiteSpace(error))
{
var note = "آیتم های زیر برای ثبت سابقه الزامی می باشد" + Environment.NewLine + error;
@@ -610,7 +656,8 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
InsuranceCode = x.InsuranceCode,
IsActiveString = x.IsActiveString,
IsActive = x.IsActive,
PersonnelCode = _context.PersonnelCodeSet.FirstOrDefault(p => p.EmployeeId == x.Id && p.WorkshopId == searchModel.WorkshopId)?.PersonnelCode
PersonnelCode = _context.PersonnelCodeSet
.FirstOrDefault(p => p.EmployeeId == x.Id && p.WorkshopId == searchModel.WorkshopId)?.PersonnelCode
}).ToList();
//w2.Stop();
//Console.WriteLine("efore :" + w2.ElapsedMilliseconds);
@@ -619,6 +666,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
}
return res;
}
@@ -663,6 +711,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
if (_EmployeeRepository.ExistsEmployeeWorkshopNationalCode(command.NationalCode, command.WorkshopId))
return opration.Failed("کد ملی وارد شده تکراری است");
}
if (_EmployeeRepository.Exists(x => x.InsuranceCode == command.InsuranceCode && x.InsuranceCode != null))
{
if (_EmployeeRepository.ExistsEmployeeWorkshoppInsuranceCode(command.InsuranceCode, command.WorkshopId))
@@ -789,13 +838,17 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
if (_EmployeeRepository.Exists(x => x.NationalCode == command.NationalCode && x.id != command.Id))
{
nationalcodeIsOk = false;
if (_EmployeeRepository.ExistsEmployeeWorkshopNationalCodeEmployeeId(command.NationalCode, command.WorkshopId, command.Id))
if (_EmployeeRepository.ExistsEmployeeWorkshopNationalCodeEmployeeId(command.NationalCode,
command.WorkshopId, command.Id))
return opration.Failed("کد ملی وارد شده تکراری است");
}
if (!string.IsNullOrEmpty(command.InsuranceCode) && _EmployeeRepository.Exists(x => x.InsuranceCode == command.InsuranceCode && x.id != command.Id))
if (!string.IsNullOrEmpty(command.InsuranceCode) &&
_EmployeeRepository.Exists(x => x.InsuranceCode == command.InsuranceCode && x.id != command.Id))
{
nationalcodeIsOk = false;
if (_EmployeeRepository.ExistsEmployeeWorkshopInsuranceCodeEmployeeId(command.InsuranceCode, command.WorkshopId, command.Id))
if (_EmployeeRepository.ExistsEmployeeWorkshopInsuranceCodeEmployeeId(command.InsuranceCode,
command.WorkshopId, command.Id))
return opration.Failed("کد بیمه وارد شده تکراری است");
}
@@ -877,8 +930,12 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
string initial = "1300/10/11";
var dateOfBirth = command.DateOfBirth != null ? command.DateOfBirth.ToGeorgianDateTime() : initial.ToGeorgianDateTime();
var dateOfIssue = command.DateOfIssue != null ? command.DateOfIssue.ToGeorgianDateTime() : initial.ToGeorgianDateTime();
var dateOfBirth = command.DateOfBirth != null
? command.DateOfBirth.ToGeorgianDateTime()
: initial.ToGeorgianDateTime();
var dateOfIssue = command.DateOfIssue != null
? command.DateOfIssue.ToGeorgianDateTime()
: initial.ToGeorgianDateTime();
employee.Edit(command.FName, command.LName, command.FatherName, dateOfBirth,
dateOfIssue,
command.PlaceOfIssue, command.NationalCode, command.IdNumber, command.Gender, command.Nationality,
@@ -898,14 +955,17 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
}
public EditEmployee GetDetailsForClient(long id, long workshopId)
{
var employee = _EmployeeRepository.GetDetails(id);
employee.PersonelCode = _context.PersonnelCodeSet.FirstOrDefault(p => p.EmployeeId == id && p.WorkshopId == workshopId)?.PersonnelCode;
employee.PersonelCode = _context.PersonnelCodeSet
.FirstOrDefault(p => p.EmployeeId == id && p.WorkshopId == workshopId)?.PersonnelCode;
return employee;
}
#region NewByHeydari
public List<EmployeeViewModel> SearchForMain(EmployeeSearchModel searchModel)
{
var res = _EmployeeRepository.SearchForMain(searchModel);
@@ -917,6 +977,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return res;
}
#endregion
@@ -926,7 +987,9 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
if (nationalCode.NationalCodeValid() != "valid")
return new();
var workshopEmployeesWithLeftWork = _EmployeeRepository.GetWorkingEmployeesByWorkshopIdsAndNationalCodeAndDate(workshopIds, nationalCode, DateTime.Now.Date);
var workshopEmployeesWithLeftWork =
_EmployeeRepository.GetWorkingEmployeesByWorkshopIdsAndNationalCodeAndDate(workshopIds, nationalCode,
DateTime.Now.Date);
return workshopEmployeesWithLeftWork.FirstOrDefault();
}
@@ -934,9 +997,12 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
if (nationalCode.NationalCodeValid() != "valid")
return new();
var workshopEmployeesWithLeftWork = _EmployeeRepository.GetWorkedEmployeesByWorkshopIdsAndNationalCodeAndDate(workshopIds, nationalCode, DateTime.Now.Date);
var workshopEmployeesWithLeftWork =
_EmployeeRepository.GetWorkedEmployeesByWorkshopIdsAndNationalCodeAndDate(workshopIds, nationalCode,
DateTime.Now.Date);
return workshopEmployeesWithLeftWork.FirstOrDefault();
}
public List<EmployeeViewModel> GetWorkingEmployeesByWorkshopId(long workshopId)
{
return _EmployeeRepository.GetWorkingEmployeesByWorkshopId(workshopId);
@@ -980,6 +1046,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
#endregion
#region Mahan
public OperationResult CreateEmployeeByClient(CreateEmployeeByClient command)
{
OperationResult op = new();
@@ -1028,20 +1095,23 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
_EmployeeRepository.SaveChanges();
}
if (employee == null)
{
return op.Failed("خطای سیستمی. لطفا دوباره تلاش کنید . درصورت تکرار این مشکل با تیم پشتیبان تماس بگیرید");
}
if (_leftWorkTempRepository.Exists(x =>
x.EmployeeId == employee.id && x.WorkshopId == command.WorkshopId && x.LeftWorkType == LeftWorkTempType.StartWork))
x.EmployeeId == employee.id && x.WorkshopId == command.WorkshopId &&
x.LeftWorkType == LeftWorkTempType.StartWork))
{
return op.Failed("این پرسنل در کارگاه شما قبلا افزوده شده است و در انتظار تایید میباشد");
}
var startLeftWork = command.StartLeftWork.ToGeorgianDateTime();
var leftWorkViewModel = _leftWorkRepository.GetLastLeftWorkByEmployeeIdAndWorkshopId(command.WorkshopId, employee.id);
var leftWorkViewModel =
_leftWorkRepository.GetLastLeftWorkByEmployeeIdAndWorkshopId(command.WorkshopId, employee.id);
PersonnelCodeDomain personnelCode = null;
@@ -1125,8 +1195,10 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
rollCallEmployee.HasImage();
_rollCallEmployeeRepository.Create(rollCallEmployee);
_rollCallEmployeeRepository.SaveChanges();
string employeeFullName = employee.FName + " " + employee.LName;
var res = _faceEmbeddingService.GenerateEmbeddingsAsync(employee.id,command.WorkshopId,employeeFullName, filePath1,filePath2).GetAwaiter().GetResult();
string employeeFullName = employee.FName + " " + employee.LName;
var res = _faceEmbeddingService
.GenerateEmbeddingsAsync(employee.id, command.WorkshopId, employeeFullName, filePath1, filePath2)
.GetAwaiter().GetResult();
if (!res.IsSuccedded)
{
return op.Failed(res.Message);
@@ -1212,7 +1284,8 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
command.EmployeeDocumentItems = command.EmployeeDocumentItems ?? [];
var employeeDocumentResult = _employeeDocumentsApplication.AddRangeEmployeeDocumentItemsByClient(command.WorkshopId,
var employeeDocumentResult = _employeeDocumentsApplication.AddRangeEmployeeDocumentItemsByClient(
command.WorkshopId,
employee.id, command.EmployeeDocumentItems);
if (employeeDocumentResult.IsSuccedded == false)
@@ -1262,8 +1335,9 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
byte[] bytes = Convert.FromBase64String(subBase64);
System.IO.File.WriteAllBytes(filePath, bytes);
}
public async Task<OperationResult<EmployeeByNationalCodeInWorkshopViewModel>>
ValidateCreateEmployeeClientByNationalCodeAndWorkshopId(string nationalCode, string birthDate,bool authorizedCanceled, long workshopId)
ValidateCreateEmployeeClientByNationalCodeAndWorkshopId(string nationalCode, string birthDate, long workshopId)
{
var op = new OperationResult<EmployeeByNationalCodeInWorkshopViewModel>();
@@ -1279,25 +1353,71 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
var employee = _EmployeeRepository.GetByNationalCodeIgnoreQueryFilter(nationalCode);
if (employee == null && !authorizedCanceled)
if (employee == null)
{
var personalInfo = await _uidService.GetPersonalInfo(nationalCode, birthDate);
if (personalInfo != null)
if (personalInfo.ResponseContext.Status.Code == 14)
{
if (personalInfo.ResponseContext.Status.Code == 14)
{
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید", new EmployeeByNationalCodeInWorkshopViewModel() { AuthorizedCanceled = true });
}
if (personalInfo.ResponseContext.Status.Code != 0)
{
return op.Failed("کد ملی و تاریخ تولد با هم همخانی ندارند");
}
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید",
new EmployeeByNationalCodeInWorkshopViewModel() { AuthorizedCanceled = true });
}
var basicInfo = personalInfo.BasicInformation;
var identityInfo = personalInfo.IdentificationInformation;
DateTime apiBirthDate = identityInfo.BirthDate.ToGeorgianDateTime();
if (personalInfo.ResponseContext.Status.Code != 0)
{
return op.Failed("کد ملی و تاریخ تولد با هم همخانی ندارند");
}
var dateOfIssue = new DateTime(1922, 1, 1);
var basicInfo = personalInfo.BasicInformation;
var identityInfo = personalInfo.IdentificationInformation;
DateTime apiBirthDate = identityInfo.BirthDate.ToGeorgianDateTime();
var dateOfIssue = new DateTime(1922, 1, 1);
var gender = basicInfo.GenderEnum switch
{
Gender.Female => "زن",
Gender.Male => "مرد",
_ => throw new AggregateException()
};
var idNumber = identityInfo.ShenasnamehNumber == "0"
? identityInfo.NationalId
: identityInfo.ShenasnamehNumber;
var newEmployee = new Employee(basicInfo.FirstName, basicInfo.LastName, basicInfo.FatherName, apiBirthDate,
dateOfIssue, null, identityInfo.NationalId, idNumber, gender, "ایرانی", identityInfo.ShenasnameSerial,
identityInfo.ShenasnameSeri);
newEmployee.Authorized();
await _EmployeeRepository.CreateAsync(newEmployee);
await _EmployeeRepository.SaveChangesAsync();
return op.Succcedded(new EmployeeByNationalCodeInWorkshopViewModel()
{
EmployeeId = newEmployee.id,
EmployeeFName = newEmployee.FName,
Gender = newEmployee.Gender,
Nationality = newEmployee.Nationality,
EmployeeLName = newEmployee.LName
});
}
if (_leftWorkTempRepository.ExistsIgnoreQueryFilter(x =>
x.EmployeeId == employee.id && x.WorkshopId == workshopId &&
x.LeftWorkType == LeftWorkTempType.StartWork))
{
return op.Failed("این پرسنل در کارگاه شما قبلا افزوده شده است و در انتظار تایید میباشد");
}
if (employee.IsAuthorized == false)
{
var personalInfoResponse = await _uidService.GetPersonalInfo(nationalCode, birthDate);
if (personalInfoResponse.ResponseContext.Status.Code == 0)
{
var basicInfo = personalInfoResponse.BasicInformation;
var identityInfo = personalInfoResponse.IdentificationInformation;
var apiBirthDate = identityInfo.BirthDate.ToGeorgianDateTime();
var gender = basicInfo.GenderEnum switch
{
@@ -1306,92 +1426,36 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
_ => throw new AggregateException()
};
var idNumber = identityInfo.ShenasnamehNumber == "0" ? identityInfo.NationalId : identityInfo.ShenasnamehNumber;
var idNumber = identityInfo.ShenasnamehNumber == "0"
? identityInfo.NationalId
: identityInfo.ShenasnamehNumber;
employee.Edit(basicInfo.FirstName, basicInfo.LastName, basicInfo.FatherName, apiBirthDate,
employee.DateOfIssue, employee.PlaceOfIssue, identityInfo.NationalId, idNumber,
gender, "ایرانی", employee.Phone, employee.Address, employee.State, employee.City,
employee.MaritalStatus, employee.MilitaryService, employee.LevelOfEducation,
employee.FieldOfStudy, employee.BankCardNumber, employee.BankBranch, employee.InsuranceCode,
employee.InsuranceHistoryByYear,
employee.InsuranceHistoryByMonth, employee.NumberOfChildren,
employee.OfficePhone, employee.MclsUserName, employee.MclsPassword,
employee.EserviceUserName, employee.EservicePassword, employee.TaxOfficeUserName,
employee.TaxOfficepassword, employee.SanaUserName, employee.SanaPassword);
employee.Authorized();
var newEmployee = new Employee(basicInfo.FirstName, basicInfo.LastName, basicInfo.FatherName, apiBirthDate,
dateOfIssue, null, identityInfo.NationalId, idNumber, gender, "ایرانی", identityInfo.ShenasnameSerial, identityInfo.ShenasnameSeri);
newEmployee.Authorized();
await _EmployeeRepository.CreateAsync(newEmployee);
await _EmployeeRepository.SaveChangesAsync();
return op.Succcedded(new EmployeeByNationalCodeInWorkshopViewModel()
{
EmployeeId = newEmployee.id,
EmployeeFName = newEmployee.FName,
Gender = newEmployee.Gender,
Nationality = newEmployee.Nationality,
EmployeeLName = newEmployee.LName
});
}
else
{
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید", new EmployeeByNationalCodeInWorkshopViewModel() { AuthorizedCanceled = true });
}
}
else if (employee == null && authorizedCanceled)
{
return op.Succcedded(new EmployeeByNationalCodeInWorkshopViewModel());
}
if (_leftWorkTempRepository.ExistsIgnoreQueryFilter(x =>
x.EmployeeId == employee.id && x.WorkshopId == workshopId && x.LeftWorkType == LeftWorkTempType.StartWork))
{
return op.Failed("این پرسنل در کارگاه شما قبلا افزوده شده است و در انتظار تایید میباشد");
}
var personalInfoResponse = await _uidService.GetPersonalInfo(nationalCode, birthDate);
if (personalInfoResponse != null)
{
if (employee.IsAuthorized == false)
{
if (personalInfoResponse.ResponseContext.Status.Code == 0)
{
var basicInfo = personalInfoResponse.BasicInformation;
var identityInfo = personalInfoResponse.IdentificationInformation;
var apiBirthDate = identityInfo.BirthDate.ToGeorgianDateTime();
var gender = basicInfo.GenderEnum switch
{
Gender.Female => "زن",
Gender.Male => "مرد",
_ => throw new AggregateException()
};
var idNumber = identityInfo.ShenasnamehNumber == "0" ? identityInfo.NationalId : identityInfo.ShenasnamehNumber;
employee.Edit(basicInfo.FirstName, basicInfo.LastName, basicInfo.FatherName, apiBirthDate,
employee.DateOfIssue, employee.PlaceOfIssue, identityInfo.NationalId, idNumber,
gender, "ایرانی", employee.Phone, employee.Address, employee.State, employee.City,
employee.MaritalStatus, employee.MilitaryService, employee.LevelOfEducation,
employee.FieldOfStudy, employee.BankCardNumber, employee.BankBranch, employee.InsuranceCode, employee.InsuranceHistoryByYear,
employee.InsuranceHistoryByMonth, employee.NumberOfChildren,
employee.OfficePhone, employee.MclsUserName, employee.MclsPassword,
employee.EserviceUserName, employee.EservicePassword, employee.TaxOfficeUserName,
employee.TaxOfficepassword, employee.SanaUserName, employee.SanaPassword);
employee.Authorized();
await _EmployeeRepository.SaveChangesAsync();
}
else
{
return op.Failed("کد ملی با تاریخ تولد وارد شده مطابقت ندارد");
}
}
else if (employee.DateOfBirth.ToFarsi() != birthDate || employee.NationalCode != nationalCode)
{
return op.Failed("کد ملی با تاریخ تولد وارد شده مطابقت ندارد");
}
}
else if (employee.DateOfBirth.ToFarsi() != birthDate || employee.NationalCode != nationalCode)
{
return op.Failed("کد ملی با تاریخ تولد وارد شده مطابقت ندارد");
}
var leftWorkViewModel = _leftWorkRepository.GetLastLeftWorkByEmployeeIdAndWorkshopId(workshopId, employee.id);
if (leftWorkViewModel == null)
@@ -1403,7 +1467,8 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
Gender = employee.Gender,
Nationality = employee.Nationality,
EmployeeLName = employee.LName
}); ;
});
;
}
if (leftWorkViewModel.LeftWorkDate >= DateTime.Now || !leftWorkViewModel.HasLeft)
@@ -1455,17 +1520,18 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
Picture1 = picture1,
Picture2 = picture2,
PersonnelCode = personnelCode,
EmployeeBankInfos = bankInformationViewModel.BankInformation.Select(x => new EmployeeByNationalCodeEmployeeBankInfoViewModel
{
ShebaNumber = x.ShebaNumber,
IsDefault = x.IsDefault,
CardNumber = x.CardNumber,
BankAccountNumber = x.BankAccountNumber,
BankId = x.BankId,
BankLogoMediaId = x.BankLogoMediaId,
BankLogoPath = x.BankLogoPath,
BankName = x.BankName
}).ToList(),
EmployeeBankInfos = bankInformationViewModel.BankInformation.Select(x =>
new EmployeeByNationalCodeEmployeeBankInfoViewModel
{
ShebaNumber = x.ShebaNumber,
IsDefault = x.IsDefault,
CardNumber = x.CardNumber,
BankAccountNumber = x.BankAccountNumber,
BankId = x.BankId,
BankLogoMediaId = x.BankLogoMediaId,
BankLogoPath = x.BankLogoPath,
BankName = x.BankName
}).ToList(),
EmployeeDocument = new EmployeeByNationalCodeEmployeeDocumentViewModel
{
EducationalDegree = employeeDocumentsViewModel.EducationalDegree,
@@ -1519,6 +1585,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
return op.Failed("جنسیت وارد شده نامعتبر است");
}
if (command.BirthDate.TryToGeorgianDateTime(out var birthDateGr) == false)
{
return op.Failed("تاریخ تولد وارد شده نامعتبر است");
@@ -1555,7 +1622,8 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
}
}
var employeeClientTemp = _employeeClientTempRepository.GetByEmployeeIdAndWorkshopId(command.EmployeeId, command.WorkshopId);
var employeeClientTemp =
_employeeClientTempRepository.GetByEmployeeIdAndWorkshopId(command.EmployeeId, command.WorkshopId);
employeeClientTemp?.Edit(command.MaritalStatus);
@@ -1582,6 +1650,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
employee.EserviceUserName, employee.EservicePassword, employee.TaxOfficeUserName,
employee.TaxOfficepassword, employee.SanaUserName, employee.SanaPassword);
}
await _EmployeeRepository.SaveChangesAsync();
return op.Succcedded();
@@ -1592,7 +1661,8 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return await _EmployeeRepository.WorkedEmployeesInWorkshopSelectList(workshopId);
}
public async Task<OperationResult<EmployeeDataFromApiViewModel>> GetEmployeeDataFromApi(string nationalCode, string birthDate)
public async Task<OperationResult<EmployeeDataFromApiViewModel>> GetEmployeeDataFromApi(string nationalCode,
string birthDate)
{
var op = new OperationResult<EmployeeDataFromApiViewModel>();
var birthDateGr = birthDate.ToGeorgianDateTime();
@@ -1604,20 +1674,23 @@ 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)
{
return op.Failed("این پرسنل در بانک اطلاعات موجود میباشد");
}
if (apiResult.ResponseContext.Status.Code != 0)
{
return op.Failed("کد ملی و تاریخ تولد با هم همخانی ندارند");
}
var basicInfo = apiResult.BasicInformation;
var identityInfo = apiResult.IdentificationInformation;
@@ -1628,12 +1701,15 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
_ => throw new AggregateException()
};
var idNumber = identityInfo.ShenasnamehNumber == "0" ? identityInfo.NationalId : identityInfo.ShenasnamehNumber;
var idNumber = identityInfo.ShenasnamehNumber == "0"
? identityInfo.NationalId
: identityInfo.ShenasnamehNumber;
employee.Edit(basicInfo.FirstName, basicInfo.LastName, basicInfo.FatherName, birthDateGr,
employee.DateOfIssue, employee.PlaceOfIssue, identityInfo.NationalId, idNumber,
gender, "ایرانی", employee.Phone, employee.Address, employee.State, employee.City,
employee.MaritalStatus, employee.MilitaryService, employee.LevelOfEducation,
employee.FieldOfStudy, employee.BankCardNumber, employee.BankBranch, employee.InsuranceCode, employee.InsuranceHistoryByYear,
employee.FieldOfStudy, employee.BankCardNumber, employee.BankBranch, employee.InsuranceCode,
employee.InsuranceHistoryByYear,
employee.InsuranceHistoryByMonth, employee.NumberOfChildren,
employee.OfficePhone, employee.MclsUserName, employee.MclsPassword,
employee.EserviceUserName, employee.EservicePassword, employee.TaxOfficeUserName,
@@ -1668,15 +1744,18 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
};
return op.Succcedded(data);
}
var apiResult = await _uidService.GetPersonalInfo(nationalCode, birthDate);
if (apiResult == null)
{
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید", new EmployeeDataFromApiViewModel() { AuthorizedCanceled = true });
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید",
new EmployeeDataFromApiViewModel() { AuthorizedCanceled = true });
}
if (apiResult.ResponseContext.Status.Code is 14 or 3)
{
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید", new EmployeeDataFromApiViewModel() { AuthorizedCanceled = true });
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید",
new EmployeeDataFromApiViewModel() { AuthorizedCanceled = true });
}
@@ -1684,10 +1763,12 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
return op.Failed("کد ملی و تاریخ تولد با هم همخانی ندارند");
}
if (apiResult.ResponseContext.Status.Code != 0)
{
return op.Failed("اطلاعات وارد شده نامعتبر میباشد");
}
var basicInfo = apiResult.BasicInformation;
var identityInfo = apiResult.IdentificationInformation;
@@ -1695,7 +1776,9 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
{
BirthDate = identityInfo.BirthDate,
NationalCode = identityInfo.NationalId,
IdNumber = identityInfo.ShenasnamehNumber == "0" ? identityInfo.NationalId : identityInfo.ShenasnamehNumber,
IdNumber = identityInfo.ShenasnamehNumber == "0"
? identityInfo.NationalId
: identityInfo.ShenasnamehNumber,
FatherName = basicInfo.FatherName,
FName = basicInfo.FirstName,
Gender = basicInfo.GenderEnum,
@@ -1704,7 +1787,8 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
IdNumberSerial = identityInfo.ShenasnameSerial
};
var newAuthorizeTemp = new EmployeeAuthorizeTemp(data.Gender, data.FName, data.LName, data.FatherName, birthDateGr, data.NationalCode, data.IdNumber, data.IdNumberSerial, data.IdNumberSeri);
var newAuthorizeTemp = new EmployeeAuthorizeTemp(data.Gender, data.FName, data.LName, data.FatherName,
birthDateGr, data.NationalCode, data.IdNumber, data.IdNumberSerial, data.IdNumberSeri);
await _employeeAuthorizeTempRepository.CreateAsync(newAuthorizeTemp);
await _employeeAuthorizeTempRepository.SaveChangesAsync();
@@ -1719,9 +1803,9 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
#region Api
public async Task<List<EmployeeSelectListViewModel>> GetSelectList(string searchText,long id)
public async Task<List<EmployeeSelectListViewModel>> GetSelectList(string searchText, long id)
{
return await _EmployeeRepository.GetSelectList(searchText,id );
return await _EmployeeRepository.GetSelectList(searchText, id);
}
public async Task<List<GetEmployeeListViewModel>> GetList(GetEmployeeListSearchModel searchModel)
@@ -1729,5 +1813,10 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return await _EmployeeRepository.GetList(searchModel);
}
#endregion
public Task<List<GetEmployeeClientListViewModel>> GetEmployeeClientList(GetEmployeeClientListSearchModel searchModel,long workshopId)
{
return _EmployeeRepository.GetEmployeeClientList(searchModel, workshopId);
}
#endregion
}

View File

@@ -1537,7 +1537,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
return (await _institutionContractRepository.PrintAllAsync([id])).FirstOrDefault();
}
public async Task<OperationResult> SetPendingWorkflow(long entityId,InstitutionContractSigningType signingType)
public async Task<OperationResult> SetPendingWorkflow(long entityId)
{
var op = new OperationResult();
var institutionContract = await _institutionContractRepository.GetIncludeWorkshopDetailsAsync(entityId);
@@ -1551,30 +1551,6 @@ public class InstitutionContractApplication : IInstitutionContractApplication
return op.Failed("وضعیت قرارداد مالی برای این عملیات مناسب نمی باشد");
}
var initialCreatedWorkshops = institutionContract.WorkshopGroup.InitialWorkshops
.Where(x => x.WorkshopCreated && x.WorkshopId is > 0).ToList();
var currentWorkshops = institutionContract.WorkshopGroup.CurrentWorkshops.ToList();
foreach (var createdWorkshop in initialCreatedWorkshops)
{
if (currentWorkshops.Any(x => x.WorkshopId == createdWorkshop.WorkshopId))
{
continue;
}
var currentWorkshop = new InstitutionContractWorkshopCurrent(createdWorkshop.WorkshopName,
createdWorkshop.Services.RollCall, createdWorkshop.Services.RollCallInPerson,
createdWorkshop.Services.CustomizeCheckout, createdWorkshop.Services.Contract,
createdWorkshop.Services.ContractInPerson, createdWorkshop.Services.Insurance,
createdWorkshop.Services.InsuranceInPerson,createdWorkshop.PersonnelCount, createdWorkshop.Price,
createdWorkshop.InstitutionContractWorkshopGroupId,createdWorkshop.WorkshopGroup,
createdWorkshop.WorkshopId!.Value, createdWorkshop.id);
institutionContract.WorkshopGroup.AddCurrentWorkshop(currentWorkshop);
}
if (institutionContract.WorkshopGroup.InitialWorkshops.All(x => x.WorkshopCreated && x.WorkshopId is > 0))
{
institutionContract.Verified();
@@ -1583,9 +1559,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
{
institutionContract.SetPendingWorkflow();
}
institutionContract.SetSigningType(signingType);
await _institutionContractRepository.SaveChangesAsync();
return op.Succcedded();
}
@@ -1595,42 +1569,6 @@ public class InstitutionContractApplication : IInstitutionContractApplication
return await _institutionContractRepository.GetIdByInstallmentId(installmentId);
}
public async Task<OperationResult> VerifyInstitutionContractManually(long institutionContractId)
{
var op = new OperationResult();
var institutionContract =await _institutionContractRepository
.GetIncludeWorkshopDetailsAsync(institutionContractId);
if (institutionContract == null)
return op.Failed("قرارداد مالی یافت نشد");
if (institutionContract.VerificationStatus == InstitutionContractVerificationStatus.Verified)
return op.Failed("قرارداد مالی قبلا تایید شده است");
var transaction = await _institutionContractRepository.BeginTransactionAsync();
await SetPendingWorkflow(institutionContractId,InstitutionContractSigningType.Physical);
var financialStatement = await _financialStatmentRepository
.GetByContractingPartyId(institutionContract.ContractingPartyId);
DateTime today = DateTime.Today;
var description = institutionContract.IsInstallment
? "قسط اول سرویس"
: "پرداخت کل سرویس";
var debtorAmount = institutionContract.IsInstallment
? institutionContract.Installments.First().Amount
: institutionContract.TotalAmount;
var financialTransaction = new FinancialTransaction(0, today, today.ToFarsi(),
description, "debt", "بابت خدمات", debtorAmount, 0, 0);
financialStatement.AddFinancialTransaction(financialTransaction);
await _institutionContractRepository.SaveChangesAsync();
await transaction.CommitAsync();
return op.Succcedded();
}
private async Task<OperationResult<PersonalContractingParty>> CreateLegalContractingPartyEntity(
CreateInstitutionContractLegalPartyRequest request, long representativeId, string address, string city,
string state)

View File

@@ -2371,11 +2371,6 @@ public class InsuranceListApplication : IInsuranceListApplication
return _insuranceListRepositpry.GetTabCounts(searchModel);
}
public async Task<PagedResult<InsuranceClientListViewModel>> GetInsuranceClientList(InsuranceClientSearchModel searchModel)
{
return await _insuranceListRepositpry.GetInsuranceClientList(searchModel);
}
public async Task<List<InsuranceListViewModel>> GetNotCreatedWorkshop(InsuranceListSearchModel searchModel)
{
return await _insuranceListRepositpry.GetNotCreatedWorkshop(searchModel);

View File

@@ -384,7 +384,6 @@ public class RollCallApplication : IRollCallApplication
var workshopSettings = _customizeWorkshopSettingsRepository.GetBy(command.WorkshopId);
var employeeSettings =
_customizeWorkshopEmployeeSettingsRepository.GetByEmployeeIdAndWorkshopIdIncludeGroupSettings(
command.WorkshopId, command.EmployeeId)?.WorkshopShiftStatus;

View File

@@ -11,7 +11,6 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Transactions;
using _0_Framework.Application.FaceEmbedding;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
namespace CompanyManagment.Application;
@@ -24,9 +23,7 @@ public class RollCallEmployeeApplication : IRollCallEmployeeApplication
private readonly ILeftWorkRepository _leftWorkRepository;
private readonly IRollCallEmployeeStatusRepository _rollCallEmployeeStatusRepository;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly IFaceEmbeddingService _faceEmbeddingService;
public RollCallEmployeeApplication(IRollCallEmployeeRepository rollCallEmployeeRepository, IEmployeeRepository employeeRepository, IRollCallEmployeeStatusApplication rollCallEmployeeStatusApplication, ILeftWorkRepository leftWorkRepository, IRollCallEmployeeStatusRepository rollCallEmployeeStatusRepository, IWebHostEnvironment webHostEnvironment, IFaceEmbeddingService faceEmbeddingService)
public RollCallEmployeeApplication(IRollCallEmployeeRepository rollCallEmployeeRepository, IEmployeeRepository employeeRepository, IRollCallEmployeeStatusApplication rollCallEmployeeStatusApplication, ILeftWorkRepository leftWorkRepository, IRollCallEmployeeStatusRepository rollCallEmployeeStatusRepository, IWebHostEnvironment webHostEnvironment)
{
_rollCallEmployeeRepository = rollCallEmployeeRepository;
_employeeRepository = employeeRepository;
@@ -34,7 +31,6 @@ public class RollCallEmployeeApplication : IRollCallEmployeeApplication
_leftWorkRepository = leftWorkRepository;
_rollCallEmployeeStatusRepository = rollCallEmployeeStatusRepository;
_webHostEnvironment = webHostEnvironment;
_faceEmbeddingService = faceEmbeddingService;
}
public OperationResult Create(CreateRollCallEmployee command)
@@ -217,18 +213,9 @@ public class RollCallEmployeeApplication : IRollCallEmployeeApplication
if (entity.IsActiveString != "true")
return result.Failed("امکان تغییر نام برای کارمند غیر فعال وجود ندارد");
var transaction = _rollCallEmployeeRepository.BeginTransactionAsync().GetAwaiter().GetResult();
entity.ChangeName(fName, lName);
_rollCallEmployeeRepository.SaveChanges();
var embeddingRes =_faceEmbeddingService
.UpdateEmbeddingFullNameAsync(entity.EmployeeId, entity.WorkshopId, fullName)
.GetAwaiter().GetResult();
if (!embeddingRes.IsSuccedded)
return result.Failed("خطا در به روز رسانی نام در سیستم تشخیص چهره: " + embeddingRes.Message);
transaction.Commit();
return result.Succcedded();
}
#endregion

View File

@@ -34,10 +34,6 @@ public class InstitutionContractMapping : IEntityTypeConfiguration<InstitutionCo
builder.Property(x => x.VerifierPhoneNumber).HasMaxLength(20);
builder.Property(x => x.VerificationStatus).HasConversion<string>().HasMaxLength(122);
builder.Property(x=>x.SigningType).HasConversion<string>()
.HasMaxLength(25)
.IsRequired(false);
builder.HasMany(x => x.Installments)
.WithOne(x => x.InstitutionContract)
@@ -49,8 +45,5 @@ public class InstitutionContractMapping : IEntityTypeConfiguration<InstitutionCo
builder.HasMany(x => x.Amendments).WithOne(x => x.InstitutionContract)
.HasForeignKey(x => x.InstitutionContractId);
builder.Ignore(x => x.ContractAmountWithTax);
}
}

View File

@@ -1,29 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CompanyManagment.EFCore.Migrations
{
/// <inheritdoc />
public partial class addsigningTypeforinstitutioncontract : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "SigningType",
table: "InstitutionContracts",
type: "nvarchar(25)",
maxLength: 25,
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "SigningType",
table: "InstitutionContracts");
}
}
}

View File

@@ -3462,10 +3462,6 @@ namespace CompanyManagment.EFCore.Migrations
.HasMaxLength(1)
.HasColumnType("nvarchar(1)");
b.Property<string>("SigningType")
.HasMaxLength(25)
.HasColumnType("nvarchar(25)");
b.Property<string>("State")
.HasMaxLength(20)
.HasColumnType("nvarchar(20)");

View File

@@ -64,7 +64,7 @@ public class CheckoutRepository : RepositoryBase<long, Checkout>, ICheckoutRepos
}
/// <summary>
/// چک میکند که آیا پرسنل در سال و ماه درخواستی در این کارگاه فیش حقوقی دارد یا خیر
/// چیک میکند که آیا پرسنل در سال و ماه درخواستی در این کارگاه فیش حقوقی دارد یا خیر
/// </summary>
/// <param name="workshopId"></param>
/// <param name="employeId"></param>
@@ -74,21 +74,12 @@ public class CheckoutRepository : RepositoryBase<long, Checkout>, ICheckoutRepos
public (bool hasChekout, double FamilyAlloance, double OverTimePay, double RotatingShift, double Nightwork, double Fridaywork, double YraesPay) HasCheckout(long workshopId, long employeId, string year, string month)
{
var farisMonthName = Tools.ToFarsiMonthByNumber(month);
var res = _context.CheckoutSet.FirstOrDefault(x =>
x.WorkshopId == workshopId && x.EmployeeId == employeId && x.Year == year && x.Month == farisMonthName &&
x.IsActiveString == "true");
if (res == null)
{
var checkLeftDate = ($"{year}/{month}/01").ToGeorgianDateTime();
var hasLeftwork = _context.LeftWorkList.Any(x =>
x.EmployeeId == employeId && x.WorkshopId == workshopId && x.LeftWorkDate == checkLeftDate);
if(hasLeftwork)
return (true, 0, 0, 0, 0, 0, 0);
return (false, 0, 0, 0, 0, 0, 0);
}
return (false, 0, 0,0,0,0,0);
return (true, res.FamilyAllowance, res.OvertimePay, res.ShiftPay, res.NightworkPay, res.FridayPay,res.YearsPay);
}

View File

@@ -1194,99 +1194,41 @@ public class EmployeeDocumentsRepository : RepositoryBase<long, EmployeeDocument
{
return new List<WorkshopWithEmployeeDocumentsViewModel>();
}
// Step 1: Get employee client temps in memory
var employeeClientTempData = await _companyContext.EmployeeClientTemps
.Where(x => workshops.Contains(x.WorkshopId))
.Select(x => new { x.WorkshopId, x.EmployeeId })
.ToListAsync();
// Step 2: Get employee documents with simplified filter
var employeeDocuments = await _companyContext.EmployeeDocuments
.Where(x => workshops.Contains(x.WorkshopId) && !x.IsConfirmed && !x.IsSentToChecker)
.Select(x => new
{
x.id,
x.WorkshopId,
x.EmployeeId,
x.IsConfirmed,
x.IsSentToChecker,
WorkshopName = x.Workshop.WorkshopName
})
.ToListAsync();
var filteredDocuments = employeeDocuments
.Where(x => employeeClientTempData.Any(temp =>
temp.WorkshopId == x.WorkshopId && temp.EmployeeId == x.EmployeeId))
.ToList();
var groupedByWorkshop = filteredDocuments
.GroupBy(x => x.WorkshopId)
.Select(g => new
{
WorkshopId = g.Key,
WorkshopName = g.First().WorkshopName,
Count = g.Count()
})
.ToList();
var employeeClientTemp = _companyContext.EmployeeClientTemps.Where(x => workshops.Contains(x.WorkshopId));
// Step 5: Get workshop employers for the filtered workshops
var workshopIds = groupedByWorkshop.Select(x => x.WorkshopId).ToList();
var workshopEmployers = await _companyContext.WorkshopEmployers
.Where(x => workshopIds.Contains(x.WorkshopId))
.Include(x => x.Employer)
.GroupBy(x => x.WorkshopId)
.Select(g => g.FirstOrDefault())
.ToListAsync();
// Step 6: Build result
var res = groupedByWorkshop
.Select(x => new WorkshopWithEmployeeDocumentsViewModel()
{
WorkshopId = x.WorkshopId,
WorkshopFullName = x.WorkshopName,
EmployeesWithoutDocumentCount = x.Count,
EmployerName = workshopEmployers
.FirstOrDefault(y => y.WorkshopId == x.WorkshopId)?
.Employer?.FullName
})
.Where(x => x.EmployeesWithoutDocumentCount > 0)
.OrderByDescending(x => x.EmployeesWithoutDocumentCount)
.ToList();
return res;
//var employeeClientTemp = _companyContext.EmployeeClientTemps.Where(x => workshops.Contains(x.WorkshopId));
// var query = _companyContext.EmployeeDocuments
// .Where(x => workshops.Contains(x.WorkshopId) &&
// employeeClientTemp.Any(temp => x.EmployeeId == temp.EmployeeId && temp.WorkshopId == x.WorkshopId) && x.IsConfirmed == false &&x.IsSentToChecker == false)
// .Include(x => x.Workshop).Include(x => x.EmployeeDocumentItemCollection)
// .GroupBy(x => x.WorkshopId).Select(x => new WorkshopWithEmployeeDocumentsViewModel()
// {
// WorkshopId = x.Key,
// WorkshopFullName = x.FirstOrDefault().Workshop.WorkshopFullName,
// EmployeesWithoutDocumentCount = x.Count()
// });
var query = _companyContext.EmployeeDocuments
.Where(x => workshops.Contains(x.WorkshopId) &&
employeeClientTemp.Any(temp => x.EmployeeId == temp.EmployeeId && temp.WorkshopId == x.WorkshopId) && x.IsConfirmed == false &&x.IsSentToChecker == false)
.Include(x => x.Workshop).Include(x => x.EmployeeDocumentItemCollection)
.GroupBy(x => x.WorkshopId).Select(x => new WorkshopWithEmployeeDocumentsViewModel()
{
WorkshopId = x.Key,
WorkshopFullName = x.FirstOrDefault().Workshop.WorkshopFullName,
EmployeesWithoutDocumentCount = x.Count()
});
// var workshopEmployers = await _companyContext.WorkshopEmployers.Include(x => x.Employer)
// .Where(x => query.Any(y => y.WorkshopId == x.WorkshopId))
// .GroupBy(x => x.WorkshopId).Select(x => x.FirstOrDefault()).ToListAsync();
var workshopEmployers = await _companyContext.WorkshopEmployers.Include(x => x.Employer)
.Where(x => query.Any(y => y.WorkshopId == x.WorkshopId))
.GroupBy(x => x.WorkshopId).Select(x => x.FirstOrDefault()).ToListAsync();
// var result = await query.ToListAsync();
var result = await query.ToListAsync();
// result.ForEach(x =>
// {
// var employer = workshopEmployers.FirstOrDefault(y => y.WorkshopId == x.WorkshopId)?.Employer;
// x.EmployerName = employer?.FullName;
result.ForEach(x =>
{
var employer = workshopEmployers.FirstOrDefault(y => y.WorkshopId == x.WorkshopId)?.Employer;
x.EmployerName = employer?.FullName;
// //x.SubmittedItems.ForEach(y=>y.PicturePath= medias.FirstOrDefault(z=>z.id == y.MediaId)?.Path ?? "");
// });
//x.SubmittedItems.ForEach(y=>y.PicturePath= medias.FirstOrDefault(z=>z.id == y.MediaId)?.Path ?? "");
});
// return result.Where(x => x.EmployeesWithoutDocumentCount > 0).OrderByDescending(x => x.EmployeesWithoutDocumentCount).ToList();
return result.Where(x => x.EmployeesWithoutDocumentCount > 0).OrderByDescending(x => x.EmployeesWithoutDocumentCount).ToList();
}
public async Task<List<EmployeeDocumentsViewModel>> GetCreatedEmployeesDocumentByWorkshopIdForAdmin(long workshopId)
@@ -1405,37 +1347,33 @@ public class EmployeeDocumentsRepository : RepositoryBase<long, EmployeeDocument
// ترکیب کل لیست‌ها در حافظه
var allActiveEmployees = activeEmployees
.Concat(clientTemp)
.Concat(leftWorkTemp).ToList();
.Concat(leftWorkTemp);
var contractingPartyIds = _companyContext.WorkshopEmployers.Where(x => workshops.Contains(x.WorkshopId))
.Include(x => x.Employer).Select(x => x.Employer.ContractingPartyId).Distinct().ToList();
.Include(x => x.Employer).Select(x => x.Employer.ContractingPartyId).Distinct();
var accountIds = await _companyContext.ContractingPartyAccounts
.Where(x => contractingPartyIds.Contains(x.PersonalContractingPartyId)).Select(x => x.AccountId)
.ToListAsync();
var query =await _companyContext.EmployeeDocuments
.Where(x => workshops.Contains(x.WorkshopId))
var query = _companyContext.EmployeeDocuments
.Where(x => workshops.Contains(x.WorkshopId) &&
(allActiveEmployees.Any(y => y.WorkshopId == x.WorkshopId && y.EmployeeId == x.EmployeeId)))
.Include(x => x.Workshop).Include(x => x.EmployeeDocumentItemCollection)
.Where(x => x.IsSentToChecker == false && x.HasRejectedItems && x.EmployeeDocumentItemCollection.Any(i => i.DocumentStatus == DocumentStatus.Rejected && accountIds.Contains(i.UploaderId)))
.GroupBy(x => x.WorkshopId).Select(x => new WorkshopWithEmployeeDocumentsViewModel()
{
WorkshopId = x.Key,
WorkshopFullName = x.FirstOrDefault().Workshop.WorkshopName,
EmployeesWithoutDocumentCount = x.Count(),
EmployeeId = x.First().EmployeeId
}).ToListAsync();
EmployeesWithoutDocumentCount = x.Count()
});
query = query.Where(x =>
(allActiveEmployees.Any(y => y.WorkshopId == x.WorkshopId && y.EmployeeId == x.EmployeeId))).ToList();
var resWorkshopIds = query.Select(x => x.WorkshopId).ToList();
var workshopEmployers = await _companyContext.WorkshopEmployers.Include(x => x.Employer)
.Where(x => resWorkshopIds.Contains(x.WorkshopId))
.Where(x => query.Any(y => y.WorkshopId == x.WorkshopId))
.GroupBy(x => x.WorkshopId).Select(x => x.FirstOrDefault()).ToListAsync();
var result = query;
var result = await query.ToListAsync();
result.ForEach(x =>

View File

@@ -18,6 +18,8 @@ using CompanyManagment.App.Contracts.Employee.DTO;
using CompanyManagment.App.Contracts.LeftWorkTemp;
using _0_Framework.Application.Enums;
using _0_Framework.Exceptions;
using CompanyManagment.App.Contracts.EmployeeChildren;
using CompanyManagment.App.Contracts.Workshop;
namespace CompanyManagment.EFCore.Repository;
@@ -1062,5 +1064,158 @@ public class EmployeeRepository : RepositoryBase<long, Employee>, IEmployeeRepos
}
#endregion
}
public async Task<List<GetEmployeeClientListViewModel>> GetEmployeeClientList(GetEmployeeClientListSearchModel searchModel,long workshopId)
{
var leftDate = Tools.GetUndefinedDateTime();
var personnelCodes =await _context.PersonnelCodeSet.Include(x => x.Employee)
.ThenInclude(x => x.EmployeeChildrenList)
.IgnoreQueryFilters()
.Where(x => x.WorkshopId == workshopId).ToListAsync();
var contractLeftWork =
await _context.LeftWorkList.Where(x => x.WorkshopId == workshopId)
.Select(x => new PersonnelInfoViewModel()
{
WorkshopId = x.WorkshopId,
EmployeeId = x.EmployeeId,
FullName = x.EmployeeFullName,
PersonnelCode = 0,
ContractPerson = true,
ContractLeft = x.LeftWorkDate != leftDate,
StartWork = x.StartWorkDate,
LeftWork = x.LeftWorkDate,
LastStartContractWork = x.StartWorkDate.ToFarsi(),
LastLeftContractWork = x.LeftWorkDate != leftDate ? x.LeftWorkDate.ToFarsi() : "-",
LastStartInsuranceWork = "-",
LastLeftInsuranceWork = "-",
}).GroupBy(x => x.EmployeeId)
.Select(x => x.OrderByDescending(y => y.LeftWork)
.First()).ToListAsync();
var insuranceLeftWork =await _context.LeftWorkInsuranceList
.Where(x => x.WorkshopId == workshopId)
.Select(x => new PersonnelInfoViewModel()
{
WorkshopId = x.WorkshopId,
EmployeeId = x.EmployeeId,
FullName = x.EmployeeFullName,
PersonnelCode = 0,
InsurancePerson = true,
InsuranceLeft = x.LeftWorkDate != null,
StartWork = x.StartWorkDate,
LeftWork = x.LeftWorkDate ?? leftDate,
LastStartInsuranceWork = x.StartWorkDate.ToFarsi(),
LastLeftInsuranceWork = x.LeftWorkDate != null ? x.LeftWorkDate.ToFarsi() : "-",
LastStartContractWork = "-",
LastLeftContractWork = "-"
}).GroupBy(x => x.EmployeeId)
.Select(x => x.OrderByDescending(y => y.LeftWork)
.First()).ToListAsync();
var leftWorkTemp =await _context.LeftWorkTemps
.Where(x => x.WorkshopId == workshopId)
.Select(x => new PersonnelInfoViewModel()
{
WorkshopId = x.WorkshopId,
EmployeeId = x.EmployeeId,
PersonnelCode = 0,
ContractPerson = true,
ContractLeft = x.LeftWork != leftDate,
StartWork = x.StartWork,
LeftWork = x.LeftWork,
LastStartContractWork = x.StartWork.ToFarsi(),
LastLeftContractWork = x.LeftWork != leftDate ? x.LeftWork.ToFarsi() : "-",
LastStartInsuranceWork = "-",
LastLeftInsuranceWork = "-",
LefWorkTemp = x.LeftWorkType == LeftWorkTempType.LeftWork,
CreatedByClient = x.LeftWorkType == LeftWorkTempType.StartWork
}).ToListAsync();
var employeeClientTemp =await _context.EmployeeClientTemps
.Where(x => x.WorkshopId == workshopId)
.Select(x => new PersonnelInfoViewModel()
{
WorkshopId = x.WorkshopId,
EmployeeId = x.EmployeeId,
PersonnelCode = 0,
CreatedByClient = true,
ContractPerson = true
}).ToListAsync();
var resultTemp = employeeClientTemp.Concat(leftWorkTemp).ToList().GroupBy(x => x.EmployeeId);
var groupRes = contractLeftWork.Concat(insuranceLeftWork).GroupBy(x => x.EmployeeId).ToList();
groupRes = groupRes.Concat(resultTemp).GroupBy(x => x.First().EmployeeId).Select(x => x.First()).ToList();
var employeeClientTempList = employeeClientTemp.ToList();
var startWorkTempsForWorkshop = leftWorkTemp.Where(x => x.CreatedByClient).ToList();
var leftWorkTempsForWorkshop = leftWorkTemp.Where(x => x.LefWorkTemp).ToList();
var res= groupRes.Select(x =>
{
var insurance = x.FirstOrDefault(y => y.InsurancePerson);
var contract = x.FirstOrDefault(y => y.ContractPerson);
var personnelCode = personnelCodes.FirstOrDefault(y => y.EmployeeId == x.Key);
var employee = personnelCode.Employee;
var employeeClient = employeeClientTempList.FirstOrDefault(t => t.EmployeeId == x.First().EmployeeId);
var startWorkTemp = startWorkTempsForWorkshop.FirstOrDefault(s => s.EmployeeId == x.First().EmployeeId);
var leftWorkTemp = leftWorkTempsForWorkshop.FirstOrDefault(s => s.EmployeeId == x.First().EmployeeId);
return new GetEmployeeClientListViewModel()
{
WorkshopId = workshopId,
EmployeeId = x.Key,
FullName = employee.FullName,
PersonnelCode = personnelCode?.PersonnelCode ?? 0,
HasInsurance = insurance != null,
HasContract = contract != null,
InsuranceLeft = insurance?.InsuranceLeft ?? false,
ContractLeft = contract?.ContractLeft ?? false,
StartWork = contract?.StartWork ?? insurance.StartWork,
LeftWork = contract?.LeftWork ?? insurance.LeftWork,
LastStartInsuranceWork = insurance != null ? insurance.LastStartInsuranceWork : "-",
LastLeftInsuranceWork = insurance != null ? insurance.LastLeftInsuranceWork : "-",
LastStartContractWork = contract != null ? contract.LastStartContractWork : "-",
LastLeftContractWork = contract != null ? contract.LastLeftContractWork : "-",
NationalCode = employee.NationalCode,
IdNumber = employee.IdNumber,
MaritalStatus = employee.MaritalStatus,
DateOfBirthFa = employee.DateOfBirth.ToFarsi(),
FatherName = employee.FatherName,
PendingCreate = employeeClient != null || startWorkTemp != null,
PendingLefWork= leftWorkTemp != null,
ChildrenCount = employee.EmployeeChildrenList.Count,
};
}).ToList();
if (!string.IsNullOrWhiteSpace(searchModel.FullName))
res = res.Where(x => x.FullName.Contains(searchModel.FullName)).ToList();
if (!string.IsNullOrWhiteSpace(searchModel.NationalCode))
res = res.Where(x => x.NationalCode.Contains(searchModel.NationalCode)).ToList();
return res;
}
#endregion
}

View File

@@ -1,10 +1,23 @@
using _0_Framework.Application;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using _0_Framework.Application;
using _0_Framework.Application.Enums;
using _0_Framework.Application.Sms;
using _0_Framework.Exceptions;
using _0_Framework.InfraStructure;
using Company.Domain.ContarctingPartyAgg;
using Company.Domain.ContractingPartyAccountAgg;
using Company.Domain.empolyerAgg;
using Company.Domain.FinancialInvoiceAgg;
using Company.Domain.FinancialStatmentAgg;
using Company.Domain.FinancialTransactionAgg;
using Company.Domain.InstitutionContractAgg;
@@ -15,6 +28,7 @@ using Company.Domain.InstitutionPlanAgg;
using Company.Domain.SmsResultAgg;
using Company.Domain.WorkshopAgg;
using CompanyManagment.App.Contracts.Employer;
using CompanyManagment.App.Contracts.FinancialInvoice;
using CompanyManagment.App.Contracts.FinancialStatment;
using CompanyManagment.App.Contracts.FinancilTransaction;
using CompanyManagment.App.Contracts.Hubs;
@@ -23,21 +37,20 @@ using CompanyManagment.App.Contracts.InstitutionContractContactinfo;
using CompanyManagment.App.Contracts.Law;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using CompanyManagment.App.Contracts.Workshop;
using CompanyManagment.App.Contracts.WorkshopPlan;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MongoDB.Driver;
using OfficeOpenXml.Packaging.Ionic.Zip;
using PersianTools.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ContractingPartyAccount = Company.Domain.ContractingPartyAccountAgg.ContractingPartyAccount;
using FinancialStatment = Company.Domain.FinancialStatmentAgg.FinancialStatment;
using static System.Runtime.InteropServices.JavaScript.JSType;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using SmsResult = CompanyManagment.EFCore.Migrations.SmsResult;
using String = System.String;
using Workshop = Company.Domain.WorkshopAgg.Workshop;
namespace CompanyManagment.EFCore.Repository;
@@ -89,69 +102,69 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
public EditInstitutionContract GetDetails(long id)
{
return _context.InstitutionContractSet.Select(x => new EditInstitutionContract()
{
Id = x.id,
ContractNo = x.ContractNo,
ContractStartGr = x.ContractStartGr,
ContractStartFa = x.ContractStartFa,
ContractEndGr = x.ContractEndGr,
ContractEndFa = x.ContractEndFa,
RepresentativeName = x.RepresentativeName,
ContractingPartyName = x.ContractingPartyName,
RepresentativeId = x.RepresentativeId,
ContractingPartyId = x.ContractingPartyId,
ContractDateFa = x.ContractDateFa,
State = x.State,
City = x.City,
Address = x.Address,
Description = x.Description,
WorkshopManualCount = x.WorkshopManualCount,
EmployeeManualCount = x.EmployeeManualCount,
ContractAmountString = x.ContractAmount.ToMoney(),
ContractAmount = x.ContractAmount,
DailyCompenseationString = x.DailyCompenseation.ToMoney(),
ObligationString = x.Obligation.ToMoney(),
TotalAmountString = x.TotalAmount.ToMoney(),
ExtensionNo = x.ExtensionNo,
OfficialCompany = x.OfficialCompany,
TypeOfContract = x.TypeOfContract,
Signature = x.Signature,
HasValueAddedTax = x.HasValueAddedTax,
ValueAddedTax = x.ValueAddedTax,
})
{
Id = x.id,
ContractNo = x.ContractNo,
ContractStartGr = x.ContractStartGr,
ContractStartFa = x.ContractStartFa,
ContractEndGr = x.ContractEndGr,
ContractEndFa = x.ContractEndFa,
RepresentativeName = x.RepresentativeName,
ContractingPartyName = x.ContractingPartyName,
RepresentativeId = x.RepresentativeId,
ContractingPartyId = x.ContractingPartyId,
ContractDateFa = x.ContractDateFa,
State = x.State,
City = x.City,
Address = x.Address,
Description = x.Description,
WorkshopManualCount = x.WorkshopManualCount,
EmployeeManualCount = x.EmployeeManualCount,
ContractAmountString = x.ContractAmount.ToMoney(),
ContractAmount = x.ContractAmount,
DailyCompenseationString = x.DailyCompenseation.ToMoney(),
ObligationString = x.Obligation.ToMoney(),
TotalAmountString = x.TotalAmount.ToMoney(),
ExtensionNo = x.ExtensionNo,
OfficialCompany = x.OfficialCompany,
TypeOfContract = x.TypeOfContract,
Signature = x.Signature,
HasValueAddedTax = x.HasValueAddedTax,
ValueAddedTax = x.ValueAddedTax,
})
.FirstOrDefault(x => x.Id == id);
}
public EditInstitutionContract GetFirstContract(long contractingPartyId, string typeOfContract)
{
return _context.InstitutionContractSet.Select(x => new EditInstitutionContract()
{
Id = x.id,
ContractNo = x.ContractNo,
ContractStartGr = x.ContractStartGr,
ContractStartFa = x.ContractStartFa,
ContractEndGr = x.ContractEndGr,
ContractEndFa = x.ContractEndFa,
RepresentativeName = x.RepresentativeName,
ContractingPartyName = x.ContractingPartyName,
RepresentativeId = x.RepresentativeId,
ContractingPartyId = x.ContractingPartyId,
ContractDateFa = x.ContractDateFa,
State = x.State,
City = x.City,
Address = x.Address,
Description = x.Description,
WorkshopManualCount = x.WorkshopManualCount,
EmployeeManualCount = x.EmployeeManualCount,
ContractAmountString = x.ContractAmount.ToMoney(),
DailyCompenseationString = x.DailyCompenseation.ToMoney(),
ObligationString = x.Obligation.ToMoney(),
TotalAmountString = x.TotalAmount.ToMoney(),
ExtensionNo = x.ExtensionNo,
OfficialCompany = x.OfficialCompany,
TypeOfContract = x.TypeOfContract,
Signature = x.Signature
})
{
Id = x.id,
ContractNo = x.ContractNo,
ContractStartGr = x.ContractStartGr,
ContractStartFa = x.ContractStartFa,
ContractEndGr = x.ContractEndGr,
ContractEndFa = x.ContractEndFa,
RepresentativeName = x.RepresentativeName,
ContractingPartyName = x.ContractingPartyName,
RepresentativeId = x.RepresentativeId,
ContractingPartyId = x.ContractingPartyId,
ContractDateFa = x.ContractDateFa,
State = x.State,
City = x.City,
Address = x.Address,
Description = x.Description,
WorkshopManualCount = x.WorkshopManualCount,
EmployeeManualCount = x.EmployeeManualCount,
ContractAmountString = x.ContractAmount.ToMoney(),
DailyCompenseationString = x.DailyCompenseation.ToMoney(),
ObligationString = x.Obligation.ToMoney(),
TotalAmountString = x.TotalAmount.ToMoney(),
ExtensionNo = x.ExtensionNo,
OfficialCompany = x.OfficialCompany,
TypeOfContract = x.TypeOfContract,
Signature = x.Signature
})
.Where(x => x.ContractingPartyId == contractingPartyId && x.TypeOfContract == typeOfContract)
.OrderBy(x => x.ExtensionNo).FirstOrDefault();
}
@@ -569,40 +582,40 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
}).ToList(),
}).ToList();
listQuery = listQuery.Select(x => new InstitutionContractViewModel()
{
Id = x.Id,
ContractNo = x.ContractNo,
ContractStartGr = x.ContractStartGr,
ContractStartFa = x.ContractStartFa,
ContractEndGr = x.ContractEndGr,
ContractEndFa = x.ContractEndFa,
RepresentativeId = x.RepresentativeId,
RepresentativeName = x.RepresentativeName,
ContractingPartyName = x.ContractingPartyName,
ContractingPartyId = x.ContractingPartyId,
ContractAmount = x.ContractAmount,
TotalAmount = x.TotalAmount,
SearchAmount = x.SearchAmount,
IsActiveString = x.IsActiveString,
OfficialCompany = x.OfficialCompany,
TypeOfContract = x.TypeOfContract,
Signature = x.Signature,
ExpireColor = x.ExpireColor,
IsExpier = x.IsExpier,
BalanceDouble = x.BalanceDouble,
BalanceStr = x.BalanceStr,
EmployerViewModels = x.EmployerViewModels,
EmployerNo = x.EmployerNo,
EmployerName = x.EmployerViewModels.Select(n => n.FullName).FirstOrDefault(),
WorkshopViewModels = x.WorkshopViewModels,
WorkshopCount = x.WorkshopCount,
IsContractingPartyBlock = x.IsContractingPartyBlock,
BlockTimes = x.BlockTimes,
EmployeeCount =
{
Id = x.Id,
ContractNo = x.ContractNo,
ContractStartGr = x.ContractStartGr,
ContractStartFa = x.ContractStartFa,
ContractEndGr = x.ContractEndGr,
ContractEndFa = x.ContractEndFa,
RepresentativeId = x.RepresentativeId,
RepresentativeName = x.RepresentativeName,
ContractingPartyName = x.ContractingPartyName,
ContractingPartyId = x.ContractingPartyId,
ContractAmount = x.ContractAmount,
TotalAmount = x.TotalAmount,
SearchAmount = x.SearchAmount,
IsActiveString = x.IsActiveString,
OfficialCompany = x.OfficialCompany,
TypeOfContract = x.TypeOfContract,
Signature = x.Signature,
ExpireColor = x.ExpireColor,
IsExpier = x.IsExpier,
BalanceDouble = x.BalanceDouble,
BalanceStr = x.BalanceStr,
EmployerViewModels = x.EmployerViewModels,
EmployerNo = x.EmployerNo,
EmployerName = x.EmployerViewModels.Select(n => n.FullName).FirstOrDefault(),
WorkshopViewModels = x.WorkshopViewModels,
WorkshopCount = x.WorkshopCount,
IsContractingPartyBlock = x.IsContractingPartyBlock,
BlockTimes = x.BlockTimes,
EmployeeCount =
((x.WorkshopViewModels.Sum(w => w.LeftWorkIds.Count)) + (x.WorkshopViewModels.Sum(w =>
w.InsuranceLeftWorkIds.Count(c => !w.LeftWorkIds.Contains(c))))).ToString(),
ArchiveCode = x.WorkshopViewModels.Count > 0 ? ArchiveCodeFinder(x.WorkshopViewModels) : 0,
}).OrderBy(x => x.WorkshopCount != "0" && string.IsNullOrWhiteSpace(x.ExpireColor))
ArchiveCode = x.WorkshopViewModels.Count > 0 ? ArchiveCodeFinder(x.WorkshopViewModels) : 0,
}).OrderBy(x => x.WorkshopCount != "0" && string.IsNullOrWhiteSpace(x.ExpireColor))
.ThenBy(x => x.WorkshopCount == "0" && string.IsNullOrWhiteSpace(x.ExpireColor))
.ThenBy(x => x.IsExpier == "true")
.ThenBy(x => x.ExpireColor == "purple")
@@ -627,17 +640,17 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var op = new OperationResult();
var institutionContarct = _context.InstitutionContractSet
.FirstOrDefault(x => x.id == id);
var prevInstitutionContracts = _context.InstitutionContractSet
.Where(x => x.ContractingPartyId == institutionContarct.ContractingPartyId)
.OrderByDescending(x => x.ContractEndGr).Skip(1).FirstOrDefault();
var transaction = _context.Database.BeginTransaction();
var contactInfo = _context.InstitutionContractContactInfos
.Where(x => x.InstitutionContractId == id)
.ToList();
if (contactInfo.Count > 0)
{
foreach (var item in contactInfo)
@@ -660,20 +673,20 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var financialStatement =
_context.FinancialStatments
.Include(x => x.FinancialTransactionList)
.FirstOrDefault(x => x.ContractingPartyId == institutionContarct.ContractingPartyId);
.FirstOrDefault(x=>x.ContractingPartyId == institutionContarct.ContractingPartyId);
if (financialStatement != null)
{
var sumDebtor = financialStatement.FinancialTransactionList
.Sum(x => x.Deptor);
var sumDebtor = financialStatement.FinancialTransactionList
.Sum(x => x.Deptor);
var sumCreditor = financialStatement.FinancialTransactionList
.Sum(x => x.Creditor);
var balance = sumDebtor - sumCreditor;
if (balance > 0 && prevInstitutionContracts.ContractEndGr < now)
{
prevInstitutionContracts.DeActiveBlue();
_context.SaveChanges();
}
if (balance>0 && prevInstitutionContracts.ContractEndGr<now)
{
prevInstitutionContracts.DeActiveBlue();
_context.SaveChanges();
}
}
}
@@ -1359,7 +1372,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.Count(l => l.StartWorkDate <= DateTime.Now && l.LeftWorkDate >= DateTime.Now);
return new GetInstitutionContractListItemsViewModel()
{
ContractAmount = x.contract.ContractAmountWithTax,
ContractAmount = x.contract.ContractAmount,
Balance = statement?.FinancialTransactionList.Sum(ft => ft.Deptor - ft.Creditor) ?? 0,
WorkshopsCount = workshops.Count(),
ContractStartFa = x.contract.ContractStartGr.ToFarsi(),
@@ -1379,7 +1392,9 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
Workshops = workshopDetails,
IsInPersonContract = x.contract.WorkshopGroup?.CurrentWorkshops
.Any(y => y.Services.ContractInPerson) ?? true,
IsOldContract = x.contract.SigningType == InstitutionContractSigningType.Legacy
IsOldContract = x.contract.WorkshopGroup?.CurrentWorkshops == null
|| x.contract.WorkshopGroup.CurrentWorkshops.Count == 0
|| x.contract.WorkshopGroup.CurrentWorkshops.Any(y => y.Price == 0)
};
}).ToList()
};
@@ -3198,7 +3213,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
PaymentPrice = institution.TotalAmount.ToMoney(),
TotalPrice = (institution.TotalAmount - institution.ValueAddedTax).ToMoney(),
TaxPrice = institution.ValueAddedTax.ToMoney(),
OneMonthPrice = institution.ContractAmountWithTax.ToMoney(),
VerifierFullName = institution.VerifierFullName,
VerifierPhoneNumber = institution.VerifierPhoneNumber,
VerifyCode = institution.VerifyCode,
@@ -3559,19 +3573,19 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var smsList = new List<BlockSmsListData>();
var institutionContracts = await _context.InstitutionContractSet.Select(x => new InstitutionContractViewModel
{
Id = x.id,
ContractingPartyId = x.ContractingPartyId,
ContractingPartyName = x.ContractingPartyName,
ContractStartGr = x.ContractStartGr,
ContractStartFa = x.ContractStartFa,
ContractEndGr = x.ContractEndGr,
ContractEndFa = x.ContractEndFa,
IsActiveString = x.IsActiveString,
ContractAmountDouble = x.ContractAmount,
OfficialCompany = x.OfficialCompany
}).Where(x => x.ContractStartGr < checkDate && x.ContractEndGr >= checkDate &&
x.ContractAmountDouble > 0).GroupBy(x => x.ContractingPartyId).Select(x => x.First())
{
Id = x.id,
ContractingPartyId = x.ContractingPartyId,
ContractingPartyName = x.ContractingPartyName,
ContractStartGr = x.ContractStartGr,
ContractStartFa = x.ContractStartFa,
ContractEndGr = x.ContractEndGr,
ContractEndFa = x.ContractEndFa,
IsActiveString = x.IsActiveString,
ContractAmountDouble = x.ContractAmount,
OfficialCompany = x.OfficialCompany
}).Where(x => x.ContractStartGr < checkDate && x.ContractEndGr >= checkDate &&
x.ContractAmountDouble > 0).GroupBy(x => x.ContractingPartyId).Select(x => x.First())
.ToListAsync();
@@ -3665,12 +3679,9 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
{
smsList.Add(new BlockSmsListData()
{
PhoneNumber = number.PhoneNumber,
PartyName = partyName,
AccountType = accountType,
Amount = amount,
ContractingPartyId = contractingParty.id,
InstitutionContractId = item.Id,
PhoneNumber = number.PhoneNumber, PartyName = partyName,
AccountType = accountType, Amount = amount,
ContractingPartyId = contractingParty.id, InstitutionContractId = item.Id,
AproveId = aprove
});
}
@@ -3858,16 +3869,11 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
smsList.Add(new SmsListData()
{
PhoneNumber = number.PhoneNumber,
TemplateId = templateId,
PartyName = partyName,
Amount = balanceToMoney,
ContractingPartyId = contractingParty.id,
AproveId = aprove,
TypeOfSmsMethod = "MonthlyBillNew",
Code1 = code1,
Code2 = code2,
InstitutionContractId = item.Id
PhoneNumber = number.PhoneNumber, TemplateId = templateId,
PartyName = partyName, Amount = balanceToMoney,
ContractingPartyId = contractingParty.id, AproveId = aprove,
TypeOfSmsMethod = "MonthlyBillNew", Code1 = code1,
Code2 = code2, InstitutionContractId = item.Id
});
}
else
@@ -3881,15 +3887,10 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
smsList.Add(new SmsListData()
{
PhoneNumber = number.PhoneNumber,
TemplateId = templateId,
PartyName = partyName,
Amount = balanceToMoney,
ContractingPartyId = contractingParty.id,
AproveId = aprove,
TypeOfSmsMethod = "MonthlyBill",
Code1 = "",
Code2 = "",
PhoneNumber = number.PhoneNumber, TemplateId = templateId,
PartyName = partyName, Amount = balanceToMoney,
ContractingPartyId = contractingParty.id, AproveId = aprove,
TypeOfSmsMethod = "MonthlyBill", Code1 = "", Code2 = "",
InstitutionContractId = item.Id
});
}
@@ -3921,16 +3922,11 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
smsList.Add(new SmsListData()
{
PhoneNumber = number.PhoneNumber,
TemplateId = templateId,
PartyName = partyName,
Amount = balanceToMoney,
ContractingPartyId = contractingParty.id,
AproveId = aprove,
TypeOfSmsMethod = "MonthlyBillNew",
Code1 = code1,
Code2 = code2,
InstitutionContractId = item.Id
PhoneNumber = number.PhoneNumber, TemplateId = templateId,
PartyName = partyName, Amount = balanceToMoney,
ContractingPartyId = contractingParty.id, AproveId = aprove,
TypeOfSmsMethod = "MonthlyBillNew", Code1 = code1,
Code2 = code2, InstitutionContractId = item.Id
});
}
else
@@ -3944,15 +3940,10 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
smsList.Add(new SmsListData()
{
PhoneNumber = number.PhoneNumber,
TemplateId = templateId,
PartyName = partyName,
Amount = balanceToMoney,
ContractingPartyId = contractingParty.id,
AproveId = aprove,
TypeOfSmsMethod = "MonthlyBill",
Code1 = "",
Code2 = "",
PhoneNumber = number.PhoneNumber, TemplateId = templateId,
PartyName = partyName, Amount = balanceToMoney,
ContractingPartyId = contractingParty.id, AproveId = aprove,
TypeOfSmsMethod = "MonthlyBill", Code1 = "", Code2 = "",
InstitutionContractId = item.Id
});
}
@@ -3988,16 +3979,11 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
smsList.Add(new SmsListData()
{
PhoneNumber = number.PhoneNumber,
TemplateId = templateId,
PartyName = partyName,
Amount = balanceToMoney,
ContractingPartyId = contractingParty.id,
AproveId = aprove,
TypeOfSmsMethod = "MonthlyBillNew",
Code1 = code1,
Code2 = code2,
InstitutionContractId = item.Id
PhoneNumber = number.PhoneNumber, TemplateId = templateId,
PartyName = partyName, Amount = balanceToMoney,
ContractingPartyId = contractingParty.id, AproveId = aprove,
TypeOfSmsMethod = "MonthlyBillNew", Code1 = code1,
Code2 = code2, InstitutionContractId = item.Id
});
}
else
@@ -4011,15 +3997,10 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
smsList.Add(new SmsListData()
{
PhoneNumber = number.PhoneNumber,
TemplateId = templateId,
PartyName = partyName,
Amount = balanceToMoney,
ContractingPartyId = contractingParty.id,
AproveId = aprove,
TypeOfSmsMethod = "MonthlyBill",
Code1 = "",
Code2 = "",
PhoneNumber = number.PhoneNumber, TemplateId = templateId,
PartyName = partyName, Amount = balanceToMoney,
ContractingPartyId = contractingParty.id, AproveId = aprove,
TypeOfSmsMethod = "MonthlyBill", Code1 = "", Code2 = "",
InstitutionContractId = item.Id
});
}
@@ -4054,16 +4035,11 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
string code2 = publicId.Substring(25);
smsList.Add(new SmsListData()
{
PhoneNumber = number.PhoneNumber,
TemplateId = templateId,
PartyName = partyName,
Amount = balanceToMoney,
ContractingPartyId = contractingParty.id,
AproveId = aprove,
TypeOfSmsMethod = "MonthlyBillNew",
Code1 = code1,
Code2 = code2,
InstitutionContractId = item.Id
PhoneNumber = number.PhoneNumber, TemplateId = templateId,
PartyName = partyName, Amount = balanceToMoney,
ContractingPartyId = contractingParty.id, AproveId = aprove,
TypeOfSmsMethod = "MonthlyBillNew", Code1 = code1,
Code2 = code2, InstitutionContractId = item.Id
});
}
else
@@ -4077,15 +4053,10 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
smsList.Add(new SmsListData()
{
PhoneNumber = number.PhoneNumber,
TemplateId = templateId,
PartyName = partyName,
Amount = balanceToMoney,
ContractingPartyId = contractingParty.id,
AproveId = aprove,
TypeOfSmsMethod = "MonthlyBill",
Code1 = "",
Code2 = "",
PhoneNumber = number.PhoneNumber, TemplateId = templateId,
PartyName = partyName, Amount = balanceToMoney,
ContractingPartyId = contractingParty.id, AproveId = aprove,
TypeOfSmsMethod = "MonthlyBill", Code1 = "", Code2 = "",
InstitutionContractId = item.Id
});
}
@@ -4246,9 +4217,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
#endregion
}
#region PrivateMetods
/// <summary>
@@ -4290,88 +4258,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.FirstOrDefaultAsync(x => x.ContractingPartyId == contractingPartyId);
}
#endregion
#region InstitutionContractConfirm
/// <summary>
/// ارسال پیامک یادآور تایید قراداد مالی
/// </summary>
/// <returns></returns>
public async Task SendInstitutionContractConfirmSmsTask()
{
var now = DateTime.Now;
// تبدیل تاریخ میلادی به شمسی
var persianNow = now.ToFarsi();
var persianEndOfMonth = int.Parse(persianNow.FindeEndOfMonth().Substring(8, 2));
var dayOfMonth = int.Parse(persianNow.Substring(8, 2));
var hour = now.Hour;
var minute = now.Minute;
var checkAnyToExecute = false;
//اگر آخرین روز ماه باشد
//اگر روز مثلا عدد روز 31 بود ولی آخرین روز ماه 30 بود
if (dayOfMonth == persianEndOfMonth)
{
checkAnyToExecute = await _context.SmsSettings
.AnyAsync(x =>
x.DayOfMonth >= dayOfMonth && /// اگر بزرگتر یا مساوی رو جاری بود
x.TimeOfDay.Hours == hour &&
x.TimeOfDay.Minutes == minute &&
x.TypeOfSmsSetting == TypeOfSmsSetting.InstitutionContractConfirm &&
x.IsActive
);
}
else
{
checkAnyToExecute = await _context.SmsSettings
.AnyAsync(x =>
x.DayOfMonth == dayOfMonth &&
x.TimeOfDay.Hours == hour &&
x.TimeOfDay.Minutes == minute &&
x.TypeOfSmsSetting == TypeOfSmsSetting.InstitutionContractConfirm &&
x.IsActive
);
}
if (checkAnyToExecute)
{
//اجرای تسک
//دریافت لیست قراداد های تایید نشده
var fromAmonthAgo = now.AddDays(-30);
var pendingContracts = await _context.InstitutionContractSet
.Where(x => x.CreationDate >= fromAmonthAgo && x.CreationDate.Date != now.Date && x.VerificationStatus == InstitutionContractVerificationStatus.PendingForVerify)
.Join(_context.PersonalContractingParties,
contract => contract.ContractingPartyId,
contractingParty => contractingParty.id,
(contract, contractingParty) => new { contract, contractingParty }).Select(x => new InstitutionCreationVerificationSmsDto
{
Number = x.contractingParty.Phone,
FullName = x.contractingParty.IsLegal == "حقیقی" ? $"{x.contractingParty.FName} {x.contractingParty.LName}" : $"{x.contractingParty.LName}",
ContractingPartyId = x.contract.ContractingPartyId,
InstitutionContractId = x.contract.id,
InstitutionId = x.contract.PublicId,
}).ToListAsync();
string typeOfSms = "یادآور تایید قرارداد مالی";
foreach (var item in pendingContracts)
{
var sendResult = await _smsService.SendInstitutionCreationVerificationLink(item.Number, item.FullName,
item.InstitutionId, item.ContractingPartyId, item.InstitutionContractId, typeOfSms);
}
Console.WriteLine("executed at : " + persianNow + " - " + hour + ":" + minute);
}
}
#endregion
#endregion
@@ -4415,7 +4301,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
VerificationStatus = x.VerificationStatus,
InstallmentList = x.Installments
.Select(ins => new InstitutionContractInstallmentViewModel
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
.OrderBy(ins => ins.InstallmentDateGr).Skip(1).ToList(),
}).Where(x =>
x.ContractStartGr < endOfMonthGr && x.ContractEndGr >= endOfMonthGr && x.ContractAmountDouble > 0)
@@ -4459,7 +4345,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
VerificationStatus = x.VerificationStatus,
InstallmentList = x.Installments
.Select(ins => new InstitutionContractInstallmentViewModel
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
.OrderBy(ins => ins.InstallmentDateGr).Skip(1).ToList(),
}).ToListAsync();
@@ -4756,7 +4642,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.Where(x => x.Installments.Any(i => i.Id == installmentId))
.Select(x => x.id).FirstOrDefaultAsync();
}
#endregion

View File

@@ -1777,49 +1777,6 @@ public class InsuranceListRepository : RepositoryBase<long, InsuranceList>, IIns
return res;
}
public async Task<PagedResult<InsuranceClientListViewModel>> GetInsuranceClientList(InsuranceClientSearchModel searchModel)
{
var workshopId = _authHelper.GetWorkshopId();
var query = _context.InsuranceListSet
.Select(x => new InsuranceClientListViewModel
{
Id = x.id,
WorkShopId = x.WorkshopId,
Year = x.Year,
YearInt = Convert.ToInt32(x.Year),
Month = x.Month,
MonthName = x.Month.ToFarsiMonthByNumber(),
MonthInt = Convert.ToInt32(x.Month),
}).Where(x => x.WorkShopId == workshopId);
if (searchModel.Year>0)
{
query = query.Where(x => x.YearInt == searchModel.Year);
}
if (searchModel.Month > 0)
{
query = query.Where(x => x.MonthInt == searchModel.Month);
}
var res = new PagedResult<InsuranceClientListViewModel>
{
TotalCount = query.Count()
};
query = searchModel.Sorting switch
{
"CreationDate-Max" => query.OrderByDescending(x => x.Id),
"CreationDate-Min" => query.OrderBy(x => x.Id),
"Month-Max" => query.OrderByDescending(x => x.MonthInt),
"Month-Min" => query.OrderBy(x => x.MonthInt),
"Year-Max" => query.OrderByDescending(x => x.YearInt),
"Year-Min" => query.OrderBy(x => x.YearInt),
_ => query.OrderByDescending(x => x.Id),
};
res.List =await query.ApplyPagination(searchModel.PageIndex,searchModel.PageSize).ToListAsync();
return res;
}
public async Task<List<InsuranceListViewModel>> GetNotCreatedWorkshop(InsuranceListSearchModel searchModel)
{
if (string.IsNullOrEmpty(searchModel.Month) || string.IsNullOrEmpty(searchModel.Year))

View File

@@ -1994,9 +1994,8 @@ public class RollCallMandatoryRepository : RepositoryBase<long, RollCall>, IRoll
case "شنبه":
w1 = 7;
w2 = 14;
w3 = 21;
w4 = 28;
w5 = 31;
w3 = 28;
w4 = 31;
break;
case "یکشنبه":
w1 = 6;
@@ -2362,7 +2361,6 @@ public class RollCallMandatoryRepository : RepositoryBase<long, RollCall>, IRoll
break;
}
}
}
#endregion

View File

@@ -588,7 +588,8 @@ public class WorkshopRepository : RepositoryBase<long, Company.Domain.WorkshopAg
LeftWork = x.LeftWorkDate,
LastStartInsuranceWork = "-",
LastLeftInsuranceWork = "-",
}).Where(x => x.WorkshopId == workshopId).OrderByDescending(x => x.StartWork).ToList();
}).Where(x => x.WorkshopId == workshopId)
.OrderByDescending(x => x.StartWork).ToList();
contractLeftWork = contractLeftWork.Select(x => new PersonnelInfoViewModel()
{

View File

@@ -1,32 +1,14 @@
using Microsoft.EntityFrameworkCore;
using PersianTools.Core;
using Shared.Contracts.Holidays;
using System;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Shared.Contracts.Holidays;
namespace CompanyManagment.EFCore.Services;
public class HolidayQueryService : IHolidayQueryService
{
private readonly CompanyContext _context;
public HolidayQueryService(CompanyContext context)
public Task<List<HolidayDto>> GetHolidaysInDates(DateTime startDate, DateTime endDate)
{
_context = context;
}
public async Task<List<HolidayDto>> GetHolidaysInDates(DateTime startDate, DateTime endDate)
{
return await _context.HolidayItems.Where(x => x.Holidaydate >= startDate && x.Holidaydate <= endDate).Select(x=> new HolidayDto()
{
Holidaydate = x.Holidaydate,
HolidayId = x.id,
HolidayYear = x.HolidayYear
})
.ToListAsync();
throw new NotImplementedException();
}
}

View File

@@ -350,12 +350,9 @@ public class SmsService : ISmsService
}
public async Task<bool> SendInstitutionCreationVerificationLink(string number, string fullName, Guid institutionId, long contractingPartyId, long institutionContractId, string typeOfSms)
public async Task<bool> SendInstitutionCreationVerificationLink(string number, string fullName, Guid institutionId, long contractingPartyId, long institutionContractId)
{
typeOfSms = string.IsNullOrWhiteSpace(typeOfSms) ? "لینک تاییدیه ایجاد قرارداد مالی" : typeOfSms;
var full = fullName;
var full = fullName;
var fullName1 = fullName;
if (fullName.Length >= 25)
{
@@ -380,9 +377,8 @@ public class SmsService : ISmsService
new("CODE1",firstPart),
new("CODE2",secondPart)
});
var smsResult = new SmsResult(verificationSendResult.Data.MessageId, verificationSendResult.Message, typeOfSms,
var smsResult = new SmsResult(verificationSendResult.Data.MessageId, verificationSendResult.Message, "لینک تاییدیه ایجاد قرارداد مالی",
fullName, number, contractingPartyId, institutionContractId);
await _smsResultRepository.CreateAsync(smsResult);
await _smsResultRepository.SaveChangesAsync();

View File

@@ -106,8 +106,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GozareshgirProgramManager.I
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared.Contracts", "Shared.Contracts\Shared.Contracts.csproj", "{08B234B6-783B-44E9-9961-4F97EAD16308}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{F61F77F5-9B14-49CC-870B-1C61D2636586}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -277,7 +275,6 @@ Global
{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}
{08B234B6-783B-44E9-9961-4F97EAD16308} = {F61F77F5-9B14-49CC-870B-1C61D2636586}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E6CFB3A7-A7C8-4E82-8F06-F750408F0BA9}

View File

@@ -1,23 +0,0 @@
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Application.Interfaces;
using GozareshgirProgramManager.Domain.ProjectAgg.Events;
using MediatR;
namespace GozareshgirProgramManager.Application.DomainEventHandlers.ProjectSection;
public class TaskSectionStatusChangedHandler:INotificationHandler<DomainEventNotification<TaskSectionStatusChangedEvent>>
{
private readonly IBoardNotificationPublisher _boardNotificationPublisher;
public TaskSectionStatusChangedHandler(IBoardNotificationPublisher boardNotificationPublisher)
{
_boardNotificationPublisher = boardNotificationPublisher;
}
public Task Handle(DomainEventNotification<TaskSectionStatusChangedEvent> notification, CancellationToken cancellationToken)
{
var domainEvent = notification.DomainEvent;
_boardNotificationPublisher.SendProjectStatusChanged(domainEvent.UserId,domainEvent.OldStatus,domainEvent.NewStatus,domainEvent.SectionId);
return Task.CompletedTask;
}
}

View File

@@ -1,9 +0,0 @@
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
namespace GozareshgirProgramManager.Application.Interfaces;
public interface IBoardNotificationPublisher
{
Task SendProjectStatusChanged(long userId, TaskSectionStatus oldStatus,
TaskSectionStatus newStatus, Guid sectionId);
}

View File

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

View File

@@ -185,7 +185,7 @@ public class CreateOrEditCheckoutCommandHandler : IBaseCommandHandler<CreateOrEd
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);
var holidays = await _holidayQueryService.GetHolidaysInDates(start, end) ;
int mandatoryHours = 0;
for (var currentDay = persianStart; currentDay <= persianEnd; currentDay = currentDay.AddDays(1))
{
@@ -205,9 +205,13 @@ public class CreateOrEditCheckoutCommandHandler : IBaseCommandHandler<CreateOrEd
Console.WriteLine((int)getDaySetting.ShiftDuration.TotalMinutes + " " + currentDay + " - " + day);
}
}
}
//حقوق نهایی
var monthlySalaryPay = (totalHoursWorked * monthlySalaryDefined) / mandatoryHours;

View File

@@ -45,15 +45,12 @@ public class ChangeStatusSectionCommandHandler : IBaseCommandHandler<ChangeStatu
if (section.Status == TaskSectionStatus.InProgress)
{
// Coming FROM InProgress: Stop the active activity
section.StopWork(request.Status);
section.StopWork(currentUser, request.Status);
}
else if (request.Status == TaskSectionStatus.InProgress)
{
// Going TO InProgress: Check if section has remaining time, then start work
if (!section.HasRemainingTime())
return OperationResult.ValidationError("زمان این بخش به پایان رسیده است");
section.StartWork();
// Going TO InProgress: Start work and create activity
section.StartWork(currentUser);
}
else
{
@@ -85,11 +82,11 @@ public class ChangeStatusSectionCommandHandler : IBaseCommandHandler<ChangeStatu
// Valid transitions matrix
var validTransitions = new Dictionary<TaskSectionStatus, List<TaskSectionStatus>>
{
{ TaskSectionStatus.ReadyToStart, [TaskSectionStatus.InProgress] },
{ TaskSectionStatus.InProgress, [TaskSectionStatus.Incomplete, TaskSectionStatus.Completed] },
{ TaskSectionStatus.Incomplete, [TaskSectionStatus.InProgress, TaskSectionStatus.Completed] },
{ TaskSectionStatus.Completed, [TaskSectionStatus.InProgress, TaskSectionStatus.Incomplete] }, // Can return to InProgress or Incomplete
{ TaskSectionStatus.NotAssigned, [TaskSectionStatus.InProgress, TaskSectionStatus.ReadyToStart] }
{ 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))

View File

@@ -8,8 +8,6 @@ public class CreateProjectCommandValidator:AbstractValidator<CreateProjectComman
public CreateProjectCommandValidator()
{
RuleFor(x => x.Name)
.MaximumLength(25)
.WithMessage("نام نمیتواند بیشتر از 25 کاراکتر باشد")
.NotEmpty()
.NotNull()
.WithMessage("نام نمیتواند خالی باشد");

View File

@@ -2,14 +2,13 @@ using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Application.Modules.Projects.DTOs;
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.SetTimeProject;
public class SetTimeProjectCommandHandler : IBaseCommandHandler<SetTimeProjectCommand>
public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectCommand>
{
private readonly IProjectRepository _projectRepository;
private readonly IProjectPhaseRepository _projectPhaseRepository;
@@ -17,7 +16,7 @@ public class SetTimeProjectCommandHandler : IBaseCommandHandler<SetTimeProjectCo
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthHelper _authHelper;
private long? _userId;
public SetTimeProjectCommandHandler(
IProjectRepository projectRepository,
@@ -41,11 +40,11 @@ public class SetTimeProjectCommandHandler : IBaseCommandHandler<SetTimeProjectCo
return await SetTimeForProjectTask(request, cancellationToken);
default:
return OperationResult.Failure("سطح پروژه نامعتبر است");
}
}
private async Task<OperationResult> SetTimeForProject(SetTimeProjectCommand request,
CancellationToken cancellationToken)
private async Task<OperationResult> SetTimeForProject(SetTimeProjectCommand request, CancellationToken cancellationToken)
{
var project = await _projectRepository.GetWithFullHierarchyAsync(request.Id);
if (project == null)
@@ -76,8 +75,7 @@ public class SetTimeProjectCommandHandler : IBaseCommandHandler<SetTimeProjectCo
return OperationResult.Success();
}
private async Task<OperationResult> SetTimeForProjectPhase(SetTimeProjectCommand request,
CancellationToken cancellationToken)
private async Task<OperationResult> SetTimeForProjectPhase(SetTimeProjectCommand request, CancellationToken cancellationToken)
{
var phase = await _projectPhaseRepository.GetWithTasksAsync(request.Id);
if (phase == null)
@@ -105,13 +103,13 @@ public class SetTimeProjectCommandHandler : IBaseCommandHandler<SetTimeProjectCo
return OperationResult.Success();
}
private async Task<OperationResult> SetTimeForProjectTask(SetTimeProjectCommand request,
CancellationToken cancellationToken)
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;
@@ -129,17 +127,12 @@ public class SetTimeProjectCommandHandler : IBaseCommandHandler<SetTimeProjectCo
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);
if (initialTime <= TimeSpan.Zero)
{
return;
}
// تنظیم زمان اولیه
section.UpdateInitialEstimatedHours(initialTime, initData.Description);
@@ -151,7 +144,7 @@ public class SetTimeProjectCommandHandler : IBaseCommandHandler<SetTimeProjectCo
section.AddAdditionalTime(additionalTimeSpan, additionalTime.Description, addedByUserId);
}
}
// private void SetSectionTime(ProjectSection section, SetTimeProjectSectionItem sectionItem, long? addedByUserId)
// {
// var initData = sectionItem.InitData;
@@ -168,4 +161,4 @@ public class SetTimeProjectCommandHandler : IBaseCommandHandler<SetTimeProjectCo
// section.AddAdditionalTime(additionalTimeSpan, additionalTime.Description, addedByUserId);
// }
// }
}
}

View File

@@ -1,5 +1,4 @@
using FluentValidation;
using FluentValidation.Validators;
using GozareshgirProgramManager.Application.Modules.Projects.DTOs;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.SetTimeProject;
@@ -16,9 +15,6 @@ public class SetTimeProjectCommandValidator:AbstractValidator<SetTimeProjectComm
RuleForEach(x => x.SectionItems)
.SetValidator(command => new SetTimeProjectSectionItemValidator());
RuleFor(x => x.SectionItems)
.Must(sectionItems => sectionItems.Any(si => si.InitData?.Hours > 0))
.WithMessage("حداقل یکی از بخش‌ها باید مقدار ساعت معتبری داشته باشد.");
}
}
public class SetTimeProjectSectionItemValidator:AbstractValidator<SetTimeProjectSectionItem>
@@ -34,14 +30,13 @@ public class SetTimeProjectSectionItemValidator:AbstractValidator<SetTimeProject
.SetValidator(new TimeDataValidator());
RuleForEach(x=>x.AdditionalTime)
.SetValidator(new AdditionalTimeDataValidator());
.SetValidator(new TimeDataValidator());
}
}
public class AdditionalTimeDataValidator: AbstractValidator<SetTimeSectionTime>
public class TimeDataValidator : AbstractValidator<SetTimeSectionTime>
{
public AdditionalTimeDataValidator()
public TimeDataValidator()
{
RuleFor(x => x.Hours)
.GreaterThanOrEqualTo(0)
@@ -50,13 +45,6 @@ public class AdditionalTimeDataValidator: AbstractValidator<SetTimeSectionTime>
RuleFor(x=>x.Description)
.MaximumLength(500)
.WithMessage("توضیحات نمی‌تواند بیشتر از 500 کاراکتر باشد.");
}
}
public class TimeDataValidator : AbstractValidator<SetTimeSectionTime>
{
public TimeDataValidator()
{
}
}

View File

@@ -132,82 +132,91 @@ public class GetProjectsListQueryHandler : IBaseQueryHandler<GetProjectsListQuer
private async Task SetSkillFlags(List<GetProjectListDto> projects, CancellationToken cancellationToken)
{
if (!projects.Any())
return;
var projectIds = projects.Select(x => x.Id).ToList();
var hierarchyLevel = projects.First().Level;
switch (hierarchyLevel)
// تنها تسک‌ها sections دارند، بنابراین برای سطوح مختلف باید متفاوت عمل کنیم
List<Guid> taskIds;
switch (projects.FirstOrDefault()?.Level)
{
case ProjectHierarchyLevel.Project:
await SetSkillFlagsForProjects(projects, projectIds, cancellationToken);
// برای پروژه‌ها، باید تمام تسک‌های زیرمجموعه را پیدا کنیم
var phaseIds = await _context.ProjectPhases
.Where(ph => projectIds.Contains(ph.ProjectId))
.Select(ph => ph.Id)
.ToListAsync(cancellationToken);
taskIds = await _context.ProjectTasks
.Where(t => phaseIds.Contains(t.PhaseId))
.Select(t => t.Id)
.ToListAsync(cancellationToken);
break;
case ProjectHierarchyLevel.Phase:
await SetSkillFlagsForPhases(projects, projectIds, cancellationToken);
// برای فازها، تمام تسک‌های آن فازها را پیدا کنیم
taskIds = await _context.ProjectTasks
.Where(t => projectIds.Contains(t.PhaseId))
.Select(t => t.Id)
.ToListAsync(cancellationToken);
break;
case ProjectHierarchyLevel.Task:
await SetSkillFlagsForTasks(projects, projectIds, cancellationToken);
// برای تسک‌ها، خود آنها taskIds هستند
taskIds = projectIds;
break;
default:
return;
}
}
private async Task SetSkillFlagsForProjects(List<GetProjectListDto> projects, List<Guid> projectIds, CancellationToken cancellationToken)
{
var projectSections = await _context.ProjectSections
.Include(x => x.Skill)
.Where(s => projectIds.Contains(s.ProjectId))
.ToListAsync(cancellationToken);
if (!projectSections.Any())
if (!taskIds.Any())
return;
var sections = await _context.TaskSections
.Include(x => x.Skill)
.Where(x => taskIds.Contains(x.TaskId))
.ToListAsync(cancellationToken);
foreach (var project in projects)
{
var sections = projectSections.Where(s => s.ProjectId == project.Id).ToList();
project.HasBackend = sections.Any(x => x.Skill?.Name == "Backend");
project.HasFront = sections.Any(x => x.Skill?.Name == "Frontend");
project.HasDesign = sections.Any(x => x.Skill?.Name == "UI/UX Design");
}
}
private async Task SetSkillFlagsForPhases(List<GetProjectListDto> projects, List<Guid> phaseIds, CancellationToken cancellationToken)
{
var phaseSections = await _context.PhaseSections
.Include(x => x.Skill)
.Where(s => phaseIds.Contains(s.PhaseId))
.ToListAsync(cancellationToken);
if (!phaseSections.Any())
return;
foreach (var phase in projects)
{
var sections = phaseSections.Where(s => s.PhaseId == phase.Id).ToList();
phase.HasBackend = sections.Any(x => x.Skill?.Name == "Backend");
phase.HasFront = sections.Any(x => x.Skill?.Name == "Frontend");
phase.HasDesign = sections.Any(x => x.Skill?.Name == "UI/UX Design");
}
}
private async Task SetSkillFlagsForTasks(List<GetProjectListDto> projects, List<Guid> taskIds, CancellationToken cancellationToken)
{
var taskSections = await _context.TaskSections
.Include(x => x.Skill)
.Where(s => taskIds.Contains(s.TaskId))
.ToListAsync(cancellationToken);
if (!taskSections.Any())
return;
foreach (var task in projects)
{
var sections = taskSections.Where(s => s.TaskId == task.Id).ToList();
task.HasBackend = sections.Any(x => x.Skill?.Name == "Backend");
task.HasFront = sections.Any(x => x.Skill?.Name == "Frontend");
task.HasDesign = sections.Any(x => x.Skill?.Name == "UI/UX Design");
List<Guid> relevantTaskIds;
switch (project.Level)
{
case ProjectHierarchyLevel.Project:
// برای پروژه، تمام تسک‌های زیرمجموعه
var projectPhaseIds = await _context.ProjectPhases
.Where(ph => ph.ProjectId == project.Id)
.Select(ph => ph.Id)
.ToListAsync(cancellationToken);
relevantTaskIds = await _context.ProjectTasks
.Where(t => projectPhaseIds.Contains(t.PhaseId))
.Select(t => t.Id)
.ToListAsync(cancellationToken);
break;
case ProjectHierarchyLevel.Phase:
// برای فاز، تمام تسک‌های آن فاز
relevantTaskIds = await _context.ProjectTasks
.Where(t => t.PhaseId == project.Id)
.Select(t => t.Id)
.ToListAsync(cancellationToken);
break;
case ProjectHierarchyLevel.Task:
// برای تسک، خود آن
relevantTaskIds = new List<Guid> { project.Id };
break;
default:
continue;
}
var projectSections = sections.Where(x => relevantTaskIds.Contains(x.TaskId)).ToList();
project.HasBackend = projectSections.Any(x => x.Skill.Name == "Backend");
project.HasFront = projectSections.Any(x => x.Skill.Name == "Frontend");
project.HasDesign = projectSections.Any(x => x.Skill.Name == "UI/UX Design");
}
}

View File

@@ -1,74 +0,0 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using Microsoft.EntityFrameworkCore;
namespace GozareshgirProgramManager.Application.Modules.Projects.Queries.ProjectBoardDetail;
public record ProjectBoardDetailQuery(Guid SectionId) : IBaseQuery<ProjectBoardDetailResponse>;
public record ProjectBoardDetailResponse(List<ProjectBoardDetailUserResponse> Users, string TotalTime);
public record ProjectBoardDetailUserResponse
{
public List<ProjectBoardDetailUserHistoryResponse> Histories { get; set; } = new();
public string UserFullName { get; set; }
public long UserId { get; set; }
}
public class ProjectBoardDetailUserHistoryResponse
{
public string Date { get; set; }
public string startTime { get; set; }
public string EndTime { get; set; }
public string TotalTime { get; set; }
}
public class ProjectBoardDetailQueryHandler : IBaseQueryHandler<ProjectBoardDetailQuery, ProjectBoardDetailResponse>
{
private readonly IProgramManagerDbContext _programManagerDbContext;
public ProjectBoardDetailQueryHandler(IProgramManagerDbContext programManagerDbContext)
{
_programManagerDbContext = programManagerDbContext;
}
public async Task<OperationResult<ProjectBoardDetailResponse>> Handle(ProjectBoardDetailQuery request,
CancellationToken cancellationToken)
{
var section = await _programManagerDbContext.TaskSections
.Include(x => x.Activities)
.FirstOrDefaultAsync(x => x.Id == request.SectionId, cancellationToken: cancellationToken);
if (section == null)
return OperationResult<ProjectBoardDetailResponse>.NotFound("بخش مورد نظر یافت نشد");
var userIds = section.Activities.Select(x => x.UserId).Distinct().ToList();
var usersDict = await _programManagerDbContext.Users
.Where(x => userIds.Contains(x.Id))
.ToDictionaryAsync(x => x.Id, x => x.FullName, cancellationToken);
var totalTimeSpan = section.Activities
.Select(x => x.GetTimeSpent())
.Aggregate(TimeSpan.Zero, (sum, next) => sum.Add(next));
var users = section.Activities.GroupBy(x => x.UserId).Select(x =>
{
return new ProjectBoardDetailUserResponse()
{
UserId = x.Key,
UserFullName = usersDict[x.Key],
Histories = x.Select(h => new ProjectBoardDetailUserHistoryResponse()
{
Date = h.StartDate.ToFarsi(),
startTime = h.StartDate.ToString("HH:mm"),
EndTime = h.EndDate?.ToString("HH:mm") ?? "-",
TotalTime = h.GetTimeSpent().ToString(@"hh\:mm")
}).ToList()
};
}).ToList();
var response = new ProjectBoardDetailResponse(users, $"{(int)totalTimeSpan.TotalHours}:{totalTimeSpan.Minutes:D2}");
return OperationResult<ProjectBoardDetailResponse>.Success(response);
}
}

View File

@@ -6,5 +6,5 @@ namespace GozareshgirProgramManager.Application.Modules.Projects.Queries.Project
public record ProjectBoardListQuery: IBaseQuery<List<ProjectBoardListResponse>>
{
public TaskSectionStatus? Status { get; set; }
}
}

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