Compare commits

...

86 Commits

Author SHA1 Message Date
c488f61a09 refactor: enhance error logging and add installment amount to institution contract view model 2025-12-27 10:26:12 +03:30
a986212834 add from form to verify gateway 2025-12-25 15:11:27 +03:30
649242fc76 refactor: optimize institution contract list retrieval and improve workshop group loading 2025-12-25 14:33:00 +03:30
ad4b0be033 fix: improve error handling and streamline activation process in ActiveAll method 2025-12-25 11:28:29 +03:30
733f39db9f feat: add total amount and one month payment without discount to institution contract 2025-12-24 22:22:49 +03:30
94237434c5 fix: safely deactivate previous institution contract if it exists 2025-12-24 19:30:58 +03:30
2da8bc8a20 Merge remote-tracking branch 'origin/master' 2025-12-24 18:55:19 +03:30
8b217f6cd0 remove maximum length validation for project name in CreateProjectCommandValidator 2025-12-24 18:28:02 +03:30
SamSys
74bd802a3d sms settings frontEnd bug fixed 2025-12-24 18:24:37 +03:30
b58481a36f add employee client api 2025-12-24 18:07:43 +03:30
SamSys
3fd17299f9 fix 2025-12-24 17:20:26 +03:30
SamSys
fc315cc908 change backgrooundTask 2025-12-24 17:18:21 +03:30
SamSys
abe07e1c4b Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-24 16:58:47 +03:30
SamSys
6046f55ece backgroundTask change 2025-12-24 16:58:35 +03:30
d80a36ec35 add: create EmployeeController to manage employee selection for workshops 2025-12-24 16:31:32 +03:30
SamSys
7b648b135e add new logs 2025-12-24 16:22:51 +03:30
SamSys
5998bd212f Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-24 15:56:17 +03:30
SamSys
d77bffabdd add SeriLog on Backgroundtask InstitutionContract 2025-12-24 15:56:00 +03:30
4f0e5a34a4 add: implement reactivation logic for institution contracts and retrieve previous contracts 2025-12-24 15:40:06 +03:30
5faa2062b9 add: implement reactivation logic for contracting parties and associated employers after extension 2025-12-24 13:54:51 +03:30
30b4f52896 add: refactor RollCall application to support asynchronous operations and enhance transaction handling 2025-12-23 20:16:33 +03:30
134466547e add: enhance InstitutionContractRepository to include employer workshops and left work details 2025-12-23 18:54:10 +03:30
a191968c15 add: include Installments in InstitutionContractRepository query 2025-12-23 18:16:50 +03:30
d740c36dc6 add: update ProjectBoardDetailResponse to use TotalTimeMinute and SpentTimeMinute 2025-12-23 17:33:09 +03:30
SamSys
f00fde4084 Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-23 13:47:25 +03:30
SamSys
e8b3700cdf GetList PlanPercentage CountAsync 2025-12-23 13:46:59 +03:30
0ca35e3295 Merge remote-tracking branch 'origin/master' 2025-12-23 11:51:47 +03:30
1a91743916 add: update CalculateDiscount method to include contractStart parameter 2025-12-23 10:50:11 +03:30
SamSys
dd68473150 Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-23 04:18:08 +03:30
SamSys
72e3859d2c next ui upload from wbe completed 2025-12-23 04:17:52 +03:30
46d193b45e Merge branch 'Feature/program-manager/test-upload' 2025-12-22 19:51:49 +03:30
1bfe41418b add: enhance ProjectBoardDetailResponse to include RemainingTime and user time details 2025-12-22 19:51:21 +03:30
6a446d5972 add: implement AutoStopOverTimeTaskSections command and related functionality 2025-12-22 19:13:34 +03:30
Mahan Chamani
acec101c4c Update deployment password in workflow file 2025-12-22 18:24:02 +03:30
SamSys
7d92321d1c Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-22 17:46:31 +03:30
SamSys
19f78a230c change 2025-12-22 17:46:02 +03:30
0e91e6f287 Merge remote-tracking branch 'origin/master' 2025-12-22 17:44:20 +03:30
9df56ee19b Merge branch 'Feature/institution-contract/verify-mannually' 2025-12-22 17:44:04 +03:30
8750604d96 feat: add financial transaction handling during institution contract verification 2025-12-22 17:43:32 +03:30
f27ce460fd feat: integrate RollCallService repository into InstitutionContractApplication and WorkshopApplication 2025-12-22 17:33:37 +03:30
SamSys
934019c6c6 InsuranceNotCreated tab backend changed 2025-12-22 16:34:42 +03:30
SamSys
82bf10c2d5 ServiceAmount GetList 2025-12-22 14:21:01 +03:30
SamSys
19a72ac78d load data and create service percentage 2025-12-22 12:35:51 +03:30
SamSys
9cb42b7cef background job changed 2025-12-22 11:16:50 +03:30
12fab5a9a5 add {id:guid} convention for controllers 2025-12-20 20:57:34 +03:30
20dd8f64f4 add: include OneMonthWithoutTax and OneMonthTax properties in InstitutionContractPrintViewModel 2025-12-20 20:28:08 +03:30
b827493306 refactor: remove unused discount-related classes from IInstitutionContractApplicationpnpm 2025-12-20 20:12:31 +03:30
04c65eae93 Merge branch 'Feature/institution-contract/print'
# Conflicts:
#	CompanyManagment.App.Contracts/InstitutionContract/IInstitutionContractApplication.cs
2025-12-20 20:10:30 +03:30
b4526a4338 Merge branch 'Feature/institution-contract/verify-mannually' 2025-12-20 20:09:13 +03:30
2d879ce80a fix: update workshop identification logic in InstitutionContractApplication 2025-12-20 20:06:28 +03:30
56e79d2099 fix: correct ContractAmountWithTax calculation for old contracts 2025-12-20 19:38:32 +03:30
93891f3837 add one month more details for InstitutionContract.cs print 2025-12-20 19:18:27 +03:30
SamSys
5bdfbc572b add next deploy and contractingParty add to workshop on AndroidApk page 2025-12-20 18:42:53 +03:30
4385a65cbc feat: add manual verification endpoint for institution contracts 2025-12-20 18:27:59 +03:30
722f8dae7c feat: implement manual verification for institution contracts and add signing type handling 2025-12-20 18:27:17 +03:30
SamSys
07113353c4 add uploadFrontEnd btn to AndroidApk page 2025-12-20 16:01:07 +03:30
8c6336b9bd fix: correct IsOldContract logic to properly identify old contracts 2025-12-20 14:35:02 +03:30
20e3d454cf feat: add ContractAmountWithTax calculation and update related references 2025-12-20 13:35:52 +03:30
2bf31db6b2 fix: enhance parameter binding logic for route parameters 2025-12-20 12:05:34 +03:30
7a4a6de84f feat: add OneMonthPrice to institution contract details 2025-12-20 10:56:36 +03:30
4f16d7680c feat: add insurance client list retrieval with pagination and filtering 2025-12-18 10:59:06 +03:30
SamSys
7a10d5ce59 changes 2025-12-18 10:40:11 +03:30
SamSys
3d88feeee7 Clent Add Employee Change to authorizedCanceled 2025-12-17 19:13:47 +03:30
SamSys
f408624463 Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-17 13:25:38 +03:30
SamSys
8296292e49 checkout week finder switch fixed bug 2025-12-17 13:25:24 +03:30
be8deef167 fix: update license context setting for Excel packages 2025-12-17 11:33:40 +03:30
84fb29c8c8 feat: enhance project creation validation and add operation result filter 2025-12-16 20:18:54 +03:30
0969e8a5fd Merge remote-tracking branch 'origin/master' 2025-12-16 19:14:28 +03:30
92e2282381 refactor: change GetAllCodes to return a dictionary for improved structure 2025-12-16 19:13:30 +03:30
SamSys
3b71b7d707 add pmPermission to claim 2025-12-16 18:24:18 +03:30
6123a53f01 fix: update permission check for project board visibility 2025-12-16 17:15:22 +03:30
ec74db17eb Merge branch 'master' into Feature/program-manager/set-permission-board 2025-12-16 17:10:41 +03:30
dc118cf18b Merge branch 'master' of https://github.com/syntax24/OriginalGozareshgir 2025-12-16 17:09:54 +03:30
a11e54c333 Add project board detail endpoint & validation improvements
- Added GET /board/{id:guid} endpoint to ProjectController for detailed project board info.
- Enforced max length of 15 characters for project names in CreateProjectCommandValidator.
- Improved SetTimeProjectCommandHandler: skip zero/negative initial times, removed duplicate error message, and cleaned up formatting.
- Enhanced RollCallApplication to use employee-specific workshop shift settings when available.
2025-12-16 17:09:28 +03:30
SamSys
2383e7a54f Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-16 17:03:02 +03:30
SamSys
2ef1ea3d1a add new permission for workshop 2025-12-16 17:02:40 +03:30
SamSys
ebdc9b1e55 ProgramManager PermissionCodes set 2025-12-16 16:26:15 +03:30
9e5a494881 feat: enhance project board query with skill and user details 2025-12-16 14:18:00 +03:30
2972807c9f feat: add permission handling methods and project board detail query 2025-12-16 12:56:49 +03:30
f7351454f3 feat: implement method to update face embedding names for employees with changed names 2025-12-16 11:05:22 +03:30
b64d0e5ffd feat: add method to update employee full name in FaceEmbeddingService and integrate with RollCallEmployeeApplication 2025-12-16 10:39:51 +03:30
35b7a3a3dd remove documentation file generation from project settings 2025-12-16 09:32:42 +03:30
fe93ef60c9 Merge branch 'master' of https://github.com/syntax24/OriginalGozareshgir 2025-12-15 21:14:06 +03:30
ef865d9c68 Add Skill navigation to Phase/ProjectSection, refactor logic
- Add Skill navigation properties to PhaseSection and ProjectSection, with EF Core mappings and migration for foreign keys and indexes.
- Refactor SetSkillFlags in GetProjectsListQueryHandler for clarity and efficiency; use eager loading for Skill.
- Add HasRemainingTime() to TaskSection and enforce time check in ChangeStatusSectionCommandHandler.
- Optimize EmployeeDocumentsRepository queries; add EmployeeId to WorkshopWithEmployeeDocumentsViewModel.
- Improve CustomExceptionHandler to handle FluentValidation exceptions and return proper status codes.
- Add FluentValidation package reference and perform minor code cleanups.
2025-12-15 20:56:32 +03:30
SamSys
61e35100f9 Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-15 18:49:35 +03:30
SamSys
01d33ff340 add InstitutionContract Confirm Reminder Sms completed 2025-12-15 18:49:13 +03:30
139 changed files with 16980 additions and 1784 deletions

View File

@@ -37,7 +37,7 @@ jobs:
& "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" `
-verb:sync `
-source:contentPath="$publishFolder" `
-dest:contentPath="dadmehrg",computerName="https://171.22.24.15:8172/msdeploy.axd?site=dadmehrg",userName="Administrator",password="R2rNpdnetP3j>q5b18",authType="Basic" `
-dest:contentPath="dadmehrg",computerName="https://171.22.24.15:8172/msdeploy.axd?site=dadmehrg",userName="Administrator",password="R",authType="Basic" `
-allowUntrusted `
-enableRule:AppOffline

View File

@@ -6,6 +6,7 @@
</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

@@ -11,6 +11,7 @@ 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

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

View File

@@ -39,4 +39,15 @@ public static class StaticWorkshopAccounts
/// که کاربر همچنان به کارگاه دسترسی دارد
/// </summary>
public static DateTime ContinuesWorkingDate = new DateTime(2150, 1, 1);
/// <summary>
/// لیستی آی دی نقش هایی که مسئول بیمه کارگاه هستند
/// 7 : بیمه ارشد
/// 8 : بیمه ساده
/// </summary>
public static List<long> InsuranceAccountsRoleIds = [7, 8];
}

View File

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

View File

@@ -1,7 +1,10 @@
using System;
#nullable enable
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;
@@ -21,12 +24,24 @@ public class CustomExceptionHandler : IExceptionHandler
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken cancellationToken)
{
_logger.LogError(
"Error Message: {exceptionMessage}, Time of occurrence {time}",
exception.Message, DateTime.UtcNow);
_logger.LogError(exception,
"Error Message: {exceptionMessage}, Type: {exceptionType}, Time: {time}, Path: {path}, TraceId: {traceId}",
exception.Message,
exception.GetType().FullName,
DateTime.UtcNow,
context.Request.Path,
context.TraceIdentifier);
(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,
@@ -34,6 +49,7 @@ public class CustomExceptionHandler : IExceptionHandler
context.Response.StatusCode = StatusCodes.Status500InternalServerError,
null
),
BadRequestException bre =>
(
exception.Message,
@@ -41,6 +57,7 @@ public class CustomExceptionHandler : IExceptionHandler
context.Response.StatusCode = StatusCodes.Status400BadRequest,
bre.Extra
),
NotFoundException =>
(
exception.Message,
@@ -48,6 +65,7 @@ public class CustomExceptionHandler : IExceptionHandler
context.Response.StatusCode = StatusCodes.Status404NotFound,
null
),
UnAuthorizeException =>
(
exception.Message,
@@ -55,6 +73,7 @@ public class CustomExceptionHandler : IExceptionHandler
context.Response.StatusCode = StatusCodes.Status401Unauthorized,
null
),
_ =>
(
exception.Message,
@@ -73,8 +92,6 @@ 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,329 +18,387 @@ 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 (_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 (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embeddings generated successfully from streams for Employee {EmployeeId}",
employeeId);
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"
};
}
}
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingCreatedAsync(workshopId, employeeId, employeeFullName);
}
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 = 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);
var requestBody = new
{
employeeId,
workshopId,
embedding,
confidence,
metadata = metadata ?? new Dictionary<string, object>()
};
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 response = await httpClient.PostAsJsonAsync("embeddings/refine", requestBody);
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);
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 requestBody = new
{
employeeId,
workshopId,
embedding,
confidence,
metadata = metadata ?? new Dictionary<string, object>()
};
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"
};
}
}
var response = await httpClient.PostAsJsonAsync("embeddings/refine", requestBody);
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 (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embedding refined successfully for Employee {EmployeeId}", employeeId);
var response = await httpClient.DeleteAsync($"embeddings/{workshopId}/{employeeId}");
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingRefinedAsync(workshopId, employeeId);
}
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 = true, Message = "Embedding بهبود یافت" };
}
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 deleting 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 refining 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);
public async Task<OperationResult> DeleteEmbeddingAsync(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}");
var response = await httpClient.DeleteAsync($"embeddings/{workshopId}/{employeeId}");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var embeddingData = JsonSerializer.Deserialize<FaceEmbeddingResponse>(content,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Embedding deleted successfully for Employee {EmployeeId}", employeeId);
_logger.LogInformation("Embedding retrieved successfully for Employee {EmployeeId}", employeeId);
// ارسال اطلاع‌رسانی به سایر سیستم‌ها
if (_notificationService != null)
{
await _notificationService.NotifyEmbeddingDeletedAsync(workshopId, 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"
};
}
}
}
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"
};
}
}
}

View File

@@ -155,6 +155,8 @@ 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));
@@ -252,6 +254,8 @@ public class AccountApplication : IAccountApplication
//);
var userResult =await _pmUserQueryService.GetPmUserDataByAccountId(account.id);
if (command.UserRoles == null)
return operation.Failed("حداقل یک نقش برای کاربر مدیریت پروژه لازم است");
var pmUserRoles = command.UserRoles.Where(x => x > 0).ToList();
//اگر کاربر در پروگرام منیجر قبلا ایجاد شده
@@ -396,6 +400,23 @@ 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)
{
@@ -405,7 +426,7 @@ public class AccountApplication : IAccountApplication
{
positionValue = null;
}
var pmUserId = _pmUserQueryService.GetCurrentPmUserIdFromAccountId(account.id).GetAwaiter().GetResult();
var pmUserId = PmUserData.AccountId > 0 ? PmUserData.AccountId : null;
var authViewModel = new AuthViewModel(account.id, account.RoleId, account.Fullname
, account.Username, account.Mobile, account.ProfilePhoto,
permissions, account.RoleName, account.AdminAreaPermission,

View File

@@ -12,8 +12,14 @@
<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>
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
</ItemGroup>
</Project>

View File

@@ -1,5 +1,6 @@
using _0_Framework.Application;
using _0_Framework.Application.Sms;
using Company.Domain.ContarctingPartyAgg;
using Company.Domain.InstitutionContractAgg;
using Hangfire;
@@ -13,18 +14,22 @@ public class JobSchedulerRegistrator
private readonly IInstitutionContractRepository _institutionContractRepository;
private static DateTime? _lastRunCreateTransaction;
private static DateTime? _lastRunSendMonthlySms;
private readonly ISmsService _smsService;
private readonly ILogger<JobSchedulerRegistrator> _logger;
public JobSchedulerRegistrator(SmsReminder smsReminder, IBackgroundJobClient backgroundJobClient, IInstitutionContractRepository institutionContractRepository)
public JobSchedulerRegistrator(SmsReminder smsReminder, IBackgroundJobClient backgroundJobClient, IInstitutionContractRepository institutionContractRepository, ISmsService smsService, ILogger<JobSchedulerRegistrator> logger)
{
_smsReminder = smsReminder;
_backgroundJobClient = backgroundJobClient;
_institutionContractRepository = institutionContractRepository;
_smsService = smsService;
_logger = logger;
}
public void Register()
{
_logger.LogInformation("hangfire Started");
RecurringJob.AddOrUpdate(
"InstitutionContract.CreateFinancialTransaction",
() => CreateFinancialTransaction(),
@@ -47,6 +52,11 @@ public class JobSchedulerRegistrator
() => SendBlockSms(),
"*/1 * * * *" // هر 1 دقیقه یکبار چک کن
);
RecurringJob.AddOrUpdate(
"InstitutionContract.SendInstitutionContractConfirmSms",
() => SendInstitutionContractConfirmSms(),
"*/1 * * * *" // هر 1 دقیقه یکبار چک کن
);
}
@@ -86,8 +96,8 @@ public class JobSchedulerRegistrator
}
catch (Exception e)
{
//_smsService.Alarm("09114221321", "خطا-ایجاد سند مالی");
await _smsService.Alarm("09114221321", "خطا-ایجاد سند مالی");
}
}
@@ -146,4 +156,15 @@ 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

@@ -0,0 +1,10 @@
using GozareshgirProgramManager.Application.Interfaces;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
public class NullBoardNotificationPublisher:IBoardNotificationPublisher
{
public Task SendProjectStatusChanged(long userId, TaskSectionStatus oldStatus, TaskSectionStatus newStatus, Guid sectionId)
{
throw new NotImplementedException();
}
}

View File

@@ -7,13 +7,47 @@ using BackgroundInstitutionContract.Task;
using BackgroundInstitutionContract.Task.Jobs;
using CompanyManagment.App.Contracts.Hubs;
using CompanyManagment.EFCore.Services;
using GozareshgirProgramManager.Application._Bootstrapper;
using GozareshgirProgramManager.Application.Interfaces;
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 Serilog;
using Serilog.Events;
using Shared.Contracts.PmUser.Queries;
using WorkFlow.Infrastructure.Config;
var logDirectory = @"C:\Logs\Hangfire\BackgroundInstitutionContract\";
if (!Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
Log.Logger = new LoggerConfiguration()
//NO EF Core log
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
//NO DbCommand log
.MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning)
//NO Microsoft Public log
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.WriteTo.File(
path: Path.Combine(logDirectory, "institution-contract-log-.txt"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 30,
shared: true,
outputTemplate:
"{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
).CreateLogger();
var builder = WebApplication.CreateBuilder(args);
var hangfireConnectionString = builder.Configuration.GetConnectionString("HangfireDb");
builder.Services.AddHangfire(x => x.UseSqlServerStorage(hangfireConnectionString));
@@ -26,7 +60,7 @@ builder.Services.AddTransient<ISmsService, SmsService>();
builder.Services.AddTransient<IUidService, UidService>();
builder.Services.AddTransient<IFileUploader, FileUploader>();
builder.Services.Configure<AppSettingConfiguration>(builder.Configuration);
builder.Services.AddScoped<IBoardNotificationPublisher, NullBoardNotificationPublisher>();
#region MongoDb
var mongoConnectionSection = builder.Configuration.GetSection("MongoDb");
@@ -38,17 +72,28 @@ 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();
builder.Services.AddHttpContextAccessor();
builder.Services.AddSignalR();
builder.Host.UseSerilog();
Log.Information("SERILOG STARTED SUCCESSFULLY");
var app = builder.Build();
app.MapHub<SendSmsHub>("/sendSmsHub");
app.MapHangfireDashboard();

View File

@@ -25,8 +25,8 @@
//mahan Docker
//"MesbahDb": "Data Source=localhost,5069;Initial Catalog=mesbah_db;User ID=sa;Password=YourPassword123;TrustServerCertificate=True;",
//"HangfireDb": "Data Source=.;Initial Catalog=hangfire_db;Integrated Security=True;TrustServerCertificate=true;",
"HangfireDb": "Data Source=185.208.175.186;Initial Catalog=hangfire_db;Persist Security Info=False;User ID=ir_db;Password=R2rNp[170]18[3019]#@ATt;TrustServerCertificate=true;"
"HangfireDb": "Data Source=.;Initial Catalog=hangfire_db;Integrated Security=True;TrustServerCertificate=true;",
//"HangfireDb": "Data Source=185.208.175.186;Initial Catalog=hangfire_db;Persist Security Info=False;User ID=ir_db;Password=R2rNp[170]18[3019]#@ATt;TrustServerCertificate=true;"
},
"GoogleRecaptchaV3": {

View File

@@ -76,6 +76,7 @@ public interface IEmployeeRepository : IRepository<long, Employee>
#region Api
Task<List<EmployeeSelectListViewModel>> GetSelectList(string searchText,long id);
Task<List<GetEmployeeListViewModel>> GetList(GetEmployeeListSearchModel searchModel);
Task<List<GetClientEmployeeListViewModel>> GetClientEmployeeList(GetClientEmployeeListSearchModel searchModel, long workshopId);
#endregion

View File

@@ -56,7 +56,7 @@ public interface IInstitutionContractRepository : IRepository<long, InstitutionC
void UpdateStatusIfNeeded(long institutionContractId);
Task<GetInstitutionVerificationDetailsViewModel> GetVerificationDetails(Guid id);
Task<InstitutionContract> GetByPublicIdAsync(Guid id);
InstitutionContractDiscountResponse CalculateDiscount(InstitutionContractSetDiscountRequest request);
InstitutionContractDiscountResponse CalculateDiscount(InstitutionContractSetDiscountRequest request,string contractStart = null);
InstitutionContractDiscountResponse ResetDiscountCreate(InstitutionContractResetDiscountForCreateRequest request);
@@ -140,6 +140,11 @@ 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
@@ -154,4 +159,5 @@ public interface IInstitutionContractRepository : IRepository<long, InstitutionC
#endregion
Task<long> GetIdByInstallmentId(long installmentId);
Task<InstitutionContract> GetPreviousContract(long currentInstitutionContractId);
}

View File

@@ -98,6 +98,11 @@ public class InstitutionContract : EntityBase
// مبلغ قرارداد
public double ContractAmount { get; private set; }
public double ContractAmountWithTax => !IsOldContract ? ContractAmount + ContractAmountTax
: ContractAmount;
public double ContractAmountTax => ContractAmount*0.10;
//خسارت روزانه
public double DailyCompenseation { get; private set; }
@@ -159,6 +164,10 @@ 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 = [];
@@ -262,6 +271,10 @@ public class InstitutionContract : EntityBase
{
WorkshopGroup = null;
}
public void SetSigningType(InstitutionContractSigningType signingType)
{
SigningType = signingType;
}
}
public class InstitutionContractAmendment : EntityBase

View File

@@ -10,13 +10,15 @@ 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) : base(workshopName, hasRollCallPlan,
int personnelCount, double price,long institutionContractWorkshopGroupId,
InstitutionContractWorkshopGroup workshopGroup,long workshopId,long initialWorkshopId) : 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,4 +37,10 @@ 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);
Services.InsuranceInPerson,PersonnelCount,Price,InstitutionContractWorkshopGroupId,WorkshopGroup,workshopId,id);
WorkshopCurrent.SetEmployers(Employers.Select(x=>x.EmployerId).ToList());
}

View File

@@ -1,7 +1,9 @@
using _0_Framework.Domain;
using _0_Framework.Application;
using _0_Framework.Domain;
using CompanyManagment.App.Contracts.InstitutionPlan;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Company.Domain.InstitutionPlanAgg;
@@ -26,4 +28,18 @@ public interface IPlanPercentageRepository : IRepository<long, PlanPercentage>
/// <param name="command"></param>
/// <returns></returns>
InstitutionPlanViewModel GetInstitutionPlanForWorkshop(WorkshopTempViewModel command);
/// <summary>
/// دریافت دیتای مودال ایجاد
/// </summary>
/// <returns></returns>
Task<CreateServiceAmountDto> GetCreateModalData();
/// <summary>
/// دریافت لیست مبالغ سرویس ها
/// </summary>
/// <param name="searchModel"></param>
/// <returns></returns>
Task<PagedResult<InstitutionPlanListDto>> GetList(
InstitutionPlanSearchModel searchModel);
}

View File

@@ -73,6 +73,7 @@ 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

@@ -316,7 +316,10 @@ public class Workshop : EntityBase
IsStaticCheckout = isStaticCheckout;
}
public void AddContractingPartyId(long contractingPartyId)
{
ContractingPartyId = contractingPartyId;
}
public void Active(string archiveCode)
{
this.IsActive = true;

View File

@@ -26,7 +26,7 @@ public class CustomizeWorkshopGroupSettingExcelGenerator
{
public static byte[] Generate(List<CustomizeWorkshopGroupExcelViewModel> groups)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
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.LicenseContext = LicenseContext.NonCommercial;
OfficeOpenXml.ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
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)
{
OfficeOpenXml.ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
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.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
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.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
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.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
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.LicenseContext = LicenseContext.NonCommercial;
OfficeOpenXml.ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
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.LicenseContext = LicenseContext.NonCommercial;
OfficeOpenXml.ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
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.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
if (file == null || file.Length == 0)
{

View File

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

View File

@@ -60,7 +60,7 @@ public interface IEmployeeApplication
/// <returns></returns>
Task<OperationResult<EmployeeByNationalCodeInWorkshopViewModel>>
ValidateCreateEmployeeClientByNationalCodeAndWorkshopId(string nationalCode,
string birthDate, long workshopId);
string birthDate,bool authorizedCanceled, long workshopId);
/// <summary>
/// پرسنل هایی که در کارگاهی از سمت ادمین شروع به کار کرده اند
@@ -94,7 +94,42 @@ public interface IEmployeeApplication
/// </summary>
/// <returns></returns>
Task<List<GetEmployeeListViewModel>> GetList(GetEmployeeListSearchModel searchModel);
/// <summary>
/// لیست کل پرسنل کلاینت
/// </summary>
/// <param name="searchModel"></param>
/// <param name="workshopId"></param>
/// <returns></returns>
Task<List<GetClientEmployeeListViewModel>> GetClientEmployeeList(GetClientEmployeeListSearchModel searchModel, long workshopId);
#endregion
}
public class GetClientEmployeeListSearchModel
{
}
public class GetClientEmployeeListViewModel
{
public string FullName { get; set; }
public long EmployeeId { get; set; }
public long WorkshopId { get; set; }
public long PersonnelCode { get; set; }
public string MaritalStatus { get; set; }
public string NationalCode { get; set; }
public string IdNumber { get; set; }
public string DateOfBirthFa { get; set; }
public string FatherName { get; set; }
public int ChildrenCount { get; set; }
public string LastStartInsuranceWork { get; set; }
public string LastLeftInsuranceWork { get; set; }
public string LastStartContractWork { get; set; }
public string LastLeftContractWork { get; set; }
public bool HasContractLeftWork { get; set; }
public bool HasInsuranceLeftWork { get; set; }
public bool LeftWorkCompletely { get; set; }
public bool PendingStartWork { get; set; }
public bool PendingLeftWork { get; set; }
}

View File

@@ -13,5 +13,6 @@ 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

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

View File

@@ -91,6 +91,11 @@ public class GetInstitutionContractListItemsViewModel
public bool IsInPersonContract { get; set; }
public bool IsOldContract { get; set; }
/// <summary>
/// مبلغ قسط
/// </summary>
public double InstallmentAmount { get; set; }
}
public class InstitutionContractListWorkshop

View File

@@ -7,7 +7,6 @@ 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;
@@ -260,154 +259,13 @@ public interface IInstitutionContractApplication
/// <returns></returns>
Task<InstitutionContractPrintViewModel> PrintOneAsync(long id);
Task<OperationResult> SetPendingWorkflow(long entityId);
Task<OperationResult> SetPendingWorkflow(long entityId,InstitutionContractSigningType signingType);
Task<long> GetIdByInstallmentId(long installmentId);
}
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; }
/// <param name="institutionContractId"></param>
/// <returns></returns>
Task<OperationResult> VerifyInstitutionContractManually(long institutionContractId);
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

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

View File

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

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

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

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

@@ -18,6 +18,16 @@ public class InstitutionContractPaymentOneTimeViewModel
/// </summary>
public string PaymentAmount { get; set; }
/// <summary>
/// مجموع مبالغ بدون تخفیف
/// </summary>
public string TotalAmountWithoutDiscount { get; set; }
/// <summary>
/// مبلغ یک ماه بدون تخفیف
/// </summary>
public string OneMonthPaymentWithoutDiscount { get; set; }
public string DiscountedAmount { get; set; }
public int DiscountPercetage { get; set; }
}

View File

@@ -0,0 +1,28 @@
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; }
public string OneMonthWithoutTax { get; set; }
public string OneMonthTax { get; set; }
}

View File

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

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

View File

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

View File

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

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

@@ -76,5 +76,7 @@ public class InstitutionContractViewModel
public bool IsInstallment { get; set; }
public InstitutionContractVerificationStatus VerificationStatus { get; set; }
public InstitutionContractSigningType? SigningType { get; set; }
public List<InstitutionContractInstallmentViewModel> InstallmentList { get; set; }
}

View File

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

@@ -0,0 +1,51 @@
namespace CompanyManagment.App.Contracts.InstitutionPlan;
public class CreateServiceAmountDto
{
/// <summary>
/// آی دی
/// </summary>
public long Id { get; set; }
/// <summary>
/// قرارداد و تصفیه
/// درصد از مزد روزانه
/// string
/// </summary>
public string ContractAndCheckoutPercentStr { get; set; }
/// <summary>
/// بیمه
/// درصد از مزد روزانه
/// string
/// </summary>
public string InsurancePercentStr { get; set; }
/// <summary>
/// حضورغباب
/// درصد از مزد روزانه
/// string
/// </summary>
public string RollCallPercentStr { get; set; }
/// <summary>
/// فیش غیر رسمی
/// درصد از مزد روزانه
/// string
/// </summary>
public string CustomizeCheckoutPercentStr { get; set; }
/// <summary>
/// خدمات حضوری قرداد و تصفیه
/// درصد از مزد روزانه
/// string
/// </summary>
public string ContractAndCheckoutInPersonPercentStr { get; set; }
/// <summary>
/// خدمات حضوری بیمه
/// درصد از مزد روزانه
/// string
/// </summary>
public string InsuranceInPersonPercentStr { get; set; }
}

View File

@@ -1,6 +1,7 @@
using System.Collections.Generic;
using _0_Framework.Application;
using _0_Framework.Application;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CompanyManagment.App.Contracts.InstitutionPlan;
@@ -34,4 +35,27 @@ public interface IInstitutionPlanApplication
/// <param name="command"></param>
/// <returns></returns>
InstitutionPlanViewModel GetInstitutionPlanForWorkshop(WorkshopTempViewModel command);
/// <summary>
/// دریافت دیتای درصد سرویس برای مودال ایجاد
/// </summary>
/// <returns></returns>
Task<CreateServiceAmountDto> GetCreateModalData();
/// <summary>
/// ایجاد درصد سرویس
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
Task<OperationResult> CreateInstitutionPlanPercentage(CreateServiceAmountDto command);
/// <summary>
/// دریافت لیست مبالغ سرویس ها
/// </summary>
/// <param name="searchModel"></param>
/// <returns></returns>
Task<PagedResult<InstitutionPlanListDto>> GetList(
InstitutionPlanSearchModel searchModel);
}

View File

@@ -0,0 +1,84 @@
namespace CompanyManagment.App.Contracts.InstitutionPlan;
public class InstitutionPlanListDto
{
/// <summary>
/// تعداد پرسنل
/// </summary>
public int CountPerson { get; set; }
/// <summary>
/// مبلغ قرارداد و تصفیه
/// </summary>
public string ContractAndCheckout { get; set; }
/// <summary>
/// مبلغ بیمه
/// </summary>
public string Insurance { get; set; }
/// <summary>
/// مبلغ حضورغباب
/// </summary>
public string RollCall { get; set; }
/// <summary>
/// مبلغ فیش غیر رسمی
/// </summary>
public string CustomizeCheckout { get; set; }
/// <summary>
/// مبلغ خدمات حضوری قرداد و تصفیه
/// </summary>
public string ContractAndCheckoutInPerson { get; set; }
/// <summary>
/// مبلغ خدمات حضوری بیمه
/// </summary>
public string InsuranceInPerson { get; set; }
#region Total
/// <summary>
/// مبلغ کل خدمات حضوری
/// </summary>
public string InPersonSumAmountStr { get; set; }
/// <summary>
/// مبلغ کل خدمات آنلاین
/// </summary>
public string OnlineOnlySumAmountStr { get; set; }
/// <summary>
/// مبلغ کل خدمات حضوری و آنلاین
/// </summary>
public string OnlineAndInPersonSumAmountStr { get; set; }
/// <summary>
/// مبلغ کل خدمات حضوری و آنلاین
/// double
/// </summary>
public double OnlineAndInPersonSumAmountDouble { get; set; }
/// <summary>
/// مبلغ کل خدمات حضوری
/// double
/// </summary>
public double InPersonSumAmountDouble { get; set; }
/// <summary>
/// مبلغ کل خدمات آنلاین
/// double
/// </summary>
public double OnlineOnlySumAmountDouble { get; set; }
#endregion
}

View File

@@ -0,0 +1,11 @@
using _0_Framework.Application;
namespace CompanyManagment.App.Contracts.InstitutionPlan;
public class InstitutionPlanSearchModel : PaginationRequest
{
/// <summary>
/// تعداد پرسنل برای جستجو
/// </summary>
public int CountPerson { get; set; }
}

View File

@@ -90,8 +90,27 @@ 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

@@ -124,7 +124,7 @@ namespace CompanyManagment.App.Contracts.RollCall
/// <param name="workshopId"></param>
/// <param name="command"></param>
/// <returns></returns>
OperationResult RecalculateValues(long workshopId, List<ReCalculateRollCallValues> command);
Task<OperationResult> RecalculateValues(long workshopId, List<ReCalculateRollCallValues> command);
}
public class ReCalculateRollCallValues
{

View File

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

View File

@@ -25,6 +25,7 @@ using Microsoft.EntityFrameworkCore.Query;
using Company.Domain.CheckoutAgg;
using Company.Domain.CustomizeCheckoutAgg;
using Company.Domain.CustomizeCheckoutTempAgg;
using Company.Domain.RollCallAgg;
using CompanyManagment.EFCore.Repository;
@@ -38,7 +39,8 @@ public class CustomizeWorkshopSettingsApplication(ICustomizeWorkshopSettingsRepo
IRollCallApplication rollCallAppllication,
ICheckoutRepository checkoutRepository,
ICustomizeCheckoutRepository customizeCheckoutRepository,
ICustomizeCheckoutTempRepository customizeCheckoutTempRepository)
ICustomizeCheckoutTempRepository customizeCheckoutTempRepository,
IRollCallRepository rollCallRepository)
: ICustomizeWorkshopSettingsApplication
{
private readonly ICustomizeWorkshopSettingsRepository _customizeWorkshopSettingsRepository = customizeWorkshopSettingsRepository;
@@ -53,6 +55,7 @@ public class CustomizeWorkshopSettingsApplication(ICustomizeWorkshopSettingsRepo
private readonly ICheckoutRepository _checkoutRepository = checkoutRepository;
private readonly ICustomizeCheckoutRepository _customizeCheckoutRepository = customizeCheckoutRepository;
private readonly ICustomizeCheckoutTempRepository _customizeCheckoutTempRepository = customizeCheckoutTempRepository;
private readonly IRollCallRepository _rollCallRepository = rollCallRepository;
#region RollCallShifts
@@ -822,14 +825,19 @@ public class CustomizeWorkshopSettingsApplication(ICustomizeWorkshopSettingsRepo
var notSelectedEmployeeSettings = employeeSettings.Where(x => !selectedEmployeesIds.Contains(x.EmployeeId));
var weeklyOffDays = command.OffDayOfWeeks?.Select(x => new WeeklyOffDay(x)).ToList() ?? [];
using var transaction = new TransactionScope();
var weeklyOffDays = command.OffDayOfWeeks?
.Select(x => new WeeklyOffDay(x)).ToList() ?? [];
using var rollCallTransaction = _rollCallRepository.BeginTransactionAsync()
.GetAwaiter().GetResult();
entity.EditSimpleAndOverwriteOnEmployee(command.Name, selectedEmployeesIds, groupSettingsShifts, command.WorkshopShiftStatus,
command.IrregularShift, breakTime, isChanged, command.HolidayWork, rotatingShift, weeklyOffDays);
if (reCalculateCommand.Count > 0)
{
var result = _rollCallApplication.RecalculateValues(workshopSettings.WorkshopId, reCalculateCommand);
var result = _rollCallApplication
.RecalculateValues(workshopSettings.WorkshopId, reCalculateCommand)
.GetAwaiter().GetResult();
if (result.IsSuccedded == false)
{
@@ -844,7 +852,7 @@ public class CustomizeWorkshopSettingsApplication(ICustomizeWorkshopSettingsRepo
_customizeWorkshopGroupSettingsRepository.SaveChanges();
transaction.Complete();
rollCallTransaction.Commit();
return op.Succcedded();
}
public OperationResult EditSimpleRollCallEmployeeSetting(EditCustomizeEmployeeSettings command,
@@ -1043,7 +1051,9 @@ public class CustomizeWorkshopSettingsApplication(ICustomizeWorkshopSettingsRepo
_customizeWorkshopGroupSettingsRepository.SaveChanges();
if (reCalculateCommand.Count > 0)
{
var result = _rollCallApplication.RecalculateValues(command.WorkshopId, reCalculateCommand);
var result = _rollCallApplication
.RecalculateValues(command.WorkshopId, reCalculateCommand)
.GetAwaiter().GetResult();
if (result.IsSuccedded == false)
{

View File

@@ -1263,7 +1263,7 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
System.IO.File.WriteAllBytes(filePath, bytes);
}
public async Task<OperationResult<EmployeeByNationalCodeInWorkshopViewModel>>
ValidateCreateEmployeeClientByNationalCodeAndWorkshopId(string nationalCode, string birthDate, long workshopId)
ValidateCreateEmployeeClientByNationalCodeAndWorkshopId(string nationalCode, string birthDate,bool authorizedCanceled, long workshopId)
{
var op = new OperationResult<EmployeeByNationalCodeInWorkshopViewModel>();
@@ -1279,65 +1279,25 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
var employee = _EmployeeRepository.GetByNationalCodeIgnoreQueryFilter(nationalCode);
if (employee == null)
if (employee == null && !authorizedCanceled)
{
var personalInfo = await _uidService.GetPersonalInfo(nationalCode, birthDate);
if (personalInfo.ResponseContext.Status.Code == 14)
if (personalInfo != null)
{
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید", new EmployeeByNationalCodeInWorkshopViewModel() { AuthorizedCanceled = true });
}
if (personalInfo.ResponseContext.Status.Code != 0)
{
return op.Failed("کد ملی و تاریخ تولد با هم همخانی ندارند");
}
if (personalInfo.ResponseContext.Status.Code == 14)
{
return op.Failed("سامانه احراز هویت در دسترس نمیباشد لطفا اطلاعات پرسنل را به صورت دستی وارد کنید", new EmployeeByNationalCodeInWorkshopViewModel() { AuthorizedCanceled = true });
}
if (personalInfo.ResponseContext.Status.Code != 0)
{
return op.Failed("کد ملی و تاریخ تولد با هم همخانی ندارند");
}
var basicInfo = personalInfo.BasicInformation;
var identityInfo = personalInfo.IdentificationInformation;
DateTime apiBirthDate = identityInfo.BirthDate.ToGeorgianDateTime();
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 dateOfIssue = new DateTime(1922, 1, 1);
var gender = basicInfo.GenderEnum switch
{
@@ -1348,31 +1308,90 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
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)
@@ -1710,5 +1729,10 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return await _EmployeeRepository.GetList(searchModel);
}
public async Task<List<GetClientEmployeeListViewModel>> GetClientEmployeeList(GetClientEmployeeListSearchModel searchModel, long workshopId)
{
return await _EmployeeRepository.GetClientEmployeeList(searchModel, workshopId);
}
#endregion
}

View File

@@ -22,6 +22,7 @@ using Company.Domain.InstitutionContractAgg;
using Company.Domain.LeftWorkAgg;
using Company.Domain.PaymentTransactionAgg;
using Company.Domain.RepresentativeAgg;
using Company.Domain.RollCallServiceAgg;
using Company.Domain.TemporaryClientRegistrationAgg;
using Company.Domain.WorkshopAgg;
using CompanyManagment.App.Contracts.FinancialInvoice;
@@ -59,6 +60,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
private readonly IFinancialInvoiceRepository _financialInvoiceRepository;
private readonly IPaymentGateway _paymentGateway;
private readonly IPaymentTransactionRepository _paymentTransactionRepository;
private readonly IRollCallServiceRepository _rollCallServiceRepository;
public InstitutionContractApplication(IInstitutionContractRepository institutionContractRepository,
@@ -70,7 +72,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
IFinancialStatmentRepository financialStatmentRepository, IContactInfoApplication contactInfoApplication,
IAccountApplication accountApplication, ISmsService smsService, IUidService uidService,
IFinancialInvoiceRepository financialInvoiceRepository, IHttpClientFactory httpClientFactory,
IPaymentTransactionRepository paymentTransactionRepository)
IPaymentTransactionRepository paymentTransactionRepository, IRollCallServiceRepository rollCallServiceRepository)
{
_institutionContractRepository = institutionContractRepository;
_contractingPartyRepository = contractingPartyRepository;
@@ -88,6 +90,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
_uidService = uidService;
_financialInvoiceRepository = financialInvoiceRepository;
_paymentTransactionRepository = paymentTransactionRepository;
_rollCallServiceRepository = rollCallServiceRepository;
_paymentGateway = new SepehrPaymentGateway(httpClientFactory);
}
@@ -1537,7 +1540,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
return (await _institutionContractRepository.PrintAllAsync([id])).FirstOrDefault();
}
public async Task<OperationResult> SetPendingWorkflow(long entityId)
public async Task<OperationResult> SetPendingWorkflow(long entityId,InstitutionContractSigningType signingType)
{
var op = new OperationResult();
var institutionContract = await _institutionContractRepository.GetIncludeWorkshopDetailsAsync(entityId);
@@ -1551,15 +1554,64 @@ 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();
var accountId = _contractingPartyRepository
.GetAccountByPersonalContractingParty(institutionContract.ContractingPartyId).Id;
foreach (var createdWorkshop in initialCreatedWorkshops)
{
if (currentWorkshops.Any(x => x.WorkshopId == createdWorkshop.WorkshopId))
{
//rollcall serviecs
if (createdWorkshop.Services.RollCall)
{
var ActiveService = _rollCallServiceRepository.GetActiveServiceByWorkshopId(createdWorkshop.WorkshopId!.Value);
var startTime = institutionContract.ContractStartGr;
var endTime = institutionContract.ContractEndGr;
if (ActiveService != null)
{
if (ActiveService.EndService> startTime)
{
startTime = ActiveService.EndService;
}
}
var rollCallService = new RollCallService("BasedOnIC",
startTime, endTime, createdWorkshop.WorkshopId.Value,accountId,createdWorkshop.PersonnelCount,
0,"12");
await _rollCallServiceRepository.CreateAsync(rollCallService);
}
}
else
{
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();
}
else
{
institutionContract.SetPendingWorkflow();
}
institutionContract.SetSigningType(signingType);
var previousInstitutionContract = await _institutionContractRepository
.GetPreviousContract(institutionContract.id);
previousInstitutionContract?.DeActive();
ReActiveAllAfterCreateNew(institutionContract.ContractingPartyId);
await _institutionContractRepository.SaveChangesAsync();
return op.Succcedded();
}
@@ -1569,6 +1621,42 @@ 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

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using _0_Framework.Application;
using Company.Domain.InstitutionPlanAgg;
using CompanyManagment.App.Contracts.InstitutionPlan;
@@ -84,4 +85,73 @@ public class InstitutionPlanApplication : IInstitutionPlanApplication
{
return _planPercentageRepository.GetInstitutionPlanForWorkshop(command);
}
#region ForApi
public async Task<CreateServiceAmountDto> GetCreateModalData()
{
return await _planPercentageRepository.GetCreateModalData();
}
public async Task<OperationResult> CreateInstitutionPlanPercentage(CreateServiceAmountDto command)
{
var op = new OperationResult();
if (string.IsNullOrWhiteSpace(command.ContractAndCheckoutInPersonPercentStr) || command.ContractAndCheckoutInPersonPercentStr == "0" ||
string.IsNullOrWhiteSpace(command.ContractAndCheckoutPercentStr) || (command.ContractAndCheckoutPercentStr == "0" ||
string.IsNullOrWhiteSpace(command.CustomizeCheckoutPercentStr) || command.CustomizeCheckoutPercentStr == "0" ||
string.IsNullOrWhiteSpace(command.InsuranceInPersonPercentStr) || command.InsuranceInPersonPercentStr == "0" ||
string.IsNullOrWhiteSpace(command.InsurancePercentStr) || command.InsurancePercentStr == "0" ||
string.IsNullOrWhiteSpace(command.RollCallPercentStr) || command.RollCallPercentStr == "0"))
return op.Failed("هیچ یک از فیلدها نمیتوانند صفر باشند");
int contractAndCheckoutInPersonPercent = 0;
int contractAndCheckoutPercent = 0;
int customizeCheckoutPercent = 0;
int insuranceInPersonPercent = 0;
int insurancePercent = 0;
int rollCallPercent = 0;
try
{
contractAndCheckoutInPersonPercent = Convert.ToInt32(command.ContractAndCheckoutInPersonPercentStr);
contractAndCheckoutPercent = Convert.ToInt32(command.ContractAndCheckoutPercentStr);
customizeCheckoutPercent = Convert.ToInt32(command.CustomizeCheckoutPercentStr);
insuranceInPersonPercent = Convert.ToInt32(command.InsuranceInPersonPercentStr);
insurancePercent = Convert.ToInt32(command.InsurancePercentStr);
rollCallPercent = Convert.ToInt32(command.RollCallPercentStr);
}
catch (Exception e)
{
return op.Failed("لطفا عدد معتبر وارد کنید");
}
var firstPlan =await _planPercentageRepository.GetCreateModalData();
if (firstPlan != null)
{
var planPercentage = _planPercentageRepository.Get(firstPlan.Id);
planPercentage.Edit(contractAndCheckoutPercent, insurancePercent, rollCallPercent, customizeCheckoutPercent, contractAndCheckoutInPersonPercent, insuranceInPersonPercent);
_planPercentageRepository.SaveChanges();
}
else
{
var create = new PlanPercentage(contractAndCheckoutPercent, insurancePercent, rollCallPercent,
customizeCheckoutPercent, contractAndCheckoutInPersonPercent, insuranceInPersonPercent);
await _planPercentageRepository.CreateAsync(create);
await _planPercentageRepository.SaveChangesAsync();
}
return op.Succcedded();
}
public async Task<PagedResult<InstitutionPlanListDto>> GetList(InstitutionPlanSearchModel searchModel)
{
return await _planPercentageRepository.GetList(searchModel);
}
#endregion
}

View File

@@ -2371,6 +2371,11 @@ 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,6 +384,7 @@ public class RollCallApplication : IRollCallApplication
var workshopSettings = _customizeWorkshopSettingsRepository.GetBy(command.WorkshopId);
var employeeSettings =
_customizeWorkshopEmployeeSettingsRepository.GetByEmployeeIdAndWorkshopIdIncludeGroupSettings(
command.WorkshopId, command.EmployeeId)?.WorkshopShiftStatus;
@@ -787,7 +788,7 @@ public class RollCallApplication : IRollCallApplication
return _rollCallRepository.CheckRepeat(employeeId, workshopId);
}
public OperationResult RecalculateValues(long workshopId, List<ReCalculateRollCallValues> commands)
public async Task<OperationResult> RecalculateValues(long workshopId, List<ReCalculateRollCallValues> commands)
{
var operationResult = new OperationResult();
try
@@ -811,24 +812,43 @@ public class RollCallApplication : IRollCallApplication
var oldestDate = commands.MinBy(x => x.FromDate).FromDate.ToGeorgianDateTime();
var allRollCalls = _rollCallRepository
var allRollCalls = await _rollCallRepository
.GetRollCallsUntilNowWithWorkshopIdEmployeeIds(workshopId, commands.Select(x => x.EmployeeId).ToList(),
oldestDate).GetAwaiter().GetResult();
oldestDate);
var rollCalls =
commands.SelectMany(command =>
allRollCalls.Where(x =>
x.EmployeeId == command.EmployeeId &&
x.ShiftDate >= command.FromDate.ToGeorgianDateTime()
)
);
foreach (var command in commands)
foreach (var rollCall in rollCalls)
{
var rollCalls = allRollCalls
.Where(x => x.EmployeeId == command.EmployeeId && x.ShiftDate >= command.FromDate.ToGeorgianDateTime()).ToList();
rollCall.ClearTimeDiff();
foreach (var rollCall in rollCalls)
{
rollCall.ClearTimeDiff();
_rollCallRepository.SaveChanges();
rollCall.SetEndDateTime(rollCall.EndDate!.Value, _rollCallDomainService);
}
await _rollCallRepository.SaveChangesAsync();
rollCall.SetEndDateTime(
rollCall.EndDate!.Value,
_rollCallDomainService
);
}
_rollCallRepository.SaveChanges();
// foreach (var command in commands)
// {
// var rollCalls = allRollCalls
// .Where(x => x.EmployeeId == command.EmployeeId && x.ShiftDate >= command.FromDate.ToGeorgianDateTime()).ToList();
//
// foreach (var rollCall in rollCalls)
// {
// rollCall.ClearTimeDiff();
// await _rollCallRepository.SaveChangesAsync();
// rollCall.SetEndDateTime(rollCall.EndDate!.Value, _rollCallDomainService);
// }
// }
await _rollCallRepository.SaveChangesAsync();
return operationResult.Succcedded();
}

View File

@@ -11,6 +11,7 @@ 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;
@@ -23,7 +24,9 @@ public class RollCallEmployeeApplication : IRollCallEmployeeApplication
private readonly ILeftWorkRepository _leftWorkRepository;
private readonly IRollCallEmployeeStatusRepository _rollCallEmployeeStatusRepository;
private readonly IWebHostEnvironment _webHostEnvironment;
public RollCallEmployeeApplication(IRollCallEmployeeRepository rollCallEmployeeRepository, IEmployeeRepository employeeRepository, IRollCallEmployeeStatusApplication rollCallEmployeeStatusApplication, ILeftWorkRepository leftWorkRepository, IRollCallEmployeeStatusRepository rollCallEmployeeStatusRepository, IWebHostEnvironment webHostEnvironment)
private readonly IFaceEmbeddingService _faceEmbeddingService;
public RollCallEmployeeApplication(IRollCallEmployeeRepository rollCallEmployeeRepository, IEmployeeRepository employeeRepository, IRollCallEmployeeStatusApplication rollCallEmployeeStatusApplication, ILeftWorkRepository leftWorkRepository, IRollCallEmployeeStatusRepository rollCallEmployeeStatusRepository, IWebHostEnvironment webHostEnvironment, IFaceEmbeddingService faceEmbeddingService)
{
_rollCallEmployeeRepository = rollCallEmployeeRepository;
_employeeRepository = employeeRepository;
@@ -31,6 +34,7 @@ public class RollCallEmployeeApplication : IRollCallEmployeeApplication
_leftWorkRepository = leftWorkRepository;
_rollCallEmployeeStatusRepository = rollCallEmployeeStatusRepository;
_webHostEnvironment = webHostEnvironment;
_faceEmbeddingService = faceEmbeddingService;
}
public OperationResult Create(CreateRollCallEmployee command)
@@ -213,9 +217,18 @@ 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

@@ -1092,7 +1092,9 @@ public class WorkshopAppliction : IWorkshopApplication
Amount = 1000,
MaxPersonValid = 500,
Duration = "12",
HasCustomizeCheckoutService = command.HasCustomizeCheckoutService
HasCustomizeCheckoutService = command.HasCustomizeCheckoutService,
StartService = institutionContract.ContractStartGr,
};
_rollCallServiceApplication.Create(commandSave);
}

View File

@@ -34,6 +34,10 @@ 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)
@@ -45,5 +49,10 @@ public class InstitutionContractMapping : IEntityTypeConfiguration<InstitutionCo
builder.HasMany(x => x.Amendments).WithOne(x => x.InstitutionContract)
.HasForeignKey(x => x.InstitutionContractId);
builder.Ignore(x => x.ContractAmountWithTax);
builder.Ignore(x => x.ContractAmountTax);
builder.Ignore(x => x.ContractAmountTax);
}
}

View File

@@ -0,0 +1,29 @@
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,6 +3462,10 @@ 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

@@ -1194,41 +1194,99 @@ 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 employeeClientTemp = _companyContext.EmployeeClientTemps.Where(x => workshops.Contains(x.WorkshopId));
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 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()
});
// 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 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)
@@ -1347,33 +1405,37 @@ public class EmployeeDocumentsRepository : RepositoryBase<long, EmployeeDocument
// ترکیب کل لیست‌ها در حافظه
var allActiveEmployees = activeEmployees
.Concat(clientTemp)
.Concat(leftWorkTemp);
.Concat(leftWorkTemp).ToList();
var contractingPartyIds = _companyContext.WorkshopEmployers.Where(x => workshops.Contains(x.WorkshopId))
.Include(x => x.Employer).Select(x => x.Employer.ContractingPartyId).Distinct();
.Include(x => x.Employer).Select(x => x.Employer.ContractingPartyId).Distinct().ToList();
var accountIds = await _companyContext.ContractingPartyAccounts
.Where(x => contractingPartyIds.Contains(x.PersonalContractingPartyId)).Select(x => x.AccountId)
.ToListAsync();
var query = _companyContext.EmployeeDocuments
.Where(x => workshops.Contains(x.WorkshopId) &&
(allActiveEmployees.Any(y => y.WorkshopId == x.WorkshopId && y.EmployeeId == x.EmployeeId)))
var query =await _companyContext.EmployeeDocuments
.Where(x => workshops.Contains(x.WorkshopId))
.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()
});
EmployeesWithoutDocumentCount = x.Count(),
EmployeeId = x.First().EmployeeId
}).ToListAsync();
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 => query.Any(y => y.WorkshopId == x.WorkshopId))
.Where(x => resWorkshopIds.Contains(x.WorkshopId))
.GroupBy(x => x.WorkshopId).Select(x => x.FirstOrDefault()).ToListAsync();
var result = await query.ToListAsync();
var result = query;
result.ForEach(x =>

View File

@@ -1062,5 +1062,116 @@ public class EmployeeRepository : RepositoryBase<long, Employee>, IEmployeeRepos
}
#endregion
public Task<List<GetClientEmployeeListViewModel>> GetClientEmployeeList(GetClientEmployeeListSearchModel searchModel, long workshopId)
{
// var leftDate = Tools.GetUndefinedDateTime();
//
// var personnelCodes = _context.PersonnelCodeSet.Include(x => x.Employee)
// .ThenInclude(x => x.EmployeeChildrenList).IgnoreQueryFilters().Where(x => x.WorkshopId == workshopId).ToList();
//
// var contractLeftWork =
// _context.LeftWorkList.Where(x => x.WorkshopId == workshopId)
// .GroupBy(x => x.EmployeeId).Select(x => x.OrderByDescending(y => y.LeftWork).First()).ToList();
//
//
//
//
// var insuranceLeftWork = _context.LeftWorkInsuranceList.Where(x => x.WorkshopId == workshopId).Select(x => new
// {
// 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()).ToList();
//
// var leftWorkTemp = _context.LeftWorkTemps.Where(x => x.WorkshopId == workshopId).Select(x => new
// {
// 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
// }).ToList();
//
//
// var employeeClientTemp = _context.EmployeeClientTemps.Where(x => x.WorkshopId == workshopId).Select(x => new
// {
// WorkshopId = x.WorkshopId,
// EmployeeId = x.EmployeeId,
// PersonnelCode = 0,
// CreatedByClient = true,
// ContractPerson = true
// }).ToList();
//
// var resultTemp = employeeClientTemp.Concat(leftWorkTemp).ToList().GroupBy(x => x.EmployeeId);
//
//
//
// var result = contractLeftWork.Concat(insuranceLeftWork).GroupBy(x => x.EmployeeId).ToList();
//
// result = result.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();
//
// return result.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 GetClientEmployeeListViewModel()
// {
// EmployeeId = x.Key,
// FullName = employee.FullName,
// PersonnelCode = personnelCode?.PersonnelCode ?? 0,
// HasContractLeftWork = insurance != null,
// HasInsuranceLeftWork = contract != null,
//
// LeftWorkCompletely = (insurance?.InsuranceLeft ?? false) && (contract?.ContractLeft ?? false),
//
// 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,
// ChildrenCount = employee.EmployeeChildrenList.Count,
//
// PendingStartWork = employeeClient != null || startWorkTemp != null,
// PendingLeftWork = leftWorkTemp != null,
//
//
// };
// }).OrderByDescending(x => x.StartWork).ToList();
throw new NotImplementedException();
}
#endregion
}

View File

@@ -722,34 +722,33 @@ public class EmployerRepository : RepositoryBase<long, Employer>, IEmployerRepos
public OperationResult ActiveAll(long id)
{
OperationResult result = new OperationResult();
using (var transaction = _context.Database.BeginTransaction())
try
{
try
var employer = _context.Employers.FirstOrDefault(x => x.id == id);
if (employer == null)
{
var employer = _context.Employers.FirstOrDefault(x => x.id == id);
employer.Active();
var workshopIds = _context.WorkshopEmployers.Where(x => x.EmployerId == id).Select(x => x.WorkshopId)
.ToList();
var workshops = _context.Workshops.Where(x => workshopIds.Contains(x.id)).ToList();
workshops.ForEach(x => x.Active(x.ArchiveCode));
var contracts = _context.Contracts.Where(x => workshopIds.Contains(x.WorkshopIds)).ToList();
contracts.ForEach(x => x.Active());
var contractIds = contracts.Select(x => x.id).ToList();
var checkouts = _context.CheckoutSet.Where(x => contractIds.Contains(x.ContractId)).ToList();
checkouts.ForEach(x => x.Active());
_context.SaveChanges();
transaction.Commit();
result.Succcedded();
}
catch (Exception)
{
result.Failed("فعال کردن کارفرما با خطا مواجه شد");
transaction.Rollback();
return result.Failed("کارفرما یافت نشد");
}
employer.Active();
var workshopIds = _context.WorkshopEmployers.Where(x => x.EmployerId == id).Select(x => x.WorkshopId)
.ToList();
var workshops = _context.Workshops.Where(x => workshopIds.Contains(x.id)).ToList();
workshops.ForEach(x => x.Active(x.ArchiveCode));
var contracts = _context.Contracts.Where(x => workshopIds.Contains(x.WorkshopIds)).ToList();
contracts.ForEach(x => x.Active());
var contractIds = contracts.Select(x => x.id).ToList();
var checkouts = _context.CheckoutSet.Where(x => contractIds.Contains(x.ContractId)).ToList();
checkouts.ForEach(x => x.Active());
_context.SaveChanges();
result.Succcedded();
}
catch (Exception)
{
result.Failed("فعال کردن کارفرما با خطا مواجه شد");
}
return result;

View File

@@ -1777,19 +1777,67 @@ public class InsuranceListRepository : RepositoryBase<long, InsuranceList>, IIns
return res;
}
public async Task<List<InsuranceListViewModel>> GetNotCreatedWorkshop(InsuranceListSearchModel searchModel)
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))
{
return [];
}
var workshopsHasInsuranceAccount = await _accountContext
.AccountLeftWorks
.Where(x => StaticWorkshopAccounts.InsuranceAccountsRoleIds.Contains(x.RoleId) && x.IsActive)
.Select(x => x.WorkshopId).Distinct().ToListAsync();
var acountId = _authHelper.CurrentAccountId();
var accountWorkshopIds = _context.WorkshopAccounts.Where(x => x.AccountId == acountId)
var accountWorkshopIds = _context.WorkshopAccounts.Where(x => x.AccountId == acountId && workshopsHasInsuranceAccount.Contains(x.WorkshopId))
.Select(x => x.WorkshopId);
var firstDayOfMonth = $"{searchModel.Year}/{searchModel.Month}/01".ToGeorgianDateTime();
var insuranceWorkshops = _context.Workshops
.Where(x => x.InsuranceCode != null && x.InsuranceCode.Length >= 10 && accountWorkshopIds.Contains(x.id) &&
.Where(x => accountWorkshopIds.Contains(x.id) &&
x.IsActiveString == "true");
@@ -1812,7 +1860,7 @@ public class InsuranceListRepository : RepositoryBase<long, InsuranceList>, IIns
WorkShopId = result.id,
WorkShopCode = result.InsuranceWorkshopInfo != null
? result.InsuranceWorkshopInfo.InsuranceCode
: result.InsuranceCode,
: string.IsNullOrWhiteSpace(result.InsuranceCode) ? "کد کارگاهی ندارد" : result.InsuranceCode,
WorkShopName = result.InsuranceWorkshopInfo != null
? result.InsuranceWorkshopInfo.WorkshopName
: result.WorkshopFullName,

View File

@@ -1,12 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using _0_Framework.Application;
using _0_Framework.Application;
using _0_Framework.InfraStructure;
using Company.Domain.InstitutionPlanAgg;
using CompanyManagment.App.Contracts.InstitutionContract;
using CompanyManagment.App.Contracts.InstitutionPlan;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CompanyManagment.EFCore.Repository;
@@ -44,6 +46,7 @@ public class PlanPercentageRepository : RepositoryBase<long, PlanPercentage>, IP
}).FirstOrDefault();
}
public List<InstitutionPlanViewModel> GetInstitutionPlanList(int pageIndex, int countPeron)
{
var planPercentage = _context.PlanPercentages.FirstOrDefault();
@@ -303,4 +306,109 @@ public class PlanPercentageRepository : RepositoryBase<long, PlanPercentage>, IP
return new InstitutionPlanViewModel();
}
#region ForApi
public async Task<CreateServiceAmountDto> GetCreateModalData()
{
return await _context.PlanPercentages.Select(x => new CreateServiceAmountDto()
{
Id = x.id,
ContractAndCheckoutInPersonPercentStr = $"{x.ContractAndCheckoutInPersonPercent}",
CustomizeCheckoutPercentStr = $"{x.CustomizeCheckoutPercent}",
ContractAndCheckoutPercentStr = $"{x.ContractAndCheckoutPercent}",
InsuranceInPersonPercentStr = $"{x.InsuranceInPersonPercent}",
InsurancePercentStr = $"{x.InsurancePercent}",
RollCallPercentStr = $"{x.RollCallPercent}",
}).FirstOrDefaultAsync();
}
public async Task<PagedResult<InstitutionPlanListDto>> GetList(
InstitutionPlanSearchModel searchModel)
{
var planPercentage = await _context.PlanPercentages.FirstOrDefaultAsync();
if (planPercentage == null)
return new PagedResult<InstitutionPlanListDto>();
var dailyWageYearlySalery = await _context.YearlySalaries.Include(i => i.YearlySalaryItemsList).FirstOrDefaultAsync(x =>
x.StartDate.Date <= DateTime.Now.Date && x.EndDate >= DateTime.Now.Date);
if (dailyWageYearlySalery == null)
return new PagedResult<InstitutionPlanListDto>();
var dailyWage = dailyWageYearlySalery.YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه")
.Select(x => x.ItemValue).FirstOrDefault();
var plans = _context.InstitutionPlans.AsQueryable();
if (searchModel.CountPerson > 0)
plans = plans.Where(x => x.CountPerson == searchModel.CountPerson);
var count = await plans.CountAsync();
var planQueryFilter =await plans.ApplyPagination(searchModel.PageIndex, searchModel.PageSize).ToListAsync();
var planResult = planQueryFilter.Select(plan =>
new InstitutionPlanViewModel
{
CountPerson = plan.CountPerson,
ContractAndCheckoutDouble =
((dailyWage * planPercentage.ContractAndCheckoutPercent / 100) * plan.CountPerson *
plan.IncreasePercentage),
InsuranceDouble = (((dailyWage * planPercentage.InsurancePercent) / 100) * plan.CountPerson *
plan.IncreasePercentage),
RollCallDouble = (((dailyWage * planPercentage.RollCallPercent) / 100) * plan.CountPerson *
plan.IncreasePercentage),
CustomizeCheckoutDouble = (((dailyWage * planPercentage.CustomizeCheckoutPercent) / 100) *
plan.CountPerson *
plan.IncreasePercentage),
ContractAndCheckoutInPersonDouble =
(((dailyWage * planPercentage.ContractAndCheckoutInPersonPercent) / 100) * plan.CountPerson *
plan.IncreasePercentage),
InsuranceInPersonDouble = (((dailyWage * planPercentage.InsuranceInPersonPercent) / 100) *
plan.CountPerson *
plan.IncreasePercentage)
}).ToList();
var finalResult = planResult.Select(plan => new InstitutionPlanListDto()
{
CountPerson = plan.CountPerson,
ContractAndCheckout = plan.ContractAndCheckoutDouble.ToMoney(),
Insurance = plan.InsuranceDouble.ToMoney(),
RollCall = plan.RollCallDouble.ToMoney(),
CustomizeCheckout = plan.CustomizeCheckoutDouble.ToMoney(),
ContractAndCheckoutInPerson = plan.ContractAndCheckoutInPersonDouble.ToMoney(),
InsuranceInPerson = plan.InsuranceInPersonDouble.ToMoney(),
InPersonSumAmountStr =
(plan.ContractAndCheckoutDouble + plan.InsuranceDouble + plan.ContractAndCheckoutInPersonDouble +
plan.InsuranceInPersonDouble).ToMoney(),
OnlineAndInPersonSumAmountStr = (plan.ContractAndCheckoutDouble + plan.InsuranceDouble +
plan.ContractAndCheckoutInPersonDouble + plan.InsuranceInPersonDouble +
plan.RollCallDouble + plan.CustomizeCheckoutDouble).ToMoney(),
OnlineOnlySumAmountStr =
(plan.ContractAndCheckoutDouble + plan.InsuranceDouble + plan.RollCallDouble +
plan.CustomizeCheckoutDouble).ToMoney(),
}).ToList();
return new PagedResult<InstitutionPlanListDto>()
{
TotalCount = count,
List = finalResult
};
}
#endregion
}

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using Microsoft.EntityFrameworkCore;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.AutoStopOverTimeTaskSections;
public record AutoStopOverTimeTaskSectionsCommand : IBaseCommand;
public class AutoStopOverTimeTaskSectionsCommandHandler : IBaseCommandHandler<AutoStopOverTimeTaskSectionsCommand>
{
private readonly ITaskSectionRepository _taskSectionRepository;
private readonly IUnitOfWork _unitOfWork;
public AutoStopOverTimeTaskSectionsCommandHandler(ITaskSectionRepository taskSectionRepository,
IUnitOfWork unitOfWork)
{
_taskSectionRepository = taskSectionRepository;
_unitOfWork = unitOfWork;
}
public async Task<OperationResult> Handle(AutoStopOverTimeTaskSectionsCommand request,
CancellationToken cancellationToken)
{
try
{
// دریافت تمام تسک‌های در حال انجام
var taskSections = await _taskSectionRepository.GetActiveSectionsIncludeAllAsync(cancellationToken);
foreach (var taskSection in taskSections)
{
// استفاده از متد Domain برای بررسی و متوقف کردن خودکار
taskSection.AutoStopIfOverTime();
}
// ذخیره تغییرات در دیتابیس
await _unitOfWork.SaveChangesAsync(cancellationToken);
return OperationResult.Success();
}
catch (Exception ex)
{
return OperationResult.Failure($"خطا در ناتمام کردن تسک‌های overtime: {ex.Message}");
}
}
}

View File

@@ -49,8 +49,11 @@ public class ChangeStatusSectionCommandHandler : IBaseCommandHandler<ChangeStatu
}
else if (request.Status == TaskSectionStatus.InProgress)
{
// Going TO InProgress: Start work and create activity
section.StartWork();
// Going TO InProgress: Check if section has remaining time, then start work
if (!section.HasRemainingTime())
return OperationResult.ValidationError("زمان این بخش به پایان رسیده است");
section.StartWork();
}
else
{

View File

@@ -2,13 +2,14 @@ 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;
@@ -16,7 +17,7 @@ public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectComm
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthHelper _authHelper;
private long? _userId;
public SetTimeProjectCommandHandler(
IProjectRepository projectRepository,
@@ -40,11 +41,11 @@ public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectComm
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)
@@ -75,7 +76,8 @@ public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectComm
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)
@@ -103,13 +105,13 @@ public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectComm
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;
@@ -127,12 +129,17 @@ public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectComm
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);
@@ -144,7 +151,7 @@ public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectComm
section.AddAdditionalTime(additionalTimeSpan, additionalTime.Description, addedByUserId);
}
}
// private void SetSectionTime(ProjectSection section, SetTimeProjectSectionItem sectionItem, long? addedByUserId)
// {
// var initData = sectionItem.InitData;
@@ -161,4 +168,4 @@ public class SetTimeProjectCommandHandler:IBaseCommandHandler<SetTimeProjectComm
// section.AddAdditionalTime(additionalTimeSpan, additionalTime.Description, addedByUserId);
// }
// }
}
}

View File

@@ -1,4 +1,5 @@
using FluentValidation;
using FluentValidation.Validators;
using GozareshgirProgramManager.Application.Modules.Projects.DTOs;
namespace GozareshgirProgramManager.Application.Modules.Projects.Commands.SetTimeProject;
@@ -15,6 +16,9 @@ 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>
@@ -30,13 +34,14 @@ public class SetTimeProjectSectionItemValidator:AbstractValidator<SetTimeProject
.SetValidator(new TimeDataValidator());
RuleForEach(x=>x.AdditionalTime)
.SetValidator(new TimeDataValidator());
.SetValidator(new AdditionalTimeDataValidator());
}
}
public class TimeDataValidator : AbstractValidator<SetTimeSectionTime>
public class AdditionalTimeDataValidator: AbstractValidator<SetTimeSectionTime>
{
public TimeDataValidator()
public AdditionalTimeDataValidator()
{
RuleFor(x => x.Hours)
.GreaterThanOrEqualTo(0)
@@ -45,6 +50,13 @@ public class TimeDataValidator : AbstractValidator<SetTimeSectionTime>
RuleFor(x=>x.Description)
.MaximumLength(500)
.WithMessage("توضیحات نمی‌تواند بیشتر از 500 کاراکتر باشد.");
}
}
public class TimeDataValidator : AbstractValidator<SetTimeSectionTime>
{
public TimeDataValidator()
{
}
}

View File

@@ -132,91 +132,82 @@ 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();
// تنها تسک‌ها sections دارند، بنابراین برای سطوح مختلف باید متفاوت عمل کنیم
List<Guid> taskIds;
switch (projects.FirstOrDefault()?.Level)
var hierarchyLevel = projects.First().Level;
switch (hierarchyLevel)
{
case ProjectHierarchyLevel.Project:
// برای پروژه‌ها، باید تمام تسک‌های زیرمجموعه را پیدا کنیم
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);
await SetSkillFlagsForProjects(projects, projectIds, cancellationToken);
break;
case ProjectHierarchyLevel.Phase:
// برای فازها، تمام تسک‌های آن فازها را پیدا کنیم
taskIds = await _context.ProjectTasks
.Where(t => projectIds.Contains(t.PhaseId))
.Select(t => t.Id)
.ToListAsync(cancellationToken);
await SetSkillFlagsForPhases(projects, projectIds, cancellationToken);
break;
case ProjectHierarchyLevel.Task:
// برای تسک‌ها، خود آنها taskIds هستند
taskIds = projectIds;
await SetSkillFlagsForTasks(projects, projectIds, cancellationToken);
break;
default:
return;
}
}
if (!taskIds.Any())
return;
var sections = await _context.TaskSections
private async Task SetSkillFlagsForProjects(List<GetProjectListDto> projects, List<Guid> projectIds, CancellationToken cancellationToken)
{
var projectSections = await _context.ProjectSections
.Include(x => x.Skill)
.Where(x => taskIds.Contains(x.TaskId))
.Where(s => projectIds.Contains(s.ProjectId))
.ToListAsync(cancellationToken);
if (!projectSections.Any())
return;
foreach (var project in projects)
{
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");
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");
}
}

View File

@@ -0,0 +1,84 @@
using System.Globalization;
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 TotalTimeMinute,string RemainingTimeMinute );
public record ProjectBoardDetailUserResponse
{
public List<ProjectBoardDetailUserHistoryResponse> Histories { get; init; }
public string UserFullName { get; init; }
public string SpentTimeMinute { get; init; }
public long UserId { get; init; }
}
public record ProjectBoardDetailUserHistoryResponse
{
public string Date { get; init; }
public string startTime { get; init; }
public string EndTime { get; init; }
public string TotalTimeMinute { get; init; }
}
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)
.Include(x=>x.AdditionalTimes)
.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 totalActivityTimeSpan = section.Activities
.Select(x => x.GetTimeSpent())
.Aggregate(TimeSpan.Zero, (sum, next) => sum.Add(next));
var finalTime = section.FinalEstimatedHours;
var remainingTimeSpan = finalTime >= totalActivityTimeSpan
? TimeSpan.FromTicks(finalTime.Ticks - totalActivityTimeSpan.Ticks)
: TimeSpan.Zero;
var users = section.Activities.GroupBy(x => x.UserId).Select(x =>
{
return new ProjectBoardDetailUserResponse()
{
UserId = x.Key,
UserFullName = usersDict[x.Key],
SpentTimeMinute = ((int)TimeSpan.FromTicks(x.Sum(h=>h.GetTimeSpent().Ticks)).TotalMinutes).ToString(CultureInfo.InvariantCulture),
Histories = x.Select(h => new ProjectBoardDetailUserHistoryResponse()
{
Date = h.StartDate.ToFarsi(),
startTime = h.StartDate.ToString("HH:mm"),
EndTime = h.EndDate?.ToString("HH:mm") ?? "-",
TotalTimeMinute = h.GetTimeSpent().TotalMinutes.ToString("F0",CultureInfo.InvariantCulture)
}).ToList()
};
}).ToList();
var response = new ProjectBoardDetailResponse(users, $"{(int)finalTime.TotalMinutes}",
$"{(int)remainingTimeSpan.TotalMinutes: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; }
}

View File

@@ -1,6 +1,9 @@
using GozareshgirProgramManager.Application._Common.Constants;
using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query.Internal;
namespace GozareshgirProgramManager.Application.Modules.Projects.Queries.ProjectBoardList;
@@ -19,21 +22,35 @@ public class ProjectBoardListQueryHandler : IBaseQueryHandler<ProjectBoardListQu
CancellationToken cancellationToken)
{
var currentUserId = _authHelper.GetCurrentUserId();
var data = await _programManagerDbContext.TaskSections.AsNoTracking()
.Where(x => x.CurrentAssignedUserId == currentUserId)
var queryable = _programManagerDbContext.TaskSections.AsNoTracking()
.Where(x => x.InitialEstimatedHours > TimeSpan.Zero)
.Include(x => x.Task)
.ThenInclude(x => x.Phase)
.ThenInclude(x => x.Project)
.Include(x => x.Activities)
.Include(x => x.AdditionalTimes)
.ToListAsync(cancellationToken);
.Include(x => x.AdditionalTimes).AsQueryable().
Include(x => x.Skill).AsQueryable();
if (!_authHelper.HasPermission(ProgramManagerPermissionCode.Board.ViewAllUsersProjects.Code))
{
queryable = queryable.Where(x => x.CurrentAssignedUserId == currentUserId);
}
if (request.Status != null)
{
queryable = queryable.Where(x => x.Status == request.Status);
}
var data = await queryable.ToListAsync(cancellationToken);
var activityUserIds = data.SelectMany(x => x.Activities).Select(a => a.UserId).Distinct().ToList();
var assignedUser = data.Select(x => x.CurrentAssignedUserId)
.Concat(data.Select(x => x.OriginalAssignedUserId)).ToList();
var allUserIds = activityUserIds.Concat(assignedUser).Distinct().ToList();
var users = await _programManagerDbContext.Users.AsNoTracking()
.Where(x => activityUserIds.Contains(x.Id))
.Where(x => allUserIds.Contains(x.Id))
.Select(x => new { x.Id, x.FullName })
.ToDictionaryAsync(x => x.Id, x => x.FullName, cancellationToken);
var result = data.Select(x =>
{
@@ -89,7 +106,11 @@ public class ProjectBoardListQueryHandler : IBaseQueryHandler<ProjectBoardListQu
CompleteSecond = x.FinalEstimatedHours.TotalSeconds,
CurrentSecond = activityTimeData.Sum(a => a.TotalSeconds),
Histories = mergedHistories
}
},
OriginalUser = users.GetValueOrDefault(x.OriginalAssignedUserId, "ناشناس"),
AssignedUser = x.CurrentAssignedUserId == x.OriginalAssignedUserId ? null
: users.GetValueOrDefault(x.CurrentAssignedUserId, "ناشناس"),
SkillName = x.Skill?.Name??"-",
};
}).ToList();

View File

@@ -10,6 +10,10 @@ public class ProjectBoardListResponse
public string TaskName { get; set; }
public ProjectProgressDto Progress { get; set; }
public TaskSectionStatus SectionStatus { get; set; }
public string? AssignedUser { get; set; }
public string OriginalUser { get; set; }
public string SkillName { get; set; }
}
public class ProjectProgressDto
{

View File

@@ -4,35 +4,238 @@ namespace GozareshgirProgramManager.Application._Common.Constants;
public static class ProgramManagerPermissionCode
{
/// <summary>
/// دسترسی به بخش مدیریت پروژه
/// </summary>
public const int Code = 99;
#region DeveloperUsers[تب کاربران برنامه نویسی]
/// <summary>
///بخش اجرا
/// تب کاربران برنامه نویسی
/// </summary>
public static class DeveloperUsers
{
public const int Code = 9900;
/// <summary>
/// تب تعیین حقوق
/// </summary>
public static class SalaryDetermination
{
public const int Code = 990001;
/// <summary>
/// تعیین زمان
/// </summary>
public const int WorkingHoursDetermination = 990001;
}
/// <summary>
/// تب وضعیت کارکرد
/// </summary>
public static class WorkingStatus
{
public const int Code = 990002;
}
/// <summary>
/// تب فیش حقوقی
/// </summary>
public static class Checkout
{
public const int Code = 990003;
/// <summary>
/// ایجاد فیش
/// </summary>
public const int Create = 99000301;
/// <summary>
/// حذف تکی فیش
/// </summary>
public const int SingleDeletion = 99000302;
/// <summary>
/// حذف گروهی فیش ها
/// </summary>
public const int GroupDeletion = 99000303;
/// <summary>
/// محاسبه مجدد گروهی فیش ها
/// </summary>
public const int GroupReCompute = 99000304;
/// <summary>
/// محاسبه مجدد تکی فیش
/// </summary>
public const int SingleReCompute = 99000305;
}
}
#endregion
#region ProgramManager[تب مدیریت پروژه]
/// <summary>
/// تب مدیریت پروژه
/// </summary>
public static class ProgramManager
{
public const int Code = 9901;
/// <summary>
/// ایجاد پروژه
/// </summary>
public static class CreateProject
{
public const int Code = 9901;
}
/// <summary>
/// همه پروژه ها
/// </summary>
public static class AllProjects
{
public const int Code = 990102;
}
/// <summary>
/// تعیین کاربر
/// </summary>
public static class UserDetermination
{
public const int Code = 990106;
}
/// <summary>
/// تعیین زمان پروژه
/// </summary>
public static class ProjectTimeSetting
{
public const int Code = 990107;
}
/// <summary>
/// ویرایش پروژه
/// </summary>
public static class EditProject
{
public const int Code = 990108;
}
/// <summary>
/// حذف پروژه
/// </summary>
public static class DeleteProject
{
public const int Code = 990109;
}
/// <summary>
/// ایجاد بخش اصلی
/// </summary>
public static class CreateMainSection
{
public const int Code = 990110;
}
/// <summary>
/// ایجاد بخش فرعی
/// </summary>
public static class CreateSubSection
{
public const int Code = 990111;
}
}
#endregion
#region Board[تب اجرا]
/// <summary>
///تب اجرا
/// </summary>
public static class Board
{
public const int Code = 991;
public const int Code = 9902;
/// <summary>
/// تب همه
/// </summary>
public static class All
{
public const int Code = 99101;
public const int Code = 990201;
}
/// <summary>
/// دیدن همه تسک ها
/// </summary>
public const int ViewAll = 9910101;
/// <summary>
/// آماده اجرا
/// </summary>
public static class ReadyToRun
{
public const int Code = 990202;
}
/// <summary>
/// در حال اجرا
/// </summary>
public static class Running
{
public const int Code = 990203;
}
/// <summary>
/// نیمه کاره
/// </summary>
public static class Unfinished
{
public const int Code = 990204;
}
/// <summary>
/// اتمام اجرا
/// </summary>
public static class Finished
{
public const int Code = 990204;
}
/// <summary>
/// دیدن پروژه همه کاربران
/// </summary>
public static class ViewAllUsersProjects
{
public const int Code = 990206;
}
/// <summary>
/// ارجاع به دیگران
/// </summary>
public static class ReferralToOthers
{
public const int Code = 990207;
}
/// <summary>
/// چت
/// </summary>
public static class Chat
{
public const int Code = 990208;
}
}
public static List<int> GetAllCodes()
{
var result = new List<int>();
void Collect(Type type)
#endregion
public static Dictionary<string, object> GetAllCodes()
{
var result = new Dictionary<string, object>();
void Collect(Type type, Dictionary<string, object> dict)
{
// Collect const int fields directly declared on this type
var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly);
@@ -43,7 +246,7 @@ public static class ProgramManagerPermissionCode
var raw = f.GetRawConstantValue();
if (raw is int value)
{
result.Add(value);
dict[f.Name] = value;
}
}
}
@@ -52,11 +255,16 @@ public static class ProgramManagerPermissionCode
var nestedTypes = type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic);
foreach (var nt in nestedTypes)
{
Collect(nt);
var nestedDict = new Dictionary<string, object>();
Collect(nt, nestedDict);
if (nestedDict.Count > 0)
{
dict[nt.Name] = nestedDict;
}
}
}
Collect(typeof(ProgramManagerPermissionCode));
Collect(typeof(ProgramManagerPermissionCode), result);
return result;
}
}

View File

@@ -71,6 +71,10 @@ public interface IAuthHelper
/// دریافت نام کامل کاربر جاری از Claims
/// </summary>
string? GetCurrentFullName();
bool HasPermission(int permission);
List<int> GetPermissions();
}

View File

@@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="DNTPersianUtils.Core" Version="6.7.1" />
<PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.3" />
<PackageReference Include="PersianTools.Core" Version="2.0.4" />
</ItemGroup>

View File

@@ -1,4 +1,5 @@
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.SkillAgg.Entities;
namespace GozareshgirProgramManager.Domain.ProjectAgg.Entities;
@@ -22,6 +23,7 @@ public class PhaseSection : EntityBase<Guid>
// Navigation property
public ProjectPhase Phase { get; private set; } = null!;
public Skill? Skill { get; set; }
public void UpdateUser(long userId)
{

View File

@@ -1,4 +1,5 @@
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.SkillAgg.Entities;
namespace GozareshgirProgramManager.Domain.ProjectAgg.Entities;
@@ -21,6 +22,7 @@ public class ProjectSection : EntityBase<Guid>
public Guid SkillId { get; private set; }
public Project Project { get; private set; } = null!;
public Skill? Skill { get; set; }
public void UpdateUser(long userId)
{

View File

@@ -210,4 +210,46 @@ public class TaskSection : EntityBase<Guid>
{
_additionalTimes.Clear();
}
public bool HasRemainingTime()
{
var totalSpent = GetTotalTimeSpent();
var finalEstimate = FinalEstimatedHours;
return totalSpent < finalEstimate;
}
/// <summary>
/// اگر زمان کار شده بیش از تایم تعیین شده باشد، تسک را متوقف می‌کند
/// و EndDate را به طوری تنظیم می‌کند که کل زمان برابر با FinalEstimatedHours شود
/// </summary>
public void AutoStopIfOverTime()
{
if (Status != TaskSectionStatus.InProgress)
return;
var activeActivity = _activities.FirstOrDefault(a => a.IsActive);
if (activeActivity == null)
return;
// محاسبه کل زمان صرف شده تا کنون (بدون فعالیت فعال)
var totalTimeSpentExcludingActive = _activities.Where(a => !a.IsActive).Sum(a => a.GetTimeSpent().Ticks);
var totalTimeSpentTimeSpan = TimeSpan.FromTicks(totalTimeSpentExcludingActive);
var finalEstimate = FinalEstimatedHours;
// اگر زمان صرف شده (بدون فعالیت فعال) + فعالیت فعال > تایم تعیین شده
var activeTimeSpent = activeActivity.GetTimeSpent();
if (totalTimeSpentTimeSpan + activeTimeSpent > finalEstimate)
{
// محاسبه مدت زمانی که این فعالیت باید برای رسیدن به FinalEstimatedHours داشته باشد
var remainingTime = finalEstimate - totalTimeSpentTimeSpan;
// EndDate = StartDate + remainingTime
var adjustedEndDate = activeActivity.StartDate.Add(remainingTime);
// متوقف کردن فعالیت با EndDate دقیق شده
activeActivity.StopWorkWithSpecificTime(adjustedEndDate, "متوقف خودکار - بیش از تایم تعیین شده");
UpdateStatus(TaskSectionStatus.Incomplete);
}
}
}

View File

@@ -40,6 +40,22 @@ public class TaskSectionActivity : EntityBase<Guid>
IsActive = false;
}
/// <summary>
/// متوقف کردن فعالیت با مشخص کردن EndDate دقیق
/// </summary>
public void StopWorkWithSpecificTime(DateTime endDate, string? endNotes = null)
{
if (!IsActive)
throw new InvalidOperationException("این فعالیت قبلاً متوقف شده است.");
if (endDate < StartDate)
throw new InvalidOperationException("تاریخ پایان نمی‌تواند قبل از تاریخ شروع باشد.");
EndDate = endDate;
EndNotes = endNotes;
IsActive = false;
}
public TimeSpan GetTimeSpent()
{
if (IsActive)

View File

@@ -1,3 +1,4 @@
using System.Collections;
using GozareshgirProgramManager.Domain._Common;
using GozareshgirProgramManager.Domain.ProjectAgg.Entities;
@@ -11,4 +12,5 @@ public interface ITaskSectionRepository: IRepository<Guid,TaskSection>
Task<TaskSection?> GetByIdWithFullDataAsync(Guid id, CancellationToken cancellationToken = default);
Task<List<TaskSection>> GetAssignedToUserAsync(long userId);
Task<List<TaskSection>> GetActiveSectionsIncludeAllAsync(CancellationToken cancellationToken);
}

View File

@@ -1,5 +1,7 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using PersianTools.Core;
@@ -1704,25 +1706,25 @@ public static class Tools
// return Convert.ToBase64String(bsonData);
//}
////بیسان هایی که بصورت لیست بودند استخراج میشود
//public static List<T> DeserializeFromBsonList<T>(string base64Data)
//{
// byte[] data = Convert.FromBase64String(base64Data);
public static List<T> DeserializeFromBsonList<T>(string base64Data)
{
byte[] data = Convert.FromBase64String(base64Data);
// using MemoryStream memoryStream = new MemoryStream(data);
// using BsonDataReader reader = new BsonDataReader(memoryStream);
// reader.ReadRootValueAsArray = true;
// JsonSerializer serializer = new JsonSerializer();
// return serializer.Deserialize<List<T>>(reader);
//}
////بیسان هایی که بصورت تکی بودند استخراج میشود
//public static T DeserializeFromBson<T>(string base64Data)
//{
// byte[] bsonData = Convert.FromBase64String(base64Data);
// using MemoryStream memoryStream = new MemoryStream(bsonData);
// using BsonDataReader bsonReader = new BsonDataReader(memoryStream);
// JsonSerializer serializer = new JsonSerializer();
// return serializer.Deserialize<T>(bsonReader);
//}
using MemoryStream memoryStream = new MemoryStream(data);
using BsonDataReader reader = new BsonDataReader(memoryStream);
reader.ReadRootValueAsArray = true;
JsonSerializer serializer = new JsonSerializer();
return serializer.Deserialize<List<T>>(reader);
}
//بیسان هایی که بصورت تکی بودند استخراج میشود
public static T DeserializeFromBson<T>(string base64Data)
{
byte[] bsonData = Convert.FromBase64String(base64Data);
using MemoryStream memoryStream = new MemoryStream(bsonData);
using BsonDataReader bsonReader = new BsonDataReader(memoryStream);
JsonSerializer serializer = new JsonSerializer();
return serializer.Deserialize<T>(bsonReader);
}
//public static TimeOnly CalculateOffset(ICollection<CustomizeSifts> shiftDetailsRegularShifts)
//{

View File

@@ -0,0 +1,857 @@
// <auto-generated />
using System;
using GozareshgirProgramManager.Infrastructure.Persistence.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace GozareshgirProgramManager.Infrastructure.Migrations
{
[DbContext(typeof(ProgramManagerDbContext))]
[Migration("20251215155149_add relation to phase section and projectsection to skill")]
partial class addrelationtophasesectionandprojectsectiontoskill
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("GozareshgirProgramManager.Domain.CheckoutAgg.Entities.Checkout", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CheckoutEndDate")
.HasColumnType("datetime2");
b.Property<DateTime>("CheckoutStartDate")
.HasColumnType("datetime2");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<double>("DeductionFromSalary")
.HasColumnType("float");
b.Property<string>("FullName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<int>("MandatoryHours")
.HasColumnType("int");
b.Property<int>("Month")
.HasColumnType("int");
b.Property<double>("MonthlySalaryDefined")
.HasColumnType("float");
b.Property<double>("MonthlySalaryPay")
.HasColumnType("float");
b.Property<int>("RemainingHours")
.HasColumnType("int");
b.Property<int>("TotalDaysWorked")
.HasColumnType("int");
b.Property<int>("TotalHoursWorked")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<int>("Year")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Checkouts", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.CustomerAgg.Customer", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("Id");
b.ToTable("Customers", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.PhaseSection", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<Guid>("PhaseId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("SkillId")
.HasColumnType("uniqueidentifier");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("PhaseId");
b.HasIndex("SkillId");
b.ToTable("PhaseSections");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.Project", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<DateTime?>("EndDate")
.HasColumnType("datetime2");
b.Property<bool>("HasAssignmentOverride")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<DateTime?>("PlannedEndDate")
.HasColumnType("datetime2");
b.Property<DateTime?>("PlannedStartDate")
.HasColumnType("datetime2");
b.Property<DateTime?>("StartDate")
.HasColumnType("datetime2");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Projects", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectPhase", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<DateTime?>("EndDate")
.HasColumnType("datetime2");
b.Property<bool>("HasAssignmentOverride")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<int>("OrderIndex")
.HasColumnType("int");
b.Property<Guid>("ProjectId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime?>("StartDate")
.HasColumnType("datetime2");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.HasIndex("ProjectId");
b.ToTable("ProjectPhases", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectSection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<Guid>("ProjectId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("SkillId")
.HasColumnType("uniqueidentifier");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("ProjectId");
b.HasIndex("SkillId");
b.ToTable("ProjectSections");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectTask", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<string>("AllocatedTime")
.HasMaxLength(30)
.HasColumnType("nvarchar(30)");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<DateTime?>("DueDate")
.HasColumnType("datetime2");
b.Property<DateTime?>("EndDate")
.HasColumnType("datetime2");
b.Property<bool>("HasAssignmentOverride")
.HasColumnType("bit");
b.Property<bool>("HasTimeOverride")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<int>("OrderIndex")
.HasColumnType("int");
b.Property<Guid>("PhaseId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Priority")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<DateTime?>("StartDate")
.HasColumnType("datetime2");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.HasIndex("PhaseId");
b.ToTable("ProjectTasks", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<long>("CurrentAssignedUserId")
.HasColumnType("bigint");
b.Property<string>("InitialDescription")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<string>("InitialEstimatedHours")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("nvarchar(30)");
b.Property<long>("OriginalAssignedUserId")
.HasColumnType("bigint");
b.Property<Guid>("SkillId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<Guid>("TaskId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("SkillId");
b.HasIndex("TaskId");
b.ToTable("TaskSections", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSectionActivity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<DateTime?>("EndDate")
.HasColumnType("datetime2");
b.Property<string>("EndNotes")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Notes")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<Guid>("SectionId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("StartDate")
.HasColumnType("datetime2");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("SectionId");
b.ToTable("TaskSectionActivities", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSectionAdditionalTime", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("AddedAt")
.HasColumnType("datetime2");
b.Property<long?>("AddedByUserId")
.HasColumnType("bigint");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Hours")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("nvarchar(30)");
b.Property<string>("Reason")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<Guid?>("TaskSectionId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("TaskSectionId");
b.ToTable("TaskSectionAdditionalTimes", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.RoleAgg.Entities.Role", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<long?>("GozareshgirRoleId")
.HasColumnType("bigint");
b.Property<string>("RoleName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Id");
b.ToTable("PmRoles", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.SalaryPaymentSettingAgg.Entities.SalaryPaymentSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<DateTime?>("EndSettingDate")
.HasColumnType("datetime2");
b.Property<bool>("HolidayWorking")
.HasColumnType("bit");
b.Property<double>("MonthlySalary")
.HasColumnType("float");
b.Property<DateTime?>("StartSettingDate")
.HasColumnType("datetime2");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.ToTable("SalaryPaymentSetting", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.SkillAgg.Entities.Skill", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("Id");
b.ToTable("Skills", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.UserAgg.Entities.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<long?>("AccountId")
.HasColumnType("bigint");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasMaxLength(150)
.HasColumnType("nvarchar(150)");
b.Property<string>("FullName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Mobile")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("nvarchar(20)");
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<string>("ProfilePhotoPath")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("VerifyCode")
.HasMaxLength(10)
.HasColumnType("nvarchar(10)");
b.HasKey("Id");
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.UserAgg.Entities.UserRefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime2");
b.Property<string>("IpAddress")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<DateTime?>("RevokedAt")
.HasColumnType("datetime2");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<string>("UserAgent")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("ExpiresAt");
b.HasIndex("Token")
.IsUnique();
b.HasIndex("UserId");
b.ToTable("UserRefreshTokens", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.PhaseSection", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectPhase", "Phase")
.WithMany("PhaseSections")
.HasForeignKey("PhaseId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GozareshgirProgramManager.Domain.SkillAgg.Entities.Skill", "Skill")
.WithMany()
.HasForeignKey("SkillId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Phase");
b.Navigation("Skill");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectPhase", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.ProjectAgg.Entities.Project", "Project")
.WithMany("Phases")
.HasForeignKey("ProjectId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Project");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectSection", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.ProjectAgg.Entities.Project", "Project")
.WithMany("ProjectSections")
.HasForeignKey("ProjectId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GozareshgirProgramManager.Domain.SkillAgg.Entities.Skill", "Skill")
.WithMany()
.HasForeignKey("SkillId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Project");
b.Navigation("Skill");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectTask", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectPhase", "Phase")
.WithMany("Tasks")
.HasForeignKey("PhaseId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Phase");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSection", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.SkillAgg.Entities.Skill", "Skill")
.WithMany("Sections")
.HasForeignKey("SkillId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectTask", "Task")
.WithMany("Sections")
.HasForeignKey("TaskId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Skill");
b.Navigation("Task");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSectionActivity", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSection", "Section")
.WithMany("Activities")
.HasForeignKey("SectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Section");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSectionAdditionalTime", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSection", null)
.WithMany("AdditionalTimes")
.HasForeignKey("TaskSectionId");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.RoleAgg.Entities.Role", b =>
{
b.OwnsMany("GozareshgirProgramManager.Domain.PermissionAgg.Entities.Permission", "Permissions", b1 =>
{
b1.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b1.Property<long>("Id"));
b1.Property<int>("Code")
.HasColumnType("int");
b1.Property<long>("RoleId")
.HasColumnType("bigint");
b1.HasKey("Id");
b1.HasIndex("RoleId");
b1.ToTable("PmRolePermissions", (string)null);
b1.WithOwner("Role")
.HasForeignKey("RoleId");
b1.Navigation("Role");
});
b.Navigation("Permissions");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.SalaryPaymentSettingAgg.Entities.SalaryPaymentSetting", b =>
{
b.OwnsMany("GozareshgirProgramManager.Domain.SalaryPaymentSettingAgg.Entities.WorkingHours", "WorkingHoursList", b1 =>
{
b1.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b1.Property<long>("Id"));
b1.Property<TimeSpan>("EndShiftOne")
.HasColumnType("time(0)");
b1.Property<TimeSpan>("EndShiftTwo")
.HasColumnType("time(0)");
b1.Property<bool>("HasRestTime")
.HasColumnType("bit");
b1.Property<bool>("HasShiftOne")
.HasColumnType("bit");
b1.Property<bool>("HasShiftTow")
.HasColumnType("bit");
b1.Property<bool>("IsActiveDay")
.HasColumnType("bit");
b1.Property<int>("PersianDayOfWeek")
.HasColumnType("int");
b1.Property<TimeSpan>("RestTime")
.HasColumnType("time(0)");
b1.Property<long>("SalaryPaymentSettingId")
.HasColumnType("bigint");
b1.Property<int>("ShiftDurationInMinutes")
.HasColumnType("int");
b1.Property<TimeSpan>("StartShiftOne")
.HasColumnType("time(0)");
b1.Property<TimeSpan>("StartShiftTwo")
.HasColumnType("time(0)");
b1.HasKey("Id");
b1.HasIndex("SalaryPaymentSettingId");
b1.ToTable("WorkingHours", (string)null);
b1.WithOwner("SalaryPaymentSetting")
.HasForeignKey("SalaryPaymentSettingId");
b1.Navigation("SalaryPaymentSetting");
});
b.Navigation("WorkingHoursList");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.UserAgg.Entities.User", b =>
{
b.OwnsMany("GozareshgirProgramManager.Domain.RoleUserAgg.RoleUser", "RoleUser", b1 =>
{
b1.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b1.Property<long>("Id"));
b1.Property<long>("RoleId")
.HasColumnType("bigint");
b1.Property<long>("UserId")
.HasColumnType("bigint");
b1.HasKey("Id");
b1.HasIndex("UserId");
b1.ToTable("RoleUsers", (string)null);
b1.WithOwner("User")
.HasForeignKey("UserId");
b1.Navigation("User");
});
b.Navigation("RoleUser");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.UserAgg.Entities.UserRefreshToken", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.UserAgg.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.Project", b =>
{
b.Navigation("Phases");
b.Navigation("ProjectSections");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectPhase", b =>
{
b.Navigation("PhaseSections");
b.Navigation("Tasks");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectTask", b =>
{
b.Navigation("Sections");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.TaskSection", b =>
{
b.Navigation("Activities");
b.Navigation("AdditionalTimes");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.SkillAgg.Entities.Skill", b =>
{
b.Navigation("Sections");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.UserAgg.Entities.User", b =>
{
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,63 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GozareshgirProgramManager.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class addrelationtophasesectionandprojectsectiontoskill : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_ProjectSections_SkillId",
table: "ProjectSections",
column: "SkillId");
migrationBuilder.CreateIndex(
name: "IX_PhaseSections_SkillId",
table: "PhaseSections",
column: "SkillId");
migrationBuilder.AddForeignKey(
name: "FK_PhaseSections_Skills_SkillId",
table: "PhaseSections",
column: "SkillId",
principalTable: "Skills",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ProjectSections_Skills_SkillId",
table: "ProjectSections",
column: "SkillId",
principalTable: "Skills",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_PhaseSections_Skills_SkillId",
table: "PhaseSections");
migrationBuilder.DropForeignKey(
name: "FK_ProjectSections_Skills_SkillId",
table: "ProjectSections");
migrationBuilder.DropIndex(
name: "IX_ProjectSections_SkillId",
table: "ProjectSections");
migrationBuilder.DropIndex(
name: "IX_PhaseSections_SkillId",
table: "PhaseSections");
}
}
}

View File

@@ -17,7 +17,7 @@ namespace GozareshgirProgramManager.Infrastructure.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.0")
.HasAnnotation("ProductVersion", "10.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
@@ -102,56 +102,6 @@ namespace GozareshgirProgramManager.Infrastructure.Migrations
b.ToTable("Customers", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.HolidayAgg.Holiday", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<string>("Year")
.IsRequired()
.HasMaxLength(4)
.HasColumnType("nvarchar(4)");
b.HasKey("Id");
b.ToTable("Holidays", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.HolidayItemAgg.HolidayItem", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreationDate")
.HasColumnType("datetime2");
b.Property<long>("HolidayId")
.HasColumnType("bigint");
b.Property<string>("HolidayYear")
.IsRequired()
.HasMaxLength(4)
.HasColumnType("nvarchar(4)");
b.Property<DateTime>("Holidaydate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("HolidayId");
b.ToTable("Holidayitems", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.PhaseSection", b =>
{
b.Property<Guid>("Id")
@@ -174,7 +124,9 @@ namespace GozareshgirProgramManager.Infrastructure.Migrations
b.HasIndex("PhaseId");
b.ToTable("PhaseSections");
b.HasIndex("SkillId");
b.ToTable("PhaseSections", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.Project", b =>
@@ -284,7 +236,9 @@ namespace GozareshgirProgramManager.Infrastructure.Migrations
b.HasIndex("ProjectId");
b.ToTable("ProjectSections");
b.HasIndex("SkillId");
b.ToTable("ProjectSections", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectTask", b =>
@@ -630,17 +584,6 @@ namespace GozareshgirProgramManager.Infrastructure.Migrations
b.ToTable("UserRefreshTokens", (string)null);
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.HolidayItemAgg.HolidayItem", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.HolidayAgg.Holiday", "Holidayss")
.WithMany("HolidayItems")
.HasForeignKey("HolidayId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Holidayss");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.PhaseSection", b =>
{
b.HasOne("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectPhase", "Phase")
@@ -649,7 +592,14 @@ namespace GozareshgirProgramManager.Infrastructure.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GozareshgirProgramManager.Domain.SkillAgg.Entities.Skill", "Skill")
.WithMany()
.HasForeignKey("SkillId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Phase");
b.Navigation("Skill");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectPhase", b =>
@@ -671,7 +621,14 @@ namespace GozareshgirProgramManager.Infrastructure.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GozareshgirProgramManager.Domain.SkillAgg.Entities.Skill", "Skill")
.WithMany()
.HasForeignKey("SkillId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Project");
b.Navigation("Skill");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.ProjectTask", b =>
@@ -856,11 +813,6 @@ namespace GozareshgirProgramManager.Infrastructure.Migrations
b.Navigation("User");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.HolidayAgg.Holiday", b =>
{
b.Navigation("HolidayItems");
});
modelBuilder.Entity("GozareshgirProgramManager.Domain.ProjectAgg.Entities.Project", b =>
{
b.Navigation("Phases");

View File

@@ -17,5 +17,11 @@ public class PhaseSectionMapping:IEntityTypeConfiguration<PhaseSection>
.WithMany(p => p.PhaseSections)
.HasForeignKey(ps => ps.PhaseId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(ps => ps.Skill)
.WithMany()
.HasForeignKey(ps => ps.SkillId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Restrict);
}
}

View File

@@ -16,5 +16,11 @@ public class ProjectSectionMapping:IEntityTypeConfiguration<ProjectSection>
.WithMany(x => x.ProjectSections)
.HasForeignKey(x => x.ProjectId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(x => x.Skill)
.WithMany()
.HasForeignKey(x => x.SkillId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Restrict);
}
}

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