diff --git a/0_Framework/Application/AuthHelper.cs b/0_Framework/Application/AuthHelper.cs index bb94f1b2..f0af9a47 100644 --- a/0_Framework/Application/AuthHelper.cs +++ b/0_Framework/Application/AuthHelper.cs @@ -150,8 +150,8 @@ public class AuthHelper : IAuthHelper { #region MahanChanges - if (account.Id == 322) - account.Permissions.AddRange([3060301, 30603, 30604, 30605]); + //if (account.Id == 322) + // account.Permissions.AddRange([3060301, 30603, 30604, 30605]); var permissions = account.Permissions is { Count: > 0 } ? Tools.SerializeToBson(account.Permissions) : ""; diff --git a/CompanyManagment.Application/InsuranceListApplication.cs b/CompanyManagment.Application/InsuranceListApplication.cs index 95d3f118..e1a5bc4d 100644 --- a/CompanyManagment.Application/InsuranceListApplication.cs +++ b/CompanyManagment.Application/InsuranceListApplication.cs @@ -35,7 +35,7 @@ using MD.PersianDateTime.Standard; namespace CompanyManagment.Application; -public class InsuranceListApplication: IInsuranceListApplication +public class InsuranceListApplication : IInsuranceListApplication { //private readonly ITransactionManager _transactionManager; @@ -58,10 +58,10 @@ public class InsuranceListApplication: IInsuranceListApplication private readonly IInsuranceYearlySalaryApplication _insuranceYearlySalaryApplication; private readonly ICheckoutRepository _checkoutRepository; - public InsuranceListApplication( IInsuranceListRepository insuranceListRepositpry, IEmployeeInsurancListDataRepository employeeInsurancListDataRepository, IInsuranceEmployeeInfoRepository insuranceEmployeeInfoRepository, IEmployeeRepository employeeRepository, IWorkshopRepository workShopRepository, ILeftWorkInsuranceApplication leftWorkInsuranceApplication, IInsuranceEmployeeInfoApplication insuranceEmployeeInfoApplication, IEmployeeInsurancListDataApplication employeeInsurancListDataApplication, IYearlySalaryApplication yearlySalaryApplication,IYearlySalaryItemApplication yearlySalaryItemApplication ,IInsuranceWorkshopInfoRepository insuranceWorkshopInfoRepository,IInsuranceJobItemRepositpry insuranceJobItemRepository, IDateSalaryRepository dateSalaryRepository, IDateSalaryItemRepository dateSalaryItemRepository, IPersonalContractingPartyApp contractingPartyApp, ILeftWorkInsuranceRepository leftWorkInsuranceRepository, IInsuranceYearlySalaryApplication insuranceYearlySalaryApplication, ICheckoutRepository checkoutRepository) + public InsuranceListApplication(IInsuranceListRepository insuranceListRepositpry, IEmployeeInsurancListDataRepository employeeInsurancListDataRepository, IInsuranceEmployeeInfoRepository insuranceEmployeeInfoRepository, IEmployeeRepository employeeRepository, IWorkshopRepository workShopRepository, ILeftWorkInsuranceApplication leftWorkInsuranceApplication, IInsuranceEmployeeInfoApplication insuranceEmployeeInfoApplication, IEmployeeInsurancListDataApplication employeeInsurancListDataApplication, IYearlySalaryApplication yearlySalaryApplication, IYearlySalaryItemApplication yearlySalaryItemApplication, IInsuranceWorkshopInfoRepository insuranceWorkshopInfoRepository, IInsuranceJobItemRepositpry insuranceJobItemRepository, IDateSalaryRepository dateSalaryRepository, IDateSalaryItemRepository dateSalaryItemRepository, IPersonalContractingPartyApp contractingPartyApp, ILeftWorkInsuranceRepository leftWorkInsuranceRepository, IInsuranceYearlySalaryApplication insuranceYearlySalaryApplication, ICheckoutRepository checkoutRepository) { // _transactionManager = transactionManager; - + _insuranceListRepositpry = insuranceListRepositpry; _employeeInsurancListDataRepository = employeeInsurancListDataRepository; _insuranceEmployeeInfoRepository = insuranceEmployeeInfoRepository; @@ -84,17 +84,17 @@ public class InsuranceListApplication: IInsuranceListApplication public OperationResult Create(CreateInsuranceList command) { - + var operation = new OperationResult(); - if (command.WorkshopId==0 ) + if (command.WorkshopId == 0) { return operation.Failed(" انتخاب کارگاه اجباری می باشد "); } - if ( command.Month == "0" ) + if (command.Month == "0") { return operation.Failed(" انتخاب ماه اجباری می باشد "); } - if ( command.Year == "0") + if (command.Year == "0") { return operation.Failed("انتخاب سال اجباری می باشد "); } @@ -171,7 +171,7 @@ public class InsuranceListApplication: IInsuranceListApplication public OperationResult Edit(EditInsuranceList command) { - + var operation = new OperationResult(); if (command.WorkshopId == 0) { @@ -185,7 +185,7 @@ public class InsuranceListApplication: IInsuranceListApplication { return operation.Failed("انتخاب سال اجباری می باشد "); } - else if (_insuranceListRepositpry.Exists(x =>x.id!=command.Id && x.WorkshopId == command.WorkshopId && x.Month == command.Month && x.Year == command.Year)) + else if (_insuranceListRepositpry.Exists(x => x.id != command.Id && x.WorkshopId == command.WorkshopId && x.Month == command.Month && x.Year == command.Year)) { return operation.Failed(" لیست بیمه برای کارگاه، سال و ماه انتخاب شده قبلا ایجاد شده است "); } @@ -211,7 +211,7 @@ public class InsuranceListApplication: IInsuranceListApplication createInsuranceEmployeeInfo.Gender = item.Gender; createInsuranceEmployeeInfo.InsuranceCode = item.InsuranceCode; createInsuranceEmployeeInfo.DateOfBirthGr = item.DateOfBirth.ToGeorgianDateTime(); - createInsuranceEmployeeInfo.DateOfIssueGr =!string.IsNullOrEmpty(item.DateOfIssue)? item.DateOfIssue.ToGeorgianDateTime(): "1300/10/11".ToGeorgianDateTime(); + createInsuranceEmployeeInfo.DateOfIssueGr = !string.IsNullOrEmpty(item.DateOfIssue) ? item.DateOfIssue.ToGeorgianDateTime() : "1300/10/11".ToGeorgianDateTime(); _insuranceEmployeeInfoApplication.Create(createInsuranceEmployeeInfo); } else @@ -266,8 +266,8 @@ public class InsuranceListApplication: IInsuranceListApplication return operation; } - - } + + } public EditInsuranceList GetDetails(long id) { @@ -302,8 +302,8 @@ public class InsuranceListApplication: IInsuranceListApplication foreach (var item in insuranceListDetails.EmployeeDetailsForInsuranceList) { - - item.IncludeStatus = _leftWorkInsuranceApplication.GetLeftPersonelByWorkshopIdAndEmployeeId(insuranceListDetails.WorkshopId,item.EmployeeId).IncludeStatus; + + item.IncludeStatus = _leftWorkInsuranceApplication.GetLeftPersonelByWorkshopIdAndEmployeeId(insuranceListDetails.WorkshopId, item.EmployeeId).IncludeStatus; if (!string.IsNullOrEmpty(item.LeftWorkDate)) { var yearEndDateUser = Convert.ToInt32(item.LeftWorkDate.Substring(0, 4)); @@ -348,7 +348,7 @@ public class InsuranceListApplication: IInsuranceListApplication return insuranceListDetails; } - public List Search(InsuranceListSearchModel searchModel) + public List Search(InsuranceListSearchModel searchModel) { return _insuranceListRepositpry.OptimizedSearch(searchModel); //var result = _insuranceListRepositpry.Search(searchModel); @@ -380,10 +380,10 @@ public class InsuranceListApplication: IInsuranceListApplication /// /// /// - public MainEmployeeDetailsViewModel SearchEmployeeForCreateInsuranceList( EmployeeForCreateInsuranceListSearchModel searchModel) + public MainEmployeeDetailsViewModel SearchEmployeeForCreateInsuranceList(EmployeeForCreateInsuranceListSearchModel searchModel) { - var watch = new Stopwatch(); - + var watch = new Stopwatch(); + var result = new MainEmployeeDetailsViewModel(); var workshopId = searchModel.WorkshopIds.FirstOrDefault(); var workshop = _workShopRepository.GetDetails(workshopId); @@ -392,30 +392,30 @@ public class InsuranceListApplication: IInsuranceListApplication double monthlybaseYear = 0; // اگر در این سال و ماه برای این کارگاه لیست بیمه ایجاد نشده بود if (!_insuranceListRepositpry.Exists(x => - x.Year == searchModel.Year && x.Month == searchModel.Month && - searchModel.WorkshopIds.Contains(x.WorkshopId))) + x.Year == searchModel.Year && x.Month == searchModel.Month && + searchModel.WorkshopIds.Contains(x.WorkshopId))) { var startMonthFa = $"{searchModel.Year}/{searchModel.Month.PadLeft(2, '0')}/01"; DateTime startDateGr = startMonthFa.ToGeorgianDateTime(); - DateTime endDateGr = startMonthFa.FindeEndOfMonth() - .ToGeorgianDateTime(); + DateTime endDateGr = startMonthFa.FindeEndOfMonth() + .ToGeorgianDateTime(); int endOfMonth = Convert.ToInt32((startMonthFa.FindeEndOfMonth()).Substring(8, 2)); - - //مقادیر سالانه این تاریخ - var yearlysaleries = _yearlySalaryApplication.GetInsuranceItems(startDateGr, endDateGr, searchModel.Year); + + //مقادیر سالانه این تاریخ + var yearlysaleries = _yearlySalaryApplication.GetInsuranceItems(startDateGr, endDateGr, searchModel.Year); - // دریافت اطلاعات هویتی و شروع و ترک کار کارکنان - var employeesInfoAndLeftWorks = - _leftWorkInsuranceApplication.GetEmployeeInsuranceLeftWorksAndInformation(workshopId, startDateGr, - endDateGr); + // دریافت اطلاعات هویتی و شروع و ترک کار کارکنان + var employeesInfoAndLeftWorks = + _leftWorkInsuranceApplication.GetEmployeeInsuranceLeftWorksAndInformation(workshopId, startDateGr, + endDateGr); var employeeInsurancDataPreviusList = _insuranceListRepositpry.GetEmployeeInsuranceDataAmonthAgo(startDateGr, workshopId); - watch.Start(); - var computeResult = employeesInfoAndLeftWorks.Select(employee => + watch.Start(); + var computeResult = employeesInfoAndLeftWorks.Select(employee => { var dateOfBirth = employee.DateOfBirthGr.ToFarsi(); var dateOfIssue = employee.DateOfIssueGr.ToFarsi(); @@ -426,7 +426,7 @@ public class InsuranceListApplication: IInsuranceListApplication //آیا در کارگاه تیک محاسبه اضافه کار یا حق اولاد زده شده است؟ bool hasWorkshopOverTimeOrFamilyAllowance = workshop.InsuranceCheckoutFamilyAllowance || workshop.InsuranceCheckoutOvertime; - + //آیا پرسنل فیش حقوق دارد //این مورد زمانی چک می شود که تیک محاسبه در کارگاه زده شده باشد // در غیر اینصورت بصورت پیشفرض دارای فیش حقوق در نظر گرفته می شود @@ -439,21 +439,24 @@ public class InsuranceListApplication: IInsuranceListApplication searchModel.Year, searchModel.Month); if (checkout.hasChekout) { - + familyAllowance = checkout.FamilyAlloance; overTimePay = checkout.OverTimePay; - + } else { + //چون کارفرما فیش حقوقی ندارد + //ولی در لیست بیمه حضور دارد + //برای جلوگیری از هشدار فرانت کارفرما را داری فیش حقوقی فرض میکنیم employeeHasCheckout = isManager == false ? false : true; } } - - var workingDays = Tools.GetEmployeeInsuranceWorkingDays(employee.StartWorkDateGr, leftDate, startDateGr,endDateGr, employee.EmployeeId); - var leftWorkFa = workingDays.hasLeftWorkInMonth ? employee.LeftWorkDateGr.ToFarsi(): ""; + + var workingDays = Tools.GetEmployeeInsuranceWorkingDays(employee.StartWorkDateGr, leftDate, startDateGr, endDateGr, employee.EmployeeId); + var leftWorkFa = workingDays.hasLeftWorkInMonth ? employee.LeftWorkDateGr.ToFarsi() : ""; var startWorkFa = employee.StartWorkDateGr.ToFarsi(); //به دست آوردن دستمزد روزانه با توجه به اینکه کارگاه مشاغل مقطوع است یا خیر @@ -463,34 +466,34 @@ public class InsuranceListApplication: IInsuranceListApplication var res = GetDailyWageFixedSalary(searchModel.Year, workshopId, employee.EmployeeId, startDateGr, endDateGr, employee.JobId, searchModel.Population, searchModel.InsuranceJobId); dailyWage = res ?? 0; - + } else { var res = ComputeDailyWage(yearlysaleries.DayliWage, employee.EmployeeId, workshopId, searchModel.Year); dailyWage = res; } - - + + //بدست آوردن پایه سنوات var baseYears = _insuranceListRepositpry.GetEmployeeInsuranceBaseYear(employee.EmployeeId, workshopId, - workingDays.countWorkingDays, startDateGr, endDateGr,workingDays.startWork, workingDays.endWork, workingDays.hasLeftWorkInMonth); + workingDays.countWorkingDays, startDateGr, endDateGr, workingDays.startWork, workingDays.endWork, workingDays.hasLeftWorkInMonth); //آیا کارفرما یا مدیر عامل است؟ - - baseYears.baseYear = isManager ? 0 : baseYears.baseYear; - Console.WriteLine(employee.JobId + " - "+ baseYears.baseYear); - //جمع مزد روزانه و پایه سنوات - var dailyWagePlusBaseYears = dailyWage + baseYears.baseYear; - - //دستمزد ماهانه با محاسبه پایه سنوات + baseYears.baseYear = isManager ? 0 : baseYears.baseYear; + Console.WriteLine(employee.JobId + " - " + baseYears.baseYear); + //جمع مزد روزانه و پایه سنوات + var dailyWagePlusBaseYears = dailyWage + baseYears.baseYear; + + + //دستمزد ماهانه با محاسبه پایه سنوات var monthlySalary = GetRoundValue(dailyWagePlusBaseYears * workingDays.countWorkingDays); //حق تاهل var marriedAllowance = employee.MaritalStatus == "متاهل" && !isManager ? yearlysaleries.MarriedAllowance : 0; //محاسبه مزایای ماهانه - var monthlyBenefits = GetMonthlyBenefits(endOfMonth, yearlysaleries.ConsumableItems, yearlysaleries.HousingAllowance, marriedAllowance, workingDays.countWorkingDays, searchModel.TypeOfInsuranceSendWorkshop, employee.JobId, employee.EmployeeId,employee.IncludeStatus); + var monthlyBenefits = GetMonthlyBenefits(endOfMonth, yearlysaleries.ConsumableItems, yearlysaleries.HousingAllowance, marriedAllowance, workingDays.countWorkingDays, searchModel.TypeOfInsuranceSendWorkshop, employee.JobId, employee.EmployeeId, employee.IncludeStatus); //if (employee.EmployeeId is 7999)// سید عباس خوشکلام سلیمان // monthlyBenefits = 80869389; @@ -501,7 +504,7 @@ public class InsuranceListApplication: IInsuranceListApplication monthlyBenefits = GetRoundValue(monthlyBenefits += overTimePay); } - + //سرای ملک // نوشین خالی // 39692467 @@ -509,13 +512,13 @@ public class InsuranceListApplication: IInsuranceListApplication // monthlyBenefits += 39692467; var marriedAllowanceCompute = MarriedAllowance(employee.MaritalStatus, employee.JobId, employee.IncludeStatus, - workingDays.countWorkingDays, yearlysaleries.MarriedAllowance, endOfMonth); - //محاسبه جمع مزایای مشمول و دستمزد ماهانه - var benefitsIncludedContinuous = monthlyBenefits + monthlySalary; + workingDays.countWorkingDays, yearlysaleries.MarriedAllowance, endOfMonth); + //محاسبه جمع مزایای مشمول و دستمزد ماهانه + var benefitsIncludedContinuous = monthlyBenefits + monthlySalary; - //benefitsIncludedContinuous = employee.JobId != 16 ? benefitsIncludedContinuous : 0; - //محاسبه حق بیمه سهم بیمه شده - var insuranceShare = (benefitsIncludedContinuous * 7) / 100; + //benefitsIncludedContinuous = employee.JobId != 16 ? benefitsIncludedContinuous : 0; + //محاسبه حق بیمه سهم بیمه شده + var insuranceShare = (benefitsIncludedContinuous * 7) / 100; //محاسبه حق بیمه سهم کارفرما var employerShare = (benefitsIncludedContinuous * 20) / 100; @@ -535,30 +538,30 @@ public class InsuranceListApplication: IInsuranceListApplication benefitsIncludedNonContinuous = GetRoundValue(benefitsIncludedNonContinuous + familyAllowance); } - - + + var includedAndNotIncluded = benefitsIncludedContinuous + benefitsIncludedNonContinuous; return new EmployeeDetailsForInsuranceListViewModel - { - #region EmployeeInfo + { + #region EmployeeInfo EmployeeHasCheckout = employeeHasCheckout, InsuranceEmployeeInformationId = employee.InsuranceEmployeeInformationId, - EmployeeId = employee.EmployeeId, - FName = employee.FName, - LName = employee.LName, - FatherName = employee.FatherName, - DateOfBirth = dateOfBirth == "1300/10/11" ? "" : dateOfBirth, - DateOfIssue = dateOfIssue, - DateOfBirthGr = employee.DateOfBirthGr, - DateOfIssueGr = employee.DateOfIssueGr, - PlaceOfIssue = employee.PlaceOfIssue, - IdNumber = employee.IdNumber, - Gender = employee.Gender, - NationalCode = employee.NationalCode, - Nationality = employee.Nationality, - InsuranceCode = employee.InsuranceCode, + EmployeeId = employee.EmployeeId, + FName = employee.FName, + LName = employee.LName, + FatherName = employee.FatherName, + DateOfBirth = dateOfBirth == "1300/10/11" ? "" : dateOfBirth, + DateOfIssue = dateOfIssue, + DateOfBirthGr = employee.DateOfBirthGr, + DateOfIssueGr = employee.DateOfIssueGr, + PlaceOfIssue = employee.PlaceOfIssue, + IdNumber = employee.IdNumber, + Gender = employee.Gender, + NationalCode = employee.NationalCode, + Nationality = employee.Nationality, + InsuranceCode = employee.InsuranceCode, // آیا وضعیت تاهل پرسنل ست شده است IsMaritalStatusSet = !string.IsNullOrWhiteSpace(employee.MaritalStatus), MaritalStatus = employee.MaritalStatus, @@ -582,7 +585,7 @@ public class InsuranceListApplication: IInsuranceListApplication IncludeStatus = employee.IncludeStatus, //دستمزد روزانه - DailyWage = GetRoundValue(dailyWage), + DailyWage = GetRoundValue(dailyWage), DailyWageStr = dailyWage.ToMoney(), HasConfilictJobs = dailyWage == 0, @@ -598,13 +601,13 @@ public class InsuranceListApplication: IInsuranceListApplication //دستمزد ماهانه MonthlySalary = monthlySalary, - - + + //مزایای ماهانه MonthlyBenefits = monthlyBenefits, - //جمع مزایای مشمول و دستمزد ماهانه - BenefitsIncludedContinuous = benefitsIncludedContinuous, + //جمع مزایای مشمول و دستمزد ماهانه + BenefitsIncludedContinuous = benefitsIncludedContinuous, //مزایای غیر مشمول * BenefitsIncludedNonContinuous = benefitsIncludedNonContinuous, @@ -636,9 +639,9 @@ public class InsuranceListApplication: IInsuranceListApplication }; - }).ToList(); + }).ToList(); Console.WriteLine("New Compute : " + watch.Elapsed); - watch.Stop(); + watch.Stop(); watch.Start(); @@ -951,28 +954,28 @@ public class InsuranceListApplication: IInsuranceListApplication result.IsExist = true; result.IsBlock = isBolock; } - + return result; } - public double MarriedAllowance(string maritalStatus,long jobId, bool includedStatus, - int countWorkingDays, double marriedAlowance,int endMonthCurrentDay) + public double MarriedAllowance(string maritalStatus, long jobId, bool includedStatus, + int countWorkingDays, double marriedAlowance, int endMonthCurrentDay) { - bool isManager = jobId is 10 or 16 or 17 or 18 or 3498; - if (isManager)//اگر مدیر عامل بود - return 0; - if (maritalStatus != "متاهل")//اگر مجرد بود - return 0; - - if(countWorkingDays == endMonthCurrentDay) - return (marriedAlowance); + bool isManager = jobId is 10 or 16 or 17 or 18 or 3498; + if (isManager)//اگر مدیر عامل بود + return 0; + if (maritalStatus != "متاهل")//اگر مجرد بود + return 0; + + if (countWorkingDays == endMonthCurrentDay) + return (marriedAlowance); return endMonthCurrentDay switch { - 29 => GetRoundValue((marriedAlowance / 29) * countWorkingDays), - 30 => GetRoundValue((marriedAlowance / 30) * countWorkingDays), - 31 => GetRoundValue((marriedAlowance / 31) * countWorkingDays), - _ => marriedAlowance + 29 => GetRoundValue((marriedAlowance / 29) * countWorkingDays), + 30 => GetRoundValue((marriedAlowance / 30) * countWorkingDays), + 31 => GetRoundValue((marriedAlowance / 31) * countWorkingDays), + _ => marriedAlowance }; } @@ -1147,9 +1150,9 @@ public class InsuranceListApplication: IInsuranceListApplication string strValue = value.ToString(); if (strValue.IndexOf('.') > -1) { - - string a = strValue.Substring(strValue.IndexOf('.')+1, 1); + + string a = strValue.Substring(strValue.IndexOf('.') + 1, 1); if (int.Parse(a) > 5) { return (Math.Round(value, MidpointRounding.ToPositiveInfinity)); @@ -1166,13 +1169,13 @@ public class InsuranceListApplication: IInsuranceListApplication //محاسبه پرسنل در جدول - DSKWOR EDIT public MainEmployeeDetailsViewModel SearchEmployeeListForEditByInsuranceListId(EmployeeForEditInsuranceListSearchModel searchModel) { - var mainEmployeeDetailsViewModel= new MainEmployeeDetailsViewModel(); - var mainEmployeeDetailsViewModel2= new MainEmployeeDetailsViewModel(); - var mainEmployeeDetailsViewModelForNewPersonel= new MainEmployeeDetailsViewModel(); + var mainEmployeeDetailsViewModel = new MainEmployeeDetailsViewModel(); + var mainEmployeeDetailsViewModel2 = new MainEmployeeDetailsViewModel(); + var mainEmployeeDetailsViewModelForNewPersonel = new MainEmployeeDetailsViewModel(); - List ids = searchModel.WorkshopIds.Where(x=>x!=searchModel.WorkshopId).ToList(); + List ids = searchModel.WorkshopIds.Where(x => x != searchModel.WorkshopId).ToList(); searchModel.Month = searchModel.Month.PadLeft(2, '0'); - if (!_insuranceListRepositpry.Exists(x => x.Year == searchModel.Year && x.Month == searchModel.Month && (ids!=null && ids.Count > 0 && ids.Contains(x.WorkshopId)))) + if (!_insuranceListRepositpry.Exists(x => x.Year == searchModel.Year && x.Month == searchModel.Month && (ids != null && ids.Count > 0 && ids.Contains(x.WorkshopId)))) { mainEmployeeDetailsViewModel = _insuranceListRepositpry.SearchEmployeeListForEditByInsuranceListId(searchModel); @@ -1194,11 +1197,11 @@ public class InsuranceListApplication: IInsuranceListApplication var searchModelForCreate = new EmployeeForCreateInsuranceListSearchModel(); searchModelForCreate.Month = searchModel.Month; searchModelForCreate.Year = searchModel.Year; - searchModelForCreate.WorkshopIds=new List(){ searchModel.WorkshopId }; + searchModelForCreate.WorkshopIds = new List() { searchModel.WorkshopId }; var leftWorkInsuranceViewModelList = _leftWorkInsuranceApplication.SearchForCreateInsuranceList(searchModelForCreate); var newEmployeeId = leftWorkInsuranceViewModelList.Select(x => x.EmployeeId).ToList(); var oldEmployeeId = mainEmployeeDetailsViewModel.EmployeeDetailsForInsuranceList.Select(x => x.EmployeeId).ToList(); - if(!newEmployeeId.SequenceEqual(oldEmployeeId)) + if (!newEmployeeId.SequenceEqual(oldEmployeeId)) { var employeeAddIds = new List(); var employeeRemoveIds = new List(); @@ -1223,14 +1226,14 @@ public class InsuranceListApplication: IInsuranceListApplication if (employeeAddIds != null && employeeAddIds.Count > 0) { leftWorkInsuranceViewModelList = leftWorkInsuranceViewModelList.Where(x => employeeAddIds.Contains(x.EmployeeId)).ToList(); - mainEmployeeDetailsViewModelForNewPersonel = GetEmployeeForInsuranceList(leftWorkInsuranceViewModelList,searchModel); + mainEmployeeDetailsViewModelForNewPersonel = GetEmployeeForInsuranceList(leftWorkInsuranceViewModelList, searchModel); if (mainEmployeeDetailsViewModelForNewPersonel.EmployeeDetailsForInsuranceList != null && mainEmployeeDetailsViewModelForNewPersonel.EmployeeDetailsForInsuranceList.Count > 0) { mainEmployeeDetailsViewModel.EmployeeDetailsForInsuranceList = mainEmployeeDetailsViewModel.EmployeeDetailsForInsuranceList.Union(mainEmployeeDetailsViewModelForNewPersonel.EmployeeDetailsForInsuranceList).ToList(); } } - if (employeeRemoveIds != null && employeeRemoveIds.Count>0) + if (employeeRemoveIds != null && employeeRemoveIds.Count > 0) { mainEmployeeDetailsViewModel.EmployeeDetailsForInsuranceList = mainEmployeeDetailsViewModel .EmployeeDetailsForInsuranceList.Where(x => !employeeRemoveIds.Contains(x.EmployeeId)) @@ -1251,12 +1254,12 @@ public class InsuranceListApplication: IInsuranceListApplication var day = 1; var persianCurrentStartDate = new PersianDateTime(year, month, day); var persianCurrentEndDate = new PersianDateTime(year, month, dayMonthCurrent); - + var model = new YearlySalarySearchModel(); model.StartDateGr = startMonthCurrent.ToGeorgianDateTime(); model.EndDateGr = endMonthCurrent.ToGeorgianDateTime(); model.year = searchModel.Year; - + var yearlysalaryItem = new YearlysalaryItemViewModel(); var housingAllowance = new YearlysalaryItemViewModel(); var consumableItems = new YearlysalaryItemViewModel(); @@ -1270,7 +1273,7 @@ public class InsuranceListApplication: IInsuranceListApplication int endWork = 0; item.IsMaritalStatusSet = // آیا وضعیت تاهل پرسنل ست شده است !string.IsNullOrWhiteSpace(employeeObject.MaritalStatus); - + #region HasConfilictLeftWork bool hasConfilict = false; @@ -1325,7 +1328,7 @@ public class InsuranceListApplication: IInsuranceListApplication } //ترک کارش در ماه و سال جاری بود نمایش داده شود - if (!string.IsNullOrEmpty(item.LeftWorkDate) && !item.LeftWorkDate.Contains(searchModel.Year+"/"+searchModel.Month ) ) + if (!string.IsNullOrEmpty(item.LeftWorkDate) && !item.LeftWorkDate.Contains(searchModel.Year + "/" + searchModel.Month)) { item.LeftWorkDate = string.Empty; item.LeftWorkDateGr = null; @@ -1366,8 +1369,8 @@ public class InsuranceListApplication: IInsuranceListApplication var monthStartDateUser = Convert.ToInt32(item.StartWorkDate.Substring(5, 2)); var dayStartDateUser = Convert.ToInt32(item.StartWorkDate.Substring(8, 2)); var persianStartDateUser = new PersianDateTime(yearStartDateUser, monthStartDateUser, dayStartDateUser); - - if(persianStartDateUser <= persianCurrentStartDate) + + if (persianStartDateUser <= persianCurrentStartDate) { startWork = 1; } @@ -1376,18 +1379,18 @@ public class InsuranceListApplication: IInsuranceListApplication startWork = dayStartDateUser; } - if(persianStartDateUser < persianCurrentStartDate) + if (persianStartDateUser < persianCurrentStartDate) item.HasStartWorkInMonth = false; else item.HasStartWorkInMonth = true; - + if (hasConfilict) //اگر ترک کار شخص تغییر کرده بود، دوباره محاسبه شود { item.StartMonthCurrent = startMonthCurrent; item.HousingAllowance = housingAllowance.ItemValue; item.ConsumableItems = consumableItems.ItemValue; - item.DailyWage= ComputeDailyWage(yearlysalaryItem.ItemValue, item.EmployeeId, searchModel.WorkshopId, searchModel.Year); + item.DailyWage = ComputeDailyWage(yearlysalaryItem.ItemValue, item.EmployeeId, searchModel.WorkshopId, searchModel.Year); item.DailyWageStr = item.DailyWage.ToMoney(); } else @@ -1447,15 +1450,15 @@ public class InsuranceListApplication: IInsuranceListApplication item.UnEmploymentInsurance = GetRoundValue(unEmploymentInsurance); // item.BenefitsIncludedNonContinuous = item.BenefitsIncludedContinuous; - item.IncludedAndNotIncluded = item.BenefitsIncludedContinuous + item.BenefitsIncludedNonContinuous; + item.IncludedAndNotIncluded = item.BenefitsIncludedContinuous + item.BenefitsIncludedNonContinuous; } - + } - if (mainEmployeeDetailsViewModel2.EmployeeDetailsForInsuranceList!=null && mainEmployeeDetailsViewModel2.EmployeeDetailsForInsuranceList.Count>0) + if (mainEmployeeDetailsViewModel2.EmployeeDetailsForInsuranceList != null && mainEmployeeDetailsViewModel2.EmployeeDetailsForInsuranceList.Count > 0) mainEmployeeDetailsViewModel.EmployeeDetailsForInsuranceList = mainEmployeeDetailsViewModel.EmployeeDetailsForInsuranceList.Union(mainEmployeeDetailsViewModel2.EmployeeDetailsForInsuranceList).OrderByDescending(x => x.HasLeftWorkInMonth).ThenByDescending(x => x.HasStartWorkInMonth).ThenBy(x => x.LName).ToList(); else mainEmployeeDetailsViewModel.EmployeeDetailsForInsuranceList = mainEmployeeDetailsViewModel.EmployeeDetailsForInsuranceList.OrderByDescending(x => x.HasLeftWorkInMonth).ThenByDescending(x => x.HasStartWorkInMonth).ThenBy(x => x.LName).ToList(); - + mainEmployeeDetailsViewModel.IsExist = false; mainEmployeeDetailsViewModel.MaritalStatus = maritalStatus.ItemValue; } @@ -1486,7 +1489,7 @@ public class InsuranceListApplication: IInsuranceListApplication // endDateGr); var employeeInsurancDataPreviusList = - _insuranceListRepositpry.GetEmployeeInsuranceDataForEdit(searchModel.InsuranceId,startDateGr,endDateGr); + _insuranceListRepositpry.GetEmployeeInsuranceDataForEdit(searchModel.InsuranceId, startDateGr, endDateGr); var computeResult = employeeInsurancDataPreviusList.Select(employeeData => { @@ -1550,12 +1553,12 @@ public class InsuranceListApplication: IInsuranceListApplication overTimePayIsSet = false; } return new EmployeeDetailsForInsuranceListViewModel - { + { #region EmployeeInfo EmployeeHasCheckout = employeeHasCheckout, EmployeeInsurancListDataId = employeeData.EmployeeInsurancListDataId, - InsuranceEmployeeInformationId = employeeData.InsuranceEmployeeInformationId, + InsuranceEmployeeInformationId = employeeData.InsuranceEmployeeInformationId, EmployeeId = employeeData.EmployeeId, FName = employeeData.FName, LName = employeeData.LName, @@ -1676,9 +1679,9 @@ public class InsuranceListApplication: IInsuranceListApplication return result; } - private double? GetDailyWageFixedSalary(string year, long workshopId,long employeeId,DateTime? startDateGr, DateTime? endDateGr, long jobId, string population, long? insuranceJobId) + private double? GetDailyWageFixedSalary(string year, long workshopId, long employeeId, DateTime? startDateGr, DateTime? endDateGr, long jobId, string population, long? insuranceJobId) { - + double? result = 0; string month = $"{startDateGr.ToFarsi()}".Substring(5, 2); //اگر مشاغل مقطوع بود و شغلش کارفرما بود @@ -1727,7 +1730,7 @@ public class InsuranceListApplication: IInsuranceListApplication { var inJob = _insuranceJobItemRepository - .GetInsuranceJobItemByInsuranceJobId((long)workshop.InsuranceJobId,year, month); + .GetInsuranceJobItemByInsuranceJobId((long)workshop.InsuranceJobId, year, month); if (workshop.Population == "MoreThan500") { var max = inJob.MaxBy(x => x.PercentageMoreThan); @@ -1776,9 +1779,9 @@ public class InsuranceListApplication: IInsuranceListApplication else { - var searchModel = new InsuranceJobItemSearchModel(); - searchModel.InsuranceJobId = (long)insuranceJobId; - var JobItem = _insuranceJobItemRepository.GetInsuranceJobItemByInsuranceJobIdForFixedSalary((long)insuranceJobId, jobId, year, month); + var searchModel = new InsuranceJobItemSearchModel(); + searchModel.InsuranceJobId = (long)insuranceJobId; + var JobItem = _insuranceJobItemRepository.GetInsuranceJobItemByInsuranceJobIdForFixedSalary((long)insuranceJobId, jobId, year, month); if (JobItem != null && JobItem.Id != 0) { @@ -1804,7 +1807,7 @@ public class InsuranceListApplication: IInsuranceListApplication } } - + } } catch (Exception) @@ -1827,28 +1830,28 @@ public class InsuranceListApplication: IInsuranceListApplication /// /// /// - private double GetMonthlyBenefits(int endMonthCurrentDay, double consumableItemsItemValue, double housingAllowanceItemValue,double maritalStatus, int countWorkingDays, string typeOfInsuranceSendWorkshop, long jobId,long employeeId,bool includeStatus) + private double GetMonthlyBenefits(int endMonthCurrentDay, double consumableItemsItemValue, double housingAllowanceItemValue, double maritalStatus, int countWorkingDays, string typeOfInsuranceSendWorkshop, long jobId, long employeeId, bool includeStatus) { - //ToDo - //افزودن شرط مشمول مزایای + //ToDo + //افزودن شرط مشمول مزایای - //اگر پرسنل کارفرما بود و نوع لیست کارگاه کمک دولت بود مزایا محاسبه نشود - //اگر تیک مشمول مزایا در ترک کار خاموش بود مزایا نگیرد + //اگر پرسنل کارفرما بود و نوع لیست کارگاه کمک دولت بود مزایا محاسبه نشود + //اگر تیک مشمول مزایا در ترک کار خاموش بود مزایا نگیرد - bool isManager = jobId is 10 or 16 or 17 or 18 or 3498; - if (isManager && !includeStatus) + bool isManager = jobId is 10 or 16 or 17 or 18 or 3498; + if (isManager && !includeStatus) return 0; //پرسنل استثناء if (employeeId == 42783) return 53082855; - - //if(employeeId == 8859) - // return GetRoundValue(((consumableItemsItemValue + housingAllowanceItemValue + maritalStatus) / 31) * countWorkingDays); - //مزایای ماهانه با توجه به پایان ماه که 30 یا 31 روزه است، متفاوت می باشد - //برای ماه 29 روزه هم تقسیم بر 30 می شود. - if (countWorkingDays == endMonthCurrentDay) + //if(employeeId == 8859) + // return GetRoundValue(((consumableItemsItemValue + housingAllowanceItemValue + maritalStatus) / 31) * countWorkingDays); + + //مزایای ماهانه با توجه به پایان ماه که 30 یا 31 روزه است، متفاوت می باشد + //برای ماه 29 روزه هم تقسیم بر 30 می شود. + if (countWorkingDays == endMonthCurrentDay) return (consumableItemsItemValue + housingAllowanceItemValue + maritalStatus); else if (endMonthCurrentDay == 29)//farokhiChanges در خط پایین عدد 30 رو به 29 تغییر دادم return GetRoundValue(((consumableItemsItemValue + housingAllowanceItemValue + maritalStatus) / 29) * countWorkingDays); @@ -1860,31 +1863,31 @@ public class InsuranceListApplication: IInsuranceListApplication return GetRoundValue(((consumableItemsItemValue + housingAllowanceItemValue + maritalStatus) / endMonthCurrentDay) * countWorkingDays); } - - private double ComputeDailyWage(double yearlysalaryItemValue, long employeeId, long workshopId, string year) + + private double ComputeDailyWage(double yearlysalaryItemValue, long employeeId, long workshopId, string year) { double dailyWage = yearlysalaryItemValue; - InsuranceListSearchModel searchModel = new InsuranceListSearchModel(); + InsuranceListSearchModel searchModel = new InsuranceListSearchModel(); var insuransList = _insuranceListRepositpry.GetInsuranceListByWorkshopIdAndYear(workshopId, year); if (insuransList != null) { - var employeeInsurancListData = _employeeInsurancListDataRepository.GetEmployeeInsurancListDataByEmployeeIdAndInsuranceListId( employeeId, insuransList.Id); - if (employeeInsurancListData != null && employeeInsurancListData.DailyWage> dailyWage) + var employeeInsurancListData = _employeeInsurancListDataRepository.GetEmployeeInsurancListDataByEmployeeIdAndInsuranceListId(employeeId, insuransList.Id); + if (employeeInsurancListData != null && employeeInsurancListData.DailyWage > dailyWage) { - dailyWage=employeeInsurancListData.DailyWage; + dailyWage = employeeInsurancListData.DailyWage; } } dailyWage = employeeId == 6536 ? 9399512 : dailyWage; return dailyWage; } - public MainEmployeeDetailsViewModel GetEmployeeForInsuranceList(List leftWorkInsuranceViewModelList, EmployeeForEditInsuranceListSearchModel searchModel) + public MainEmployeeDetailsViewModel GetEmployeeForInsuranceList(List leftWorkInsuranceViewModelList, EmployeeForEditInsuranceListSearchModel searchModel) { var result = new MainEmployeeDetailsViewModel(); List list = new List(); - int leftWorkInsuranceCount= leftWorkInsuranceViewModelList.Count(); + int leftWorkInsuranceCount = leftWorkInsuranceViewModelList.Count(); string startMonthCurrent = searchModel.Year + "/" + searchModel.Month + "/01"; string endMonthCurrent = startMonthCurrent.FindeEndOfMonth(); @@ -1893,7 +1896,7 @@ public class InsuranceListApplication: IInsuranceListApplication model.EndDateGr = endMonthCurrent.ToGeorgianDateTime(); model.year = searchModel.Year; - + var yearSalaryObj = _yearlySalaryApplication.GetDetailsBySearchModel(model); @@ -1953,7 +1956,7 @@ public class InsuranceListApplication: IInsuranceListApplication employeeDetailsForInsuranceObj.FName = employeeObject.FName; employeeDetailsForInsuranceObj.LName = employeeObject.LName; employeeDetailsForInsuranceObj.FatherName = employeeObject.FatherName; - employeeDetailsForInsuranceObj.DateOfBirth = employeeObject.DateOfBirth=="1300/10/11"?"": employeeObject.DateOfBirth; + employeeDetailsForInsuranceObj.DateOfBirth = employeeObject.DateOfBirth == "1300/10/11" ? "" : employeeObject.DateOfBirth; employeeDetailsForInsuranceObj.DateOfIssue = employeeObject.DateOfIssue; employeeDetailsForInsuranceObj.PlaceOfIssue = employeeObject.PlaceOfIssue; employeeDetailsForInsuranceObj.NationalCode = employeeObject.NationalCode; @@ -2059,8 +2062,8 @@ public class InsuranceListApplication: IInsuranceListApplication case 40469://ثابت countWorkingDays = 7; break; - //case 9950://ثابت - // countWorkingDays = 15; + //case 9950://ثابت + // countWorkingDays = 15; break; case 9640://ثابت countWorkingDays = 15; @@ -2071,9 +2074,9 @@ public class InsuranceListApplication: IInsuranceListApplication case 6219://ثابت countWorkingDays = 15; break; - //case 7897://ثابت - // countWorkingDays = 15; - // break; + //case 7897://ثابت + // countWorkingDays = 15; + // break; } ; #endregion @@ -2085,17 +2088,17 @@ public class InsuranceListApplication: IInsuranceListApplication double dailyWage = employeeDetailsForInsuranceObj.DailyWage; if (searchModel.FixedSalary) { - dailyWage = Convert.ToDouble(GetDailyWageFixedSalary(searchModel.Year, item.WorkshopId,item.EmployeeId, model.StartDateGr, model.EndDateGr, item.JobId, searchModel.Population, searchModel.InsuranceJobId)); + dailyWage = Convert.ToDouble(GetDailyWageFixedSalary(searchModel.Year, item.WorkshopId, item.EmployeeId, model.StartDateGr, model.EndDateGr, item.JobId, searchModel.Population, searchModel.InsuranceJobId)); employeeDetailsForInsuranceObj.HasConfilictJobs = (dailyWage == 0 ? true : false); } #endregion if (yearlysalaryItem != null) { - if(!searchModel.FixedSalary ) + if (!searchModel.FixedSalary) { //dailyWage= yearlysalaryItem.ItemValue; - dailyWage = ComputeDailyWage(yearlysalaryItem.ItemValue, item.EmployeeId,item.WorkshopId, searchModel.Year) ; + dailyWage = ComputeDailyWage(yearlysalaryItem.ItemValue, item.EmployeeId, item.WorkshopId, searchModel.Year); } employeeDetailsForInsuranceObj.DailyWage = GetRoundValue(dailyWage); employeeDetailsForInsuranceObj.DailyWageStr = employeeDetailsForInsuranceObj.DailyWage.ToMoney(); @@ -2119,8 +2122,8 @@ public class InsuranceListApplication: IInsuranceListApplication employeeDetailsForInsuranceObj.MonthlyBenefits = 0; } - employeeDetailsForInsuranceObj.BenefitsIncludedContinuous =employeeDetailsForInsuranceObj.MonthlyBenefits + employeeDetailsForInsuranceObj.MonthlySalary; - + employeeDetailsForInsuranceObj.BenefitsIncludedContinuous = employeeDetailsForInsuranceObj.MonthlyBenefits + employeeDetailsForInsuranceObj.MonthlySalary; + //if ((!item.IncludeStatus &&(item.JobId == 10 || item.JobId == 17 || item.JobId == 18 || item.JobId == 16)) ||(item.IncludeStatus && item.JobId == 10)) // 10 --> karfarma //{ // var insuranceShare2 =(employeeDetailsForInsuranceObj.BenefitsIncludedContinuous * 27) / 100; @@ -2133,14 +2136,14 @@ public class InsuranceListApplication: IInsuranceListApplication //} var employerShare = (employeeDetailsForInsuranceObj.BenefitsIncludedContinuous * 20) / 100; - employeeDetailsForInsuranceObj.EmployerShare = GetRoundValue(employerShare); //Math.Round(employerShare, MidpointRounding.ToPositiveInfinity); + employeeDetailsForInsuranceObj.EmployerShare = GetRoundValue(employerShare); //Math.Round(employerShare, MidpointRounding.ToPositiveInfinity); //if (searchModel.TypeOfInsuranceSendWorkshop == "Govermentlist" && item.JobId==10)//کمک دولت //{employeeDetailsForInsuranceObj.InsuranceShare = 0;} - var unEmploymentInsurance =(employeeDetailsForInsuranceObj.BenefitsIncludedContinuous * 3) / 100; + var unEmploymentInsurance = (employeeDetailsForInsuranceObj.BenefitsIncludedContinuous * 3) / 100; employeeDetailsForInsuranceObj.UnEmploymentInsurance = GetRoundValue(unEmploymentInsurance); employeeDetailsForInsuranceObj.BenefitsIncludedNonContinuous = employeeDetailsForInsuranceObj.BenefitsIncludedNonContinuous; @@ -2195,7 +2198,7 @@ public class InsuranceListApplication: IInsuranceListApplication public double GetMonthlyBaseYear(double dayliBase, int countWorkingDays) { - double res =GetRoundValue(dayliBase * countWorkingDays); + double res = GetRoundValue(dayliBase * countWorkingDays); return res; } } \ No newline at end of file diff --git a/CompanyManagment.EFCore/Repository/RollCallMandatoryRepository.cs b/CompanyManagment.EFCore/Repository/RollCallMandatoryRepository.cs index 3fd4fac8..3a204db6 100644 --- a/CompanyManagment.EFCore/Repository/RollCallMandatoryRepository.cs +++ b/CompanyManagment.EFCore/Repository/RollCallMandatoryRepository.cs @@ -60,8 +60,8 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll _leaveRepository = leaveRepository; _holidayItemRepository = holidayItemRepository; _testDbContext = testDbContext; - - } + + } #region OfficialChckout public ComputingViewModel MandatoryCompute(long employeeId, long workshopId, DateTime contractStart, @@ -108,8 +108,8 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll .Include(x => x.CustomizeWorkshopGroupSettings).FirstOrDefault(x => x.WorkshopId == workshopId && x.EmployeeId == employeeId); //اگر ساعت استراحت پرسنل وجود نداشت صفر است - var breakTime = settings == null ? new BreakTime(false, new TimeOnly()) : settings.BreakTime; - + var breakTimeEntity = settings == null ? new BreakTime(false, new TimeOnly()) : settings.BreakTime; + var endOfFarvardin = "1404/01/31".ToGeorgianDateTime(); #endregion @@ -145,16 +145,31 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll BreakTimeSpan = x.BreakTimeSpan }).ToList(); - groupedRollCall = rollCallResult.GroupBy(x => x.CreationDate.Date).Select(x => new GroupedRollCalls() + groupedRollCall = rollCallResult.GroupBy(x => x.CreationDate.Date).Select(x => { - CreationDate = x.Key, - ShiftList = x.Select(s => new ShiftList() { Start = s.StartDate!.Value, End = s.EndDate!.Value }).ToList(), - HasFriday = x.Any(s => s.StartDate != null && s.EndDate != null && (s.StartDate.Value.DayOfWeek == DayOfWeek.Friday || s.EndDate.Value!.DayOfWeek == DayOfWeek.Friday)), - SumOneDaySpan = new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks)) - CalculateBreakTime(x.First().BreakTimeSpan, - new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))), - - BreakTime = CalculateBreakTime(x.First().BreakTimeSpan, new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))), + TimeSpan breakTime; + if (contractStart > endOfFarvardin) + { + breakTime = CalculateBreakTime( + x.First().BreakTimeSpan, + new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))); + } + else + { + breakTime = CalculateBreakTime(breakTimeEntity, new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))); + } + return new GroupedRollCalls() + { + CreationDate = x.Key, + ShiftList = x.Select(s => new ShiftList() { Start = s.StartDate!.Value, End = s.EndDate!.Value }) + .ToList(), + HasFriday = x.Any(s => + s.StartDate != null && s.EndDate != null && (s.StartDate.Value.DayOfWeek == DayOfWeek.Friday || + s.EndDate.Value!.DayOfWeek == DayOfWeek.Friday)), + SumOneDaySpan = new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks)) - breakTime, + BreakTime = breakTime, + }; }).OrderBy(x => x.CreationDate).ToList(); } @@ -728,52 +743,52 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll } - /// - /// محاسبه ساعات کارکرد پرسنل در صورت داشتن حضور غیاب - /// - /// - /// - /// - /// - /// - public (bool hasRollCall, TimeSpan sumOfSpan) GetRollCallWorkingSpan(long employeeId, long workshopId, - DateTime contractStart, DateTime contractEnd) - { - //bool hasRollcall = - // _rollCallEmployeeRepository.HasRollCallRecord(employeeId, workshopId, contractStart, contractEnd); - //if (!hasRollcall) - // return (false, new TimeSpan()); - List rollCallResult; - List groupedRollCall; - - - rollCallResult = _context.RollCalls.Where(x => - x.EmployeeId == employeeId && x.WorkshopId == workshopId && x.StartDate.Value.Date >= contractStart.Date && - x.StartDate.Value.Date <= contractEnd.Date && x.EndDate != null).Select(x => new RollCallViewModel() - { - StartDate = x.StartDate, - EndDate = x.EndDate, - ShiftSpan = (x.EndDate.Value - x.StartDate.Value), - CreationDate = x.ShiftDate, - BreakTimeSpan = x.BreakTimeSpan - }).ToList(); - - groupedRollCall = rollCallResult.GroupBy(x => x.CreationDate.Date).Select(x => new GroupedRollCalls() - { - CreationDate = x.Key, - ShiftList = x.Select(s => new ShiftList() { Start = s.StartDate!.Value, End = s.EndDate!.Value }).ToList(), - HasFriday = x.Any(s => s.StartDate != null && s.EndDate != null && (s.StartDate.Value.DayOfWeek == DayOfWeek.Friday || s.EndDate.Value!.DayOfWeek == DayOfWeek.Friday)), - SumOneDaySpan = new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks)) - CalculateBreakTime(x.First().BreakTimeSpan, - new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))), - - BreakTime = CalculateBreakTime(x.First().BreakTimeSpan, new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))), - - }).OrderBy(x => x.CreationDate).ToList(); + /// + /// محاسبه ساعات کارکرد پرسنل در صورت داشتن حضور غیاب + /// + /// + /// + /// + /// + /// + public (bool hasRollCall, TimeSpan sumOfSpan) GetRollCallWorkingSpan(long employeeId, long workshopId, + DateTime contractStart, DateTime contractEnd) + { + //bool hasRollcall = + // _rollCallEmployeeRepository.HasRollCallRecord(employeeId, workshopId, contractStart, contractEnd); + //if (!hasRollcall) + // return (false, new TimeSpan()); + List rollCallResult; + List groupedRollCall; - TimeSpan sumSpans = new TimeSpan(groupedRollCall.Sum(x => x.SumOneDaySpan.Ticks)); - return (true, sumSpans); - } + rollCallResult = _context.RollCalls.Where(x => + x.EmployeeId == employeeId && x.WorkshopId == workshopId && x.StartDate.Value.Date >= contractStart.Date && + x.StartDate.Value.Date <= contractEnd.Date && x.EndDate != null).Select(x => new RollCallViewModel() + { + StartDate = x.StartDate, + EndDate = x.EndDate, + ShiftSpan = (x.EndDate.Value - x.StartDate.Value), + CreationDate = x.ShiftDate, + BreakTimeSpan = x.BreakTimeSpan + }).ToList(); + + groupedRollCall = rollCallResult.GroupBy(x => x.CreationDate.Date).Select(x => new GroupedRollCalls() + { + CreationDate = x.Key, + ShiftList = x.Select(s => new ShiftList() { Start = s.StartDate!.Value, End = s.EndDate!.Value }).ToList(), + HasFriday = x.Any(s => s.StartDate != null && s.EndDate != null && (s.StartDate.Value.DayOfWeek == DayOfWeek.Friday || s.EndDate.Value!.DayOfWeek == DayOfWeek.Friday)), + SumOneDaySpan = new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks)) - CalculateBreakTime(x.First().BreakTimeSpan, + new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))), + + BreakTime = CalculateBreakTime(x.First().BreakTimeSpan, new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))), + + }).OrderBy(x => x.CreationDate).ToList(); + + + TimeSpan sumSpans = new TimeSpan(groupedRollCall.Sum(x => x.SumOneDaySpan.Ticks)); + return (true, sumSpans); + } public async Task RotatingShiftReport(long workshopId, long employeeId, DateTime contractStart, DateTime contractEnd, string shiftwork, bool hasRollCall, CreateWorkingHoursTemp command, bool holidayWorking) @@ -939,19 +954,19 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll - //public static TimeSpan CalculateBreakTime(BreakTime breakTime, TimeSpan sumOneDaySpan) - //{ - // if (breakTime.BreakTimeType != BreakTimeType.WithTime) - // return new TimeSpan(); + public static TimeSpan CalculateBreakTime(BreakTime breakTime, TimeSpan sumOneDaySpan) + { + if (breakTime.BreakTimeType != BreakTimeType.WithTime) + return new TimeSpan(); - // var breakTimeSpan = breakTime.BreakTimeValue.ToTimeSpan(); + var breakTimeSpan = breakTime.BreakTimeValue.ToTimeSpan(); - // if (breakTimeSpan * 2 >= sumOneDaySpan) - // return new TimeSpan(); + if (breakTimeSpan * 2 >= sumOneDaySpan) + return new TimeSpan(); - // return breakTimeSpan; ; + return breakTimeSpan; ; - //} + } public static TimeSpan CalculateBreakTime(TimeSpan breakTimeSpan, TimeSpan sumOneDaySpan) { if (breakTimeSpan * 2 >= sumOneDaySpan) @@ -2090,7 +2105,7 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll var starTimeSingel1 = Convert.ToDateTime(shift1Start); var endTimeSingel2 = Convert.ToDateTime(shift1End); - bool hasRestTime = false; + bool hasRestTime = false; shift1StartGr = new DateTime(cuurentDate.Year, cuurentDate.Month, cuurentDate.Day, starTimeSingel1.Hour, starTimeSingel1.Minute, 0); @@ -2099,92 +2114,92 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll if (shift1EndGr.TimeOfDay < shift1StartGr.TimeOfDay) shift1EndGr = shift1EndGr.AddDays(1); - var shiftEndWithoutRest = shift1EndGr; + var shiftEndWithoutRest = shift1EndGr; - var shiftSpan = (shift1EndGr - shift1StartGr); - if (restTime > TimeSpan.Zero && shiftSpan >= restTime) - { - hasRestTime = true; - shift1EndGr = shift1EndGr.Subtract(restTime); - shiftSpan = (shift1EndGr - shift1StartGr); - - } + var shiftSpan = (shift1EndGr - shift1StartGr); + if (restTime > TimeSpan.Zero && shiftSpan >= restTime) + { + hasRestTime = true; + shift1EndGr = shift1EndGr.Subtract(restTime); + shiftSpan = (shift1EndGr - shift1StartGr); - if (!leaveSearchResult.Any(x => x.StartLeaveGr < shift1EndGr && x.EndLeaveGr > shift1StartGr && x.PaidLeaveType =="روزانه")) - { - var hourseLeaveTypeResult = leaveSearchResult.FirstOrDefault(x => - x.StartLeaveGr < shift1EndGr && x.EndLeaveGr > shift1StartGr && x.PaidLeaveType == "ساعتی"); - if (hourseLeaveTypeResult == null) - { - result.Add(new RollCallViewModel() - { - BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, - StartDate = shift1StartGr, - EndDate = shift1EndGr, - ShiftSpan = shiftSpan, - ShiftDate = shift1StartGr, + } + + if (!leaveSearchResult.Any(x => x.StartLeaveGr < shift1EndGr && x.EndLeaveGr > shift1StartGr && x.PaidLeaveType == "روزانه")) + { + var hourseLeaveTypeResult = leaveSearchResult.FirstOrDefault(x => + x.StartLeaveGr < shift1EndGr && x.EndLeaveGr > shift1StartGr && x.PaidLeaveType == "ساعتی"); + if (hourseLeaveTypeResult == null) + { + result.Add(new RollCallViewModel() + { + BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, + StartDate = shift1StartGr, + EndDate = shift1EndGr, + ShiftSpan = shiftSpan, + ShiftDate = shift1StartGr, ShiftEndWithoutRest = shiftEndWithoutRest - }); - } - else - { + }); + } + else + { - if (hourseLeaveTypeResult.StartLeaveGr <= shift1StartGr && hourseLeaveTypeResult.EndLeaveGr < shift1EndGr) - { - //leave <--------------------> - //shift <----------------------------------> - result.Add(new RollCallViewModel() - { - BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, - StartDate = hourseLeaveTypeResult.EndLeaveGr, - EndDate = shift1EndGr, - ShiftSpan = (shift1EndGr - hourseLeaveTypeResult.EndLeaveGr), - ShiftDate = shift1StartGr, - ShiftEndWithoutRest = shiftEndWithoutRest + if (hourseLeaveTypeResult.StartLeaveGr <= shift1StartGr && hourseLeaveTypeResult.EndLeaveGr < shift1EndGr) + { + //leave <--------------------> + //shift <----------------------------------> + result.Add(new RollCallViewModel() + { + BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, + StartDate = hourseLeaveTypeResult.EndLeaveGr, + EndDate = shift1EndGr, + ShiftSpan = (shift1EndGr - hourseLeaveTypeResult.EndLeaveGr), + ShiftDate = shift1StartGr, + ShiftEndWithoutRest = shiftEndWithoutRest - }); - } - else if (hourseLeaveTypeResult.StartLeaveGr > shift1StartGr && hourseLeaveTypeResult.EndLeaveGr < shift1EndGr) - { - //leave <--------------------> - //shift <----------------------------------> - result.Add(new RollCallViewModel() - { - BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, - StartDate = shift1StartGr, - EndDate = hourseLeaveTypeResult.StartLeaveGr, - ShiftSpan = (hourseLeaveTypeResult.StartLeaveGr - shift1StartGr), - ShiftDate = shift1StartGr, - ShiftEndWithoutRest = hourseLeaveTypeResult.StartLeaveGr + }); + } + else if (hourseLeaveTypeResult.StartLeaveGr > shift1StartGr && hourseLeaveTypeResult.EndLeaveGr < shift1EndGr) + { + //leave <--------------------> + //shift <----------------------------------> + result.Add(new RollCallViewModel() + { + BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, + StartDate = shift1StartGr, + EndDate = hourseLeaveTypeResult.StartLeaveGr, + ShiftSpan = (hourseLeaveTypeResult.StartLeaveGr - shift1StartGr), + ShiftDate = shift1StartGr, + ShiftEndWithoutRest = hourseLeaveTypeResult.StartLeaveGr - }); + }); - result.Add(new RollCallViewModel() - { - BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, - StartDate = hourseLeaveTypeResult.EndLeaveGr, - EndDate = shift1EndGr, - ShiftSpan = (shift1EndGr - hourseLeaveTypeResult.EndLeaveGr), - ShiftDate = shift1StartGr, - ShiftEndWithoutRest = shiftEndWithoutRest + result.Add(new RollCallViewModel() + { + BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, + StartDate = hourseLeaveTypeResult.EndLeaveGr, + EndDate = shift1EndGr, + ShiftSpan = (shift1EndGr - hourseLeaveTypeResult.EndLeaveGr), + ShiftDate = shift1StartGr, + ShiftEndWithoutRest = shiftEndWithoutRest - }); - } - else if (hourseLeaveTypeResult.StartLeaveGr > shift1StartGr && hourseLeaveTypeResult.EndLeaveGr >= shift1EndGr) - { - //leave <--------------------> - //shift <----------------------------------> + }); + } + else if (hourseLeaveTypeResult.StartLeaveGr > shift1StartGr && hourseLeaveTypeResult.EndLeaveGr >= shift1EndGr) + { + //leave <--------------------> + //shift <----------------------------------> - result.Add(new RollCallViewModel() - { - BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, - StartDate = shift1StartGr, - EndDate = hourseLeaveTypeResult.StartLeaveGr, - ShiftSpan = (hourseLeaveTypeResult.StartLeaveGr - shift1StartGr), - ShiftDate = shift1StartGr, - ShiftEndWithoutRest = hourseLeaveTypeResult.StartLeaveGr + result.Add(new RollCallViewModel() + { + BreakTimeSpan = hasRestTime ? restTime : TimeSpan.Zero, + StartDate = shift1StartGr, + EndDate = hourseLeaveTypeResult.StartLeaveGr, + ShiftSpan = (hourseLeaveTypeResult.StartLeaveGr - shift1StartGr), + ShiftDate = shift1StartGr, + ShiftEndWithoutRest = hourseLeaveTypeResult.StartLeaveGr - }); + }); } @@ -3021,13 +3036,13 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll var endFarvarding = new DateTime(2025, 4, 20); - if (contractStart>endFarvarding) + if (contractStart > endFarvarding) { - customizeWorkshopEmployeeSettings=_context.CustomizeWorkshopEmployeeSettings + customizeWorkshopEmployeeSettings = _context.CustomizeWorkshopEmployeeSettings .AsSplitQuery().AsNoTracking().FirstOrDefault(x => x.WorkshopId == workshopId && x.EmployeeId == employeeId); - customizeWorkshopSettings =_context.CustomizeWorkshopSettings.AsNoTracking().FirstOrDefault(x => x.WorkshopId == workshopId); + customizeWorkshopSettings = _context.CustomizeWorkshopSettings.AsNoTracking().FirstOrDefault(x => x.WorkshopId == workshopId); } else @@ -3982,40 +3997,40 @@ public class RollCallMandatoryRepository : RepositoryBase, IRoll }).ToList(); } - public List LoanInstallmentForCheckout(long employeeId, long workshopId, DateTime contractStart, DateTime contractEnd) - { - return _context.Loans - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .SelectMany(x => x.LoanInstallments) - .Where(i => i.InstallmentDate >= contractStart && i.InstallmentDate <= contractEnd && i.IsActive == IsActive.True) - .Select(x => new LoanInstallmentViewModel() - { - Id = x.Id, - Month = x.Month, - IsActive = x.IsActive, - Amount = x.AmountForMonth.ToMoney(), - Year = x.Year, - AmountDouble = x.AmountForMonth, - RemainingAmount = _context.Loans.SelectMany(l => l.LoanInstallments).Where(i => i.LoanId == x.LoanId && i.IsActive == IsActive.True && i.InstallmentDate > x.InstallmentDate) - .Sum(i => i.AmountForMonth).ToMoney(), - LoanAmount = _context.Loans.FirstOrDefault(l => l.id == x.LoanId).Amount.ToMoney() - }).ToList(); - } + public List LoanInstallmentForCheckout(long employeeId, long workshopId, DateTime contractStart, DateTime contractEnd) + { + return _context.Loans + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .SelectMany(x => x.LoanInstallments) + .Where(i => i.InstallmentDate >= contractStart && i.InstallmentDate <= contractEnd && i.IsActive == IsActive.True) + .Select(x => new LoanInstallmentViewModel() + { + Id = x.Id, + Month = x.Month, + IsActive = x.IsActive, + Amount = x.AmountForMonth.ToMoney(), + Year = x.Year, + AmountDouble = x.AmountForMonth, + RemainingAmount = _context.Loans.SelectMany(l => l.LoanInstallments).Where(i => i.LoanId == x.LoanId && i.IsActive == IsActive.True && i.InstallmentDate > x.InstallmentDate) + .Sum(i => i.AmountForMonth).ToMoney(), + LoanAmount = _context.Loans.FirstOrDefault(l => l.id == x.LoanId).Amount.ToMoney() + }).ToList(); + } - public List SalaryAidsForCheckout(long employeeId, long workshopId, DateTime checkoutStart, DateTime checkoutEnd) - { - return _context.SalaryAids - .Where(x => x.CalculationDate >= checkoutStart && x.CalculationDate <= checkoutEnd && x.EmployeeId == employeeId && x.WorkshopId == workshopId).Select(x => new SalaryAidViewModel() - { - Amount = x.Amount.ToMoney(), - AmountDouble = x.Amount, - SalaryAidDateTimeFa = x.SalaryAidDateTime.ToFarsi(), - SalaryAidDateTimeGe = x.SalaryAidDateTime, - CalculationDateTimeGe = x.CalculationDate, - CalculationDateTimeFa = x.CalculationDate.ToFarsi(), - Id = x.id - }).ToList(); - } + public List SalaryAidsForCheckout(long employeeId, long workshopId, DateTime checkoutStart, DateTime checkoutEnd) + { + return _context.SalaryAids + .Where(x => x.CalculationDate >= checkoutStart && x.CalculationDate <= checkoutEnd && x.EmployeeId == employeeId && x.WorkshopId == workshopId).Select(x => new SalaryAidViewModel() + { + Amount = x.Amount.ToMoney(), + AmountDouble = x.Amount, + SalaryAidDateTimeFa = x.SalaryAidDateTime.ToFarsi(), + SalaryAidDateTimeGe = x.SalaryAidDateTime, + CalculationDateTimeGe = x.CalculationDate, + CalculationDateTimeFa = x.CalculationDate.ToFarsi(), + Id = x.id + }).ToList(); + } private void CreateRewardForBirthDay(long employeeId, long workshopId, double amount, int month, int year, DateTime contractStart) diff --git a/CompanyManagment.EFCore/Repository/RollCallRepository.cs b/CompanyManagment.EFCore/Repository/RollCallRepository.cs index a54f063c..0e07d3bb 100644 --- a/CompanyManagment.EFCore/Repository/RollCallRepository.cs +++ b/CompanyManagment.EFCore/Repository/RollCallRepository.cs @@ -152,16 +152,16 @@ public class RollCallRepository : RepositoryBase, IRollCallRepos public List GetEmployeeRollCallsForMonth(long employeeId, long workshopId, DateTime startMonthDay, DateTime endMonthDay) { var firstDayOfMonth = $"{startMonthDay.ToFarsi().Substring(0,8)}01".ToGeorgianDateTime(); - + var endFarvardin = "1404/01/31".ToGeorgianDateTime(); //گرفتن ساعت استراحت پرسنل از تنظیمات #region breakTime - //BaseCustomizeEntity settings = _context.CustomizeWorkshopEmployeeSettings.AsSplitQuery().FirstOrDefault(x => - // x.WorkshopId == workshopId && x.EmployeeId == employeeId); - ////اگر ساعت استراحت پرسنل وجود نداشت صفر است - //var breakTime = settings == null ? new BreakTime(false, new TimeOnly()) : settings.BreakTime; + BaseCustomizeEntity settings = _context.CustomizeWorkshopEmployeeSettings.AsSplitQuery().FirstOrDefault(x => + x.WorkshopId == workshopId && x.EmployeeId == employeeId); + //اگر ساعت استراحت پرسنل وجود نداشت صفر است + var breakTime = settings == null ? new BreakTime(false, new TimeOnly()) : settings.BreakTime; #endregion - var rollCalls = _context.RollCalls.Where(x => + var rollCalls = _context.RollCalls.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && x.StartDate != null && x.EndDate != null && x.RollCallModifyType != RollCallModifyType.Undefined && x.ShiftDate.Date >= startMonthDay && x.ShiftDate.Date <= endMonthDay).ToList(); @@ -224,26 +224,30 @@ public class RollCallRepository : RepositoryBase, IRollCallRepos var rollCallTimeSpanPerDay = new TimeSpan(x.Where(y => y.EndDate != null).Sum(y => (y.EndDate - y.StartDate)!.Value.Ticks)); - var breakTimePerDay = RollCallMandatoryRepository.CalculateBreakTime(x.First().BreakTimeSpan, rollCallTimeSpanPerDay); + TimeSpan breakTimePerDay ; + if(startMonthDay>endFarvardin) + breakTimePerDay= RollCallMandatoryRepository.CalculateBreakTime(x.First().BreakTimeSpan, rollCallTimeSpanPerDay); + else + breakTimePerDay = RollCallMandatoryRepository.CalculateBreakTime(breakTime, rollCallTimeSpanPerDay); return new CheckoutDailyRollCallViewModel() - { - StartDate1 = orderedRollcalls.FirstOrDefault().StartDate.Value.ToString("HH:mm"), - EndDate1 = orderedRollcalls.FirstOrDefault().EndDate.Value.ToString("HH:mm"), + { + StartDate1 = orderedRollcalls.FirstOrDefault().StartDate.Value.ToString("HH:mm"), + EndDate1 = orderedRollcalls.FirstOrDefault().EndDate.Value.ToString("HH:mm"), - StartDate2 = orderedRollcalls.Skip(1).FirstOrDefault()?.StartDate?.ToString("HH:mm") ?? "", - EndDate2 = orderedRollcalls.Skip(1).FirstOrDefault()?.EndDate?.ToString("HH:mm") ?? "", + StartDate2 = orderedRollcalls.Skip(1).FirstOrDefault()?.StartDate?.ToString("HH:mm") ?? "", + EndDate2 = orderedRollcalls.Skip(1).FirstOrDefault()?.EndDate?.ToString("HH:mm") ?? "", - TotalhourseSpan = rollCallTimeSpanPerDay - breakTimePerDay, + TotalhourseSpan = rollCallTimeSpanPerDay - breakTimePerDay, - BreakTimeTimeSpan = breakTimePerDay, + BreakTimeTimeSpan = breakTimePerDay, - DayOfWeek = x.Key.DayOfWeek.DayOfWeeKToPersian(), - RollCallDateFa = x.Key.Date.ToFarsi(), - DateTimeGr = x.Key.Date, - IsSliced = x.Count() > 2, - IsAbsent = false - }; + DayOfWeek = x.Key.DayOfWeek.DayOfWeeKToPersian(), + RollCallDateFa = x.Key.Date.ToFarsi(), + DateTimeGr = x.Key.Date, + IsSliced = x.Count() > 2, + IsAbsent = false + }; }); diff --git a/CompanyManagment.EFCore/Repository/YearlySalaryRepository.cs b/CompanyManagment.EFCore/Repository/YearlySalaryRepository.cs index 6187a5ec..ac6a0777 100644 --- a/CompanyManagment.EFCore/Repository/YearlySalaryRepository.cs +++ b/CompanyManagment.EFCore/Repository/YearlySalaryRepository.cs @@ -5,6 +5,9 @@ using System.Linq; using System.Net.Http; using System.Threading.Tasks; using _0_Framework.Application; +using _0_Framework.Domain.CustomizeCheckoutShared.Base; +using _0_Framework.Domain.CustomizeCheckoutShared.Enums; +using _0_Framework.Domain.CustomizeCheckoutShared.ValueObjects; using _0_Framework.InfraStructure; using Company.Domain.LeftWorkAgg; using Company.Domain.MandatoryHoursAgg; @@ -27,255 +30,255 @@ namespace CompanyManagment.EFCore.Repository; public class YearlySalaryRepository : RepositoryBase, IYearlySalaryRepository { - private readonly CompanyContext _context; - private readonly ILeftWorkRepository _leftWorkRepository; - private readonly IMandatoryHoursRepository _mandatoryHoursRepository; - private readonly IRollCallEmployeeRepository _rollCallEmployeeRepository; - - - - public YearlySalaryRepository(CompanyContext context, ILeftWorkRepository leftWorkRepository, IMandatoryHoursRepository mandatoryHoursRepository, IRollCallEmployeeRepository rollCallEmployeeRepository) : base(context) - { - _context = context; - _leftWorkRepository = leftWorkRepository; - _mandatoryHoursRepository = mandatoryHoursRepository; - _rollCallEmployeeRepository = rollCallEmployeeRepository; - } - // لیست سال های برای دراپ دان - #region GetYearsToDropDown - public List GetYears() - { - List yearlist = new List(); - PersianDateTime startDate = new PersianDateTime(1370, 1, 1); - DateTime endDateNow = DateTime.Now; - - var endDateNowFa = endDateNow.ToFarsi(); - var y = Convert.ToInt32(endDateNowFa.Substring(0, 4)); - var m = Convert.ToInt32(endDateNowFa.Substring(5, 2)); - var d = Convert.ToInt32(endDateNowFa.Substring(8, 2)); - - PersianDateTime endDate = new PersianDateTime(y, m, d); - - if (m == 12) - endDate.AddYears(1); - for (PersianDateTime date = endDate; date >= startDate; date = date.AddYears(-1)) - { - yearlist.Add(date.ToString("yyyy")); - } - - return yearlist; - } - - #endregion - - //دریافت مقادیر یک سال بر اساس سال انتخاب شده - #region YearlySalaryByYear - - public List GetYearlySalary() - { - return _context.YearlySalaries.Select(x => new YearlySalaryViewModel - { - Id = x.id, - StartDate = x.StartDate.ToFarsi(), - Year = x.Year - - - }) - .OrderByDescending(x => x.Year).ToList(); - } - - #endregion - - - //محاسبه حقوق ماهیانه عیدی و پاداش ، سنوات - #region GetMontlyBunosYears - public MontlywageBunosYearsViewModel GetMontlyBunosYears(TimeSpan weeklyTime, DateTime contractStart, DateTime contractEnd, double daylyWage, - string weeklyWorkingTime, int officialholiday, int friday, string totalHoursH, string totalHorsM, string basic, int fridayStartToEnd, double dayliFeeComplete, bool hasRollCall, bool holidaysWorking, string shiftWork) - { - double basicDouble = basic.MoneyToDouble(); - double sub = 0; - double bacicMontlyResult = 0; - double montlyResult = 0; - - double montlySalaryResult = 0; - double basicYearResult = 0; - var salary = _context.YearlySalaries.OrderByDescending(x => x.EndDate).Include(x => x.YearlySalaryItemsList).ToList(); - - var SalaryItems = - salary.FirstOrDefault(x => x.StartDate <= contractStart && x.EndDate >= contractStart); - var BasicDayliFee = SalaryItems - .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); - var contractEndFa = contractEnd.ToFarsi(); - var TotalDays = (contractEnd - contractStart).TotalDays + 1; - //var DayCounter = Convert.ToInt32(TotalDays); - //var EndOfM = Convert.ToInt32(contractEndFa.Substring(8, 2)); - //if (EndOfM == 31) - //{ - // TotalDays = 30; - //} - - // یدست آوردن کل ساعت کار پرسنل در ماه - var totalHoursHDouble = Convert.ToDouble(totalHoursH); - var totalHoursMDouble = Convert.ToDouble(totalHorsM); - if (totalHoursMDouble > 0) - { - //تبیدل دقیه به اعشار - totalHoursMDouble = totalHoursMDouble / 60; - } - //کل ساعت کار پرسنل در این ماه - var totalHours = totalHoursHDouble + totalHoursMDouble;// ساعت کارکرد پرسنل در این ماه - - //var MandatoryDays = TotalDays - friday - officialholiday; - //var MandatoryDays = TotalDays - fridayStartToEnd; - ////اگر حضورغیاب داشت - //if (hasRollCall) - var MandatoryDays = TotalDays - fridayStartToEnd - officialholiday; - - if (!hasRollCall && shiftWork != "4") - MandatoryDays = TotalDays - fridayStartToEnd; - //بدست آوردن ساعت موظفی این ماه - var TotalMandatoryHours = MandatoryDays * 7.33;//ساعت موظفی این ماه - - - //محاسبه سنوات - var yearsResult = (daylyWage * 30) / 365 * TotalDays; - - //محاسبه عیدی و پاداش - var bunosResult = (daylyWage * 60) / 365 * TotalDays; - - - if (weeklyWorkingTime == "24 - 12" || weeklyWorkingTime == "24 - 24" - || weeklyWorkingTime == "36 - 12" || - weeklyWorkingTime == "48 - 24") - { - - if (totalHours < TotalMandatoryHours)//weeklyTimeDouble < 44.00اگر کمتر از 44 ساعت کار کرد - { - - var b = (BasicDayliFee * totalHours) / TotalMandatoryHours; - var dayli = (dayliFeeComplete * totalHours) / TotalMandatoryHours; - - if (basicDouble > 0)//اگر پایه سنوات داشت - { - //حقوق ماهیانه - montlySalaryResult = b * TotalDays; - //پایه سنوات - basicYearResult = (dayli - b) * TotalDays; - } - else// اگر پایه سنوات نداشت - { - //حقوق ماهانه - montlySalaryResult = daylyWage * TotalDays; - //پایه سنوات - basicYearResult = 0; - - } - - } - else - { - - - daylyWage = basicDouble > 0 ? (daylyWage + basicDouble) : daylyWage; - montlyResult = daylyWage * TotalDays;// مزد ماهانه با پایه سنوات - bacicMontlyResult = BasicDayliFee * TotalDays;// مزد ماهانه بدون پایه سنوات - - if (montlyResult > bacicMontlyResult) - { - - montlySalaryResult = bacicMontlyResult; - basicYearResult = montlyResult - bacicMontlyResult; - } - else - { - montlySalaryResult = montlyResult; - } - } - - - } - else - { - //double weeklyTimeDouble = 0; - //try - //{ - // weeklyTimeDouble = double.Parse(weeklyWorkingTime, CultureInfo.InvariantCulture); - //} - //catch (Exception e) - //{ - // weeklyTimeDouble = double.Parse(weeklyWorkingTime); - //} - - - if (totalHours < TotalMandatoryHours)//weeklyTimeDouble < 44.00اگر کمتر از 44 ساعت کار کرد - { - //var divideNum = TimeSpan.Parse("06:00"); - //// مجموع ساعت کار هفته تقسیم بر 6 ساعت - //var dividTo6Days = 34.57 / 6; + private readonly CompanyContext _context; + private readonly ILeftWorkRepository _leftWorkRepository; + private readonly IMandatoryHoursRepository _mandatoryHoursRepository; + private readonly IRollCallEmployeeRepository _rollCallEmployeeRepository; + + + + public YearlySalaryRepository(CompanyContext context, ILeftWorkRepository leftWorkRepository, IMandatoryHoursRepository mandatoryHoursRepository, IRollCallEmployeeRepository rollCallEmployeeRepository) : base(context) + { + _context = context; + _leftWorkRepository = leftWorkRepository; + _mandatoryHoursRepository = mandatoryHoursRepository; + _rollCallEmployeeRepository = rollCallEmployeeRepository; + } + // لیست سال های برای دراپ دان + #region GetYearsToDropDown + public List GetYears() + { + List yearlist = new List(); + PersianDateTime startDate = new PersianDateTime(1370, 1, 1); + DateTime endDateNow = DateTime.Now; + + var endDateNowFa = endDateNow.ToFarsi(); + var y = Convert.ToInt32(endDateNowFa.Substring(0, 4)); + var m = Convert.ToInt32(endDateNowFa.Substring(5, 2)); + var d = Convert.ToInt32(endDateNowFa.Substring(8, 2)); + + PersianDateTime endDate = new PersianDateTime(y, m, d); + + if (m == 12) + endDate.AddYears(1); + for (PersianDateTime date = endDate; date >= startDate; date = date.AddYears(-1)) + { + yearlist.Add(date.ToString("yyyy")); + } + + return yearlist; + } + + #endregion + + //دریافت مقادیر یک سال بر اساس سال انتخاب شده + #region YearlySalaryByYear + + public List GetYearlySalary() + { + return _context.YearlySalaries.Select(x => new YearlySalaryViewModel + { + Id = x.id, + StartDate = x.StartDate.ToFarsi(), + Year = x.Year + + + }) + .OrderByDescending(x => x.Year).ToList(); + } + + #endregion + + + //محاسبه حقوق ماهیانه عیدی و پاداش ، سنوات + #region GetMontlyBunosYears + public MontlywageBunosYearsViewModel GetMontlyBunosYears(TimeSpan weeklyTime, DateTime contractStart, DateTime contractEnd, double daylyWage, + string weeklyWorkingTime, int officialholiday, int friday, string totalHoursH, string totalHorsM, string basic, int fridayStartToEnd, double dayliFeeComplete, bool hasRollCall, bool holidaysWorking, string shiftWork) + { + double basicDouble = basic.MoneyToDouble(); + double sub = 0; + double bacicMontlyResult = 0; + double montlyResult = 0; + + double montlySalaryResult = 0; + double basicYearResult = 0; + var salary = _context.YearlySalaries.OrderByDescending(x => x.EndDate).Include(x => x.YearlySalaryItemsList).ToList(); + + var SalaryItems = + salary.FirstOrDefault(x => x.StartDate <= contractStart && x.EndDate >= contractStart); + var BasicDayliFee = SalaryItems + .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); + var contractEndFa = contractEnd.ToFarsi(); + var TotalDays = (contractEnd - contractStart).TotalDays + 1; + //var DayCounter = Convert.ToInt32(TotalDays); + //var EndOfM = Convert.ToInt32(contractEndFa.Substring(8, 2)); + //if (EndOfM == 31) + //{ + // TotalDays = 30; + //} + + // یدست آوردن کل ساعت کار پرسنل در ماه + var totalHoursHDouble = Convert.ToDouble(totalHoursH); + var totalHoursMDouble = Convert.ToDouble(totalHorsM); + if (totalHoursMDouble > 0) + { + //تبیدل دقیه به اعشار + totalHoursMDouble = totalHoursMDouble / 60; + } + //کل ساعت کار پرسنل در این ماه + var totalHours = totalHoursHDouble + totalHoursMDouble;// ساعت کارکرد پرسنل در این ماه + + //var MandatoryDays = TotalDays - friday - officialholiday; + //var MandatoryDays = TotalDays - fridayStartToEnd; + ////اگر حضورغیاب داشت + //if (hasRollCall) + var MandatoryDays = TotalDays - fridayStartToEnd - officialholiday; + + if (!hasRollCall && shiftWork != "4") + MandatoryDays = TotalDays - fridayStartToEnd; + //بدست آوردن ساعت موظفی این ماه + var TotalMandatoryHours = MandatoryDays * 7.33;//ساعت موظفی این ماه + + + //محاسبه سنوات + var yearsResult = (daylyWage * 30) / 365 * TotalDays; + + //محاسبه عیدی و پاداش + var bunosResult = (daylyWage * 60) / 365 * TotalDays; + + + if (weeklyWorkingTime == "24 - 12" || weeklyWorkingTime == "24 - 24" + || weeklyWorkingTime == "36 - 12" || + weeklyWorkingTime == "48 - 24") + { + + if (totalHours < TotalMandatoryHours)//weeklyTimeDouble < 44.00اگر کمتر از 44 ساعت کار کرد + { + + var b = (BasicDayliFee * totalHours) / TotalMandatoryHours; + var dayli = (dayliFeeComplete * totalHours) / TotalMandatoryHours; + + if (basicDouble > 0)//اگر پایه سنوات داشت + { + //حقوق ماهیانه + montlySalaryResult = b * TotalDays; + //پایه سنوات + basicYearResult = (dayli - b) * TotalDays; + } + else// اگر پایه سنوات نداشت + { + //حقوق ماهانه + montlySalaryResult = daylyWage * TotalDays; + //پایه سنوات + basicYearResult = 0; + + } + + } + else + { + + + daylyWage = basicDouble > 0 ? (daylyWage + basicDouble) : daylyWage; + montlyResult = daylyWage * TotalDays;// مزد ماهانه با پایه سنوات + bacicMontlyResult = BasicDayliFee * TotalDays;// مزد ماهانه بدون پایه سنوات + + if (montlyResult > bacicMontlyResult) + { + + montlySalaryResult = bacicMontlyResult; + basicYearResult = montlyResult - bacicMontlyResult; + } + else + { + montlySalaryResult = montlyResult; + } + } + + + } + else + { + //double weeklyTimeDouble = 0; + //try + //{ + // weeklyTimeDouble = double.Parse(weeklyWorkingTime, CultureInfo.InvariantCulture); + //} + //catch (Exception e) + //{ + // weeklyTimeDouble = double.Parse(weeklyWorkingTime); + //} + + + if (totalHours < TotalMandatoryHours)//weeklyTimeDouble < 44.00اگر کمتر از 44 ساعت کار کرد + { + //var divideNum = TimeSpan.Parse("06:00"); + //// مجموع ساعت کار هفته تقسیم بر 6 ساعت + //var dividTo6Days = 34.57 / 6; - //// مزد روزانه تقسیم بر 7.33 - //var dailyStep1 = BasicDayliFee / 7.33; - ////نتیجه ضربدر جواب مجموع ساعت تقسیم بر 6 روز هفته - //var dailyStep2 = dailyStep1 * dividTo6Days; - //var dailyFeeString = dailyStep2.ToMoney(); - //var dayilyFee = dailyFeeString.MoneyToDouble(); + //// مزد روزانه تقسیم بر 7.33 + //var dailyStep1 = BasicDayliFee / 7.33; + ////نتیجه ضربدر جواب مجموع ساعت تقسیم بر 6 روز هفته + //var dailyStep2 = dailyStep1 * dividTo6Days; + //var dailyFeeString = dailyStep2.ToMoney(); + //var dayilyFee = dailyFeeString.MoneyToDouble(); - //var a = (daylyWage * totalHours) / TotalMandatoryHours; - var b = (BasicDayliFee * totalHours) / TotalMandatoryHours; - var dayli = (dayliFeeComplete * totalHours) / TotalMandatoryHours; - if (basicDouble > 0)//اگر پایه سنوات داشت - { - //حقوق ماهیانه - montlySalaryResult = b * TotalDays; - //پایه سنوات - basicYearResult = (dayli - b) * TotalDays; - } - else// اگر پایه سنوات نداشت - { - //حقوق ماهانه - montlySalaryResult = daylyWage * TotalDays; - //پایه سنوات - basicYearResult = 0; - - } - - //if (sub >= 0) - //{ - // basicYearResult = sub * TotalDays; - // montlySalaryResult = dayilyFee * TotalDays; - //} - //else - //{ - // basicYearResult = 0; - // montlySalaryResult = daylyWage * TotalDays; - - //} + //var a = (daylyWage * totalHours) / TotalMandatoryHours; + var b = (BasicDayliFee * totalHours) / TotalMandatoryHours; + var dayli = (dayliFeeComplete * totalHours) / TotalMandatoryHours; + if (basicDouble > 0)//اگر پایه سنوات داشت + { + //حقوق ماهیانه + montlySalaryResult = b * TotalDays; + //پایه سنوات + basicYearResult = (dayli - b) * TotalDays; + } + else// اگر پایه سنوات نداشت + { + //حقوق ماهانه + montlySalaryResult = daylyWage * TotalDays; + //پایه سنوات + basicYearResult = 0; + + } + + //if (sub >= 0) + //{ + // basicYearResult = sub * TotalDays; + // montlySalaryResult = dayilyFee * TotalDays; + //} + //else + //{ + // basicYearResult = 0; + // montlySalaryResult = daylyWage * TotalDays; + + //} - } - else//اگر بیشتر از 44 ساعت کار کرد - { - //محاسبه حقوق ماهانه - - montlyResult = daylyWage * TotalDays;// مزد ماهانه با پایه سنوات - bacicMontlyResult = BasicDayliFee * TotalDays;// مزد ماهانه بدون پایه سنوات - if (montlyResult > bacicMontlyResult) - { - - montlySalaryResult = bacicMontlyResult; - basicYearResult = montlyResult - bacicMontlyResult; - } - else - { - montlySalaryResult = montlyResult; - } - } - } - + } + else//اگر بیشتر از 44 ساعت کار کرد + { + //محاسبه حقوق ماهانه + + montlyResult = daylyWage * TotalDays;// مزد ماهانه با پایه سنوات + bacicMontlyResult = BasicDayliFee * TotalDays;// مزد ماهانه بدون پایه سنوات + if (montlyResult > bacicMontlyResult) + { + + montlySalaryResult = bacicMontlyResult; + basicYearResult = montlyResult - bacicMontlyResult; + } + else + { + montlySalaryResult = montlyResult; + } + } + } + @@ -286,3577 +289,3616 @@ public class YearlySalaryRepository : RepositoryBase, IYearl - var result = new MontlywageBunosYearsViewModel() - { - MontlyWage = montlySalaryResult,// حقوق ماهانه بدون پایه سنوات - Years = yearsResult,// سنوات - Bunos = bunosResult,//عیدی پاداش - - BasicYears = basicYearResult,//پایه سنوات - SumOfWorkingDay = $"{TotalDays}", - }; - return result; - } - - #endregion - - //مزد مرخصی - #region GetLeavePay - - public double GetLeavePay(DateTime contractStart, DateTime contractEnd, double daylyWage, double consumableItem, - double housingAllowance, double familyAllowance, string weeklyWorkingTime, int officialholiday, int friday, string totalHoursH, string totalHorsM) - { - double result = 0; - var TotalDays = (contractEnd - contractStart).TotalDays + 1; - - - // {مقدار ساعت مجاز مرخصی در برای یک روز{کامل - var leaveHoursesPerDay = 190.58 / 365; - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل - var leaveHoursesPerContractDays = leaveHoursesPerDay * TotalDays; + var result = new MontlywageBunosYearsViewModel() + { + MontlyWage = montlySalaryResult,// حقوق ماهانه بدون پایه سنوات + Years = yearsResult,// سنوات + Bunos = bunosResult,//عیدی پاداش + + BasicYears = basicYearResult,//پایه سنوات + SumOfWorkingDay = $"{TotalDays}", + }; + return result; + } + + #endregion + + //مزد مرخصی + #region GetLeavePay + + public double GetLeavePay(DateTime contractStart, DateTime contractEnd, double daylyWage, double consumableItem, + double housingAllowance, double familyAllowance, string weeklyWorkingTime, int officialholiday, int friday, string totalHoursH, string totalHorsM) + { + double result = 0; + var TotalDays = (contractEnd - contractStart).TotalDays + 1; + + + // {مقدار ساعت مجاز مرخصی در برای یک روز{کامل + var leaveHoursesPerDay = 190.58 / 365; + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل + var leaveHoursesPerContractDays = leaveHoursesPerDay * TotalDays; - if (weeklyWorkingTime == "24 - 12" || weeklyWorkingTime == "24 - 24" - || weeklyWorkingTime == "36 - 12" || - weeklyWorkingTime == "48 - 24") - { - var MandatoryDays = TotalDays - friday - officialholiday; - //بدست آوردن ساعت موظفی این ماه - var TotalMandatoryHours = MandatoryDays * 7.33; - //تبدیل ساعت به عدد - var totalHoursHDouble = Convert.ToDouble(totalHoursH); - var totalHoursMDouble = Convert.ToDouble(totalHorsM); - if (totalHoursMDouble > 0) - { - //تبیدل دقیه به اعشار - totalHoursMDouble = totalHoursMDouble / 60; - } - //کل ساعت کار پرسنل در این ماه - var totalHours = totalHoursHDouble + totalHoursMDouble; + if (weeklyWorkingTime == "24 - 12" || weeklyWorkingTime == "24 - 24" + || weeklyWorkingTime == "36 - 12" || + weeklyWorkingTime == "48 - 24") + { + var MandatoryDays = TotalDays - friday - officialholiday; + //بدست آوردن ساعت موظفی این ماه + var TotalMandatoryHours = MandatoryDays * 7.33; + //تبدیل ساعت به عدد + var totalHoursHDouble = Convert.ToDouble(totalHoursH); + var totalHoursMDouble = Convert.ToDouble(totalHorsM); + if (totalHoursMDouble > 0) + { + //تبیدل دقیه به اعشار + totalHoursMDouble = totalHoursMDouble / 60; + } + //کل ساعت کار پرسنل در این ماه + var totalHours = totalHoursHDouble + totalHoursMDouble; - var employeeWorkingDay = TotalDays - friday; + var employeeWorkingDay = TotalDays - friday; - if (totalHours < TotalMandatoryHours)// اگر کمتر از 44 ساعت کار کرد - { - var dayliHours = totalHours / employeeWorkingDay; + if (totalHours < TotalMandatoryHours)// اگر کمتر از 44 ساعت کار کرد + { + var dayliHours = totalHours / employeeWorkingDay; - //مقدار مزد روزانه برای یک ساعت - var dayliFee = daylyWage / dayliHours; + //مقدار مزد روزانه برای یک ساعت + var dayliFee = daylyWage / dayliHours; - //اقلام مصرفی برای یک ساعت - var ConoumableItemsStep1 = consumableItem / 30; - var ConsumableItems = ConoumableItemsStep1 / dayliHours; + //اقلام مصرفی برای یک ساعت + var ConoumableItemsStep1 = consumableItem / 30; + var ConsumableItems = ConoumableItemsStep1 / dayliHours; - //کمک هزینه مسکن برای یک ساعت - var housingAllowanceStep1 = housingAllowance / 30; - var HousingAllowance = housingAllowanceStep1 / dayliHours; + //کمک هزینه مسکن برای یک ساعت + var housingAllowanceStep1 = housingAllowance / 30; + var HousingAllowance = housingAllowanceStep1 / dayliHours; - //حق عائله مندی برای یک ساعت - var familyAllowanceStep1 = familyAllowance / 30; - var FamilyAllowance = familyAllowanceStep1 / dayliHours; + //حق عائله مندی برای یک ساعت + var familyAllowanceStep1 = familyAllowance / 30; + var FamilyAllowance = familyAllowanceStep1 / dayliHours; - var Step1Result1 = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance; + var Step1Result1 = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance; - // تناسب مجدد به نسبت ساعات کمتر از 7/33 - var res = (leaveHoursesPerContractDays * dayliHours) / 7.33; - result = Step1Result1 * res; - } - else - { - //مقدار مزد روزانه برای یک ساعت - var dayliFee = daylyWage / 7.33; + // تناسب مجدد به نسبت ساعات کمتر از 7/33 + var res = (leaveHoursesPerContractDays * dayliHours) / 7.33; + result = Step1Result1 * res; + } + else + { + //مقدار مزد روزانه برای یک ساعت + var dayliFee = daylyWage / 7.33; - //اقلام مصرفی برای یک ساعت - var ConoumableItemsStep1 = consumableItem / 30; - var ConsumableItems = ConoumableItemsStep1 / 7.33; + //اقلام مصرفی برای یک ساعت + var ConoumableItemsStep1 = consumableItem / 30; + var ConsumableItems = ConoumableItemsStep1 / 7.33; - //کمک هزینه مسکن برای یک ساعت - var housingAllowanceStep1 = housingAllowance / 30; - var HousingAllowance = housingAllowanceStep1 / 7.33; + //کمک هزینه مسکن برای یک ساعت + var housingAllowanceStep1 = housingAllowance / 30; + var HousingAllowance = housingAllowanceStep1 / 7.33; - //حق عائله مندی برای یک ساعت - var familyAllowanceStep1 = familyAllowance / 30; - var FamilyAllowance = familyAllowanceStep1 / 7.33; + //حق عائله مندی برای یک ساعت + var familyAllowanceStep1 = familyAllowance / 30; + var FamilyAllowance = familyAllowanceStep1 / 7.33; - var Step1Result2 = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance; - result = Step1Result2 * leaveHoursesPerContractDays; - } + var Step1Result2 = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance; + result = Step1Result2 * leaveHoursesPerContractDays; + } - } - else - { - double weeklyTime = 0; - try - { - weeklyTime = double.Parse(weeklyWorkingTime, CultureInfo.InvariantCulture); - } - catch (Exception e) - { - weeklyTime = double.Parse(weeklyWorkingTime); - } + } + else + { + double weeklyTime = 0; + try + { + weeklyTime = double.Parse(weeklyWorkingTime, CultureInfo.InvariantCulture); + } + catch (Exception e) + { + weeklyTime = double.Parse(weeklyWorkingTime); + } - if (weeklyTime < 44.00) - { - //بدست آوردن میانگین ساعت کار پرسنل در روز - var personelDayliHours = weeklyTime / 6; - - - //مقدار مزد روزانه برای یک ساعت - var dayliFee = daylyWage / personelDayliHours; - - //اقلام مصرفی برای یک ساعت - var ConoumableItemsStep1 = consumableItem / 30; - var ConsumableItems = ConoumableItemsStep1 / personelDayliHours; - - //کمک هزینه مسکن برای یک ساعت - var housingAllowanceStep1 = housingAllowance / 30; - var HousingAllowance = housingAllowanceStep1 / personelDayliHours; - - //حق عائله مندی برای یک ساعت - var familyAllowanceStep1 = familyAllowance / 30; - var FamilyAllowance = familyAllowanceStep1 / personelDayliHours; - - //مزد مرخصی این پرسنل به ازای یک ساعت - var leavPayPerHours = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance; - - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - var res = (leaveHoursesPerContractDays * personelDayliHours) / 7.33; - result = leavPayPerHours * res; - - } - else - { - //مقدار مزد روزانه برای یک ساعت - var dayliFee = daylyWage / 7.33; - - //اقلام مصرفی برای یک ساعت - var ConoumableItemsStep1 = consumableItem / 30; - var ConsumableItems = ConoumableItemsStep1 / 7.33; + if (weeklyTime < 44.00) + { + //بدست آوردن میانگین ساعت کار پرسنل در روز + var personelDayliHours = weeklyTime / 6; + + + //مقدار مزد روزانه برای یک ساعت + var dayliFee = daylyWage / personelDayliHours; + + //اقلام مصرفی برای یک ساعت + var ConoumableItemsStep1 = consumableItem / 30; + var ConsumableItems = ConoumableItemsStep1 / personelDayliHours; + + //کمک هزینه مسکن برای یک ساعت + var housingAllowanceStep1 = housingAllowance / 30; + var HousingAllowance = housingAllowanceStep1 / personelDayliHours; + + //حق عائله مندی برای یک ساعت + var familyAllowanceStep1 = familyAllowance / 30; + var FamilyAllowance = familyAllowanceStep1 / personelDayliHours; + + //مزد مرخصی این پرسنل به ازای یک ساعت + var leavPayPerHours = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance; + + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + var res = (leaveHoursesPerContractDays * personelDayliHours) / 7.33; + result = leavPayPerHours * res; + + } + else + { + //مقدار مزد روزانه برای یک ساعت + var dayliFee = daylyWage / 7.33; + + //اقلام مصرفی برای یک ساعت + var ConoumableItemsStep1 = consumableItem / 30; + var ConsumableItems = ConoumableItemsStep1 / 7.33; - //کمک هزینه مسکن برای یک ساعت - var housingAllowanceStep1 = housingAllowance / 30; - var HousingAllowance = housingAllowanceStep1 / 7.33; - - //حق عائله مندی برای یک ساعت - var familyAllowanceStep1 = familyAllowance / 30; - var FamilyAllowance = familyAllowanceStep1 / 7.33; - - var leavPayPerHours = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance; - result = leavPayPerHours * leaveHoursesPerContractDays; - } - - } - - - return result; - } - - #endregion - - //اضافه کاری - #region OverTimeWorking - public double GetOverTimeWorking(double dayliWage, string overTimeWorkH, string overTimeWorkM) - { - double result = 0; - - - // اگر اضافه کاری داشت - if (overTimeWorkH != "0" || overTimeWorkM != "0") - { - var overtimeH = Convert.ToDouble(overTimeWorkH); - var overtimeM = Convert.ToDouble(overTimeWorkM); - if (overtimeM > 0) - { - //تبیدل دقیه به اعشار - overtimeM = overtimeM / 60; - } - - var overTime = overtimeH + overtimeM; - - // محاسبه اضافه کاری برای یک ساعت - var oneHouerOverTime = dayliWage / 7.33 * 1.4; - result = oneHouerOverTime * overTime; - - } - - return result; - - - } - #endregion - - //شب کاری - #region OverNightWorking - - public double GetOverNightWorking(double dayliWage, string overNightWorkH, string overNightWorkM, string weeklyWorkingTime, int officialholiday, int friday, DateTime contractStart, DateTime contractEnd, string totalHoursH, string totalHorsM) - { - double result = 0; - double computeResult = 0; - //تعداد روزهای قرارداد + //کمک هزینه مسکن برای یک ساعت + var housingAllowanceStep1 = housingAllowance / 30; + var HousingAllowance = housingAllowanceStep1 / 7.33; + + //حق عائله مندی برای یک ساعت + var familyAllowanceStep1 = familyAllowance / 30; + var FamilyAllowance = familyAllowanceStep1 / 7.33; + + var leavPayPerHours = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance; + result = leavPayPerHours * leaveHoursesPerContractDays; + } + + } + + + return result; + } + + #endregion + + //اضافه کاری + #region OverTimeWorking + public double GetOverTimeWorking(double dayliWage, string overTimeWorkH, string overTimeWorkM) + { + double result = 0; + + + // اگر اضافه کاری داشت + if (overTimeWorkH != "0" || overTimeWorkM != "0") + { + var overtimeH = Convert.ToDouble(overTimeWorkH); + var overtimeM = Convert.ToDouble(overTimeWorkM); + if (overtimeM > 0) + { + //تبیدل دقیه به اعشار + overtimeM = overtimeM / 60; + } + + var overTime = overtimeH + overtimeM; + + // محاسبه اضافه کاری برای یک ساعت + var oneHouerOverTime = dayliWage / 7.33 * 1.4; + result = oneHouerOverTime * overTime; + + } + + return result; + + + } + #endregion + + //شب کاری + #region OverNightWorking + + public double GetOverNightWorking(double dayliWage, string overNightWorkH, string overNightWorkM, string weeklyWorkingTime, int officialholiday, int friday, DateTime contractStart, DateTime contractEnd, string totalHoursH, string totalHorsM) + { + double result = 0; + double computeResult = 0; + //تعداد روزهای قرارداد - if (weeklyWorkingTime == "24 - 12" || weeklyWorkingTime == "24 - 24" - || weeklyWorkingTime == "36 - 12" || - weeklyWorkingTime == "48 - 24") - { - var TotalDays = (contractEnd - contractStart).TotalDays + 1; - //روزهای قرارداد منهای جمعه ها و تعطیلات رسمی - var MandatoryDays = TotalDays - friday - officialholiday; - //بدست آوردن ساعت موظفی این ماه - var TotalMandatoryHours = MandatoryDays * 7.33; - //تبدیل ساعت به عدد - var totalHoursHDouble = Convert.ToDouble(totalHoursH); - var totalHoursMDouble = Convert.ToDouble(totalHorsM); - if (totalHoursMDouble > 0) - { - //تبیدل دقیه به اعشار - totalHoursMDouble = totalHoursMDouble / 60; - } - //کل ساعت کار پرسنل در این ماه - var totalHours = totalHoursHDouble + totalHoursMDouble; - - var employeeWorkingDay = TotalDays - friday; - - - if (overNightWorkH != "0" || overNightWorkM != "0") - { - var overtimeNightH = Convert.ToDouble(overNightWorkH); - var overtimeNightM = Convert.ToDouble(overNightWorkM); - if (overtimeNightM > 0) - { - //تبیدل دقیه به اعشار - overtimeNightM = overtimeNightM / 60; - } - - var overNightTime = overtimeNightH + overtimeNightM; - - //به دست آوردن ساعات کارکرد - - - // محاسبه اضافه کاری برای یک ساعت - if (totalHours < TotalMandatoryHours)// اگر کمتر از 44 ساعت کار کرد - { - //بدست آوردن میانگین ساعت کار کارگر در یک روز - var employeeMonadtory = totalHours / employeeWorkingDay; - computeResult = (dayliWage / employeeMonadtory * 35) / 100; - } - else - { - computeResult = (dayliWage / 7.33 * 35) / 100; - } - - - result = computeResult * overNightTime; - - } - } - else - { - if (overNightWorkH != "0" || overNightWorkM != "0") - { - var overtimeNightH = Convert.ToDouble(overNightWorkH); - var overtimeNightM = Convert.ToDouble(overNightWorkM); - if (overtimeNightM > 0) - { - //تبیدل دقیه به اعشار - overtimeNightM = overtimeNightM / 60; - } - - var overNightTime = overtimeNightH + overtimeNightM; - - //به دست آوردن ساعات کارکرد - double weeklyTime = 0; - try - { - - weeklyTime = double.Parse(weeklyWorkingTime, CultureInfo.InvariantCulture); - } - catch (Exception e) - { - weeklyTime = double.Parse(weeklyWorkingTime); - } - - // محاسبه اضافه کاری برای یک ساعت - if (weeklyTime < 44.00)// اگر کمتر از 44 ساعت کار کرد - { - var dayliHours = weeklyTime / 6; - computeResult = (dayliWage / dayliHours * 35) / 100; - } - else - { - computeResult = (dayliWage / 7.33 * 35) / 100; - } - - - result = computeResult * overNightTime; - - } - - - // اگر شیکاری کاری داشت - - } - - return result; - } - - #endregion - - public void TestDayliFeeCompute() - { - //مقادیر سالانه - var salary = _context.YearlySalaries.Include(i => i.YearlySalaryItemsList).OrderBy(x => x.StartDate).ToList(); - - // یافتن مزد روزانه سال قبل از اولین شروع بکار - var DayliSalaryStep1 = salary.FirstOrDefault(x => x.Year == "1370")! - .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); - var DayliSalaryStep1Fa = DayliSalaryStep1.ToMoney(); - double firstDayliSalary = DayliSalaryStep1Fa.MoneyToDouble(); - - string firstYear = "1370"; - int counter = 0; - foreach (var item in salary) - { - Console.WriteLine($"{item.Year} - {item.ConnectionId}"); - var currentDayliFee = item! - .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); - var fixFeePercentage = item! - .YearlySalaryItemsList.Where(x => x.ItemName == "درصد مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); - // مبلغ مزد ثابت سال جاری - var fixFeePrice = item!.YearlySalaryItemsList - .Where(x => x.ItemName == "مبلغ مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); - - if (counter > 0) - { - if (firstYear == item.Year) - { - int currentYear = Convert.ToInt32(item.Year); - string lastYear = $"{currentYear - 1}"; - firstDayliSalary = salary.Where(x => x.Year == lastYear).MaxBy(x=>x.StartDate)! - .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); - - } - // مزد روزانه سال قبل ضربدر درصد مزد ثابت تقسیم بر صد - var percntSumDaylifee = (firstDayliSalary * fixFeePercentage) / 100; - // نتیجه عملیات بالا بعلاوه مزد سال قبل - var Sum = firstDayliSalary + percntSumDaylifee; - - //مزد پایه - var BaseResult = Sum + fixFeePrice; - var baseResultFa = BaseResult.ToMoney(); - var res = GetCurrectFirstDailyFee(BaseResult,item.Year); - - if (currentDayliFee != res) - { - Console.BackgroundColor = ConsoleColor.DarkRed; - Console.WriteLine($" lastYear : {firstDayliSalary} thisYearOriginal : {currentDayliFee} GetCurrect : {res} falseResut : {BaseResult} "); - Console.ResetColor(); - } - else - { - Console.WriteLine($" lastYear : {firstDayliSalary} thisYearOriginal : {currentDayliFee} GetCurrect : {res} falseResut : {BaseResult} "); - } - - //Console.WriteLine($"{item.Year} defualtFa : {currentDayliFee.ToMoney()} dailFeeFa : {BaseResult.ToMoney()} "); - firstDayliSalary = res; - firstYear = item.Year; - - - } - - counter++; - } - - //مقدار اولیه مزد روزانه - - } - - private double GetCurrectFirstDailyFee(double value,string year) - { - double currected = 0; - switch (year) - { - case "1370": currected = value; - break; - case "1371": currected = value; - break; - case "1372": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1373": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1374": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1375": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1376": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1377": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1378": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1379": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1380": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1381": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1382": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1383": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1384": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1385": - currected = value == 49950.4 ? 50000 : value; - break; - case "1386": - currected = value < 61000 ? 61000 : value; - break; - case "1387": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1388": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1389": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1390": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1391": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1392": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1393": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1394": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1395": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1396": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1397": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1398": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1399": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1400": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1401": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - case "1402": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1403": - currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); - break; - case "1404": - currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); - break; - default: currected = value; - break; - - - } - - return currected; - - } - //محاسبه حقوق روزانه - #region DayliSalary - public DayliFeeViewModel DayliFeeComputing(DateTime startDateW, DateTime contractStart, DateTime endDateW, long employeeId, long workshopId, List leftWorkList) - { - int oldYear = 0; - string oldYearTemp = string.Empty; - var startPeriod = new DateTime(); - var endtPeriod = new DateTime(); - string finalResultMoney = string.Empty; - double FinalResult = 0; - int DayCounter = 0; - int Max365 = 366; - double Basic = 0; - double BaseResult = 0; - DateTime periodStarter = new DateTime(); - int loopdateYear = 0; - long stDateId = 0;//ای دی ماه های دوگانه - double basicResultSum = 0; - //مقادیر سالانه - var salary = _context.YearlySalaries.OrderByDescending(x => x.EndDate).Include(x => x.YearlySalaryItemsList).ToList(); - - - - // تاریخ اولین شروع بکار - var startDateB = leftWorkList.OrderBy(x => x.StartWorkDateGr).Select(x => x.StartWorkDate).FirstOrDefault(); - - //نگهدارنده آی دی سال در مقادیر سالانه - long loopDateId = 0; - - - var syear = Convert.ToInt32(startDateB.Substring(0, 4)); - var smonth = Convert.ToInt32(startDateB.Substring(5, 2)); - var sday = Convert.ToInt32(startDateB.Substring(8, 2)); - - var endDateConvert = endDateW.ToFarsi(); - var eyear = Convert.ToInt32(endDateConvert.Substring(0, 4)); - var emonth = Convert.ToInt32(endDateConvert.Substring(5, 2)); - var eday = Convert.ToInt32(endDateConvert.Substring(8, 2)); - - //تبدیل تاریخ اولین شروع بکار به شمسی تقویمی - var d1 = new PersianDateTime(syear, smonth, sday); - //تبدیل تاریخ پایان قرارداد به شمسی تقویمی - var d2 = new PersianDateTime(eyear, emonth, eday); - - var getWork = startDateB.ToGeorgianDateTime(); - //یافتن سال گزشته - var getWorkYear = syear - 1; - oldYear = syear - 1; - var getWorkYearString = getWorkYear.ToString(); - //var getWorkSalary = salary.FirstOrDefault(x=>x.Year == getWorkYearString); - var dayliSalaryStep1Check = salary.Any(x => x.Year == getWorkYearString); - // یافتن مزد روزانه سال قبل از اولین شروع بکار - var DayliSalaryStep1 = salary.FirstOrDefault(x => x.Year == getWorkYearString) - .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); - - //مقدار اولیه مزد روزانه - var DayliSalaryStep1Fa = DayliSalaryStep1.ToMoney(); - double firstDayliSalary = DayliSalaryStep1Fa.MoneyToDouble(); - - DateTime baseYearDate = new DateTime(); - - for (DateTime LoopDate = getWork; LoopDate <= endDateW; LoopDate = LoopDate.AddDays(1)) - { - var loopdateFa = LoopDate.ToFarsi(); - loopdateYear = Convert.ToInt32(loopdateFa.Substring(0, 4)); - - var LoopDateGr = LoopDate; - //یافتن ترک کار - var check = leftWorkList.Any(x => x.StartWorkDateGr == LoopDateGr); - if (check) - { - var period = leftWorkList.FirstOrDefault(x => x.StartWorkDateGr == LoopDateGr); - //ذخیره تاریخ شروع بکار - startPeriod = period.StartWorkDateGr; - if (period.LeftWorkDate == "1500/01/01") - { - endtPeriod = endDateW; - } - else - { - - endtPeriod = period.LeftWorkDateGr.AddDays(-1); - // ذخیره تاریخ ترک کار - - } - - - } - - - - //اگر تاریخ جاری بزرگتر یت مساوی تاریخ شروع ترک کار و کوچکتر یا مساوی تاریخ پایان ترک کار بود - if (LoopDateGr >= startPeriod && LoopDateGr <= endtPeriod) - { - //اگر شمارنده روزها صفر بود - if (DayCounter == 0) - { - - //var date = LoopDate.ToString(); - // ذهیر تعداد روز های سال جاری بر اساس کبیسه یودن یا نبودن - Max365 = loopdateFa.YearTotalDays(); - } - // یک روز به شمارنده روزها اضافه کن - DayCounter += 1; - - //periodStarter = startPeriod.ContractStartGr; - } - - - //آیا در مقادیر سالانه رکوردی وجود دارد که شروعش از تاریخ جاری کوچکتر و پایانش از تاریخ جاری بزرگتر باشد - var checkExist = salary.Any(x => - x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId); - if (checkExist) - { - var test = loopdateYear.ToString();//سال جاری رو بدست بیار - var step2 = salary.Where(x => x.Year == test).OrderByDescending(x => x.StartDate).ToList();// اونایی رو بیار که سال جاری هستن - if (step2.Count > 1)// اگر تعدادشون بیش از 1 بود - { - - var stDate = step2.FirstOrDefault(); // آخری - - if (DayCounter < Max365) - { - - if (LoopDateGr >= stDate.StartDate && LoopDateGr <= stDate.EndDate && oldYear != loopdateYear && stDate.id != stDateId) - { - - var fixFeePercentage = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) - .YearlySalaryItemsList.Where(x => x.ItemName == "درصد مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); - // مبلغ مزد ثابت سال جاری - var fixFeePrice = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) - .YearlySalaryItemsList.Where(x => x.ItemName == "مبلغ مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); - - // مزد روزانه سال قبل ضربدر درصد مزد ثابت تقسیم بر صد - var percntSumDaylifee = (firstDayliSalary * fixFeePercentage) / 100; - // نتیجه عملیات بالا بعلاوه مزد سال قبل - var Sum = firstDayliSalary + percntSumDaylifee; - - //مزد پایه - BaseResult = Sum + fixFeePrice; - BaseResult = GetCurrectFirstDailyFee(BaseResult, test); - //var rondUp = Convert.ToInt32(BaseResult); - - Console.WriteLine($"{test} - mozdeSaleGhabl[{firstDayliSalary}] - mozdeSaleJari[{BaseResult}] - fixFeePercentage[{fixFeePercentage}] - fixFeePrice[{fixFeePrice}]"); - //آی دی سال جاری - loopDateId = salary.Where(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId).Select(x => x.id).FirstOrDefault(); - // ذخیره سال جاری بعنوان سال گذشته برای عملیات بعدی - oldYear = loopdateYear; - stDateId = stDate.id; - } - else - { - if (BaseResult == 0) - { - var oldYearString = oldYear.ToString(); - var resDouble = salary.FirstOrDefault(x => x.Year == oldYearString) - .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); - var resFa = resDouble.ToMoney(); - BaseResult = resFa.MoneyToDouble(); - - } - - } - - - } - else if (DayCounter == Max365 && oldYear != loopdateYear) - { - - var fixFeePercentage = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) - .YearlySalaryItemsList.Where(x => x.ItemName == "درصد مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); - // مبلغ مزد ثابت سال جاری - var fixFeePrice = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) - .YearlySalaryItemsList.Where(x => x.ItemName == "مبلغ مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); - - // مزد روزانه سال قبل ضربدر درصد مزد ثابت تقسیم بر صد - var percntSumDaylifee = (firstDayliSalary * fixFeePercentage) / 100; - // نتیجه عملیات بالا بعلاوه مزد سال قبل - var Sum = firstDayliSalary + percntSumDaylifee; - //مزد پایه - BaseResult = Sum + fixFeePrice; - //var rondUp = Convert.ToInt32(BaseResult); - BaseResult = GetCurrectFirstDailyFee(BaseResult, test); - Console.WriteLine($"{test} - mozdeSaleGhabl[{firstDayliSalary}] - mozdeSaleJari[{BaseResult}] - fixFeePercentage[{fixFeePercentage}] - fixFeePrice[{fixFeePrice}]"); - - //آی دی سال جاری - loopDateId = salary.Where(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId).Select(x => x.id).FirstOrDefault(); - // ذخیره سال جاری بعنوان سال گذشته برای عملیات بعدی - oldYear = loopdateYear; - } - - } - else if (step2.Count == 1 && oldYear != loopdateYear) - { - //درصد مزد ثابت تاریخ جاری - var fixFeePercentage = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) - .YearlySalaryItemsList.Where(x => x.ItemName == "درصد مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); - // مبلغ مزد ثابت سال جاری - var fixFeePrice = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) - .YearlySalaryItemsList.Where(x => x.ItemName == "مبلغ مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); - - // مزد روزانه سال قبل ضربدر درصد مزد ثابت تقسیم بر صد - var percntSumDaylifee = (firstDayliSalary * fixFeePercentage) / 100; - // نتیجه عملیات بالا بعلاوه مزد سال قبل - var Sum = firstDayliSalary + percntSumDaylifee; - - - //مزد پایه - BaseResult = Sum + fixFeePrice; - BaseResult = GetCurrectFirstDailyFee(BaseResult, test); - //var rondUp = Convert.ToInt32(BaseResult); - - Console.WriteLine($"{test} - mozdeSaleGhabl[{firstDayliSalary}] - mozdeSaleJari[{BaseResult}] - fixFeePercentage[{fixFeePercentage}] - fixFeePrice[{fixFeePrice}]"); - - //آی دی سال جاری - loopDateId = salary.Where(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId).Select(x => x.id).FirstOrDefault(); - // ذخیره سال جاری بعنوان سال گذشته برای عملیات بعدی - oldYear = loopdateYear; - } - } - //اگر شرط بالا صحیح بود و سال جاری از سال گذشته بزرگتر بود اعملیات را انجام بده - //if (checkExist && loopdateYear > oldYear) - //{ - - - //} - - - - - //اگر شمارنده روزها مساوی شد یا 365 - if (DayCounter == Max365) - { - var test = LoopDateGr.ToFarsi(); - var basicSalari = - salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr); - //پایه سنوات سال جاری - Basic = basicSalari - .YearlySalaryItemsList.Where(x => x.ItemName == "پایه سنوات").Select(x => x.ItemValue).FirstOrDefault(); - //پایه سنوات سال جاری بعلاوه مزد پایه - BaseResult += Basic; - basicResultSum += Basic; - Console.BackgroundColor = ConsoleColor.DarkYellow; - Console.WriteLine($"{test} - mozd[{BaseResult}] - Basic[{Basic}]"); - Console.ResetColor(); - //صفر نمودن شمارنده روزها - DayCounter = 0; - } - - //if (loopdateFa == "1398/12/29") - //{ - // Console.WriteLine(BaseResult); - //} - //else if (loopdateFa == "1399/12/30") - //{ - // Console.WriteLine(BaseResult); - //} - //else if (loopdateFa == "1400/12/29") - //{ - // Console.WriteLine(BaseResult); - //} - //else if (loopdateFa == "1401/12/29") - //{ - // Console.WriteLine(BaseResult); - //} - //else if (loopdateFa == "1402/01/29") - //{ - // Console.WriteLine(BaseResult); - //} - - - FinalResult = BaseResult; - //ذخیره نتیجه نهایی مزد پایه - firstDayliSalary = FinalResult; - - } - - //ارسال مزد نهایی بعد از پایان حقه - #region round - - int FinalResultInt = (int)FinalResult; - var FinalResultDouble = (double)FinalResultInt; - #endregion - finalResultMoney = FinalResultDouble.ToMoney(); - - var res = new DayliFeeViewModel() - { - DayliFeeDouble = FinalResultDouble, - DayliFee = finalResultMoney, - Basic = basicResultSum.ToMoney() - }; - return res; - - - - - } - - public async Task DayliFeeComputingAsync(DateTime startDateW, DateTime contractStart, DateTime endDateW, long employeeId, - long workshopId, List leftWorkList) - { - var res = DayliFeeComputing(startDateW, contractStart, endDateW, employeeId, - workshopId, leftWorkList); - return res; - } - - #endregion - - //کمک هزینه اقلام از جدول مقادیر بر اساس سال انتخاب شده - #region ConsumableItems - - public string ConsumableItems(DateTime endDateW) - { - var endDateInput = _context.YearlySalaries - .SingleOrDefault(x => x.StartDate <= endDateW && x.EndDate >= endDateW); - var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "کمک هزینه اقلام"); - var res = FirstItems.ItemValue; - var result = res.ToMoney(); - return result; - } - - #endregion - - //یافتن حق مسکن از جدول مقادیر بر اساس سال انتخاب شده - #region HousingAllowance - - public string HousingAllowance(DateTime endDateW) - { - var endDateInput = _context.YearlySalaries - .SingleOrDefault(x => x.StartDate <= endDateW && x.EndDate >= endDateW); - var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "کمک هزینه مسکن"); - var res = FirstItems.ItemValue; - var result = res.ToMoney(); - return result; - } - - #endregion - - // محاسبه حق عائله مندی پرسنل بر اساس تاریخ ورودی و آی دی پرسنل - #region FamilyAllowance - - public string FamilyAllowance(long personelID, DateTime startContract, DateTime endContract) - { - //DateTime zeroTime = new DateTime(1, 1, 1); - //TimeSpan Age = new TimeSpan(); - - - var endDateInput = _context.YearlySalaries - .SingleOrDefault(x => x.StartDate <= endContract && x.EndDate >= endContract); - var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "مزد روزانه"); - var dayliSalary = FirstItems.ItemValue; - var familyAllowance = dayliSalary * 3; - double sumOfFamilyAllowance = 0; - DateTime firstDayOFContract = endContract.FindFirstDayOfMonthGr(); - if (startContract < firstDayOFContract) - startContract = firstDayOFContract; - var totalContractDays = Convert.ToInt32((endContract - startContract).TotalDays + 1); - try - { - var children = _context.EmployeeChildrenSet.Where(x => x.EmployeeId == personelID).ToList(); - var insuranceYearAndMonth = _context.Employees.SingleOrDefault(x => x.id == personelID); - var yearI = Convert.ToInt32(insuranceYearAndMonth.InsuranceHistoryByYear); - var monthI = Convert.ToInt32(insuranceYearAndMonth.InsuranceHistoryByMonth); - yearI *= 365; - monthI *= 30; - var insurancHistoey = yearI + monthI; - - foreach (var item in children) - { - if (item.DateOfBirth < endContract) - { - //Age = (endContract - item.DateOfBirth); - //var ageUp18 = (zeroTime + Age).Year - 1; - - var childAge = Tools.GetAge(item.DateOfBirth, endContract); - - if (childAge.yearCount < 18 && insurancHistoey >= 720) - { - sumOfFamilyAllowance += familyAllowance; - - } - else if (childAge.yearCount == 18 && childAge.monthCount == 0 && insurancHistoey >= 720) - { - - if (childAge.dayCount > 0) - { - //به دست آوردن روزهای مجاز قبل از 18 سال - var daysToPay = totalContractDays - childAge.dayCount; - - if (daysToPay > 0) - { - //محاسبه مبلغ بر اساس تعداد روزهای مجاز - var payPerDay = (familyAllowance / 30) * daysToPay; - sumOfFamilyAllowance += payPerDay; - } - - } - else - { - sumOfFamilyAllowance += familyAllowance; - } - } - } - - } - } - catch (Exception e) - { - sumOfFamilyAllowance = 0; - } - - //var ress = dayliSalar3 * childeNumber; - - var result = sumOfFamilyAllowance.ToMoney(); - - - return result; - } - - public string FamilyAllowanceAutoExtention(long personelID, DateTime startContract) - { - var endDateInput = _context.YearlySalaries - .SingleOrDefault(x => x.StartDate <= startContract && x.EndDate >= startContract); - var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "مزد روزانه"); - var dayliSalary = FirstItems.ItemValue; - var familyAllowance = dayliSalary * 3; - double sumOfFamilyAllowance = 0; - try - { - var children = _context.EmployeeChildrenSet.Where(x => x.EmployeeId == personelID).ToList(); - var insuranceYearAndMonth = _context.Employees.SingleOrDefault(x => x.id == personelID); - var yearI = Convert.ToInt32(insuranceYearAndMonth.InsuranceHistoryByYear); - var monthI = Convert.ToInt32(insuranceYearAndMonth.InsuranceHistoryByMonth); - yearI *= 365; - monthI *= 30; - var insurancHistoey = yearI + monthI; - - foreach (var item in children) - { - if (item.DateOfBirth < startContract) - { - - - var childAge = Tools.GetAge(item.DateOfBirth, startContract); - - if (childAge.yearCount < 18 && insurancHistoey >= 720) - { - sumOfFamilyAllowance += familyAllowance; - - } - - } - - } - } - catch (Exception e) - { - sumOfFamilyAllowance = 0; - } - - - - var result = sumOfFamilyAllowance.ToMoney(); - - return result; - } - - #endregion - - - #region AsyncMetods - public async Task ConsumableItemsAsync(DateTime endDateW) - { - var res = ConsumableItems(endDateW); - return res; - } - - public async Task HousingAllowanceAsync(DateTime endDateW) - { - var res = HousingAllowance(endDateW); - return res; - } - - public async Task FamilyAllowanceAsync(long personelID, DateTime EndCantract) - { - var res = "FamilyAllowance(personelID, EndCantract);"; - return res; - } - #endregion - - - //جستجوی مقادیر یک سال یا آی دی - #region SerachYearlySalaryById - - public EditYearlySalary GetDetails(long id) - { - return _context.YearlySalaries.Select(x => new EditYearlySalary - { - Id = x.id, - StartDate = x.StartDate.ToFarsi(), - EndDate = x.EndDate.ToFarsi(), - ConnectionId = x.ConnectionId, - - }).FirstOrDefault(x => x.Id == id); - } - - #endregion - - - // سرچ مدل صفحه مقادیر سالانه - #region YearlySalaryMainSerach - - public List Search(YearlySalarySearchModel searchModel) - { - var query = _context.YearlySalaries.Select(x => new YearlySalaryViewModel - { - Id = x.id, - - StartDate = x.StartDate.ToFarsi(), - StartDateGr = x.StartDate, - Year = x.Year, - EndDate = x.EndDate.ToFarsi(), - - - }); - - if (!string.IsNullOrWhiteSpace(searchModel.year)) - { - - - query = query.Where(x => x.Year == searchModel.year); - } - - - return query.OrderByDescending(x => x.StartDateGr).ToList(); - } - #endregion - - - public int FindConnection() - { - int connectionid = 0; - var exist = _context.YearlySalaries.Any(x => x.ConnectionId > 0); - if (exist) - { - connectionid = _context.YearlySalaries.Max(x => x.ConnectionId); - } - else - { - connectionid = 0; - } - return connectionid += 1; - } - - // heydari جستجوی مقادیر با سرچ مدل - #region yearlySalarySearchBySearchModel - - public EditYearlySalary GetDetailsBySearchModel(YearlySalarySearchModel searchModel) - { - var query = _context.YearlySalaries.FirstOrDefault(x => x.StartDate <= searchModel.StartDateGr && x.EndDate >= searchModel.EndDateGr && x.Year == searchModel.year); - if (query != null) - { - var yearlySalariesObj = new EditYearlySalary() - { - Id = query.id, - StartDate = query.StartDate.ToFarsi(), - EndDate = query.EndDate.ToFarsi(), - ConnectionId = query.ConnectionId, - }; - return yearlySalariesObj; - } - else - return null; - } - - #endregion - - // محاسبه حق تاهل - #region MarriedAlloance - public double MarriedAllowance(DateTime endDateW, long employeeId) - { - var getEmployee = _context.Employees.FirstOrDefault(x => x.id == employeeId); - if (getEmployee == null) - { - return 0; - } - - if (getEmployee.MaritalStatus == "متاهل") - { - var endDateInput = _context.YearlySalaries - .SingleOrDefault(x => x.StartDate <= endDateW && x.EndDate >= endDateW); - var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "حق تاهل"); - if (FirstItems == null) - { - return 0; - } - return FirstItems.ItemValue; - } - else - { - return 0; - } - - - } - - - #endregion - - //سنوات - #region yeaers - - public BunosesAndYearsPayStatus Years(DateTime separationStartDate, DateTime leftWorkDate, DateTime separationEndDate, double daylyWage, string yearsOptions, - bool hasleft, DateTime startWorkDate, DateTime contractStart, DateTime contractEnd, long workshopId, long employeeId, bool isOldContract) - { - BunosesAndYearsPayStatus finalResult = new BunosesAndYearsPayStatus(); - var startDateFa = separationEndDate.ToFarsi(); - var checkoutMonth = startDateFa.Substring(5, 2); - double result = 0; - var start1403 = new DateTime(2024, 3, 20); - switch (yearsOptions) - { - case "OnCheckoutOfMonth": - var totalCheckoutDays = (separationEndDate - separationStartDate).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalCheckoutDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalCheckoutDays); - break; - //محاسبه در پایان سال به شرطی که قرارداد منتهی به پایان سال باشد - case "OnEndOfYear"://درپایان سال - - if (isOldContract && contractEnd < start1403) - { - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - else if (isOldContract && contractEnd > start1403) - { - if ((hasleft && leftWorkDate <= separationEndDate) || (checkoutMonth == "12" && separationEndDate == contractEnd)) - { - - //بدست آوردن اولین روز سال - var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - - // اگر تاریخ شروع بکار بزرگتر مساوی روز اول همین سال بود از تازیخ شوع بکار استفاده میشود در غیر اینصورت از روز اول سال استفاده میشود - var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; - - - - #region NewCompute - - //شروع دوره - string st = startComputeDay.ToFarsi(); - int syear = Convert.ToInt32(st.Substring(0, 4)); - int smonth = Convert.ToInt32(st.Substring(5, 2)); - PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); - PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); - //پایان فیش حقوقی آخر - PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); - if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) - { - var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - else - { - var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && - x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); - //پایان دوره - PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); - List nullDateList = new List(); - double sumOfOldYearsPay = 0; - var oldTotaldays = 0; - for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) - { - var searchStart = ($"{startDate}").ToGeorgianDateTime(); - var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); - var foundCheckout = checkoutList.FirstOrDefault(x => - x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); - if (foundCheckout == null) - { - nullDateList.Add(new BunosesAndYearsPayStatus() - { - ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, - ContractEnd = searchEnd - }); - finalResult.NotCompleted = true; - } - else - { - double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; - int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); - double foundDayliWage = foundMonthlySalary / foundTotaldays; - double foundYearsPay = ((foundDayliWage * 30) / 365) * foundTotaldays; - oldTotaldays += foundTotaldays; - sumOfOldYearsPay += foundYearsPay; - } - - } - - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - double lastMonthYearsPay = ((daylyWage * 30) / 365) * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotaldays); - finalResult.YearsPay = lastMonthYearsPay + sumOfOldYearsPay; - finalResult.BunosesStatusList = nullDateList; - - } - - #endregion - } - } - else if (!isOldContract) - - { - if ((hasleft && leftWorkDate <= separationEndDate) || (checkoutMonth == "12" && separationEndDate == contractEnd)) - { - //بدست آوردن اولین روز سال - var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; - #region NewCompute - - //شروع دوره - string st = startComputeDay.ToFarsi(); - int syear = Convert.ToInt32(st.Substring(0, 4)); - int smonth = Convert.ToInt32(st.Substring(5, 2)); - PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); - PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); - //پایان فیش حقوقی آخر - PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); - if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) - { - var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - else - { - var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && - x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); - //پایان دوره - PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); - List nullDateList = new List(); - double sumOfOldYearsPay = 0; - var oldTotaldays = 0; - for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) - { - var searchStart = ($"{startDate}").ToGeorgianDateTime(); - var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); - var foundCheckout = checkoutList.FirstOrDefault(x => - x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); - if (foundCheckout == null) - { - nullDateList.Add(new BunosesAndYearsPayStatus() - { - ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, - ContractEnd = searchEnd - }); - finalResult.NotCompleted = true; - } - else - { - double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; - int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); - double foundDayliWage = foundMonthlySalary / foundTotaldays; - double foundYearsPay = ((foundDayliWage * 30) / 365) * foundTotaldays; - oldTotaldays += foundTotaldays; - sumOfOldYearsPay += foundYearsPay; - } - - } - - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - double lastMonthYearsPay = ((daylyWage * 30) / 365) * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotaldays); - finalResult.YearsPay = lastMonthYearsPay + sumOfOldYearsPay; - finalResult.BunosesStatusList = nullDateList; - - } - - #endregion - //var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - //result = (daylyWage * 30) / 365 * totalDays; - } - } - - break; - //از شروع بکار تا ترک کار - case "OnLeftWork"://درپایان همکاری - - if (isOldContract && contractEnd < start1403) - { - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - else if (isOldContract && contractEnd > start1403) - { - - if ((hasleft && leftWorkDate <= separationEndDate)) - { - //بدست آوردن اولین روز سال - var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - - // اگر تاریخ شروع بکار بزرگتر مساوی روز اول همین سال بود از تازیخ شوع بکار استفاده میشود در غیر اینصورت از روز اول سال استفاده میشود - var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; - var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - } - else if (!isOldContract) - { - if ((hasleft && leftWorkDate <= separationEndDate)) - { - - var totalDays = (separationEndDate - startWorkDate).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - } - - break; - // از شروع قراداد تا پایان قراداد یا ترک کار - case "OnEndOfContract"://در پایان قرارداد - var start1403EndOfContract = new DateTime(2024, 3, 20); - if (isOldContract && contractEnd < start1403EndOfContract) - { - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - else if (isOldContract && contractEnd > start1403) - { - if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd) - { - var totalDays = (separationEndDate - contractStart).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - - } - else if (!isOldContract) - { - if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd) - { - var totalDays = (separationEndDate - contractStart).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - } - - break; - case "EndOfContract1402LeftWork1403": //پایان قرارداد قبل 403 پایان همکاری بعد 403 - - if (contractStart >= start1403 && contractEnd > start1403)// بعد از 1403 - { - if (hasleft && leftWorkDate <= separationEndDate)//اگر ترک کار کرده بود - { - //اگر شروع بکار بعد از 1403 بود تاریخ شرو بکار را در نظر میگیرد در غیر اینصورت اولین روز 1403 را در نظر میگیرد - var startComputeDay = startWorkDate >= start1403 ? startWorkDate : start1403; - var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - } - else if (contractStart < start1403 && contractEnd < start1403)// قبل از 1403 - { - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - //if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd)// اگر ترک کار کرده بود یا فیش آخر قراداد بود - //{ - // var totalDays = (separationEndDate - contractStart).TotalDays + 1; - // result = (daylyWage * 30) / 365 * totalDays; - //} - } - break; - default: - finalResult.YearsPay = 0; - finalResult.TotalDayCompute = 0; - break; - } - - return finalResult; - } - - - - #endregion - //مزد مرخصی - #region LeavePay - - public LeaveAndAbsenceViewModel LeavePay(string startDateFa, DateTime leftWorkDate, DateTime separationStartDate, DateTime separationEndDate, - double daylyWage, string computeOptions, bool hasleft, DateTime startWorkDate, DateTime contractStart, - DateTime contractEnd, long workshopId, long employeeId, int fridayStartToEnd, int officialHoliday, string totalHoursH, string totalHorsM, double consumableItem, - double housingAllowance, double familyAllowance, double marriedAllowance, bool isOldContract) - { - - - var result = new LeaveAndAbsenceViewModel(); - // ماه فیش آخر - var checkoutMonth = startDateFa.Substring(5, 2); - // بدست آوردن مقدار مجاژ مرخصی پرسنل در این فیش - #region HoursPerDay - // روز های کارکرد فیش - var totalChekoutDays = (separationEndDate - separationStartDate).TotalDays + 1; - - //تعداد روزهای موظفی این فیش حقوقی - //var mandatoryWorkingDay = totalChekoutDays - (fridayStartToEnd + officialHoliday); - //تبدیل ساعت به عدد - var totalHoursHDouble = Convert.ToDouble(totalHoursH); - var totalHoursMDouble = Convert.ToDouble(totalHorsM); - if (totalHoursMDouble > 0) - { - //تبیدل دقیه به اعشار - totalHoursMDouble = totalHoursMDouble / 60; - } - //کل ساعت کار پرسنل در این ماه - var totalHours = totalHoursHDouble + totalHoursMDouble; - var checkoutMandatoryDays = _mandatoryHoursRepository.GetMondatoryDays(separationStartDate, separationEndDate); - // میانگین ساعت کارکرد پرسنل در روز - var hoursePerDay = totalHours / checkoutMandatoryDays.MoandatoryDays; - - - // {مقدار ساعت مجاز مرخصی در برای یک روز{کامل - var leaveHoursesPerDay = 190.58 / 365; - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل - - double canToLeave = 0; - - - //مزد مرخصی برای یک ساعت - #region MyRegion - - //مقدار مزد روزانه برای یک ساعت - var LeaveDayliFee = daylyWage / 7.33;// مورد سوم - به این روش برای بک ساعت مرد مرخصی درست است - - //اقلام مصرفی برای یک ساعت - var LeaveConoumableItemsStep1 = consumableItem / totalChekoutDays; - var LeaveConsumableItems = LeaveConoumableItemsStep1 / 7.33; - - //کمک هزینه مسکن برای یک ساعت - var LeavehousingAllowanceStep1 = housingAllowance / totalChekoutDays; - var LeaveHousingAllowance = LeavehousingAllowanceStep1 / 7.33; - - //حق عائله مندی برای یک ساعت - var LeavefamilyAllowanceStep1 = familyAllowance / totalChekoutDays; - var LeaveFamilyAllowance = LeavefamilyAllowanceStep1 / 7.33; - - //حق تاهل برای یک ساعت - var LeavemarriedAllowanceStep1 = marriedAllowance / totalChekoutDays; - var LeaveMarriedAllowance = LeavemarriedAllowanceStep1 / 7.33; - - var leavePayPerHours = LeaveDayliFee + LeaveConsumableItems + LeaveHousingAllowance + LeaveFamilyAllowance + LeaveMarriedAllowance; - - #endregion - - - //غیبت برای یک ساعت - double absenceDeductionPerHourses = leavePayPerHours; - //if (hoursePerDay < 7.33) - //{ - // //مقدار مزد روزانه برای یک ساعت - // var dayliFee = daylyWage / hoursePerDay; - - // //اقلام مصرفی برای یک ساعت - // var ConoumableItemsStep1 = consumableItem / 30; - // var ConsumableItems = ConoumableItemsStep1 / hoursePerDay; - - // //کمک هزینه مسکن برای یک ساعت - // var housingAllowanceStep1 = housingAllowance / 30; - // var HousingAllowance = housingAllowanceStep1 / hoursePerDay; - - // //حق عائله مندی برای یک ساعت - // var familyAllowanceStep1 = familyAllowance / 30; - // var FamilyAllowance = familyAllowanceStep1 / hoursePerDay; - - // //حق تاهل برای یک ساعت - // var marriedAllowanceStep1 = marriedAllowance / 30; - // var MarriedAllowance = marriedAllowanceStep1 / hoursePerDay; - // //مزد مرخصی این پرسنل به ازای یک ساعت - // absenceDeductionPerHourses = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance + MarriedAllowance; - //} - //else - //{ - // //مزد مرخصی این پرسنل به ازای یک ساعت - // absenceDeductionPerHourses = LeaveDayliFee + LeaveConsumableItems + LeaveHousingAllowance + LeaveFamilyAllowance + LeaveMarriedAllowance; - - //} - - #endregion - - //بدست آوردن اولین روز سال - var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - var start1403 = new DateTime(2024, 3, 20); - switch (computeOptions) - { - case "OnCheckoutOfMonth": - var resCanToLeave = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, - leaveHoursesPerDay, totalChekoutDays, hoursePerDay); - - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = resCanToLeave.CanToLeave; - //مزد مرخصی - result.LeavPay = resCanToLeave.CanToLeave * leavePayPerHours; - //مدت غیبت - result.AbsencePeriod = resCanToLeave.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = resCanToLeave.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = hoursePerDay; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{(separationEndDate - separationStartDate).TotalDays + 1}"; - - break; - //محاسبه در پایان سال به شرطی که قرارداد منتهی به پایان سال باشد - case "OnEndOfYear": - if (isOldContract && contractEnd < start1403) - { - var resEndOfYear = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, - leaveHoursesPerDay, totalChekoutDays, hoursePerDay); - - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = resEndOfYear.CanToLeave; - //مزد مرخصی - result.LeavPay = resEndOfYear.CanToLeave * leavePayPerHours; - //مدت غیبت - result.AbsencePeriod = resEndOfYear.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = resEndOfYear.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = hoursePerDay; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{resEndOfYear.CountChekoutDays}"; - - } - else if (isOldContract && contractEnd > start1403) - { - var startDate = startWorkDate >= start1403 ? startWorkDate : start1403; - - var endOfYearRes = EndOfYearCantoleaveList(startDate, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) - .FirstOrDefault(x => x.ContractStart == separationStartDate); - if ((hasleft && leftWorkDate <= separationEndDate) || (separationEndDate == contractEnd && checkoutMonth == "12")) - { - var end = EndOfYearCantoleaveList(startDate, separationEndDate, workshopId, employeeId, - hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, - separationStartDate); - - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - - var canTolv = endOfYearRes.CanToLeave; - var absence = end.Sum(x => x.PeriodOfAbsence); - - if (canTolv >= absence) - { - canTolv -= absence; - absence = 0; - - } - else - { - absence -= canTolv; - canTolv = 0; - - } - - //مزد مرخصی - //result.LeavPay = endOfYearRes.CanToLeave * leavePayPerHours; - result.LeavPay = canTolv * leavePayPerHours; - //مدت غیبت - result.AbsencePeriod = absence; - ////مدت طلب مرخصی - result.CreditLeaves = canTolv; - //کسری غیبت - result.AbsenceDeduction = absence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = end.FirstOrDefault()!.WorkingPerDayHourses; - - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{endOfYearRes.CountChekoutDays}"; - - } - else - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = false; - //مدت طلب مرخصی - result.CreditLeaves = endOfYearRes.CanToLeave; - //مزد مرخصی - result.LeavPay = 0; - //مدت غیبت - result.AbsencePeriod = endOfYearRes.PeriodOfAbsence; - //کسری غیبت - //result.AbsenceDeduction = endOfYearRes.PeriodOfAbsence * absenceDeductionPerHourses; - result.AbsenceDeduction = 0; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = endOfYearRes.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = "0"; - - } - } - else if (!isOldContract) - { - var endOfYearRes = EndOfYearCantoleaveList(startWorkDate, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) - .FirstOrDefault(x => x.ContractStart == separationStartDate); - if ((hasleft && leftWorkDate <= separationEndDate) || (separationEndDate == contractEnd && checkoutMonth == "12")) - { - var end = EndOfYearCantoleaveList(startWorkDate, separationEndDate, workshopId, employeeId, - hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, - separationStartDate); - - var canTolv = endOfYearRes.CanToLeave; - var absence = end.Sum(x => x.PeriodOfAbsence); - if (canTolv >= absence) - { - canTolv -= absence; - absence = 0; - - } - else - { - absence -= canTolv; - canTolv = 0; - - } - - result.LeavPay = canTolv * leavePayPerHours; - //مدت غیبت - result.AbsencePeriod = absence; - ////مدت طلب مرخصی - result.CreditLeaves = canTolv; - //کسری غیبت - result.AbsenceDeduction = absence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = end.FirstOrDefault()!.WorkingPerDayHourses; - - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{endOfYearRes.CountChekoutDays}"; - - //مزد مرخصی - //result.LeavPay = endOfYearRes.CanToLeave * leavePayPerHours; - - //مدت غیبت - //result.AbsencePeriod = endOfYearRes.PeriodOfAbsence; - //کسری غیبت - //result.AbsenceDeduction = endOfYearRes.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - //result.AverageHoursPerDay = endOfYearRes.WorkingPerDayHourses; - - } - else - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = false; - //مدت طلب مرخصی - result.CreditLeaves = endOfYearRes.CanToLeave; - //مزد مرخصی - result.LeavPay = 0; - //مدت غیبت - result.AbsencePeriod = endOfYearRes.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = endOfYearRes.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = endOfYearRes.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = "0"; - - } - } - - break; - case "OnLeftWork"://درپایان همکاری - if (isOldContract && contractEnd < start1403) - { - - var resLeftWork = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, - leaveHoursesPerDay, totalChekoutDays, hoursePerDay); - - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = resLeftWork.CanToLeave; - //مزد مرخصی - result.LeavPay = resLeftWork.CanToLeave * leavePayPerHours; - //مدت غیبت - result.AbsencePeriod = resLeftWork.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = resLeftWork.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = hoursePerDay; - } - else if (isOldContract && contractEnd > start1403) - { - var startDate = startWorkDate >= start1403 ? startWorkDate : start1403; - var res = LeftWorkCantoleaveList(startDate, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) - .FirstOrDefault(x => x.ContractStart == separationStartDate); - - if (hasleft && leftWorkDate <= separationEndDate) - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = 0; - - //مزد مرخصی - result.LeavPay = res.CanToLeave * leavePayPerHours; - - //مدت غیبت - result.AbsencePeriod = res.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = res.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = res.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{res.CountChekoutDays}"; - } - else - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = false; - //مدت طلب مرخصی - result.CreditLeaves = res.CanToLeave; - //مزد مرخصی - result.LeavPay = 0; - //مدت غیبت - result.AbsencePeriod = res.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = res.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = res.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"0"; - - } - - } - else if (!isOldContract) - { - - var res = LeftWorkCantoleaveList(startWorkDate, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) - .FirstOrDefault(x => x.ContractStart == separationStartDate); - - if (hasleft && leftWorkDate <= separationEndDate) - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = 0; - - //مزد مرخصی - result.LeavPay = res.CanToLeave * leavePayPerHours; - - //مدت غیبت - result.AbsencePeriod = res.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = res.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = res.WorkingPerDayHourses; - - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{res.CountChekoutDays}"; - } - else - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = false; - //مدت طلب مرخصی - result.CreditLeaves = res.CanToLeave; - //مزد مرخصی - result.LeavPay = 0; - //مدت غیبت - result.AbsencePeriod = res.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = res.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = res.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"0"; - - } - } - - break; - case "OnEndOfContract"://در پایان قرارداد - if (isOldContract && contractEnd < start1403) - { - var resEndOfContract = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, - leaveHoursesPerDay, totalChekoutDays, hoursePerDay); - - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = resEndOfContract.CanToLeave; - //مزد مرخصی - result.LeavPay = resEndOfContract.CanToLeave * leavePayPerHours; - //مدت غیبت - result.AbsencePeriod = resEndOfContract.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = resEndOfContract.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = hoursePerDay; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{(separationEndDate - separationEndDate).TotalDays + 1}"; - - } - else if ((isOldContract && contractEnd > start1403) || (!isOldContract)) - { - var resEndOfContract = LeftWorkCantoleaveList(contractStart, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) - .FirstOrDefault(x => x.ContractStart == separationStartDate); - if (resEndOfContract != null) - { - if ((hasleft && leftWorkDate <= separationEndDate) || resEndOfContract.LastChekoutOfContract) - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = 0; - - //مزد مرخصی - result.LeavPay = resEndOfContract.CanToLeave * leavePayPerHours; - - //مدت غیبت - result.AbsencePeriod = resEndOfContract.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = resEndOfContract.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = resEndOfContract.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{resEndOfContract.CountChekoutDays}"; - } - else - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = false; - //مدت طلب مرخصی - result.CreditLeaves = resEndOfContract.CanToLeave; - //مزد مرخصی - result.LeavPay = 0; - //مدت غیبت - result.AbsencePeriod = resEndOfContract.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = resEndOfContract.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = resEndOfContract.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"0"; - - } - } - } - break; - case "EndOfContract1402LeftWork1403": //پایان قرارداد قبل 403 پایان همکاری بعد 403 - - if (contractStart >= start1403 && contractEnd > start1403)// بعد از 1403 - { - //تاریخ شروع یافتن قرادادها - var startSearchContracts = startWorkDate >= start1403 ? startWorkDate : start1403; - //تمام قراداد ها از تاریخ شروع تا پایان این فیش - - - - var ress = LeftWorkCantoleaveList(startSearchContracts, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) - .FirstOrDefault(x => x.ContractStart == separationStartDate); - - if (hasleft && leftWorkDate <= separationEndDate) - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = 0; - - //مزد مرخصی - result.LeavPay = ress.CanToLeave * leavePayPerHours; - - //مدت غیبت - result.AbsencePeriod = ress.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = ress.PeriodOfAbsence * absenceDeductionPerHourses; ; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = ress.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{ress.CountChekoutDays}"; - - } - else - { - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = false; - //مدت طلب مرخصی - result.CreditLeaves = ress.CanToLeave; - //مزد مرخصی - result.LeavPay = 0; - //مدت غیبت - result.AbsencePeriod = ress.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = ress.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = ress.WorkingPerDayHourses; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"0"; - - } - } - else if (contractEnd < start1403)// قبل از 1403 - { - var resCanTo1402 = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, - leaveHoursesPerDay, totalChekoutDays, hoursePerDay); - - //وضعیت تصفیه مزد مرخصی - result.LeaveCheckout = true; - ////مدت طلب مرخصی - result.CreditLeaves = resCanTo1402.CanToLeave; - //مزد مرخصی - result.LeavPay = resCanTo1402.CanToLeave * leavePayPerHours; - //مدت غیبت - result.AbsencePeriod = resCanTo1402.PeriodOfAbsence; - //کسری غیبت - result.AbsenceDeduction = resCanTo1402.PeriodOfAbsence * absenceDeductionPerHourses; - //میانگین ساعت کار در یک روز - result.AverageHoursPerDay = hoursePerDay; - // تعداد روزهایی که برای پرسنل مرخصی حساب شده - result.TotalDayOfLeaveCompute = $"{totalChekoutDays}"; - - } - break; - default: - result = new LeaveAndAbsenceViewModel(); - break; - } - - return result; - } - private static TimeSpan CalculateBreakTime(TimeSpan breakTimeSpan, TimeSpan sumOneDaySpan) - { - if (breakTimeSpan * 2 >= sumOneDaySpan) - return new TimeSpan(); - return breakTimeSpan; ; - } - - private (bool hasRollCall, double WorkingTotalHours) GetTotalWorkingHoursIfHasRollCall(long employeeId,long workshopId, DateTime contractStart, DateTime contractEnd) - { - bool hasRollCall = _rollCallEmployeeRepository.HasRollCallRecord(employeeId, workshopId, - contractStart, contractEnd); - double totalWorkingHours = 0; - if (!hasRollCall) - return (false, 0); - - List rollCallResult; - List groupedRollCall; - - - rollCallResult = _context.RollCalls.Where(x => - x.EmployeeId == employeeId && x.WorkshopId == workshopId && x.StartDate.Value.Date >= contractStart && - x.StartDate.Value.Date <= contractEnd && x.EndDate != null).Select(x => new RollCallViewModel() - { - StartDate = x.StartDate, - EndDate = x.EndDate, - ShiftSpan = (x.EndDate.Value - x.StartDate.Value), - CreationDate = x.ShiftDate, - BreakTimeSpan = x.BreakTimeSpan - }).ToList(); - - groupedRollCall = rollCallResult.GroupBy(x => x.CreationDate.Date).Select(x => new GroupedRollCalls() - { - CreationDate = x.Key, - ShiftList = x.Select(s => new ShiftList() { Start = s.StartDate!.Value, End = s.EndDate!.Value }).ToList(), - HasFriday = x.Any(s => s.StartDate != null && s.EndDate != null && (s.StartDate.Value.DayOfWeek == DayOfWeek.Friday || s.EndDate.Value!.DayOfWeek == DayOfWeek.Friday)), - SumOneDaySpan = new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks)) - CalculateBreakTime(x.First().BreakTimeSpan, - new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))), - - - - }).OrderBy(x => x.CreationDate).ToList(); - - - TimeSpan sumSpans = new TimeSpan(groupedRollCall.Sum(x => x.SumOneDaySpan.Ticks)); - totalWorkingHours = sumSpans.TotalMinutes / 60; - - return (true, totalWorkingHours); - - - } - public List LeftWorkCantoleaveList(DateTime startDate, DateTime endDate, long workshopId, long employeeId, bool hasleft, DateTime leftWorkDate, int fridayStartToEnd, int officialHoliday, string totalHoursH, string totalHorsM, DateTime separationStartDate) - { - // {مقدار ساعت مجاز مرخصی در برای یک روز{کامل - var leaveHoursesPerDay = 190.58 / 365; - var contactCanToleaveList = new List(); - var allContractsBetween = _context.Contracts.AsSplitQuery().Include(x => x.WorkingHoursList) - .Where(x => x.WorkshopIds == workshopId && x.EmployeeId == employeeId && - x.ContractEnd >= startDate && x.ContarctStart <= endDate).ToList(); - - int mandatoryDays = 0; - double allCanToLeave = 0; - double canToLeave = 0; - int contractCounter = 0; - foreach (var contract in allContractsBetween) - { - contractCounter += 1; - var m = _mandatoryHoursRepository.GetMondatoryDays(contract.ContarctStart, - contract.ContractEnd); - - var workinghoursH = contract.WorkingHoursList.Select(x => x.TotalHoursesH).FirstOrDefault(); - var workinghoursM = contract.WorkingHoursList.Select(x => x.TotalHoursesM).FirstOrDefault(); - workinghoursM = string.IsNullOrWhiteSpace(workinghoursM) ? "0" : workinghoursM; - var workingHoursHDouble = Convert.ToDouble(workinghoursH); - var workingHoursMDouble = Convert.ToDouble(workinghoursM); - - - if (workingHoursMDouble > 0) - { - //تبیدل دقیه به اعشار - workingHoursMDouble = workingHoursMDouble / 60; - } - //کل ساعت کار پرسنل در این ماه - var totalWorkingHours = workingHoursHDouble + workingHoursMDouble; - - #region RollCallSpan - - var contractTotallDays = Convert.ToInt32((contract.ContractEnd - contract.ContarctStart).TotalDays + 1); - if (contractTotallDays <= 31) - { - - var rollCallTotalHoures = GetTotalWorkingHoursIfHasRollCall(employeeId, workshopId, - contract.ContarctStart.Date, contract.ContractEnd.Date); - if (rollCallTotalHoures.hasRollCall) - { - totalWorkingHours = rollCallTotalHoures.WorkingTotalHours; - } - } - - #endregion - // میانگین ساعت کارکرد پرسنل در روز - var workingHoursePerDay = totalWorkingHours / m.MoandatoryDays; - - // از شروع قرارداد تا پایان قرارداد - var totalDays = (contract.ContractEnd - contract.ContarctStart).TotalDays + 1; - double leftChekoutCanToleave = 0; - double leftleaveHoursesPerTotalDays = 0; - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل - var leaveHoursesPerTotalDays = leaveHoursesPerDay * totalDays; - - - double thisContractCanToLeavPerDay = 0; - double leftThisContractCanToLeavePerDay = 0; - if (workingHoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - thisContractCanToLeavPerDay = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - //if (hasleft && leftWorkDate <= endDate) - //{ - // leftThisContractCanToLeavePerDay = (leftleaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - //} - - } - else - { - workingHoursePerDay = 7.33; - thisContractCanToLeavPerDay = leaveHoursesPerTotalDays; - //if (hasleft && leftWorkDate <= endDate) - //{ - // leftThisContractCanToLeavePerDay = leftleaveHoursesPerTotalDays; - //} - - } - //canToLeave = allCanToLeave + thisContractCanToLeavPerDay; - //leftChekoutCanToleave = allCanToLeave + leftThisContractCanToLeavePerDay; - - var sdate = contract.ContarctStart.ToFarsi(); - var edate = contract.ContractEnd.ToFarsi(); - // اگر فیش در قرارداد جاری حلقه بود تا تاریخ پایان فیش برو - if (separationStartDate >= contract.ContarctStart && separationStartDate < contract.ContractEnd) - edate = endDate.ToFarsi(); - var syear = Convert.ToInt32(sdate.Substring(0, 4)); - var smonth = Convert.ToInt32(sdate.Substring(5, 2)); - var sday = Convert.ToInt32(sdate.Substring(8, 2)); - - var eyear = Convert.ToInt32(edate.Substring(0, 4)); - var emonth = Convert.ToInt32(edate.Substring(5, 2)); - var eday = Convert.ToInt32(edate.Substring(8, 2)); - - var d1 = new PersianDateTime(syear, smonth, sday); - var d2 = new PersianDateTime(eyear, emonth, eday); - for (var currntMonth = d1; currntMonth <= d2; currntMonth = currntMonth.AddMonths(1)) - { - var startMonthFa = $"{currntMonth}"; - var startMonthGr = new DateTime(); - if (currntMonth == d1) - { - var d1Fa = $"{d1}"; - startMonthGr = d1Fa.ToGeorgianDateTime(); - } - else - { - var a = $"{startMonthFa.Substring(0, 8)}01"; - startMonthGr = a.ToGeorgianDateTime(); - } - - - var endMonthFa = startMonthFa.FindeEndOfMonth(); - var endMonthGr = endMonthFa.ToGeorgianDateTime(); - bool left = false; - if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) - { - left = true; - - if (endMonthGr > leftWorkDate) - endMonthGr = endDate; - } - #region 365 - - double canToLeavAfter365 = 0; - bool is365 = false; - var countChekoutDays = (int)((endMonthGr - startMonthGr).TotalDays + 1); - var beforeCountDays = contactCanToleaveList.MaxBy(x => x.ContractStart); - if (beforeCountDays != null) - { - if (!beforeCountDays.EndOfYear) - { - var sumCounDays = countChekoutDays + beforeCountDays.CountChekoutDays; - if (sumCounDays > 365) - { - is365 = true; - countChekoutDays = sumCounDays - 365; - - // مقدار ساعت مجاز مرخصی باقی مانده بعد از 365 روز - leaveHoursesPerTotalDays = 7.33 * 9; - if (workingHoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - canToLeavAfter365 = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - } - else - { - - canToLeavAfter365 = leaveHoursesPerTotalDays; - } - } - else - { - countChekoutDays = sumCounDays; - } - } - - } - - - - #endregion - - - var leaveList = _context.LeaveList.AsSplitQuery() - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) - .Where(x => - (x.StartLeave <= startMonthGr && x.EndLeave >= startMonthGr) || - (x.StartLeave <= endMonthGr && x.EndLeave >= endMonthGr) || - (x.StartLeave >= startMonthGr && x.StartLeave <= endMonthGr) || - (x.EndLeave >= startMonthGr && x.EndLeave <= endMonthGr)).ToList(); - //مرخصی استفاده شده در این ماه - double usedLeaves = 0; - if (leaveList.Count > 0) - { - foreach (var item in leaveList) - { - var start = new DateTime(); - var end = new DateTime(); - start = item.StartLeave < startDate ? startDate : item.StartLeave; - end = item.EndLeave > endDate ? endDate : item.EndLeave; - if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) - { - - var leaveSpan = (end - start).TotalDays + 1; - var usedLeave = leaveSpan * workingHoursePerDay; - usedLeaves += usedLeave; - } - else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) - { - var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - else - { - - var leavingHourses = TimeSpan.Parse(item.LeaveHourses); - var usedLeave = (leavingHourses.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - - } - } - - - - //طلب مرخصی این ماه - double creditLeaves = 0; - // مزد مرخصی - double leavePay = 0; - //مدت غیبت - double periodOfAbsence = 0; - double absenceDeduction = 0; - var beforContactCanToleave = new ContractsCanToLeave(); - var beforContractCount = contractCounter - 1; - if (contactCanToleaveList.Count > 0) - { - //آخری قبل از این - beforContactCanToleave = contactCanToleaveList.MaxBy(x => x.ContractStart); - canToLeave = beforContactCanToleave.CanToLeave; - if (beforContactCanToleave.LastChekoutOfContract) - canToLeave = thisContractCanToLeavPerDay + beforContactCanToleave.CanToLeave; - if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) - { - if (canToLeave > 0) - { - #region LeftChekoutCanToLeave - - var leftMonthtotalDays = Convert.ToInt32((leftWorkDate - contract.ContarctStart).TotalDays + 1); - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{ترک کار شده - leaveHoursesPerTotalDays = leaveHoursesPerDay * leftMonthtotalDays; - if (workingHoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - thisContractCanToLeavPerDay = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - } - else - { - workingHoursePerDay = 7.33; - thisContractCanToLeavPerDay = leaveHoursesPerTotalDays; - } - - - if (contactCanToleaveList.Any(x => x.LastChekoutOfContract && x.ContractCounter == beforContractCount)) - { - - var b = contactCanToleaveList.FirstOrDefault(x => - x.LastChekoutOfContract && x.ContractCounter == beforContractCount); - canToLeave = thisContractCanToLeavPerDay + b.CanToLeave; - } - else - { - canToLeave = thisContractCanToLeavPerDay; - } - leaveList = _context.LeaveList.AsSplitQuery() - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) - .Where(x => - (x.StartLeave <= contract.ContarctStart && x.EndLeave >= contract.ContarctStart) || - (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || - (x.StartLeave >= contract.ContarctStart && x.StartLeave <= leftWorkDate) || - (x.EndLeave >= contract.ContarctStart && x.EndLeave <= leftWorkDate)).ToList(); - usedLeaves = 0; - if (leaveList.Count > 0) - { - foreach (var item in leaveList) - { - var start = new DateTime(); - var end = new DateTime(); - start = item.StartLeave < startDate ? startDate : item.StartLeave; - end = item.EndLeave > endDate ? endDate : item.EndLeave; - if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) - { - - var leaveSpan = (end - start).TotalDays + 1; - var usedLeave = leaveSpan * workingHoursePerDay; - usedLeaves += usedLeave; - } - else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) - { - var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - else - { - var leavingHourses = TimeSpan.Parse(item.LeaveHourses); - var usedLeave = (leavingHourses.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - - } - } - - - - #endregion - - } - else - { - var checkAbsenceDeduction = contactCanToleaveList - .Where(x => x.CanToLeave == 0 && x.ContractStart >= contract.ContarctStart).MaxBy(x => x.ContractStart); - if (checkAbsenceDeduction != null) - { - - var startSerach = checkAbsenceDeduction.ContractEnd.AddDays(1); - leaveList = _context.LeaveList.AsSplitQuery() - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) - .Where(x => - (x.StartLeave <= startSerach && x.EndLeave >= startSerach) || - (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || - (x.StartLeave >= startSerach && x.StartLeave <= leftWorkDate) || - (x.EndLeave >= startSerach && x.EndLeave <= leftWorkDate)).ToList(); - usedLeaves = 0; - if (leaveList.Count > 0) - { - foreach (var item in leaveList) - { - var start = new DateTime(); - var end = new DateTime(); - start = item.StartLeave < startSerach ? startSerach : item.StartLeave; - end = item.EndLeave > leftWorkDate ? leftWorkDate : item.EndLeave; - if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) - { - - var leaveSpan = (end - start).TotalDays + 1; - var usedLeave = leaveSpan * workingHoursePerDay; - usedLeaves += usedLeave; - } - else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) - { - var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - else - { - var leavingHourses = TimeSpan.Parse(item.LeaveHourses); - var usedLeave = (leavingHourses.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - - } - } - } - } - - - - } - - } - else - { - canToLeave = thisContractCanToLeavPerDay; - if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) - { - var leftMonthtotalDays = Convert.ToInt32((leftWorkDate - contract.ContarctStart).TotalDays + 1); - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل - leaveHoursesPerTotalDays = leaveHoursesPerDay * leftMonthtotalDays; - if (workingHoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - canToLeave = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - } - else - { - workingHoursePerDay = 7.33; - canToLeave = leaveHoursesPerTotalDays; - } - } - - - - } + if (weeklyWorkingTime == "24 - 12" || weeklyWorkingTime == "24 - 24" + || weeklyWorkingTime == "36 - 12" || + weeklyWorkingTime == "48 - 24") + { + var TotalDays = (contractEnd - contractStart).TotalDays + 1; + //روزهای قرارداد منهای جمعه ها و تعطیلات رسمی + var MandatoryDays = TotalDays - friday - officialholiday; + //بدست آوردن ساعت موظفی این ماه + var TotalMandatoryHours = MandatoryDays * 7.33; + //تبدیل ساعت به عدد + var totalHoursHDouble = Convert.ToDouble(totalHoursH); + var totalHoursMDouble = Convert.ToDouble(totalHorsM); + if (totalHoursMDouble > 0) + { + //تبیدل دقیه به اعشار + totalHoursMDouble = totalHoursMDouble / 60; + } + //کل ساعت کار پرسنل در این ماه + var totalHours = totalHoursHDouble + totalHoursMDouble; + + var employeeWorkingDay = TotalDays - friday; + + + if (overNightWorkH != "0" || overNightWorkM != "0") + { + var overtimeNightH = Convert.ToDouble(overNightWorkH); + var overtimeNightM = Convert.ToDouble(overNightWorkM); + if (overtimeNightM > 0) + { + //تبیدل دقیه به اعشار + overtimeNightM = overtimeNightM / 60; + } + + var overNightTime = overtimeNightH + overtimeNightM; + + //به دست آوردن ساعات کارکرد + + + // محاسبه اضافه کاری برای یک ساعت + if (totalHours < TotalMandatoryHours)// اگر کمتر از 44 ساعت کار کرد + { + //بدست آوردن میانگین ساعت کار کارگر در یک روز + var employeeMonadtory = totalHours / employeeWorkingDay; + computeResult = (dayliWage / employeeMonadtory * 35) / 100; + } + else + { + computeResult = (dayliWage / 7.33 * 35) / 100; + } + + + result = computeResult * overNightTime; + + } + } + else + { + if (overNightWorkH != "0" || overNightWorkM != "0") + { + var overtimeNightH = Convert.ToDouble(overNightWorkH); + var overtimeNightM = Convert.ToDouble(overNightWorkM); + if (overtimeNightM > 0) + { + //تبیدل دقیه به اعشار + overtimeNightM = overtimeNightM / 60; + } + + var overNightTime = overtimeNightH + overtimeNightM; + + //به دست آوردن ساعات کارکرد + double weeklyTime = 0; + try + { + + weeklyTime = double.Parse(weeklyWorkingTime, CultureInfo.InvariantCulture); + } + catch (Exception e) + { + weeklyTime = double.Parse(weeklyWorkingTime); + } + + // محاسبه اضافه کاری برای یک ساعت + if (weeklyTime < 44.00)// اگر کمتر از 44 ساعت کار کرد + { + var dayliHours = weeklyTime / 6; + computeResult = (dayliWage / dayliHours * 35) / 100; + } + else + { + computeResult = (dayliWage / 7.33 * 35) / 100; + } + + + result = computeResult * overNightTime; + + } + + + // اگر شیکاری کاری داشت + + } + + return result; + } + + #endregion + + public void TestDayliFeeCompute() + { + //مقادیر سالانه + var salary = _context.YearlySalaries.Include(i => i.YearlySalaryItemsList).OrderBy(x => x.StartDate).ToList(); + + // یافتن مزد روزانه سال قبل از اولین شروع بکار + var DayliSalaryStep1 = salary.FirstOrDefault(x => x.Year == "1370")! + .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); + var DayliSalaryStep1Fa = DayliSalaryStep1.ToMoney(); + double firstDayliSalary = DayliSalaryStep1Fa.MoneyToDouble(); + + string firstYear = "1370"; + int counter = 0; + foreach (var item in salary) + { + Console.WriteLine($"{item.Year} - {item.ConnectionId}"); + var currentDayliFee = item! + .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); + var fixFeePercentage = item! + .YearlySalaryItemsList.Where(x => x.ItemName == "درصد مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); + // مبلغ مزد ثابت سال جاری + var fixFeePrice = item!.YearlySalaryItemsList + .Where(x => x.ItemName == "مبلغ مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); + + if (counter > 0) + { + if (firstYear == item.Year) + { + int currentYear = Convert.ToInt32(item.Year); + string lastYear = $"{currentYear - 1}"; + firstDayliSalary = salary.Where(x => x.Year == lastYear).MaxBy(x => x.StartDate)! + .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); + + } + // مزد روزانه سال قبل ضربدر درصد مزد ثابت تقسیم بر صد + var percntSumDaylifee = (firstDayliSalary * fixFeePercentage) / 100; + // نتیجه عملیات بالا بعلاوه مزد سال قبل + var Sum = firstDayliSalary + percntSumDaylifee; + + //مزد پایه + var BaseResult = Sum + fixFeePrice; + var baseResultFa = BaseResult.ToMoney(); + var res = GetCurrectFirstDailyFee(BaseResult, item.Year); + + if (currentDayliFee != res) + { + Console.BackgroundColor = ConsoleColor.DarkRed; + Console.WriteLine($" lastYear : {firstDayliSalary} thisYearOriginal : {currentDayliFee} GetCurrect : {res} falseResut : {BaseResult} "); + Console.ResetColor(); + } + else + { + Console.WriteLine($" lastYear : {firstDayliSalary} thisYearOriginal : {currentDayliFee} GetCurrect : {res} falseResut : {BaseResult} "); + } + + //Console.WriteLine($"{item.Year} defualtFa : {currentDayliFee.ToMoney()} dailFeeFa : {BaseResult.ToMoney()} "); + firstDayliSalary = res; + firstYear = item.Year; + + + } + + counter++; + } + + //مقدار اولیه مزد روزانه + + } + + private double GetCurrectFirstDailyFee(double value, string year) + { + double currected = 0; + switch (year) + { + case "1370": + currected = value; + break; + case "1371": + currected = value; + break; + case "1372": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1373": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1374": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1375": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1376": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1377": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1378": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1379": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1380": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1381": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1382": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1383": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1384": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1385": + currected = value == 49950.4 ? 50000 : value; + break; + case "1386": + currected = value < 61000 ? 61000 : value; + break; + case "1387": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1388": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1389": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1390": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1391": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1392": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1393": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1394": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1395": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1396": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1397": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1398": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1399": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1400": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1401": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + case "1402": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1403": + currected = Math.Round(value, MidpointRounding.ToNegativeInfinity); + break; + case "1404": + currected = Math.Round(value, MidpointRounding.ToPositiveInfinity); + break; + default: + currected = value; + break; + + + } + + return currected; + + } + //محاسبه حقوق روزانه + #region DayliSalary + public DayliFeeViewModel DayliFeeComputing(DateTime startDateW, DateTime contractStart, DateTime endDateW, long employeeId, long workshopId, List leftWorkList) + { + int oldYear = 0; + string oldYearTemp = string.Empty; + var startPeriod = new DateTime(); + var endtPeriod = new DateTime(); + string finalResultMoney = string.Empty; + double FinalResult = 0; + int DayCounter = 0; + int Max365 = 366; + double Basic = 0; + double BaseResult = 0; + DateTime periodStarter = new DateTime(); + int loopdateYear = 0; + long stDateId = 0;//ای دی ماه های دوگانه + double basicResultSum = 0; + //مقادیر سالانه + var salary = _context.YearlySalaries.OrderByDescending(x => x.EndDate).Include(x => x.YearlySalaryItemsList).ToList(); + + + + // تاریخ اولین شروع بکار + var startDateB = leftWorkList.OrderBy(x => x.StartWorkDateGr).Select(x => x.StartWorkDate).FirstOrDefault(); + + //نگهدارنده آی دی سال در مقادیر سالانه + long loopDateId = 0; + + + var syear = Convert.ToInt32(startDateB.Substring(0, 4)); + var smonth = Convert.ToInt32(startDateB.Substring(5, 2)); + var sday = Convert.ToInt32(startDateB.Substring(8, 2)); + + var endDateConvert = endDateW.ToFarsi(); + var eyear = Convert.ToInt32(endDateConvert.Substring(0, 4)); + var emonth = Convert.ToInt32(endDateConvert.Substring(5, 2)); + var eday = Convert.ToInt32(endDateConvert.Substring(8, 2)); + + //تبدیل تاریخ اولین شروع بکار به شمسی تقویمی + var d1 = new PersianDateTime(syear, smonth, sday); + //تبدیل تاریخ پایان قرارداد به شمسی تقویمی + var d2 = new PersianDateTime(eyear, emonth, eday); + + var getWork = startDateB.ToGeorgianDateTime(); + //یافتن سال گزشته + var getWorkYear = syear - 1; + oldYear = syear - 1; + var getWorkYearString = getWorkYear.ToString(); + //var getWorkSalary = salary.FirstOrDefault(x=>x.Year == getWorkYearString); + var dayliSalaryStep1Check = salary.Any(x => x.Year == getWorkYearString); + // یافتن مزد روزانه سال قبل از اولین شروع بکار + var DayliSalaryStep1 = salary.FirstOrDefault(x => x.Year == getWorkYearString) + .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); + + //مقدار اولیه مزد روزانه + var DayliSalaryStep1Fa = DayliSalaryStep1.ToMoney(); + double firstDayliSalary = DayliSalaryStep1Fa.MoneyToDouble(); + + DateTime baseYearDate = new DateTime(); + + for (DateTime LoopDate = getWork; LoopDate <= endDateW; LoopDate = LoopDate.AddDays(1)) + { + var loopdateFa = LoopDate.ToFarsi(); + loopdateYear = Convert.ToInt32(loopdateFa.Substring(0, 4)); + + var LoopDateGr = LoopDate; + //یافتن ترک کار + var check = leftWorkList.Any(x => x.StartWorkDateGr == LoopDateGr); + if (check) + { + var period = leftWorkList.FirstOrDefault(x => x.StartWorkDateGr == LoopDateGr); + //ذخیره تاریخ شروع بکار + startPeriod = period.StartWorkDateGr; + if (period.LeftWorkDate == "1500/01/01") + { + endtPeriod = endDateW; + } + else + { + + endtPeriod = period.LeftWorkDateGr.AddDays(-1); + // ذخیره تاریخ ترک کار + + } + + + } + + + + //اگر تاریخ جاری بزرگتر یت مساوی تاریخ شروع ترک کار و کوچکتر یا مساوی تاریخ پایان ترک کار بود + if (LoopDateGr >= startPeriod && LoopDateGr <= endtPeriod) + { + //اگر شمارنده روزها صفر بود + if (DayCounter == 0) + { + + //var date = LoopDate.ToString(); + // ذهیر تعداد روز های سال جاری بر اساس کبیسه یودن یا نبودن + Max365 = loopdateFa.YearTotalDays(); + } + // یک روز به شمارنده روزها اضافه کن + DayCounter += 1; + + //periodStarter = startPeriod.ContractStartGr; + } + + + //آیا در مقادیر سالانه رکوردی وجود دارد که شروعش از تاریخ جاری کوچکتر و پایانش از تاریخ جاری بزرگتر باشد + var checkExist = salary.Any(x => + x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId); + if (checkExist) + { + var test = loopdateYear.ToString();//سال جاری رو بدست بیار + var step2 = salary.Where(x => x.Year == test).OrderByDescending(x => x.StartDate).ToList();// اونایی رو بیار که سال جاری هستن + if (step2.Count > 1)// اگر تعدادشون بیش از 1 بود + { + + var stDate = step2.FirstOrDefault(); // آخری + + if (DayCounter < Max365) + { + + if (LoopDateGr >= stDate.StartDate && LoopDateGr <= stDate.EndDate && oldYear != loopdateYear && stDate.id != stDateId) + { + + var fixFeePercentage = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) + .YearlySalaryItemsList.Where(x => x.ItemName == "درصد مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); + // مبلغ مزد ثابت سال جاری + var fixFeePrice = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) + .YearlySalaryItemsList.Where(x => x.ItemName == "مبلغ مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); + + // مزد روزانه سال قبل ضربدر درصد مزد ثابت تقسیم بر صد + var percntSumDaylifee = (firstDayliSalary * fixFeePercentage) / 100; + // نتیجه عملیات بالا بعلاوه مزد سال قبل + var Sum = firstDayliSalary + percntSumDaylifee; + + //مزد پایه + BaseResult = Sum + fixFeePrice; + BaseResult = GetCurrectFirstDailyFee(BaseResult, test); + //var rondUp = Convert.ToInt32(BaseResult); + + Console.WriteLine($"{test} - mozdeSaleGhabl[{firstDayliSalary}] - mozdeSaleJari[{BaseResult}] - fixFeePercentage[{fixFeePercentage}] - fixFeePrice[{fixFeePrice}]"); + //آی دی سال جاری + loopDateId = salary.Where(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId).Select(x => x.id).FirstOrDefault(); + // ذخیره سال جاری بعنوان سال گذشته برای عملیات بعدی + oldYear = loopdateYear; + stDateId = stDate.id; + } + else + { + if (BaseResult == 0) + { + var oldYearString = oldYear.ToString(); + var resDouble = salary.FirstOrDefault(x => x.Year == oldYearString) + .YearlySalaryItemsList.Where(x => x.ItemName == "مزد روزانه").Select(x => x.ItemValue).FirstOrDefault(); + var resFa = resDouble.ToMoney(); + BaseResult = resFa.MoneyToDouble(); + + } + + } + + + } + else if (DayCounter == Max365 && oldYear != loopdateYear) + { + + var fixFeePercentage = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) + .YearlySalaryItemsList.Where(x => x.ItemName == "درصد مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); + // مبلغ مزد ثابت سال جاری + var fixFeePrice = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) + .YearlySalaryItemsList.Where(x => x.ItemName == "مبلغ مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); + + // مزد روزانه سال قبل ضربدر درصد مزد ثابت تقسیم بر صد + var percntSumDaylifee = (firstDayliSalary * fixFeePercentage) / 100; + // نتیجه عملیات بالا بعلاوه مزد سال قبل + var Sum = firstDayliSalary + percntSumDaylifee; + //مزد پایه + BaseResult = Sum + fixFeePrice; + //var rondUp = Convert.ToInt32(BaseResult); + BaseResult = GetCurrectFirstDailyFee(BaseResult, test); + Console.WriteLine($"{test} - mozdeSaleGhabl[{firstDayliSalary}] - mozdeSaleJari[{BaseResult}] - fixFeePercentage[{fixFeePercentage}] - fixFeePrice[{fixFeePrice}]"); + + //آی دی سال جاری + loopDateId = salary.Where(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId).Select(x => x.id).FirstOrDefault(); + // ذخیره سال جاری بعنوان سال گذشته برای عملیات بعدی + oldYear = loopdateYear; + } + + } + else if (step2.Count == 1 && oldYear != loopdateYear) + { + //درصد مزد ثابت تاریخ جاری + var fixFeePercentage = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) + .YearlySalaryItemsList.Where(x => x.ItemName == "درصد مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); + // مبلغ مزد ثابت سال جاری + var fixFeePrice = salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId) + .YearlySalaryItemsList.Where(x => x.ItemName == "مبلغ مزد ثابت").Select(x => x.ItemValue).FirstOrDefault(); + + // مزد روزانه سال قبل ضربدر درصد مزد ثابت تقسیم بر صد + var percntSumDaylifee = (firstDayliSalary * fixFeePercentage) / 100; + // نتیجه عملیات بالا بعلاوه مزد سال قبل + var Sum = firstDayliSalary + percntSumDaylifee; + + + //مزد پایه + BaseResult = Sum + fixFeePrice; + BaseResult = GetCurrectFirstDailyFee(BaseResult, test); + //var rondUp = Convert.ToInt32(BaseResult); + + Console.WriteLine($"{test} - mozdeSaleGhabl[{firstDayliSalary}] - mozdeSaleJari[{BaseResult}] - fixFeePercentage[{fixFeePercentage}] - fixFeePrice[{fixFeePrice}]"); + + //آی دی سال جاری + loopDateId = salary.Where(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr && x.id != loopDateId).Select(x => x.id).FirstOrDefault(); + // ذخیره سال جاری بعنوان سال گذشته برای عملیات بعدی + oldYear = loopdateYear; + } + } + //اگر شرط بالا صحیح بود و سال جاری از سال گذشته بزرگتر بود اعملیات را انجام بده + //if (checkExist && loopdateYear > oldYear) + //{ + + + //} + + + + + //اگر شمارنده روزها مساوی شد یا 365 + if (DayCounter == Max365) + { + var test = LoopDateGr.ToFarsi(); + var basicSalari = + salary.FirstOrDefault(x => x.StartDate <= LoopDateGr && x.EndDate >= LoopDateGr); + //پایه سنوات سال جاری + Basic = basicSalari + .YearlySalaryItemsList.Where(x => x.ItemName == "پایه سنوات").Select(x => x.ItemValue).FirstOrDefault(); + //پایه سنوات سال جاری بعلاوه مزد پایه + BaseResult += Basic; + basicResultSum += Basic; + Console.BackgroundColor = ConsoleColor.DarkYellow; + Console.WriteLine($"{test} - mozd[{BaseResult}] - Basic[{Basic}]"); + Console.ResetColor(); + //صفر نمودن شمارنده روزها + DayCounter = 0; + } + + //if (loopdateFa == "1398/12/29") + //{ + // Console.WriteLine(BaseResult); + //} + //else if (loopdateFa == "1399/12/30") + //{ + // Console.WriteLine(BaseResult); + //} + //else if (loopdateFa == "1400/12/29") + //{ + // Console.WriteLine(BaseResult); + //} + //else if (loopdateFa == "1401/12/29") + //{ + // Console.WriteLine(BaseResult); + //} + //else if (loopdateFa == "1402/01/29") + //{ + // Console.WriteLine(BaseResult); + //} + + + FinalResult = BaseResult; + //ذخیره نتیجه نهایی مزد پایه + firstDayliSalary = FinalResult; + + } + + //ارسال مزد نهایی بعد از پایان حقه + #region round + + int FinalResultInt = (int)FinalResult; + var FinalResultDouble = (double)FinalResultInt; + #endregion + finalResultMoney = FinalResultDouble.ToMoney(); + + var res = new DayliFeeViewModel() + { + DayliFeeDouble = FinalResultDouble, + DayliFee = finalResultMoney, + Basic = basicResultSum.ToMoney() + }; + return res; + + + + + } + + public async Task DayliFeeComputingAsync(DateTime startDateW, DateTime contractStart, DateTime endDateW, long employeeId, + long workshopId, List leftWorkList) + { + var res = DayliFeeComputing(startDateW, contractStart, endDateW, employeeId, + workshopId, leftWorkList); + return res; + } + + #endregion + + //کمک هزینه اقلام از جدول مقادیر بر اساس سال انتخاب شده + #region ConsumableItems + + public string ConsumableItems(DateTime endDateW) + { + var endDateInput = _context.YearlySalaries + .SingleOrDefault(x => x.StartDate <= endDateW && x.EndDate >= endDateW); + var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "کمک هزینه اقلام"); + var res = FirstItems.ItemValue; + var result = res.ToMoney(); + return result; + } + + #endregion + + //یافتن حق مسکن از جدول مقادیر بر اساس سال انتخاب شده + #region HousingAllowance + + public string HousingAllowance(DateTime endDateW) + { + var endDateInput = _context.YearlySalaries + .SingleOrDefault(x => x.StartDate <= endDateW && x.EndDate >= endDateW); + var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "کمک هزینه مسکن"); + var res = FirstItems.ItemValue; + var result = res.ToMoney(); + return result; + } + + #endregion + + // محاسبه حق عائله مندی پرسنل بر اساس تاریخ ورودی و آی دی پرسنل + #region FamilyAllowance + + public string FamilyAllowance(long personelID, DateTime startContract, DateTime endContract) + { + //DateTime zeroTime = new DateTime(1, 1, 1); + //TimeSpan Age = new TimeSpan(); + + + var endDateInput = _context.YearlySalaries + .SingleOrDefault(x => x.StartDate <= endContract && x.EndDate >= endContract); + var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "مزد روزانه"); + var dayliSalary = FirstItems.ItemValue; + var familyAllowance = dayliSalary * 3; + double sumOfFamilyAllowance = 0; + DateTime firstDayOFContract = endContract.FindFirstDayOfMonthGr(); + if (startContract < firstDayOFContract) + startContract = firstDayOFContract; + var totalContractDays = Convert.ToInt32((endContract - startContract).TotalDays + 1); + try + { + var children = _context.EmployeeChildrenSet.Where(x => x.EmployeeId == personelID).ToList(); + var insuranceYearAndMonth = _context.Employees.SingleOrDefault(x => x.id == personelID); + var yearI = Convert.ToInt32(insuranceYearAndMonth.InsuranceHistoryByYear); + var monthI = Convert.ToInt32(insuranceYearAndMonth.InsuranceHistoryByMonth); + yearI *= 365; + monthI *= 30; + var insurancHistoey = yearI + monthI; + + foreach (var item in children) + { + if (item.DateOfBirth < endContract) + { + //Age = (endContract - item.DateOfBirth); + //var ageUp18 = (zeroTime + Age).Year - 1; + + var childAge = Tools.GetAge(item.DateOfBirth, endContract); + + if (childAge.yearCount < 18 && insurancHistoey >= 720) + { + sumOfFamilyAllowance += familyAllowance; + + } + else if (childAge.yearCount == 18 && childAge.monthCount == 0 && insurancHistoey >= 720) + { + + if (childAge.dayCount > 0) + { + //به دست آوردن روزهای مجاز قبل از 18 سال + var daysToPay = totalContractDays - childAge.dayCount; + + if (daysToPay > 0) + { + //محاسبه مبلغ بر اساس تعداد روزهای مجاز + var payPerDay = (familyAllowance / 30) * daysToPay; + sumOfFamilyAllowance += payPerDay; + } + + } + else + { + sumOfFamilyAllowance += familyAllowance; + } + } + } + + } + } + catch (Exception e) + { + sumOfFamilyAllowance = 0; + } + + //var ress = dayliSalar3 * childeNumber; + + var result = sumOfFamilyAllowance.ToMoney(); + + + return result; + } + + public string FamilyAllowanceAutoExtention(long personelID, DateTime startContract) + { + var endDateInput = _context.YearlySalaries + .SingleOrDefault(x => x.StartDate <= startContract && x.EndDate >= startContract); + var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "مزد روزانه"); + var dayliSalary = FirstItems.ItemValue; + var familyAllowance = dayliSalary * 3; + double sumOfFamilyAllowance = 0; + try + { + var children = _context.EmployeeChildrenSet.Where(x => x.EmployeeId == personelID).ToList(); + var insuranceYearAndMonth = _context.Employees.SingleOrDefault(x => x.id == personelID); + var yearI = Convert.ToInt32(insuranceYearAndMonth.InsuranceHistoryByYear); + var monthI = Convert.ToInt32(insuranceYearAndMonth.InsuranceHistoryByMonth); + yearI *= 365; + monthI *= 30; + var insurancHistoey = yearI + monthI; + + foreach (var item in children) + { + if (item.DateOfBirth < startContract) + { + + + var childAge = Tools.GetAge(item.DateOfBirth, startContract); + + if (childAge.yearCount < 18 && insurancHistoey >= 720) + { + sumOfFamilyAllowance += familyAllowance; + + } + + } + + } + } + catch (Exception e) + { + sumOfFamilyAllowance = 0; + } + + + + var result = sumOfFamilyAllowance.ToMoney(); + + return result; + } + + #endregion + + + #region AsyncMetods + public async Task ConsumableItemsAsync(DateTime endDateW) + { + var res = ConsumableItems(endDateW); + return res; + } + + public async Task HousingAllowanceAsync(DateTime endDateW) + { + var res = HousingAllowance(endDateW); + return res; + } + + public async Task FamilyAllowanceAsync(long personelID, DateTime EndCantract) + { + var res = "FamilyAllowance(personelID, EndCantract);"; + return res; + } + #endregion + + + //جستجوی مقادیر یک سال یا آی دی + #region SerachYearlySalaryById + + public EditYearlySalary GetDetails(long id) + { + return _context.YearlySalaries.Select(x => new EditYearlySalary + { + Id = x.id, + StartDate = x.StartDate.ToFarsi(), + EndDate = x.EndDate.ToFarsi(), + ConnectionId = x.ConnectionId, + + }).FirstOrDefault(x => x.Id == id); + } + + #endregion + + + // سرچ مدل صفحه مقادیر سالانه + #region YearlySalaryMainSerach + + public List Search(YearlySalarySearchModel searchModel) + { + var query = _context.YearlySalaries.Select(x => new YearlySalaryViewModel + { + Id = x.id, + + StartDate = x.StartDate.ToFarsi(), + StartDateGr = x.StartDate, + Year = x.Year, + EndDate = x.EndDate.ToFarsi(), + + + }); + + if (!string.IsNullOrWhiteSpace(searchModel.year)) + { + + + query = query.Where(x => x.Year == searchModel.year); + } + + + return query.OrderByDescending(x => x.StartDateGr).ToList(); + } + #endregion + + + public int FindConnection() + { + int connectionid = 0; + var exist = _context.YearlySalaries.Any(x => x.ConnectionId > 0); + if (exist) + { + connectionid = _context.YearlySalaries.Max(x => x.ConnectionId); + } + else + { + connectionid = 0; + } + return connectionid += 1; + } + + // heydari جستجوی مقادیر با سرچ مدل + #region yearlySalarySearchBySearchModel + + public EditYearlySalary GetDetailsBySearchModel(YearlySalarySearchModel searchModel) + { + var query = _context.YearlySalaries.FirstOrDefault(x => x.StartDate <= searchModel.StartDateGr && x.EndDate >= searchModel.EndDateGr && x.Year == searchModel.year); + if (query != null) + { + var yearlySalariesObj = new EditYearlySalary() + { + Id = query.id, + StartDate = query.StartDate.ToFarsi(), + EndDate = query.EndDate.ToFarsi(), + ConnectionId = query.ConnectionId, + }; + return yearlySalariesObj; + } + else + return null; + } + + #endregion + + // محاسبه حق تاهل + #region MarriedAlloance + public double MarriedAllowance(DateTime endDateW, long employeeId) + { + var getEmployee = _context.Employees.FirstOrDefault(x => x.id == employeeId); + if (getEmployee == null) + { + return 0; + } + + if (getEmployee.MaritalStatus == "متاهل") + { + var endDateInput = _context.YearlySalaries + .SingleOrDefault(x => x.StartDate <= endDateW && x.EndDate >= endDateW); + var FirstItems = _context.YearlySalaryItems.SingleOrDefault(x => x.YearlySalaryId == endDateInput.id && x.ItemName == "حق تاهل"); + if (FirstItems == null) + { + return 0; + } + return FirstItems.ItemValue; + } + else + { + return 0; + } + + + } + + + #endregion + + //سنوات + #region yeaers + + public BunosesAndYearsPayStatus Years(DateTime separationStartDate, DateTime leftWorkDate, DateTime separationEndDate, double daylyWage, string yearsOptions, + bool hasleft, DateTime startWorkDate, DateTime contractStart, DateTime contractEnd, long workshopId, long employeeId, bool isOldContract) + { + BunosesAndYearsPayStatus finalResult = new BunosesAndYearsPayStatus(); + var startDateFa = separationEndDate.ToFarsi(); + var checkoutMonth = startDateFa.Substring(5, 2); + double result = 0; + var start1403 = new DateTime(2024, 3, 20); + switch (yearsOptions) + { + case "OnCheckoutOfMonth": + var totalCheckoutDays = (separationEndDate - separationStartDate).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalCheckoutDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalCheckoutDays); + break; + //محاسبه در پایان سال به شرطی که قرارداد منتهی به پایان سال باشد + case "OnEndOfYear"://درپایان سال + + if (isOldContract && contractEnd < start1403) + { + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + else if (isOldContract && contractEnd > start1403) + { + if ((hasleft && leftWorkDate <= separationEndDate) || (checkoutMonth == "12" && separationEndDate == contractEnd)) + { + + //بدست آوردن اولین روز سال + var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + + // اگر تاریخ شروع بکار بزرگتر مساوی روز اول همین سال بود از تازیخ شوع بکار استفاده میشود در غیر اینصورت از روز اول سال استفاده میشود + var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; + + + + #region NewCompute + + //شروع دوره + string st = startComputeDay.ToFarsi(); + int syear = Convert.ToInt32(st.Substring(0, 4)); + int smonth = Convert.ToInt32(st.Substring(5, 2)); + PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); + PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); + //پایان فیش حقوقی آخر + PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); + if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) + { + var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + else + { + var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && + x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); + //پایان دوره + PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); + List nullDateList = new List(); + double sumOfOldYearsPay = 0; + var oldTotaldays = 0; + for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) + { + var searchStart = ($"{startDate}").ToGeorgianDateTime(); + var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); + var foundCheckout = checkoutList.FirstOrDefault(x => + x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); + if (foundCheckout == null) + { + nullDateList.Add(new BunosesAndYearsPayStatus() + { + ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, + ContractEnd = searchEnd + }); + finalResult.NotCompleted = true; + } + else + { + double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; + int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); + double foundDayliWage = foundMonthlySalary / foundTotaldays; + double foundYearsPay = ((foundDayliWage * 30) / 365) * foundTotaldays; + oldTotaldays += foundTotaldays; + sumOfOldYearsPay += foundYearsPay; + } + + } + + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + double lastMonthYearsPay = ((daylyWage * 30) / 365) * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotaldays); + finalResult.YearsPay = lastMonthYearsPay + sumOfOldYearsPay; + finalResult.BunosesStatusList = nullDateList; + + } + + #endregion + } + } + else if (!isOldContract) + + { + if ((hasleft && leftWorkDate <= separationEndDate) || (checkoutMonth == "12" && separationEndDate == contractEnd)) + { + //بدست آوردن اولین روز سال + var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; + #region NewCompute + + //شروع دوره + string st = startComputeDay.ToFarsi(); + int syear = Convert.ToInt32(st.Substring(0, 4)); + int smonth = Convert.ToInt32(st.Substring(5, 2)); + PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); + PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); + //پایان فیش حقوقی آخر + PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); + if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) + { + var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + else + { + var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && + x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); + //پایان دوره + PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); + List nullDateList = new List(); + double sumOfOldYearsPay = 0; + var oldTotaldays = 0; + for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) + { + var searchStart = ($"{startDate}").ToGeorgianDateTime(); + var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); + var foundCheckout = checkoutList.FirstOrDefault(x => + x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); + if (foundCheckout == null) + { + nullDateList.Add(new BunosesAndYearsPayStatus() + { + ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, + ContractEnd = searchEnd + }); + finalResult.NotCompleted = true; + } + else + { + double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; + int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); + double foundDayliWage = foundMonthlySalary / foundTotaldays; + double foundYearsPay = ((foundDayliWage * 30) / 365) * foundTotaldays; + oldTotaldays += foundTotaldays; + sumOfOldYearsPay += foundYearsPay; + } + + } + + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + double lastMonthYearsPay = ((daylyWage * 30) / 365) * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotaldays); + finalResult.YearsPay = lastMonthYearsPay + sumOfOldYearsPay; + finalResult.BunosesStatusList = nullDateList; + + } + + #endregion + //var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + //result = (daylyWage * 30) / 365 * totalDays; + } + } + + break; + //از شروع بکار تا ترک کار + case "OnLeftWork"://درپایان همکاری + + if (isOldContract && contractEnd < start1403) + { + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + else if (isOldContract && contractEnd > start1403) + { + + if ((hasleft && leftWorkDate <= separationEndDate)) + { + //بدست آوردن اولین روز سال + var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + + // اگر تاریخ شروع بکار بزرگتر مساوی روز اول همین سال بود از تازیخ شوع بکار استفاده میشود در غیر اینصورت از روز اول سال استفاده میشود + var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; + var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + } + else if (!isOldContract) + { + if ((hasleft && leftWorkDate <= separationEndDate)) + { + + var totalDays = (separationEndDate - startWorkDate).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + } + + break; + // از شروع قراداد تا پایان قراداد یا ترک کار + case "OnEndOfContract"://در پایان قرارداد + var start1403EndOfContract = new DateTime(2024, 3, 20); + if (isOldContract && contractEnd < start1403EndOfContract) + { + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + else if (isOldContract && contractEnd > start1403) + { + if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd) + { + var totalDays = (separationEndDate - contractStart).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + + } + else if (!isOldContract) + { + if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd) + { + var totalDays = (separationEndDate - contractStart).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + } + + break; + case "EndOfContract1402LeftWork1403": //پایان قرارداد قبل 403 پایان همکاری بعد 403 + + if (contractStart >= start1403 && contractEnd > start1403)// بعد از 1403 + { + if (hasleft && leftWorkDate <= separationEndDate)//اگر ترک کار کرده بود + { + //اگر شروع بکار بعد از 1403 بود تاریخ شرو بکار را در نظر میگیرد در غیر اینصورت اولین روز 1403 را در نظر میگیرد + var startComputeDay = startWorkDate >= start1403 ? startWorkDate : start1403; + var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + } + else if (contractStart < start1403 && contractEnd < start1403)// قبل از 1403 + { + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + finalResult.YearsPay = (daylyWage * 30) / 365 * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + //if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd)// اگر ترک کار کرده بود یا فیش آخر قراداد بود + //{ + // var totalDays = (separationEndDate - contractStart).TotalDays + 1; + // result = (daylyWage * 30) / 365 * totalDays; + //} + } + break; + default: + finalResult.YearsPay = 0; + finalResult.TotalDayCompute = 0; + break; + } + + return finalResult; + } + + + + #endregion + //مزد مرخصی + #region LeavePay + + public LeaveAndAbsenceViewModel LeavePay(string startDateFa, DateTime leftWorkDate, DateTime separationStartDate, DateTime separationEndDate, + double daylyWage, string computeOptions, bool hasleft, DateTime startWorkDate, DateTime contractStart, + DateTime contractEnd, long workshopId, long employeeId, int fridayStartToEnd, int officialHoliday, string totalHoursH, string totalHorsM, double consumableItem, + double housingAllowance, double familyAllowance, double marriedAllowance, bool isOldContract) + { + + + var result = new LeaveAndAbsenceViewModel(); + // ماه فیش آخر + var checkoutMonth = startDateFa.Substring(5, 2); + // بدست آوردن مقدار مجاژ مرخصی پرسنل در این فیش + #region HoursPerDay + // روز های کارکرد فیش + var totalChekoutDays = (separationEndDate - separationStartDate).TotalDays + 1; + + //تعداد روزهای موظفی این فیش حقوقی + //var mandatoryWorkingDay = totalChekoutDays - (fridayStartToEnd + officialHoliday); + //تبدیل ساعت به عدد + var totalHoursHDouble = Convert.ToDouble(totalHoursH); + var totalHoursMDouble = Convert.ToDouble(totalHorsM); + if (totalHoursMDouble > 0) + { + //تبیدل دقیه به اعشار + totalHoursMDouble = totalHoursMDouble / 60; + } + //کل ساعت کار پرسنل در این ماه + var totalHours = totalHoursHDouble + totalHoursMDouble; + var checkoutMandatoryDays = _mandatoryHoursRepository.GetMondatoryDays(separationStartDate, separationEndDate); + // میانگین ساعت کارکرد پرسنل در روز + var hoursePerDay = totalHours / checkoutMandatoryDays.MoandatoryDays; + + + // {مقدار ساعت مجاز مرخصی در برای یک روز{کامل + var leaveHoursesPerDay = 190.58 / 365; + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل + + double canToLeave = 0; + + + //مزد مرخصی برای یک ساعت + #region MyRegion + + //مقدار مزد روزانه برای یک ساعت + var LeaveDayliFee = daylyWage / 7.33;// مورد سوم - به این روش برای بک ساعت مرد مرخصی درست است + + //اقلام مصرفی برای یک ساعت + var LeaveConoumableItemsStep1 = consumableItem / totalChekoutDays; + var LeaveConsumableItems = LeaveConoumableItemsStep1 / 7.33; + + //کمک هزینه مسکن برای یک ساعت + var LeavehousingAllowanceStep1 = housingAllowance / totalChekoutDays; + var LeaveHousingAllowance = LeavehousingAllowanceStep1 / 7.33; + + //حق عائله مندی برای یک ساعت + var LeavefamilyAllowanceStep1 = familyAllowance / totalChekoutDays; + var LeaveFamilyAllowance = LeavefamilyAllowanceStep1 / 7.33; + + //حق تاهل برای یک ساعت + var LeavemarriedAllowanceStep1 = marriedAllowance / totalChekoutDays; + var LeaveMarriedAllowance = LeavemarriedAllowanceStep1 / 7.33; + + var leavePayPerHours = LeaveDayliFee + LeaveConsumableItems + LeaveHousingAllowance + LeaveFamilyAllowance + LeaveMarriedAllowance; + + #endregion + + + //غیبت برای یک ساعت + double absenceDeductionPerHourses = leavePayPerHours; + //if (hoursePerDay < 7.33) + //{ + // //مقدار مزد روزانه برای یک ساعت + // var dayliFee = daylyWage / hoursePerDay; + + // //اقلام مصرفی برای یک ساعت + // var ConoumableItemsStep1 = consumableItem / 30; + // var ConsumableItems = ConoumableItemsStep1 / hoursePerDay; + + // //کمک هزینه مسکن برای یک ساعت + // var housingAllowanceStep1 = housingAllowance / 30; + // var HousingAllowance = housingAllowanceStep1 / hoursePerDay; + + // //حق عائله مندی برای یک ساعت + // var familyAllowanceStep1 = familyAllowance / 30; + // var FamilyAllowance = familyAllowanceStep1 / hoursePerDay; + + // //حق تاهل برای یک ساعت + // var marriedAllowanceStep1 = marriedAllowance / 30; + // var MarriedAllowance = marriedAllowanceStep1 / hoursePerDay; + // //مزد مرخصی این پرسنل به ازای یک ساعت + // absenceDeductionPerHourses = dayliFee + ConsumableItems + HousingAllowance + FamilyAllowance + MarriedAllowance; + //} + //else + //{ + // //مزد مرخصی این پرسنل به ازای یک ساعت + // absenceDeductionPerHourses = LeaveDayliFee + LeaveConsumableItems + LeaveHousingAllowance + LeaveFamilyAllowance + LeaveMarriedAllowance; + + //} + + #endregion + + //بدست آوردن اولین روز سال + var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + var start1403 = new DateTime(2024, 3, 20); + switch (computeOptions) + { + case "OnCheckoutOfMonth": + var resCanToLeave = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, + leaveHoursesPerDay, totalChekoutDays, hoursePerDay); + + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = resCanToLeave.CanToLeave; + //مزد مرخصی + result.LeavPay = resCanToLeave.CanToLeave * leavePayPerHours; + //مدت غیبت + result.AbsencePeriod = resCanToLeave.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = resCanToLeave.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = hoursePerDay; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{(separationEndDate - separationStartDate).TotalDays + 1}"; + + break; + //محاسبه در پایان سال به شرطی که قرارداد منتهی به پایان سال باشد + case "OnEndOfYear": + if (isOldContract && contractEnd < start1403) + { + var resEndOfYear = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, + leaveHoursesPerDay, totalChekoutDays, hoursePerDay); + + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = resEndOfYear.CanToLeave; + //مزد مرخصی + result.LeavPay = resEndOfYear.CanToLeave * leavePayPerHours; + //مدت غیبت + result.AbsencePeriod = resEndOfYear.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = resEndOfYear.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = hoursePerDay; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{resEndOfYear.CountChekoutDays}"; + + } + else if (isOldContract && contractEnd > start1403) + { + var startDate = startWorkDate >= start1403 ? startWorkDate : start1403; + + var endOfYearRes = EndOfYearCantoleaveList(startDate, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) + .FirstOrDefault(x => x.ContractStart == separationStartDate); + if ((hasleft && leftWorkDate <= separationEndDate) || (separationEndDate == contractEnd && checkoutMonth == "12")) + { + var end = EndOfYearCantoleaveList(startDate, separationEndDate, workshopId, employeeId, + hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, + separationStartDate); + + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + + var canTolv = endOfYearRes.CanToLeave; + var absence = end.Sum(x => x.PeriodOfAbsence); + + if (canTolv >= absence) + { + canTolv -= absence; + absence = 0; + + } + else + { + absence -= canTolv; + canTolv = 0; + + } + + //مزد مرخصی + //result.LeavPay = endOfYearRes.CanToLeave * leavePayPerHours; + result.LeavPay = canTolv * leavePayPerHours; + //مدت غیبت + result.AbsencePeriod = absence; + ////مدت طلب مرخصی + result.CreditLeaves = canTolv; + //کسری غیبت + result.AbsenceDeduction = absence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = end.FirstOrDefault()!.WorkingPerDayHourses; + + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{endOfYearRes.CountChekoutDays}"; + + } + else + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = false; + //مدت طلب مرخصی + result.CreditLeaves = endOfYearRes.CanToLeave; + //مزد مرخصی + result.LeavPay = 0; + //مدت غیبت + result.AbsencePeriod = endOfYearRes.PeriodOfAbsence; + //کسری غیبت + //result.AbsenceDeduction = endOfYearRes.PeriodOfAbsence * absenceDeductionPerHourses; + result.AbsenceDeduction = 0; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = endOfYearRes.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = "0"; + + } + } + else if (!isOldContract) + { + var endOfYearRes = EndOfYearCantoleaveList(startWorkDate, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) + .FirstOrDefault(x => x.ContractStart == separationStartDate); + if ((hasleft && leftWorkDate <= separationEndDate) || (separationEndDate == contractEnd && checkoutMonth == "12")) + { + var end = EndOfYearCantoleaveList(startWorkDate, separationEndDate, workshopId, employeeId, + hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, + separationStartDate); + + var canTolv = endOfYearRes.CanToLeave; + var absence = end.Sum(x => x.PeriodOfAbsence); + if (canTolv >= absence) + { + canTolv -= absence; + absence = 0; + + } + else + { + absence -= canTolv; + canTolv = 0; + + } + + result.LeavPay = canTolv * leavePayPerHours; + //مدت غیبت + result.AbsencePeriod = absence; + ////مدت طلب مرخصی + result.CreditLeaves = canTolv; + //کسری غیبت + result.AbsenceDeduction = absence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = end.FirstOrDefault()!.WorkingPerDayHourses; + + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{endOfYearRes.CountChekoutDays}"; + + //مزد مرخصی + //result.LeavPay = endOfYearRes.CanToLeave * leavePayPerHours; + + //مدت غیبت + //result.AbsencePeriod = endOfYearRes.PeriodOfAbsence; + //کسری غیبت + //result.AbsenceDeduction = endOfYearRes.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + //result.AverageHoursPerDay = endOfYearRes.WorkingPerDayHourses; + + } + else + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = false; + //مدت طلب مرخصی + result.CreditLeaves = endOfYearRes.CanToLeave; + //مزد مرخصی + result.LeavPay = 0; + //مدت غیبت + result.AbsencePeriod = endOfYearRes.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = endOfYearRes.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = endOfYearRes.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = "0"; + + } + } + + break; + case "OnLeftWork"://درپایان همکاری + if (isOldContract && contractEnd < start1403) + { + + var resLeftWork = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, + leaveHoursesPerDay, totalChekoutDays, hoursePerDay); + + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = resLeftWork.CanToLeave; + //مزد مرخصی + result.LeavPay = resLeftWork.CanToLeave * leavePayPerHours; + //مدت غیبت + result.AbsencePeriod = resLeftWork.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = resLeftWork.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = hoursePerDay; + } + else if (isOldContract && contractEnd > start1403) + { + var startDate = startWorkDate >= start1403 ? startWorkDate : start1403; + var res = LeftWorkCantoleaveList(startDate, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) + .FirstOrDefault(x => x.ContractStart == separationStartDate); + + if (hasleft && leftWorkDate <= separationEndDate) + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = 0; + + //مزد مرخصی + result.LeavPay = res.CanToLeave * leavePayPerHours; + + //مدت غیبت + result.AbsencePeriod = res.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = res.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = res.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{res.CountChekoutDays}"; + } + else + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = false; + //مدت طلب مرخصی + result.CreditLeaves = res.CanToLeave; + //مزد مرخصی + result.LeavPay = 0; + //مدت غیبت + result.AbsencePeriod = res.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = res.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = res.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"0"; + + } + + } + else if (!isOldContract) + { + + var res = LeftWorkCantoleaveList(startWorkDate, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) + .FirstOrDefault(x => x.ContractStart == separationStartDate); + + if (hasleft && leftWorkDate <= separationEndDate) + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = 0; + + //مزد مرخصی + result.LeavPay = res.CanToLeave * leavePayPerHours; + + //مدت غیبت + result.AbsencePeriod = res.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = res.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = res.WorkingPerDayHourses; + + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{res.CountChekoutDays}"; + } + else + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = false; + //مدت طلب مرخصی + result.CreditLeaves = res.CanToLeave; + //مزد مرخصی + result.LeavPay = 0; + //مدت غیبت + result.AbsencePeriod = res.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = res.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = res.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"0"; + + } + } + + break; + case "OnEndOfContract"://در پایان قرارداد + if (isOldContract && contractEnd < start1403) + { + var resEndOfContract = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, + leaveHoursesPerDay, totalChekoutDays, hoursePerDay); + + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = resEndOfContract.CanToLeave; + //مزد مرخصی + result.LeavPay = resEndOfContract.CanToLeave * leavePayPerHours; + //مدت غیبت + result.AbsencePeriod = resEndOfContract.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = resEndOfContract.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = hoursePerDay; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{(separationEndDate - separationEndDate).TotalDays + 1}"; + + } + else if ((isOldContract && contractEnd > start1403) || (!isOldContract)) + { + var resEndOfContract = LeftWorkCantoleaveList(contractStart, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) + .FirstOrDefault(x => x.ContractStart == separationStartDate); + if (resEndOfContract != null) + { + if ((hasleft && leftWorkDate <= separationEndDate) || resEndOfContract.LastChekoutOfContract) + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = 0; + + //مزد مرخصی + result.LeavPay = resEndOfContract.CanToLeave * leavePayPerHours; + + //مدت غیبت + result.AbsencePeriod = resEndOfContract.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = resEndOfContract.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = resEndOfContract.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{resEndOfContract.CountChekoutDays}"; + } + else + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = false; + //مدت طلب مرخصی + result.CreditLeaves = resEndOfContract.CanToLeave; + //مزد مرخصی + result.LeavPay = 0; + //مدت غیبت + result.AbsencePeriod = resEndOfContract.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = resEndOfContract.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = resEndOfContract.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"0"; + + } + } + } + break; + case "EndOfContract1402LeftWork1403": //پایان قرارداد قبل 403 پایان همکاری بعد 403 + + if (contractStart >= start1403 && contractEnd > start1403)// بعد از 1403 + { + //تاریخ شروع یافتن قرادادها + var startSearchContracts = startWorkDate >= start1403 ? startWorkDate : start1403; + //تمام قراداد ها از تاریخ شروع تا پایان این فیش + + + + var ress = LeftWorkCantoleaveList(startSearchContracts, separationEndDate, workshopId, employeeId, hasleft, leftWorkDate, fridayStartToEnd, officialHoliday, totalHoursH, totalHorsM, separationStartDate) + .FirstOrDefault(x => x.ContractStart == separationStartDate); + + if (hasleft && leftWorkDate <= separationEndDate) + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = 0; + + //مزد مرخصی + result.LeavPay = ress.CanToLeave * leavePayPerHours; + + //مدت غیبت + result.AbsencePeriod = ress.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = ress.PeriodOfAbsence * absenceDeductionPerHourses; ; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = ress.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{ress.CountChekoutDays}"; + + } + else + { + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = false; + //مدت طلب مرخصی + result.CreditLeaves = ress.CanToLeave; + //مزد مرخصی + result.LeavPay = 0; + //مدت غیبت + result.AbsencePeriod = ress.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = ress.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = ress.WorkingPerDayHourses; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"0"; + + } + } + else if (contractEnd < start1403)// قبل از 1403 + { + var resCanTo1402 = OnCheckoutCantoleaveList(separationStartDate, separationEndDate, workshopId, employeeId, + leaveHoursesPerDay, totalChekoutDays, hoursePerDay); + + //وضعیت تصفیه مزد مرخصی + result.LeaveCheckout = true; + ////مدت طلب مرخصی + result.CreditLeaves = resCanTo1402.CanToLeave; + //مزد مرخصی + result.LeavPay = resCanTo1402.CanToLeave * leavePayPerHours; + //مدت غیبت + result.AbsencePeriod = resCanTo1402.PeriodOfAbsence; + //کسری غیبت + result.AbsenceDeduction = resCanTo1402.PeriodOfAbsence * absenceDeductionPerHourses; + //میانگین ساعت کار در یک روز + result.AverageHoursPerDay = hoursePerDay; + // تعداد روزهایی که برای پرسنل مرخصی حساب شده + result.TotalDayOfLeaveCompute = $"{totalChekoutDays}"; + + } + break; + default: + result = new LeaveAndAbsenceViewModel(); + break; + } + + return result; + } + private static TimeSpan CalculateBreakTime(BreakTime breakTime, TimeSpan sumOneDaySpan) + { + if (breakTime.BreakTimeType != BreakTimeType.WithTime) + return new TimeSpan(); + + var breakTimeSpan = breakTime.BreakTimeValue.ToTimeSpan(); + + if (breakTimeSpan * 2 >= sumOneDaySpan) + return new TimeSpan(); + + return breakTimeSpan; ; + + } + private static TimeSpan CalculateBreakTime(TimeSpan breakTimeSpan, TimeSpan sumOneDaySpan) + { + if (breakTimeSpan * 2 >= sumOneDaySpan) + return new TimeSpan(); + return breakTimeSpan; ; + } + + private (bool hasRollCall, double WorkingTotalHours) GetTotalWorkingHoursIfHasRollCall(long employeeId, long workshopId, DateTime contractStart, DateTime contractEnd) + { + bool hasRollCall = _rollCallEmployeeRepository.HasRollCallRecord(employeeId, workshopId, + contractStart, contractEnd); + double totalWorkingHours = 0; + if (!hasRollCall) + return (false, 0); + + List rollCallResult; + List groupedRollCall; + + + BaseCustomizeEntity settings = _context.CustomizeWorkshopEmployeeSettings.AsSplitQuery() + .Include(x => x.CustomizeWorkshopGroupSettings).FirstOrDefault(x => + x.WorkshopId == workshopId && x.EmployeeId == employeeId); + //اگر ساعت استراحت پرسنل وجود نداشت صفر است + var breakTimeEntity = settings == null ? new BreakTime(false, new TimeOnly()) : settings.BreakTime; + var endOfFarvardin = "1404/01/31".ToGeorgianDateTime(); + + + rollCallResult = _context.RollCalls.Where(x => + x.EmployeeId == employeeId && x.WorkshopId == workshopId && x.StartDate.Value.Date >= contractStart && + x.StartDate.Value.Date <= contractEnd && x.EndDate != null).Select(x => new RollCallViewModel() + { + StartDate = x.StartDate, + EndDate = x.EndDate, + ShiftSpan = (x.EndDate.Value - x.StartDate.Value), + CreationDate = x.ShiftDate, + BreakTimeSpan = x.BreakTimeSpan + }).ToList(); + + groupedRollCall = rollCallResult.GroupBy(x => x.CreationDate.Date).Select(x => + { + TimeSpan breakTime; + if (contractStart > endOfFarvardin) + { + breakTime = CalculateBreakTime( + x.First().BreakTimeSpan, + new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))); + } + else + { + breakTime = CalculateBreakTime(breakTimeEntity, new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks))); + } + return new GroupedRollCalls() + { + CreationDate = x.Key, + ShiftList = x.Select(s => new ShiftList() { Start = s.StartDate!.Value, End = s.EndDate!.Value }) + .ToList(), + HasFriday = x.Any(s => + s.StartDate != null && s.EndDate != null && (s.StartDate.Value.DayOfWeek == DayOfWeek.Friday || + s.EndDate.Value!.DayOfWeek == DayOfWeek.Friday)), + SumOneDaySpan = new TimeSpan(x.Sum(shift => shift.ShiftSpan.Ticks)) - breakTime, + + BreakTime = breakTime, + }; + }).OrderBy(x => x.CreationDate).ToList(); + + + TimeSpan sumSpans = new TimeSpan(groupedRollCall.Sum(x => x.SumOneDaySpan.Ticks)); + totalWorkingHours = sumSpans.TotalMinutes / 60; + + return (true, totalWorkingHours); + + + } + public List LeftWorkCantoleaveList(DateTime startDate, DateTime endDate, long workshopId, long employeeId, bool hasleft, DateTime leftWorkDate, int fridayStartToEnd, int officialHoliday, string totalHoursH, string totalHorsM, DateTime separationStartDate) + { + // {مقدار ساعت مجاز مرخصی در برای یک روز{کامل + var leaveHoursesPerDay = 190.58 / 365; + var contactCanToleaveList = new List(); + var allContractsBetween = _context.Contracts.AsSplitQuery().Include(x => x.WorkingHoursList) + .Where(x => x.WorkshopIds == workshopId && x.EmployeeId == employeeId && + x.ContractEnd >= startDate && x.ContarctStart <= endDate).ToList(); + + int mandatoryDays = 0; + double allCanToLeave = 0; + double canToLeave = 0; + int contractCounter = 0; + foreach (var contract in allContractsBetween) + { + contractCounter += 1; + var m = _mandatoryHoursRepository.GetMondatoryDays(contract.ContarctStart, + contract.ContractEnd); + + var workinghoursH = contract.WorkingHoursList.Select(x => x.TotalHoursesH).FirstOrDefault(); + var workinghoursM = contract.WorkingHoursList.Select(x => x.TotalHoursesM).FirstOrDefault(); + workinghoursM = string.IsNullOrWhiteSpace(workinghoursM) ? "0" : workinghoursM; + var workingHoursHDouble = Convert.ToDouble(workinghoursH); + var workingHoursMDouble = Convert.ToDouble(workinghoursM); + + + if (workingHoursMDouble > 0) + { + //تبیدل دقیه به اعشار + workingHoursMDouble = workingHoursMDouble / 60; + } + //کل ساعت کار پرسنل در این ماه + var totalWorkingHours = workingHoursHDouble + workingHoursMDouble; + + #region RollCallSpan + + var contractTotallDays = Convert.ToInt32((contract.ContractEnd - contract.ContarctStart).TotalDays + 1); + if (contractTotallDays <= 31) + { + + var rollCallTotalHoures = GetTotalWorkingHoursIfHasRollCall(employeeId, workshopId, + contract.ContarctStart.Date, contract.ContractEnd.Date); + if (rollCallTotalHoures.hasRollCall) + { + totalWorkingHours = rollCallTotalHoures.WorkingTotalHours; + } + } + + #endregion + // میانگین ساعت کارکرد پرسنل در روز + var workingHoursePerDay = totalWorkingHours / m.MoandatoryDays; + + // از شروع قرارداد تا پایان قرارداد + var totalDays = (contract.ContractEnd - contract.ContarctStart).TotalDays + 1; + double leftChekoutCanToleave = 0; + double leftleaveHoursesPerTotalDays = 0; + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل + var leaveHoursesPerTotalDays = leaveHoursesPerDay * totalDays; + + + double thisContractCanToLeavPerDay = 0; + double leftThisContractCanToLeavePerDay = 0; + if (workingHoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + thisContractCanToLeavPerDay = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + //if (hasleft && leftWorkDate <= endDate) + //{ + // leftThisContractCanToLeavePerDay = (leftleaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + //} + + } + else + { + workingHoursePerDay = 7.33; + thisContractCanToLeavPerDay = leaveHoursesPerTotalDays; + //if (hasleft && leftWorkDate <= endDate) + //{ + // leftThisContractCanToLeavePerDay = leftleaveHoursesPerTotalDays; + //} + + } + //canToLeave = allCanToLeave + thisContractCanToLeavPerDay; + //leftChekoutCanToleave = allCanToLeave + leftThisContractCanToLeavePerDay; + + var sdate = contract.ContarctStart.ToFarsi(); + var edate = contract.ContractEnd.ToFarsi(); + // اگر فیش در قرارداد جاری حلقه بود تا تاریخ پایان فیش برو + if (separationStartDate >= contract.ContarctStart && separationStartDate < contract.ContractEnd) + edate = endDate.ToFarsi(); + var syear = Convert.ToInt32(sdate.Substring(0, 4)); + var smonth = Convert.ToInt32(sdate.Substring(5, 2)); + var sday = Convert.ToInt32(sdate.Substring(8, 2)); + + var eyear = Convert.ToInt32(edate.Substring(0, 4)); + var emonth = Convert.ToInt32(edate.Substring(5, 2)); + var eday = Convert.ToInt32(edate.Substring(8, 2)); + + var d1 = new PersianDateTime(syear, smonth, sday); + var d2 = new PersianDateTime(eyear, emonth, eday); + for (var currntMonth = d1; currntMonth <= d2; currntMonth = currntMonth.AddMonths(1)) + { + var startMonthFa = $"{currntMonth}"; + var startMonthGr = new DateTime(); + if (currntMonth == d1) + { + var d1Fa = $"{d1}"; + startMonthGr = d1Fa.ToGeorgianDateTime(); + } + else + { + var a = $"{startMonthFa.Substring(0, 8)}01"; + startMonthGr = a.ToGeorgianDateTime(); + } + + + var endMonthFa = startMonthFa.FindeEndOfMonth(); + var endMonthGr = endMonthFa.ToGeorgianDateTime(); + bool left = false; + if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) + { + left = true; + + if (endMonthGr > leftWorkDate) + endMonthGr = endDate; + } + #region 365 + + double canToLeavAfter365 = 0; + bool is365 = false; + var countChekoutDays = (int)((endMonthGr - startMonthGr).TotalDays + 1); + var beforeCountDays = contactCanToleaveList.MaxBy(x => x.ContractStart); + if (beforeCountDays != null) + { + if (!beforeCountDays.EndOfYear) + { + var sumCounDays = countChekoutDays + beforeCountDays.CountChekoutDays; + if (sumCounDays > 365) + { + is365 = true; + countChekoutDays = sumCounDays - 365; + + // مقدار ساعت مجاز مرخصی باقی مانده بعد از 365 روز + leaveHoursesPerTotalDays = 7.33 * 9; + if (workingHoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + canToLeavAfter365 = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + } + else + { + + canToLeavAfter365 = leaveHoursesPerTotalDays; + } + } + else + { + countChekoutDays = sumCounDays; + } + } + + } + + + + #endregion + + + var leaveList = _context.LeaveList.AsSplitQuery() + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) + .Where(x => + (x.StartLeave <= startMonthGr && x.EndLeave >= startMonthGr) || + (x.StartLeave <= endMonthGr && x.EndLeave >= endMonthGr) || + (x.StartLeave >= startMonthGr && x.StartLeave <= endMonthGr) || + (x.EndLeave >= startMonthGr && x.EndLeave <= endMonthGr)).ToList(); + //مرخصی استفاده شده در این ماه + double usedLeaves = 0; + if (leaveList.Count > 0) + { + foreach (var item in leaveList) + { + var start = new DateTime(); + var end = new DateTime(); + start = item.StartLeave < startDate ? startDate : item.StartLeave; + end = item.EndLeave > endDate ? endDate : item.EndLeave; + if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) + { + + var leaveSpan = (end - start).TotalDays + 1; + var usedLeave = leaveSpan * workingHoursePerDay; + usedLeaves += usedLeave; + } + else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) + { + var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + else + { + + var leavingHourses = TimeSpan.Parse(item.LeaveHourses); + var usedLeave = (leavingHourses.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + + } + } + + + + //طلب مرخصی این ماه + double creditLeaves = 0; + // مزد مرخصی + double leavePay = 0; + //مدت غیبت + double periodOfAbsence = 0; + double absenceDeduction = 0; + var beforContactCanToleave = new ContractsCanToLeave(); + var beforContractCount = contractCounter - 1; + if (contactCanToleaveList.Count > 0) + { + //آخری قبل از این + beforContactCanToleave = contactCanToleaveList.MaxBy(x => x.ContractStart); + canToLeave = beforContactCanToleave.CanToLeave; + if (beforContactCanToleave.LastChekoutOfContract) + canToLeave = thisContractCanToLeavPerDay + beforContactCanToleave.CanToLeave; + if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) + { + if (canToLeave > 0) + { + #region LeftChekoutCanToLeave + + var leftMonthtotalDays = Convert.ToInt32((leftWorkDate - contract.ContarctStart).TotalDays + 1); + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{ترک کار شده + leaveHoursesPerTotalDays = leaveHoursesPerDay * leftMonthtotalDays; + if (workingHoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + thisContractCanToLeavPerDay = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + } + else + { + workingHoursePerDay = 7.33; + thisContractCanToLeavPerDay = leaveHoursesPerTotalDays; + } + + + if (contactCanToleaveList.Any(x => x.LastChekoutOfContract && x.ContractCounter == beforContractCount)) + { + + var b = contactCanToleaveList.FirstOrDefault(x => + x.LastChekoutOfContract && x.ContractCounter == beforContractCount); + canToLeave = thisContractCanToLeavPerDay + b.CanToLeave; + } + else + { + canToLeave = thisContractCanToLeavPerDay; + } + leaveList = _context.LeaveList.AsSplitQuery() + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) + .Where(x => + (x.StartLeave <= contract.ContarctStart && x.EndLeave >= contract.ContarctStart) || + (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || + (x.StartLeave >= contract.ContarctStart && x.StartLeave <= leftWorkDate) || + (x.EndLeave >= contract.ContarctStart && x.EndLeave <= leftWorkDate)).ToList(); + usedLeaves = 0; + if (leaveList.Count > 0) + { + foreach (var item in leaveList) + { + var start = new DateTime(); + var end = new DateTime(); + start = item.StartLeave < startDate ? startDate : item.StartLeave; + end = item.EndLeave > endDate ? endDate : item.EndLeave; + if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) + { + + var leaveSpan = (end - start).TotalDays + 1; + var usedLeave = leaveSpan * workingHoursePerDay; + usedLeaves += usedLeave; + } + else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) + { + var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + else + { + var leavingHourses = TimeSpan.Parse(item.LeaveHourses); + var usedLeave = (leavingHourses.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + + } + } + + + + #endregion + + } + else + { + var checkAbsenceDeduction = contactCanToleaveList + .Where(x => x.CanToLeave == 0 && x.ContractStart >= contract.ContarctStart).MaxBy(x => x.ContractStart); + if (checkAbsenceDeduction != null) + { + + var startSerach = checkAbsenceDeduction.ContractEnd.AddDays(1); + leaveList = _context.LeaveList.AsSplitQuery() + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) + .Where(x => + (x.StartLeave <= startSerach && x.EndLeave >= startSerach) || + (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || + (x.StartLeave >= startSerach && x.StartLeave <= leftWorkDate) || + (x.EndLeave >= startSerach && x.EndLeave <= leftWorkDate)).ToList(); + usedLeaves = 0; + if (leaveList.Count > 0) + { + foreach (var item in leaveList) + { + var start = new DateTime(); + var end = new DateTime(); + start = item.StartLeave < startSerach ? startSerach : item.StartLeave; + end = item.EndLeave > leftWorkDate ? leftWorkDate : item.EndLeave; + if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) + { + + var leaveSpan = (end - start).TotalDays + 1; + var usedLeave = leaveSpan * workingHoursePerDay; + usedLeaves += usedLeave; + } + else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) + { + var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + else + { + var leavingHourses = TimeSpan.Parse(item.LeaveHourses); + var usedLeave = (leavingHourses.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + + } + } + } + } + + + + } + + } + else + { + canToLeave = thisContractCanToLeavPerDay; + if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) + { + var leftMonthtotalDays = Convert.ToInt32((leftWorkDate - contract.ContarctStart).TotalDays + 1); + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل + leaveHoursesPerTotalDays = leaveHoursesPerDay * leftMonthtotalDays; + if (workingHoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + canToLeave = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + } + else + { + workingHoursePerDay = 7.33; + canToLeave = leaveHoursesPerTotalDays; + } + } + + + + } ; - if (canToLeave >= usedLeaves) //اگر طلب مرخصی داشت - { - creditLeaves = canToLeave - usedLeaves; - var has365 = contactCanToleaveList.Any(x => x.Is365); - //اگر از 365 روز تجاوز کرد و باقی مانده مرخصی بیشتر از 9 روز بود فقط 9 روز بماند - if (is365 && !has365 && creditLeaves > canToLeavAfter365 && !left) - { - creditLeaves = canToLeavAfter365; - - } - - if (is365 && has365 && !left) - { - var last365 = contactCanToleaveList - .Where(x => x.Is365) - .MaxBy(x => x.ContractStart); - canToLeavAfter365 += last365.CanToLeave; - if (creditLeaves > canToLeavAfter365) - { - creditLeaves = canToLeavAfter365; - } - - } - periodOfAbsence = 0; - } - else - { - periodOfAbsence = usedLeaves - canToLeave; - - #region AbsenceItemsCompute - - //var consumableItems = ConsumableItems(endMonthGr); - //var housingAllowance = HousingAllowance(endMonthGr); - //var familyAllowance = FamilyAllowance(employeeId, endMonthGr); - //var marriedAllowance = MarriedAllowance(endMonthGr, employeeId); - - //var leftworkList = _leftWorkRepository.search(new LeftWorkSearchModel(){EmployeeId = employeeId,WorkshopId = workshopId}); - //if (leftworkList == null) - // leftworkList = new List(); - ////دستمزد تجمیعی تا این تاریخ - //var dayliFeeResult = DayliFeeComputing(startDate, contract.ContarctStart, endDate, employeeId, workshopId, leftworkList); - - //var dayliFeeComplete = dayliFeeResult.DayliFee.MoneyToDouble(); - //if (workingHoursePerDay < 7.33) - //{ - // //مقدار مزد روزانه برای یک ساعت - // //var contractDayliFee = contract.DayliWage.MoneyToDouble(); - // var dayliFee = dayliFeeComplete / workingHoursePerDay; - - // var HousingAllowonceNumberType = housingAllowance.MoneyToDouble(); - // var HousingStep1 = HousingAllowonceNumberType / 30; - // var HousingPerHourse = HousingStep1 / workingHoursePerDay; - - // var consumableItemsNumberType = consumableItems.MoneyToDouble(); - // var consumableItemsStep1 = consumableItemsNumberType / 30; - // var consumablePerHourse = consumableItemsStep1 / workingHoursePerDay; - - // var MarriedStep1 = marriedAllowance / 30; - // var MarriedPerHours = MarriedStep1 / workingHoursePerDay; - - // var familyAllowanceNumberType = familyAllowance.MoneyToDouble(); - // var familyAllowanceStep1 = familyAllowanceNumberType / 30; - // var familyPerHours = familyAllowanceStep1 / workingHoursePerDay; - - // //کسری غیبت این پرسنل به ازای یک ساعت - // var absencePerHourse = dayliFee + HousingPerHourse + consumablePerHourse + MarriedPerHours + familyPerHours; - // absenceDeduction = absencePerHourse * periodOfAbsence; - //} - //else - //{ - // //مقدار مزد روزانه برای یک ساعت - // var dayliFee = dayliFeeComplete / 7.33; - - // var HousingAllowonceNumberType = housingAllowance.MoneyToDouble(); - // var HousingStep1 = HousingAllowonceNumberType / 30; - // var HousingPerHourse = HousingStep1 / 7.33; - - // var consumableItemsNumberType = consumableItems.MoneyToDouble(); - // var consumableItemsStep1 = consumableItemsNumberType / 30; - // var consumablePerHourse = consumableItemsStep1 / 7.33; - - // var MarriedStep1 = marriedAllowance / 30; - // var MarriedPerHours = MarriedStep1 / 7.33; - - // var familyAllowanceNumberType = familyAllowance.MoneyToDouble(); - // var familyAllowanceStep1 = familyAllowanceNumberType / 30; - // var familyPerHours = familyAllowanceStep1 / 7.33; - - // //کسری غیبت این پرسنل به ازای یک ساعت - // var absencePerHourse = dayliFee + HousingPerHourse + consumablePerHourse + MarriedPerHours + familyPerHours; - // absenceDeduction = absencePerHourse * periodOfAbsence; - //} - #endregion - - - creditLeaves = 0; - } - - bool lastChekout = endMonthGr == contract.ContractEnd; - - contactCanToleaveList.Add(new ContractsCanToLeave() - { - ContractCounter = contractCounter, - WorkingPerDayHourses = workingHoursePerDay, - ContractStart = startMonthGr, - ContractEnd = endMonthGr, - CanToLeave = creditLeaves, - PeriodOfAbsence = periodOfAbsence, - AbsenceDeduction = absenceDeduction, - LastChekoutOfContract = lastChekout, - Left = left, - CountChekoutDays = countChekoutDays, - Is365 = is365, - }); - - } - - allCanToLeave = canToLeave; - - - - } - - return contactCanToleaveList; - } - - public List EndOfYearCantoleaveList(DateTime startDate, DateTime endDate, long workshopId, long employeeId, bool hasleft, - DateTime leftWorkDate, int fridayStartToEnd, int officialHoliday, string totalHoursH, string totalHorsM, - DateTime separationStartDate) - { - // {مقدار ساعت مجاز مرخصی در برای یک روز{کامل - var leaveHoursesPerDay = 190.58 / 365; - var contactCanToleaveList = new List(); - var allContractsBetween = _context.Contracts.AsSplitQuery().Include(x => x.WorkingHoursList) - .Where(x => x.WorkshopIds == workshopId && x.EmployeeId == employeeId && - x.ContractEnd >= startDate && x.ContarctStart <= endDate).OrderBy(x => x.ContarctStart).ToList(); - double canToLeave = 0; - int contractCounter = 0; - foreach (var contract in allContractsBetween) - { - contractCounter += 1; - var m = _mandatoryHoursRepository.GetMondatoryDays(contract.ContarctStart, - contract.ContractEnd); - // میانگین ساعت کارکرد پرسنل در روز - #region PersonelWorkingHoursPerDay - - var workinghoursH = contract.WorkingHoursList.Select(x => x.TotalHoursesH).FirstOrDefault(); - var workinghoursM = contract.WorkingHoursList.Select(x => x.TotalHoursesM).FirstOrDefault(); - //workinghoursH = string.IsNullOrWhiteSpace(workinghoursH) ? "0" : workinghoursH; - workinghoursM = string.IsNullOrWhiteSpace(workinghoursM) ? "0" : workinghoursM; - var workingHoursHDouble = Convert.ToDouble(workinghoursH); - var workingHoursMDouble = Convert.ToDouble(workinghoursM); - if (workingHoursMDouble > 0) - { - //تبیدل دقیه به اعشار - workingHoursMDouble = workingHoursMDouble / 60; - } - //کل ساعت کار پرسنل در این قرارداد - var totalWorkingHours = workingHoursHDouble + workingHoursMDouble; - - #region RollCallSpan - - var contractTotallDays = Convert.ToInt32((contract.ContractEnd - contract.ContarctStart).TotalDays + 1); - if (contractTotallDays <= 31) - { - - var rollCallTotalHoures = GetTotalWorkingHoursIfHasRollCall(employeeId, workshopId, - contract.ContarctStart.Date, contract.ContractEnd.Date); - if (rollCallTotalHoures.hasRollCall) - { - totalWorkingHours = rollCallTotalHoures.WorkingTotalHours; - } - } - - #endregion - // میانگین ساعت کارکرد پرسنل در روز - var workingHoursePerDay = totalWorkingHours / m.MoandatoryDays; - - #endregion - // مقدار ساعت استاندارد مرخصی در این قرارداد - #region StandardCanToleave - - // از شروع قرارداد تا پایان قرارداد - var totalDays = (contract.ContractEnd - contract.ContarctStart).TotalDays + 1; - double leftChekoutCanToleave = 0; - double leftleaveHoursesPerTotalDays = 0; - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل - var leaveHoursesPerTotalDays = leaveHoursesPerDay * totalDays; - - #endregion - - //مقدار ساعت مجاز مرخصی پرسنل در این قرارداد - #region PersonelCanToLeave - - double personelCanToLeave = 0; - if (workingHoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - personelCanToLeave = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - } - else - { - workingHoursePerDay = 7.33; - personelCanToLeave = leaveHoursesPerTotalDays; - } - - #endregion - - double leftThisContractCanToLeavePerDay = 0; - - - var sdate = contract.ContarctStart.ToFarsi(); - var edate = contract.ContractEnd.ToFarsi(); - // اگر فیش در قرارداد جاری حلقه بود تا تاریخ پایان فیش برو - if (separationStartDate >= contract.ContarctStart && separationStartDate < contract.ContractEnd) - edate = endDate.ToFarsi(); - var syear = Convert.ToInt32(sdate.Substring(0, 4)); - var smonth = Convert.ToInt32(sdate.Substring(5, 2)); - var sday = Convert.ToInt32(sdate.Substring(8, 2)); - - var eyear = Convert.ToInt32(edate.Substring(0, 4)); - var emonth = Convert.ToInt32(edate.Substring(5, 2)); - var eday = Convert.ToInt32(edate.Substring(8, 2)); - - var d1 = new PersianDateTime(syear, smonth, sday); - var d2 = new PersianDateTime(eyear, emonth, eday); - for (var currntMonth = d1; currntMonth <= d2; currntMonth = currntMonth.AddMonths(1)) - { - - var startMonthFa = $"{currntMonth}"; - var startMonthGr = new DateTime(); - if (currntMonth == d1) - { - var d1Fa = $"{d1}"; - startMonthGr = d1Fa.ToGeorgianDateTime(); - } - else - { - var a = $"{startMonthFa.Substring(0, 8)}01"; - startMonthGr = a.ToGeorgianDateTime(); - } - - - var endMonthFa = startMonthFa.FindeEndOfMonth(); - bool isEndOfYear = endMonthFa.Substring(5, 2) == "12"; - var endMonthGr = endMonthFa.ToGeorgianDateTime(); - bool left = false; - if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) - { - left = true; - - if (endMonthGr > leftWorkDate) - endMonthGr = endDate; - } - #region 365 - - double canToLeavAfter365 = 0; - bool is365 = false; - var countChekoutDays = (int)((endMonthGr - startMonthGr).TotalDays + 1); - var beforeCountDays = contactCanToleaveList.MaxBy(x => x.ContractStart); - if (beforeCountDays != null) - { - if (!beforeCountDays.EndOfYear) - { - var sumCounDays = countChekoutDays + beforeCountDays.CountChekoutDays; - if (sumCounDays > 365) - { - - is365 = true; - countChekoutDays = sumCounDays - 365; - - // مقدار ساعت مجاز مرخصی باقی مانده بعد از 365 روز - leaveHoursesPerTotalDays = 7.33 * 9; - if (workingHoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - canToLeavAfter365 = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - } - else - { - - canToLeavAfter365 = leaveHoursesPerTotalDays; - } - } - else - { - countChekoutDays = sumCounDays; - } - } - - } - - - - #endregion - var leaveList = _context.LeaveList.AsSplitQuery() - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) - .Where(x => - (x.StartLeave <= startMonthGr && x.EndLeave >= startMonthGr) || - (x.StartLeave <= endMonthGr && x.EndLeave >= endMonthGr) || - (x.StartLeave >= startMonthGr && x.StartLeave <= endMonthGr) || - (x.EndLeave >= startMonthGr && x.EndLeave <= endMonthGr)).ToList(); - //مرخصی استفاده شده در این ماه - double usedLeaves = 0; - if (leaveList.Count > 0) - { - foreach (var item in leaveList) - { - - var start = new DateTime(); - var end = new DateTime(); - start = item.StartLeave < startDate ? startDate : item.StartLeave; - end = item.EndLeave > endDate ? endDate : item.EndLeave; - if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) - { - - var leaveSpan = (end - start).TotalDays + 1; - var usedLeave = leaveSpan * workingHoursePerDay; - usedLeaves += usedLeave; - } - else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) - { - var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - else - { - - var leavingHourses = TimeSpan.Parse(item.LeaveHourses); - var usedLeave = (leavingHourses.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - - } - } - - - - //طلب مرخصی این ماه - double creditLeaves = 0; - // مزد مرخصی - double leavePay = 0; - //مدت غیبت - double periodOfAbsence = 0; - double absenceDeduction = 0; - var beforContactCanToleave = new ContractsCanToLeave(); - var beforContractCount = contractCounter - 1; - if (contactCanToleaveList.Count > 0) - { - //آخری قبل از این - beforContactCanToleave = contactCanToleaveList.MaxBy(x => x.ContractStart); - if (beforContactCanToleave.EndOfYear) - { - canToLeave = personelCanToLeave; - } - else - { - canToLeave = beforContactCanToleave.CanToLeave; - } - - - if (beforContactCanToleave.LastChekoutOfContract && !beforContactCanToleave.EndOfYear) - canToLeave = personelCanToLeave + beforContactCanToleave.CanToLeave; - if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) - { - if (canToLeave > 0) - { - #region LeftChekoutCanToLeave - - var check365 = contactCanToleaveList.FirstOrDefault(x => - x.ContractStart >= contract.ContarctStart && x.Is365); - - if (check365 != null) - { - var startAfter365 = check365.ContractEnd.AddDays(1); - canToLeave = check365.CanToLeave; - leaveList = _context.LeaveList.AsSplitQuery() - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) - .Where(x => - (x.StartLeave <= startAfter365 && x.EndLeave >= startAfter365) || - (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || - (x.StartLeave >= startAfter365 && x.StartLeave <= leftWorkDate) || - (x.EndLeave >= startAfter365 && x.EndLeave <= leftWorkDate)).ToList(); - usedLeaves = 0; - if (leaveList.Count > 0) - { - foreach (var item in leaveList) - { - var start = new DateTime(); - var end = new DateTime(); - start = item.StartLeave < startAfter365 ? startAfter365 : item.StartLeave; - end = item.EndLeave > leftWorkDate ? leftWorkDate : item.EndLeave; - if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) - { - - var leaveSpan = (end - start).TotalDays + 1; - var usedLeave = leaveSpan * workingHoursePerDay; - usedLeaves += usedLeave; - } - else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) - { - var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - else - { - var leavingHourses = TimeSpan.Parse(item.LeaveHourses); - var usedLeave = (leavingHourses.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - - } - } - } - else - { - var leftMonthtotalDays = Convert.ToInt32((leftWorkDate - contract.ContarctStart).TotalDays + 1); - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{ترک کار شده - leaveHoursesPerTotalDays = leaveHoursesPerDay * leftMonthtotalDays; - if (workingHoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - personelCanToLeave = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - } - else - { - workingHoursePerDay = 7.33; - personelCanToLeave = leaveHoursesPerTotalDays; - } - - if (contactCanToleaveList.Any(x => x.LastChekoutOfContract && x.ContractCounter == beforContractCount && !x.EndOfYear)) - { - - var b = contactCanToleaveList.FirstOrDefault(x => - x.LastChekoutOfContract && x.ContractCounter == beforContractCount && !x.EndOfYear); - - canToLeave = personelCanToLeave + b.CanToLeave; - - - } - else - { - canToLeave = personelCanToLeave; - } - - leaveList = _context.LeaveList.AsSplitQuery() - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) - .Where(x => - (x.StartLeave <= contract.ContarctStart && x.EndLeave >= contract.ContarctStart) || - (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || - (x.StartLeave >= contract.ContarctStart && x.StartLeave <= leftWorkDate) || - (x.EndLeave >= contract.ContarctStart && x.EndLeave <= leftWorkDate)).ToList(); - usedLeaves = 0; - if (leaveList.Count > 0) - { - foreach (var item in leaveList) - { - var start = new DateTime(); - var end = new DateTime(); - start = item.StartLeave < contract.ContarctStart ? contract.ContarctStart : item.StartLeave; - end = item.EndLeave > leftWorkDate ? leftWorkDate : item.EndLeave; - if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) - { - - var leaveSpan = (end - start).TotalDays + 1; - var usedLeave = leaveSpan * workingHoursePerDay; - usedLeaves += usedLeave; - } - else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) - { - var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - else - { - var leavingHourses = TimeSpan.Parse(item.LeaveHourses); - var usedLeave = (leavingHourses.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - - } - } - } - - #endregion - - } - else - { - var checkAbsenceDeduction = contactCanToleaveList - .Where(x => x.CanToLeave == 0 && x.ContractStart >= contract.ContarctStart) - .MaxBy(x => x.ContractStart); - if (checkAbsenceDeduction != null) - { - - var startSerach = checkAbsenceDeduction.ContractEnd.AddDays(1); - leaveList = _context.LeaveList.AsSplitQuery() - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) - .Where(x => - (x.StartLeave <= startSerach && x.EndLeave >= startSerach) || - (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || - (x.StartLeave >= startSerach && x.StartLeave <= leftWorkDate) || - (x.EndLeave >= startSerach && x.EndLeave <= leftWorkDate)).ToList(); - usedLeaves = 0; - if (leaveList.Count > 0) - { - foreach (var item in leaveList) - { - - var start = new DateTime(); - var end = new DateTime(); - start = item.StartLeave < startSerach ? startSerach : item.StartLeave; - end = item.EndLeave > leftWorkDate ? leftWorkDate : item.EndLeave; - if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) - { - - var leaveSpan = (end - start).TotalDays + 1; - var usedLeave = leaveSpan * workingHoursePerDay; - usedLeaves += usedLeave; - } - else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) - { - var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - else - { - var leavingHourses = TimeSpan.Parse(item.LeaveHourses); - var usedLeave = (leavingHourses.TotalMinutes) / 60; - usedLeaves += usedLeave; - } - - } - } - } - } - - - - } - - } - else - { - canToLeave = personelCanToLeave; - if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) - { - var leftMonthtotalDays = Convert.ToInt32((leftWorkDate - contract.ContarctStart).TotalDays + 1); - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل - leaveHoursesPerTotalDays = leaveHoursesPerDay * leftMonthtotalDays; - if (workingHoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - canToLeave = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; - } - else - { - workingHoursePerDay = 7.33; - canToLeave = leaveHoursesPerTotalDays; - } - } - - - - } - - - - bool lastChekout = endMonthGr == contract.ContractEnd; - bool endOfyear = lastChekout && isEndOfYear; - - - - #region NewcChanges - - var has365B = contactCanToleaveList.Any(x => x.Is365); - creditLeaves = canToLeave; - //اگر از 365 روز تجاوز کرد و باقی مانده مرخصی بیشتر از 9 روز بود فقط 9 روز بماند - if (is365 && !has365B && creditLeaves > canToLeavAfter365 && !left && !endOfyear) - { - creditLeaves = canToLeavAfter365; - - } - - if (is365 && has365B && !left && !endOfyear) - { - var last365 = contactCanToleaveList - .Where(x => x.Is365) - .MaxBy(x => x.ContractStart); - canToLeavAfter365 += last365.CanToLeave; - if (creditLeaves > canToLeavAfter365) - { - creditLeaves = canToLeavAfter365; - } - - } - - periodOfAbsence = usedLeaves; - - #endregion - - contactCanToleaveList.Add(new ContractsCanToLeave() - { - ContractCounter = contractCounter, - WorkingPerDayHourses = workingHoursePerDay, - ContractStart = startMonthGr, - ContractEnd = endMonthGr, - CanToLeave = creditLeaves, - PeriodOfAbsence = periodOfAbsence, - AbsenceDeduction = absenceDeduction, - LastChekoutOfContract = lastChekout, - Left = left, - EndOfYear = endOfyear, - CountChekoutDays = countChekoutDays, - Is365 = is365, - }); - - } - - } - return contactCanToleaveList; - } - - - - public ContractsCanToLeave OnCheckoutCantoleaveList(DateTime startDate, DateTime endDate, long workshopId, long employeeId, - double leaveHoursesPerDay, double totalChekoutDays, double hoursePerDay) - { - double checkoutCanToLeave = 0; - // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل - var starndardHoursesPerTotalDays = leaveHoursesPerDay * totalChekoutDays; - if (hoursePerDay < 7.33) - { - // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل - checkoutCanToLeave = (starndardHoursesPerTotalDays * hoursePerDay) / 7.33; - } - else - { - hoursePerDay = 7.33; - checkoutCanToLeave = starndardHoursesPerTotalDays; - } - //بدست آوردن مرخصی این ماه - var checkoutLeaveList = _context.LeaveList.AsSplitQuery() - .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) - .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) - .Where(x => - (x.StartLeave <= startDate && x.EndLeave >= startDate) || - (x.StartLeave <= endDate && x.EndLeave >= endDate) || - (x.StartLeave >= startDate && x.StartLeave <= endDate) || - (x.EndLeave >= startDate && x.EndLeave <= endDate)).ToList(); - //مرخصی استفاده شده در این ماه - double usedLeavesChekout = 0; - if (checkoutLeaveList.Count > 0) - { - foreach (var item in checkoutLeaveList) - { - var start = new DateTime(); - var end = new DateTime(); - start = item.StartLeave < startDate ? startDate : item.StartLeave; - end = item.EndLeave > endDate ? endDate : item.EndLeave; - - if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) - { - var leaveSpan = (end - start).TotalDays + 1; - var usedLeave = leaveSpan * hoursePerDay; - usedLeavesChekout += usedLeave; - } - else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) - { - var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; - usedLeavesChekout += usedLeave; - } - else - { - var leavingHourses = TimeSpan.Parse(item.LeaveHourses); - var usedLeave = (leavingHourses.TotalMinutes) / 60; - usedLeavesChekout += usedLeave; - } - - } - } - - double creditLeaves = 0; - double periodOfAbsence = 0; - if (checkoutCanToLeave >= usedLeavesChekout) //اگر طلب مرخصی داشت - { - creditLeaves = checkoutCanToLeave - usedLeavesChekout; - periodOfAbsence = 0; - - } - else - { - - - periodOfAbsence = usedLeavesChekout - checkoutCanToLeave; - - creditLeaves = 0; - } - - - var result = new ContractsCanToLeave() - { - - CanToLeave = creditLeaves, - PeriodOfAbsence = periodOfAbsence, - - }; - return result; - - } - - public async Task HolidayGregorian(DateTime gregorianDate) - { - var result = new HolidayApiVewModel(); - var gregorianStr = gregorianDate.ToString("MM/dd/yyyy"); - var month = gregorianStr.Substring(0, 2); - var day = gregorianStr.Substring(3, 2); - var year = gregorianStr.Substring(6, 4); - - var client = new HttpClient(); - var request = new HttpRequestMessage(HttpMethod.Get, $"https://holidayapi.ir/gregorian/{year}/{month}/{day}"); - request.Headers.Add("Cookie", "XSRF-TOKEN=eyJpdiI6IjFrOTRrM0tFeVh5ZHFnNis3K0xZQVE9PSIsInZhbHVlIjoidlQ5TEg3c2hGYTVYeU0zRU9ha2NWTWpnYWRLMWxWSG9NWm5JYXhiaC8xRzliSlpmZGp2TlExd0VtL0JIL2JYWXNnVEREeTZNNDd1VHRQdjlQajFCNUxHZkwvdExWb3hCc25IMndUdEVwdDJ4T3drbkdhRTdscVoxNUxDeVNNOTciLCJtYWMiOiJkNjY4NGNkZWI3NGNkMzA1YWUyMjQxNGU5MWYwMjVlMGE1OGQzMjhkYTQ1NGE5NzcyNjA3NGNhM2RjOGI2NDVmIiwidGFnIjoiIn0%3D; holidayapi_session=eyJpdiI6IkdxRGx1NUZsRnlJazUwS3JhRUgrMFE9PSIsInZhbHVlIjoiclZ2U0hQZTErZ3duQmZXWmV6WjlvR1JTWEpwZHRSR0p2YytFOENUYzg0R1JBOGZHcWI1TzhFTEtIRjdXQy9Qa0doY0RXR2pBRGZTOEN3cGJsVEtTcC9uSkliOWZ6U3ZJRkFvY3N0TytWSGJwNWt2dWhKTmI0bnJOb09Ic3NJd0siLCJtYWMiOiI2MTk4YzNjNTdmODJmNDVkZTM5YWE2OTcyNGJiYzI1MTM1ZTViYTZlZTVhZTNhMzNmY2U5NzM1OThiOTg5YThlIiwidGFnIjoiIn0%3D"); - var response = await client.SendAsync(request); - var success = response.IsSuccessStatusCode; - - if (success) - { - var res = await response.Content.ReadAsStringAsync(); - var convertedRes = JsonConvert.DeserializeObject(res); - result.IsHoliday = convertedRes.IsHoliday; - result.IsSuccess = true; - } - - return result; - } - - public async Task HolidayShamsi(string shamsiDate) - { - var result = new HolidayApiVewModel(); - var year = shamsiDate.Substring(0, 4); - var month = shamsiDate.Substring(5, 2); - var day = shamsiDate.Substring(8, 2); - - - var client = new HttpClient(); - var request = new HttpRequestMessage(HttpMethod.Get, $"https://holidayapi.ir/gregorian/{year}/{month}/{day}"); - request.Headers.Add("Cookie", "XSRF-TOKEN=eyJpdiI6IjFrOTRrM0tFeVh5ZHFnNis3K0xZQVE9PSIsInZhbHVlIjoidlQ5TEg3c2hGYTVYeU0zRU9ha2NWTWpnYWRLMWxWSG9NWm5JYXhiaC8xRzliSlpmZGp2TlExd0VtL0JIL2JYWXNnVEREeTZNNDd1VHRQdjlQajFCNUxHZkwvdExWb3hCc25IMndUdEVwdDJ4T3drbkdhRTdscVoxNUxDeVNNOTciLCJtYWMiOiJkNjY4NGNkZWI3NGNkMzA1YWUyMjQxNGU5MWYwMjVlMGE1OGQzMjhkYTQ1NGE5NzcyNjA3NGNhM2RjOGI2NDVmIiwidGFnIjoiIn0%3D; holidayapi_session=eyJpdiI6IkdxRGx1NUZsRnlJazUwS3JhRUgrMFE9PSIsInZhbHVlIjoiclZ2U0hQZTErZ3duQmZXWmV6WjlvR1JTWEpwZHRSR0p2YytFOENUYzg0R1JBOGZHcWI1TzhFTEtIRjdXQy9Qa0doY0RXR2pBRGZTOEN3cGJsVEtTcC9uSkliOWZ6U3ZJRkFvY3N0TytWSGJwNWt2dWhKTmI0bnJOb09Ic3NJd0siLCJtYWMiOiI2MTk4YzNjNTdmODJmNDVkZTM5YWE2OTcyNGJiYzI1MTM1ZTViYTZlZTVhZTNhMzNmY2U5NzM1OThiOTg5YThlIiwidGFnIjoiIn0%3D"); - var response = await client.SendAsync(request); - var success = response.IsSuccessStatusCode; - - if (success) - { - var res = await response.Content.ReadAsStringAsync(); - var convertedRes = JsonConvert.DeserializeObject(res); - result.IsHoliday = convertedRes.IsHoliday; - result.IsSuccess = true; - } - - return result; - } - - #endregion - - //عیدی - #region Bunoses - - public BunosesAndYearsPayStatus Bunoses(string startDateFa, DateTime leftWorkDate, DateTime separationStartDate, DateTime separationEndDate, double daylyWage, string bonusesOptions, - bool hasleft, DateTime startWorkDate, DateTime contractStart, DateTime contractEnd, long workshopId, - long employeeId, bool isOldContract) - { - BunosesAndYearsPayStatus finalResult = new BunosesAndYearsPayStatus(); - double result = 0; - // ماه فیش آخر - var checkoutMonth = startDateFa.Substring(5, 2); - var start1403 = new DateTime(2024, 3, 20); - switch (bonusesOptions) - { - case "OnCheckoutOfMonth": - - var totalCheckoutDays = (separationEndDate - separationStartDate).TotalDays + 1; - finalResult.Bunoses = ((daylyWage * 60) / 365) * totalCheckoutDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalCheckoutDays); - - break; - case "OnEndOfYear"://درپایان سال - - if (isOldContract && contractEnd < start1403) - { - var totaltDays = (separationEndDate - separationStartDate).TotalDays + 1; - finalResult.Bunoses = ((daylyWage * 60) / 365) * totaltDays; - finalResult.TotalDayCompute = Convert.ToInt32(totaltDays); - } - else if (isOldContract && contractEnd > start1403) - { - - - if ((hasleft && leftWorkDate <= separationEndDate) || checkoutMonth == "12") - { - - //بدست آوردن اولین روز سال - string startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - DateTime startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - - // اگر تاریخ شروع بکار بزرگتر مساوی روز اول همین سال بود از تازیخ شوع بکار استفاده میشود در غیر اینصورت از روز اول سال استفاده میشود - DateTime startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; - - - #region NewCompute - - //شروع دوره - string st = startComputeDay.ToFarsi(); - int syear = Convert.ToInt32(st.Substring(0, 4)); - int smonth = Convert.ToInt32(st.Substring(5, 2)); - PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); - PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); - //پایان فیش حقوقی آخر - PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); - if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) - { - var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - finalResult.Bunoses = ((daylyWage * 60) / 365) * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - else - { - var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && - x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); - //پایان دوره - PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); - List nullDateList = new List(); - double sumOfOldBonuses = 0; - var oldTotalDays = 0; - for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) - { - var searchStart = ($"{startDate}").ToGeorgianDateTime(); - var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); - var foundCheckout = checkoutList.FirstOrDefault(x => - x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); - if (foundCheckout == null) - { - nullDateList.Add(new BunosesAndYearsPayStatus() - { - ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, - ContractEnd = searchEnd - }); - finalResult.NotCompleted = true; - } - else - { - double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; - int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); - double foundDayliWage = foundMonthlySalary / foundTotaldays; - double foundYearsPay = ((foundDayliWage * 60) / 365) * foundTotaldays; - oldTotalDays += foundTotaldays; - sumOfOldBonuses += foundYearsPay; - } - - } - - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - double lastMonthBonuses = ((daylyWage * 60) / 365) * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotalDays); - finalResult.Bunoses = lastMonthBonuses + sumOfOldBonuses; - finalResult.BunosesStatusList = nullDateList; - } - - #endregion - - - } - } - else if (!isOldContract) - { - if ((hasleft && leftWorkDate <= separationEndDate) || checkoutMonth == "12") - { - //بدست آوردن اولین روز سال - var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; - #region NewCompute - - //شروع دوره - string st = startComputeDay.ToFarsi(); - int syear = Convert.ToInt32(st.Substring(0, 4)); - int smonth = Convert.ToInt32(st.Substring(5, 2)); - PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); - PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); - //پایان فیش حقوقی آخر - PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); - if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) - { - var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - finalResult.Bunoses = ((daylyWage * 60) / 365) * totalDays; - } - else - { - var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && - x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); - //پایان دوره - PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); - List nullDateList = new List(); - double sumOfOldBonuses = 0; - var oldTotalDays = 0; - for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) - { - var searchStart = ($"{startDate}").ToGeorgianDateTime(); - var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); - var foundCheckout = checkoutList.FirstOrDefault(x => - x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); - if (foundCheckout == null) - { - nullDateList.Add(new BunosesAndYearsPayStatus() - { - ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, - ContractEnd = searchEnd - }); - finalResult.NotCompleted = true; - } - else - { - double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; - int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); - double foundDayliWage = foundMonthlySalary / foundTotaldays; - double foundYearsPay = ((foundDayliWage * 60) / 365) * foundTotaldays; - oldTotalDays += foundTotaldays; - sumOfOldBonuses += foundYearsPay; - } - - } - - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - double lastMonthBonuses = ((daylyWage * 60) / 365) * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotalDays); - finalResult.Bunoses = lastMonthBonuses + sumOfOldBonuses; - finalResult.BunosesStatusList = nullDateList; - } - - #endregion - } - } - - - break; - case "OnEndOfContract"://در پایان قرارداد - - if (isOldContract && contractEnd < start1403) - { - var totaltDays = (separationEndDate - separationStartDate).TotalDays + 1; - finalResult.Bunoses = ((daylyWage * 60) / 365) * totaltDays; - } - else if (isOldContract && contractEnd > start1403) - { - if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd) - { - - //بدست آوردن اولین روز سال - //var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - //var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - - var startComputeDay = contractStart; - //var totalDays = (separationEndDate - contractStart).TotalDays + 1; - //result = (daylyWage * 60) / 365 * totalDays; - - #region NewCompute - - //شروع دوره - string st = startComputeDay.ToFarsi(); - int syear = Convert.ToInt32(st.Substring(0, 4)); - int smonth = Convert.ToInt32(st.Substring(5, 2)); - PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); - PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); - //پایان فیش حقوقی آخر - PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); - if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) - { - var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - finalResult.Bunoses = ((daylyWage * 60) / 365) * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays); - } - else - { - var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && - x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); - //پایان دوره - PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); - List nullDateList = new List(); - double sumOfOldBonuses = 0; - var oldTotalDays = 0; - for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) - { - var searchStart = ($"{startDate}").ToGeorgianDateTime(); - var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); - var foundCheckout = checkoutList.FirstOrDefault(x => - x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); - if (foundCheckout == null) - { - nullDateList.Add(new BunosesAndYearsPayStatus() - { - ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, - ContractEnd = searchEnd - }); - finalResult.NotCompleted = true; - } - else - { - double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; - int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); - double foundDayliWage = foundMonthlySalary / foundTotaldays; - double foundBonuses = ((foundDayliWage * 60) / 365) * foundTotaldays; - oldTotalDays += foundTotaldays; - sumOfOldBonuses += foundBonuses; - } - - } - - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - double lastMonthBonuses = ((daylyWage * 60) / 365) * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotalDays); - finalResult.Bunoses = lastMonthBonuses + sumOfOldBonuses; - finalResult.BunosesStatusList = nullDateList; - } - - #endregion - } - } - else if (!isOldContract) - { - if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd) - { - var startComputeDay = contractStart; - //var totalDays = (separationEndDate - contractStart).TotalDays + 1; - // finalResult.Bunoses = (daylyWage * 60) / 365 * totalDays; - - #region NewCompute - - //شروع دوره - string st = startComputeDay.ToFarsi(); - int syear = Convert.ToInt32(st.Substring(0, 4)); - int smonth = Convert.ToInt32(st.Substring(5, 2)); - PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); - PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); - //پایان فیش حقوقی آخر - PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); - if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) - { - var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - finalResult.Bunoses = ((daylyWage * 60) / 365) * totalDays; - } - else - { - var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && - x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); - //پایان دوره - PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); - List nullDateList = new List(); - double sumOfOldBonuses = 0; - var oldTotalDays = 0; - for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) - { - var searchStart = ($"{startDate}").ToGeorgianDateTime(); - var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); - var foundCheckout = checkoutList.FirstOrDefault(x => - x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); - if (foundCheckout == null) - { - nullDateList.Add(new BunosesAndYearsPayStatus() - { - ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, - ContractEnd = searchEnd - }); - finalResult.NotCompleted = true; - } - else - { - double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; - int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); - double foundDayliWage = foundMonthlySalary / foundTotaldays; - double foundBonuses = ((foundDayliWage * 60) / 365) * foundTotaldays; - oldTotalDays += foundTotaldays; - sumOfOldBonuses += foundBonuses; - } - - } - - var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - double lastMonthBonuses = ((daylyWage * 60) / 365) * totalDays; - finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotalDays); - finalResult.Bunoses = lastMonthBonuses + sumOfOldBonuses; - finalResult.BunosesStatusList = nullDateList; - } - - #endregion - } - } - - break; - //case "EndOfContract1402LeftWork1403": //پایان قرارداد قبل 403 پایان همکاری بعد 403 - - // if (contractStart >= start1403 && contractEnd > start1403)// بعد از 1403 - // { - // if (hasleft && leftWorkDate <= separationEndDate) - // { - // //بدست آوردن اولین روز سال - // var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - // var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - - // // اگر تاریخ شروع بکار بزرگتر مساوی روز اول همین سال بود از تازیخ شوع بکار استفاده میشود در غیر اینصورت از روز اول سال استفاده میشود - // var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; - // var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; - // result = (daylyWage * 60) / 365 * totalDays; - // } - // } - // else if (contractStart < start1403)// قبل از 1403 - // { - // var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; - // finalResult.Bunoses = (daylyWage * 60) / 365 * totalDays; - - // //if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd || checkoutMonth == "12") - // //{ - // // //بدست آوردن اولین روز سال - // // var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; - // // var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); - - // // var startComputeDay = contractStart >= startDayOfYearGr ? contractStart : startDayOfYearGr; - - // //} - // } - // break; - - default: - finalResult.Bunoses = 0; - finalResult.TotalDayCompute = 0; - break; - } - - return finalResult; - } - - - - #endregion - - - #region Insurance - - public InsuranceYearlySalaryModel GetInsuranceItems(DateTime startDate, DateTime endDate, string year) - { - var query = _context.YearlySalaries - .Where(x => x.StartDate <= startDate && x.EndDate >= endDate && x.Year == year) - .Include(x => x.YearlySalaryItemsList) - .Select(x => new InsuranceYearlySalaryModel - { - DayliWage = x.YearlySalaryItemsList.FirstOrDefault(item => item.ItemName == "مزد روزانه").ItemValue, - ConsumableItems = x.YearlySalaryItemsList.FirstOrDefault(item => item.ItemName == "کمک هزینه اقلام").ItemValue, - HousingAllowance = x.YearlySalaryItemsList.FirstOrDefault(item => item.ItemName == "کمک هزینه مسکن").ItemValue, - MarriedAllowance = x.YearlySalaryItemsList.Any(item => item.ItemName == "حق تاهل") ? x.YearlySalaryItemsList.FirstOrDefault(item => item.ItemName == "حق تاهل").ItemValue : 0, - - }).FirstOrDefault(); - - return query; - } - - #endregion - - - private double GetRoundValue(double value) - { - string strValue = value.ToString(); - if (strValue.IndexOf('.') > -1) - { - - - string a = strValue.Substring(strValue.IndexOf('.') + 1, 1); - if (int.Parse(a) > 3) - { - return (Math.Round(value, MidpointRounding.ToPositiveInfinity)); - } - else - { - return (Math.Round(value, MidpointRounding.ToNegativeInfinity)); - } - } - - return value; - } + if (canToLeave >= usedLeaves) //اگر طلب مرخصی داشت + { + creditLeaves = canToLeave - usedLeaves; + var has365 = contactCanToleaveList.Any(x => x.Is365); + //اگر از 365 روز تجاوز کرد و باقی مانده مرخصی بیشتر از 9 روز بود فقط 9 روز بماند + if (is365 && !has365 && creditLeaves > canToLeavAfter365 && !left) + { + creditLeaves = canToLeavAfter365; + + } + + if (is365 && has365 && !left) + { + var last365 = contactCanToleaveList + .Where(x => x.Is365) + .MaxBy(x => x.ContractStart); + canToLeavAfter365 += last365.CanToLeave; + if (creditLeaves > canToLeavAfter365) + { + creditLeaves = canToLeavAfter365; + } + + } + periodOfAbsence = 0; + } + else + { + periodOfAbsence = usedLeaves - canToLeave; + + #region AbsenceItemsCompute + + //var consumableItems = ConsumableItems(endMonthGr); + //var housingAllowance = HousingAllowance(endMonthGr); + //var familyAllowance = FamilyAllowance(employeeId, endMonthGr); + //var marriedAllowance = MarriedAllowance(endMonthGr, employeeId); + + //var leftworkList = _leftWorkRepository.search(new LeftWorkSearchModel(){EmployeeId = employeeId,WorkshopId = workshopId}); + //if (leftworkList == null) + // leftworkList = new List(); + ////دستمزد تجمیعی تا این تاریخ + //var dayliFeeResult = DayliFeeComputing(startDate, contract.ContarctStart, endDate, employeeId, workshopId, leftworkList); + + //var dayliFeeComplete = dayliFeeResult.DayliFee.MoneyToDouble(); + //if (workingHoursePerDay < 7.33) + //{ + // //مقدار مزد روزانه برای یک ساعت + // //var contractDayliFee = contract.DayliWage.MoneyToDouble(); + // var dayliFee = dayliFeeComplete / workingHoursePerDay; + + // var HousingAllowonceNumberType = housingAllowance.MoneyToDouble(); + // var HousingStep1 = HousingAllowonceNumberType / 30; + // var HousingPerHourse = HousingStep1 / workingHoursePerDay; + + // var consumableItemsNumberType = consumableItems.MoneyToDouble(); + // var consumableItemsStep1 = consumableItemsNumberType / 30; + // var consumablePerHourse = consumableItemsStep1 / workingHoursePerDay; + + // var MarriedStep1 = marriedAllowance / 30; + // var MarriedPerHours = MarriedStep1 / workingHoursePerDay; + + // var familyAllowanceNumberType = familyAllowance.MoneyToDouble(); + // var familyAllowanceStep1 = familyAllowanceNumberType / 30; + // var familyPerHours = familyAllowanceStep1 / workingHoursePerDay; + + // //کسری غیبت این پرسنل به ازای یک ساعت + // var absencePerHourse = dayliFee + HousingPerHourse + consumablePerHourse + MarriedPerHours + familyPerHours; + // absenceDeduction = absencePerHourse * periodOfAbsence; + //} + //else + //{ + // //مقدار مزد روزانه برای یک ساعت + // var dayliFee = dayliFeeComplete / 7.33; + + // var HousingAllowonceNumberType = housingAllowance.MoneyToDouble(); + // var HousingStep1 = HousingAllowonceNumberType / 30; + // var HousingPerHourse = HousingStep1 / 7.33; + + // var consumableItemsNumberType = consumableItems.MoneyToDouble(); + // var consumableItemsStep1 = consumableItemsNumberType / 30; + // var consumablePerHourse = consumableItemsStep1 / 7.33; + + // var MarriedStep1 = marriedAllowance / 30; + // var MarriedPerHours = MarriedStep1 / 7.33; + + // var familyAllowanceNumberType = familyAllowance.MoneyToDouble(); + // var familyAllowanceStep1 = familyAllowanceNumberType / 30; + // var familyPerHours = familyAllowanceStep1 / 7.33; + + // //کسری غیبت این پرسنل به ازای یک ساعت + // var absencePerHourse = dayliFee + HousingPerHourse + consumablePerHourse + MarriedPerHours + familyPerHours; + // absenceDeduction = absencePerHourse * periodOfAbsence; + //} + #endregion + + + creditLeaves = 0; + } + + bool lastChekout = endMonthGr == contract.ContractEnd; + + contactCanToleaveList.Add(new ContractsCanToLeave() + { + ContractCounter = contractCounter, + WorkingPerDayHourses = workingHoursePerDay, + ContractStart = startMonthGr, + ContractEnd = endMonthGr, + CanToLeave = creditLeaves, + PeriodOfAbsence = periodOfAbsence, + AbsenceDeduction = absenceDeduction, + LastChekoutOfContract = lastChekout, + Left = left, + CountChekoutDays = countChekoutDays, + Is365 = is365, + }); + + } + + allCanToLeave = canToLeave; + + + + } + + return contactCanToleaveList; + } + + public List EndOfYearCantoleaveList(DateTime startDate, DateTime endDate, long workshopId, long employeeId, bool hasleft, + DateTime leftWorkDate, int fridayStartToEnd, int officialHoliday, string totalHoursH, string totalHorsM, + DateTime separationStartDate) + { + // {مقدار ساعت مجاز مرخصی در برای یک روز{کامل + var leaveHoursesPerDay = 190.58 / 365; + var contactCanToleaveList = new List(); + var allContractsBetween = _context.Contracts.AsSplitQuery().Include(x => x.WorkingHoursList) + .Where(x => x.WorkshopIds == workshopId && x.EmployeeId == employeeId && + x.ContractEnd >= startDate && x.ContarctStart <= endDate).OrderBy(x => x.ContarctStart).ToList(); + double canToLeave = 0; + int contractCounter = 0; + foreach (var contract in allContractsBetween) + { + contractCounter += 1; + var m = _mandatoryHoursRepository.GetMondatoryDays(contract.ContarctStart, + contract.ContractEnd); + // میانگین ساعت کارکرد پرسنل در روز + #region PersonelWorkingHoursPerDay + + var workinghoursH = contract.WorkingHoursList.Select(x => x.TotalHoursesH).FirstOrDefault(); + var workinghoursM = contract.WorkingHoursList.Select(x => x.TotalHoursesM).FirstOrDefault(); + //workinghoursH = string.IsNullOrWhiteSpace(workinghoursH) ? "0" : workinghoursH; + workinghoursM = string.IsNullOrWhiteSpace(workinghoursM) ? "0" : workinghoursM; + var workingHoursHDouble = Convert.ToDouble(workinghoursH); + var workingHoursMDouble = Convert.ToDouble(workinghoursM); + if (workingHoursMDouble > 0) + { + //تبیدل دقیه به اعشار + workingHoursMDouble = workingHoursMDouble / 60; + } + //کل ساعت کار پرسنل در این قرارداد + var totalWorkingHours = workingHoursHDouble + workingHoursMDouble; + + #region RollCallSpan + + var contractTotallDays = Convert.ToInt32((contract.ContractEnd - contract.ContarctStart).TotalDays + 1); + if (contractTotallDays <= 31) + { + + var rollCallTotalHoures = GetTotalWorkingHoursIfHasRollCall(employeeId, workshopId, + contract.ContarctStart.Date, contract.ContractEnd.Date); + if (rollCallTotalHoures.hasRollCall) + { + totalWorkingHours = rollCallTotalHoures.WorkingTotalHours; + } + } + + #endregion + // میانگین ساعت کارکرد پرسنل در روز + var workingHoursePerDay = totalWorkingHours / m.MoandatoryDays; + + #endregion + // مقدار ساعت استاندارد مرخصی در این قرارداد + #region StandardCanToleave + + // از شروع قرارداد تا پایان قرارداد + var totalDays = (contract.ContractEnd - contract.ContarctStart).TotalDays + 1; + double leftChekoutCanToleave = 0; + double leftleaveHoursesPerTotalDays = 0; + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل + var leaveHoursesPerTotalDays = leaveHoursesPerDay * totalDays; + + #endregion + + //مقدار ساعت مجاز مرخصی پرسنل در این قرارداد + #region PersonelCanToLeave + + double personelCanToLeave = 0; + if (workingHoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + personelCanToLeave = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + } + else + { + workingHoursePerDay = 7.33; + personelCanToLeave = leaveHoursesPerTotalDays; + } + + #endregion + + double leftThisContractCanToLeavePerDay = 0; + + + var sdate = contract.ContarctStart.ToFarsi(); + var edate = contract.ContractEnd.ToFarsi(); + // اگر فیش در قرارداد جاری حلقه بود تا تاریخ پایان فیش برو + if (separationStartDate >= contract.ContarctStart && separationStartDate < contract.ContractEnd) + edate = endDate.ToFarsi(); + var syear = Convert.ToInt32(sdate.Substring(0, 4)); + var smonth = Convert.ToInt32(sdate.Substring(5, 2)); + var sday = Convert.ToInt32(sdate.Substring(8, 2)); + + var eyear = Convert.ToInt32(edate.Substring(0, 4)); + var emonth = Convert.ToInt32(edate.Substring(5, 2)); + var eday = Convert.ToInt32(edate.Substring(8, 2)); + + var d1 = new PersianDateTime(syear, smonth, sday); + var d2 = new PersianDateTime(eyear, emonth, eday); + for (var currntMonth = d1; currntMonth <= d2; currntMonth = currntMonth.AddMonths(1)) + { + + var startMonthFa = $"{currntMonth}"; + var startMonthGr = new DateTime(); + if (currntMonth == d1) + { + var d1Fa = $"{d1}"; + startMonthGr = d1Fa.ToGeorgianDateTime(); + } + else + { + var a = $"{startMonthFa.Substring(0, 8)}01"; + startMonthGr = a.ToGeorgianDateTime(); + } + + + var endMonthFa = startMonthFa.FindeEndOfMonth(); + bool isEndOfYear = endMonthFa.Substring(5, 2) == "12"; + var endMonthGr = endMonthFa.ToGeorgianDateTime(); + bool left = false; + if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) + { + left = true; + + if (endMonthGr > leftWorkDate) + endMonthGr = endDate; + } + #region 365 + + double canToLeavAfter365 = 0; + bool is365 = false; + var countChekoutDays = (int)((endMonthGr - startMonthGr).TotalDays + 1); + var beforeCountDays = contactCanToleaveList.MaxBy(x => x.ContractStart); + if (beforeCountDays != null) + { + if (!beforeCountDays.EndOfYear) + { + var sumCounDays = countChekoutDays + beforeCountDays.CountChekoutDays; + if (sumCounDays > 365) + { + + is365 = true; + countChekoutDays = sumCounDays - 365; + + // مقدار ساعت مجاز مرخصی باقی مانده بعد از 365 روز + leaveHoursesPerTotalDays = 7.33 * 9; + if (workingHoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + canToLeavAfter365 = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + } + else + { + + canToLeavAfter365 = leaveHoursesPerTotalDays; + } + } + else + { + countChekoutDays = sumCounDays; + } + } + + } + + + + #endregion + var leaveList = _context.LeaveList.AsSplitQuery() + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) + .Where(x => + (x.StartLeave <= startMonthGr && x.EndLeave >= startMonthGr) || + (x.StartLeave <= endMonthGr && x.EndLeave >= endMonthGr) || + (x.StartLeave >= startMonthGr && x.StartLeave <= endMonthGr) || + (x.EndLeave >= startMonthGr && x.EndLeave <= endMonthGr)).ToList(); + //مرخصی استفاده شده در این ماه + double usedLeaves = 0; + if (leaveList.Count > 0) + { + foreach (var item in leaveList) + { + + var start = new DateTime(); + var end = new DateTime(); + start = item.StartLeave < startDate ? startDate : item.StartLeave; + end = item.EndLeave > endDate ? endDate : item.EndLeave; + if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) + { + + var leaveSpan = (end - start).TotalDays + 1; + var usedLeave = leaveSpan * workingHoursePerDay; + usedLeaves += usedLeave; + } + else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) + { + var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + else + { + + var leavingHourses = TimeSpan.Parse(item.LeaveHourses); + var usedLeave = (leavingHourses.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + + } + } + + + + //طلب مرخصی این ماه + double creditLeaves = 0; + // مزد مرخصی + double leavePay = 0; + //مدت غیبت + double periodOfAbsence = 0; + double absenceDeduction = 0; + var beforContactCanToleave = new ContractsCanToLeave(); + var beforContractCount = contractCounter - 1; + if (contactCanToleaveList.Count > 0) + { + //آخری قبل از این + beforContactCanToleave = contactCanToleaveList.MaxBy(x => x.ContractStart); + if (beforContactCanToleave.EndOfYear) + { + canToLeave = personelCanToLeave; + } + else + { + canToLeave = beforContactCanToleave.CanToLeave; + } + + + if (beforContactCanToleave.LastChekoutOfContract && !beforContactCanToleave.EndOfYear) + canToLeave = personelCanToLeave + beforContactCanToleave.CanToLeave; + if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) + { + if (canToLeave > 0) + { + #region LeftChekoutCanToLeave + + var check365 = contactCanToleaveList.FirstOrDefault(x => + x.ContractStart >= contract.ContarctStart && x.Is365); + + if (check365 != null) + { + var startAfter365 = check365.ContractEnd.AddDays(1); + canToLeave = check365.CanToLeave; + leaveList = _context.LeaveList.AsSplitQuery() + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) + .Where(x => + (x.StartLeave <= startAfter365 && x.EndLeave >= startAfter365) || + (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || + (x.StartLeave >= startAfter365 && x.StartLeave <= leftWorkDate) || + (x.EndLeave >= startAfter365 && x.EndLeave <= leftWorkDate)).ToList(); + usedLeaves = 0; + if (leaveList.Count > 0) + { + foreach (var item in leaveList) + { + var start = new DateTime(); + var end = new DateTime(); + start = item.StartLeave < startAfter365 ? startAfter365 : item.StartLeave; + end = item.EndLeave > leftWorkDate ? leftWorkDate : item.EndLeave; + if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) + { + + var leaveSpan = (end - start).TotalDays + 1; + var usedLeave = leaveSpan * workingHoursePerDay; + usedLeaves += usedLeave; + } + else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) + { + var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + else + { + var leavingHourses = TimeSpan.Parse(item.LeaveHourses); + var usedLeave = (leavingHourses.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + + } + } + } + else + { + var leftMonthtotalDays = Convert.ToInt32((leftWorkDate - contract.ContarctStart).TotalDays + 1); + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{ترک کار شده + leaveHoursesPerTotalDays = leaveHoursesPerDay * leftMonthtotalDays; + if (workingHoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + personelCanToLeave = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + } + else + { + workingHoursePerDay = 7.33; + personelCanToLeave = leaveHoursesPerTotalDays; + } + + if (contactCanToleaveList.Any(x => x.LastChekoutOfContract && x.ContractCounter == beforContractCount && !x.EndOfYear)) + { + + var b = contactCanToleaveList.FirstOrDefault(x => + x.LastChekoutOfContract && x.ContractCounter == beforContractCount && !x.EndOfYear); + + canToLeave = personelCanToLeave + b.CanToLeave; + + + } + else + { + canToLeave = personelCanToLeave; + } + + leaveList = _context.LeaveList.AsSplitQuery() + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) + .Where(x => + (x.StartLeave <= contract.ContarctStart && x.EndLeave >= contract.ContarctStart) || + (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || + (x.StartLeave >= contract.ContarctStart && x.StartLeave <= leftWorkDate) || + (x.EndLeave >= contract.ContarctStart && x.EndLeave <= leftWorkDate)).ToList(); + usedLeaves = 0; + if (leaveList.Count > 0) + { + foreach (var item in leaveList) + { + var start = new DateTime(); + var end = new DateTime(); + start = item.StartLeave < contract.ContarctStart ? contract.ContarctStart : item.StartLeave; + end = item.EndLeave > leftWorkDate ? leftWorkDate : item.EndLeave; + if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) + { + + var leaveSpan = (end - start).TotalDays + 1; + var usedLeave = leaveSpan * workingHoursePerDay; + usedLeaves += usedLeave; + } + else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) + { + var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + else + { + var leavingHourses = TimeSpan.Parse(item.LeaveHourses); + var usedLeave = (leavingHourses.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + + } + } + } + + #endregion + + } + else + { + var checkAbsenceDeduction = contactCanToleaveList + .Where(x => x.CanToLeave == 0 && x.ContractStart >= contract.ContarctStart) + .MaxBy(x => x.ContractStart); + if (checkAbsenceDeduction != null) + { + + var startSerach = checkAbsenceDeduction.ContractEnd.AddDays(1); + leaveList = _context.LeaveList.AsSplitQuery() + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) + .Where(x => + (x.StartLeave <= startSerach && x.EndLeave >= startSerach) || + (x.StartLeave <= leftWorkDate && x.EndLeave >= leftWorkDate) || + (x.StartLeave >= startSerach && x.StartLeave <= leftWorkDate) || + (x.EndLeave >= startSerach && x.EndLeave <= leftWorkDate)).ToList(); + usedLeaves = 0; + if (leaveList.Count > 0) + { + foreach (var item in leaveList) + { + + var start = new DateTime(); + var end = new DateTime(); + start = item.StartLeave < startSerach ? startSerach : item.StartLeave; + end = item.EndLeave > leftWorkDate ? leftWorkDate : item.EndLeave; + if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) + { + + var leaveSpan = (end - start).TotalDays + 1; + var usedLeave = leaveSpan * workingHoursePerDay; + usedLeaves += usedLeave; + } + else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) + { + var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + else + { + var leavingHourses = TimeSpan.Parse(item.LeaveHourses); + var usedLeave = (leavingHourses.TotalMinutes) / 60; + usedLeaves += usedLeave; + } + + } + } + } + } + + + + } + + } + else + { + canToLeave = personelCanToLeave; + if (hasleft && leftWorkDate >= startMonthGr && leftWorkDate <= endMonthGr) + { + var leftMonthtotalDays = Convert.ToInt32((leftWorkDate - contract.ContarctStart).TotalDays + 1); + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل + leaveHoursesPerTotalDays = leaveHoursesPerDay * leftMonthtotalDays; + if (workingHoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + canToLeave = (leaveHoursesPerTotalDays * workingHoursePerDay) / 7.33; + } + else + { + workingHoursePerDay = 7.33; + canToLeave = leaveHoursesPerTotalDays; + } + } + + + + } + + + + bool lastChekout = endMonthGr == contract.ContractEnd; + bool endOfyear = lastChekout && isEndOfYear; + + + + #region NewcChanges + + var has365B = contactCanToleaveList.Any(x => x.Is365); + creditLeaves = canToLeave; + //اگر از 365 روز تجاوز کرد و باقی مانده مرخصی بیشتر از 9 روز بود فقط 9 روز بماند + if (is365 && !has365B && creditLeaves > canToLeavAfter365 && !left && !endOfyear) + { + creditLeaves = canToLeavAfter365; + + } + + if (is365 && has365B && !left && !endOfyear) + { + var last365 = contactCanToleaveList + .Where(x => x.Is365) + .MaxBy(x => x.ContractStart); + canToLeavAfter365 += last365.CanToLeave; + if (creditLeaves > canToLeavAfter365) + { + creditLeaves = canToLeavAfter365; + } + + } + + periodOfAbsence = usedLeaves; + + #endregion + + contactCanToleaveList.Add(new ContractsCanToLeave() + { + ContractCounter = contractCounter, + WorkingPerDayHourses = workingHoursePerDay, + ContractStart = startMonthGr, + ContractEnd = endMonthGr, + CanToLeave = creditLeaves, + PeriodOfAbsence = periodOfAbsence, + AbsenceDeduction = absenceDeduction, + LastChekoutOfContract = lastChekout, + Left = left, + EndOfYear = endOfyear, + CountChekoutDays = countChekoutDays, + Is365 = is365, + }); + + } + + } + return contactCanToleaveList; + } + + + + public ContractsCanToLeave OnCheckoutCantoleaveList(DateTime startDate, DateTime endDate, long workshopId, long employeeId, + double leaveHoursesPerDay, double totalChekoutDays, double hoursePerDay) + { + double checkoutCanToLeave = 0; + // {مقدار ساعت مجاز مرخصی در مدت این فیش حقوقی{کامل + var starndardHoursesPerTotalDays = leaveHoursesPerDay * totalChekoutDays; + if (hoursePerDay < 7.33) + { + // تناسب مجدد به نسبت ساعات کمتر از 7/33 برای بدست آوردن ساعت مجاز مرخصی این پرسنل + checkoutCanToLeave = (starndardHoursesPerTotalDays * hoursePerDay) / 7.33; + } + else + { + hoursePerDay = 7.33; + checkoutCanToLeave = starndardHoursesPerTotalDays; + } + //بدست آوردن مرخصی این ماه + var checkoutLeaveList = _context.LeaveList.AsSplitQuery() + .Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId) + .Where(x => x.LeaveType == "استحقاقی" && x.IsAccepted) + .Where(x => + (x.StartLeave <= startDate && x.EndLeave >= startDate) || + (x.StartLeave <= endDate && x.EndLeave >= endDate) || + (x.StartLeave >= startDate && x.StartLeave <= endDate) || + (x.EndLeave >= startDate && x.EndLeave <= endDate)).ToList(); + //مرخصی استفاده شده در این ماه + double usedLeavesChekout = 0; + if (checkoutLeaveList.Count > 0) + { + foreach (var item in checkoutLeaveList) + { + var start = new DateTime(); + var end = new DateTime(); + start = item.StartLeave < startDate ? startDate : item.StartLeave; + end = item.EndLeave > endDate ? endDate : item.EndLeave; + + if (item.PaidLeaveType == "روزانه" && !item.HasShiftDuration) + { + var leaveSpan = (end - start).TotalDays + 1; + var usedLeave = leaveSpan * hoursePerDay; + usedLeavesChekout += usedLeave; + } + else if (item.PaidLeaveType == "روزانه" && item.HasShiftDuration) + { + var usedLeave = (item.ShiftDuration.TotalMinutes) / 60; + usedLeavesChekout += usedLeave; + } + else + { + var leavingHourses = TimeSpan.Parse(item.LeaveHourses); + var usedLeave = (leavingHourses.TotalMinutes) / 60; + usedLeavesChekout += usedLeave; + } + + } + } + + double creditLeaves = 0; + double periodOfAbsence = 0; + if (checkoutCanToLeave >= usedLeavesChekout) //اگر طلب مرخصی داشت + { + creditLeaves = checkoutCanToLeave - usedLeavesChekout; + periodOfAbsence = 0; + + } + else + { + + + periodOfAbsence = usedLeavesChekout - checkoutCanToLeave; + + creditLeaves = 0; + } + + + var result = new ContractsCanToLeave() + { + + CanToLeave = creditLeaves, + PeriodOfAbsence = periodOfAbsence, + + }; + return result; + + } + + public async Task HolidayGregorian(DateTime gregorianDate) + { + var result = new HolidayApiVewModel(); + var gregorianStr = gregorianDate.ToString("MM/dd/yyyy"); + var month = gregorianStr.Substring(0, 2); + var day = gregorianStr.Substring(3, 2); + var year = gregorianStr.Substring(6, 4); + + var client = new HttpClient(); + var request = new HttpRequestMessage(HttpMethod.Get, $"https://holidayapi.ir/gregorian/{year}/{month}/{day}"); + request.Headers.Add("Cookie", "XSRF-TOKEN=eyJpdiI6IjFrOTRrM0tFeVh5ZHFnNis3K0xZQVE9PSIsInZhbHVlIjoidlQ5TEg3c2hGYTVYeU0zRU9ha2NWTWpnYWRLMWxWSG9NWm5JYXhiaC8xRzliSlpmZGp2TlExd0VtL0JIL2JYWXNnVEREeTZNNDd1VHRQdjlQajFCNUxHZkwvdExWb3hCc25IMndUdEVwdDJ4T3drbkdhRTdscVoxNUxDeVNNOTciLCJtYWMiOiJkNjY4NGNkZWI3NGNkMzA1YWUyMjQxNGU5MWYwMjVlMGE1OGQzMjhkYTQ1NGE5NzcyNjA3NGNhM2RjOGI2NDVmIiwidGFnIjoiIn0%3D; holidayapi_session=eyJpdiI6IkdxRGx1NUZsRnlJazUwS3JhRUgrMFE9PSIsInZhbHVlIjoiclZ2U0hQZTErZ3duQmZXWmV6WjlvR1JTWEpwZHRSR0p2YytFOENUYzg0R1JBOGZHcWI1TzhFTEtIRjdXQy9Qa0doY0RXR2pBRGZTOEN3cGJsVEtTcC9uSkliOWZ6U3ZJRkFvY3N0TytWSGJwNWt2dWhKTmI0bnJOb09Ic3NJd0siLCJtYWMiOiI2MTk4YzNjNTdmODJmNDVkZTM5YWE2OTcyNGJiYzI1MTM1ZTViYTZlZTVhZTNhMzNmY2U5NzM1OThiOTg5YThlIiwidGFnIjoiIn0%3D"); + var response = await client.SendAsync(request); + var success = response.IsSuccessStatusCode; + + if (success) + { + var res = await response.Content.ReadAsStringAsync(); + var convertedRes = JsonConvert.DeserializeObject(res); + result.IsHoliday = convertedRes.IsHoliday; + result.IsSuccess = true; + } + + return result; + } + + public async Task HolidayShamsi(string shamsiDate) + { + var result = new HolidayApiVewModel(); + var year = shamsiDate.Substring(0, 4); + var month = shamsiDate.Substring(5, 2); + var day = shamsiDate.Substring(8, 2); + + + var client = new HttpClient(); + var request = new HttpRequestMessage(HttpMethod.Get, $"https://holidayapi.ir/gregorian/{year}/{month}/{day}"); + request.Headers.Add("Cookie", "XSRF-TOKEN=eyJpdiI6IjFrOTRrM0tFeVh5ZHFnNis3K0xZQVE9PSIsInZhbHVlIjoidlQ5TEg3c2hGYTVYeU0zRU9ha2NWTWpnYWRLMWxWSG9NWm5JYXhiaC8xRzliSlpmZGp2TlExd0VtL0JIL2JYWXNnVEREeTZNNDd1VHRQdjlQajFCNUxHZkwvdExWb3hCc25IMndUdEVwdDJ4T3drbkdhRTdscVoxNUxDeVNNOTciLCJtYWMiOiJkNjY4NGNkZWI3NGNkMzA1YWUyMjQxNGU5MWYwMjVlMGE1OGQzMjhkYTQ1NGE5NzcyNjA3NGNhM2RjOGI2NDVmIiwidGFnIjoiIn0%3D; holidayapi_session=eyJpdiI6IkdxRGx1NUZsRnlJazUwS3JhRUgrMFE9PSIsInZhbHVlIjoiclZ2U0hQZTErZ3duQmZXWmV6WjlvR1JTWEpwZHRSR0p2YytFOENUYzg0R1JBOGZHcWI1TzhFTEtIRjdXQy9Qa0doY0RXR2pBRGZTOEN3cGJsVEtTcC9uSkliOWZ6U3ZJRkFvY3N0TytWSGJwNWt2dWhKTmI0bnJOb09Ic3NJd0siLCJtYWMiOiI2MTk4YzNjNTdmODJmNDVkZTM5YWE2OTcyNGJiYzI1MTM1ZTViYTZlZTVhZTNhMzNmY2U5NzM1OThiOTg5YThlIiwidGFnIjoiIn0%3D"); + var response = await client.SendAsync(request); + var success = response.IsSuccessStatusCode; + + if (success) + { + var res = await response.Content.ReadAsStringAsync(); + var convertedRes = JsonConvert.DeserializeObject(res); + result.IsHoliday = convertedRes.IsHoliday; + result.IsSuccess = true; + } + + return result; + } + + #endregion + + //عیدی + #region Bunoses + + public BunosesAndYearsPayStatus Bunoses(string startDateFa, DateTime leftWorkDate, DateTime separationStartDate, DateTime separationEndDate, double daylyWage, string bonusesOptions, + bool hasleft, DateTime startWorkDate, DateTime contractStart, DateTime contractEnd, long workshopId, + long employeeId, bool isOldContract) + { + BunosesAndYearsPayStatus finalResult = new BunosesAndYearsPayStatus(); + double result = 0; + // ماه فیش آخر + var checkoutMonth = startDateFa.Substring(5, 2); + var start1403 = new DateTime(2024, 3, 20); + switch (bonusesOptions) + { + case "OnCheckoutOfMonth": + + var totalCheckoutDays = (separationEndDate - separationStartDate).TotalDays + 1; + finalResult.Bunoses = ((daylyWage * 60) / 365) * totalCheckoutDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalCheckoutDays); + + break; + case "OnEndOfYear"://درپایان سال + + if (isOldContract && contractEnd < start1403) + { + var totaltDays = (separationEndDate - separationStartDate).TotalDays + 1; + finalResult.Bunoses = ((daylyWage * 60) / 365) * totaltDays; + finalResult.TotalDayCompute = Convert.ToInt32(totaltDays); + } + else if (isOldContract && contractEnd > start1403) + { + + + if ((hasleft && leftWorkDate <= separationEndDate) || checkoutMonth == "12") + { + + //بدست آوردن اولین روز سال + string startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + DateTime startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + + // اگر تاریخ شروع بکار بزرگتر مساوی روز اول همین سال بود از تازیخ شوع بکار استفاده میشود در غیر اینصورت از روز اول سال استفاده میشود + DateTime startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; + + + #region NewCompute + + //شروع دوره + string st = startComputeDay.ToFarsi(); + int syear = Convert.ToInt32(st.Substring(0, 4)); + int smonth = Convert.ToInt32(st.Substring(5, 2)); + PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); + PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); + //پایان فیش حقوقی آخر + PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); + if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) + { + var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + finalResult.Bunoses = ((daylyWage * 60) / 365) * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + else + { + var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && + x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); + //پایان دوره + PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); + List nullDateList = new List(); + double sumOfOldBonuses = 0; + var oldTotalDays = 0; + for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) + { + var searchStart = ($"{startDate}").ToGeorgianDateTime(); + var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); + var foundCheckout = checkoutList.FirstOrDefault(x => + x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); + if (foundCheckout == null) + { + nullDateList.Add(new BunosesAndYearsPayStatus() + { + ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, + ContractEnd = searchEnd + }); + finalResult.NotCompleted = true; + } + else + { + double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; + int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); + double foundDayliWage = foundMonthlySalary / foundTotaldays; + double foundYearsPay = ((foundDayliWage * 60) / 365) * foundTotaldays; + oldTotalDays += foundTotaldays; + sumOfOldBonuses += foundYearsPay; + } + + } + + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + double lastMonthBonuses = ((daylyWage * 60) / 365) * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotalDays); + finalResult.Bunoses = lastMonthBonuses + sumOfOldBonuses; + finalResult.BunosesStatusList = nullDateList; + } + + #endregion + + + } + } + else if (!isOldContract) + { + if ((hasleft && leftWorkDate <= separationEndDate) || checkoutMonth == "12") + { + //بدست آوردن اولین روز سال + var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; + #region NewCompute + + //شروع دوره + string st = startComputeDay.ToFarsi(); + int syear = Convert.ToInt32(st.Substring(0, 4)); + int smonth = Convert.ToInt32(st.Substring(5, 2)); + PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); + PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); + //پایان فیش حقوقی آخر + PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); + if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) + { + var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + finalResult.Bunoses = ((daylyWage * 60) / 365) * totalDays; + } + else + { + var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && + x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); + //پایان دوره + PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); + List nullDateList = new List(); + double sumOfOldBonuses = 0; + var oldTotalDays = 0; + for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) + { + var searchStart = ($"{startDate}").ToGeorgianDateTime(); + var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); + var foundCheckout = checkoutList.FirstOrDefault(x => + x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); + if (foundCheckout == null) + { + nullDateList.Add(new BunosesAndYearsPayStatus() + { + ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, + ContractEnd = searchEnd + }); + finalResult.NotCompleted = true; + } + else + { + double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; + int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); + double foundDayliWage = foundMonthlySalary / foundTotaldays; + double foundYearsPay = ((foundDayliWage * 60) / 365) * foundTotaldays; + oldTotalDays += foundTotaldays; + sumOfOldBonuses += foundYearsPay; + } + + } + + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + double lastMonthBonuses = ((daylyWage * 60) / 365) * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotalDays); + finalResult.Bunoses = lastMonthBonuses + sumOfOldBonuses; + finalResult.BunosesStatusList = nullDateList; + } + + #endregion + } + } + + + break; + case "OnEndOfContract"://در پایان قرارداد + + if (isOldContract && contractEnd < start1403) + { + var totaltDays = (separationEndDate - separationStartDate).TotalDays + 1; + finalResult.Bunoses = ((daylyWage * 60) / 365) * totaltDays; + } + else if (isOldContract && contractEnd > start1403) + { + if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd) + { + + //بدست آوردن اولین روز سال + //var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + //var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + + var startComputeDay = contractStart; + //var totalDays = (separationEndDate - contractStart).TotalDays + 1; + //result = (daylyWage * 60) / 365 * totalDays; + + #region NewCompute + + //شروع دوره + string st = startComputeDay.ToFarsi(); + int syear = Convert.ToInt32(st.Substring(0, 4)); + int smonth = Convert.ToInt32(st.Substring(5, 2)); + PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); + PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); + //پایان فیش حقوقی آخر + PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); + if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) + { + var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + finalResult.Bunoses = ((daylyWage * 60) / 365) * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays); + } + else + { + var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && + x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); + //پایان دوره + PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); + List nullDateList = new List(); + double sumOfOldBonuses = 0; + var oldTotalDays = 0; + for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) + { + var searchStart = ($"{startDate}").ToGeorgianDateTime(); + var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); + var foundCheckout = checkoutList.FirstOrDefault(x => + x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); + if (foundCheckout == null) + { + nullDateList.Add(new BunosesAndYearsPayStatus() + { + ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, + ContractEnd = searchEnd + }); + finalResult.NotCompleted = true; + } + else + { + double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; + int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); + double foundDayliWage = foundMonthlySalary / foundTotaldays; + double foundBonuses = ((foundDayliWage * 60) / 365) * foundTotaldays; + oldTotalDays += foundTotaldays; + sumOfOldBonuses += foundBonuses; + } + + } + + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + double lastMonthBonuses = ((daylyWage * 60) / 365) * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotalDays); + finalResult.Bunoses = lastMonthBonuses + sumOfOldBonuses; + finalResult.BunosesStatusList = nullDateList; + } + + #endregion + } + } + else if (!isOldContract) + { + if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd) + { + var startComputeDay = contractStart; + //var totalDays = (separationEndDate - contractStart).TotalDays + 1; + // finalResult.Bunoses = (daylyWage * 60) / 365 * totalDays; + + #region NewCompute + + //شروع دوره + string st = startComputeDay.ToFarsi(); + int syear = Convert.ToInt32(st.Substring(0, 4)); + int smonth = Convert.ToInt32(st.Substring(5, 2)); + PersianDateTime startPeriod = new PersianDateTime(syear, smonth, 1); + PersianDateTime startPeriodGr = new PersianDateTime(syear, smonth, 1); + //پایان فیش حقوقی آخر + PersianDateTime endCheckout = separationEndDate.ToPersianDateTime(); + if (startPeriod.Year == endCheckout.Year && startPeriod.Month == endCheckout.Month) + { + var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + finalResult.Bunoses = ((daylyWage * 60) / 365) * totalDays; + } + else + { + var checkoutList = _context.CheckoutSet.Where(x => x.EmployeeId == employeeId && x.WorkshopId == workshopId && + x.ContractStart >= startComputeDay && x.ContractEnd < separationStartDate).AsEnumerable(); + //پایان دوره + PersianDateTime endPeriod = (separationStartDate.AddDays(-1)).ToPersianDateTime(); + List nullDateList = new List(); + double sumOfOldBonuses = 0; + var oldTotalDays = 0; + for (var startDate = startPeriod; startDate <= endPeriod; startDate = startDate.AddMonths(1)) + { + var searchStart = ($"{startDate}").ToGeorgianDateTime(); + var searchEnd = (($"{startDate}").FindeEndOfMonth()).ToGeorgianDateTime(); + var foundCheckout = checkoutList.FirstOrDefault(x => + x.ContractStart >= searchStart && x.ContractEnd <= searchEnd); + if (foundCheckout == null) + { + nullDateList.Add(new BunosesAndYearsPayStatus() + { + ContractStart = startDate == startPeriodGr ? startComputeDay : searchStart, + ContractEnd = searchEnd + }); + finalResult.NotCompleted = true; + } + else + { + double foundMonthlySalary = foundCheckout.MonthlySalary + foundCheckout.BaseYearsPay; + int foundTotaldays = Convert.ToInt32(foundCheckout.SumOfWorkingDays); + double foundDayliWage = foundMonthlySalary / foundTotaldays; + double foundBonuses = ((foundDayliWage * 60) / 365) * foundTotaldays; + oldTotalDays += foundTotaldays; + sumOfOldBonuses += foundBonuses; + } + + } + + var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + double lastMonthBonuses = ((daylyWage * 60) / 365) * totalDays; + finalResult.TotalDayCompute = Convert.ToInt32(totalDays + oldTotalDays); + finalResult.Bunoses = lastMonthBonuses + sumOfOldBonuses; + finalResult.BunosesStatusList = nullDateList; + } + + #endregion + } + } + + break; + //case "EndOfContract1402LeftWork1403": //پایان قرارداد قبل 403 پایان همکاری بعد 403 + + // if (contractStart >= start1403 && contractEnd > start1403)// بعد از 1403 + // { + // if (hasleft && leftWorkDate <= separationEndDate) + // { + // //بدست آوردن اولین روز سال + // var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + // var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + + // // اگر تاریخ شروع بکار بزرگتر مساوی روز اول همین سال بود از تازیخ شوع بکار استفاده میشود در غیر اینصورت از روز اول سال استفاده میشود + // var startComputeDay = startWorkDate >= startDayOfYearGr ? startWorkDate : startDayOfYearGr; + // var totalDays = (separationEndDate - startComputeDay).TotalDays + 1; + // result = (daylyWage * 60) / 365 * totalDays; + // } + // } + // else if (contractStart < start1403)// قبل از 1403 + // { + // var totalDays = (separationEndDate - separationStartDate).TotalDays + 1; + // finalResult.Bunoses = (daylyWage * 60) / 365 * totalDays; + + // //if ((hasleft && leftWorkDate <= separationEndDate) || separationEndDate == contractEnd || checkoutMonth == "12") + // //{ + // // //بدست آوردن اولین روز سال + // // var startDayOfYear = $"{startDateFa.Substring(0, 4)}/01/01"; + // // var startDayOfYearGr = startDayOfYear.ToGeorgianDateTime(); + + // // var startComputeDay = contractStart >= startDayOfYearGr ? contractStart : startDayOfYearGr; + + // //} + // } + // break; + + default: + finalResult.Bunoses = 0; + finalResult.TotalDayCompute = 0; + break; + } + + return finalResult; + } + + + + #endregion + + + #region Insurance + + public InsuranceYearlySalaryModel GetInsuranceItems(DateTime startDate, DateTime endDate, string year) + { + var query = _context.YearlySalaries + .Where(x => x.StartDate <= startDate && x.EndDate >= endDate && x.Year == year) + .Include(x => x.YearlySalaryItemsList) + .Select(x => new InsuranceYearlySalaryModel + { + DayliWage = x.YearlySalaryItemsList.FirstOrDefault(item => item.ItemName == "مزد روزانه").ItemValue, + ConsumableItems = x.YearlySalaryItemsList.FirstOrDefault(item => item.ItemName == "کمک هزینه اقلام").ItemValue, + HousingAllowance = x.YearlySalaryItemsList.FirstOrDefault(item => item.ItemName == "کمک هزینه مسکن").ItemValue, + MarriedAllowance = x.YearlySalaryItemsList.Any(item => item.ItemName == "حق تاهل") ? x.YearlySalaryItemsList.FirstOrDefault(item => item.ItemName == "حق تاهل").ItemValue : 0, + + }).FirstOrDefault(); + + return query; + } + + #endregion + + + private double GetRoundValue(double value) + { + string strValue = value.ToString(); + if (strValue.IndexOf('.') > -1) + { + + + string a = strValue.Substring(strValue.IndexOf('.') + 1, 1); + if (int.Parse(a) > 3) + { + return (Math.Round(value, MidpointRounding.ToPositiveInfinity)); + } + else + { + return (Math.Round(value, MidpointRounding.ToNegativeInfinity)); + } + } + + return value; + } } diff --git a/ServiceHost/Areas/Admin/Pages/Company/Checkouts/PrintDetailsRollCall.cshtml b/ServiceHost/Areas/Admin/Pages/Company/Checkouts/PrintDetailsRollCall.cshtml index 4e9378ab..bfc8dc07 100644 --- a/ServiceHost/Areas/Admin/Pages/Company/Checkouts/PrintDetailsRollCall.cshtml +++ b/ServiceHost/Areas/Admin/Pages/Company/Checkouts/PrintDetailsRollCall.cshtml @@ -1,7 +1,7 @@ @using _0_Framework.Application @model CompanyManagment.App.Contracts.Checkout.CheckoutViewModel @{ - string adminVersion = _0_Framework.Application.Version.AdminVersion; + string adminVersion = _0_Framework.Application.Version.AdminVersion; } @@ -19,18 +19,18 @@ -
-
- @{ - if (@Model.EmployerList.FirstOrDefault().IsLegal == "حقیقی") - { -
-
- نام کارگاه: - @Model.WorkshopName + } +
+
+ به کد ملی: + @if (string.IsNullOrWhiteSpace(@Model.NationalCode)) + { + + } + else + { + + @Model.NationalCode + + } +
+
+ متولد: + @if (string.IsNullOrWhiteSpace(@Model.DateOfBirth)) + { + 1401/01/01 + } + else + { + @Model.DateOfBirth + } +
+
+
+
+
+ @{ + if (@Model.EmployerList.FirstOrDefault().IsLegal == "حقیقی") + { +
+
+ نام کارگاه: + @Model.WorkshopName +
-
-
- نام کارفرما: - @if (Model.EmployerList.Count > 1) - { +
+ نام کارفرما: + @if (Model.EmployerList.Count > 1) + { + + @Model.EmployerList[0].EmployerFullName ، +  @Model.EmployerList[1].EmployerFullName + @if (@Model.EmployerList.Count > 2) + { + و غیره + } + + } + else + { + + @Model.EmployerList.FirstOrDefault().EmployerFullName + + } +
+ + } + else if (@Model.EmployerList.FirstOrDefault().IsLegal == "حقوقی") + { +
+ پـرسنل شرکت/موسسه: - @Model.EmployerList[0].EmployerFullName ، -  @Model.EmployerList[1].EmployerFullName - @if (@Model.EmployerList.Count > 2) - { - و غیره - } + @Model.WorkshopName - } - else - { - - @Model.EmployerList.FirstOrDefault().EmployerFullName - - } -
+
+ } + } +
+
+ @{ + var items = new List(); + if (Model.MonthlySalary != "0") items.Add("حقوق و مزد"); + if (Model.ConsumableItems != "0") items.Add("کمک هزینه اقلام مصرفی خانوار"); + if (Model.HousingAllowance != "0") items.Add("کمک هزینه مسکن"); + if (!string.IsNullOrWhiteSpace(Model.OvertimePay) && Model.OvertimePay != "0") items.Add("فوق العاده اضافه کاری"); + if (!string.IsNullOrWhiteSpace(Model.NightworkPay) && Model.NightworkPay != "0") items.Add("فوق العاده شب کاری"); + if (!string.IsNullOrWhiteSpace(Model.FridayPay) && Model.FridayPay != "0") items.Add("فوق العاده جمعه کاری"); + if (Model.MissionPay != "0") items.Add("فوق العاده ماموریت"); + if (Model.ShiftPay != "0") items.Add("فوق العاده نوبت کاری"); + if (Model.FamilyAllowance != "0") items.Add("کمک هزینه عائله مندی"); + if (Model.MarriedAllowance != "0") items.Add("حق تاهل"); + if (Model.RewardPay != "0") items.Add("پاداش"); + if (Model.BonusesPay != "0") items.Add("عیدی و پاداش"); + if (Model.YearsPay != "0") items.Add("سنوات"); + if (Model.LeavePay != "0") items.Add("مزد مرخصی"); + + string finalText = ""; + if (items.Count == 1) + { + finalText = items[0]; + } + else if (items.Count > 1) + { + finalText = string.Join("، ", items.Take(items.Count - 1)) + " و " + items.Last(); + } } - else if (@Model.EmployerList.FirstOrDefault().IsLegal == "حقوقی") - { -
- پـرسنل شرکت/موسسه: - - @Model.WorkshopName - -
- } - } + + + کلیه حق السعی خود اعم از @Html.Raw(finalText) @Model.Month ماه سال @Model.Year برابر با قرارداد به شماره فوق را از کارفرما بصورت وجه نقد و واریز به حساب دریافت نموده ام. + +
-
- @{ - var items = new List(); +
+ - if (Model.MonthlySalary != "0") items.Add("حقوق و مزد"); - if (Model.ConsumableItems != "0") items.Add("کمک هزینه اقلام مصرفی خانوار"); - if (Model.HousingAllowance != "0") items.Add("کمک هزینه مسکن"); - if (!string.IsNullOrWhiteSpace(Model.OvertimePay) && Model.OvertimePay != "0") items.Add("فوق العاده اضافه کاری"); - if (!string.IsNullOrWhiteSpace(Model.NightworkPay) && Model.NightworkPay != "0") items.Add("فوق العاده شب کاری"); - if (!string.IsNullOrWhiteSpace(Model.FridayPay) && Model.FridayPay != "0") items.Add("فوق العاده جمعه کاری"); - if (Model.MissionPay != "0") items.Add("فوق العاده ماموریت"); - if (Model.ShiftPay != "0") items.Add("فوق العاده نوبت کاری"); - if (Model.FamilyAllowance != "0") items.Add("کمک هزینه عائله مندی"); - if (Model.MarriedAllowance != "0") items.Add("حق تاهل"); - if (Model.RewardPay != "0") items.Add("پاداش"); - if (Model.BonusesPay != "0") items.Add("عیدی و پاداش"); - if (Model.YearsPay != "0") items.Add("سنوات"); - if (Model.LeavePay != "0") items.Add("مزد مرخصی"); - string finalText = ""; - if (items.Count == 1) - { - finalText = items[0]; - } - else if (items.Count > 1) - { - finalText = string.Join("، ", items.Take(items.Count - 1)) + " و " + items.Last(); - } - } +
+
+ - - کلیه حق السعی خود اعم از @Html.Raw(finalText) @Model.Month ماه سال @Model.Year برابر با قرارداد به شماره فوق را از کارفرما بصورت وجه نقد و واریز به حساب دریافت نموده ام. - - - - - - - -
-
-
- - - @* *@ - - @* + + @* *@ + + @* *@ - - @* + + @* *@ - + - - - - - - - - - + + + + + + + + + - - - - - - - - - + + + + + + + + + - - - - - - - - - + + + + + + + + + - - - - - - - - - + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @{ - if (Model.IsLeft) - { - - } - else - { + + + + + + + + + + + + + + + + + + + + + + + - } - } - - - - - - - - - @{ - if (!Model.IsLeft) - { + + + + + + - } - } - - - - - - - - @{ - if (!Model.IsLeft) - { + + + + + + - } - } - - - - - - - - - - - - - - - - - - - -
مطالبات
مطالبات کسورات کسورات
ردیف شرح ساعت/روز/تعداد مبلغ(ریال) شرح ساعت/روز/تعداد مبلغ(ریال)
ردیف شرح ساعت/روز/تعداد مبلغ(ریال) شرح ساعت/روز/تعداد مبلغ(ریال)
1 حقوق و مزد @Model.SumOfWorkingDays @(Model.MonthlySalary == "0" ? "-" : Model.MonthlySalary) حق بیمه سهم کارگر - @(Model.InsuranceDeduction == "0" ? "-" : Model.InsuranceDeduction)
1 حقوق و مزد @Model.SumOfWorkingDays @(Model.MonthlySalary == "0" ? "-" : Model.MonthlySalary) حق بیمه سهم کارگر - @(Model.InsuranceDeduction == "0" ? "-" : Model.InsuranceDeduction)
2 پایه سنوات @(Model.BaseYearsPay == "0" ? "-" : Model.SumOfWorkingDays) @(Model.BaseYearsPay == "0" ? "-" : Model.BaseYearsPay) مالیات بر حقوق - @(Model.TaxDeducation == "0" ? "-" : Model.TaxDeducation)
2 پایه سنوات @(Model.BaseYearsPay == "0" ? "-" : Model.SumOfWorkingDays) @(Model.BaseYearsPay == "0" ? "-" : Model.BaseYearsPay) مالیات بر حقوق - @(Model.TaxDeducation == "0" ? "-" : Model.TaxDeducation)
3 کمک هزینه اقلام مصرفی خانوار @(Model.ConsumableItems == "0" ? "-" : Model.SumOfWorkingDays) @(Model.ConsumableItems == "0" ? "-" : Model.ConsumableItems) قسط تسهیلات - @(Model.InstallmentDeduction == "0" ? "-" : Model.InstallmentDeduction)
3 کمک هزینه اقلام مصرفی خانوار @(Model.ConsumableItems == "0" ? "-" : Model.SumOfWorkingDays) @(Model.ConsumableItems == "0" ? "-" : Model.ConsumableItems) قسط تسهیلات - @(Model.InstallmentDeduction == "0" ? "-" : Model.InstallmentDeduction)
4 کمک هزینه مسکن @(Model.HousingAllowance == "0" ? "-" : Model.SumOfWorkingDays) @(Model.HousingAllowance == "0" ? "-" : Model.HousingAllowance) مساعده - @(Model.SalaryAidDeduction == "0" ? "-" : Model.SalaryAidDeduction)
5 فوق العاده اضافه کاری @((Model.OverTimeWorkValue == "00:00" || string.IsNullOrWhiteSpace(Model.OverTimeWorkValue)) ? "-" : Model.OverTimeWorkValue) @((Model.OvertimePay == "0" || string.IsNullOrWhiteSpace(Model.OvertimePay)) ? "-" : Model.OvertimePay) غیبت - @(Model.AbsenceDeduction == "0" ? "-" : Model.AbsenceDeduction)
6 فوق العاده شب کاری @((Model.OverNightWorkValue == "00:00" || string.IsNullOrWhiteSpace(Model.OverNightWorkValue)) ? "-" : Model.OverNightWorkValue) @((Model.NightworkPay == "0" || string.IsNullOrWhiteSpace(Model.NightworkPay)) ? "-" : Model.NightworkPay)
7 فوق العاده جمعه کاری @((Model.FridayWorkValue == "0" || string.IsNullOrWhiteSpace(Model.FridayWorkValue)) ? "-" : Model.FridayWorkValue) @((Model.FridayPay == "0" || string.IsNullOrWhiteSpace(Model.FridayPay)) ? "-" : Model.FridayPay)
8 فوق العاده ماموریت - @(Model.MissionPay == "0" ? "-" : Model.MissionPay)
9 فوق العاده نوبت کاری @((Model.RotatingShiftValue == "0" || string.IsNullOrWhiteSpace(Model.RotatingShiftValue)) ? "-" : "%" + Model.RotatingShiftValue) @(Model.ShiftPay == "0" ? "-" : Model.ShiftPay)
10 کمک هزینه عائله مندی - @(Model.FamilyAllowance == "0" ? "-" : Model.FamilyAllowance)
11 حق تاهل @Model.MaritalStatus @(Model.MarriedAllowance == "0" ? "-" : Model.MarriedAllowance)
12 پاداش - @(Model.RewardPay == "0" ? "-" : Model.RewardPay)
13 عیدی و پاداش @(Model.BonusesPay == "0" ? "-" : Model.SumOfWorkingDays) @(Model.BonusesPay == "0" ? "-" : Model.BonusesPay) -
-
- طبق تصفیه حساب نهایی تنظیمی فوق، آخرین روز اشتغال بکار اینجانب - @Model.LastDayOfWork - بوده و قطع همکاری با کارفرما و کارگاه از تاریخ - @Model.LeftWorkDate - می باشد -
-
-
4 کمک هزینه مسکن @(Model.HousingAllowance == "0" ? "-" : Model.SumOfWorkingDays) @(Model.HousingAllowance == "0" ? "-" : Model.HousingAllowance) مساعده - @(Model.SalaryAidDeduction == "0" ? "-" : Model.SalaryAidDeduction)
5 فوق العاده اضافه کاری @((Model.OverTimeWorkValue == "00:00" || string.IsNullOrWhiteSpace(Model.OverTimeWorkValue)) ? "-" : Model.OverTimeWorkValue) @((Model.OvertimePay == "0" || string.IsNullOrWhiteSpace(Model.OvertimePay)) ? "-" : Model.OvertimePay) غیبت - @(Model.AbsenceDeduction == "0" ? "-" : Model.AbsenceDeduction)
6 فوق العاده شب کاری @((Model.OverNightWorkValue == "00:00" || string.IsNullOrWhiteSpace(Model.OverNightWorkValue)) ? "-" : Model.OverNightWorkValue) @((Model.NightworkPay == "0" || string.IsNullOrWhiteSpace(Model.NightworkPay)) ? "-" : Model.NightworkPay)
14 سنوات @(Model.YearsPay == "0" ? "-" : Model.SumOfWorkingDays) @(Model.YearsPay == "0" ? "-" : Model.YearsPay)
7 فوق العاده جمعه کاری @((Model.FridayWorkValue == "0" || string.IsNullOrWhiteSpace(Model.FridayWorkValue)) ? "-" : Model.FridayWorkValue) @((Model.FridayPay == "0" || string.IsNullOrWhiteSpace(Model.FridayPay)) ? "-" : Model.FridayPay)
15 مزد مرخصی @(Model.LeavePay == "0" ? "-" : Model.SumOfWorkingDays) @(Model.LeavePay == "0" ? "-" : Model.LeavePay)
8 فوق العاده ماموریت - @(Model.MissionPay == "0" ? "-" : Model.MissionPay)
جمع مطالبات - @(Model.TotalClaims == "0" ? "-" : Model.TotalClaims) جمع کسورات - @(Model.TotalDeductions == "0" ? "-" : Model.TotalDeductions)
مبلغ قابل پرداخت @(Model.TotalPayment == "0" ? "-" : Model.TotalPayment)
-
-
+ + + 9 + فوق العاده نوبت کاری + @((Model.RotatingShiftValue == "0" || string.IsNullOrWhiteSpace(Model.RotatingShiftValue)) ? "-" : "%" + Model.RotatingShiftValue) + @(Model.ShiftPay == "0" ? "-" : Model.ShiftPay) + + + + + + 10 + کمک هزینه عائله مندی + - + @(Model.FamilyAllowance == "0" ? "-" : Model.FamilyAllowance) + + + + + + 11 + حق تاهل + @Model.MaritalStatus + @(Model.MarriedAllowance == "0" ? "-" : Model.MarriedAllowance) + + + + + + 12 + پاداش + - + @(Model.RewardPay == "0" ? "-" : Model.RewardPay) + + + + + + 13 + عیدی و پاداش + @(Model.BonusesPay == "0" ? "-" : Model.SumOfWorkingDays) + @(Model.BonusesPay == "0" ? "-" : Model.BonusesPay) + + @{ + if (Model.IsLeft) + { + +
+
+ طبق تصفیه حساب نهایی تنظیمی فوق، آخرین روز اشتغال بکار اینجانب + @Model.LastDayOfWork + بوده و قطع همکاری با کارفرما و کارگاه از تاریخ + @Model.LeftWorkDate + می باشد +
+
+ + } + else + { + + + + } + } + + + + 14 + سنوات + @(Model.YearsPay == "0" ? "-" : Model.SumOfWorkingDays) + @(Model.YearsPay == "0" ? "-" : Model.YearsPay) + + @{ + if (!Model.IsLeft) + { + + + + } + } + + + 15 + مزد مرخصی + @(Model.LeavePay == "0" ? "-" : Model.SumOfWorkingDays) + @(Model.LeavePay == "0" ? "-" : Model.LeavePay) + + @{ + if (!Model.IsLeft) + { + + + + } + } + + + + جمع مطالبات + - + @(Model.TotalClaims == "0" ? "-" : Model.TotalClaims) + جمع کسورات + - + @(Model.TotalDeductions == "0" ? "-" : Model.TotalDeductions) + + + + مبلغ قابل پرداخت + + @(Model.TotalPayment == "0" ? "-" : Model.TotalPayment) + + + + + + +
@@ -580,47 +580,47 @@
-
-
+
+
-
- - - - - +
+
+ + + + - - - + + + - - - - + + + + - @for (int i = 0; i < 5; i++) - { - - - - - } + @for (int i = 0; i < 5; i++) + { + + + + + } -
مساعده
مساعده
تاریخمبلغ
تاریخمبلغ
- @(Model.SalaryAidViewModels != null && i < Model.SalaryAidViewModels.Count - ? Model.SalaryAidViewModels[i]?.SalaryAidDateTimeFa ?? "" - : "") - - @(Model.SalaryAidViewModels != null && i < Model.SalaryAidViewModels.Count - ? Model.SalaryAidViewModels[i]?.Amount ?? "" - : "") -
+ @(Model.SalaryAidViewModels != null && i < Model.SalaryAidViewModels.Count + ? Model.SalaryAidViewModels[i]?.SalaryAidDateTimeFa ?? "" + : "") + + @(Model.SalaryAidViewModels != null && i < Model.SalaryAidViewModels.Count + ? Model.SalaryAidViewModels[i]?.Amount ?? "" + : "") +
+ -
+
+ +
- -
@@ -680,7 +680,7 @@
- +
@@ -690,7 +690,7 @@ - + diff --git a/ServiceHost/Areas/AdminNew/Pages/Company/AndroidApk/Index.cshtml b/ServiceHost/Areas/AdminNew/Pages/Company/AndroidApk/Index.cshtml index 59293939..b0b19817 100644 --- a/ServiceHost/Areas/AdminNew/Pages/Company/AndroidApk/Index.cshtml +++ b/ServiceHost/Areas/AdminNew/Pages/Company/AndroidApk/Index.cshtml @@ -5,13 +5,13 @@ }

Upload File

-@*
+
-
*@ +