Compare commits

...

51 Commits

Author SHA1 Message Date
adf297455f feat: enhance Excel export for institution contracts by removing row number and adding dynamic physical contract status 2025-12-29 17:20:07 +03:30
8b6786c09a add route for excel download 2025-12-28 19:20:25 +03:30
45c5d20323 add excel download 2025-12-28 19:17:50 +03:30
aa0eae6c83 feat: implement Excel export for institution contracts with categorized tabs 2025-12-28 13:01:40 +03:30
SamSys
8bc9e044ae Warning Mesage For EmployeeShare bug Fixed 2025-12-27 18:24:50 +03:30
SamSys
27e8d302d9 Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-27 12:06:35 +03:30
92e1d6de5c Merge branch 'Feature/institution-contract/refactor-list' 2025-12-27 10:26:35 +03:30
c488f61a09 refactor: enhance error logging and add installment amount to institution contract view model 2025-12-27 10:26:12 +03:30
SamSys
dc703fad3c Merge branch 'master' of https://github.com/samsyntax24/OriginalGozareshgir 2025-12-25 17:56:45 +03:30
54e5904951 add from form to verify gateway 2025-12-25 17:16:07 +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
SamSys
d254da1393 bacgrountTask InstitutionContract some changes 2025-12-25 12:32:10 +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
45 changed files with 1662 additions and 783 deletions

View File

@@ -37,7 +37,7 @@ jobs:
& "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" ` & "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" `
-verb:sync ` -verb:sync `
-source:contentPath="$publishFolder" ` -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 ` -allowUntrusted `
-enableRule:AppOffline -enableRule:AppOffline

View File

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

View File

@@ -24,9 +24,13 @@ public class CustomExceptionHandler : IExceptionHandler
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken cancellationToken) public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken cancellationToken)
{ {
_logger.LogError( _logger.LogError(exception,
"Error Message: {exceptionMessage}, Time of occurrence {time}", "Error Message: {exceptionMessage}, Type: {exceptionType}, Time: {time}, Path: {path}, TraceId: {traceId}",
exception.Message, DateTime.UtcNow); 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 (string Detail, string Title, int StatusCode, Dictionary<string, object>? Extra) details = exception switch
{ {

View File

@@ -17,4 +17,9 @@
<ProjectReference Include="..\..\WorkFlow\Infrastructure\WorkFlow.Infrastructure.Config\WorkFlow.Infrastructure.Config.csproj" /> <ProjectReference Include="..\..\WorkFlow\Infrastructure\WorkFlow.Infrastructure.Config\WorkFlow.Infrastructure.Config.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
</ItemGroup>
</Project> </Project>

View File

@@ -15,19 +15,21 @@ public class JobSchedulerRegistrator
private static DateTime? _lastRunCreateTransaction; private static DateTime? _lastRunCreateTransaction;
private static DateTime? _lastRunSendMonthlySms; private static DateTime? _lastRunSendMonthlySms;
private readonly ISmsService _smsService; private readonly ISmsService _smsService;
private readonly ILogger<JobSchedulerRegistrator> _logger;
public JobSchedulerRegistrator(SmsReminder smsReminder, IBackgroundJobClient backgroundJobClient, IInstitutionContractRepository institutionContractRepository, ISmsService smsService) public JobSchedulerRegistrator(SmsReminder smsReminder, IBackgroundJobClient backgroundJobClient, IInstitutionContractRepository institutionContractRepository, ISmsService smsService, ILogger<JobSchedulerRegistrator> logger)
{ {
_smsReminder = smsReminder; _smsReminder = smsReminder;
_backgroundJobClient = backgroundJobClient; _backgroundJobClient = backgroundJobClient;
_institutionContractRepository = institutionContractRepository; _institutionContractRepository = institutionContractRepository;
_smsService = smsService; _smsService = smsService;
_logger = logger;
} }
public void Register() public void Register()
{ {
_logger.LogInformation("hangfire Started");
RecurringJob.AddOrUpdate( RecurringJob.AddOrUpdate(
"InstitutionContract.CreateFinancialTransaction", "InstitutionContract.CreateFinancialTransaction",
() => CreateFinancialTransaction(), () => CreateFinancialTransaction(),
@@ -68,7 +70,7 @@ public class JobSchedulerRegistrator
var now =DateTime.Now; var now =DateTime.Now;
var endOfMonth = now.ToFarsi().FindeEndOfMonth(); var endOfMonth = now.ToFarsi().FindeEndOfMonth();
var endOfMonthGr = endOfMonth.ToGeorgianDateTime(); var endOfMonthGr = endOfMonth.ToGeorgianDateTime();
_logger.LogInformation("CreateFinancialTransaction job run");
if (now.Date == endOfMonthGr.Date && now.Hour >= 2 && now.Hour < 4 && if (now.Date == endOfMonthGr.Date && now.Hour >= 2 && now.Hour < 4 &&
now.Date != _lastRunCreateTransaction?.Date) now.Date != _lastRunCreateTransaction?.Date)
{ {
@@ -113,7 +115,7 @@ public class JobSchedulerRegistrator
var now = DateTime.Now; var now = DateTime.Now;
var endOfMonth = now.ToFarsi().FindeEndOfMonth(); var endOfMonth = now.ToFarsi().FindeEndOfMonth();
var endOfMonthGr = endOfMonth.ToGeorgianDateTime(); var endOfMonthGr = endOfMonth.ToGeorgianDateTime();
_logger.LogInformation("SendFirstDayOfMonthSms job run");
if (now.Date == endOfMonthGr.Date && now.Hour >= 10 && now.Hour < 11 && if (now.Date == endOfMonthGr.Date && now.Hour >= 10 && now.Hour < 11 &&
now.Date != _lastRunSendMonthlySms?.Date) now.Date != _lastRunSendMonthlySms?.Date)
{ {
@@ -141,6 +143,7 @@ public class JobSchedulerRegistrator
[DisableConcurrentExecution(timeoutInSeconds: 1200)] [DisableConcurrentExecution(timeoutInSeconds: 1200)]
public async System.Threading.Tasks.Task SendReminderSms() public async System.Threading.Tasks.Task SendReminderSms()
{ {
_logger.LogInformation("SendReminderSms job run");
await _institutionContractRepository.SendReminderSmsForBackgroundTask(); await _institutionContractRepository.SendReminderSmsForBackgroundTask();
} }
@@ -151,6 +154,7 @@ public class JobSchedulerRegistrator
[DisableConcurrentExecution(timeoutInSeconds: 100)] [DisableConcurrentExecution(timeoutInSeconds: 100)]
public async System.Threading.Tasks.Task SendBlockSms() public async System.Threading.Tasks.Task SendBlockSms()
{ {
_logger.LogInformation("SendBlockSms job run");
await _institutionContractRepository.SendBlockSmsForBackgroundTask(); await _institutionContractRepository.SendBlockSmsForBackgroundTask();
} }
@@ -162,6 +166,7 @@ public class JobSchedulerRegistrator
[DisableConcurrentExecution(timeoutInSeconds: 100)] [DisableConcurrentExecution(timeoutInSeconds: 100)]
public async System.Threading.Tasks.Task SendInstitutionContractConfirmSms() public async System.Threading.Tasks.Task SendInstitutionContractConfirmSms()
{ {
_logger.LogInformation("SendInstitutionContractConfirmSms job run");
await _institutionContractRepository.SendInstitutionContractConfirmSmsTask(); await _institutionContractRepository.SendInstitutionContractConfirmSmsTask();
} }

View File

@@ -17,9 +17,37 @@ using Microsoft.AspNetCore.Identity;
using MongoDB.Driver; using MongoDB.Driver;
using PersonalContractingParty.Config; using PersonalContractingParty.Config;
using Query.Bootstrapper; using Query.Bootstrapper;
using Serilog;
using Serilog.Events;
using Shared.Contracts.PmUser.Queries; using Shared.Contracts.PmUser.Queries;
using WorkFlow.Infrastructure.Config; 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)
//.MinimumLevel.Information()
.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 builder = WebApplication.CreateBuilder(args);
var hangfireConnectionString = builder.Configuration.GetConnectionString("HangfireDb"); var hangfireConnectionString = builder.Configuration.GetConnectionString("HangfireDb");
builder.Services.AddHangfire(x => x.UseSqlServerStorage(hangfireConnectionString)); builder.Services.AddHangfire(x => x.UseSqlServerStorage(hangfireConnectionString));
@@ -59,7 +87,13 @@ builder.Services.AddHttpClient();
builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpContextAccessor();
builder.Services.AddSignalR(); builder.Services.AddSignalR();
builder.Host.UseSerilog();
Log.Information("SERILOG STARTED SUCCESSFULLY");
var app = builder.Build(); var app = builder.Build();
app.MapHub<SendSmsHub>("/sendSmsHub"); app.MapHub<SendSmsHub>("/sendSmsHub");
app.MapHangfireDashboard(); app.MapHangfireDashboard();

View File

@@ -25,8 +25,8 @@
//mahan Docker //mahan Docker
//"MesbahDb": "Data Source=localhost,5069;Initial Catalog=mesbah_db;User ID=sa;Password=YourPassword123;TrustServerCertificate=True;", //"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=.;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=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": { "GoogleRecaptchaV3": {

View File

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

View File

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

View File

@@ -8,86 +8,129 @@ using System.Text.RegularExpressions;
namespace CompanyManagement.Infrastructure.Excel.InstitutionContract; namespace CompanyManagement.Infrastructure.Excel.InstitutionContract;
// Enum برای تعریف ستون‌های موجود
public enum ExcelColumnType
{
RowNumber, // ردیف
PhysicalContract, // قرارداد فیزیکی
ContractNo, // شماره قرارداد
Representative, // معرف
ContractingPartyName, // طرف حساب
ArchiveCode, // شماره کارفرما
EmployerName, // کارفرما
WorkshopName, // کارگاه‌ها (چندخطی)
WorkshopCount, // تعداد کارگاه
EmployeeCount, // مجموع پرسنل
ContractStartDate, // شروع قرارداد
ContractEndDate, // پایان قرارداد
InstallmentAmount, // مبلغ قسط
ContractAmount, // مبلغ قرارداد
FinancialStatus // وضعیت مالی
}
// کلاس کانفیگ برای تنظیم ستون‌های نمایشی
public class ExcelColumnConfig
{
public List<ExcelColumnType> VisibleColumns { get; set; }
public ExcelColumnConfig()
{
// فعلاً تمام ستون‌ها فعال هستند
VisibleColumns = new List<ExcelColumnType>
{
ExcelColumnType.PhysicalContract,
ExcelColumnType.ContractNo,
ExcelColumnType.Representative,
ExcelColumnType.ContractingPartyName,
ExcelColumnType.ArchiveCode,
ExcelColumnType.EmployerName,
ExcelColumnType.WorkshopName,
ExcelColumnType.WorkshopCount,
ExcelColumnType.EmployeeCount,
ExcelColumnType.ContractStartDate,
ExcelColumnType.ContractEndDate,
ExcelColumnType.InstallmentAmount,
ExcelColumnType.ContractAmount,
ExcelColumnType.FinancialStatus
};
}
}
public class InstitutionContractExcelGenerator public class InstitutionContractExcelGenerator
{ {
private static ExcelColumnConfig _columnConfig = new ExcelColumnConfig();
public static byte[] GenerateExcel(List<InstitutionContractViewModel> institutionContractViewModels) public static byte[] GenerateExcel(List<InstitutionContractExcelViewModel> contractViewModels)
{ {
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization"); ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
using var package = new ExcelPackage(); using var package = new ExcelPackage();
var allWorksheet = package.Workbook.Worksheets.Add("همه");
var blueWorksheet = package.Workbook.Worksheets.Add("آبی");
blueWorksheet.TabColor = Color.LightBlue;
var grayWorksheet = package.Workbook.Worksheets.Add("خاکستری");
grayWorksheet.TabColor = Color.LightGray;
var redWorksheet = package.Workbook.Worksheets.Add("قرمز");
redWorksheet.TabColor = Color.LightCoral;
var purpleWorksheet = package.Workbook.Worksheets.Add("بنفش");
purpleWorksheet.TabColor = Color.MediumPurple;
var blackWorksheet = package.Workbook.Worksheets.Add("مشکی");
blackWorksheet.TabColor = Color.DimGray;
var yellowWorksheet = package.Workbook.Worksheets.Add("زرد");
yellowWorksheet.TabColor = Color.Yellow;
var whiteWorksheet = package.Workbook.Worksheets.Add("سفید");
whiteWorksheet.TabColor = Color.White;
CreateExcelSheet(institutionContractViewModels, allWorksheet);
var blueContracts = institutionContractViewModels.Where(x=>x.ExpireColor == "blue").ToList();
CreateExcelSheet(blueContracts, blueWorksheet);
institutionContractViewModels = institutionContractViewModels.Except(blueContracts).ToList();
var grayContracts = institutionContractViewModels.Where(x => x.IsContractingPartyBlock == "true").ToList();
CreateExcelSheet(grayContracts, grayWorksheet);
institutionContractViewModels = institutionContractViewModels.Except(grayContracts).ToList();
var redContracts = institutionContractViewModels.Where(x=>x.ExpireColor == "red").ToList();
CreateExcelSheet(redContracts, redWorksheet);
institutionContractViewModels = institutionContractViewModels.Except(redContracts).ToList();
var purpleContracts = institutionContractViewModels.Where(x=>x.ExpireColor == "purple").ToList();
CreateExcelSheet(purpleContracts, purpleWorksheet);
institutionContractViewModels = institutionContractViewModels.Except(purpleContracts).ToList();
var blackContracts = institutionContractViewModels.Where(x=>x.ExpireColor == "black").ToList(); // ایجاد شیت برای هر تب با داده‌های مربوطه
CreateExcelSheet(blackContracts, blackWorksheet); foreach (var viewModel in contractViewModels)
institutionContractViewModels = institutionContractViewModels.Except(blackContracts).ToList(); {
var worksheet = CreateWorksheet(package, viewModel.Tab);
var yellowContracts = institutionContractViewModels CreateExcelSheet(viewModel.GetInstitutionContractListItemsViewModels ?? new List<GetInstitutionContractListItemsViewModel>(), worksheet);
.Where(x => string.IsNullOrWhiteSpace(x.ExpireColor) && x.WorkshopCount == "0").ToList(); }
CreateExcelSheet(yellowContracts, yellowWorksheet);
institutionContractViewModels = institutionContractViewModels.Except(yellowContracts).ToList();
var otherContracts = institutionContractViewModels;
CreateExcelSheet(otherContracts, whiteWorksheet);
return package.GetAsByteArray(); return package.GetAsByteArray();
} }
private static void CreateExcelSheet(List<InstitutionContractViewModel> institutionContractViewModels, ExcelWorksheet worksheet) /// <summary>
/// ایجاد شیت بر اساس نوع تب
/// </summary>
private static ExcelWorksheet CreateWorksheet(ExcelPackage package, InstitutionContractListStatus? status)
{ {
// Headers return status switch
worksheet.Cells[1, 1].Value = "شماره قرارداد"; {
worksheet.Cells[1, 2].Value = "طرف حساب"; InstitutionContractListStatus.DeactiveWithDebt =>
worksheet.Cells[1, 3].Value = "شماره کارفرما"; CreateColoredWorksheet(package, "غیرفعال دارای بدهی", Color.LightBlue),
worksheet.Cells[1, 4].Value = "کارفرما ها";
worksheet.Cells[1, 5].Value = "کارگاه ها"; InstitutionContractListStatus.Deactive =>
worksheet.Cells[1, 6].Value = "مجبوع پرسنل"; CreateColoredWorksheet(package, "غیرفعال", Color.LightGray),
worksheet.Cells[1, 7].Value = "شروع قرارداد";
worksheet.Cells[1, 8].Value = "پایان قرارداد"; InstitutionContractListStatus.PendingForRenewal =>
worksheet.Cells[1, 9].Value = "مبلغ قرارداد (بدون کارگاه)"; CreateColoredWorksheet(package, "در انتظار تمدید", Color.LightCoral),
worksheet.Cells[1, 10].Value = "مبلغ قرارداد";
worksheet.Cells[1, 11].Value = "وضعیت مالی"; InstitutionContractListStatus.Free =>
CreateColoredWorksheet(package, "بنفش", Color.MediumPurple),
InstitutionContractListStatus.Block =>
CreateColoredWorksheet(package, "بلاک", Color.DimGray),
InstitutionContractListStatus.WithoutWorkshop =>
CreateColoredWorksheet(package, "بدون کارگاه", Color.Yellow),
InstitutionContractListStatus.Active =>
CreateColoredWorksheet(package, "فعال", Color.White),
InstitutionContractListStatus.PendingForVerify =>
CreateColoredWorksheet(package, "در انتظار تایید", Color.OrangeRed),
null => CreateColoredWorksheet(package, "کل قرارداد ها", Color.White),
_ => throw new ArgumentOutOfRangeException(nameof(status), status, null)
};
}
using (var range = worksheet.Cells[1, 1, 1, 11]) /// <summary>
/// ایجاد شیت با رنگ تب
/// </summary>
private static ExcelWorksheet CreateColoredWorksheet(ExcelPackage package, string sheetName, Color tabColor)
{
var worksheet = package.Workbook.Worksheets.Add(sheetName);
worksheet.TabColor = tabColor;
return worksheet;
}
private static void CreateExcelSheet(List<GetInstitutionContractListItemsViewModel> contractItems, ExcelWorksheet worksheet)
{
// دریافت نقشه ستون‌های مرئی
var visibleColumnIndices = GetVisibleColumnIndices();
int columnCount = visibleColumnIndices.Count;
// تنظیم Headers
SetupHeaders(worksheet, visibleColumnIndices, columnCount);
using (var range = worksheet.Cells[1, 1, 1, columnCount])
{ {
range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
range.Style.VerticalAlignment = ExcelVerticalAlignment.Center; range.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
@@ -110,30 +153,35 @@ public class InstitutionContractExcelGenerator
int row = 2; int row = 2;
for (int i = 0; i < institutionContractViewModels.Count; i++) for (int i = 0; i < contractItems.Count; i++)
{ {
var contract = institutionContractViewModels[i]; var contract = contractItems[i];
var employers = contract.EmployerViewModels?.ToList() ?? new(); var employers = contract.EmployerNames?.ToList() ?? new();
var workshops = contract.WorkshopViewModels?.ToList() ?? new(); var workshops = contract.WorkshopNames?.ToList() ?? new();
int maxRows = Math.Max(employers.Count, workshops.Count); int maxRows = 1; // هر قرارداد فقط یک ردیف؛ نیازی به مرج عمودی نیست
maxRows = Math.Max(1, maxRows);
int startRow = row; int startRow = row;
int endRow = row + maxRows - 1; int endRow = row + maxRows - 1;
// 🎨 دریافت رنگ پس‌زمینه از مقدار رنگ موجود در داده // 🎨 دریافت رنگ پس‌زمینه بر اساس وضعیت قرارداد
string colorName = contract.ExpireColor.ToLower(); var fillColor = GetColorByStatus(contract.ListStatus, contract.WorkshopsCount);
var fillColor = GetColorByName(colorName, contract.WorkshopCount, contract.IsContractingPartyBlock);
for (int j = 0; j < maxRows; j++) for (int j = 0; j < maxRows; j++)
{ {
int currentRow = row + j; int currentRow = row + j;
worksheet.Cells[currentRow, 4].Value = j < employers.Count ? employers[j].FullName : null; // پر کردن ستون‌های employer و workshop
worksheet.Cells[currentRow, 5].Value = j < workshops.Count ? workshops[j].WorkshopFullName : null; var employerColIndex = GetColumnIndexForType(ExcelColumnType.EmployerName, visibleColumnIndices);
var workshopColIndex = GetColumnIndexForType(ExcelColumnType.WorkshopName, visibleColumnIndices);
for (int col = 1; col <= 11; col++) if (employerColIndex > 0)
worksheet.Cells[currentRow, employerColIndex].Value = j < employers.Count ? employers[j] : null;
if (workshopColIndex > 0)
worksheet.Cells[currentRow, workshopColIndex].Value = j < workshops.Count ? workshops[j] : null;
for (int col = 1; col <= columnCount; col++)
{ {
var cell = worksheet.Cells[currentRow, col]; var cell = worksheet.Cells[currentRow, col];
@@ -154,109 +202,235 @@ public class InstitutionContractExcelGenerator
} }
// 🧱 مرج و مقداردهی ستون‌های اصلی // 🧱 مرج و مقداردهی ستون‌های اصلی
worksheet.Cells[startRow, 1, endRow, 1].Merge = true; FillColumnData(worksheet, contract, startRow, endRow, visibleColumnIndices);
worksheet.Cells[startRow, 1].Value = contract.ContractNo;
worksheet.Cells[startRow, 2, endRow, 2].Merge = true;
worksheet.Cells[startRow, 2].Value = contract.ContractingPartyName;
worksheet.Cells[startRow, 3, endRow, 3].Merge = true;
worksheet.Cells[startRow, 3].Value = contract.ArchiveCode;
worksheet.Cells[startRow, 6, endRow, 6].Merge = true;
worksheet.Cells[startRow, 6].Value = contract.EmployeeCount;
worksheet.Cells[startRow, 7, endRow, 7].Merge = true;
worksheet.Cells[startRow, 7].Value = contract.ContractStartFa;
worksheet.Cells[startRow, 8, endRow, 8].Merge = true;
worksheet.Cells[startRow, 8].Value = contract.ContractEndFa;
worksheet.Cells[startRow, 9, endRow, 9].Merge = true;
var contractWithoutWorkshopAmountCell = worksheet.Cells[startRow, 9];
contractWithoutWorkshopAmountCell.Value = contract.WorkshopCount == "0" ? MoneyToDouble(contract.ContractAmount) : "";
contractWithoutWorkshopAmountCell.Style.Numberformat.Format = "#,##0";
worksheet.Cells[startRow, 10, endRow, 10].Merge = true;
var contractAmountCell = worksheet.Cells[startRow, 10];
contractAmountCell.Value = contract.WorkshopCount != "0" ? MoneyToDouble(contract.ContractAmount) : "";
contractAmountCell.Style.Numberformat.Format = "#,##0";
worksheet.Cells[startRow, 11, endRow, 11].Merge = true;
var balance = MoneyToDouble(contract.BalanceStr);
var balanceCell = worksheet.Cells[startRow, 11];
balanceCell.Value = balance;
balanceCell.Style.Numberformat.Format = "#,##0";
if (balance > 0)
balanceCell.Style.Font.Color.SetColor(Color.Red);
else if (balance < 0)
balanceCell.Style.Font.Color.SetColor(Color.Green);
// 📦 بوردر ضخیم خارجی برای هر سطر // 📦 بوردر ضخیم خارجی برای هر سطر
var boldRange = worksheet.Cells[startRow, 1, endRow, 11]; var boldRange = worksheet.Cells[startRow, 1, endRow, columnCount];
boldRange.Style.Border.BorderAround(ExcelBorderStyle.Medium); boldRange.Style.Border.BorderAround(ExcelBorderStyle.Medium);
row += maxRows; row += maxRows;
} }
SetupPrintSettings(worksheet, visibleColumnIndices, columnCount);
}
/// <summary>
/// دریافت فهرست ستون‌های مرئی بر اساس کانفیگ
/// </summary>
private static List<ExcelColumnType> GetVisibleColumnIndices()
{
return _columnConfig.VisibleColumns;
}
/// <summary>
/// دریافت شماره ستون برای یک نوع ستون خاص
/// </summary>
private static int GetColumnIndexForType(ExcelColumnType columnType, List<ExcelColumnType> visibleColumns)
{
var index = visibleColumns.IndexOf(columnType);
return index >= 0 ? index + 1 : 0; // 1-based indexing
}
/// <summary>
/// دریافت متن header برای یک نوع ستون
/// </summary>
private static string GetColumnHeader(ExcelColumnType columnType)
{
return columnType switch
{
ExcelColumnType.RowNumber => "ردیف",
ExcelColumnType.PhysicalContract => "قرارداد فیزیکی",
ExcelColumnType.ContractNo => "شماره قرارداد",
ExcelColumnType.Representative => "معرف",
ExcelColumnType.ContractingPartyName => "طرف حساب",
ExcelColumnType.ArchiveCode => "شماره کارفرما",
ExcelColumnType.EmployerName => "کارفرما",
ExcelColumnType.WorkshopName => "کارگاه‌ها",
ExcelColumnType.WorkshopCount => "تعداد کارگاه",
ExcelColumnType.EmployeeCount => "مجموع پرسنل",
ExcelColumnType.ContractStartDate => "شروع قرارداد",
ExcelColumnType.ContractEndDate => "پایان قرارداد",
ExcelColumnType.InstallmentAmount => "مبلغ قسط",
ExcelColumnType.ContractAmount => "مبلغ قرارداد",
ExcelColumnType.FinancialStatus => "وضعیت مالی",
_ => ""
};
}
/// <summary>
/// تنظیم Headerهای ستون‌ها
/// </summary>
private static void SetupHeaders(ExcelWorksheet worksheet, List<ExcelColumnType> visibleColumns, int columnCount)
{
for (int i = 0; i < visibleColumns.Count; i++)
{
worksheet.Cells[1, i + 1].Value = GetColumnHeader(visibleColumns[i]);
}
}
/// <summary>
/// پر کردن داده‌های ستون‌ها برای یک قرارداد
/// </summary>
private static void FillColumnData(ExcelWorksheet worksheet, GetInstitutionContractListItemsViewModel contract, int startRow, int endRow, List<ExcelColumnType> visibleColumns)
{
for (int i = 0; i < visibleColumns.Count; i++)
{
int columnIndex = i + 1; // 1-based indexing
var columnType = visibleColumns[i];
// Merge cells for non-repeating columns
worksheet.Cells[startRow, columnIndex, endRow, columnIndex].Merge = true;
var cell = worksheet.Cells[startRow, columnIndex];
switch (columnType)
{
case ExcelColumnType.PhysicalContract:
var physicalText = contract.IsOldContract
? (contract.HasSigniture ? "موجود" : "ناموجود")
: (contract.IsInPersonContract ? "الکترونیکی حضوری" : "الکترونیکی غیر حضوری");
cell.Value = physicalText;
cell.Style.Font.Bold = true;
cell.Style.Font.Color.SetColor(physicalText switch
{
"موجود" => Color.Green,
"ناموجود" => Color.Red,
"الکترونیکی حضوری" => Color.Purple,
_ => Color.Blue
});
break;
case ExcelColumnType.ContractNo:
cell.Value = contract.ContractNo;
break;
case ExcelColumnType.Representative:
cell.Value = contract.RepresentativeName;
break;
case ExcelColumnType.ContractingPartyName:
cell.Value = contract.ContractingPartyName;
break;
case ExcelColumnType.ArchiveCode:
cell.Value = contract.ArchiveNo;
break;
case ExcelColumnType.EmployerName:
// این ستون چندخطی است و داخل loop پر می‌شود
break;
case ExcelColumnType.WorkshopName:
// این ستون چندخطی است و داخل loop پر می‌شود
break;
case ExcelColumnType.WorkshopCount:
cell.Value = contract.WorkshopsCount;
break;
case ExcelColumnType.EmployeeCount:
cell.Value = contract.EmployeesCount;
break;
case ExcelColumnType.ContractStartDate:
cell.Value = contract.ContractStartFa;
break;
case ExcelColumnType.ContractEndDate:
cell.Value = contract.ContractEndFa;
break;
case ExcelColumnType.InstallmentAmount:
cell.Value = contract.InstallmentAmount;
cell.Style.Numberformat.Format = "#,##0";
break;
case ExcelColumnType.ContractAmount:
cell.Value = contract.ContractAmount;
cell.Style.Numberformat.Format = "#,##0";
break;
case ExcelColumnType.FinancialStatus:
cell.Value = contract.Balance;
cell.Style.Numberformat.Format = "#,##0";
if (contract.Balance > 0)
cell.Style.Font.Color.SetColor(Color.Red);
else if (contract.Balance < 0)
cell.Style.Font.Color.SetColor(Color.Green);
break;
}
}
}
/// <summary>
/// تنظیم تنظیمات چاپ و عرض ستون‌ها
/// </summary>
private static void SetupPrintSettings(ExcelWorksheet worksheet, List<ExcelColumnType> visibleColumns, int columnCount)
{
worksheet.PrinterSettings.PaperSize = ePaperSize.A4; worksheet.PrinterSettings.PaperSize = ePaperSize.A4;
worksheet.PrinterSettings.Orientation = eOrientation.Landscape; worksheet.PrinterSettings.Orientation = eOrientation.Landscape;
worksheet.PrinterSettings.FitToPage = true; worksheet.PrinterSettings.FitToPage = true;
worksheet.PrinterSettings.FitToWidth = 1; worksheet.PrinterSettings.FitToWidth = 1;
worksheet.PrinterSettings.FitToHeight = 0; worksheet.PrinterSettings.FitToHeight = 0;
worksheet.PrinterSettings.Scale = 85; worksheet.PrinterSettings.Scale = 85;
int contractNoCol = 1;
int contractingPartyNameCol = 2; // تنظیم عرض ستون‌ها بر اساس نوع ستون
int archiveNoCol = 3; for (int i = 0; i < visibleColumns.Count; i++)
int employersCol = 4; {
int workshopsCol = 5; int columnIndex = i + 1;
int employeeCountCol = 6; worksheet.Columns[columnIndex].Width = GetColumnWidth(visibleColumns[i]);
int startContractCol = 7; }
int endContractCol = 8;
int contractWithoutWorkshopAmountCol = 9;
int contractAmountCol = 10;
int balanceCol = 11;
worksheet.Columns[contractNoCol].Width = 17;
worksheet.Columns[contractingPartyNameCol].Width = 40;
worksheet.Columns[archiveNoCol].Width = 10;
worksheet.Columns[employersCol].Width = 40;
worksheet.Columns[workshopsCol].Width = 45;
worksheet.Columns[employeeCountCol].Width = 12;
worksheet.Columns[startContractCol].Width = 12;
worksheet.Columns[endContractCol].Width = 12;
worksheet.Columns[contractWithoutWorkshopAmountCol].Width = 18;
worksheet.Columns[contractAmountCol].Width = 12;
worksheet.Columns[balanceCol].Width = 12;
worksheet.View.RightToLeft = true; // فارسی worksheet.View.RightToLeft = true; // فارسی
//worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); }
/// <summary>
/// دریافت عرض ستون پیش‌فرض برای هر نوع ستون
/// </summary>
private static double GetColumnWidth(ExcelColumnType columnType)
{
return columnType switch
{
ExcelColumnType.RowNumber => 8,
ExcelColumnType.PhysicalContract => 15,
ExcelColumnType.ContractNo => 17,
ExcelColumnType.Representative => 15,
ExcelColumnType.ContractingPartyName => 40,
ExcelColumnType.ArchiveCode => 10,
ExcelColumnType.EmployerName => 40,
ExcelColumnType.WorkshopName => 45,
ExcelColumnType.WorkshopCount => 12,
ExcelColumnType.EmployeeCount => 12,
ExcelColumnType.ContractStartDate => 12,
ExcelColumnType.ContractEndDate => 12,
ExcelColumnType.InstallmentAmount => 15,
ExcelColumnType.ContractAmount => 15,
ExcelColumnType.FinancialStatus => 12,
_ => 12
};
} }
private static double MoneyToDouble(string value) private static double MoneyToDouble(string value)
{ {
Console.WriteLine(value); if (string.IsNullOrEmpty(value))
return 0;
var min = value.Length > 1 ? value.Substring(0, 2) : ""; var min = value.Length > 1 ? value.Substring(0, 2) : "";
var test = min == "\u200e\u2212" ? value.MoneyToDouble() * -1 : value.MoneyToDouble(); var test = min == "\u200e\u2212" ? value.MoneyToDouble() * -1 : value.MoneyToDouble();
Console.WriteLine(test);
return test; return test;
} }
private static Color GetColorByName(string name, string workshopCount, string IsContractingPartyBlock)
/// <summary>
/// دریافت رنگ بر اساس وضعیت قرارداد
/// </summary>
private static Color GetColorByStatus(InstitutionContractListStatus status, int workshopsCount)
{ {
return name switch return status switch
{ {
"blue" => Color.LightBlue, InstitutionContractListStatus.DeactiveWithDebt => Color.LightBlue,
_ when IsContractingPartyBlock == "true" => Color.LightGray, InstitutionContractListStatus.Deactive => Color.LightGray,
"red" => Color.LightCoral, InstitutionContractListStatus.PendingForRenewal => Color.LightCoral,
"purple" => Color.MediumPurple, InstitutionContractListStatus.Free => Color.MediumPurple,
"black" => Color.DimGray, InstitutionContractListStatus.Block => Color.DimGray,
var n when string.IsNullOrWhiteSpace(n) && workshopCount == "0" => Color.Yellow, InstitutionContractListStatus.WithoutWorkshop => Color.Yellow,
InstitutionContractListStatus.Active => Color.White,
_ => Color.White _ => Color.White
}; };
} }
} }
public class InstitutionContractExcelViewModel
{
public InstitutionContractListStatus? Tab { get; set; }
public List<GetInstitutionContractListItemsViewModel> GetInstitutionContractListItemsViewModels { get; set; }
}

View File

@@ -94,7 +94,42 @@ public interface IEmployeeApplication
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
Task<List<GetEmployeeListViewModel>> GetList(GetEmployeeListSearchModel searchModel); 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 #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

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

View File

@@ -18,6 +18,16 @@ public class InstitutionContractPaymentOneTimeViewModel
/// </summary> /// </summary>
public string PaymentAmount { get; set; } 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 string DiscountedAmount { get; set; }
public int DiscountPercetage { get; set; } public int DiscountPercetage { get; set; }
} }

View File

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

View File

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

View File

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

View File

@@ -1729,5 +1729,10 @@ public class EmployeeAplication : RepositoryBase<long, Employee>, IEmployeeAppli
return await _EmployeeRepository.GetList(searchModel); return await _EmployeeRepository.GetList(searchModel);
} }
public async Task<List<GetClientEmployeeListViewModel>> GetClientEmployeeList(GetClientEmployeeListSearchModel searchModel, long workshopId)
{
return await _EmployeeRepository.GetClientEmployeeList(searchModel, workshopId);
}
#endregion #endregion
} }

View File

@@ -22,6 +22,7 @@ using Company.Domain.InstitutionContractAgg;
using Company.Domain.LeftWorkAgg; using Company.Domain.LeftWorkAgg;
using Company.Domain.PaymentTransactionAgg; using Company.Domain.PaymentTransactionAgg;
using Company.Domain.RepresentativeAgg; using Company.Domain.RepresentativeAgg;
using Company.Domain.RollCallServiceAgg;
using Company.Domain.TemporaryClientRegistrationAgg; using Company.Domain.TemporaryClientRegistrationAgg;
using Company.Domain.WorkshopAgg; using Company.Domain.WorkshopAgg;
using CompanyManagment.App.Contracts.FinancialInvoice; using CompanyManagment.App.Contracts.FinancialInvoice;
@@ -59,6 +60,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
private readonly IFinancialInvoiceRepository _financialInvoiceRepository; private readonly IFinancialInvoiceRepository _financialInvoiceRepository;
private readonly IPaymentGateway _paymentGateway; private readonly IPaymentGateway _paymentGateway;
private readonly IPaymentTransactionRepository _paymentTransactionRepository; private readonly IPaymentTransactionRepository _paymentTransactionRepository;
private readonly IRollCallServiceRepository _rollCallServiceRepository;
public InstitutionContractApplication(IInstitutionContractRepository institutionContractRepository, public InstitutionContractApplication(IInstitutionContractRepository institutionContractRepository,
@@ -70,7 +72,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
IFinancialStatmentRepository financialStatmentRepository, IContactInfoApplication contactInfoApplication, IFinancialStatmentRepository financialStatmentRepository, IContactInfoApplication contactInfoApplication,
IAccountApplication accountApplication, ISmsService smsService, IUidService uidService, IAccountApplication accountApplication, ISmsService smsService, IUidService uidService,
IFinancialInvoiceRepository financialInvoiceRepository, IHttpClientFactory httpClientFactory, IFinancialInvoiceRepository financialInvoiceRepository, IHttpClientFactory httpClientFactory,
IPaymentTransactionRepository paymentTransactionRepository) IPaymentTransactionRepository paymentTransactionRepository, IRollCallServiceRepository rollCallServiceRepository)
{ {
_institutionContractRepository = institutionContractRepository; _institutionContractRepository = institutionContractRepository;
_contractingPartyRepository = contractingPartyRepository; _contractingPartyRepository = contractingPartyRepository;
@@ -88,6 +90,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
_uidService = uidService; _uidService = uidService;
_financialInvoiceRepository = financialInvoiceRepository; _financialInvoiceRepository = financialInvoiceRepository;
_paymentTransactionRepository = paymentTransactionRepository; _paymentTransactionRepository = paymentTransactionRepository;
_rollCallServiceRepository = rollCallServiceRepository;
_paymentGateway = new SepehrPaymentGateway(httpClientFactory); _paymentGateway = new SepehrPaymentGateway(httpClientFactory);
} }
@@ -1555,28 +1558,48 @@ public class InstitutionContractApplication : IInstitutionContractApplication
.Where(x => x.WorkshopCreated && x.WorkshopId is > 0).ToList(); .Where(x => x.WorkshopCreated && x.WorkshopId is > 0).ToList();
var currentWorkshops = institutionContract.WorkshopGroup.CurrentWorkshops.ToList(); var currentWorkshops = institutionContract.WorkshopGroup.CurrentWorkshops.ToList();
var accountId = _contractingPartyRepository
.GetAccountByPersonalContractingParty(institutionContract.ContractingPartyId).Id;
foreach (var createdWorkshop in initialCreatedWorkshops) foreach (var createdWorkshop in initialCreatedWorkshops)
{ {
if (currentWorkshops.Any(x => x.WorkshopId == createdWorkshop.WorkshopId)) if (currentWorkshops.Any(x => x.WorkshopId == createdWorkshop.WorkshopId))
{ {
continue; //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);
} }
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)) if (institutionContract.WorkshopGroup.InitialWorkshops.All(x => x.WorkshopCreated && x.WorkshopId is > 0))
{ {
institutionContract.Verified(); institutionContract.Verified();
} }
else else
@@ -1585,7 +1608,10 @@ public class InstitutionContractApplication : IInstitutionContractApplication
} }
institutionContract.SetSigningType(signingType); institutionContract.SetSigningType(signingType);
var previousInstitutionContract = await _institutionContractRepository
.GetPreviousContract(institutionContract.id);
previousInstitutionContract?.DeActive();
ReActiveAllAfterCreateNew(institutionContract.ContractingPartyId);
await _institutionContractRepository.SaveChangesAsync(); await _institutionContractRepository.SaveChangesAsync();
return op.Succcedded(); return op.Succcedded();
} }
@@ -1611,9 +1637,23 @@ public class InstitutionContractApplication : IInstitutionContractApplication
var transaction = await _institutionContractRepository.BeginTransactionAsync(); var transaction = await _institutionContractRepository.BeginTransactionAsync();
await SetPendingWorkflow(institutionContractId,InstitutionContractSigningType.Physical); 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 transaction.CommitAsync();
await _institutionContractRepository.SaveChangesAsync(); await _institutionContractRepository.SaveChangesAsync();
await transaction.CommitAsync();
return op.Succcedded(); return op.Succcedded();
} }

View File

@@ -788,7 +788,7 @@ public class RollCallApplication : IRollCallApplication
return _rollCallRepository.CheckRepeat(employeeId, workshopId); 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(); var operationResult = new OperationResult();
try try
@@ -812,24 +812,43 @@ public class RollCallApplication : IRollCallApplication
var oldestDate = commands.MinBy(x => x.FromDate).FromDate.ToGeorgianDateTime(); var oldestDate = commands.MinBy(x => x.FromDate).FromDate.ToGeorgianDateTime();
var allRollCalls = _rollCallRepository var allRollCalls = await _rollCallRepository
.GetRollCallsUntilNowWithWorkshopIdEmployeeIds(workshopId, commands.Select(x => x.EmployeeId).ToList(), .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 rollCall in rollCalls)
foreach (var command in commands)
{ {
var rollCalls = allRollCalls rollCall.ClearTimeDiff();
.Where(x => x.EmployeeId == command.EmployeeId && x.ShiftDate >= command.FromDate.ToGeorgianDateTime()).ToList();
foreach (var rollCall in rollCalls) await _rollCallRepository.SaveChangesAsync();
{
rollCall.ClearTimeDiff(); rollCall.SetEndDateTime(
_rollCallRepository.SaveChanges(); rollCall.EndDate!.Value,
rollCall.SetEndDateTime(rollCall.EndDate!.Value, _rollCallDomainService); _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(); return operationResult.Succcedded();
} }

View File

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

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) public OperationResult ActiveAll(long id)
{ {
OperationResult result = new OperationResult(); 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); 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();
transaction.Commit();
result.Succcedded();
}
catch (Exception)
{
result.Failed("فعال کردن کارفرما با خطا مواجه شد");
transaction.Rollback();
} }
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; return result;

View File

@@ -25,6 +25,7 @@ using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using CompanyManagment.App.Contracts.Workshop; using CompanyManagment.App.Contracts.Workshop;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MongoDB.Driver; using MongoDB.Driver;
using PersianTools.Core; using PersianTools.Core;
using System; using System;
@@ -54,6 +55,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
private readonly IFinancialTransactionRepository _financialTransactionRepository; private readonly IFinancialTransactionRepository _financialTransactionRepository;
private readonly IFinancialStatmentRepository _financialStatmentRepository; private readonly IFinancialStatmentRepository _financialStatmentRepository;
private readonly IHubContext<SendSmsHub> _hubContext; private readonly IHubContext<SendSmsHub> _hubContext;
private readonly ILogger<InstitutionContractRepository> _logger;
private readonly InstitutionContratVerificationParty _firstParty = new() private readonly InstitutionContratVerificationParty _firstParty = new()
{ {
@@ -69,7 +71,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
IWorkshopRepository workshopRepository, IMongoDatabase database, IWorkshopRepository workshopRepository, IMongoDatabase database,
IPlanPercentageRepository planPercentageRepository, ISmsService smsService, IPlanPercentageRepository planPercentageRepository, ISmsService smsService,
ISmsResultRepository smsResultRepository, IFinancialTransactionRepository financialTransactionRepository, ISmsResultRepository smsResultRepository, IFinancialTransactionRepository financialTransactionRepository,
IFinancialStatmentRepository financialStatmentRepository, IHubContext<SendSmsHub> hubContext) : base(context) IFinancialStatmentRepository financialStatmentRepository, IHubContext<SendSmsHub> hubContext, ILogger<InstitutionContractRepository> logger) : base(context)
{ {
_context = context; _context = context;
_employerRepository = employerRepository; _employerRepository = employerRepository;
@@ -80,6 +82,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
_financialTransactionRepository = financialTransactionRepository; _financialTransactionRepository = financialTransactionRepository;
_financialStatmentRepository = financialStatmentRepository; _financialStatmentRepository = financialStatmentRepository;
_hubContext = hubContext; _hubContext = hubContext;
_logger = logger;
_institutionExtensionTemp = _institutionExtensionTemp =
database.GetCollection<InstitutionContractExtensionTemp>("InstitutionContractExtensionTemp"); database.GetCollection<InstitutionContractExtensionTemp>("InstitutionContractExtensionTemp");
_institutionAmendmentTemp = _institutionAmendmentTemp =
@@ -1095,26 +1098,41 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
public async Task<PagedResult<GetInstitutionContractListItemsViewModel>> GetList( public async Task<PagedResult<GetInstitutionContractListItemsViewModel>> GetList(
InstitutionContractListSearchModel searchModel) InstitutionContractListSearchModel searchModel)
{ {
var query = _context.InstitutionContractSet
.Include(x => x.WorkshopGroup)
.ThenInclude(x => x.InitialWorkshops)
.Include(x => x.WorkshopGroup)
.ThenInclude(x => x.CurrentWorkshops)
.Include(x => x.ContactInfoList).AsNoTracking();
var now = DateTime.Today; var now = DateTime.Today;
var nowFa = now.ToFarsi(); var nowFa = now.ToFarsi();
var endFa = nowFa.FindeEndOfMonth(); var endFa = nowFa.FindeEndOfMonth();
var endThisMontGr = endFa.ToGeorgianDateTime(); var endThisMontGr = endFa.ToGeorgianDateTime();
var joinedQuery = query.Join(_context.PersonalContractingParties var contractsWithExtension = await _context.InstitutionContractSet
.Where(x => x.IsActiveString == "true")
.Select(x => new { x.ContractingPartyId, x.ExtensionNo })
.ToListAsync();
// var contractsWithExtensionLookup = contractsWithExtension
// .GroupBy(x => x.ContractingPartyId)
// .ToDictionary(
// g => g.Key,
// g => g.Max(x => x.ExtensionNo)
// );
var rawQuery = _context.InstitutionContractSet
.Include(x=>x.Installments)
.AsNoTracking()
.Join(_context.PersonalContractingParties
.AsNoTracking()
.Include(x => x.Employers) .Include(x => x.Employers)
.ThenInclude(x => x.WorkshopEmployers) .ThenInclude(x => x.WorkshopEmployers)
.ThenInclude(x => x.Workshop), .ThenInclude(x => x.Workshop),
contract => contract.ContractingPartyId, contract => contract.ContractingPartyId,
contractingParty => contractingParty.id, contractingParty => contractingParty.id,
(contract, contractingParty) => new { contract, contractingParty }) (contract, contractingParty) => new { contract, contractingParty });
.Select(x => new
// var pendingForRenewalContracts = _context.InstitutionContractSet.AsNoTracking()
// .Where(c => c.IsActiveString == "true" &&
// c.ContractEndGr >= now &&
// c.ContractEndGr <= endThisMontGr);
var joinedQuery = rawQuery.Select(x => new
{ {
x.contract, x.contract,
x.contractingParty, x.contractingParty,
@@ -1135,7 +1153,8 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
: x.contract.ContractAmount == 0 : x.contract.ContractAmount == 0
? (int)InstitutionContractListStatus.Free ? (int)InstitutionContractListStatus.Free
: !x.contractingParty.Employers : !x.contractingParty.Employers
.SelectMany(e => e.WorkshopEmployers.Select(we => we.Workshop)).Any() .SelectMany(e => e.WorkshopEmployers
.Select(we => we.Workshop)).Any()
? (int)InstitutionContractListStatus.WithoutWorkshop ? (int)InstitutionContractListStatus.WithoutWorkshop
: (int)InstitutionContractListStatus.Active : (int)InstitutionContractListStatus.Active
}); });
@@ -1298,6 +1317,15 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var list = await orderedQuery.ApplyPagination(searchModel.PageIndex, searchModel.PageSize).ToListAsync(); var list = await orderedQuery.ApplyPagination(searchModel.PageIndex, searchModel.PageSize).ToListAsync();
var contractingPartyIds = list.Select(x => x.contractingParty.id).ToList(); var contractingPartyIds = list.Select(x => x.contractingParty.id).ToList();
var contractIds = list.Select(x => x.contract.id).ToList();
// بارگذاری WorkshopGroups فقط برای قراردادهای صفحه فعلی
var workshopGroups = await _context.InstitutionContractWorkshopGroups
.AsNoTracking()
.Include(x=>x.InitialWorkshops )
.Include(x => x.CurrentWorkshops)
.Where(x => contractIds.Contains(x.InstitutionContractId))
.ToDictionaryAsync(x => x.InstitutionContractId, x => x);
var financialStatements = _context.FinancialStatments.Include(x => x.FinancialTransactionList) var financialStatements = _context.FinancialStatments.Include(x => x.FinancialTransactionList)
.Where(x => contractingPartyIds.Contains(x.ContractingPartyId)).ToList(); .Where(x => contractingPartyIds.Contains(x.ContractingPartyId)).ToList();
@@ -1321,13 +1349,19 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var archiveCode = minArchiveCode == 10000000 ? 0 : minArchiveCode; var archiveCode = minArchiveCode == 10000000 ? 0 : minArchiveCode;
var status = Enum.Parse<InstitutionContractListStatus>(x.StatusPriority.ToString()); var status = Enum.Parse<InstitutionContractListStatus>(x.StatusPriority.ToString());
List<InstitutionContractWorkshopBase> currentStateWorkshops = x.contract.WorkshopGroup?.CurrentWorkshops
// دریافت WorkshopGroup از dictionary بارگذاری شده
workshopGroups.TryGetValue(x.contract.id, out var workshopGroup);
List<InstitutionContractWorkshopBase> currentStateWorkshops = workshopGroup?.CurrentWorkshops
.Cast<InstitutionContractWorkshopBase>().ToList(); .Cast<InstitutionContractWorkshopBase>().ToList();
var statement = financialStatements.FirstOrDefault(f => f.ContractingPartyId == x.contractingParty.id); var statement = financialStatements.FirstOrDefault(f => f.ContractingPartyId == x.contractingParty.id);
currentStateWorkshops?.AddRange( if (currentStateWorkshops != null && workshopGroup != null)
x.contract.WorkshopGroup?.InitialWorkshops.Where(w => !w.WorkshopCreated) ?? []); {
currentStateWorkshops.AddRange(workshopGroup.InitialWorkshops.Where(w => !w.WorkshopCreated));
}
var workshopDetails = currentStateWorkshops?.Select(w => var workshopDetails = currentStateWorkshops?.Select(w =>
{ {
@@ -1357,9 +1391,28 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var employeesCount = _context.LeftWorkList var employeesCount = _context.LeftWorkList
.Where(l => workshops.Select(w => w.id).Contains(l.WorkshopId)) .Where(l => workshops.Select(w => w.id).Contains(l.WorkshopId))
.Count(l => l.StartWorkDate <= DateTime.Now && l.LeftWorkDate >= DateTime.Now); .Count(l => l.StartWorkDate <= DateTime.Now && l.LeftWorkDate >= DateTime.Now);
var contractAmount = x.contract.SigningType is not InstitutionContractSigningType.Legacy
&& !x.contract.IsInstallment?
x.contract.TotalAmount:0;
var installmentAmount = 0d;
try
{
installmentAmount =x.contract.SigningType == InstitutionContractSigningType.Legacy
?x.contract.ContractAmount : x.contract.IsInstallment ? x.contract.Installments.First().Amount :0;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return new GetInstitutionContractListItemsViewModel() return new GetInstitutionContractListItemsViewModel()
{ {
ContractAmount = x.contract.ContractAmountWithTax, ContractAmount = contractAmount,
InstallmentAmount = installmentAmount,
Balance = statement?.FinancialTransactionList.Sum(ft => ft.Deptor - ft.Creditor) ?? 0, Balance = statement?.FinancialTransactionList.Sum(ft => ft.Deptor - ft.Creditor) ?? 0,
WorkshopsCount = workshops.Count(), WorkshopsCount = workshops.Count(),
ContractStartFa = x.contract.ContractStartGr.ToFarsi(), ContractStartFa = x.contract.ContractStartGr.ToFarsi(),
@@ -1377,7 +1430,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
IsExpired = x.contract.ContractEndGr <= endThisMontGr, IsExpired = x.contract.ContractEndGr <= endThisMontGr,
ContractingPartyId = x.contractingParty.id, ContractingPartyId = x.contractingParty.id,
Workshops = workshopDetails, Workshops = workshopDetails,
IsInPersonContract = x.contract.WorkshopGroup?.CurrentWorkshops IsInPersonContract = workshopGroup?.CurrentWorkshops
.Any(y => y.Services.ContractInPerson) ?? true, .Any(y => y.Services.ContractInPerson) ?? true,
IsOldContract = x.contract.SigningType == InstitutionContractSigningType.Legacy IsOldContract = x.contract.SigningType == InstitutionContractSigningType.Legacy
}; };
@@ -1754,6 +1807,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.ThenInclude(x => x.InitialWorkshops) .ThenInclude(x => x.InitialWorkshops)
.Include(x => x.WorkshopGroup) .Include(x => x.WorkshopGroup)
.ThenInclude(x => x.CurrentWorkshops) .ThenInclude(x => x.CurrentWorkshops)
.Include(x=>x.Installments)
.FirstOrDefaultAsync(x => x.id == institutionContractId); .FirstOrDefaultAsync(x => x.id == institutionContractId);
} }
@@ -1895,7 +1949,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.FirstOrDefaultAsync(x => x.PublicId == id); .FirstOrDefaultAsync(x => x.PublicId == id);
} }
public InstitutionContractDiscountResponse CalculateDiscount(InstitutionContractSetDiscountRequest request) public InstitutionContractDiscountResponse CalculateDiscount(InstitutionContractSetDiscountRequest request,string contractStart=null)
{ {
var baseAmount = request.TotalAmount; var baseAmount = request.TotalAmount;
var discountAmount = (baseAmount * request.DiscountPercentage) / 100; var discountAmount = (baseAmount * request.DiscountPercentage) / 100;
@@ -2154,6 +2208,10 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.Include(x => x.WorkshopGroup) .Include(x => x.WorkshopGroup)
.ThenInclude(institutionContractWorkshopGroup => institutionContractWorkshopGroup.CurrentWorkshops) .ThenInclude(institutionContractWorkshopGroup => institutionContractWorkshopGroup.CurrentWorkshops)
.FirstOrDefaultAsync(x => x.id == extenstionTemp.PreviousId); .FirstOrDefaultAsync(x => x.id == extenstionTemp.PreviousId);
var employerWorkshopIds = _context.Employers.Where(x=>x.ContractingPartyId == prevInstitutionContracts.ContractingPartyId).Include(x=>x.WorkshopEmployers)
.SelectMany(x=>x.WorkshopEmployers).Select(x=>x.WorkshopId).Distinct().ToList();
if (prevInstitutionContracts == null) if (prevInstitutionContracts == null)
{ {
throw new BadRequestException("قرارداد مالی قبلی یافت نشد"); throw new BadRequestException("قرارداد مالی قبلی یافت نشد");
@@ -2166,7 +2224,12 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
); );
var workshopIds = prevInstitutionContracts.WorkshopGroup.CurrentWorkshops.Select(x => x.WorkshopId.Value); var workshopIds = prevInstitutionContracts.WorkshopGroup.CurrentWorkshops.Select(x => x.WorkshopId.Value);
var workshops = await _context.Workshops.Where(x => workshopIds.Contains(x.id)).ToListAsync();
var workshopsNotInInstitution = employerWorkshopIds.Where(x=> !workshopIds.Contains(x)).ToList();
var workshops = await _context.Workshops.Where(x => workshopIds.Contains(x.id) || employerWorkshopIds.Contains(x.id))
.ToListAsync();
var workshopDetails = prevInstitutionContracts.WorkshopGroup.CurrentWorkshops var workshopDetails = prevInstitutionContracts.WorkshopGroup.CurrentWorkshops
.Select(x => .Select(x =>
{ {
@@ -2208,6 +2271,32 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
RollCallInPerson = service.RollCallInPerson RollCallInPerson = service.RollCallInPerson
}; };
}).ToList(); }).ToList();
var notIncludeWorskhopsLeftWork =await _context.LeftWorkList
.Where(x => workshopsNotInInstitution.Contains(x.WorkshopId) && x.StartWorkDate <= DateTime.Now &&
x.LeftWorkDate >= DateTime.Now)
.GroupBy(x => x.WorkshopId).ToListAsync();
var notIncludeWorskhopsInContract = workshopsNotInInstitution.Select(x =>
{
var workshop = workshops.FirstOrDefault(w => w.id == x);
var leftWorks = notIncludeWorskhopsLeftWork.FirstOrDefault(l=>l.Key ==x);
return new WorkshopTempViewModel()
{
WorkshopName = workshop?.WorkshopName ?? "فاقد کارگاه",
WorkshopServicesAmount = 0,
WorkshopServicesAmountStr = "0",
WorkshopId = x,
Id = 0,
ContractAndCheckout = false,
ContractAndCheckoutInPerson = false,
CustomizeCheckout = false,
CountPerson = leftWorks?.Count()??0,
Insurance = false,
InsuranceInPerson = false,
RollCall = false,
RollCallInPerson = false,
};
}).ToList();
workshopDetails = workshopDetails.Concat(notIncludeWorskhopsInContract).ToList();
var res = new InstitutionContractExtensionWorkshopsResponse() var res = new InstitutionContractExtensionWorkshopsResponse()
{ {
TotalAmount = workshopDetails.Sum(x => x.WorkshopServicesAmount).ToMoney(), TotalAmount = workshopDetails.Sum(x => x.WorkshopServicesAmount).ToMoney(),
@@ -2322,6 +2411,10 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
{ {
if (request.DiscountPercentage <= 0) if (request.DiscountPercentage <= 0)
throw new BadRequestException("مقدار تخفیف نمی‌تواند برابر یا کمتر از صفر باشد"); throw new BadRequestException("مقدار تخفیف نمی‌تواند برابر یا کمتر از صفر باشد");
if (request.DiscountPercentage>=100)
{
throw new BadRequestException("مقدار تخفیف نمی‌تواند برابر یا بیشتر از صد باشد");
}
var institutionTemp = await _institutionExtensionTemp.Find(x => x.Id == request.TempId) var institutionTemp = await _institutionExtensionTemp.Find(x => x.Id == request.TempId)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
if (institutionTemp == null) if (institutionTemp == null)
@@ -2339,7 +2432,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (institutionTemp.OneTimePayment.DiscountPercetage > 0) if (institutionTemp.OneTimePayment.DiscountPercetage > 0)
throw new BadRequestException("تخفیف قبلا برای این قرارداد اعمال شده است"); throw new BadRequestException("تخفیف قبلا برای این قرارداد اعمال شده است");
} }
var selectedPlan = institutionTemp.Duration switch var selectedPlan = institutionTemp.Duration switch
{ {
InstitutionContractDuration.OneMonth => institutionTemp.OneMonth, InstitutionContractDuration.OneMonth => institutionTemp.OneMonth,
@@ -2356,12 +2449,18 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
IsInstallment = request.IsInstallment, IsInstallment = request.IsInstallment,
OneMonthAmount = selectedPlan.OneMonthPaymentDiscounted.MoneyToDouble() OneMonthAmount = selectedPlan.OneMonthPaymentDiscounted.MoneyToDouble()
}; };
var res = CalculateDiscount(calculateRequest); var res = CalculateDiscount(calculateRequest,selectedPlan.ContractStart);
//این به این دلیل هست که متد caclulate discount یکی از مقادیر رو پر میکنه و ما نیاز داریم هر دو مقدار رو داشته باشیم //این به این دلیل هست که متد caclulate discount یکی از مقادیر رو پر میکنه و ما نیاز داریم هر دو مقدار رو داشته باشیم
if (request.IsInstallment) if (request.IsInstallment)
{ {
var onetime = institutionTemp.OneTimePayment; var onetime = institutionTemp.OneTimePayment;
onetime.TotalAmountWithoutDiscount = onetime.TotalAmount;
onetime.OneMonthPaymentWithoutDiscount = selectedPlan.OneMonthPaymentDiscounted;
institutionTemp.OneTimePayment.TotalAmountWithoutDiscount = onetime.TotalAmount;
institutionTemp.OneTimePayment.OneMonthPaymentWithoutDiscount = selectedPlan.OneMonthPaymentDiscounted;
res.OneTime = new() res.OneTime = new()
{ {
PaymentAmount = onetime.PaymentAmount, PaymentAmount = onetime.PaymentAmount,
@@ -2370,6 +2469,9 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
DiscountedAmount = onetime.DiscountedAmount, DiscountedAmount = onetime.DiscountedAmount,
DiscountPercetage = onetime.DiscountPercetage, DiscountPercetage = onetime.DiscountPercetage,
}; };
institutionTemp.MonthlyPayment = new() institutionTemp.MonthlyPayment = new()
{ {
Installments = res.Monthly.Installments, Installments = res.Monthly.Installments,
@@ -2378,8 +2480,10 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
TotalAmount = res.Monthly.TotalAmount, TotalAmount = res.Monthly.TotalAmount,
DiscountedAmount = res.Monthly.DiscountedAmount, DiscountedAmount = res.Monthly.DiscountedAmount,
DiscountPercetage = res.Monthly.DiscountPercetage, DiscountPercetage = res.Monthly.DiscountPercetage,
TotalAmountWithoutDiscount = institutionTemp.MonthlyPayment.TotalAmount,
OneMonthPaymentWithoutDiscount = selectedPlan.OneMonthPaymentDiscounted,
}; };
selectedPlan.TotalPayment = res.Monthly.TotalAmount; selectedPlan.TotalPayment = res.Monthly.TotalAmount;
selectedPlan.Obligation = res.Monthly.Obligation; selectedPlan.Obligation = res.Monthly.Obligation;
selectedPlan.OneMonthPaymentDiscounted = res.Monthly.OneMonthAmount; selectedPlan.OneMonthPaymentDiscounted = res.Monthly.OneMonthAmount;
@@ -2388,6 +2492,9 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
else else
{ {
var monthly = institutionTemp.MonthlyPayment; var monthly = institutionTemp.MonthlyPayment;
institutionTemp.MonthlyPayment.TotalAmountWithoutDiscount = monthly.TotalAmount;
res.Monthly = new() res.Monthly = new()
{ {
PaymentAmount = monthly.PaymentAmount, PaymentAmount = monthly.PaymentAmount,
@@ -2397,6 +2504,8 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
DiscountPercetage = monthly.DiscountPercetage, DiscountPercetage = monthly.DiscountPercetage,
Installments = monthly.Installments, Installments = monthly.Installments,
}; };
institutionTemp.OneTimePayment = new() institutionTemp.OneTimePayment = new()
{ {
PaymentAmount = res.OneTime.PaymentAmount, PaymentAmount = res.OneTime.PaymentAmount,
@@ -2404,6 +2513,8 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
TotalAmount = res.OneTime.TotalAmount, TotalAmount = res.OneTime.TotalAmount,
DiscountedAmount = res.OneTime.DiscountedAmount, DiscountedAmount = res.OneTime.DiscountedAmount,
DiscountPercetage = res.OneTime.DiscountPercetage, DiscountPercetage = res.OneTime.DiscountPercetage,
TotalAmountWithoutDiscount = institutionTemp.OneTimePayment.TotalAmount,
OneMonthPaymentWithoutDiscount = selectedPlan.OneMonthPaymentDiscounted,
}; };
selectedPlan.TotalPayment = res.OneTime.TotalAmount; selectedPlan.TotalPayment = res.OneTime.TotalAmount;
selectedPlan.Obligation = res.OneTime.Obligation; selectedPlan.Obligation = res.OneTime.Obligation;
@@ -2462,12 +2573,10 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (request.IsInstallment) if (request.IsInstallment)
{ {
var prevMonthlyPayment = institutionTemp.MonthlyPayment; var prevMonthlyPayment = institutionTemp.MonthlyPayment;
var resetTotalAmount = prevMonthlyPayment.TotalAmount.MoneyToDouble() / var resetTotalAmount = prevMonthlyPayment.TotalAmountWithoutDiscount.MoneyToDouble();
(1 - (prevMonthlyPayment.DiscountPercetage / 100.0));
var resetTax = (resetTotalAmount * 0.10); var resetTax = (resetTotalAmount * 0.10);
var paymentAmount = (resetTotalAmount + resetTax); var paymentAmount = (resetTotalAmount + resetTax);
var newOneMonthAmount = selectedPlan.OneMonthPaymentDiscounted.MoneyToDouble() / var newOneMonthAmount = prevMonthlyPayment.OneMonthPaymentWithoutDiscount.MoneyToDouble();
(1 - (prevMonthlyPayment.DiscountPercetage / 100));
monthlyPayment = new InstitutionContractDiscountMonthlyViewModel() monthlyPayment = new InstitutionContractDiscountMonthlyViewModel()
{ {
DiscountPercetage = 0, DiscountPercetage = 0,
@@ -2476,7 +2585,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
Tax = resetTax.ToMoney(), Tax = resetTax.ToMoney(),
TotalAmount = resetTotalAmount.ToMoney(), TotalAmount = resetTotalAmount.ToMoney(),
Installments = InstitutionMonthlyInstallmentCaculation((int)institutionTemp.Duration.Value, Installments = InstitutionMonthlyInstallmentCaculation((int)institutionTemp.Duration.Value,
paymentAmount, DateTime.Now.ToFarsi()), paymentAmount,selectedPlan.ContractStart),
OneMonthAmount = newOneMonthAmount.ToMoney(), OneMonthAmount = newOneMonthAmount.ToMoney(),
Obligation = resetTotalAmount.ToMoney() Obligation = resetTotalAmount.ToMoney()
}; };
@@ -2518,11 +2627,9 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
else else
{ {
var prevOneTimePayment = institutionTemp.OneTimePayment; var prevOneTimePayment = institutionTemp.OneTimePayment;
var resetTotalAmount = prevOneTimePayment.TotalAmount.MoneyToDouble() / var resetTotalAmount = prevOneTimePayment.TotalAmountWithoutDiscount.MoneyToDouble();
(1 - (prevOneTimePayment.DiscountPercetage / 100.0));
var resetTax = (resetTotalAmount * 0.10); var resetTax = (resetTotalAmount * 0.10);
var newOneMonthAmount = selectedPlan.OneMonthPaymentDiscounted.MoneyToDouble() / var newOneMonthAmount = prevOneTimePayment.OneMonthPaymentWithoutDiscount.MoneyToDouble();
(1 - (prevOneTimePayment.DiscountPercetage / 100));
oneTimePayment = new InstitutionContractDiscountOneTimeViewModel() oneTimePayment = new InstitutionContractDiscountOneTimeViewModel()
{ {
@@ -2541,8 +2648,12 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
TotalAmount = oneTimePayment.TotalAmount, TotalAmount = oneTimePayment.TotalAmount,
DiscountedAmount = oneTimePayment.DiscountedAmount, DiscountedAmount = oneTimePayment.DiscountedAmount,
DiscountPercetage = oneTimePayment.DiscountPercetage, DiscountPercetage = oneTimePayment.DiscountPercetage,
TotalAmountWithoutDiscount = institutionTemp.OneTimePayment.TotalAmount,
OneMonthPaymentWithoutDiscount = institutionTemp.OneTimePayment.OneMonthPaymentWithoutDiscount
}; };
selectedPlan.TotalPayment = oneTimePayment.TotalAmount; selectedPlan.TotalPayment = institutionTemp.HasContractInPerson?
(oneTimePayment.TotalAmount.MoneyToDouble()/(0.9)).ToMoney()
:oneTimePayment.TotalAmount;
selectedPlan.Obligation = oneTimePayment.Obligation; selectedPlan.Obligation = oneTimePayment.Obligation;
selectedPlan.OneMonthPaymentDiscounted = oneTimePayment.OneMonthAmount; selectedPlan.OneMonthPaymentDiscounted = oneTimePayment.OneMonthAmount;
selectedPlan.DailyCompenseation = (oneTimePayment.OneMonthAmount.MoneyToDouble() * 0.10).ToMoney(); selectedPlan.DailyCompenseation = (oneTimePayment.OneMonthAmount.MoneyToDouble() * 0.10).ToMoney();
@@ -2798,7 +2909,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
_context.InstitutionContractContactInfos.Add(contactinfo); _context.InstitutionContractContactInfos.Add(contactinfo);
} }
} }
await SaveChangesAsync(); await SaveChangesAsync();
await _smsService.SendInstitutionCreationVerificationLink(contractingParty.Phone, contractingPartyFullName, await _smsService.SendInstitutionCreationVerificationLink(contractingParty.Phone, contractingPartyFullName,
@@ -2809,6 +2919,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
await transaction.CommitAsync(); await transaction.CommitAsync();
return opration.Succcedded(); return opration.Succcedded();
} }
#endregion #endregion
@@ -3415,7 +3526,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
public async Task<bool> SendReminderSmsForBackgroundTask() public async Task<bool> SendReminderSmsForBackgroundTask()
{ {
var now = DateTime.Now; var now = DateTime.Now;
_logger.LogInformation("================>> SendReminderSmsForBackgroundTask job run");
// تبدیل تاریخ میلادی به شمسی // تبدیل تاریخ میلادی به شمسی
var persianNow = now.ToFarsi(); var persianNow = now.ToFarsi();
@@ -3454,7 +3565,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (checkAnyToExecute) if (checkAnyToExecute)
{ {
//اجرای تسک //اجرای تسک
_logger.LogInformation("اجرای تسک پیامک های یاد آور SendReminderSmsForBackgroundTask" + persianNow + " - " + hour + ":" + minute);
//دریافت لیست بدهکاران //دریافت لیست بدهکاران
var smsListData = await GetSmsListData(now, TypeOfSmsSetting.InstitutionContractDebtReminder); var smsListData = await GetSmsListData(now, TypeOfSmsSetting.InstitutionContractDebtReminder);
string typeOfSms = "یادآور بدهی ماهانه"; string typeOfSms = "یادآور بدهی ماهانه";
@@ -4229,6 +4340,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
{ {
string name = item.PartyName.Length > 18 ? item.PartyName.Substring(0, 18) : item.PartyName; string name = item.PartyName.Length > 18 ? item.PartyName.Substring(0, 18) : item.PartyName;
string errMess = $"{name}-خطا"; string errMess = $"{name}-خطا";
_logger.LogError(errMess);
await _smsService.Alarm("09114221321", errMess); await _smsService.Alarm("09114221321", errMess);
} }
@@ -4342,7 +4454,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (checkAnyToExecute) if (checkAnyToExecute)
{ {
//اجرای تسک //اجرای تسک
_logger.LogInformation("اجرای تسک ارسال یاد آور تایید قراداد مالی SendInstitutionContractConfirmSms" + persianNow + " - " + hour + ":" + minute);
//دریافت لیست قراداد های تایید نشده //دریافت لیست قراداد های تایید نشده
var fromAmonthAgo = now.AddDays(-30); var fromAmonthAgo = now.AddDays(-30);
var pendingContracts = await _context.InstitutionContractSet var pendingContracts = await _context.InstitutionContractSet
@@ -4362,6 +4474,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
string typeOfSms = "یادآور تایید قرارداد مالی"; string typeOfSms = "یادآور تایید قرارداد مالی";
foreach (var item in pendingContracts) foreach (var item in pendingContracts)
{ {
var sendResult = await _smsService.SendInstitutionCreationVerificationLink(item.Number, item.FullName, var sendResult = await _smsService.SendInstitutionCreationVerificationLink(item.Number, item.FullName,
item.InstitutionId, item.ContractingPartyId, item.InstitutionContractId, typeOfSms); item.InstitutionId, item.ContractingPartyId, item.InstitutionContractId, typeOfSms);
Thread.Sleep(1000); Thread.Sleep(1000);
@@ -4770,7 +4883,20 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.Where(x => x.Installments.Any(i => i.Id == installmentId)) .Where(x => x.Installments.Any(i => i.Id == installmentId))
.Select(x => x.id).FirstOrDefaultAsync(); .Select(x => x.id).FirstOrDefaultAsync();
} }
public async Task<InstitutionContract> GetPreviousContract(long currentInstitutionContractId)
{
var institutionContract =await _context.InstitutionContractSet
.FirstOrDefaultAsync(x=>x.id ==currentInstitutionContractId);
if (institutionContract == null)
return null;
var previousContract = await _context.InstitutionContractSet
.Where(x => x.ContractingPartyId == institutionContract.ContractingPartyId)
.Where(x => x.ContractStartGr < institutionContract.ContractStartGr)
.OrderByDescending(x => x.ContractEndGr)
.FirstOrDefaultAsync();
return previousContract;
}
#endregion #endregion

View File

@@ -755,7 +755,7 @@ public class InsuranceListRepository : RepositoryBase<long, InsuranceList>, IIns
if (item.InsuranceShare.ToMoney() != checkout.InsuranceDeduction.ToMoney()) if (item.InsuranceShare.ToMoney() != checkout.InsuranceDeduction.ToMoney())
{ {
checkout.SetUpdateNeeded(); checkout.SetUpdateNeeded();
if (!_context.CheckoutWarningMessages.Any(x => x.CheckoutId == checkout.id && x.TypeOfCheckoutWarning != TypeOfCheckoutWarning.InsuranceEmployeeShare)) if (!_context.CheckoutWarningMessages.Any(x => x.CheckoutId == checkout.id && x.TypeOfCheckoutWarning == TypeOfCheckoutWarning.InsuranceEmployeeShare))
{ {
var createWarrning = var createWarrning =
new CheckoutWarningMessage( new CheckoutWarningMessage(
@@ -1820,19 +1820,24 @@ public class InsuranceListRepository : RepositoryBase<long, InsuranceList>, IIns
return res; return res;
} }
public async Task<List<InsuranceListViewModel>> GetNotCreatedWorkshop(InsuranceListSearchModel searchModel) public async Task<List<InsuranceListViewModel>> GetNotCreatedWorkshop(InsuranceListSearchModel searchModel)
{ {
if (string.IsNullOrEmpty(searchModel.Month) || string.IsNullOrEmpty(searchModel.Year)) if (string.IsNullOrEmpty(searchModel.Month) || string.IsNullOrEmpty(searchModel.Year))
{ {
return []; 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 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); .Select(x => x.WorkshopId);
var firstDayOfMonth = $"{searchModel.Year}/{searchModel.Month}/01".ToGeorgianDateTime(); var firstDayOfMonth = $"{searchModel.Year}/{searchModel.Month}/01".ToGeorgianDateTime();
var insuranceWorkshops = _context.Workshops 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"); x.IsActiveString == "true");
@@ -1855,7 +1860,7 @@ public class InsuranceListRepository : RepositoryBase<long, InsuranceList>, IIns
WorkShopId = result.id, WorkShopId = result.id,
WorkShopCode = result.InsuranceWorkshopInfo != null WorkShopCode = result.InsuranceWorkshopInfo != null
? result.InsuranceWorkshopInfo.InsuranceCode ? result.InsuranceWorkshopInfo.InsuranceCode
: result.InsuranceCode, : string.IsNullOrWhiteSpace(result.InsuranceCode) ? "کد کارگاهی ندارد" : result.InsuranceCode,
WorkShopName = result.InsuranceWorkshopInfo != null WorkShopName = result.InsuranceWorkshopInfo != null
? result.InsuranceWorkshopInfo.WorkshopName ? result.InsuranceWorkshopInfo.WorkshopName
: result.WorkshopFullName, : result.WorkshopFullName,

View File

@@ -340,8 +340,10 @@ public class PlanPercentageRepository : RepositoryBase<long, PlanPercentage>, IP
.Select(x => x.ItemValue).FirstOrDefault(); .Select(x => x.ItemValue).FirstOrDefault();
var plans = _context.InstitutionPlans.AsQueryable(); var plans = _context.InstitutionPlans.AsQueryable();
if (searchModel.CountPeron > 0) if (searchModel.CountPerson > 0)
plans = plans.Where(x => x.CountPerson == searchModel.CountPeron); plans = plans.Where(x => x.CountPerson == searchModel.CountPerson);
var count = await plans.CountAsync();
var planQueryFilter =await plans.ApplyPagination(searchModel.PageIndex, searchModel.PageSize).ToListAsync(); var planQueryFilter =await plans.ApplyPagination(searchModel.PageIndex, searchModel.PageSize).ToListAsync();
var planResult = planQueryFilter.Select(plan => var planResult = planQueryFilter.Select(plan =>
@@ -403,7 +405,7 @@ public class PlanPercentageRepository : RepositoryBase<long, PlanPercentage>, IP
return new PagedResult<InstitutionPlanListDto>() return new PagedResult<InstitutionPlanListDto>()
{ {
TotalCount = finalResult.Count, TotalCount = count,
List = finalResult List = finalResult
}; };

View File

@@ -1,8 +1,4 @@
using System; using _0_Framework.Application;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using _0_Framework.Application;
using _0_Framework.Application.Sms; using _0_Framework.Application.Sms;
using Company.Domain.SmsResultAgg; using Company.Domain.SmsResultAgg;
using CompanyManagment.App.Contracts.SmsResult; using CompanyManagment.App.Contracts.SmsResult;
@@ -10,6 +6,11 @@ using IPE.SmsIrClient;
using IPE.SmsIrClient.Models.Requests; using IPE.SmsIrClient.Models.Requests;
using IPE.SmsIrClient.Models.Results; using IPE.SmsIrClient.Models.Results;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SmsResult = Company.Domain.SmsResultAgg.SmsResult; using SmsResult = Company.Domain.SmsResultAgg.SmsResult;
@@ -17,521 +18,531 @@ namespace CompanyManagment.EFCore.Services;
public class SmsService : ISmsService public class SmsService : ISmsService
{ {
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private readonly ISmsResultRepository _smsResultRepository; private readonly ISmsResultRepository _smsResultRepository;
private readonly bool _isDevEnvironment; private readonly bool _isDevEnvironment;
private readonly List<string> _testNumbers; private readonly List<string> _testNumbers;
public SmsIr SmsIr { get; set; } private readonly ILogger<SmsService> _logger;
public SmsIr SmsIr { get; set; }
public SmsService(IConfiguration configuration, ISmsResultRepository smsResultRepository) public SmsService(IConfiguration configuration, ISmsResultRepository smsResultRepository, ILogger<SmsService> logger)
{ {
_configuration = configuration; _configuration = configuration;
_smsResultRepository = smsResultRepository; _smsResultRepository = smsResultRepository;
SmsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa"); _logger = logger;
SmsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
// خواندن تنظیمات SMS از appsettings // خواندن تنظیمات SMS از appsettings
var smsSettings = _configuration.GetSection("SmsSettings"); var smsSettings = _configuration.GetSection("SmsSettings");
_isDevEnvironment = smsSettings.GetValue<bool>("IsTestMode"); _isDevEnvironment = smsSettings.GetValue<bool>("IsTestMode");
_testNumbers = smsSettings.GetSection("TestNumbers").Get<List<string>>() ?? new List<string>(); _testNumbers = smsSettings.GetSection("TestNumbers").Get<List<string>>() ?? new List<string>();
} }
/// <summary> /// <summary>
/// متد مرکزی برای ارسال پیامک که محیط dev را چک می‌کند /// متد مرکزی برای ارسال پیامک که محیط dev را چک می‌کند
/// </summary> /// </summary>
private async Task<SmsIrResult<VerifySendResult>> VerifySendSmsAsync(string number, int templateId, VerifySendParameter[] parameters) private async Task<SmsIrResult<VerifySendResult>> VerifySendSmsAsync(string number, int templateId, VerifySendParameter[] parameters)
{ {
// اگر محیط dev است و شماره‌های تست وجود دارد، به شماره‌های تست ارسال می‌شود // اگر محیط dev است و شماره‌های تست وجود دارد، به شماره‌های تست ارسال می‌شود
if (_isDevEnvironment && _testNumbers is { Count: > 0 }) if (_isDevEnvironment && _testNumbers is { Count: > 0 })
{ {
// ارسال به همه شماره‌های تست // ارسال به همه شماره‌های تست
SmsIrResult<VerifySendResult> lastResult = null; SmsIrResult<VerifySendResult> lastResult = null;
foreach (var testNumber in _testNumbers) foreach (var testNumber in _testNumbers)
{ {
lastResult = await SmsIr.VerifySendAsync(testNumber, templateId, parameters); lastResult = await SmsIr.VerifySendAsync(testNumber, templateId, parameters);
} }
return lastResult; // برگرداندن نتیجه آخرین ارسال return lastResult; // برگرداندن نتیجه آخرین ارسال
} }
else else
{ {
// ارسال به شماره واقعی // ارسال به شماره واقعی
return await SmsIr.VerifySendAsync(number, templateId, parameters); return await SmsIr.VerifySendAsync(number, templateId, parameters);
} }
} }
public void Send(string number, string message) public void Send(string number, string message)
{ {
//var token = GetToken(); //var token = GetToken();
//var lines = new SmsLine().GetSmsLines(token); //var lines = new SmsLine().GetSmsLines(token);
//if (lines == null) return; //if (lines == null) return;
//var line = lines.SMSLines.Last().LineNumber.ToString(); //var line = lines.SMSLines.Last().LineNumber.ToString();
//var data = new MessageSendObject //var data = new MessageSendObject
//{ //{
// Messages = new List<string> // Messages = new List<string>
// {message}.ToArray(), // {message}.ToArray(),
// MobileNumbers = new List<string> {number}.ToArray(), // MobileNumbers = new List<string> {number}.ToArray(),
// LineNumber = line, // LineNumber = line,
// SendDateTime = DateTime.Now, // SendDateTime = DateTime.Now,
// CanContinueInCaseOfError = true // CanContinueInCaseOfError = true
//}; //};
//var messageSendResponseObject = //var messageSendResponseObject =
// new MessageSend().Send(token, data); // new MessageSend().Send(token, data);
//if (messageSendResponseObject.IsSuccessful) return; //if (messageSendResponseObject.IsSuccessful) return;
//line = lines.SMSLines.First().LineNumber.ToString(); //line = lines.SMSLines.First().LineNumber.ToString();
//data.LineNumber = line; //data.LineNumber = line;
//new MessageSend().Send(token, data); //new MessageSend().Send(token, data);
} }
public bool VerifySend(string number, string message) public bool VerifySend(string number, string message)
{ {
var verificationSendResult = VerifySendSmsAsync(number, 768382, new VerifySendParameter[] { new VerifySendParameter("VerificationCode", message) }); var verificationSendResult = VerifySendSmsAsync(number, 768382, new VerifySendParameter[] { new VerifySendParameter("VerificationCode", message) });
Thread.Sleep(2000); Thread.Sleep(2000);
if (verificationSendResult.IsCompletedSuccessfully) if (verificationSendResult.IsCompletedSuccessfully)
{ {
var resStartStatus = verificationSendResult.Result; var resStartStatus = verificationSendResult.Result;
var b = resStartStatus.Status; var b = resStartStatus.Status;
var resResult = verificationSendResult.Status; var resResult = verificationSendResult.Status;
var a = verificationSendResult.IsCompleted; var a = verificationSendResult.IsCompleted;
var reseExceptiont = verificationSendResult.Exception; var reseExceptiont = verificationSendResult.Exception;
return true; return true;
} }
else else
{ {
var resStartStatus = verificationSendResult.Status; var resStartStatus = verificationSendResult.Status;
var resResult = verificationSendResult.Status; var resResult = verificationSendResult.Status;
var reseExceptiont = verificationSendResult.Exception; var reseExceptiont = verificationSendResult.Exception;
return false; return false;
} }
} }
public bool LoginSend(string number, string message) public bool LoginSend(string number, string message)
{ {
var verificationSendResult = VerifySendSmsAsync(number, 635330, new VerifySendParameter[] { new VerifySendParameter("LOGINCODE", message) }); var verificationSendResult = VerifySendSmsAsync(number, 635330, new VerifySendParameter[] { new VerifySendParameter("LOGINCODE", message) });
Thread.Sleep(2000); Thread.Sleep(2000);
if (verificationSendResult.IsCompletedSuccessfully) if (verificationSendResult.IsCompletedSuccessfully)
{ {
var resStartStatus = verificationSendResult.Result; var resStartStatus = verificationSendResult.Result;
var b = resStartStatus.Status; var b = resStartStatus.Status;
var resResult = verificationSendResult.Status; var resResult = verificationSendResult.Status;
var a = verificationSendResult.IsCompleted; var a = verificationSendResult.IsCompleted;
var reseExceptiont = verificationSendResult.Exception; var reseExceptiont = verificationSendResult.Exception;
return true; return true;
} }
else else
{ {
var resStartStatus = verificationSendResult.Status; var resStartStatus = verificationSendResult.Status;
var resResult = verificationSendResult.Status; var resResult = verificationSendResult.Status;
var reseExceptiont = verificationSendResult.Exception; var reseExceptiont = verificationSendResult.Exception;
return false; return false;
} }
} }
public async Task<SentSmsViewModel> SendVerifyCodeToClient(string number, string code) public async Task<SentSmsViewModel> SendVerifyCodeToClient(string number, string code)
{ {
var result = new SentSmsViewModel(); var result = new SentSmsViewModel();
var sendResult = await VerifySendSmsAsync(number, 768382, new VerifySendParameter[] { new VerifySendParameter("VerificationCode", code) }); var sendResult = await VerifySendSmsAsync(number, 768382, new VerifySendParameter[] { new VerifySendParameter("VerificationCode", code) });
Thread.Sleep(2000); Thread.Sleep(2000);
if (sendResult.Message == "موفق") if (sendResult.Message == "موفق")
{ {
var status = sendResult.Status; var status = sendResult.Status;
var message = sendResult.Message; var message = sendResult.Message;
var messaeId = sendResult.Data.MessageId; var messaeId = sendResult.Data.MessageId;
return result.Succedded(status, message, messaeId); return result.Succedded(status, message, messaeId);
} }
else else
{ {
var status = sendResult.Status; var status = sendResult.Status;
var message = sendResult.Message; var message = sendResult.Message;
var messaeId = sendResult.Data.MessageId; var messaeId = sendResult.Data.MessageId;
return result.Failed(status, message, messaeId); return result.Failed(status, message, messaeId);
} }
} }
public bool SendAccountsInfo(string number, string fullName, string userName) public bool SendAccountsInfo(string number, string fullName, string userName)
{ {
var checkLength = fullName.Length; var checkLength = fullName.Length;
if (checkLength > 25) if (checkLength > 25)
fullName = fullName.Substring(0, 24); fullName = fullName.Substring(0, 24);
var sendResult = VerifySendSmsAsync(number, 725814, new VerifySendParameter[] { new VerifySendParameter("FULLNAME", fullName), new VerifySendParameter("USERNAME", userName), new VerifySendParameter("PASSWORD", userName) }); var sendResult = VerifySendSmsAsync(number, 725814, new VerifySendParameter[] { new VerifySendParameter("FULLNAME", fullName), new VerifySendParameter("USERNAME", userName), new VerifySendParameter("PASSWORD", userName) });
Console.WriteLine(userName + " - " + sendResult.Result.Status); Console.WriteLine(userName + " - " + sendResult.Result.Status);
if (sendResult.IsCompletedSuccessfully) if (sendResult.IsCompletedSuccessfully)
{ {
return true; return true;
} }
else else
{ {
return false; return false;
} }
} }
public async Task<ApiResultViewModel> GetByMessageId(int messId) public async Task<ApiResultViewModel> GetByMessageId(int messId)
{ {
SmsIr smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa"); SmsIr smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
var response = await smsIr.GetReportAsync(messId); var response = await smsIr.GetReportAsync(messId);
MessageReportResult messages = response.Data; MessageReportResult messages = response.Data;
var appendData = new ApiResultViewModel() var appendData = new ApiResultViewModel()
{ {
MessageId = messages.MessageId, MessageId = messages.MessageId,
LineNumber = messages.LineNumber, LineNumber = messages.LineNumber,
Mobile = messages.Mobile, Mobile = messages.Mobile,
MessageText = messages.MessageText, MessageText = messages.MessageText,
SendUnixTime = UnixTimeStampToDateTime(messages.SendDateTime), SendUnixTime = UnixTimeStampToDateTime(messages.SendDateTime),
DeliveryState = DeliveryStatus(messages.DeliveryState), DeliveryState = DeliveryStatus(messages.DeliveryState),
DeliveryUnixTime = UnixTimeStampToDateTime(messages.DeliveryDateTime), DeliveryUnixTime = UnixTimeStampToDateTime(messages.DeliveryDateTime),
DeliveryColor = DeliveryColorStatus(messages.DeliveryState), DeliveryColor = DeliveryColorStatus(messages.DeliveryState),
}; };
return appendData; return appendData;
} }
public async Task<List<ApiResultViewModel>> GetApiResult(string startDate, string endDate) public async Task<List<ApiResultViewModel>> GetApiResult(string startDate, string endDate)
{ {
var st = new DateTime(2024, 6, 2); var st = new DateTime(2024, 6, 2);
var ed = new DateTime(2024, 7, 1); var ed = new DateTime(2024, 7, 1);
if (!string.IsNullOrWhiteSpace(startDate) && startDate.Length == 10) if (!string.IsNullOrWhiteSpace(startDate) && startDate.Length == 10)
{ {
st = startDate.ToGeorgianDateTime(); st = startDate.ToGeorgianDateTime();
} }
if (!string.IsNullOrWhiteSpace(endDate) && endDate.Length == 10) if (!string.IsNullOrWhiteSpace(endDate) && endDate.Length == 10)
{ {
ed = endDate.ToGeorgianDateTime(); ed = endDate.ToGeorgianDateTime();
} }
var res = new List<ApiResultViewModel>(); var res = new List<ApiResultViewModel>();
Int32 unixTimestamp = (int)st.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; Int32 unixTimestamp = (int)st.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Int32 unixTimestamp2 = (int)ed.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; Int32 unixTimestamp2 = (int)ed.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
// int? fromDateUnixTime = null; // unix time - for instance: 1700598600 // int? fromDateUnixTime = null; // unix time - for instance: 1700598600
//int? toDateUnixTime = null; // unix time - for instance: 1703190600 //int? toDateUnixTime = null; // unix time - for instance: 1703190600
int pageNumber = 2; int pageNumber = 2;
int pageSize = 100; // max: 100 int pageSize = 100; // max: 100
SmsIr smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa"); SmsIr smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
var response = await smsIr.GetArchivedReportAsync(pageNumber, pageSize, unixTimestamp, unixTimestamp2); var response = await smsIr.GetArchivedReportAsync(pageNumber, pageSize, unixTimestamp, unixTimestamp2);
MessageReportResult[] messages = response.Data; MessageReportResult[] messages = response.Data;
foreach (var message in messages) foreach (var message in messages)
{ {
var appendData = new ApiResultViewModel() var appendData = new ApiResultViewModel()
{ {
MessageId = message.MessageId, MessageId = message.MessageId,
LineNumber = message.LineNumber, LineNumber = message.LineNumber,
Mobile = message.Mobile, Mobile = message.Mobile,
MessageText = message.MessageText, MessageText = message.MessageText,
SendUnixTime = UnixTimeStampToDateTime(message.SendDateTime), SendUnixTime = UnixTimeStampToDateTime(message.SendDateTime),
DeliveryState = DeliveryStatus(message.DeliveryState), DeliveryState = DeliveryStatus(message.DeliveryState),
DeliveryUnixTime = UnixTimeStampToDateTime(message.DeliveryDateTime), DeliveryUnixTime = UnixTimeStampToDateTime(message.DeliveryDateTime),
DeliveryColor = DeliveryColorStatus(message.DeliveryState), DeliveryColor = DeliveryColorStatus(message.DeliveryState),
}; };
res.Add(appendData); res.Add(appendData);
} }
return res; return res;
} }
public string DeliveryStatus(byte? dv) public string DeliveryStatus(byte? dv)
{ {
string mess = ""; string mess = "";
switch (dv) switch (dv)
{ {
case 1: case 1:
mess = "رسیده به گوشی"; mess = "رسیده به گوشی";
break; break;
case 2: case 2:
mess = "نرسیده به گوشی"; mess = "نرسیده به گوشی";
break; break;
case 3: case 3:
mess = "پردازش در مخابرات"; mess = "پردازش در مخابرات";
break; break;
case 4: case 4:
mess = "نرسیده به مخابرات"; mess = "نرسیده به مخابرات";
break; break;
case 5: case 5:
mess = "سیده به مخابرات"; mess = "سیده به مخابرات";
break; break;
case 6: case 6:
mess = "خطا"; mess = "خطا";
break; break;
case 7: case 7:
mess = "لیست سیاه"; mess = "لیست سیاه";
break; break;
default: default:
mess = ""; mess = "";
break; break;
} }
return mess; return mess;
} }
public string DeliveryColorStatus(byte? dv) public string DeliveryColorStatus(byte? dv)
{ {
string mess = ""; string mess = "";
switch (dv) switch (dv)
{ {
case 1: case 1:
mess = "successSend"; mess = "successSend";
break; break;
case 2: case 2:
mess = "errSend"; mess = "errSend";
break; break;
case 3: case 3:
mess = "pSend"; mess = "pSend";
break; break;
case 4: case 4:
mess = "noSend"; mess = "noSend";
break; break;
case 5: case 5:
mess = "itcSend"; mess = "itcSend";
break; break;
case 6: case 6:
mess = "redSend"; mess = "redSend";
break; break;
case 7: case 7:
mess = "blockSend"; mess = "blockSend";
break; break;
default: default:
mess = ""; mess = "";
break; break;
} }
return mess; return mess;
} }
public string UnixTimeStampToDateTime(int? unixTimeStamp) public string UnixTimeStampToDateTime(int? unixTimeStamp)
{ {
if (unixTimeStamp != null) if (unixTimeStamp != null)
{ {
// Unix timestamp is seconds past epoch // Unix timestamp is seconds past epoch
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(Convert.ToDouble(unixTimeStamp)).ToLocalTime(); dateTime = dateTime.AddSeconds(Convert.ToDouble(unixTimeStamp)).ToLocalTime();
var time = dateTime.ToFarsiFull(); var time = dateTime.ToFarsiFull();
return time; return time;
} }
return ""; return "";
} }
private string GetToken() private string GetToken()
{ {
return ""; return "";
//var smsSecrets = _configuration.GetSection("SmsSecrets"); //var smsSecrets = _configuration.GetSection("SmsSecrets");
//var tokenService = new Token(); //var tokenService = new Token();
//return tokenService.GetToken("x-api-key", "Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa"); //return tokenService.GetToken("x-api-key", "Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
} }
#region Mahan #region Mahan
public async Task<double> GetCreditAmount() public async Task<double> GetCreditAmount()
{ {
try try
{ {
var credit = await SmsIr.GetCreditAsync(); var credit = await SmsIr.GetCreditAsync();
return (double)credit.Data; return (double)credit.Data;
} }
catch catch
{ {
return -1; return -1;
} }
} }
public async Task<bool> SendInstitutionCreationVerificationLink(string number, string fullName, Guid institutionId, long contractingPartyId, long institutionContractId, string typeOfSms) public async Task<bool> SendInstitutionCreationVerificationLink(string number, string fullName, Guid institutionId, long contractingPartyId, long institutionContractId, string typeOfSms)
{ {
typeOfSms = string.IsNullOrWhiteSpace(typeOfSms) ? "لینک تاییدیه ایجاد قرارداد مالی" : typeOfSms; typeOfSms = string.IsNullOrWhiteSpace(typeOfSms) ? "لینک تاییدیه ایجاد قرارداد مالی" : typeOfSms;
var full = fullName; var full = fullName;
var fullName1 = fullName; var fullName1 = fullName;
if (fullName.Length >= 25) if (fullName.Length >= 25)
{ {
fullName1 = fullName.Substring(0, 25); fullName1 = fullName.Substring(0, 25);
} }
var fullName2 = ""; var fullName2 = "";
if (full.Length > 25) if (full.Length > 25)
{ {
fullName2 = full.Substring(25); fullName2 = full.Substring(25);
if (fullName2.Length>25) if (fullName2.Length > 25)
{ {
fullName2 = fullName2.Substring(0, 25); fullName2 = fullName2.Substring(0, 25);
} }
} }
var guidStr = institutionId.ToString(); var guidStr = institutionId.ToString();
var firstPart = guidStr.Substring(0, 15); var firstPart = guidStr.Substring(0, 15);
var secondPart = guidStr.Substring(15); var secondPart = guidStr.Substring(15);
var verificationSendResult = await VerifySendSmsAsync(number, 527519, new VerifySendParameter[] var verificationSendResult = await VerifySendSmsAsync(number, 527519, new VerifySendParameter[]
{ {
new("FULLNAME1", fullName1), new("FULLNAME1", fullName1),
new("FULLNAME2", fullName2), new("FULLNAME2", fullName2),
new("CODE1",firstPart), new("CODE1",firstPart),
new("CODE2",secondPart) new("CODE2",secondPart)
}); });
if (verificationSendResult.Status == 1)
{
_logger.LogInformation("ارسال لینک قراداد مالی موفق بود");
}
else
{
_logger.LogError("خطا در ارسال لینک قراداد مالی");
}
var smsResult = new SmsResult(verificationSendResult.Data.MessageId, verificationSendResult.Message, typeOfSms, var smsResult = new SmsResult(verificationSendResult.Data.MessageId, verificationSendResult.Message, typeOfSms,
fullName, number, contractingPartyId, institutionContractId); fullName, number, contractingPartyId, institutionContractId);
await _smsResultRepository.CreateAsync(smsResult); await _smsResultRepository.CreateAsync(smsResult);
await _smsResultRepository.SaveChangesAsync(); await _smsResultRepository.SaveChangesAsync();
return verificationSendResult.Status == 0; _logger.LogInformation("ذخیره در دیتابیس موفق بود");
} return verificationSendResult.Status == 0;
}
public async Task<bool> SendInstitutionAmendmentVerificationLink(string number, string fullName, Guid institutionId, public async Task<bool> SendInstitutionAmendmentVerificationLink(string number, string fullName, Guid institutionId,
long contractingPartyId, long institutionContractId) long contractingPartyId, long institutionContractId)
{ {
var guidStr = institutionId.ToString(); var guidStr = institutionId.ToString();
var firstPart = guidStr.Substring(0, 15); var firstPart = guidStr.Substring(0, 15);
var secondPart = guidStr.Substring(15); var secondPart = guidStr.Substring(15);
var verificationSendResult = await VerifySendSmsAsync(number, 527519, new VerifySendParameter[] var verificationSendResult = await VerifySendSmsAsync(number, 527519, new VerifySendParameter[]
{ {
new("FULLNAME", fullName), new("FULLNAME", fullName),
new("CODE1",firstPart), new("CODE1",firstPart),
new("CODE2",secondPart) new("CODE2",secondPart)
}); });
var smsResult = new SmsResult(verificationSendResult.Data.MessageId, verificationSendResult.Message, "لینک تاییدیه ارتقا قرارداد مالی", var smsResult = new SmsResult(verificationSendResult.Data.MessageId, verificationSendResult.Message, "لینک تاییدیه ارتقا قرارداد مالی",
fullName, number, contractingPartyId, institutionContractId); fullName, number, contractingPartyId, institutionContractId);
await _smsResultRepository.CreateAsync(smsResult); await _smsResultRepository.CreateAsync(smsResult);
await _smsResultRepository.SaveChangesAsync(); await _smsResultRepository.SaveChangesAsync();
return verificationSendResult.Status == 0; return verificationSendResult.Status == 0;
} }
public async Task<bool> SendInstitutionVerificationCode(string number, string code, string contractingPartyFullName, public async Task<bool> SendInstitutionVerificationCode(string number, string code, string contractingPartyFullName,
long contractingPartyId, long institutionContractId) long contractingPartyId, long institutionContractId)
{ {
var verificationSendResult = await VerifySendSmsAsync(number, 965348, new VerifySendParameter[] var verificationSendResult = await VerifySendSmsAsync(number, 965348, new VerifySendParameter[]
{ {
new("VERIFYCODE", code) new("VERIFYCODE", code)
}); });
var smsResult = new SmsResult(verificationSendResult.Data.MessageId, verificationSendResult.Message, "کد تاییدیه قرارداد مالی", var smsResult = new SmsResult(verificationSendResult.Data.MessageId, verificationSendResult.Message, "کد تاییدیه قرارداد مالی",
contractingPartyFullName, number, contractingPartyId, institutionContractId); contractingPartyFullName, number, contractingPartyId, institutionContractId);
await _smsResultRepository.CreateAsync(smsResult); await _smsResultRepository.CreateAsync(smsResult);
await _smsResultRepository.SaveChangesAsync(); await _smsResultRepository.SaveChangesAsync();
return verificationSendResult.Status == 0; return verificationSendResult.Status == 0;
} }
public _0_Framework.Application.Sms.SmsResult TaskReminderSms(string number, string taskCount) public _0_Framework.Application.Sms.SmsResult TaskReminderSms(string number, string taskCount)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
#endregion #endregion
#region InstitutionContractSMS #region InstitutionContractSMS
public async Task<(byte status, string message, int messaeId, bool isSucceded)> MonthlyBillNew(string number, int tamplateId, string fullname, string amount, string code1, public async Task<(byte status, string message, int messaeId, bool isSucceded)> MonthlyBillNew(string number, int tamplateId, string fullname, string amount, string code1,
string code2) string code2)
{ {
var smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa"); var smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
var result = new ValueTuple<byte, string, int, bool>(); var result = new ValueTuple<byte, string, int, bool>();
var sendResult = await smsIr.VerifySendAsync(number, tamplateId, var sendResult = await smsIr.VerifySendAsync(number, tamplateId,
new VerifySendParameter[] new VerifySendParameter[]
{ new("FULLNAME", fullname), new("AMOUNT", amount), new("CODE1", code1), new("CODE2", code2) }); { new("FULLNAME", fullname), new("AMOUNT", amount), new("CODE1", code1), new("CODE2", code2) });
Thread.Sleep(500); Thread.Sleep(500);
if (sendResult.Message == "موفق") if (sendResult.Message == "موفق")
{ {
_logger.LogInformation("ارسال پیامک یادآور موفق بود");
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, true);
return result;
}
_logger.LogError("خطا در ارسال یاد آور");
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, false);
return result;
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, true); }
return result;
}
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, false); public async Task<(byte status, string message, int messaeId, bool isSucceded)> MonthlyBill(string number, int tamplateId, string fullname, string amount, string id,
return result; string aprove)
{
} var smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
var result = new ValueTuple<byte, string, int, bool>();
var sendResult = await smsIr.VerifySendAsync(number, tamplateId,
new VerifySendParameter[]
{ new("FULLNAME", fullname), new("AMOUNT", amount), new("ID", id), new("APROVE", aprove) });
Thread.Sleep(500);
public async Task<(byte status, string message, int messaeId, bool isSucceded)> MonthlyBill(string number, int tamplateId, string fullname, string amount, string id,
string aprove) if (sendResult.Message == "موفق")
{ {
_logger.LogInformation("ارسال پیامک یادآور موفق بود");
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, true);
return result;
}
_logger.LogError("خطا در ارسال یاد آور");
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, false);
return result;
}
var smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa"); public async Task<(byte status, string message, int messaeId, bool isSucceded)> BlockMessage(string number, string fullname, string amount, string accountType, string id,
var result = new ValueTuple<byte, string, int, bool>(); string aprove)
var sendResult = await smsIr.VerifySendAsync(number, tamplateId, {
new VerifySendParameter[] var tamplateId = 117946;
{ new("FULLNAME", fullname), new("AMOUNT", amount), new("ID", id), new("APROVE", aprove) }); var result = new ValueTuple<byte, string, int, bool>();
Thread.Sleep(500); var smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
var sendResult = await smsIr.VerifySendAsync(number, tamplateId,
new VerifySendParameter[]
{
new("FULLNAME", fullname), new("AMOUNT", amount), new("ACCOUNTTYPE", accountType), new("ID", id),
new("APROVE", aprove)
});
Thread.Sleep(500);
if (sendResult.Message == "موفق") if (sendResult.Message == "موفق")
{ {
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, true); result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, true);
return result; return result;
} }
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, false); result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, false);
return result; return result;
} }
public async Task<(byte status, string message, int messaeId, bool isSucceded)> BlockMessage(string number, string fullname, string amount, string accountType, string id, #endregion
string aprove)
{
var tamplateId = 117946;
var result = new ValueTuple<byte, string, int, bool>();
var smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
var sendResult = await smsIr.VerifySendAsync(number, tamplateId,
new VerifySendParameter[]
{
new("FULLNAME", fullname), new("AMOUNT", amount), new("ACCOUNTTYPE", accountType), new("ID", id),
new("APROVE", aprove)
});
Thread.Sleep(500);
if (sendResult.Message == "موفق") #region AlarmMessage
{
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, true); public async Task<bool> Alarm(string number, string message)
return result; {
} var smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
result = (sendResult.Status, sendResult.Message, sendResult.Data.MessageId, false); //var bulkSendResult = smsIr.BulkSendAsync(95007079000006, "your text message", new string[] { "9120000000" });
return result;
}
#endregion var verificationSendResult =
smsIr.VerifySendAsync(number, 662874, new VerifySendParameter[] { new("ALARM", message) });
Thread.Sleep(1000);
var status = verificationSendResult.Result.Status;
var mess = verificationSendResult.Result.Message;
var messaeId = verificationSendResult.Result.Data.MessageId;
if (verificationSendResult.IsCompletedSuccessfully) return true;
var resStartStatus = verificationSendResult.Result;
var resResult = verificationSendResult.Status;
var reseExceptiont = verificationSendResult.Exception;
#region AlarmMessage return false;
}
public async Task<bool> Alarm(string number, string message) #endregion
{
var smsIr = new SmsIr("Og5M562igmzJRhQPnq0GdtieYdLgtfikjzxOmeQBPxJjZtyge5Klc046Lfw1mxSa");
//var bulkSendResult = smsIr.BulkSendAsync(95007079000006, "your text message", new string[] { "9120000000" });
var verificationSendResult =
smsIr.VerifySendAsync(number, 662874, new VerifySendParameter[] { new("ALARM", message) });
Thread.Sleep(1000);
var status = verificationSendResult.Result.Status;
var mess = verificationSendResult.Result.Message;
var messaeId = verificationSendResult.Result.Data.MessageId;
if (verificationSendResult.IsCompletedSuccessfully) return true;
var resStartStatus = verificationSendResult.Result;
var resResult = verificationSendResult.Status;
var reseExceptiont = verificationSendResult.Exception;
return false;
}
#endregion
} }

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

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

View File

@@ -1,3 +1,4 @@
using System.Globalization;
using GozareshgirProgramManager.Application._Common.Interfaces; using GozareshgirProgramManager.Application._Common.Interfaces;
using GozareshgirProgramManager.Application._Common.Models; using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Domain._Common; using GozareshgirProgramManager.Domain._Common;
@@ -7,21 +8,22 @@ namespace GozareshgirProgramManager.Application.Modules.Projects.Queries.Project
public record ProjectBoardDetailQuery(Guid SectionId) : IBaseQuery<ProjectBoardDetailResponse>; public record ProjectBoardDetailQuery(Guid SectionId) : IBaseQuery<ProjectBoardDetailResponse>;
public record ProjectBoardDetailResponse(List<ProjectBoardDetailUserResponse> Users, string TotalTime); public record ProjectBoardDetailResponse(List<ProjectBoardDetailUserResponse> Users, string TotalTimeMinute,string RemainingTimeMinute );
public record ProjectBoardDetailUserResponse public record ProjectBoardDetailUserResponse
{ {
public List<ProjectBoardDetailUserHistoryResponse> Histories { get; set; } = new(); public List<ProjectBoardDetailUserHistoryResponse> Histories { get; init; }
public string UserFullName { get; set; } public string UserFullName { get; init; }
public long UserId { get; set; } public string SpentTimeMinute { get; init; }
public long UserId { get; init; }
} }
public class ProjectBoardDetailUserHistoryResponse public record ProjectBoardDetailUserHistoryResponse
{ {
public string Date { get; set; } public string Date { get; init; }
public string startTime { get; set; } public string startTime { get; init; }
public string EndTime { get; set; } public string EndTime { get; init; }
public string TotalTime { get; set; } public string TotalTimeMinute { get; init; }
} }
public class ProjectBoardDetailQueryHandler : IBaseQueryHandler<ProjectBoardDetailQuery, ProjectBoardDetailResponse> public class ProjectBoardDetailQueryHandler : IBaseQueryHandler<ProjectBoardDetailQuery, ProjectBoardDetailResponse>
@@ -38,6 +40,7 @@ public class ProjectBoardDetailQueryHandler : IBaseQueryHandler<ProjectBoardDeta
{ {
var section = await _programManagerDbContext.TaskSections var section = await _programManagerDbContext.TaskSections
.Include(x => x.Activities) .Include(x => x.Activities)
.Include(x=>x.AdditionalTimes)
.FirstOrDefaultAsync(x => x.Id == request.SectionId, cancellationToken: cancellationToken); .FirstOrDefaultAsync(x => x.Id == request.SectionId, cancellationToken: cancellationToken);
if (section == null) if (section == null)
@@ -49,26 +52,33 @@ public class ProjectBoardDetailQueryHandler : IBaseQueryHandler<ProjectBoardDeta
.Where(x => userIds.Contains(x.Id)) .Where(x => userIds.Contains(x.Id))
.ToDictionaryAsync(x => x.Id, x => x.FullName, cancellationToken); .ToDictionaryAsync(x => x.Id, x => x.FullName, cancellationToken);
var totalTimeSpan = section.Activities var totalActivityTimeSpan = section.Activities
.Select(x => x.GetTimeSpent()) .Select(x => x.GetTimeSpent())
.Aggregate(TimeSpan.Zero, (sum, next) => sum.Add(next)); .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 => var users = section.Activities.GroupBy(x => x.UserId).Select(x =>
{ {
return new ProjectBoardDetailUserResponse() return new ProjectBoardDetailUserResponse()
{ {
UserId = x.Key, UserId = x.Key,
UserFullName = usersDict[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() Histories = x.Select(h => new ProjectBoardDetailUserHistoryResponse()
{ {
Date = h.StartDate.ToFarsi(), Date = h.StartDate.ToFarsi(),
startTime = h.StartDate.ToString("HH:mm"), startTime = h.StartDate.ToString("HH:mm"),
EndTime = h.EndDate?.ToString("HH:mm") ?? "-", EndTime = h.EndDate?.ToString("HH:mm") ?? "-",
TotalTime = h.GetTimeSpent().ToString(@"hh\:mm") TotalTimeMinute = h.GetTimeSpent().TotalMinutes.ToString("F0",CultureInfo.InvariantCulture)
}).ToList() }).ToList()
}; };
}).ToList(); }).ToList();
var response = new ProjectBoardDetailResponse(users, $"{(int)totalTimeSpan.TotalHours}:{totalTimeSpan.Minutes:D2}"); var response = new ProjectBoardDetailResponse(users, $"{(int)finalTime.TotalMinutes}",
$"{(int)remainingTimeSpan.TotalMinutes:D2}");
return OperationResult<ProjectBoardDetailResponse>.Success(response); return OperationResult<ProjectBoardDetailResponse>.Success(response);
} }
} }

View File

@@ -217,4 +217,39 @@ public class TaskSection : EntityBase<Guid>
var finalEstimate = FinalEstimatedHours; var finalEstimate = FinalEstimatedHours;
return totalSpent < finalEstimate; 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; 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() public TimeSpan GetTimeSpent()
{ {
if (IsActive) if (IsActive)

View File

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

View File

@@ -1,4 +1,5 @@
using GozareshgirProgramManager.Domain.ProjectAgg.Entities; using GozareshgirProgramManager.Domain.ProjectAgg.Entities;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories; using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using GozareshgirProgramManager.Infrastructure.Persistence._Common; using GozareshgirProgramManager.Infrastructure.Persistence._Common;
using GozareshgirProgramManager.Infrastructure.Persistence.Context; using GozareshgirProgramManager.Infrastructure.Persistence.Context;
@@ -35,4 +36,13 @@ public class TaskSectionRepository:RepositoryBase<Guid,TaskSection>,ITaskSection
.Where(x => x.CurrentAssignedUserId == userId) .Where(x => x.CurrentAssignedUserId == userId)
.ToListAsync(); .ToListAsync();
} }
public Task<List<TaskSection>> GetActiveSectionsIncludeAllAsync(CancellationToken cancellationToken)
{
return _context.TaskSections
.Where(x => x.Status == TaskSectionStatus.InProgress)
.Include(x => x.Activities)
.Include(x => x.AdditionalTimes)
.ToListAsync(cancellationToken);
}
} }

View File

@@ -1,6 +1,7 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using GozareshgirProgramManager.Application._Common.Models; using GozareshgirProgramManager.Application._Common.Models;
using GozareshgirProgramManager.Application.Modules.Projects.Commands.AssignProject; using GozareshgirProgramManager.Application.Modules.Projects.Commands.AssignProject;
using GozareshgirProgramManager.Application.Modules.Projects.Commands.AutoStopOverTimeTaskSections;
using GozareshgirProgramManager.Application.Modules.Projects.Commands.ChangeStatusSection; using GozareshgirProgramManager.Application.Modules.Projects.Commands.ChangeStatusSection;
using GozareshgirProgramManager.Application.Modules.Projects.Commands.CreateProject; using GozareshgirProgramManager.Application.Modules.Projects.Commands.CreateProject;
using GozareshgirProgramManager.Application.Modules.Projects.Commands.DeleteProject; using GozareshgirProgramManager.Application.Modules.Projects.Commands.DeleteProject;
@@ -98,6 +99,9 @@ public class ProjectController : ProgramManagerBaseController
[HttpGet("board")] [HttpGet("board")]
public async Task<ActionResult<OperationResult<List<ProjectBoardListResponse>>>> GetProjectBoard([FromQuery] ProjectBoardListQuery query) public async Task<ActionResult<OperationResult<List<ProjectBoardListResponse>>>> GetProjectBoard([FromQuery] ProjectBoardListQuery query)
{ {
// اجرای Command برای متوقف کردن تسک‌های overtime قبل از نمایش
await _mediator.Send(new AutoStopOverTimeTaskSectionsCommand());
var res = await _mediator.Send(query); var res = await _mediator.Send(query);
return res; return res;
} }

View File

@@ -341,7 +341,7 @@ public class institutionContractController : AdminBaseController
{ {
var institutionContractViewModels = var institutionContractViewModels =
_institutionContractApplication.NewSearch(new() { IsActiveString = "both", TypeOfContract = "both" }); _institutionContractApplication.NewSearch(new() { IsActiveString = "both", TypeOfContract = "both" });
var bytes = InstitutionContractExcelGenerator.GenerateExcel(institutionContractViewModels); var bytes = InstitutionContractExcelGenerator.GenerateExcel(new List<InstitutionContractExcelViewModel>());
return File(bytes, return File(bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
$"قرارداد های مالی.xlsx"); $"قرارداد های مالی.xlsx");
@@ -809,11 +809,39 @@ public class institutionContractController : AdminBaseController
} }
[HttpPost("mannual-verify/{id}")] [HttpPost("mannual-verify/{id}")]
public async Task<ActionResult<OperationResult>> VerifyInstitutionContractMannualy(long id) public async Task<ActionResult<OperationResult>> VerifyInstitutionContractManually(long id)
{ {
var res= await _institutionContractApplication.VerifyInstitutionContractManually(id); var res= await _institutionContractApplication.VerifyInstitutionContractManually(id);
return res; return res;
} }
[HttpGet("excel-download")]
public async Task<IActionResult> ExcelDownload()
{
var searchModel = new InstitutionContractListSearchModel();
var dataVm=new List<InstitutionContractExcelViewModel>();
foreach (var name in typeof(InstitutionContractListStatus).GetEnumNames())
{
var @enum = Enum.Parse<InstitutionContractListStatus>(name);
searchModel.Status = @enum;
searchModel.PageSize = 99999;
var data =( await(_institutionContractApplication.GetList(searchModel))).List;
dataVm.Add(new InstitutionContractExcelViewModel(){Tab = @enum, GetInstitutionContractListItemsViewModels = data});
}
searchModel.Status = null;
var nullData = ( await(_institutionContractApplication.GetList(searchModel))).List;
dataVm.Add(new InstitutionContractExcelViewModel(){Tab = null, GetInstitutionContractListItemsViewModels = nullData});
var bytes = InstitutionContractExcelGenerator.GenerateExcel(dataVm);
return File(bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
$"قرارداد های مالی.xlsx");
}
} }

View File

@@ -2,6 +2,7 @@
using System.Drawing; using System.Drawing;
using _0_Framework.Application; using _0_Framework.Application;
using AccountManagement.Application.Contracts.Account; using AccountManagement.Application.Contracts.Account;
using Company.Domain.InstitutionContractAgg;
using CompanyManagement.Infrastructure.Excel.InstitutionContract; using CompanyManagement.Infrastructure.Excel.InstitutionContract;
using CompanyManagment.App.Contracts.Employer; using CompanyManagment.App.Contracts.Employer;
using CompanyManagment.App.Contracts.InstitutionContract; using CompanyManagment.App.Contracts.InstitutionContract;
@@ -38,6 +39,7 @@ public class IndexModel : PageModel
private readonly IInstitutionContractApplication _institutionContract; private readonly IInstitutionContractApplication _institutionContract;
private readonly ILeftWorkApplication _leftWorkApplication; private readonly ILeftWorkApplication _leftWorkApplication;
private readonly IRepresentativeApplication _representativeApplication; private readonly IRepresentativeApplication _representativeApplication;
private readonly IInstitutionContractRepository _institutionContractRepository;
private readonly string _viewName; private readonly string _viewName;
@@ -60,7 +62,7 @@ public class IndexModel : PageModel
IPersonalContractingPartyApp contractingPartyApplication, IPersonalContractingPartyApp contractingPartyApplication,
IRepresentativeApplication representativeApplication, IInstitutionContractApplication institutionContract, IRepresentativeApplication representativeApplication, IInstitutionContractApplication institutionContract,
ILeftWorkApplication leftWorkApplication ILeftWorkApplication leftWorkApplication
, IContactInfoApplication contactInfoApplication, IAccountApplication accountApplication) , IContactInfoApplication contactInfoApplication, IAccountApplication accountApplication, IInstitutionContractRepository institutionContractRepository)
{ {
_workshopApplication = workshopApplication; _workshopApplication = workshopApplication;
@@ -71,6 +73,7 @@ public class IndexModel : PageModel
_leftWorkApplication = leftWorkApplication; _leftWorkApplication = leftWorkApplication;
_contactInfoApplication = contactInfoApplication; _contactInfoApplication = contactInfoApplication;
_accountApplication = accountApplication; _accountApplication = accountApplication;
_institutionContractRepository = institutionContractRepository;
} }
public string Message { get; set; } public string Message { get; set; }
@@ -920,12 +923,27 @@ public class IndexModel : PageModel
}); });
} }
public IActionResult OnGetDownloadExcel() public async Task<IActionResult> OnGetDownloadExcel()
{ {
var institutionContractViewModels = _institutionContract.NewSearch(new() {IsActiveString = "both", TypeOfContract = "both" }); var searchModel = new InstitutionContractListSearchModel();
institutionContractViewModels= institutionContractViewModels.GroupBy(x=>x.ContractingPartyId).Select(g=>g.MaxBy(x=>x.ContractStartGr)).ToList(); var dataVm=new List<InstitutionContractExcelViewModel>();
var bytes = InstitutionContractExcelGenerator.GenerateExcel(institutionContractViewModels);
foreach (var name in typeof(InstitutionContractListStatus).GetEnumNames())
{
var @enum = Enum.Parse<InstitutionContractListStatus>(name);
searchModel.Status = @enum;
searchModel.PageSize = 99999;
var data =( await(_institutionContractRepository.GetList(searchModel))).List;
dataVm.Add(new InstitutionContractExcelViewModel(){Tab = @enum, GetInstitutionContractListItemsViewModels = data});
}
searchModel.Status = null;
var nullData = ( await(_institutionContractRepository.GetList(searchModel))).List;
dataVm.Add(new InstitutionContractExcelViewModel(){Tab = null, GetInstitutionContractListItemsViewModels = nullData});
var bytes = InstitutionContractExcelGenerator.GenerateExcel(dataVm);
return File(bytes, return File(bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
$"قرارداد های مالی.xlsx"); $"قرارداد های مالی.xlsx");

View File

@@ -43,6 +43,9 @@
case TypeOfSmsSetting.Warning: case TypeOfSmsSetting.Warning:
<h5 class="modal-title">ایجاد پیامک هشدار قضائی</h5> <h5 class="modal-title">ایجاد پیامک هشدار قضائی</h5>
break; break;
case TypeOfSmsSetting.InstitutionContractConfirm:
<h5 class="modal-title">ایجاد پیامک یادآور تایید قراداد</h5>
break;
} }
} }

View File

@@ -41,6 +41,10 @@
case TypeOfSmsSetting.Warning: case TypeOfSmsSetting.Warning:
<h5 class="modal-title">ویرایش پیامک هشدار قضائی</h5> <h5 class="modal-title">ویرایش پیامک هشدار قضائی</h5>
break; break;
case TypeOfSmsSetting.InstitutionContractConfirm:
<h5 class="modal-title">ویرایش پیامک یادآور تایید قراداد</h5>
break;
} }
} }
<button type="button" class="close" data-dismiss="modal" aria-label="بستن"> <button type="button" class="close" data-dismiss="modal" aria-label="بستن">
@@ -100,8 +104,8 @@
success: function (response) { success: function (response) {
if(response.isSuccess){ if(response.isSuccess){
$.Notification.autoHideNotify('success', 'top center', 'پیام سیستم ', response.message); $.Notification.autoHideNotify('success', 'top center', 'پیام سیستم ', response.message);
$('.close').click();
$('.close').click();
setTimeout(function () { setTimeout(function () {
if(modelTypeOfSmsSetting == '@TypeOfSmsSetting.InstitutionContractDebtReminder'){ if(modelTypeOfSmsSetting == '@TypeOfSmsSetting.InstitutionContractDebtReminder'){
$('#institutionContractDebtReminderTab').click(); $('#institutionContractDebtReminderTab').click();
@@ -114,14 +118,16 @@
}else if(modelTypeOfSmsSetting == '@TypeOfSmsSetting.Warning'){ }else if(modelTypeOfSmsSetting == '@TypeOfSmsSetting.Warning'){
$('#warningTab').click(); $('#warningTab').click();
}else if(typeOfSmsSetting == '@TypeOfSmsSetting.InstitutionContractConfirm'){ }else if(modelTypeOfSmsSetting == '@TypeOfSmsSetting.InstitutionContractConfirm'){
$('#institutionContractConfirmTab').click(); $('#institutionContractConfirmTab').click();
} }
}, 700);
}, 500);
}else{ }else{
$.Notification.autoHideNotify('error', 'top center', 'پیام سیستم ', response.message); $.Notification.autoHideNotify('error', 'top center', 'پیام سیستم ', response.message);
} }

View File

@@ -74,8 +74,8 @@
</form> </form>
<div class="lineDiv"></div> <div class="lineDiv"></div>
<div class="row m-t-20"> <div class="row m-t-20">
<div class="col-4"></div> <div class="col-md-4 visible-md visible-lg"></div>
<div class="col-2"> <div class="col-6 col-md-2">
<form asp-page-handler="UploadFrontEnd" id="12" method="post"> <form asp-page-handler="UploadFrontEnd" id="12" method="post">
<button type="submit" <button type="submit"
class="btn btn-danger" class="btn btn-danger"
@@ -84,14 +84,14 @@
</button> </button>
</form> </form>
</div> </div>
<div class="col-2"> <div class="col-6 col-md-2">
<button type="button" class="btn btn-outline-secondary" <button type="button" class="btn btn-outline-secondary"
data-bs-toggle="modal" data-bs-toggle="modal"
data-bs-target="#logModal"> data-bs-target="#logModal">
مشاهده لاگ Deploy مشاهده لاگ Deploy
</button> </button>
</div> </div>
<div class="col-4"></div> <div class="col-md-4 visible-md visible-lg"></div>
</div> </div>
<div class="lineDiv"></div> <div class="lineDiv"></div>

View File

@@ -52,6 +52,7 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
private readonly IOnlinePayment _onlinePayment; private readonly IOnlinePayment _onlinePayment;
private readonly IFaceEmbeddingService _faceEmbeddingService; private readonly IFaceEmbeddingService _faceEmbeddingService;
private readonly IAuthHelper _authHelper; private readonly IAuthHelper _authHelper;
private readonly IInstitutionContractApplication _institutionContractApplication;
[BindProperty] public IFormFile File { get; set; } [BindProperty] public IFormFile File { get; set; }
@@ -77,7 +78,8 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
public IndexModel(IAndroidApkVersionApplication application, IRollCallDomainService rollCallDomainService, public IndexModel(IAndroidApkVersionApplication application, IRollCallDomainService rollCallDomainService,
CompanyContext context, AccountContext accountContext, IHttpClientFactory httpClientFactory, CompanyContext context, AccountContext accountContext, IHttpClientFactory httpClientFactory,
IOptions<AppSettingConfiguration> appSetting, IOptions<AppSettingConfiguration> appSetting,
ITemporaryClientRegistrationApplication clientRegistrationApplication, IOnlinePayment onlinePayment, IFaceEmbeddingService faceEmbeddingService, IAuthHelper authHelper) ITemporaryClientRegistrationApplication clientRegistrationApplication, IOnlinePayment onlinePayment,
IFaceEmbeddingService faceEmbeddingService, IAuthHelper authHelper, IInstitutionContractApplication institutionContractApplication)
{ {
_application = application; _application = application;
_rollCallDomainService = rollCallDomainService; _rollCallDomainService = rollCallDomainService;
@@ -88,6 +90,7 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
_onlinePayment = onlinePayment; _onlinePayment = onlinePayment;
_faceEmbeddingService = faceEmbeddingService; _faceEmbeddingService = faceEmbeddingService;
_authHelper = authHelper; _authHelper = authHelper;
_institutionContractApplication = institutionContractApplication;
_paymentGateway = new SepehrPaymentGateway(httpClientFactory); _paymentGateway = new SepehrPaymentGateway(httpClientFactory);
} }
@@ -152,31 +155,60 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
{ {
//await UpdateInstitutionContract(); //await UpdateInstitutionContract();
//await UpdateFaceEmbeddingNames(); //await UpdateFaceEmbeddingNames();
await SetInstitutionContractSigningType(); //await SetInstitutionContractSigningType();
await ReActivateInstitution();
ViewData["message"] = "تومام یک"; ViewData["message"] = "تومام یک";
return Page(); return Page();
} }
private async System.Threading.Tasks.Task ReActivateInstitution()
{
var blueInstitutionContracts = await _context.InstitutionContractSet.Where(x =>
x.IsActiveString == "blue").ToListAsync();
var blueContracts = new List<InstitutionContract>();
foreach (var blueContract in blueInstitutionContracts)
{
var verifiedContracts = await _context.InstitutionContractSet
.Where(x => x.ContractingPartyId == blueContract.ContractingPartyId
&& x.VerificationStatus == InstitutionContractVerificationStatus.Verified
&& x.ContractStartGr > blueContract.ContractEndGr)
.ToListAsync();
if (verifiedContracts.Any())
{
blueContracts.Add(blueContract);
}
}
foreach (var institutionContract in blueContracts)
{
institutionContract.DeActive();
_institutionContractApplication.ReActiveAllAfterCreateNew(institutionContract.ContractingPartyId);
}
}
private async System.Threading.Tasks.Task SetInstitutionContractSigningType() private async System.Threading.Tasks.Task SetInstitutionContractSigningType()
{ {
var query = _context.InstitutionContractSet var query = _context.InstitutionContractSet
.Where(x=>x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify); .Where(x => x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify);
var otpSigned = query.Where(x=>x.VerifierFullName != null && x.LawId != 0).ToList(); var otpSigned = query.Where(x => x.VerifierFullName != null && x.LawId != 0).ToList();
foreach (var institutionContract in otpSigned) foreach (var institutionContract in otpSigned)
{ {
institutionContract.SetSigningType(InstitutionContractSigningType.OtpBased); institutionContract.SetSigningType(InstitutionContractSigningType.OtpBased);
} }
var lagacySigned = query.Where(x=>x.VerifierFullName == null && x.LawId == 0).ToList();
var lagacySigned = query.Where(x => x.VerifierFullName == null && x.LawId == 0).ToList();
foreach (var institutionContract in lagacySigned) foreach (var institutionContract in lagacySigned)
{ {
institutionContract.SetSigningType(InstitutionContractSigningType.Legacy); institutionContract.SetSigningType(InstitutionContractSigningType.Legacy);
} }
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
} }
public async Task<IActionResult> OnPostShiftDateNew2() public async Task<IActionResult> OnPostShiftDateNew2()
@@ -326,30 +358,51 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
//TranslateCode(result?.ErrorCode); //TranslateCode(result?.ErrorCode);
return Page(); return Page();
} }
[DisableConcurrentExecution(timeoutInSeconds: 120)] [DisableConcurrentExecution(timeoutInSeconds: 120)]
public async Task<IActionResult> OnPostUploadFrontEnd(CancellationToken cancellationToken) public async Task<IActionResult> OnPostUploadFrontEnd(CancellationToken cancellationToken)
{ {
var validAccountId = _authHelper.CurrentAccountId(); var validAccountId = _authHelper.CurrentAccountId();
if (validAccountId == 2 || validAccountId == 322) if (validAccountId == 2 || validAccountId == 322)
{ {
var batPath = @"C:\next-ui\deploy-next-ui.bat"; //var batPath = @"C:\next-ui\deploy-next-ui.bat";
//var psi = new ProcessStartInfo
//{
// FileName = batPath,
// UseShellExecute = true, // خیلی مهم
// Verb = "runas", // اجرای Administrator
// CreateNoWindow = true,
// WindowStyle = ProcessWindowStyle.Hidden
//};
//Process.Start(psi);
var psi = new ProcessStartInfo var psi = new ProcessStartInfo
{ {
FileName = batPath, FileName = "cmd.exe",
UseShellExecute = true, // خیلی مهم Arguments = "/c schtasks /run /tn \"DeployNextUI\"",
Verb = "runas", // اجرای Administrator UseShellExecute = false,
CreateNoWindow = true, CreateNoWindow = true
WindowStyle = ProcessWindowStyle.Hidden
}; };
Process.Start(psi); Process.Start(psi);
//var psi = new ProcessStartInfo
//{
// FileName = @"C:\next-ui\deploy-next-ui.bat",
// UseShellExecute = false,
// CreateNoWindow = false
//};
//Process.Start(psi);
TempData["Message"] = "فرآیند Deploy شروع شد. لاگ را بررسی کنید."; TempData["Message"] = "فرآیند Deploy شروع شد. لاگ را بررسی کنید.";
return RedirectToPage(); return RedirectToPage();
} }
return Forbid();
return Forbid();
} }
/// <summary> /// <summary>
@@ -375,13 +428,10 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
{ {
contractingPartyIdList.Add(employer.Employer.ContractingPartyId); contractingPartyIdList.Add(employer.Employer.ContractingPartyId);
} }
} }
if (contractingPartyIdList.Count > 0) if (contractingPartyIdList.Count > 0)
{ {
if (contractingPartyIdList.Count == 1) if (contractingPartyIdList.Count == 1)
{ {
workshop.AddContractingPartyId(contractingPartyIdList[0]); workshop.AddContractingPartyId(contractingPartyIdList[0]);
@@ -402,7 +452,6 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
ViewData["message"] = "آی دی های طرف حساب اضافه شد"; ViewData["message"] = "آی دی های طرف حساب اضافه شد";
return Page(); return Page();
} }
/// <summary> /// <summary>
@@ -421,8 +470,8 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
var content = System.IO.File.ReadAllText(logPath, Encoding.UTF8); var content = System.IO.File.ReadAllText(logPath, Encoding.UTF8);
return Content(content); return Content(content);
} }
return Content("شما مجاز به دیدن لاگ نیستید");
return Content("شما مجاز به دیدن لاگ نیستید");
} }
@@ -1035,7 +1084,7 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
x.PersonnelCount, x.PersonnelCount,
x.Price, x.InstitutionContractWorkshopGroupId, x.Price, x.InstitutionContractWorkshopGroupId,
group, group,
x.WorkshopId.Value,x.id); x.WorkshopId.Value, x.id);
entity.SetEmployers(x.Employers.Select(e => e.EmployerId).ToList()); entity.SetEmployers(x.Employers.Select(e => e.EmployerId).ToList());
return entity; return entity;

View File

@@ -0,0 +1,25 @@
using _0_Framework.Application;
using CompanyManagment.App.Contracts.Employee;
using Microsoft.AspNetCore.Mvc;
using ServiceHost.BaseControllers;
namespace ServiceHost.Areas.Client.Controllers;
public class EmployeeController:ClientBaseController
{
private readonly IEmployeeApplication _employeeApplication;
private readonly long _workshopId;
public EmployeeController(IEmployeeApplication employeeApplication,IAuthHelper authHelper)
{
_employeeApplication = employeeApplication;
_workshopId = authHelper.GetWorkshopId();
}
[HttpGet("select-list")]
public async Task<ActionResult<List<EmployeeSelectListViewModel>>> GetEmployeeSelectList()
{
var result = await _employeeApplication.WorkedEmployeesInWorkshopSelectList(_workshopId);
return result;
}
}

View File

@@ -293,9 +293,9 @@ namespace ServiceHost.Areas.Client.Pages.Company.RollCall
}); });
} }
public IActionResult OnPostReCalculateValues(List<ReCalculateRollCallValues> command) public async Task<IActionResult> OnPostReCalculateValues(List<ReCalculateRollCallValues> command)
{ {
var result = _rollCallApplication.RecalculateValues(_workshopId, command); var result =await _rollCallApplication.RecalculateValues(_workshopId, command);
return new JsonResult(new return new JsonResult(new
{ {

View File

@@ -75,7 +75,7 @@ public class GeneralController : GeneralBaseController
} }
[HttpGet("/api/callback"), HttpPost("/api/callback")] [HttpGet("/api/callback"), HttpPost("/api/callback")]
public async Task<IActionResult> Verify(SepehrGatewayPayResponse payResponse) public async Task<IActionResult> Verify([FromForm]SepehrGatewayPayResponse payResponse)
{ {
if (!long.TryParse(payResponse.invoiceid, out var paymentTransactionId)) if (!long.TryParse(payResponse.invoiceid, out var paymentTransactionId))
{ {
@@ -133,7 +133,12 @@ public class GeneralController : GeneralBaseController
DigitalReceipt = payResponse.digitalreceipt DigitalReceipt = payResponse.digitalreceipt
}; };
var verifyRes = await _paymentGateway.Verify(verifyCommand, CancellationToken.None); var verifyRes = await _paymentGateway.Verify(verifyCommand, CancellationToken.None);
#if DEBUG
verifyRes.IsSuccess = true;
#endif
_financialInvoiceApplication.SetPaid(financialInvoiceId, DateTime.Now); _financialInvoiceApplication.SetPaid(financialInvoiceId, DateTime.Now);
if (verifyRes.IsSuccess) if (verifyRes.IsSuccess)
@@ -158,14 +163,18 @@ public class GeneralController : GeneralBaseController
payResponse.cardnumber, payResponse.issuerbank, payResponse.rrn.ToString(), payResponse.cardnumber, payResponse.issuerbank, payResponse.rrn.ToString(),
payResponse.digitalreceipt); payResponse.digitalreceipt);
if (financialInvoice.Items?.Any(x => x.Type is FinancialInvoiceItemType.BuyInstitutionContract or FinancialInvoiceItemType.BuyInstitutionContractInstallment) ?? false) if (financialInvoice.Items?.Any(x =>
x.Type is FinancialInvoiceItemType.BuyInstitutionContract
or FinancialInvoiceItemType.BuyInstitutionContractInstallment) ?? false)
{ {
var financialItems = financialInvoice.Items var financialItems = financialInvoice.Items
.Where(x => x.Type == FinancialInvoiceItemType.BuyInstitutionContract); .Where(x => x.Type == FinancialInvoiceItemType.BuyInstitutionContract);
foreach (var editFinancialInvoiceItem in financialItems) foreach (var editFinancialInvoiceItem in financialItems)
{ {
await _institutionContractApplication.SetPendingWorkflow(editFinancialInvoiceItem.EntityId,InstitutionContractSigningType.OtpBased); await _institutionContractApplication.SetPendingWorkflow(editFinancialInvoiceItem.EntityId,
InstitutionContractSigningType.OtpBased);
} }
var financialInstallmentItems = financialInvoice.Items var financialInstallmentItems = financialInvoice.Items
.Where(x => x.Type == FinancialInvoiceItemType.BuyInstitutionContractInstallment); .Where(x => x.Type == FinancialInvoiceItemType.BuyInstitutionContractInstallment);
@@ -174,7 +183,8 @@ public class GeneralController : GeneralBaseController
var institutionContractId = var institutionContractId =
await _institutionContractApplication.GetIdByInstallmentId( await _institutionContractApplication.GetIdByInstallmentId(
editFinancialInvoiceItem.EntityId); editFinancialInvoiceItem.EntityId);
await _institutionContractApplication.SetPendingWorkflow(institutionContractId,InstitutionContractSigningType.OtpBased); await _institutionContractApplication.SetPendingWorkflow(institutionContractId,
InstitutionContractSigningType.OtpBased);
} }
} }

View File

@@ -289,6 +289,7 @@ builder.Services.AddCors(options =>
"http://localhost:3000", "http://localhost:3000",
"http://localhost:4000", "http://localhost:4000",
"http://localhost:4001", "http://localhost:4001",
"http://localhost:4002",
"http://localhost:3001", "http://localhost:3001",
"https://gozareshgir.ir", "https://gozareshgir.ir",
"https://dad-mehr.ir", "https://dad-mehr.ir",

View File

@@ -11,7 +11,7 @@
}, },
"ServiceHost": { "ServiceHost": {
"commandName": "Project", "commandName": "Project",
"launchBrowser": true, "launchBrowser": false,
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation"