Compare commits

..

1 Commits

Author SHA1 Message Date
49c88e68d2 feat: implement Yekta checkout Excel generation and add view model 2025-12-22 15:51:57 +03:30
51 changed files with 805 additions and 1738 deletions

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,5 @@
using _0_Framework.Application;
using _0_Framework.Application.Sms;
using Company.Domain.ContarctingPartyAgg;
using Company.Domain.InstitutionContractAgg;
using Hangfire;
@@ -14,22 +13,18 @@ public class JobSchedulerRegistrator
private readonly IInstitutionContractRepository _institutionContractRepository;
private static DateTime? _lastRunCreateTransaction;
private static DateTime? _lastRunSendMonthlySms;
private readonly ISmsService _smsService;
private readonly ILogger<JobSchedulerRegistrator> _logger;
public JobSchedulerRegistrator(SmsReminder smsReminder, IBackgroundJobClient backgroundJobClient, IInstitutionContractRepository institutionContractRepository, ISmsService smsService, ILogger<JobSchedulerRegistrator> logger)
public JobSchedulerRegistrator(SmsReminder smsReminder, IBackgroundJobClient backgroundJobClient, IInstitutionContractRepository institutionContractRepository)
{
_smsReminder = smsReminder;
_backgroundJobClient = backgroundJobClient;
_institutionContractRepository = institutionContractRepository;
_smsService = smsService;
_logger = logger;
}
public void Register()
{
_logger.LogInformation("hangfire Started");
RecurringJob.AddOrUpdate(
"InstitutionContract.CreateFinancialTransaction",
() => CreateFinancialTransaction(),
@@ -96,8 +91,8 @@ public class JobSchedulerRegistrator
}
catch (Exception e)
{
await _smsService.Alarm("09114221321", "خطا-ایجاد سند مالی");
//_smsService.Alarm("09114221321", "خطا-ایجاد سند مالی");
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,142 @@
using _0_Framework.Application;
using OfficeOpenXml;
using OfficeOpenXml.Style;
namespace CompanyManagement.Infrastructure.Excel.Checkout;
public class YektaTejaratCheckout
{
private static readonly Dictionary<string, string> Header = new()
{
{ "FullName", "نام و نام خانوادگی" },
{ "NationalCode", "کد ملی" },
{ "StaticPayableAmount", "مبلغ قابل پرداخت استاتیک" },
{ "AttendancePayableAmount", "مبلغ قابل پرداخت حضور غیاب" }
};
public static byte[] GenerateYektaTejaratCheckoutExcel(List<YektaTejaratCheckoutViewModel> data)
{
ExcelPackage.License.SetNonCommercialOrganization("Gozareshgir Noncommercial organization");
using var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
// Add row index header
var indexCell = worksheet.Cells[1, 1];
indexCell.Value = "ردیف";
ApplyHeaderStyle(indexCell);
// Add headers to worksheet
for (int i = 0; i < Header.Count; i++)
{
worksheet.Cells[1, i + 2].Value = Header.ElementAt(i).Value;
ApplyHeaderStyle(worksheet.Cells[1, i + 2]);
}
// Add data rows
var dataRow = 2;
foreach (var item in data)
{
// Row number
var rowCounter = worksheet.Cells[dataRow, 1];
rowCounter.Value = dataRow - 1;
ApplyGeneralDataStyle(rowCounter);
ApplySpecificStyle(rowCounter, 1);
var column = 2;
foreach (var header in Header)
{
var property = item.GetType().GetProperty(header.Key);
var value = property?.GetValue(item, null)?.ToString();
// Check if the property requires MoneyToDouble()
if (RequiresMoneyToDouble(property?.Name))
{
worksheet.Cells[dataRow, column].Value = MoneyToDouble(value);
}
else
{
worksheet.Cells[dataRow, column].Value = value;
}
ApplyGeneralDataStyle(worksheet.Cells[dataRow, column]);
ApplySpecificStyle(worksheet.Cells[dataRow, column], column);
column++;
}
dataRow++;
}
// Auto-fit columns and set print settings
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
worksheet.PrinterSettings.PaperSize = ePaperSize.A4;
worksheet.PrinterSettings.Orientation = eOrientation.Portrait;
worksheet.PrinterSettings.FitToPage = true;
worksheet.PrinterSettings.FitToWidth = 1;
worksheet.PrinterSettings.FitToHeight = 0;
worksheet.View.RightToLeft = true;
return package.GetAsByteArray();
}
// Method to check if a property requires MoneyToDouble()
private static bool RequiresMoneyToDouble(string propertyName)
{
var propertiesRequiringConversion = new HashSet<string>
{
"StaticPayableAmount", "AttendancePayableAmount"
};
return propertiesRequiringConversion.Contains(propertyName);
}
// Convert money string to double
private static double MoneyToDouble(string value)
{
if (string.IsNullOrEmpty(value))
return 0;
var min = value.Length > 1 ? value.Substring(0, 2) : "";
var result = min == "\u200e\u2212" ? value.MoneyToDouble() * -1 : value.MoneyToDouble();
return result;
}
private static void ApplyHeaderStyle(ExcelRange cell)
{
cell.Style.Font.Bold = true;
cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
cell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
cell.Style.Border.BorderAround(ExcelBorderStyle.Thin);
}
private static void ApplyGeneralDataStyle(ExcelRange cell)
{
cell.Style.Border.BorderAround(ExcelBorderStyle.Thin);
cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
}
private static void ApplySpecificStyle(ExcelRange cell, int columnIndex)
{
switch (columnIndex)
{
case 1: // ردیف
cell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
break;
case 2: // نام و نام خانوادگی
case 3: // کد ملی
cell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightYellow);
break;
case 4: // مبلغ قابل پرداخت استاتیک
cell.Style.Fill.BackgroundColor.SetColor(1, 208, 248, 208); // Light green
cell.Style.Numberformat.Format = "#,##0";
break;
case 5: // مبلغ قابل پرداخت حضور غیاب
cell.Style.Fill.BackgroundColor.SetColor(1, 168, 186, 254); // Light blue
cell.Style.Numberformat.Format = "#,##0";
break;
}
}
}

View File

@@ -0,0 +1,10 @@
namespace CompanyManagement.Infrastructure.Excel.Checkout;
public class YektaTejaratCheckoutViewModel
{
public required string FullName { get; set; }
public required string NationalCode { get; set; }
public required string StaticPayableAmount { get; set; }
public required string AttendancePayableAmount { get; set; }
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -22,7 +22,6 @@ using Company.Domain.InstitutionContractAgg;
using Company.Domain.LeftWorkAgg;
using Company.Domain.PaymentTransactionAgg;
using Company.Domain.RepresentativeAgg;
using Company.Domain.RollCallServiceAgg;
using Company.Domain.TemporaryClientRegistrationAgg;
using Company.Domain.WorkshopAgg;
using CompanyManagment.App.Contracts.FinancialInvoice;
@@ -60,7 +59,6 @@ public class InstitutionContractApplication : IInstitutionContractApplication
private readonly IFinancialInvoiceRepository _financialInvoiceRepository;
private readonly IPaymentGateway _paymentGateway;
private readonly IPaymentTransactionRepository _paymentTransactionRepository;
private readonly IRollCallServiceRepository _rollCallServiceRepository;
public InstitutionContractApplication(IInstitutionContractRepository institutionContractRepository,
@@ -72,7 +70,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
IFinancialStatmentRepository financialStatmentRepository, IContactInfoApplication contactInfoApplication,
IAccountApplication accountApplication, ISmsService smsService, IUidService uidService,
IFinancialInvoiceRepository financialInvoiceRepository, IHttpClientFactory httpClientFactory,
IPaymentTransactionRepository paymentTransactionRepository, IRollCallServiceRepository rollCallServiceRepository)
IPaymentTransactionRepository paymentTransactionRepository)
{
_institutionContractRepository = institutionContractRepository;
_contractingPartyRepository = contractingPartyRepository;
@@ -90,7 +88,6 @@ public class InstitutionContractApplication : IInstitutionContractApplication
_uidService = uidService;
_financialInvoiceRepository = financialInvoiceRepository;
_paymentTransactionRepository = paymentTransactionRepository;
_rollCallServiceRepository = rollCallServiceRepository;
_paymentGateway = new SepehrPaymentGateway(httpClientFactory);
}
@@ -1558,48 +1555,28 @@ public class InstitutionContractApplication : IInstitutionContractApplication
.Where(x => x.WorkshopCreated && x.WorkshopId is > 0).ToList();
var currentWorkshops = institutionContract.WorkshopGroup.CurrentWorkshops.ToList();
var accountId = _contractingPartyRepository
.GetAccountByPersonalContractingParty(institutionContract.ContractingPartyId).Id;
foreach (var createdWorkshop in initialCreatedWorkshops)
{
if (currentWorkshops.Any(x => x.WorkshopId == createdWorkshop.WorkshopId))
{
//rollcall serviecs
if (createdWorkshop.Services.RollCall)
{
var ActiveService = _rollCallServiceRepository.GetActiveServiceByWorkshopId(createdWorkshop.WorkshopId!.Value);
var startTime = institutionContract.ContractStartGr;
var endTime = institutionContract.ContractEndGr;
if (ActiveService != null)
{
if (ActiveService.EndService> startTime)
{
startTime = ActiveService.EndService;
}
}
var rollCallService = new RollCallService("BasedOnIC",
startTime, endTime, createdWorkshop.WorkshopId.Value,accountId,createdWorkshop.PersonnelCount,
0,"12");
await _rollCallServiceRepository.CreateAsync(rollCallService);
}
}
else
{
var currentWorkshop = new InstitutionContractWorkshopCurrent(createdWorkshop.WorkshopName,
createdWorkshop.Services.RollCall, createdWorkshop.Services.RollCallInPerson,
createdWorkshop.Services.CustomizeCheckout, createdWorkshop.Services.Contract,
createdWorkshop.Services.ContractInPerson, createdWorkshop.Services.Insurance,
createdWorkshop.Services.InsuranceInPerson,createdWorkshop.PersonnelCount, createdWorkshop.Price,
createdWorkshop.InstitutionContractWorkshopGroupId,createdWorkshop.WorkshopGroup,
createdWorkshop.WorkshopId!.Value, createdWorkshop.id);
institutionContract.WorkshopGroup.AddCurrentWorkshop(currentWorkshop);
continue;
}
var currentWorkshop = new InstitutionContractWorkshopCurrent(createdWorkshop.WorkshopName,
createdWorkshop.Services.RollCall, createdWorkshop.Services.RollCallInPerson,
createdWorkshop.Services.CustomizeCheckout, createdWorkshop.Services.Contract,
createdWorkshop.Services.ContractInPerson, createdWorkshop.Services.Insurance,
createdWorkshop.Services.InsuranceInPerson,createdWorkshop.PersonnelCount, createdWorkshop.Price,
createdWorkshop.InstitutionContractWorkshopGroupId,createdWorkshop.WorkshopGroup,
createdWorkshop.WorkshopId!.Value, createdWorkshop.id);
institutionContract.WorkshopGroup.AddCurrentWorkshop(currentWorkshop);
}
if (institutionContract.WorkshopGroup.InitialWorkshops.All(x => x.WorkshopCreated && x.WorkshopId is > 0))
{
institutionContract.Verified();
}
else
@@ -1608,10 +1585,7 @@ public class InstitutionContractApplication : IInstitutionContractApplication
}
institutionContract.SetSigningType(signingType);
var previousInstitutionContract = await _institutionContractRepository
.GetPreviousContract(institutionContract.id);
previousInstitutionContract?.DeActive();
ReActiveAllAfterCreateNew(institutionContract.ContractingPartyId);
await _institutionContractRepository.SaveChangesAsync();
return op.Succcedded();
}
@@ -1637,23 +1611,9 @@ public class InstitutionContractApplication : IInstitutionContractApplication
var transaction = await _institutionContractRepository.BeginTransactionAsync();
await SetPendingWorkflow(institutionContractId,InstitutionContractSigningType.Physical);
var financialStatement = await _financialStatmentRepository
.GetByContractingPartyId(institutionContract.ContractingPartyId);
DateTime today = DateTime.Today;
var description = institutionContract.IsInstallment
? "قسط اول سرویس"
: "پرداخت کل سرویس";
var debtorAmount = institutionContract.IsInstallment
? institutionContract.Installments.First().Amount
: institutionContract.TotalAmount;
var financialTransaction = new FinancialTransaction(0, today, today.ToFarsi(),
description, "debt", "بابت خدمات", debtorAmount, 0, 0);
financialStatement.AddFinancialTransaction(financialTransaction);
await _institutionContractRepository.SaveChangesAsync();
await transaction.CommitAsync();
await _institutionContractRepository.SaveChangesAsync();
return op.Succcedded();
}

View File

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

View File

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

View File

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

View File

@@ -1062,116 +1062,5 @@ public class EmployeeRepository : RepositoryBase<long, Employee>, IEmployeeRepos
}
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
#endregion
}

View File

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

View File

@@ -25,7 +25,6 @@ using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using CompanyManagment.App.Contracts.Workshop;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using PersianTools.Core;
using System;
@@ -55,7 +54,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
private readonly IFinancialTransactionRepository _financialTransactionRepository;
private readonly IFinancialStatmentRepository _financialStatmentRepository;
private readonly IHubContext<SendSmsHub> _hubContext;
private readonly ILogger<InstitutionContractRepository> _logger;
private readonly InstitutionContratVerificationParty _firstParty = new()
{
@@ -71,7 +69,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
IWorkshopRepository workshopRepository, IMongoDatabase database,
IPlanPercentageRepository planPercentageRepository, ISmsService smsService,
ISmsResultRepository smsResultRepository, IFinancialTransactionRepository financialTransactionRepository,
IFinancialStatmentRepository financialStatmentRepository, IHubContext<SendSmsHub> hubContext, ILogger<InstitutionContractRepository> logger) : base(context)
IFinancialStatmentRepository financialStatmentRepository, IHubContext<SendSmsHub> hubContext) : base(context)
{
_context = context;
_employerRepository = employerRepository;
@@ -82,7 +80,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
_financialTransactionRepository = financialTransactionRepository;
_financialStatmentRepository = financialStatmentRepository;
_hubContext = hubContext;
_logger = logger;
_institutionExtensionTemp =
database.GetCollection<InstitutionContractExtensionTemp>("InstitutionContractExtensionTemp");
_institutionAmendmentTemp =
@@ -1098,41 +1095,26 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
public async Task<PagedResult<GetInstitutionContractListItemsViewModel>> GetList(
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 nowFa = now.ToFarsi();
var endFa = nowFa.FindeEndOfMonth();
var endThisMontGr = endFa.ToGeorgianDateTime();
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()
var joinedQuery = query.Join(_context.PersonalContractingParties
.Include(x => x.Employers)
.ThenInclude(x => x.WorkshopEmployers)
.ThenInclude(x => x.Workshop),
contract => contract.ContractingPartyId,
contractingParty => contractingParty.id,
(contract, contractingParty) => new { contract, contractingParty });
// var pendingForRenewalContracts = _context.InstitutionContractSet.AsNoTracking()
// .Where(c => c.IsActiveString == "true" &&
// c.ContractEndGr >= now &&
// c.ContractEndGr <= endThisMontGr);
var joinedQuery = rawQuery.Select(x => new
(contract, contractingParty) => new { contract, contractingParty })
.Select(x => new
{
x.contract,
x.contractingParty,
@@ -1153,8 +1135,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
: x.contract.ContractAmount == 0
? (int)InstitutionContractListStatus.Free
: !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.Active
});
@@ -1317,15 +1298,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var list = await orderedQuery.ApplyPagination(searchModel.PageIndex, searchModel.PageSize).ToListAsync();
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)
.Where(x => contractingPartyIds.Contains(x.ContractingPartyId)).ToList();
@@ -1349,19 +1321,13 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var archiveCode = minArchiveCode == 10000000 ? 0 : minArchiveCode;
var status = Enum.Parse<InstitutionContractListStatus>(x.StatusPriority.ToString());
// دریافت WorkshopGroup از dictionary بارگذاری شده
workshopGroups.TryGetValue(x.contract.id, out var workshopGroup);
List<InstitutionContractWorkshopBase> currentStateWorkshops = workshopGroup?.CurrentWorkshops
List<InstitutionContractWorkshopBase> currentStateWorkshops = x.contract.WorkshopGroup?.CurrentWorkshops
.Cast<InstitutionContractWorkshopBase>().ToList();
var statement = financialStatements.FirstOrDefault(f => f.ContractingPartyId == x.contractingParty.id);
if (currentStateWorkshops != null && workshopGroup != null)
{
currentStateWorkshops.AddRange(workshopGroup.InitialWorkshops.Where(w => !w.WorkshopCreated));
}
currentStateWorkshops?.AddRange(
x.contract.WorkshopGroup?.InitialWorkshops.Where(w => !w.WorkshopCreated) ?? []);
var workshopDetails = currentStateWorkshops?.Select(w =>
{
@@ -1391,28 +1357,9 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
var employeesCount = _context.LeftWorkList
.Where(l => workshops.Select(w => w.id).Contains(l.WorkshopId))
.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()
{
ContractAmount = contractAmount,
InstallmentAmount = installmentAmount,
ContractAmount = x.contract.ContractAmountWithTax,
Balance = statement?.FinancialTransactionList.Sum(ft => ft.Deptor - ft.Creditor) ?? 0,
WorkshopsCount = workshops.Count(),
ContractStartFa = x.contract.ContractStartGr.ToFarsi(),
@@ -1430,7 +1377,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
IsExpired = x.contract.ContractEndGr <= endThisMontGr,
ContractingPartyId = x.contractingParty.id,
Workshops = workshopDetails,
IsInPersonContract = workshopGroup?.CurrentWorkshops
IsInPersonContract = x.contract.WorkshopGroup?.CurrentWorkshops
.Any(y => y.Services.ContractInPerson) ?? true,
IsOldContract = x.contract.SigningType == InstitutionContractSigningType.Legacy
};
@@ -1807,7 +1754,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.ThenInclude(x => x.InitialWorkshops)
.Include(x => x.WorkshopGroup)
.ThenInclude(x => x.CurrentWorkshops)
.Include(x=>x.Installments)
.FirstOrDefaultAsync(x => x.id == institutionContractId);
}
@@ -1949,7 +1895,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.FirstOrDefaultAsync(x => x.PublicId == id);
}
public InstitutionContractDiscountResponse CalculateDiscount(InstitutionContractSetDiscountRequest request,string contractStart=null)
public InstitutionContractDiscountResponse CalculateDiscount(InstitutionContractSetDiscountRequest request)
{
var baseAmount = request.TotalAmount;
var discountAmount = (baseAmount * request.DiscountPercentage) / 100;
@@ -2208,10 +2154,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.Include(x => x.WorkshopGroup)
.ThenInclude(institutionContractWorkshopGroup => institutionContractWorkshopGroup.CurrentWorkshops)
.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)
{
throw new BadRequestException("قرارداد مالی قبلی یافت نشد");
@@ -2224,12 +2166,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
);
var workshopIds = prevInstitutionContracts.WorkshopGroup.CurrentWorkshops.Select(x => x.WorkshopId.Value);
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 workshops = await _context.Workshops.Where(x => workshopIds.Contains(x.id)).ToListAsync();
var workshopDetails = prevInstitutionContracts.WorkshopGroup.CurrentWorkshops
.Select(x =>
{
@@ -2271,32 +2208,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
RollCallInPerson = service.RollCallInPerson
};
}).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()
{
TotalAmount = workshopDetails.Sum(x => x.WorkshopServicesAmount).ToMoney(),
@@ -2411,10 +2322,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
{
if (request.DiscountPercentage <= 0)
throw new BadRequestException("مقدار تخفیف نمی‌تواند برابر یا کمتر از صفر باشد");
if (request.DiscountPercentage>=100)
{
throw new BadRequestException("مقدار تخفیف نمی‌تواند برابر یا بیشتر از صد باشد");
}
var institutionTemp = await _institutionExtensionTemp.Find(x => x.Id == request.TempId)
.FirstOrDefaultAsync();
if (institutionTemp == null)
@@ -2432,7 +2339,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (institutionTemp.OneTimePayment.DiscountPercetage > 0)
throw new BadRequestException("تخفیف قبلا برای این قرارداد اعمال شده است");
}
var selectedPlan = institutionTemp.Duration switch
{
InstitutionContractDuration.OneMonth => institutionTemp.OneMonth,
@@ -2449,18 +2356,12 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
IsInstallment = request.IsInstallment,
OneMonthAmount = selectedPlan.OneMonthPaymentDiscounted.MoneyToDouble()
};
var res = CalculateDiscount(calculateRequest,selectedPlan.ContractStart);
var res = CalculateDiscount(calculateRequest);
//این به این دلیل هست که متد caclulate discount یکی از مقادیر رو پر میکنه و ما نیاز داریم هر دو مقدار رو داشته باشیم
if (request.IsInstallment)
{
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()
{
PaymentAmount = onetime.PaymentAmount,
@@ -2469,9 +2370,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
DiscountedAmount = onetime.DiscountedAmount,
DiscountPercetage = onetime.DiscountPercetage,
};
institutionTemp.MonthlyPayment = new()
{
Installments = res.Monthly.Installments,
@@ -2480,10 +2378,8 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
TotalAmount = res.Monthly.TotalAmount,
DiscountedAmount = res.Monthly.DiscountedAmount,
DiscountPercetage = res.Monthly.DiscountPercetage,
TotalAmountWithoutDiscount = institutionTemp.MonthlyPayment.TotalAmount,
OneMonthPaymentWithoutDiscount = selectedPlan.OneMonthPaymentDiscounted,
};
selectedPlan.TotalPayment = res.Monthly.TotalAmount;
selectedPlan.Obligation = res.Monthly.Obligation;
selectedPlan.OneMonthPaymentDiscounted = res.Monthly.OneMonthAmount;
@@ -2492,9 +2388,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
else
{
var monthly = institutionTemp.MonthlyPayment;
institutionTemp.MonthlyPayment.TotalAmountWithoutDiscount = monthly.TotalAmount;
res.Monthly = new()
{
PaymentAmount = monthly.PaymentAmount,
@@ -2504,8 +2397,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
DiscountPercetage = monthly.DiscountPercetage,
Installments = monthly.Installments,
};
institutionTemp.OneTimePayment = new()
{
PaymentAmount = res.OneTime.PaymentAmount,
@@ -2513,8 +2404,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
TotalAmount = res.OneTime.TotalAmount,
DiscountedAmount = res.OneTime.DiscountedAmount,
DiscountPercetage = res.OneTime.DiscountPercetage,
TotalAmountWithoutDiscount = institutionTemp.OneTimePayment.TotalAmount,
OneMonthPaymentWithoutDiscount = selectedPlan.OneMonthPaymentDiscounted,
};
selectedPlan.TotalPayment = res.OneTime.TotalAmount;
selectedPlan.Obligation = res.OneTime.Obligation;
@@ -2573,10 +2462,12 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (request.IsInstallment)
{
var prevMonthlyPayment = institutionTemp.MonthlyPayment;
var resetTotalAmount = prevMonthlyPayment.TotalAmountWithoutDiscount.MoneyToDouble();
var resetTotalAmount = prevMonthlyPayment.TotalAmount.MoneyToDouble() /
(1 - (prevMonthlyPayment.DiscountPercetage / 100.0));
var resetTax = (resetTotalAmount * 0.10);
var paymentAmount = (resetTotalAmount + resetTax);
var newOneMonthAmount = prevMonthlyPayment.OneMonthPaymentWithoutDiscount.MoneyToDouble();
var newOneMonthAmount = selectedPlan.OneMonthPaymentDiscounted.MoneyToDouble() /
(1 - (prevMonthlyPayment.DiscountPercetage / 100));
monthlyPayment = new InstitutionContractDiscountMonthlyViewModel()
{
DiscountPercetage = 0,
@@ -2585,7 +2476,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
Tax = resetTax.ToMoney(),
TotalAmount = resetTotalAmount.ToMoney(),
Installments = InstitutionMonthlyInstallmentCaculation((int)institutionTemp.Duration.Value,
paymentAmount,selectedPlan.ContractStart),
paymentAmount, DateTime.Now.ToFarsi()),
OneMonthAmount = newOneMonthAmount.ToMoney(),
Obligation = resetTotalAmount.ToMoney()
};
@@ -2627,9 +2518,11 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
else
{
var prevOneTimePayment = institutionTemp.OneTimePayment;
var resetTotalAmount = prevOneTimePayment.TotalAmountWithoutDiscount.MoneyToDouble();
var resetTotalAmount = prevOneTimePayment.TotalAmount.MoneyToDouble() /
(1 - (prevOneTimePayment.DiscountPercetage / 100.0));
var resetTax = (resetTotalAmount * 0.10);
var newOneMonthAmount = prevOneTimePayment.OneMonthPaymentWithoutDiscount.MoneyToDouble();
var newOneMonthAmount = selectedPlan.OneMonthPaymentDiscounted.MoneyToDouble() /
(1 - (prevOneTimePayment.DiscountPercetage / 100));
oneTimePayment = new InstitutionContractDiscountOneTimeViewModel()
{
@@ -2648,12 +2541,8 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
TotalAmount = oneTimePayment.TotalAmount,
DiscountedAmount = oneTimePayment.DiscountedAmount,
DiscountPercetage = oneTimePayment.DiscountPercetage,
TotalAmountWithoutDiscount = institutionTemp.OneTimePayment.TotalAmount,
OneMonthPaymentWithoutDiscount = institutionTemp.OneTimePayment.OneMonthPaymentWithoutDiscount
};
selectedPlan.TotalPayment = institutionTemp.HasContractInPerson?
(oneTimePayment.TotalAmount.MoneyToDouble()/(0.9)).ToMoney()
:oneTimePayment.TotalAmount;
selectedPlan.TotalPayment = oneTimePayment.TotalAmount;
selectedPlan.Obligation = oneTimePayment.Obligation;
selectedPlan.OneMonthPaymentDiscounted = oneTimePayment.OneMonthAmount;
selectedPlan.DailyCompenseation = (oneTimePayment.OneMonthAmount.MoneyToDouble() * 0.10).ToMoney();
@@ -2909,6 +2798,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
_context.InstitutionContractContactInfos.Add(contactinfo);
}
}
await SaveChangesAsync();
await _smsService.SendInstitutionCreationVerificationLink(contractingParty.Phone, contractingPartyFullName,
@@ -2919,7 +2809,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
await transaction.CommitAsync();
return opration.Succcedded();
}
#endregion
@@ -3565,7 +3454,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (checkAnyToExecute)
{
//اجرای تسک
_logger.LogInformation("اجرای تسک پیامک های یاد آور SendReminderSmsForBackgroundTask" + persianNow + " - " + hour + ":" + minute);
//دریافت لیست بدهکاران
var smsListData = await GetSmsListData(now, TypeOfSmsSetting.InstitutionContractDebtReminder);
string typeOfSms = "یادآور بدهی ماهانه";
@@ -4340,7 +4229,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
{
string name = item.PartyName.Length > 18 ? item.PartyName.Substring(0, 18) : item.PartyName;
string errMess = $"{name}-خطا";
_logger.LogError(errMess);
await _smsService.Alarm("09114221321", errMess);
}
@@ -4454,7 +4342,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (checkAnyToExecute)
{
//اجرای تسک
_logger.LogInformation("اجرای تسک ارسال یاد آور تایید قراداد مالی SendInstitutionContractConfirmSms" + persianNow + " - " + hour + ":" + minute);
//دریافت لیست قراداد های تایید نشده
var fromAmonthAgo = now.AddDays(-30);
var pendingContracts = await _context.InstitutionContractSet
@@ -4474,10 +4362,8 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
string typeOfSms = "یادآور تایید قرارداد مالی";
foreach (var item in pendingContracts)
{
var sendResult = await _smsService.SendInstitutionCreationVerificationLink(item.Number, item.FullName,
item.InstitutionId, item.ContractingPartyId, item.InstitutionContractId, typeOfSms);
Thread.Sleep(1000);
}
Console.WriteLine("executed at : " + persianNow + " - " + hour + ":" + minute);
@@ -4529,13 +4415,12 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
TypeOfContract = x.TypeOfContract,
IsInstallment = x.IsInstallment,
VerificationStatus = x.VerificationStatus,
SigningType = x.SigningType,
InstallmentList = x.Installments
.Select(ins => new InstitutionContractInstallmentViewModel
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
.OrderBy(ins => ins.InstallmentDateGr).Skip(1).ToList(),
}).Where(x =>
x.ContractStartGr < endOfMonthGr && x.ContractEndGr >= endOfMonthGr && x.ContractAmountDouble > 0 && x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify)
x.ContractStartGr < endOfMonthGr && x.ContractEndGr >= endOfMonthGr && x.ContractAmountDouble > 0)
.ToListAsync();
#endregion
@@ -4553,13 +4438,13 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
#region GetDectivedContractOnCurrentMonth
if (futureContracts.Any())
{
List<long> futureContractIds = futureContracts.Select(x => x.ContractingPartyId).ToList();
List<InstitutionContractViewModel> deatcivedContract = await _context.InstitutionContractSet
.Where(x => x.IsActiveString == "false" && futureContractIds.Contains(x.ContractingPartyId) &&
x.ContractEndGr.Date == endOfCurrentMonth.Date && x.ContractAmount > 0 && x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify)
x.ContractEndGr.Date == endOfCurrentMonth.Date && x.ContractAmount > 0)
.Select(x => new InstitutionContractViewModel
{
Id = x.id,
@@ -4574,7 +4459,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
TypeOfContract = x.TypeOfContract,
IsInstallment = x.IsInstallment,
VerificationStatus = x.VerificationStatus,
SigningType = x.SigningType,
InstallmentList = x.Installments
.Select(ins => new InstitutionContractInstallmentViewModel
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
@@ -4585,12 +4469,6 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
institutionContracts.AddRange(deatcivedContract);
}
// قرارداد هایی که پطور یکجا پرداخت شده اند
var paidInFull = institutionContracts.Where(x =>
x.SigningType != InstitutionContractSigningType.Legacy && x.IsInstallment == false && x.SigningType != null).ToList();
//حذف قراداد هایی که یکجا پرداخت شده اند از لیست ایجاد سند ماهانه
institutionContracts = institutionContracts.Except(paidInFull).ToList();
#region RollCallServicCompute
@@ -4638,7 +4516,8 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
if (!alreadyCreated)
{
if (item.IsInstallment)
if (item.IsInstallment &&
item.VerificationStatus == InstitutionContractVerificationStatus.Verified)
{
var instalment = item.InstallmentList
.FirstOrDefault(x =>
@@ -4672,7 +4551,8 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
await _financialStatmentRepository.SaveChangesAsync();
if (item.IsInstallment)
if (item.IsInstallment &&
item.VerificationStatus == InstitutionContractVerificationStatus.Verified)
{
var instalment = item.InstallmentList
.FirstOrDefault(x =>
@@ -4699,17 +4579,12 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
#region RollCallServicCompute
//ایجاد سند مالی حضورغیاب
//قرارداد هایی که جدید نیستند و اقساط ندارند
//کارگاه های استثناء : کباب مهدی 30520 و نمونه پروتئین 30739
if (item.SigningType != InstitutionContractSigningType.OtpBased && item.SigningType != InstitutionContractSigningType.Physical
&& !item.IsInstallment && item.ContractingPartyId != 30520 && item.ContractingPartyId != 30739)
if (item.VerificationStatus != InstitutionContractVerificationStatus.Verified &&
!item.IsInstallment && item.ContractingPartyId != 30520 && item.ContractingPartyId != 30739)
{
try
{
//TODO
//@refactor Need
var employers = await _context.Employers
.Where(x => x.ContractingPartyId == item.ContractingPartyId)
.Select(x => x.id).ToListAsync();
@@ -4883,20 +4758,7 @@ public class InstitutionContractRepository : RepositoryBase<long, InstitutionCon
.Where(x => x.Installments.Any(i => i.Id == installmentId))
.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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,4 @@
using GozareshgirProgramManager.Domain.ProjectAgg.Entities;
using GozareshgirProgramManager.Domain.ProjectAgg.Enums;
using GozareshgirProgramManager.Domain.ProjectAgg.Repositories;
using GozareshgirProgramManager.Infrastructure.Persistence._Common;
using GozareshgirProgramManager.Infrastructure.Persistence.Context;
@@ -36,13 +35,4 @@ public class TaskSectionRepository:RepositoryBase<Guid,TaskSection>,ITaskSection
.Where(x => x.CurrentAssignedUserId == userId)
.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,7 +1,6 @@
using System.Runtime.InteropServices;
using GozareshgirProgramManager.Application._Common.Models;
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.CreateProject;
using GozareshgirProgramManager.Application.Modules.Projects.Commands.DeleteProject;
@@ -99,9 +98,6 @@ public class ProjectController : ProgramManagerBaseController
[HttpGet("board")]
public async Task<ActionResult<OperationResult<List<ProjectBoardListResponse>>>> GetProjectBoard([FromQuery] ProjectBoardListQuery query)
{
// اجرای Command برای متوقف کردن تسک‌های overtime قبل از نمایش
await _mediator.Send(new AutoStopOverTimeTaskSectionsCommand());
var res = await _mediator.Send(query);
return res;
}

View File

@@ -1,63 +0,0 @@
using _0_Framework.Application;
using AccountManagement.Application.Contracts.Ticket;
using CompanyManagment.App.Contracts.InstitutionPlan;
using CompanyManagment.App.Contracts.Workshop;
using Microsoft.AspNetCore.Mvc;
using ServiceHost.BaseControllers;
namespace ServiceHost.Areas.Admin.Controllers;
public class ServiceAmountsManagement : AdminBaseController
{
private readonly IInstitutionPlanApplication _institutionPlanApplication;
private readonly IAuthHelper _authHelper;
public ServiceAmountsManagement(IInstitutionPlanApplication institutionPlanApplication, IAuthHelper authHelper)
{
_institutionPlanApplication = institutionPlanApplication;
_authHelper = authHelper;
}
/// <summary>
/// دریافت دیتای مودال ایجاد
/// </summary>
/// <returns></returns>
[HttpGet("GetCreateModalData")]
public async Task<ActionResult<CreateServiceAmountDto>> GetCreateModalData()
{
if(!_authHelper.HasPermission(315))
return Forbid();
var data = await _institutionPlanApplication.GetCreateModalData();
return data;
}
/// <summary>
/// ذخیره درصدها
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HttpPost("CreateServicePercentage")]
public async Task<ActionResult<OperationResult>> CreateServicePercentage([FromBody] CreateServiceAmountDto command)
{
if (!_authHelper.HasPermission(315))
return Forbid();
var result = await _institutionPlanApplication.CreateInstitutionPlanPercentage(command);
return result;
}
/// <summary>
/// دریافت لیست مبالغ سرویس ها
/// </summary>
/// <param name="searchModel"></param>
/// <returns></returns>
[HttpGet("GetList")]
public async Task<ActionResult<PagedResult<InstitutionPlanListDto>>> GetList(InstitutionPlanSearchModel searchModel)
{
return await _institutionPlanApplication.GetList(searchModel);
}
}

View File

@@ -809,7 +809,7 @@ public class institutionContractController : AdminBaseController
}
[HttpPost("mannual-verify/{id}")]
public async Task<ActionResult<OperationResult>> VerifyInstitutionContractManually(long id)
public async Task<ActionResult<OperationResult>> VerifyInstitutionContractMannualy(long id)
{
var res= await _institutionContractApplication.VerifyInstitutionContractManually(id);
return res;

View File

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

View File

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

View File

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

View File

@@ -34,6 +34,7 @@ using System.Net.Http;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Text.Json.Serialization;
using CompanyManagement.Infrastructure.Excel.Checkout;
using Microsoft.AspNetCore.Authentication;
using static ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk.IndexModel2;
@@ -52,7 +53,6 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
private readonly IOnlinePayment _onlinePayment;
private readonly IFaceEmbeddingService _faceEmbeddingService;
private readonly IAuthHelper _authHelper;
private readonly IInstitutionContractApplication _institutionContractApplication;
[BindProperty] public IFormFile File { get; set; }
@@ -78,8 +78,7 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
public IndexModel(IAndroidApkVersionApplication application, IRollCallDomainService rollCallDomainService,
CompanyContext context, AccountContext accountContext, IHttpClientFactory httpClientFactory,
IOptions<AppSettingConfiguration> appSetting,
ITemporaryClientRegistrationApplication clientRegistrationApplication, IOnlinePayment onlinePayment,
IFaceEmbeddingService faceEmbeddingService, IAuthHelper authHelper, IInstitutionContractApplication institutionContractApplication)
ITemporaryClientRegistrationApplication clientRegistrationApplication, IOnlinePayment onlinePayment, IFaceEmbeddingService faceEmbeddingService, IAuthHelper authHelper)
{
_application = application;
_rollCallDomainService = rollCallDomainService;
@@ -90,7 +89,6 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
_onlinePayment = onlinePayment;
_faceEmbeddingService = faceEmbeddingService;
_authHelper = authHelper;
_institutionContractApplication = institutionContractApplication;
_paymentGateway = new SepehrPaymentGateway(httpClientFactory);
}
@@ -156,59 +154,36 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
//await UpdateInstitutionContract();
//await UpdateFaceEmbeddingNames();
//await SetInstitutionContractSigningType();
await ReActivateInstitution();
var bytes= GetYektaCheckout();
return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"YektaCheckout.xlsx");
ViewData["message"] = "تومام یک";
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()
{
var query = _context.InstitutionContractSet
.Where(x => x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify);
var otpSigned = query.Where(x => x.VerifierFullName != null && x.LawId != 0).ToList();
.Where(x=>x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify);
var otpSigned = query.Where(x=>x.VerifierFullName != null && x.LawId != 0).ToList();
foreach (var institutionContract in otpSigned)
{
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)
{
institutionContract.SetSigningType(InstitutionContractSigningType.Legacy);
}
await _context.SaveChangesAsync();
}
public async Task<IActionResult> OnPostShiftDateNew2()
@@ -358,51 +333,30 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
//TranslateCode(result?.ErrorCode);
return Page();
}
[DisableConcurrentExecution(timeoutInSeconds: 120)]
public async Task<IActionResult> OnPostUploadFrontEnd(CancellationToken cancellationToken)
{
var validAccountId = _authHelper.CurrentAccountId();
if (validAccountId == 2 || validAccountId == 322)
{
//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 batPath = @"C:\next-ui\deploy-next-ui.bat";
var psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c schtasks /run /tn \"DeployNextUI\"",
UseShellExecute = false,
CreateNoWindow = true
FileName = batPath,
UseShellExecute = true, // خیلی مهم
Verb = "runas", // اجرای Administrator
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
};
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 شروع شد. لاگ را بررسی کنید.";
return RedirectToPage();
}
return Forbid();
}
/// <summary>
@@ -428,10 +382,13 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
{
contractingPartyIdList.Add(employer.Employer.ContractingPartyId);
}
}
if (contractingPartyIdList.Count > 0)
{
if (contractingPartyIdList.Count == 1)
{
workshop.AddContractingPartyId(contractingPartyIdList[0]);
@@ -452,6 +409,7 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
ViewData["message"] = "آی دی های طرف حساب اضافه شد";
return Page();
}
/// <summary>
@@ -470,8 +428,8 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
var content = System.IO.File.ReadAllText(logPath, Encoding.UTF8);
return Content(content);
}
return Content("شما مجاز به دیدن لاگ نیستید");
}
@@ -1084,7 +1042,7 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
x.PersonnelCount,
x.Price, x.InstitutionContractWorkshopGroupId,
group,
x.WorkshopId.Value, x.id);
x.WorkshopId.Value,x.id);
entity.SetEmployers(x.Employers.Select(e => e.EmployerId).ToList());
return entity;
@@ -1160,6 +1118,22 @@ namespace ServiceHost.Areas.AdminNew.Pages.Company.AndroidApk
}
#endregion
private byte[] GetYektaCheckout()
{
var checkouts = _context.CheckoutSet
.Where(x => x.WorkshopId == 595
&& x.Month == "آذر" && x.Year == "1404").Select(x=>new YektaTejaratCheckoutViewModel()
{
AttendancePayableAmount = "0",
FullName = x.EmployeeFullName,
NationalCode = x.NationalCode,
StaticPayableAmount = x.TotalPayment.ToMoney()
}).ToList();
var bytes = YektaTejaratCheckout.GenerateYektaTejaratCheckoutExcel(checkouts);
return bytes;
}
}
public class IndexModel2 : PageModel

View File

@@ -1,25 +0,0 @@
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 async Task<IActionResult> OnPostReCalculateValues(List<ReCalculateRollCallValues> command)
public IActionResult OnPostReCalculateValues(List<ReCalculateRollCallValues> command)
{
var result =await _rollCallApplication.RecalculateValues(_workshopId, command);
var result = _rollCallApplication.RecalculateValues(_workshopId, command);
return new JsonResult(new
{

View File

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