using System; using Ease.Core.Model; using Ease.Core.DataAccess; using Ease.Core.Utility; using System.Collections.Generic; using HRM.BO; using System.Data; using System.Linq; using System.IO; using HRM.DA.Service.Tax; using System.Globalization; using static iTextSharp.text.pdf.AcroFields; using Microsoft.AspNetCore.Http; using System.Xml; using Org.BouncyCastle.Asn1.Pkcs; using static System.Runtime.InteropServices.JavaScript.JSType; using Org.BouncyCastle.Utilities; using HRM.DA.Fund; using System.Security.Principal; using System.Text.RegularExpressions; using NPOI.SS.Formula.Functions; using static NPOI.HSSF.Util.HSSFColor; using Microsoft.AspNetCore.Http.HttpResults; namespace HRM.DA { public class RegularDataUploadService : ServiceTemplate //, IRegularDataUploadService { private DataUploadColumnDefinationService _columndefinfationService; private List _errorOrSuccessList; private DataTable _uplodedData; private DataSet _uploadHRData; private DataSet _upLoadCVData; private BonusProcess _BonusProcess = null; private HREmployee _HREmployee = new HREmployee(); private CV _CV = new CV(); private List _HREmployees = null; private List _Occupations = null; private List _Nationalites = null; private List _Districts = null; private List _Thanas = null; private List _Relations = null; private List _EducationLevels = null; private List _NatureOfTrainings = null; private List _Institutions = null; private List _Contries = null; private List _EducationTypes = null; private List _Disciplines = null; private List _ResultTypes = null; private List _NominationPurposes = null; private List _GuarantorDocumentTypes = null; private List _TrainingTypes = null; private List _HRJoiningQuestionaries = null; private List _EmployeeTaxInvestments = null; private List _EmpTaxAitList = null; private List _TaxChallans = null; private List _DailyAttnProcess = null; List _CheckHREmployees = null; private List _PFTransactions = null; private List aProcessDetailItems = null; private List _empLifeCycles = null; private List _incomeTaxes = new List(); int nMasterCount = 0; int _payrollTypeID = 0; int _userID = 0; int nOrgRowCount; List oParentOrganogramNodes = null; List _oOrganogramNodes = new List(); private List _employeesForSave = null; private List _employeesForUpdate = null; private DataUploadException _uploadException; List memberTrans = new List(); List membersMonthlyBalances = new List(); public RegularDataUploadService() { } #region Service Implementation //public DataTable LoadData(string fileName) //{ // return this.LoadExcelData(fileName); // #region Old Code // //DataTable dt = new DataTable("ImportedData"); // //try // //{ // // using (FileStream fs = new FileStream(fileName, FileMode.Open)) // // { // // XlsReader reader = new XlsReader(fs, true); // // dt = reader.Data.Tables[0].Copy(); // // fs.Close(); // // fs.Dispose(); // // reader = null; // // } // //} // //catch (Exception e) // //{ // // throw new ServiceException(e.Message, e); // //} // //return dt; // #endregion //} //public DataTable LoadData(string fileName, string sheetName) //{ // return this.LoadExcelData(fileName, sheetName); // #region Old Code // //DataTable dt = new DataTable(sheetName); // //try // //{ // // using (FileStream fs = new FileStream(fileName, FileMode.Open)) // // { // // XlsReader reader = new XlsReader(fs, true); // // dt = reader.Data.Tables[0].Copy(); // // fs.Close(); // // fs.Dispose(); // // reader = null; // // } // //} // //catch (Exception e) // //{ // // throw new ServiceException(e.Message, e); // //} // //return dt; // #endregion //} //public DataTable LoadExcelData(string fileName, string sheetName) //{ // string connectionString = string.Empty; // if (fileName.EndsWith("xls")) // //Connection string for office 2003 // connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", fileName); // else // //Connection string for office 2007 // connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0 Xml;", fileName); // DataTable dt = new DataTable(sheetName); // try // { // OleDbConnection connection = new OleDbConnection(connectionString); // connection.Open(); // DataTable excelTable = connection.GetSchema("Tables"); // string tableName; // if (excelTable.Rows.Count > 0) // { // tableName = Convert.ToString(excelTable.Rows[0]["TABLE_NAME"]); // OleDbDataAdapter dataAdapter = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", sheetName + "$"), connection); // //dt.TableName = sheetName; // dataAdapter.Fill(dt); // dataAdapter = null; // } // connection.Close(); // connection = null; // } // catch (Exception ex) // { // throw new Exception(ex.Message); // } // return dt; //} //public DataTable LoadExcelData(string fileName) //{ // string connectionString = string.Empty; // if(fileName.EndsWith("xls")) // //Connection string for office 2003 // connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", fileName); // else // //Connection string for office 2007 // connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0 Xml;", fileName); // DataTable dt = new DataTable(); // try // { // OleDbConnection connection = new OleDbConnection(connectionString); // connection.Open(); // DataTable excelTable = connection.GetSchema("Tables"); // string tableName; // if (excelTable.Rows.Count > 0) // { // tableName = Convert.ToString(excelTable.Rows[0]["TABLE_NAME"]); // OleDbDataAdapter dataAdapter = new OleDbDataAdapter(string.Format("SELECT DISTINCT * FROM [{0}]", tableName), connection); // dt.TableName = tableName.Substring(0, tableName.Length - 1); // dataAdapter.Fill(dt); // dataAdapter = null; // } // connection.Close(); // connection = null; // } // catch (Exception ex) // { // throw new Exception(ex.Message); // } // return dt; //} public List ValidateUploadedData(DataUploadColumnDefinition columnDefinition, DataTable uploadedData) { DataUploadValidation ovalidation = new DataUploadValidation(); ovalidation.ColumnNameValidation(columnDefinition, uploadedData); if (ovalidation.ErrorOrSuccessList.Count > 0) return ovalidation.ErrorOrSuccessList; ovalidation.ValidateInput(columnDefinition, uploadedData); return ovalidation.ErrorOrSuccessList; } /// /// Regular Data Upload /// /// /// /// /// /// /// /// /// /// /// /// /// public List UploadData(int uploadId, DataUploadColumnDefinition oColumnDefination, System.IO.Stream fileStream, int payrollTypeID, int userID, int? itemid, DateTime selecteDate) { _uplodedData = ExtractFromExcel(fileStream, oColumnDefination.SheetName); _errorOrSuccessList = this.ValidateUploadedData(oColumnDefination, _uplodedData); oColumnDefination.PayrollTypeID = payrollTypeID; //oColumnDefination.SelectedItemOneID = itemid != null ? (int)itemid : 0; this._payrollTypeID = oColumnDefination.PayrollTypeID; this._userID = userID; if (_errorOrSuccessList.Count > 0) return _errorOrSuccessList; List employees = new EmployeeService().GetAllEmps(); List discontinuedEmployeeNos = new List(); //foreach (DataRow row in _uplodedData.Rows) //{ // string employeeNo = row["Employee No"].ToString(); // Employee employee = employees.FirstOrDefault(e => e.EmployeeNo == employeeNo); // if(employee?.Status == EnumEmployeeStatus.Discontinued) // { // discontinuedEmployeeNos.Add(employeeNo); // } //} //if(discontinuedEmployeeNos.Count>0) { // string disConEmpNo = string.Join(", ", discontinuedEmployeeNos); // throw new Exception(disConEmpNo +" employee(s) are discontinued"); //} switch (uploadId) { case (int)EnumRegularDataUpload.EmployeeWithBasic: this.ImportEmpBasicInfo(uploadId); break; case (int)EnumRegularDataUpload.EmployeeRegularUpload: this.ImportEmpBasicInfo(uploadId); break; case (int)EnumRegularDataUpload.EmployeeProfileUpload: this.ImportEmployeeProfileInfo(); break; case (int)EnumRegularDataUpload.LifeCycle: this.importLifeCycle(oColumnDefination); break; //case (int)EnumRegularDataUpload.EmployeeDepartmentBasic: // this.ImportDeptInfo(); // break; case (int)EnumRegularDataUpload.Allowance: this.ImportEmpIndividualAllowanceDeduction(oColumnDefination, EnumAllowOrDeduct.Allowance); break; case (int)EnumRegularDataUpload.TaxInvestment: this.ImportTaxInvestmentData(oColumnDefination, (int)itemid); break; //case (int)EnumRegularDataUpload.LTAdata: // this.ImportLTAData(oColumnDefination); // break; //case (int)EnumRegularDataUpload.ExceptionAllowance: // this.ImportEmpExceptionAllowance(oColumnDefination); // break; //case (int)EnumRegularDataUpload.EmpWorkPlanSetup: // this.ImportEmpWorkPlanSetup(oColumnDefination); // break; //case (int)EnumRegularDataUpload.NotApplicableAllowance: // this.ImportEmpNotApplicableAllowance(oColumnDefination); // break; case (int)EnumRegularDataUpload.TaxChallan: this.ImportITChallan(oColumnDefination); break; //case (int)EnumRegularDataUpload.EmpCardInfo: // this.ImportEmpCardInfo(oColumnDefination); // break; case (int)EnumRegularDataUpload.Deduction: this.ImportEmpIndividualAllowanceDeduction(oColumnDefination, EnumAllowOrDeduct.Deduction); break; //case (int)EnumRegularDataUpload.EmpDiscontinue: // break; case (int)EnumRegularDataUpload.EmployeeBankAccount: this.ImportEmpBankAccount(oColumnDefination); break; //case (int)EnumRegularDataUpload.EmployeeConfirmation: // break; //case (int)EnumRegularDataUpload.ESB: // break; //case (int)EnumRegularDataUpload.ITInvestment: // this.ImportITInvestment(oColumnDefination); // break; //case (int)EnumRegularDataUpload.Leave: // break; case (int)EnumRegularDataUpload.OPI: this.ImportOPIDataNew(oColumnDefination); break; //case (int)EnumRegularDataUpload.SalaryData: // break; //case (int)EnumRegularDataUpload.SalaryRemarks: // break; case (int)EnumRegularDataUpload.TaxAdjustCurrYear: this.ImportTaxAdjustmentData(oColumnDefination); break; //case (int)EnumRegularDataUpload.WPPFAllowance: // this.ImportWPPFAllowance(oColumnDefination); // break; //case (int)EnumRegularDataUpload.TC: // break; //case (int)EnumRegularDataUpload.EmpGradeSalary: // this.ImportEmpGradeSalaryAssignment(oColumnDefination); // break; //case (int)EnumRegularDataUpload.Organogram: // this.ImportOrganogram(oColumnDefination); // break; case (int)EnumRegularDataUpload.EmployeeAttendance: case (int)EnumRegularDataUpload.EmployeeAttendanceLM: case (int)EnumRegularDataUpload.EmployeeAttendanceCordinator: this.ImportEmployeeAttendance(oColumnDefination, payrollTypeID); break; case (int)EnumRegularDataUpload.TaxData: this.ImportTaxDataInfo(oColumnDefination); break; case (int)EnumRegularDataUpload.EmployeeLoan: this.ImportEmpLoanInformation(oColumnDefination); break; //case (int)EnumRegularDataUpload.EmployeeLoanSetup: // this.ImportEmpLoanSetup(oColumnDefination); // break; case (int)EnumRegularDataUpload.EmpSalaryComponent: this.ImportSalaryComponent(oColumnDefination); break; case (int)EnumRegularDataUpload.EmpCC: this.ImportEmpCC(oColumnDefination, this._userID); break; case (int)EnumRegularDataUpload.PFOpening: this.ImportPFOpening(oColumnDefination); break; case (int)EnumRegularDataUpload.PFYearlyInterest: this.ImportPFYearlyInterest(oColumnDefination); break; //case (int)EnumRegularDataUpload.EmpVendorCode: // this.ImportEmpVendorCode(oColumnDefination); // break; //case (int)EnumRegularDataUpload.OPI_Parameter_Individual: // //this.ImportOPIData(oColumnDefination); // this.ImportOPIParamInividual(oColumnDefination); // break; //case (int)EnumRegularDataUpload.EmpAddressData: // //this.ImportOPIData(oColumnDefination); // //this.ImportOPIParamInividual(oColumnDefination); // this.ImportAllEmpContactInfo(oColumnDefination); // break; //case (int)EnumRegularDataUpload.OrganogramData: // this.ImportOrganogramData(oColumnDefination); // break; case (int)EnumRegularDataUpload.EmployeeLineManagerUpload: this.ImportLineManager(oColumnDefination); break; case (int)EnumRegularDataUpload.LeaveBalance: this.ImportLeaveBalance(oColumnDefination); break; case (int)EnumRegularDataUpload.LeaveEncashDays: this.ImportLeaveEncashDays(oColumnDefination); break; case (int)EnumRegularDataUpload.LeaveEntry: this.ImportLeaveEntry(oColumnDefination); break; case (int)EnumRegularDataUpload.LeaveEntryLf: //Only For Li&Fung this.ImportLeaveEntryLf(oColumnDefination, userID); break; case (int)EnumRegularDataUpload.AitUpload: this.ImportAitData(oColumnDefination); break; case (int)EnumRegularDataUpload.OTImport: this.ImportOtUpload(oColumnDefination, payrollTypeID, selecteDate, userID); break; case (int)EnumRegularDataUpload.EmpWorkplanUpload: this.ImportEmployeeWorkplan(oColumnDefination, payrollTypeID, userID); break; case (int)EnumRegularDataUpload.TemporaryShiftAssignmentUpload: this.ImportTemporaryShiftAssignment(payrollTypeID, userID); break; case (int)EnumRegularDataUpload.CoordinatorUpload: this.ImportCoOrdinator(oColumnDefination); break; case (int)EnumRegularDataUpload.TaxAdjustmentDataUpload: this.ImportTaxAdjustmentData(oColumnDefination); break; case (int)EnumRegularDataUpload.EmpCardInfo: this.ImportAssingedCard(oColumnDefination, payrollTypeID); break; //case (int)EnumRegularDataUpload.TaxChallan: // this.ImportITChallan(oColumnDefination); // break; case (int)EnumRegularDataUpload.TrainingEnrollment: this.ImportTrainingEnrollment(oColumnDefination); break; case (int)EnumRegularDataUpload.TrainingAttendance: this.ImportTrainingAttendance(oColumnDefination); break; case (int)EnumRegularDataUpload.Objective: this.ImportObjectiveUpload(oColumnDefination, payrollTypeID, (int)itemid); break; case (int)EnumRegularDataUpload.SecondLineManagerObjectiveRating: this.ImportSecondLineManagerRatingUpload(oColumnDefination, payrollTypeID, (int)itemid); break; case (int)EnumRegularDataUpload.CVUpload: this.ImportCV(oColumnDefination); break; case (int)EnumRegularDataUpload.MemberOpeningBalanceUpload: this.ImportMemberOpeningBalance(oColumnDefination); break; case (int)EnumRegularDataUpload.MemberContributionUpload: this.ImportMemberContribution(oColumnDefination); break; case (int)EnumRegularDataUpload.MemberVoluntaryContributionUpload: this.ImportMemberVoluntaryContribution(oColumnDefination); break; case (int)EnumRegularDataUpload.MemberLoanScheduleInfoUpload: this.ImportMemberLoanScheduleInfo(oColumnDefination); break; case (int)EnumRegularDataUpload.MemberLoanOpeningDataUpload: this.ImportMemberLoanOpeningInfo(oColumnDefination); break; case (int)EnumRegularDataUpload.MemberUpload: case (int)EnumRegularDataUpload.GFMemberUpload: case (int)EnumRegularDataUpload.WPPFMemberUpload: this.ImportMember(oColumnDefination); break; case (int)EnumRegularDataUpload.ProfitDistributionUpload: this.ImportProfitDistribution(oColumnDefination); break; case (int)EnumRegularDataUpload.ProfitDistributionUploadWithoutVoucher: this.ImportProfitDistributionWithoutVoucher(oColumnDefination); break; case (int)EnumRegularDataUpload.MemberVoluntaryOpeningBalanceUpload: this.ImportMemberVoluntaryOpeningBalance(oColumnDefination); break; default: this.ImportException(uploadId, oColumnDefination); break; } return _errorOrSuccessList; } #region Import CoOrdinator public void ImportCoOrdinator(DataUploadColumnDefinition _columnDefinition) { List _oemployees = new EmployeeService().GetAllEmps(); List _oemployeecordinators = new List(); Employee oemployee = null; EmployeeCordinator item; int nRow = 0; int a; try { foreach (DataRow dr in _uplodedData.Rows) { item = new EmployeeCordinator(); nRow = nRow + 1; oemployee = _oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); //oEmployeeCordinator = _oemployeecordinators.Find(delegate (EmployeeCordinator empC) { return empC.EmployeeID == oemployee.ID; }); //oEmployeeCordinator.EmployeeID = oemployee.ID; if (oemployee != null) { item.EmployeeID = oemployee.ID; if (dr["Attendance In Charge"].ToString() == string.Empty && dr["Employee No"].ToString() != string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Attendance In Charge", nRow, "(" + dr["Attendance In Charge"].ToString() + ")" + "Attendance In Charge not found in the current context")); continue; } if (dr["Employee No"].ToString() == string.Empty && dr["Attendance In Charge"].ToString() != string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Attendance In Charge", nRow, "(" + dr["Attendance In Charge"].ToString() + ")" + "Can not assign empty field to Attendance In Charge")); continue; } var lineManager = _oemployees.Where(o => o.EmployeeNo == dr["Attendance In Charge"].ToString().Trim()).FirstOrDefault(); //coOrdinator.CordinatorID = lineManager.ID; if (lineManager == null) { item.EmployeeID = oemployee.ID; _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Attendance In Charge", nRow, "(" + dr["Attendance In Charge"].ToString() + ")" + "Attendance In Charge is not found in Employee List.")); continue; } item.CordinatorID = lineManager.ID; item.CreatedBy = this._userID; item.CreatedDate = DateTime.Today; if (dr["Emp Time Approve (Yes/No)"].ToString() != "") { var timeRequest = dr["Emp Time Approve (Yes/No)"].ToString(); if (timeRequest.ToLower().ToLower() == "yes") { item.ApproveTimeRequest = true; } } _oemployeecordinators.Add(item); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found in the Employee List")); } if (_errorOrSuccessList.Count == 0) { new EmployeeCordinatorService().Insert(_oemployeecordinators); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } #endregion public void ImportTemporaryShiftAssignment(int payrollTypeId, int userID) { try { int nRow = 0; List oActingResponsibilitySetup = new List(); List employees = new EmployeeService().GetAllEmps(payrollTypeId); List shifts = new ShiftService().GetAllShiftByPayrollType(payrollTypeId); Employee tempEmployee = null; Shift tempShift = null; string shiftName = string.Empty; DateTime endDate = DateTime.Today.AddDays(30); try { foreach (DataRow oDR in _uplodedData.Rows) { nRow = nRow + 1; tempEmployee = employees.Find(item => item.EmployeeNo.ToLower().Trim() == Convert.ToString(oDR["Employee-ID"]).ToLower().Trim()); try { if (tempEmployee != null) { for (DateTime date = DateTime.Today; date < endDate; date = date.AddDays(1)) { shiftName = Convert.ToString(oDR[date.ToString("dd-MMM-yyyy")]).ToLower().Trim(); tempShift = shifts.Find(item => item.Code.Trim().ToLower() == shiftName || item.ShortName.Trim().ToLower() == shiftName); if (tempShift != null) { oActingResponsibilitySetup.Add(new ActingResponsibilitySetup { EmployeeID = tempEmployee.ID, ShiftID = tempShift.ID, FromDate = date, ToDate = date, SalaryMonth = DateTime.Today, CreatedBy = userID, CreatedDate = DateTime.Today, payrollTypeID = payrollTypeId, ClaimWFStatus = EnumClaimWFStatus.LMApproved, IsHoliday = false }); } } } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee ID", nRow, "Employee ID not found: " + oDR["Employee-ID"].ToString())); } } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error occured on row:", nRow, " Reason:" + ex.Message)); } } } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error occured on row:", nRow, " Reason:" + ex.Message)); } if (_errorOrSuccessList.Count == 0) new ActingResponsibilitySetupService().Save(oActingResponsibilitySetup); } catch (Exception) { throw; } } public void ImportEmployeeWorkplan(DataUploadColumnDefinition columnDefinition, int payrollTypeId, int userID) { try { int nRow = 0; List employeeWorkPlanSetups = new List(); List employees = new EmployeeService().GetAllEmps(payrollTypeId); Employee tempEmployee = null; try { foreach (DataRow oDR in _uplodedData.Rows) { nRow = nRow + 1; tempEmployee = employees.Find(item => item.EmployeeNo.ToLower().Trim() == Convert.ToString(oDR["Employee-ID"]).ToLower().Trim()); if (tempEmployee != null) { employeeWorkPlanSetups.Add(new EmployeeWorkPlanSetup { EmployeeID = tempEmployee.ID, WorkPlanGroupID = columnDefinition.SelectedItemOneID, StartDate = tempEmployee.JoiningDate, PayrolltypeID = payrollTypeId, CreatedBy = userID }); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee ID", nRow, "Employee ID not found: " + oDR["Employee-ID"].ToString())); } } } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error occured on row:", nRow, " Reason:" + ex.Message)); } if (_errorOrSuccessList.Count == 0) new EmployeeWorkPlanSetupService().Save(employeeWorkPlanSetups); } catch (Exception) { throw; } } public void ImportOtUpload(DataUploadColumnDefinition columnDefinition, int payrollTypeId, DateTime selecteDate, int userID) { List employeeOverTimes = new List(); try { Employee oEmp = null; Term oTerm = null; TermParameter oTermParamerer = null; List oTermParamerers = new TermParameterService().GetByPayrollTypeID(payrollTypeId); List employees = new EmployeeService().GetAllEmps(); List OTCodes = new List(); List terms = new TermService().Get(EnumStatus.Active, payrollTypeId); PayrollType ptype = new PayrollTypeService().Get(payrollTypeId); bool fixedotmonth = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "overtime", "fixedotmonth"); for (int i = fixedotmonth ? 2 : 3; i < columnDefinition.ColumnName.Count; i++) { OTCodes.Add(columnDefinition.ColumnName[i]); } double otHour = 0; int nRow = 0; foreach (DataRow oDR in _uplodedData.Rows) { nRow = nRow + 1; foreach (string otCode in OTCodes) { EmployeeOverTime oEmpOverTime = new EmployeeOverTime(); //throw new ServiceException("Invalid Term:" + otCode + " , Term not exist in the System; Row:" + nRow.ToString()); oEmp = employees.Find(delegate (Employee oEmp1) { return oEmp1.EmployeeNo.ToLower().Trim() == Convert.ToString(oDR["Employee No"]).ToLower().Trim(); }); if (oEmp == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "Employee Code not found: " + oDR["Employee No"].ToString())); continue; } oTerm = terms.Find(delegate (Term oTM) { return oTM.Name.Trim().ToLower() == otCode.Trim().ToLower(); }); if (oTerm == null) { //_errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "Overtime/Term notfound: " + oDR["Employee No"].ToString())); _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "Overtime/Term notfound: " + oDR["Employee No"].ToString())); continue; } if (oEmp.GradeID == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "Grade not found: " + oDR["Employee No"].ToString())); continue; } List termParameters = new TermParameterService().GetByGradeID((int)oEmp.GradeID); oTermParamerer = termParameters.Find(t => t.TermID == oTerm.ID); /*oTermParamerer = TermParameter.GetParameter(oTermParamerers, oEmp, oTerm.ID); // baad ei line*/ if (oTermParamerer == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "OverTime Policy is not found: " + oDR["Employee No"].ToString())); continue; } otHour = 0; //throw new ServiceException("Invalid Parameter, Term parameter/rule not found for the employee:" + oEmp.EmployeeNo + " Row:" + nRow.ToString()); if (oDR[otCode].ToString() != "") { if (double.TryParse(oDR[otCode].ToString(), out otHour) == false) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "Invalid Hour Amount, Term parameter/rule not exist in the System Row: " + oDR["Employee No"].ToString())); continue; } else { otHour = Convert.ToDouble(oDR[otCode]); } } //throw new ServiceException("Invalid Hour Amount, Term parameter/rule not exist in the System Row:" + nRow.ToString()); if (!fixedotmonth) { if (oDR["OT Month"].ToString() == "") { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "OT Month is not found: " + oDR["Employee No"].ToString())); continue; } else { selecteDate = GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(oDR["OT Month"])); } } oEmpOverTime.TermID = oTermParamerer.TermID; oEmpOverTime.TermParameterID = oTermParamerer.ID; oEmpOverTime.OTHours = otHour; oEmpOverTime.EmployeeID = oEmp.ID; oEmpOverTime.Value = oTermParamerer.Amount; oEmpOverTime.MonthDate = ptype.NextPayProcessDate; oEmpOverTime.OTMonth = GlobalFunctions.LastDateOfMonth(selecteDate); oEmpOverTime.PayrollTypeID = payrollTypeId; oEmpOverTime.CreatedBy = userID; if (oEmpOverTime.OTHours > 0) employeeOverTimes.Add(oEmpOverTime); } } } catch (Exception e) { Console.WriteLine(e); throw; } if (_errorOrSuccessList.Count == 0) new EmployeeOverTimeService().SaveByExcel(employeeOverTimes); } public void ImportEmployeeAttendance(DataUploadColumnDefinition columnDefinition, int payrollTypeId) { List oemployees = new List(); if (columnDefinition.uploadID == (int)EnumRegularDataUpload.EmployeeAttendance) oemployees = new EmployeeService().GetAllEmps(columnDefinition.PayrollTypeID); else if (columnDefinition.uploadID == (int)EnumRegularDataUpload.EmployeeAttendanceLM) { User ouser = new UserService().Get(this._userID); Employee olm = new EmployeeService().Get(ouser.LoginID, columnDefinition.PayrollTypeID); oemployees = new EmployeeService().GetSubordinatesByLineManager(olm.ID); } else if (columnDefinition.uploadID == (int)EnumRegularDataUpload.EmployeeAttendanceCordinator) { User ouser = new UserService().Get(this._userID); Employee cordinator = new EmployeeService().Get(ouser.LoginID, columnDefinition.PayrollTypeID); oemployees = new EmployeeService().GetEmployeeByCoordinator(cordinator.ID); } DailyAttnProcess oDailyAttnProcess = null; _DailyAttnProcess = new List(); List oshfits = new ShiftService().Get(EnumStatus.Regardless, this._payrollTypeID); Employee oemployee = null; int nRow = 0; DateTime selectedDate = new DateTime(); DateTime MaxDate = DateTime.MinValue; DateTime MinDate = DateTime.MaxValue; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["EmployeeNo"].ToString(); }); if (oemployee != null) { oDailyAttnProcess = new DailyAttnProcess(); //oDailyAttnProcess.AttnDate = selecteDate; oDailyAttnProcess.EmployeeID = oemployee.ID; oDailyAttnProcess.Employee = oemployee; if (dr["Shift"].ToString() != string.Empty) { var sft = oshfits.FirstOrDefault(x => x.ShortName.ToLower() == dr["Shift"].ToString().ToLower()); if (sft != null) oDailyAttnProcess.ShiftID = sft.ID; else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid shift: " + dr["Shift"].ToString())); } //else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Shift Not Found")); if (dr["Date"].ToString() != string.Empty) { DateTime date; bool isDateValid = DateTime.TryParse(dr["Date"].ToString(), out date); if (isDateValid) { selectedDate = Convert.ToDateTime(dr["Date"]); oDailyAttnProcess.AttnDate = Convert.ToDateTime(dr["Date"]); if (selectedDate > MaxDate) { MaxDate = selectedDate; } if (selectedDate < MinDate) { MinDate = selectedDate; } } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Date is not Valid: " + dr["Date"].ToString())); } } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Date Not Found")); } #region Old Code //int hour = 0, minutes = 0; //string stime = ""; //stime = dr["InTime (24 Hour Format)"].ToString(); //if(stime.Contains(':') ==false) //{ // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid Time Format: " + dr["InTime (24 Hour Format)"].ToString())); //} //else //{ // string[] sptime = stime.Split(":"); // if(sptime[0].Length > 2) sptime[0] = sptime[0].Substring(sptime[0].Length - 2); // if (int.TryParse(sptime[0], out hour) ==true) // { // if(hour <0 && hour > 23) // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Hour must be between 1 to 23, " + sptime[0].ToString())); // } // else // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid Intime Hour: " + sptime[0].ToString())); // } // if (int.TryParse(sptime[1], out minutes) == true) // { // if (minutes < 0 && minutes > 59) // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Minute must be between 1 to 59, " + sptime[0].ToString())); // } // else // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid Intime Minutes: " + sptime[0].ToString())); // } // if (hour != 0 || minutes != 0) // { // DateTime dateTime = new DateTime(oDailyAttnProcess.AttnDate.Year, oDailyAttnProcess.AttnDate.Month, // oDailyAttnProcess.AttnDate.Day, hour, minutes, 0); // oDailyAttnProcess.InTime = dateTime; // } //} //hour = 0; minutes = 0; //stime = ""; //stime = dr["OutTime (24 Hour Format)"].ToString(); //if (stime.Contains(':') == false) //{ // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid Time Format: " + dr["OutTime (24 Hour Format)"].ToString())); //} //else //{ // string[] sptime = stime.Split(":"); // if (sptime[0].Length > 2) sptime[0] = sptime[0].Substring(sptime[0].Length - 2); // if (int.TryParse(sptime[0], out hour) == true) // { // if (hour < 0 && hour > 23) // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Hour must be between 1 to 23, " + sptime[0].ToString())); // } // else // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid Outtime Hour: " + sptime[0].ToString())); // } // if (int.TryParse(sptime[1], out minutes) == true) // { // if (minutes < 0 && minutes > 59) // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Minute must be between 1 to 59, " + sptime[1].ToString())); // } // else // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", // nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid Outtime Minutes: " + sptime[1].ToString())); // } // if (hour != 0 || minutes != 0) // { // DateTime dateTime = new DateTime(oDailyAttnProcess.AttnDate.Year, oDailyAttnProcess.AttnDate.Month, // oDailyAttnProcess.AttnDate.Day, hour, minutes, 0); // oDailyAttnProcess.OutTime = dateTime; // } //} #endregion if (dr["InTime (24 Hour Exp: 00:00)"].ToString() != string.Empty && dr["OutTime (24 Hour Exp: 00:00)"].ToString() != string.Empty) { DateTime inTime, outTime; bool isInTimeValid = DateTime.TryParse(dr["InTime (24 Hour Exp: 00:00)"].ToString(), out inTime); bool isOutTimeValid = DateTime.TryParse(dr["OutTime (24 Hour Exp: 00:00)"].ToString(), out outTime); if (isInTimeValid && isOutTimeValid) { DateTime newDate = Convert.ToDateTime(dr["InTime (24 Hour Exp: 00:00)"]); DateTime actualInTime = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, newDate.Hour, newDate.Minute, newDate.Second, 0); oDailyAttnProcess.InTime = actualInTime; newDate = Convert.ToDateTime(dr["OutTime (24 Hour Exp: 00:00)"]); DateTime actualOutTime = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, newDate.Hour, newDate.Minute, newDate.Second, 0); oDailyAttnProcess.OutTime = actualOutTime; } else { if (!isInTimeValid) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + " Invalid In Time Format")); } if (!isOutTimeValid) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + " Invalid Out Time Format")); } } } //else //{ // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + " In Time Or Out Time Could Not Found ")); //} if (dr["Reason"].ToString().Length > 200) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Reason is too long, try not more than 200 character")); } else if (dr["Reason"].ToString() != string.Empty) { //if (dr["Status"].ToString() == "Present") //{ // oDailyAttnProcess.AttenType = EnumAttendanceType.Present; // oDailyAttnProcess.Reason = dr["Status"].ToString(); //} //else //{ oDailyAttnProcess.Reason = dr["Reason"].ToString(); //} } else { oDailyAttnProcess.Reason = string.Empty; } oDailyAttnProcess.OTHour = dr["OTHour"].ToString() == string.Empty ? 0.00 : Convert.ToDouble(dr["OTHour"]); _DailyAttnProcess.Add(oDailyAttnProcess); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Employee not found for in the existing data")); } List workPlans = new MonthlyWorkPlanService().Get(MinDate, MaxDate, this._payrollTypeID); List empworkplans = new EmployeeWorkPlanSetupService().GetByPayrollTypeID(this._payrollTypeID); List existingData = new DailyAttnProcessService().GetDateRange(MinDate, MaxDate, this._payrollTypeID); foreach (DailyAttnProcess item in _DailyAttnProcess) { var attData = existingData.FirstOrDefault(x => x.EmployeeID == item.EmployeeID && x.AttnDate == item.AttnDate); if (attData != null) { if (attData.WFStatus == EnumWFAttnStatus.EmpSubmitted || attData.WFStatus == EnumWFAttnStatus.LMApproved) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", 0, "(" + item.Employee.EmployeeNo + ")" + "Data in approval stage, so not allowed to Edit")); } if (attData.IsFromMobile != EnumIsFromMobile.None) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", 0, "(" + item.Employee.EmployeeNo + ")" + "Check-in and Check-out from Mobile, so not allowed to Edit")); } } item.AttenType = EnumAttendanceType.Absent; if (item.InTime != null || item.OutTime != null) { item.AttenType = EnumAttendanceType.Present; } var empworkPlan = empworkplans.FirstOrDefault(x => x.EmployeeID == item.EmployeeID); if (empworkPlan != null) { var mplan = workPlans.FirstOrDefault(x => x.WorkDate == item.AttnDate && x.WorkPlanGroupID == empworkPlan.WorkPlanGroupID); if (mplan != null) { if (item.ShiftID == null) item.ShiftID = mplan.ShiftID; item.WorkDayType = mplan.Type; } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", 0, "(" + item.Employee.EmployeeNo + ")" + "Employee Monthly workplan not found")); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", 0, "(" + item.Employee.EmployeeNo + ")" + "Employee workplan not found")); item.CreatedBy = this._userID; item.CreatedDate = DateTime.Today; item.IsManualEntry = true; new AttendanceProcess().CalculateLateAndDelay(item, oshfits); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } if (_errorOrSuccessList.Count == 0) { try { var attnProcessGroupedByDate = _DailyAttnProcess.GroupBy(x => x.AttnDate); foreach (var attnProcess in attnProcessGroupedByDate) { new DailyAttnProcessService().Save(attnProcess.ToList(), new List()); } } catch (Exception ex) { throw new ServiceException("Can not save data, Reason:" + ex.Message); } } } public void ImportTaxAdjustmentData(DataUploadColumnDefinition columnDefinition) { { List oTaxMergeMasters = new List(); var payroll = new PayrollTypeService().Get().FirstOrDefault(); oTaxMergeMasters = new TaxMergeMasterService().GetbyTaxParameter((int)payroll.TaxParamID, payroll.ID); Employee oemployee = null; IncomeTax oIncomeTax = null; TaxMergeMaster oTaxMergeMaster = null; List _employees = new EmployeeService().GetWithDiscontinue(payroll.ID); List processItems = new ProcessItemService().Get(); #region Refresh Objects int nRow = 0; List savedData = new IncomeTaxService().Get(EnumIncomeTaxDataFrom.ProcessTempData, payroll.ID); try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = _employees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); });//Employee.Get(dr["Employee Code"].ToString()); if (oemployee == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "Employee Code not found: " + dr["Employee No"].ToString())); continue; } for (int i = 1; i < _uplodedData.Columns.Count; i++) { oIncomeTax = TaxMergeMaster.Extract(oTaxMergeMasters, EnumTaxMergeType.TaxAdjustItem, columnDefinition.SelectedItemOneID); if (oIncomeTax == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(_uplodedData.Columns[i].ColumnName, nRow, "Tax head grouping net yet created for the selected item", oemployee.EmployeeNo, oemployee.Name)); continue; } ProcessItem pitem = processItems.Find(delegate (ProcessItem item) { return item.ItemCode == (int)oIncomeTax.ItemGroup; }); if (pitem == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(_uplodedData.Columns[i].ColumnName, nRow, " Tax process item code not found in the process collection; Item Code:" + oTaxMergeMaster.ItemGroup.ToString(), oemployee.EmployeeNo, oemployee.Name)); continue; } oIncomeTax.EmployeeID = oemployee.ID; double nAmount = 0; if (double.TryParse(dr[_uplodedData.Columns[i].ColumnName].ToString(), out nAmount) == false) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(_uplodedData.Columns[i].ColumnName, nRow, _uplodedData.Columns[i].ColumnName + " contains Invalid value:" + dr[_uplodedData.Columns[i].ColumnName].ToString(), oemployee.EmployeeNo, oemployee.Name)); continue; } IncomeTax oNewItem = new IncomeTaxService().Get(savedData, oemployee.ID, oIncomeTax.ItemGroup, oIncomeTax.ItemID); //.Get(savedData, oemployee.ID, oTaxMergeMaster.ItemGroup, oTaxMergeMaster.ItemID); if (oNewItem != null) oIncomeTax = oNewItem; else { oIncomeTax.Side = (EnumIncomeTaxSide)pitem.ItemGroup; oIncomeTax.Position = pitem.Position; } // if (oIncomeTax == null) oIncomeTax = new IncomeTax(); oIncomeTax.EmployeeID = oemployee.ID; oIncomeTax.PreviousAmount = oIncomeTax.PreviousAmount + nAmount; if (oIncomeTax.PreviousAmount != 0) _incomeTaxes.Add(oIncomeTax); } } if (_errorOrSuccessList.Count == 0) { new IncomeTaxService().Save(_incomeTaxes, EnumIncomeTaxDataFrom.ProcessTempData); } } catch (Exception ex) { throw new ServiceException("Error occered on row:" + nRow + " Reason:" + ex.Message); } #endregion } } public void ImportITChallan(DataUploadColumnDefinition _columnDefinition) { List oemployees = new EmployeeService().GetAllEmps(); TaxChallan oTaxChallan = null; _TaxChallans = new List(); Employee oemployee = null; int nRow = 0; List obranches = new BranchService().Get(EnumStatus.Regardless, _columnDefinition.PayrollTypeID); try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { oTaxChallan = new TaxChallan(); oTaxChallan.EmployeeID = oemployee.ID; oTaxChallan.SalaryMonthly = Convert.ToDateTime(dr["Month"]); oTaxChallan.DepositDate = Convert.ToDateTime(dr["Month"]); oTaxChallan.TaxParameterID = _columnDefinition.SelectedItemOneID; oTaxChallan.ChallanAmount = Convert.ToDouble(dr["ChallanAmount"]); oTaxChallan.EmployeeAmount = Convert.ToDouble(dr["EmployeeAmount"]); oTaxChallan.ChallanNo = Convert.ToString(dr["ChallanNo"]); //oTaxChallan.BranchID = Convert.ToInt32(dr["BranchCode"]); oTaxChallan.PayrolltypeID = _payrollTypeID; oTaxChallan.CreatedBy = _userID; var brch = obranches.FirstOrDefault(x => x.Code.ToLower().Trim() == dr["BranchCode"].ToString().ToLower().Trim()); oTaxChallan.BranchID = brch.ID; if (brch == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["BranchCode"].ToString() + ")" + " Branch not found in the System.")); continue; } oTaxChallan.CreatedDate = DateTime.Today; _TaxChallans.Add(oTaxChallan); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } if (_errorOrSuccessList.Count == 0) { new TaxChallanService().SaveForExcelUpload(_TaxChallans); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportTrainingEnrollment(DataUploadColumnDefinition _columnDefinition) { List oemployees = new EmployeeService().GetAllEmps(); TrainingSchedule ts = new TrainingScheduleService().Get(_columnDefinition.SelectedItemOneID); _TaxChallans = new List(); Employee oemployee = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { var ind = ts.EnrolledTrainingEmployees.FindIndex(x => x.EmployeeID == oemployee.ID); if (ind == -1) { TrainingScheduleEmployee tse = new TrainingScheduleEmployee(); tse.EmployeeID = oemployee.ID; tse.ProposedDate = DateTime.Today; tse.ProposedByID = _userID; tse.ScheduleEmpStatus = EnumTSStatus.Enrolled; tse.TrainingScheduleID = ts.ID; ts.EnrolledTrainingEmployees.Add(tse); } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } if (_errorOrSuccessList.Count == 0) { new TrainingScheduleService().SaveTrainingEmp(ts.EnrolledTrainingEmployees); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportTrainingAttendance(DataUploadColumnDefinition _columnDefinition) { List oemployees = new EmployeeService().GetAllEmps(); _TaxChallans = new List(); Employee oemployee = null; int nRow = 0; List attns = new List(); try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { TrainingScheduleAttn attn = new TrainingScheduleAttn(); attn.TrainingScheduleID = _columnDefinition.SelectedItemOneID; attn.TSDateID = _columnDefinition.SelectedItemTwoID; attn.EmployeeID = oemployee.ID; attn.CreatedBy = _userID; attn.CreatedDate = DateTime.Today; attns.Add(attn); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } if (_errorOrSuccessList.Count == 0) { new TrainingScheduleAttnService().saveTrainingAttendance(_columnDefinition.SelectedItemOneID , _columnDefinition.SelectedItemTwoID, _userID, attns); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportProfitDistributionVoluntary(DataUploadColumnDefinition _columnDefinition) { int nRow = 0; int fundTypeID = _columnDefinition.SelectedItemOneID; double dEpfInterest = 0; double dCpfInterest = 0; decimal glTranCPFInterestDrAmount = 0; decimal glTranCPFInterestCrAmount = 0; decimal glTranEPFInterestDrAmount = 0; decimal glTranEPFInterestCrAmount = 0; //END Cr List ogls = new GLService().GetbyFundType(fundTypeID); GLTran _glTran = null; List omembers = new MemberService().GetByFundType(fundTypeID); List orecords = new UserRecordService().Get(GlobalFunctions.Fund_UserObject_Member, fundTypeID); ; List _glTranDetails = null; List tempMembers = new List(); List activityVoucherSetup = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Monthly_Dividend_Distribution); FundType ftype = new FundTypeService().Get(fundTypeID); if (ftype.CurrentMonth != ftype.NextProfitDistributionMonth) { throw new Exception("Profit distribution month :" + ftype.NextProfitDistributionMonth.ToString("MMM yyyy") + ", Current Month:" + ftype.CurrentMonth.ToString("MMM yyyy") + ","); } try { //Transaction _glTran = new GLTran(); _glTran.VoucherDate = ftype.CurrentMonth; _glTran.Description = "Profit Distribution Voucher:" + ftype.CurrentMonth.ToString("MMM yyyy"); _glTran.EntryMethod = EnumEntryMethod.Manual; _glTran.GLTranType = EnumGLTranType.YearEndVoucher; //END Tran _glTranDetails = new List(); GL gl = null; GLTranDetail glTranDetailForBank = new GLTranDetail(); GLTranDetail glTranDetailForEPFInterest = new GLTranDetail(); GLTranDetail glTranDetailForVoluntaryInterest = new GLTranDetail(); GLTranDetail glTranDetailForCPFInterest = new GLTranDetail(); GLTranUserRecord glTranUserRecord = null; //Detail for Bank Amount gl = new GL(); ActivityVoucherSetup bankSetup = activityVoucherSetup.Find(x => x.GLSide == EnumTranSide.Debit && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Bank); gl = ogls.FirstOrDefault(x => x.ID == bankSetup.GLID); glTranDetailForBank.GLID = gl.ID; glTranDetailForBank.Description = "Profit Distribution Voucher"; glTranDetailForBank.Transide = EnumTranSide.Debit; //Debit glTranDetailForBank.OperationalStatus = EnumOperationalStatus.Add; //Detail for Employee PF Interest gl = new GL(); ActivityVoucherSetup epfSetup = activityVoucherSetup.Find(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.EPF_Interest); gl = ogls.FirstOrDefault(x => x.ID == epfSetup.GLID); glTranDetailForEPFInterest.GLID = gl.ID; glTranDetailForEPFInterest.Description = "Profit Distribution for EPF"; glTranDetailForEPFInterest.Transide = epfSetup.GLSide; //Credit glTranDetailForEPFInterest.OperationalStatus = EnumOperationalStatus.Add; //Detail for Employee PF Interest gl = new GL(); ActivityVoucherSetup voluntarySetup = activityVoucherSetup.Find(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Voluntary_EPF_Interest); gl = ogls.FirstOrDefault(x => x.ID == voluntarySetup.GLID); glTranDetailForVoluntaryInterest.GLID = gl.ID; glTranDetailForVoluntaryInterest.Description = "Profit Distribution for Voluntary"; glTranDetailForVoluntaryInterest.Transide = voluntarySetup.GLSide; //Credit glTranDetailForVoluntaryInterest.OperationalStatus = EnumOperationalStatus.Add; //Detail for CPF Interest gl = new GL(); ActivityVoucherSetup cpfSetup = activityVoucherSetup.Find(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.CPF_Interest); gl = ogls.FirstOrDefault(x => x.ID == cpfSetup.GLID); glTranDetailForCPFInterest.GLID = gl.ID; glTranDetailForCPFInterest.Description = "Profit Distribution for CPF"; glTranDetailForCPFInterest.Transide = cpfSetup.GLSide; //Credit glTranDetailForCPFInterest.OperationalStatus = EnumOperationalStatus.Add; int count = 0; UserRecord uR = null; this.memberTrans = new List(); foreach (DataRow dr in _uplodedData.Rows) { nRow++; if (!dr.IsNull("EmployeeNo") && !dr.IsNull("TranDate") && !dr.IsNull("EPFInterest") && !dr.IsNull("CPFInterest")) { Member oMember = omembers.FirstOrDefault(x => x.EmpCode == Convert.ToString(dr["EmployeeNo"])); if (oMember == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Employee not found for in the existing data")); continue; } DateTime tranDate = Convert.ToDateTime(dr["TranDate"]); dEpfInterest = dEpfInterest + Convert.ToDouble(dr["EPFInterest"]); dCpfInterest = dCpfInterest + Convert.ToDouble(dr["CPFInterest"]); count = count + 1; uR = new UserRecord(); string sempCode = Convert.ToString(dr["EmployeeNo"]); uR = orecords.FirstOrDefault(x => x.Field1 == sempCode);//check if (uR == null) throw new Exception("Member Not found in following Code : " + sempCode); DateTime voucherDate; if (DateTime.TryParse(dr["TranDate"].ToString(), out voucherDate) == false) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid TranDate/Voucher Date, Date must be :" + ftype.CurrentMonth.ToString())); continue; } else { if (GlobalFunctions.LastDateOfMonth(voucherDate) != ftype.CurrentMonth) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "TranDate/Voucher Date must be :" + ftype.CurrentMonth.ToString())); continue; } } //EPF Interest glTranUserRecord = new GLTranUserRecord(); glTranUserRecord.GLID = glTranDetailForEPFInterest.GLID; glTranUserRecord.UserObject1ID = uR.UserObjectID; glTranUserRecord.UserRecord1ID = uR.ID; glTranUserRecord.Description = "Profit Distribution Voucher"; glTranUserRecord.Amount = Convert.ToDouble(dr["EPFInterest"]); if (glTranDetailForEPFInterest.Transide == EnumTranSide.Debit) { glTranEPFInterestDrAmount += (decimal)glTranUserRecord.Amount; } else { glTranEPFInterestCrAmount += (decimal)glTranUserRecord.Amount; } glTranUserRecord.OperationalStatus = EnumOperationalStatus.Add; if (glTranUserRecord.Amount > 0) glTranDetailForEPFInterest.GLTranUserRecords.Add(glTranUserRecord); //EPF voluntary glTranUserRecord = new GLTranUserRecord(); glTranUserRecord.GLID = glTranDetailForEPFInterest.GLID; glTranUserRecord.UserObject1ID = uR.UserObjectID; glTranUserRecord.UserRecord1ID = uR.ID; glTranUserRecord.Description = "Profit Distribution for Voluntary EPF"; glTranUserRecord.Amount = Convert.ToDouble(dr["voluntaryInterest"]); if (glTranDetailForEPFInterest.Transide == EnumTranSide.Debit) { glTranEPFInterestDrAmount += (decimal)glTranUserRecord.Amount; } else { glTranEPFInterestCrAmount += (decimal)glTranUserRecord.Amount; } glTranUserRecord.OperationalStatus = EnumOperationalStatus.Add; if (glTranUserRecord.Amount > 0) glTranDetailForEPFInterest.GLTranUserRecords.Add(glTranUserRecord); //CPF Interest glTranUserRecord = new GLTranUserRecord(); glTranUserRecord.GLID = glTranDetailForCPFInterest.GLID; glTranUserRecord.UserObject1ID = uR.UserObjectID; glTranUserRecord.UserRecord1ID = uR.ID; glTranUserRecord.Description = "Profit Distribution Voucher"; glTranUserRecord.Amount = Convert.ToDouble(dr["CPFInterest"]); if (glTranDetailForCPFInterest.Transide == EnumTranSide.Debit) { glTranCPFInterestDrAmount += (decimal)glTranUserRecord.Amount; } else { glTranCPFInterestCrAmount += (decimal)glTranUserRecord.Amount; } glTranUserRecord.OperationalStatus = EnumOperationalStatus.Add; if (glTranUserRecord.Amount > 0) glTranDetailForCPFInterest.GLTranUserRecords.Add(glTranUserRecord); FillMemberTrans(oMember, GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(dr["TranDate"])), Convert.ToDouble(dr["EPFInterest"]), (int)EnumMemberTranType.EPF_Interest, fundTypeID, EnumTranEffect.Increase, EnumFundCategory.EPF); //9 FillMemberTrans(oMember, GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(dr["TranDate"])), Convert.ToDouble(dr["voluntaryInterest"]), (int)EnumMemberTranType.Voluntary_Interest, fundTypeID, EnumTranEffect.Increase, EnumFundCategory.Voluntary); //10 FillMemberTrans(oMember, GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(dr["TranDate"])), Convert.ToDouble(dr["CPFInterest"]), (int)EnumMemberTranType.CPF_Interest, fundTypeID, EnumTranEffect.Increase, EnumFundCategory.CPF); //10 } } //Employee GL Heads if (glTranDetailForCPFInterest.Transide == EnumTranSide.Debit) { glTranDetailForCPFInterest.Amount = GlobalFunctions.RoundOff(glTranCPFInterestDrAmount, 2); } else { glTranDetailForCPFInterest.Amount = GlobalFunctions.RoundOff(glTranCPFInterestCrAmount, 2); } if (glTranDetailForEPFInterest.Transide == EnumTranSide.Debit) { glTranDetailForEPFInterest.Amount = GlobalFunctions.RoundOff(glTranEPFInterestDrAmount, 2); } else { glTranDetailForEPFInterest.Amount = GlobalFunctions.RoundOff(glTranEPFInterestCrAmount, 2); } //Bank is reverse GL if (glTranDetailForBank.Transide == EnumTranSide.Debit) { glTranDetailForBank.Amount = glTranDetailForCPFInterest.Amount + glTranDetailForEPFInterest.Amount; } else { glTranDetailForBank.Amount = glTranDetailForCPFInterest.Amount + glTranDetailForEPFInterest.Amount; } _glTranDetails.Add(glTranDetailForBank); if (glTranDetailForCPFInterest.Amount > 0) _glTranDetails.Add(glTranDetailForCPFInterest); if (glTranDetailForEPFInterest.Amount > 0) _glTranDetails.Add(glTranDetailForEPFInterest); _glTran.DebitAmount = (double)glTranDetailForBank.Amount; _glTran.CreditAmount = (double)glTranDetailForBank.Amount; _glTran.GlTranDetails = _glTranDetails; if (_errorOrSuccessList.Count == 0) { foreach (var item in memberTrans) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } _glTran.CreatedBy = this._userID; _glTran.CreatedDate = DateTime.Now; foreach (var item in _glTran.GlTranDetails) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; if (item.GLTranUserRecords != null) { foreach (var record in item.GLTranUserRecords) { record.CreatedBy = this._userID; record.CreatedDate = DateTime.Now; } } } new MemberService().UploadProfitDistribution(memberTrans, _glTran, fundTypeID, _userID); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportMemberVoluntaryOpeningBalance(DataUploadColumnDefinition _columnDefinition) { //Variable int fundTypeID = _columnDefinition.SelectedItemOneID; int nRow = 0; double TotalAmount = 0; //Objects List oMembers = new List(); List memberList = new List(); List membertrans = new List(); GLTran voucher = new GLTran(); List voucherDetails = new List(); List gls = new GLService().GetbyFundType(fundTypeID); FundType oftype = new FundTypeService().Get(fundTypeID); DateTime voucherDate = DateTime.Today; voucherDate = oftype.LastProfitDistributionMonth; List orecords = new UserRecordService().Get(GlobalFunctions.Fund_UserObject_Member, fundTypeID); if (new GLTranService().VoucherExist(EnumGLTranType.OpeningMemberBalance, new DateTime(2000, 1, 1), new DateTime(2050, 1, 1), fundTypeID) == true) { throw new Exception("Opening voucher is already uploaded in the system."); } try { oMembers = new MemberService().GetByFundType(fundTypeID); foreach (DataRow dr in _uplodedData.Rows) { Member tempMember = new Member(); nRow = nRow + 1; double tempAmount = 0; //Fill Member Data if (Convert.ToString(dr["Employee No"]) != string.Empty) { Member findMember = oMembers.Find(x => x.EmpCode == Convert.ToString(dr["Employee No"])); if (findMember != null) tempMember = findMember; else { tempMember.EmpCode = Convert.ToString(dr["Employee No"]); tempMember.FundTypeID = fundTypeID; tempMember.MemberStatus = EnumEmpStatus.Live; } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "This cannot be empty")); if (Convert.ToString(dr["Employee Name"]) != string.Empty) { tempMember.Name = Convert.ToString(dr["Employee Name"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Name.", nRow, "(" + dr["Employee Name"].ToString() + ")" + "This cannot be empty")); if (Convert.ToString(dr["Designation"]) != string.Empty) { tempMember.Designation = Convert.ToString(dr["Designation"]); } if (Convert.ToDateTime(dr["Joining Date"]).ToString() != string.Empty) { tempMember.DOJ = Convert.ToDateTime(dr["Joining Date"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Joining Date.", nRow, "(" + Convert.ToDateTime(dr["Joining Date"]).ToString() + ")" + "This cannot be empty")); if (Convert.ToDateTime(dr["Birthdate"]).ToString() != string.Empty) { tempMember.DOB = Convert.ToDateTime(dr["Birthdate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Birthdate.", nRow, "(" + Convert.ToDateTime(dr["Birthdate"]).ToString() + ")" + "This cannot be empty")); if (Convert.ToDateTime(dr["PF MembershipDate"]).ToString() != string.Empty) { tempMember.MembershipDate = Convert.ToDateTime(dr["PF MembershipDate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF MembershipDate.", nRow, "This row cannot be empty")); if (Convert.ToDouble(dr["Basic Salary"]).ToString() != string.Empty) { tempMember.CurrentBasic = Convert.ToDouble(dr["Basic Salary"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Basic Salary.", nRow, "This row cannot be empty")); //Fill User Record Information UserRecord oUserRecord = orecords.FirstOrDefault(x => x.Field1 == tempMember.EmpCode); if (oUserRecord != null) { tempMember.userRecord = new UserRecord(); tempMember.userRecord = oUserRecord; tempMember.userRecord.Field2 = tempMember.Name; // Name Will Update If Name Spelling Changes } else { tempMember.userRecord = new UserRecord(GlobalFunctions.Fund_UserObject_Member, fundTypeID, tempMember.EmpCode, tempMember.Name, ""); } //Fill GL Tran as Voucher //DateTime effectDate = Convert.ToDateTime(dr["Voucher Date"]); //string voucherDescription = Convert.ToString(dr["Description"]); // voucherDate = effectDate; voucher.FundTypeID = fundTypeID; voucher.ChequeDate = voucherDate; voucher.VoucherDate = voucherDate; voucher.Description = "Opening Balance " + " " + voucherDate.ToString("MMM yyyy"); voucher.GLTranType = EnumGLTranType.OpeningMemberBalance; // EPF tempAmount = Convert.ToDouble(dr["EPF"]); MembersTransactionDetail efp = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.EPF, tempAmount, voucherDate, EnumFundCategory.EPF); efp.EmpCode = tempMember.EmpCode; membertrans.Add(efp); string glcode = Convert.ToString(dr["EPF GL"]); GL vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF GL not found")); continue; } GLTranDetail vefp = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vefp == null) { vefp = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vefp); vefp.GLTranUserRecords = new List(); } else { vefp.Amount += tempAmount; } GLTranUserRecord vur = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur.UserRecord1 = tempMember.userRecord; vefp.GLTranUserRecords.Add(vur); voucher.DebitAmount += (double)tempAmount; TotalAmount += tempAmount; //EPF Interest tempAmount = Convert.ToDouble(dr["EPF Interest"]); MembersTransactionDetail epfinterest = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.EPF_Interest, tempAmount, voucherDate, EnumFundCategory.EPF); epfinterest.EmpCode = tempMember.EmpCode; membertrans.Add(epfinterest); glcode = Convert.ToString(dr["EPF Interest GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF Interest GL not found")); continue; } GLTranDetail vepfinterest = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vepfinterest == null) { vepfinterest = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vepfinterest); vepfinterest.GLTranUserRecords = new List(); } else { vepfinterest.Amount += tempAmount; } GLTranUserRecord vur1 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur1.UserRecord1 = tempMember.userRecord; vepfinterest.GLTranUserRecords.Add(vur1); voucher.DebitAmount += (double)tempAmount; TotalAmount += tempAmount; //Voluntary_EPF tempAmount = Convert.ToDouble(dr["Voluntary EPF"]); MembersTransactionDetail voluntary_efp = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.Voluntary_EFP, tempAmount, voucherDate, EnumFundCategory.Voluntary); voluntary_efp.EmpCode = tempMember.EmpCode; membertrans.Add(voluntary_efp); glcode = Convert.ToString(dr["Voluntary EPF GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Voluntary EPF GL not found")); continue; } GLTranDetail voluntaryEFP = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (voluntaryEFP == null) { voluntaryEFP = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); //<-- voucherDetails.Add(voluntaryEFP); voluntaryEFP.GLTranUserRecords = new List(); } else { voluntaryEFP.Amount += tempAmount; } GLTranUserRecord voluntary_ur = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); voluntary_ur.UserRecord1 = tempMember.userRecord; voluntaryEFP.GLTranUserRecords.Add(voluntary_ur); voucher.DebitAmount += (double)tempAmount; //<-- TotalAmount += tempAmount; //Voluntary EPF Interest tempAmount = Convert.ToDouble(dr["Voluntary EPF Interest"]); MembersTransactionDetail voluntaryepfinterest = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.Voluntary_Interest, tempAmount, voucherDate, EnumFundCategory.Voluntary); voluntaryepfinterest.EmpCode = tempMember.EmpCode; membertrans.Add(voluntaryepfinterest); glcode = Convert.ToString(dr["Voluntary EPF Interest GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Voluntary EPF Interest GL not found")); continue; } GLTranDetail vepfinterestGLTran = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vepfinterestGLTran == null) { vepfinterestGLTran = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vepfinterestGLTran); vepfinterestGLTran.GLTranUserRecords = new List(); } else { vepfinterestGLTran.Amount += tempAmount; } GLTranUserRecord vur4 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur4.UserRecord1 = tempMember.userRecord; vepfinterestGLTran.GLTranUserRecords.Add(vur4); voucher.DebitAmount += (double)tempAmount; TotalAmount += tempAmount; //************************************** //CPF tempAmount = Convert.ToDouble(dr["CPF"]); MembersTransactionDetail cpf = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.CPF, tempAmount, voucherDate, EnumFundCategory.CPF); cpf.EmpCode = tempMember.EmpCode; membertrans.Add(cpf); glcode = Convert.ToString(dr["CPF GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "CPF GL not found")); continue; } GLTranDetail vcpf = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vcpf == null) { vcpf = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vcpf); vcpf.GLTranUserRecords = new List(); } else { vcpf.Amount += tempAmount; } GLTranUserRecord vur2 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur2.UserRecord1 = tempMember.userRecord; vcpf.GLTranUserRecords.Add(vur2); voucher.DebitAmount += (double)tempAmount; TotalAmount += tempAmount; //CPF Interest GL tempAmount = Convert.ToDouble(dr["CPF Interest"]); MembersTransactionDetail cpfinterest = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.CPF_Interest, tempAmount, voucherDate, EnumFundCategory.CPF); cpfinterest.EmpCode = tempMember.EmpCode; membertrans.Add(cpfinterest); glcode = Convert.ToString(dr["CPF Interest GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "CPF Interest GL not found")); continue; } GLTranDetail vcpfinterest = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vcpfinterest == null) { vcpfinterest = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vcpfinterest); vcpfinterest.GLTranUserRecords = new List(); } else { vcpfinterest.Amount += tempAmount; } GLTranUserRecord vur3 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur3.UserRecord1 = tempMember.userRecord; vcpfinterest.GLTranUserRecords.Add(vur3); voucher.DebitAmount += (double)tempAmount; TotalAmount += tempAmount; //Bank GL string bankGL = Convert.ToString(dr["Bank GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == bankGL); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Bank GL not found")); continue; } GLTranDetail bank = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (bank == null) { bank = new GLTranDetail(vgl.ID, EnumTranSide.Debit, TotalAmount, ""); voucherDetails.Add(bank); } else { bank.Amount += tempAmount; } bank.Amount = TotalAmount; voucher.CreditAmount += (double)TotalAmount; voucher.GlTranDetails = voucherDetails; memberList.Add(tempMember); } if (_errorOrSuccessList.Count == 0) { foreach (var item in memberList) { if (item.IsNew == true) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } else { item.ModifiedBy = this._userID; item.ModifiedDate = DateTime.Now; } } foreach (var item in membertrans) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } voucher.CreatedBy = this._userID; voucher.CreatedDate = DateTime.Now; voucher.CreditAmount = Convert.ToDouble(voucher.GlTranDetails.Where(x => x.Transide == EnumTranSide.Credit).Sum(x => x.Amount)); voucher.DebitAmount = Convert.ToDouble(voucher.GlTranDetails.Where(x => x.Transide == EnumTranSide.Debit).Sum(x => x.Amount)); foreach (var item in voucher.GlTranDetails) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; if (item.GLTranUserRecords != null) { item.Amount = Convert.ToDouble(item.GLTranUserRecords.Sum(x => x.Amount)); foreach (var record in item.GLTranUserRecords) { record.CreatedBy = this._userID; record.CreatedDate = DateTime.Now; } } } new MemberService().UploadOpeningBalance(memberList, membertrans, voucher, fundTypeID, _userID); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportProfitDistribution(DataUploadColumnDefinition _columnDefinition) { int nRow = 0; int fundTypeID = _columnDefinition.SelectedItemOneID; double dEpfInterest = 0; double dCpfInterest = 0; //END Cr List ogls = new GLService().GetbyFundType(fundTypeID); GLTran _glTran = null; List omembers = new MemberService().GetByFundType(fundTypeID); List orecords = new UserRecordService().Get(GlobalFunctions.Fund_UserObject_Member, fundTypeID); ; List tempMembers = new List(); List activityVoucherSetup = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Monthly_Dividend_Distribution); FundType ftype = new FundTypeService().Get(fundTypeID); //if (ftype.CurrentMonth != ftype.NextProfitDistributionMonth) //{ // throw new Exception("Profit distribution month :" + ftype.NextProfitDistributionMonth.ToString("MMM yyyy") // + ", Current Month:" + ftype.CurrentMonth.ToString("MMM yyyy") + ","); //} try { //Transaction _glTran = new GLTran(); _glTran.VoucherDate = ftype.CurrentMonth; _glTran.Description = "Profit Distribution Voucher:" + ftype.CurrentMonth.ToString("MMM yyyy"); _glTran.EntryMethod = EnumEntryMethod.Manual; _glTran.GLTranType = EnumGLTranType.DividendDistribution; //END Tran GL gl = null; GLTranDetail glTranDetailForBank = new GLTranDetail(); GLTranDetail glTranDetailForEPFInterest = new GLTranDetail(); GLTranDetail glTranDetailForCPFInterest = new GLTranDetail(); GLTranUserRecord glTranUserRecord = null; //Detail for Bank Amount gl = new GL(); ActivityVoucherSetup bankSetup = activityVoucherSetup.Find(x => x.GLSide == EnumTranSide.Debit && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.PL_Profit); gl = ogls.FirstOrDefault(x => x.ID == bankSetup.GLID); glTranDetailForBank.GLID = gl.ID; glTranDetailForBank.Description = "Profit Distribution Voucher"; glTranDetailForBank.Transide = EnumTranSide.Debit; //Debit glTranDetailForBank.OperationalStatus = EnumOperationalStatus.Add; //Detail for Employee PF Interest gl = new GL(); ActivityVoucherSetup epfSetup = activityVoucherSetup.Find(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.EPF_Interest); gl = ogls.FirstOrDefault(x => x.ID == epfSetup.GLID); glTranDetailForEPFInterest.GLID = gl.ID; glTranDetailForEPFInterest.Description = "Profit Distribution Voucher"; glTranDetailForEPFInterest.Transide = epfSetup.GLSide; //Credit glTranDetailForEPFInterest.OperationalStatus = EnumOperationalStatus.Add; //Detail for CPF Interest gl = new GL(); ActivityVoucherSetup cpfSetup = activityVoucherSetup.Find(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.CPF_Interest); gl = ogls.FirstOrDefault(x => x.ID == cpfSetup.GLID); glTranDetailForCPFInterest.GLID = gl.ID; glTranDetailForCPFInterest.Description = "Profit Distribution Voucher"; glTranDetailForCPFInterest.Transide = cpfSetup.GLSide; //Credit glTranDetailForCPFInterest.OperationalStatus = EnumOperationalStatus.Add; int count = 0; UserRecord uR = null; this.memberTrans = new List(); foreach (DataRow dr in _uplodedData.Rows) { nRow++; if (!dr.IsNull("EmployeeNo") && !dr.IsNull("TranDate") && !dr.IsNull("EPFInterest") && !dr.IsNull("CPFInterest")) { Member oMember = omembers.FirstOrDefault(x => x.EmpCode == Convert.ToString(dr["EmployeeNo"])); if (oMember == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Employee not found for in the existing data")); continue; } dEpfInterest = dEpfInterest + Convert.ToDouble(dr["EPFInterest"]); dCpfInterest = dCpfInterest + Convert.ToDouble(dr["CPFInterest"]); count = count + 1; uR = new UserRecord(); uR = orecords.FirstOrDefault(x => x.Field1 == oMember.EmpCode);//check if (uR == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Employee not found for in the existing data...")); continue; } DateTime voucherDate; if (DateTime.TryParse(dr["TranDate"].ToString(), out voucherDate) == false) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid TranDate/Voucher Date, Date must be :" + ftype.CurrentMonth.ToString())); continue; } else { if (GlobalFunctions.LastDateOfMonth(voucherDate) != ftype.CurrentMonth) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "TranDate/Voucher Date must be :" + ftype.CurrentMonth.ToString())); continue; } } //EPF Interest glTranUserRecord = new GLTranUserRecord(); glTranUserRecord.GLID = glTranDetailForEPFInterest.GLID; glTranUserRecord.UserObject1ID = uR.UserObjectID; glTranUserRecord.UserRecord1ID = uR.ID; glTranUserRecord.UserRecord1 = uR; glTranUserRecord.Description = "Profit Distribution Voucher"; glTranUserRecord.Amount = Convert.ToDouble(dr["EPFInterest"]); glTranUserRecord.OperationalStatus = EnumOperationalStatus.Add; if (glTranUserRecord.Amount > 0) { if(glTranDetailForEPFInterest.GLTranUserRecords == null) { glTranDetailForEPFInterest.GLTranUserRecords = new List(); } glTranDetailForEPFInterest.GLTranUserRecords.Add(glTranUserRecord); } //CPF Interest glTranUserRecord = new GLTranUserRecord(); glTranUserRecord.GLID = glTranDetailForCPFInterest.GLID; glTranUserRecord.UserObject1ID = uR.UserObjectID; glTranUserRecord.UserRecord1ID = uR.ID; glTranUserRecord.UserRecord1 = uR; glTranUserRecord.Description = "Profit Distribution Voucher"; glTranUserRecord.Amount = Convert.ToDouble(dr["CPFInterest"]); glTranUserRecord.OperationalStatus = EnumOperationalStatus.Add; if (glTranUserRecord.Amount > 0) { if(glTranDetailForCPFInterest.GLTranUserRecords == null) { glTranDetailForCPFInterest.GLTranUserRecords = new List(); } glTranDetailForCPFInterest.GLTranUserRecords.Add(glTranUserRecord); } FillMemberTrans(oMember, GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(dr["TranDate"])), Convert.ToDouble(dr["EPFInterest"]), (int)EnumMemberTranType.EPF_Interest, fundTypeID, EnumTranEffect.Increase, EnumFundCategory.EPF); //9 FillMemberTrans(oMember, GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(dr["TranDate"])), Convert.ToDouble(dr["CPFInterest"]), (int)EnumMemberTranType.CPF_Interest, fundTypeID, EnumTranEffect.Increase, EnumFundCategory.CPF); //10 } } //Employee GL Heads _glTran.GlTranDetails = new List(); _glTran.GlTranDetails.Add(glTranDetailForBank); _glTran.GlTranDetails.Add(glTranDetailForEPFInterest); _glTran.GlTranDetails.Add(glTranDetailForCPFInterest); glTranDetailForEPFInterest.Amount = glTranDetailForEPFInterest.GLTranUserRecords != null ? (double)glTranDetailForEPFInterest.GLTranUserRecords.Sum(x => x.Amount) : 0; glTranDetailForEPFInterest.Amount = Math.Round(glTranDetailForEPFInterest.Amount, 2); glTranDetailForCPFInterest.Amount = glTranDetailForCPFInterest.GLTranUserRecords != null ? (double)glTranDetailForCPFInterest.GLTranUserRecords.Sum(x => x.Amount) : 0; glTranDetailForCPFInterest.Amount = Math.Round(glTranDetailForCPFInterest.Amount, 2); glTranDetailForBank.Amount= glTranDetailForEPFInterest.Amount + glTranDetailForCPFInterest.Amount; _glTran.DebitAmount = (double)glTranDetailForBank.Amount; _glTran.CreditAmount = (double)glTranDetailForBank.Amount; if (_errorOrSuccessList.Count == 0) { foreach (var item in memberTrans) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } _glTran.CreatedBy = this._userID; _glTran.CreatedDate = DateTime.Now; foreach (var item in _glTran.GlTranDetails) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; if (item.GLTranUserRecords != null) { foreach (var record in item.GLTranUserRecords) { record.CreatedBy = this._userID; record.CreatedDate = DateTime.Now; } } } new MemberService().UploadProfitDistribution(memberTrans, _glTran, fundTypeID, _userID); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportProfitDistributionWithoutVoucher(DataUploadColumnDefinition _columnDefinition) { int nRow = 0; int fundTypeID = _columnDefinition.SelectedItemOneID; //END Cr List ogls = new GLService().GetbyFundType(fundTypeID); List omembers = new MemberService().GetByFundType(fundTypeID); List tempMembers = new List(); FundType ftype = new FundTypeService().Get(fundTypeID); try { this.memberTrans = new List(); foreach (DataRow dr in _uplodedData.Rows) { nRow++; if (!dr.IsNull("EmployeeNo") && !dr.IsNull("TranDate") && !dr.IsNull("EPFInterest") && !dr.IsNull("CPFInterest")) { Member oMember = omembers.FirstOrDefault(x => x.EmpCode == Convert.ToString(dr["EmployeeNo"])); if (oMember == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Employee not found for in the existing data")); continue; } DateTime voucherDate; if (DateTime.TryParse(dr["TranDate"].ToString(), out voucherDate) == false) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Invalid TranDate/Voucher Date, Date must be :" + ftype.CurrentMonth.ToString())); continue; } voucherDate = GlobalFunctions.LastDateOfMonth(voucherDate); FillMemberTrans(oMember, voucherDate, Convert.ToDouble(dr["EPFInterest"]), (int)EnumMemberTranType.EPF_Interest, fundTypeID, EnumTranEffect.Increase, EnumFundCategory.EPF); //9 FillMemberTrans(oMember, voucherDate, Convert.ToDouble(dr["CPFInterest"]), (int)EnumMemberTranType.CPF_Interest, fundTypeID, EnumTranEffect.Increase, EnumFundCategory.CPF); //10 } } if (_errorOrSuccessList.Count == 0) { new MembersTransactionDetailsService().Save(memberTrans); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } private void FillMemberTrans(Member member, DateTime tranDate, double amount, int TranType, int fundType, EnumTranEffect tranEffect, EnumFundCategory cat) { MembersTransactionDetail detailTran = new MembersTransactionDetail(); detailTran.MemberID = member.ID; detailTran.TranTypeID = (EnumMemberTranType)TranType; detailTran.TranDate = tranDate; detailTran.Amount = amount; detailTran.Effect = tranEffect; detailTran.FundTypeID = fundType; detailTran.fundCategory = cat; memberTrans.Add(detailTran); } //private void FillMemberBalanceMonthly(Member member, int fundTypeID, DateTime tranDate, double contributionAmount, double profitAmount) //{ // try // { // double openingBalance = 0.0; // MemberBalaneMonthly monthlyBalance = new MemberBalaneMonthly(); // monthlyBalance.MembersID = member.ID; // monthlyBalance.MonthDate = tranDate; // monthlyBalance.FundTypeID = fundTypeID; // monthlyBalance.EmpCode = member.EmpCode; // if (member.MembershipDate.HasValue) // { // monthlyBalance.MembershipDate = member.MembershipDate.Value; // } // monthlyBalance.MembershipNo = member.MembershipNo; // monthlyBalance.CMOpeningContributionBalance = openingBalance; // initially amount is zero // monthlyBalance.CMClosingContributionBalance = monthlyBalance.CMOpeningContributionBalance + contributionAmount; // monthlyBalance.CMActualOpeningInterest = openingBalance; // initially amount is zero // monthlyBalance.CMActualClosingInterest = monthlyBalance.CMActualOpeningInterest + profitAmount; // membersMonthlyBalances.Add(monthlyBalance); // } // catch (Exception e) // { // throw e; // } //} public void ImportMember(DataUploadColumnDefinition _columnDefinition) { //Variable int fundTypeID = _columnDefinition.SelectedItemOneID; int nRow = 0; //Objects List oMembers = new List(); List memberList = new List(); List allUserRecords = new UserRecordService().Get(fundTypeID, GlobalFunctions.Fund_UserObject_Member); try { oMembers = new MemberService().GetByFundType(fundTypeID); foreach (DataRow dr in _uplodedData.Rows) { Member tempMember = new Member(); nRow = nRow + 1; //Fill Member Information if (Convert.ToString(dr["EmployeeNo"]) != string.Empty) { Member findMember = oMembers.Find(x => x.EmpCode == Convert.ToString(dr["EmployeeNo"])); if (findMember != null) tempMember = findMember; else { tempMember.FundTypeID = fundTypeID; tempMember.MemberStatus = EnumEmpStatus.Live; tempMember.EmpCode = Convert.ToString(dr["EmployeeNo"]); } } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "This cannot be empty")); continue; } if (Convert.ToString(dr["Name"]) != string.Empty) { tempMember.Name = Convert.ToString(dr["Name"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Name.", nRow, "(" + dr["Name"].ToString() + ")" + "This cannot be empty")); if (Convert.ToString(dr["Designation"]) != string.Empty) { tempMember.Designation = Convert.ToString(dr["Designation"]); } if (Convert.ToDateTime(dr["JoiningDate"]).ToString() != string.Empty) { tempMember.DOJ = Convert.ToDateTime(dr["JoiningDate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("JoiningDate.", nRow, "(" + Convert.ToDateTime(dr["JoiningDate"]).ToString() + ")" + "This cannot be empty")); if (Convert.ToDateTime(dr["Birthdate"]).ToString() != string.Empty) { tempMember.DOB = Convert.ToDateTime(dr["Birthdate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Birthdate.", nRow, "(" + Convert.ToDateTime(dr["Birthdate"]).ToString() + ")" + "This cannot be empty")); if (Convert.ToDateTime(dr["PFMembershipDate"]).ToString() != string.Empty) { tempMember.MembershipDate = Convert.ToDateTime(dr["PFMembershipDate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PFMembershipDate.", nRow, "This row cannot be empty")); if (Convert.ToDouble(dr["BasicSalary"]).ToString() != string.Empty) { tempMember.CurrentBasic = Convert.ToDouble(dr["BasicSalary"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Basic Salary.", nRow, "This row cannot be empty")); //Fill User Record Information UserRecord oUserRecord = allUserRecords.FirstOrDefault(x => x.Field1 == tempMember.EmpCode); if (oUserRecord != null) { tempMember.userRecord = new UserRecord(); tempMember.userRecord = oUserRecord; tempMember.userRecord.Field2 = tempMember.Name; // Name Will Update If Name Spelling Changes } else { tempMember.userRecord = new UserRecord(GlobalFunctions.Fund_UserObject_Member, fundTypeID, tempMember.EmpCode, tempMember.Name, ""); } //Making Data List For Save memberList.Add(tempMember); } //Saving The Data List if (_errorOrSuccessList.Count == 0) { foreach (var item in memberList) { if (item.IsNew) { item.CreatedBy = _userID; item.CreatedDate = DateTime.Now; } else { item.ModifiedBy = _userID; item.ModifiedDate = DateTime.Now; } if (item.userRecord.IsNew) { item.userRecord.CreatedBy = _userID; item.userRecord.CreatedDate = DateTime.Now; } else { item.userRecord.ModifiedBy = _userID; item.userRecord.ModifiedDate = DateTime.Now; } } new MemberService().UploadMember(memberList); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportMemberOpeningBalance(DataUploadColumnDefinition _columnDefinition) { //Variable int fundTypeID = _columnDefinition.SelectedItemOneID; int nRow = 0; double TotalAmount = 0; //Objects List oMembers = new List(); List memberList = new List(); List membertrans = new List(); GLTran voucher = new GLTran(); List voucherDetails = new List(); List gls = new GLService().GetbyFundType(fundTypeID); FundType oftype = new FundTypeService().Get(fundTypeID); DateTime voucherDate = DateTime.Today; voucherDate = oftype.LastProfitDistributionMonth; List orecords = new UserRecordService().Get(GlobalFunctions.Fund_UserObject_Member, fundTypeID); try { oMembers = new MemberService().GetByFundType(fundTypeID); foreach (DataRow dr in _uplodedData.Rows) { Member tempMember = new Member(); nRow = nRow + 1; double tempAmount = 0; //Fill Member Data if (Convert.ToString(dr["Employee No"]) != string.Empty) { Member findMember = oMembers.Find(x => x.EmpCode == Convert.ToString(dr["Employee No"])); if (findMember != null) tempMember = findMember; else { tempMember.EmpCode = Convert.ToString(dr["Employee No"]); tempMember.FundTypeID = fundTypeID; tempMember.MemberStatus = EnumEmpStatus.Live; } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "This cannot be empty")); if (Convert.ToString(dr["Employee Name"]) != string.Empty) { tempMember.Name = Convert.ToString(dr["Employee Name"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Name.", nRow, "(" + dr["Employee Name"].ToString() + ")" + "This cannot be empty")); if (Convert.ToString(dr["Designation"]) != string.Empty) { tempMember.Designation = Convert.ToString(dr["Designation"]); } if (Convert.ToDateTime(dr["Joining Date"]).ToString() != string.Empty) { tempMember.DOJ = Convert.ToDateTime(dr["Joining Date"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Joining Date.", nRow, "(" + Convert.ToDateTime(dr["Joining Date"]).ToString() + ")" + "This cannot be empty")); if (Convert.ToDateTime(dr["Birthdate"]).ToString() != string.Empty) { tempMember.DOB = Convert.ToDateTime(dr["Birthdate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Birthdate.", nRow, "(" + Convert.ToDateTime(dr["Birthdate"]).ToString() + ")" + "This cannot be empty")); if (Convert.ToDateTime(dr["PF MembershipDate"]).ToString() != string.Empty) { tempMember.MembershipDate = Convert.ToDateTime(dr["PF MembershipDate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF MembershipDate.", nRow, "This row cannot be empty")); if (Convert.ToDouble(dr["Basic Salary"]).ToString() != string.Empty) { tempMember.CurrentBasic = Convert.ToDouble(dr["Basic Salary"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Basic Salary.", nRow, "This row cannot be empty")); //Fill User Record Information UserRecord oUserRecord = orecords.FirstOrDefault(x => x.Field1 == tempMember.EmpCode); if (oUserRecord != null) { tempMember.userRecord = new UserRecord(); tempMember.userRecord = oUserRecord; tempMember.userRecord.Field2 = tempMember.Name; // Name Will Update If Name Spelling Changes } else { tempMember.userRecord = new UserRecord(GlobalFunctions.Fund_UserObject_Member, fundTypeID, tempMember.EmpCode, tempMember.Name, ""); } //Fill GL Tran as Voucher //DateTime effectDate = Convert.ToDateTime(dr["Voucher Date"]); //string voucherDescription = Convert.ToString(dr["Description"]); // voucherDate = effectDate; voucher.FundTypeID = fundTypeID; voucher.ChequeDate = voucherDate; voucher.VoucherDate = voucherDate; voucher.Description = "Opening Balance " + " " + voucherDate.ToString("MMM yyyy"); voucher.GLTranType = EnumGLTranType.OpeningMemberBalance; // EPF tempAmount = Math.Round(Convert.ToDouble(dr["EPF"]), 2); MembersTransactionDetail efp = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.EPF, tempAmount, voucherDate, EnumFundCategory.EPF); efp.EmpCode = tempMember.EmpCode; membertrans.Add(efp); string glcode = Convert.ToString(dr["EPF GL"]); GL vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF GL not found")); continue; } GLTranDetail vefp = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vefp == null) { vefp = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vefp); vefp.GLTranUserRecords = new List(); } else { vefp.Amount = Math.Round(vefp.Amount + tempAmount, 2); } GLTranUserRecord vur = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur.UserRecord1 = tempMember.userRecord; vefp.GLTranUserRecords.Add(vur); voucher.DebitAmount += (double)tempAmount; TotalAmount = Math.Round(TotalAmount + tempAmount, 2); //EPF Interest tempAmount = Math.Round(Convert.ToDouble(dr["EPF Interest"]), 2); MembersTransactionDetail epfinterest = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.EPF_Interest, tempAmount, voucherDate, EnumFundCategory.EPF); epfinterest.EmpCode = tempMember.EmpCode; membertrans.Add(epfinterest); glcode = Convert.ToString(dr["EPF Interest GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF Interest GL not found")); continue; } GLTranDetail vepfinterest = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vepfinterest == null) { vepfinterest = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vepfinterest); vepfinterest.GLTranUserRecords = new List(); } else { vepfinterest.Amount = Math.Round(vepfinterest.Amount + tempAmount, 2); } GLTranUserRecord vur1 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur1.UserRecord1 = tempMember.userRecord; vepfinterest.GLTranUserRecords.Add(vur1); voucher.DebitAmount += (double)tempAmount; TotalAmount = Math.Round(TotalAmount + tempAmount, 2); //CPF tempAmount = Math.Round(Convert.ToDouble(dr["CPF"]), 2); MembersTransactionDetail cpf = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.CPF, tempAmount, voucherDate, EnumFundCategory.CPF); cpf.EmpCode = tempMember.EmpCode; membertrans.Add(cpf); glcode = Convert.ToString(dr["CPF GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "CPF GL not found")); continue; } GLTranDetail vcpf = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vcpf == null) { vcpf = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vcpf); vcpf.GLTranUserRecords = new List(); } else { vcpf.Amount = Math.Round(vcpf.Amount + tempAmount, 2); } GLTranUserRecord vur2 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur2.UserRecord1 = tempMember.userRecord; vcpf.GLTranUserRecords.Add(vur2); voucher.DebitAmount += (double)tempAmount; TotalAmount = Math.Round(TotalAmount + tempAmount, 2); //CPF Interest GL tempAmount = Math.Round(Convert.ToDouble(dr["CPF Interest"]), 2); MembersTransactionDetail cpfinterest = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.CPF_Interest, tempAmount, voucherDate, EnumFundCategory.CPF); cpfinterest.EmpCode = tempMember.EmpCode; membertrans.Add(cpfinterest); glcode = Convert.ToString(dr["CPF Interest GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == glcode); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "CPF Interest GL not found")); continue; } GLTranDetail vcpfinterest = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vcpfinterest == null) { vcpfinterest = new GLTranDetail(vgl.ID, EnumTranSide.Credit, tempAmount, ""); voucherDetails.Add(vcpfinterest); vcpfinterest.GLTranUserRecords = new List(); } else { vcpfinterest.Amount = Math.Round(vcpfinterest.Amount + tempAmount, 2); } GLTranUserRecord vur3 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, 0, tempAmount); vur3.UserRecord1 = tempMember.userRecord; vcpfinterest.GLTranUserRecords.Add(vur3); voucher.DebitAmount += (double)tempAmount; TotalAmount = Math.Round(TotalAmount + tempAmount, 2); ; //Bank GL string bankGL = Convert.ToString(dr["Bank GL"]); vgl = gls.FirstOrDefault(x => x.GLCode == bankGL); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Bank GL not found")); continue; } GLTranDetail bank = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (bank == null) { bank = new GLTranDetail(vgl.ID, EnumTranSide.Debit, Math.Round(TotalAmount, 2), ""); voucherDetails.Add(bank); } else { bank.Amount = Math.Round(bank.Amount + tempAmount, 2); } bank.Amount = TotalAmount; voucher.CreditAmount += (double)TotalAmount; voucher.GlTranDetails = voucherDetails; memberList.Add(tempMember); } if (_errorOrSuccessList.Count == 0) { foreach (var item in memberList) { if (item.IsNew == true) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } else { item.ModifiedBy = this._userID; item.ModifiedDate = DateTime.Now; } } foreach (var item in membertrans) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } voucher.CreatedBy = this._userID; voucher.CreatedDate = DateTime.Now; voucher.CreditAmount = Math.Round(Convert.ToDouble(voucher.GlTranDetails.Where(x => x.Transide == EnumTranSide.Credit).Sum(x => x.Amount)), 2); voucher.DebitAmount = Math.Round(Convert.ToDouble(voucher.GlTranDetails.Where(x => x.Transide == EnumTranSide.Debit).Sum(x => x.Amount)), 2); foreach (var item in voucher.GlTranDetails) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; if (item.GLTranUserRecords != null) { item.Amount = Math.Round(Convert.ToDouble(item.GLTranUserRecords.Sum(x => x.Amount)), 2); foreach (var record in item.GLTranUserRecords) { record.CreatedBy = this._userID; record.CreatedDate = DateTime.Now; } } } new MemberService().UploadOpeningBalance(memberList, membertrans, voucher, fundTypeID, _userID); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportMemberLoanScheduleInfo(DataUploadColumnDefinition _columnDefinition) { //Variable int fundTypeID = _columnDefinition.SelectedItemOneID; int nRow = 0; //Objects FundType ofundtype = new FundTypeService().Get(fundTypeID); List oMembers = new MemberService().GetByFundType(fundTypeID); List oLoans = new FMLoanService().GetByFundType(fundTypeID); List oLoanSchedules = new FMLoanScheduleService().Get(ofundtype.CurrentMonth, fundTypeID); List schedules = []; List voucherDetails = new List(); List gls = new GLService().GetbyFundType(fundTypeID); List oPrincipalVoucherSetup = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Loan_Principal_Reliazation); // fundProcessType List oInterestVoucherSetup = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Loan_Interest_Reliazation); // fundProcessType List Principaltrandetails = new List(); List Interestrandetails = new List(); DateTime voucherDate = DateTime.Today; if (new GLTranService().VoucherExist(EnumGLTranType.LoanPrincipalReliazation, GlobalFunctions.FirstDateOfMonth(ofundtype.CurrentMonth), GlobalFunctions.LastDateOfMonth(ofundtype.CurrentMonth), fundTypeID) == true) { throw new Exception("Loan Deduction data has already uploaded, Please check fund current month:" + ofundtype.CurrentMonth.ToString("MMM yyyy")); } if (_uplodedData.Rows.Count != oLoanSchedules.Count) { throw new Exception("Excel file row count is not equal to system data, please check excel" + " file data to system Reports ( Monthly Loan installment) data:" + ofundtype.CurrentMonth.ToString("MMM yyyy")); } try { foreach (DataRow dRow in _uplodedData.Rows) { nRow += 1; #region Member member = oMembers.Find(x => x.EmpCode == dRow["Member No"].ToString()); if (member == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Member not Found", nRow, "(" + dRow["Member No"].ToString() + ")" + "Member/employee not found in the system.")); continue; } FMLoan ol = oLoans.Where(o => o.MemberID == member.ID && o.LoanStatus == EnumFMLoanStatus.Running).FirstOrDefault(); if (ol == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "(" + dRow["Member No"].ToString() + ")" + "There is no Loan Entry in Fund System for this employee ")); continue; } DateTime slt = DateTime.MinValue; if (DateTime.TryParse(Convert.ToString(dRow["Payroll Month"]), out slt) == false) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row.", nRow, "(" + dRow["Payroll Month"].ToString() + ")" + "This cannot be empty")); continue; } slt = GlobalFunctions.LastDateOfMonth(slt); if (slt != ofundtype.CurrentMonth) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row.", nRow, " upload month " + dRow["Payroll Month"].ToString() + " is not equal to System Current Monht " + ofundtype.CurrentMonth.ToString("MMM yyyy"))); continue; } List oschedules = oLoanSchedules.FindAll(o => o.ScheduledPayDate == GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(dRow["Payroll Month"])) && ol.ID == o.LoanID); if (oschedules == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "(" + dRow["Payroll Month"].ToString() + ")" + "There is no Loan_installment in current month: ")); continue; } if (oschedules.Count == 0) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, " Member: " + dRow["Member No"].ToString() + ")" + " does not have Loan_installment in current month: " + dRow["Payroll Month"].ToString())); continue; } FMLoanSchedule oschedule = null; if (oschedules.Count > 1) { oschedule = oschedules.FirstOrDefault(x => x.InstallmentPrincipal == Convert.ToDouble(dRow["Principle"])); } else { oschedule = oschedules[0]; } if (GlobalFunctions.LastDateOfMonth(slt) != oschedule.ScheduledPayDate) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "Payroll month :" + dRow["Payroll Month"].ToString() + " is not match with Fund Current month: " + ofundtype.CurrentMonth.ToString("MMM yyyy"))); } if (oschedule.InstallmentPrincipal != Convert.ToDouble(dRow["Principle"])) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "(" + dRow["Principle"].ToString() + ")" + "Principle Does Not Match")); } if (oschedule.InstallmentInterest != Convert.ToDouble(dRow["Interest"])) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "(" + dRow["Principle"].ToString() + ")" + "Interest Does Not Match")); } oschedule.PayDate = GlobalFunctions.LastDateOfMonth(slt); voucherDate = (DateTime)oschedule.PayDate; if (oschedule.SerialNo == ol.InstallmentNo) { ol.LoanStatus = EnumFMLoanStatus.Close; oschedule.IsCompleted = true; } oschedule.ModifiedBy = _userID; oschedule.ModifiedDate = DateTime.Now; schedules.Add(oschedule); #endregion #region Principal Voucher ActivityVoucherSetup pvprincipal = oPrincipalVoucherSetup.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Loan_Principal); if (pvprincipal == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "Loan Principal deduction voucher setup not found")); continue; } GL ogl = gls.FirstOrDefault(x => x.ID == pvprincipal.GLID); GLTranDetail oGTDetail = Principaltrandetails.FirstOrDefault(x => x.GLID == ogl.ID); if (oGTDetail == null) { oGTDetail = new GLTranDetail(); oGTDetail.GLID = ogl.ID; oGTDetail.Amount = oschedule.InstallmentPrincipal; oGTDetail.Transide = pvprincipal.GLSide; Principaltrandetails.Add(oGTDetail); } else { oGTDetail.Amount = oGTDetail.Amount + oschedule.InstallmentPrincipal; } if (ogl.UserObjectID != null) { UserRecord oRecord = new UserRecordService().GetByField1(ol.LoanNo, GlobalFunctions.Fund_UserObject_Loan, fundTypeID); if (oRecord != null) { HRM.BO.GLTranUserRecord gltUR = new GLTranUserRecord(ogl.ID, 0, 0, oRecord.UserObjectID, oRecord.ID, oschedule.InstallmentPrincipal); if (oGTDetail.GLTranUserRecords == null) oGTDetail.GLTranUserRecords = new List(); oGTDetail.GLTranUserRecords.Add(gltUR); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "UserRecord not found for loan no " + ol.LoanNo)); continue; } } ActivityVoucherSetup pricipalContra = oPrincipalVoucherSetup.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Bank || x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Contra); if (pricipalContra == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "Loan principal Contra/bank voucher GL not found in the setup ")); continue; } ogl = gls.FirstOrDefault(x => x.ID == pricipalContra.GLID); GLTranDetail pvcontra = Principaltrandetails.FirstOrDefault(x => x.GLID == ogl.ID); if (pvcontra == null) { pvcontra = new GLTranDetail(); pvcontra.GLID = ogl.ID; pvcontra.Amount = oschedule.InstallmentPrincipal; pvcontra.Transide = pricipalContra.GLSide; Principaltrandetails.Add(pvcontra); } else { pvcontra.Amount = pvcontra.Amount + oschedule.InstallmentPrincipal; } #endregion Principal Voucher #region Principal Voucher ActivityVoucherSetup pvinterest = oInterestVoucherSetup.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Loan_Interest); if (pvinterest == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "Loan Interest GL not found in the voucher setup")); continue; } ogl = gls.FirstOrDefault(x => x.ID == pvinterest.GLID); GLTranDetail oGTDetailintr = Interestrandetails.FirstOrDefault(x => x.GLID == ogl.ID); if (oGTDetailintr == null) { oGTDetailintr = new GLTranDetail(); oGTDetailintr.GLID = ogl.ID; oGTDetailintr.Amount = oschedule.InstallmentInterest; oGTDetailintr.Transide = pvinterest.GLSide; Interestrandetails.Add(oGTDetailintr); } else { oGTDetailintr.Amount = oGTDetailintr.Amount + oschedule.InstallmentInterest; } if (ogl.UserObjectID != null) { UserRecord oRecord = new UserRecordService().GetByField1(ol.LoanNo, GlobalFunctions.Fund_UserObject_Loan, fundTypeID); HRM.BO.GLTranUserRecord gltUR = new GLTranUserRecord(ogl.ID, 0, 0, oRecord.UserObjectID, oRecord.ID, oschedule.InstallmentInterest); if (oGTDetailintr.GLTranUserRecords == null) oGTDetailintr.GLTranUserRecords = new List(); oGTDetailintr.GLTranUserRecords.Add(gltUR); } ActivityVoucherSetup interestContra = oInterestVoucherSetup.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Bank || x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Contra); if (interestContra == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "Loan Interest contra/bank gl not found in voucher setup")); continue; } ogl = gls.FirstOrDefault(x => x.ID == interestContra.GLID); GLTranDetail pvInterest = Interestrandetails.FirstOrDefault(x => x.GLID == ogl.ID); if (pvInterest == null) { pvInterest = new GLTranDetail(); pvInterest.GLID = ogl.ID; pvInterest.Amount = oschedule.InstallmentInterest; pvInterest.Transide = interestContra.GLSide; Interestrandetails.Add(pvInterest); } else { pvInterest.Amount = pvInterest.Amount + oschedule.InstallmentInterest; } #endregion Principal Voucher } GLTran oPrincipalTran = new GLTran(); oPrincipalTran.VoucherDate = voucherDate; oPrincipalTran.Description = "Loan Principal Deduction,Month:" + voucherDate.ToString("MMM yyyy"); oPrincipalTran.GLTranType = EnumGLTranType.LoanPrincipalReliazation; oPrincipalTran.GlTranDetails = Principaltrandetails; oPrincipalTran.DebitAmount = Principaltrandetails.Where(X => X.Transide == EnumTranSide.Debit).Sum(x => x.Amount); oPrincipalTran.CreditAmount = Principaltrandetails.Where(X => X.Transide == EnumTranSide.Credit).Sum(x => x.Amount); GLTran oInterestTran = new GLTran(); oInterestTran.Description = "Loan Interest Deduction, Month:" + voucherDate.ToString("MMM yyyy"); oInterestTran.VoucherDate = voucherDate; oInterestTran.GlTranDetails = Interestrandetails; oInterestTran.GLTranType = EnumGLTranType.LoanInterestReliazation; oInterestTran.DebitAmount = Interestrandetails.Where(X => X.Transide == EnumTranSide.Debit).Sum(x => x.Amount); oInterestTran.CreditAmount = Interestrandetails.Where(X => X.Transide == EnumTranSide.Credit).Sum(x => x.Amount); List otrans = new List(); otrans.Add(oPrincipalTran); otrans.Add(oInterestTran); if (_errorOrSuccessList.Count == 0) { foreach (GLTran item in otrans) { item.FundTypeID = fundTypeID; item.CreatedBy = _userID; item.CreatedDate = DateTime.Now; item.CreditAmount = Convert.ToDouble(item.GlTranDetails.Where(x => x.Transide == EnumTranSide.Credit).Sum(x => x.Amount)); item.DebitAmount = Convert.ToDouble(item.GlTranDetails.Where(x => x.Transide == EnumTranSide.Debit).Sum(x => x.Amount)); foreach (GLTranDetail gltrandetail in item.GlTranDetails) { // gltrandetail.Amount = Convert.ToDouble(item.GLTranUserRecords.Sum(x => x.Amount)); gltrandetail.CreatedBy = _userID; gltrandetail.CreatedDate = DateTime.Now; } //if (item.GLTranUserRecords.Count > 0) //{ // foreach (GLTranUserRecord ur in item.GLTranUserRecords) // { // ur.CreatedBy = _userID; // ur.CreatedDate = DateTime.Now; // } //} } new FMLoanService().UpdateLoanPayDateSchedule(schedules, otrans); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportMemberLoanOpeningInfo(DataUploadColumnDefinition _columnDefinition) { //Variable int fundTypeID = _columnDefinition.SelectedItemOneID; int nRow = 0; //Objects List oMembers = new MemberService().GetByFundType(fundTypeID); List oLoanCategories = new FMLoanCategoryService().GetByFundType(fundTypeID); var fundType = new FundTypeService().Get(fundTypeID); bool isExist = new GLTranService().VoucherExist( EnumGLTranType.LoanOpeningIssue, GlobalFunctions.FirstDateOfMonth(fundType.LastProfitDistributionMonth), fundType.LastProfitDistributionMonth, fundTypeID); if (isExist == true) { throw new Exception("Loan opening data is already uploaded."); } List _LoanIssues = null; Member oMember = null; FMLoan _loan = null; FMLoanCategory loanCategory = null; FMLoanCustomer loanCustomer = null; DateTime effectiveDate = DateTime.MinValue; List voucherDetails = new List(); List gls = new GLService().GetbyFundType(fundTypeID); List oLoanIssueVoucherSetup = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Loan_Issue); // fundProcessType List oPrincipalVoucherSetup = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Loan_Principal_Reliazation); // fundProcessType List oInterestVoucherSetup = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Loan_Principal_Reliazation); // fundProcessType List loanIssuetrandetails = new List(); List Principaltrandetails = new List(); DateTime voucherDate = fundType.LastProfitDistributionMonth; try { foreach (DataRow dr in _uplodedData.Rows) { nRow += 1; #region Regular Upload oMember = oMembers.Where(o => o.EmpCode == dr["Member No"].ToString()).FirstOrDefault(); if (oMember == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Member No.", nRow, "(" + dr["Member No"].ToString() + ")" + "Member Not Found In The System")); continue; } _loan = new FMLoan(); _loan.IssueDate = Convert.ToDateTime(dr["Issue Date"]); _loan.Member = oMember; _loan.MemberID = oMember.ID; _loan.StartPayBackMonth = Convert.ToDateTime(dr["Pay Back Month"]); _loan.Activity = EnumFMLoanActivity.LoanIssue; _loan.TransferLogIDinInt = (int)EnumFMLoanTransferInfo.LoanInfoNotTransferToPR; loanCategory = oLoanCategories.Where(o => o.Description == Convert.ToString(dr["Loan Category"])).FirstOrDefault(); _loan.LoanCategoryID = loanCategory.ID; _loan.Description = loanCategory.Description; _loan.InstallmentNo = Convert.ToInt32(dr["Installment No"]); _loan.IsOpening = EnumFMLoanOpening.Opening; _loan.FundTypeID = fundTypeID; _loan.CreatedBy = _userID; _loan.CreatedDate = DateTime.Now; if (loanCategory != null) { _loan.LoanCategory = loanCategory; _loan.InterestRate = _loan.LoanCategory.DefaultInterestRate; } _loan.PrincipalAmount = Convert.ToDouble(dr["Loan Amount"]); _loan.LoanStatus = EnumFMLoanStatus.Running; // _loan.CreateSchedule(_loan.InstallmentNo, _loan.InterestRate, _loan.PrincipalAmount, _loan.StartPayBackMonth, _loan.IssueDate); _loan.LoanSchedules = new FMLoanScheduleService().CreateSchedule(_loan); double dInterest = 0; double pricipalRecoverd = 0; effectiveDate = GlobalFunctions.LastDateOfMonth( fundType.CurrentMonth.AddMonths(-1)); foreach (FMLoanSchedule lSchedule in _loan.LoanSchedules) { if (lSchedule.ScheduledPayDate <= effectiveDate) { pricipalRecoverd = pricipalRecoverd + lSchedule.InstallmentPrincipal; lSchedule.PayDate = GlobalFunctions.LastDateOfMonth(lSchedule.ScheduledPayDate); } dInterest += lSchedule.InstallmentInterest; } loanCustomer = new FMLoanCustomer(oMember); _loan.LoanCustomer = loanCustomer; if (_LoanIssues == null) _LoanIssues = new List(); _LoanIssues.Add(_loan); #endregion Regular Upload #region Loan Issue Voucher ActivityVoucherSetup LoanbankGL = oLoanIssueVoucherSetup.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Bank || x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Contra); if (LoanbankGL == null) { // if there is no bank GL throw exception throw new Exception("There is no bank GL in loan-issue setup"); } // Create a GL Tran Detail by this Bank GL and Amount will be Loan amount GL ogl = new GLService().Get(LoanbankGL.GLID); GLTranDetail bankGL = loanIssuetrandetails.FirstOrDefault(x => x.GLID == ogl.ID); if (bankGL == null) { bankGL = new GLTranDetail(); bankGL.Transide = LoanbankGL.GLSide; bankGL.Amount = _loan.PrincipalAmount; bankGL.GLID = ogl.ID; loanIssuetrandetails.Add(bankGL); } else bankGL.Amount = bankGL.Amount + _loan.PrincipalAmount; ActivityVoucherSetup vpLoanIssuePrincipal = oLoanIssueVoucherSetup.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Loan_Principal); if (vpLoanIssuePrincipal == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "Loan Principal deduction voucher setup not found")); continue; } ogl = new GLService().Get(vpLoanIssuePrincipal.GLID); GLTranDetail oGTDetail = loanIssuetrandetails.FirstOrDefault(x => x.GLID == ogl.ID); if (oGTDetail == null) { oGTDetail = new GLTranDetail(); oGTDetail.GLID = ogl.ID; oGTDetail.Amount = _loan.PrincipalAmount; ; oGTDetail.Transide = vpLoanIssuePrincipal.GLSide; loanIssuetrandetails.Add(oGTDetail); } else { oGTDetail.Amount = oGTDetail.Amount + _loan.PrincipalAmount; } if (ogl.UserObjectID != null) { HRM.BO.GLTranUserRecord gltUR = new GLTranUserRecord(ogl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Loan, _loan.MemberID, _loan.PrincipalAmount); if (oGTDetail.GLTranUserRecords == null) oGTDetail.GLTranUserRecords = new List(); oGTDetail.GLTranUserRecords.Add(gltUR); } #endregion Loan Issue Voucher #region Loan Recovered Voucher ActivityVoucherSetup pvprincipal = oPrincipalVoucherSetup.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Loan_Principal); if (pvprincipal == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "Loan Principal deduction voucher setup not found")); continue; } ogl = new GLService().Get(pvprincipal.GLID); GLTranDetail recoveredPrincipal = Principaltrandetails.FirstOrDefault(x => x.GLID == ogl.ID); if (recoveredPrincipal == null) { recoveredPrincipal = new GLTranDetail(); recoveredPrincipal.GLID = ogl.ID; recoveredPrincipal.Amount = pricipalRecoverd; recoveredPrincipal.Transide = pvprincipal.GLSide; Principaltrandetails.Add(recoveredPrincipal); } else { recoveredPrincipal.Amount = recoveredPrincipal.Amount + pricipalRecoverd; } if (ogl.UserObjectID != null) { HRM.BO.GLTranUserRecord gltUR = new GLTranUserRecord(ogl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Loan, _loan.MemberID, pricipalRecoverd); if (recoveredPrincipal.GLTranUserRecords == null) recoveredPrincipal.GLTranUserRecords = new List(); recoveredPrincipal.GLTranUserRecords.Add(gltUR); } ActivityVoucherSetup pricipalContra = oPrincipalVoucherSetup.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Bank || x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Contra); if (pricipalContra == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Error Row. ", nRow, "Loan Principal recovered voucher setup not found")); continue; } ogl = new GLService().Get(pricipalContra.GLID); GLTranDetail pvcontra = Principaltrandetails.FirstOrDefault(x => x.GLID == ogl.ID); if (pvcontra == null) { pvcontra = new GLTranDetail(); pvcontra.GLID = ogl.ID; pvcontra.Amount = pricipalRecoverd; pvcontra.Transide = pricipalContra.GLSide; Principaltrandetails.Add(pvcontra); } else { pvcontra.Amount = pvcontra.Amount + pricipalRecoverd; } #endregion Loan Recovered Voucher } GLTran oPrincipalTran = new GLTran(); oPrincipalTran.VoucherDate = voucherDate; oPrincipalTran.ChequeDate = voucherDate; oPrincipalTran.CreatedBy = _userID; oPrincipalTran.CreatedDate = DateTime.Today; oPrincipalTran.GLTranType = EnumGLTranType.LoanOpeningIssue; oPrincipalTran.FundTypeID = fundTypeID; oPrincipalTran.Description = "Loan Opening Payment voucher"; oPrincipalTran.GlTranDetails = loanIssuetrandetails; oPrincipalTran.DebitAmount = (double)loanIssuetrandetails[0].Amount; oPrincipalTran.CreditAmount = (double)loanIssuetrandetails[0].Amount; GLTran oInterestTran = new GLTran(); oInterestTran.CreatedBy = _userID; oInterestTran.CreatedDate = DateTime.Today; oInterestTran.GLTranType = EnumGLTranType.LoanOpeningPrincipalReliazation; oInterestTran.FundTypeID = fundTypeID; oInterestTran.Description = "Loan Opening Recovered"; oInterestTran.VoucherDate = voucherDate; oInterestTran.ChequeDate = voucherDate; oInterestTran.GlTranDetails = Principaltrandetails; oInterestTran.DebitAmount = (double)Principaltrandetails[0].Amount; oInterestTran.CreditAmount = (double)Principaltrandetails[0].Amount; List otrans = new List(); otrans.Add(oPrincipalTran); otrans.Add(oInterestTran); if (_errorOrSuccessList.Count == 0) { new FMLoanService().LoanOpeningSave(_LoanIssues, otrans); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportMemberContribution(DataUploadColumnDefinition _columnDefinition) { //Variable int fundTypeID = _columnDefinition.SelectedItemOneID; int nRow = 0; double TotalAmount = 0; FundType ofundType = new FundTypeService().Get(fundTypeID); //Objects List oMembers = new List(); List memberList = new List(); List membertrans = new List(); GLTran voucher = new GLTran(); List voucherDetails = new List(); List gls = new GLService().GetbyFundType(fundTypeID); List oActivityVoucherSetups = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Monthly_Contribution); // fundProcessType List orecords = new UserRecordService().Get(GlobalFunctions.Fund_UserObject_Member, fundTypeID); DateTime voucherDate = GlobalFunctions.LastDateOfMonth(ofundType.CurrentMonth); bool isProcessedMonth = new GLTranService().VoucherExist(EnumGLTranType.MonthlyContribution, GlobalFunctions.FirstDateOfMonth(voucherDate), GlobalFunctions.LastDateOfMonth(voucherDate), fundTypeID); try { oMembers = new MemberService().GetByFundType(fundTypeID); foreach (DataRow dr in _uplodedData.Rows) { Member tempMember = new Member(); nRow = nRow + 1; double tempAmount = 0; if (Convert.ToString(dr["Employee No"]) != string.Empty) { Member findMember = oMembers.Find(x => x.EmpCode == Convert.ToString(dr["Employee No"])); if (findMember != null) tempMember = findMember; else { tempMember.EmpCode = Convert.ToString(dr["Employee No"]); tempMember.FundTypeID = fundTypeID; tempMember.MemberStatus = EnumEmpStatus.Live; } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "EmloyeeID/Code cant' be Empty")); if (tempMember.IsNew == true) { if (Convert.ToString(dr["Employee Name"]) != string.Empty) { tempMember.Name = Convert.ToString(dr["Employee Name"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Name.", nRow, "(" + dr["Employee Name"].ToString() + ")" + "Name Cant be Empty")); } if (tempMember.IsNew == true) { if (Convert.ToString(dr["Designation"]) != string.Empty) { tempMember.Designation = Convert.ToString(dr["Designation"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Name.", nRow, "(" + dr["Employee Name"].ToString() + ")" + "Designation can't be empty")); } if (tempMember.IsNew == true) { if (Convert.ToString(dr["Joining Date"]).ToString() != string.Empty) { tempMember.DOJ = Convert.ToDateTime(dr["Joining Date"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Name.", nRow, "(" + dr["Employee Name"].ToString() + ")" + "Designation can't be empty")); } if (tempMember.IsNew == true) { if (Convert.ToString(dr["PF MembershipDate"]).ToString() != string.Empty) { tempMember.MembershipDate = Convert.ToDateTime(dr["PF MembershipDate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF MembershipDate.", nRow, "PF Membership Date cant be Empty")); } if (tempMember.IsNew == true) { if (Convert.ToString(dr["Basic Salary"]).ToString() != string.Empty) { tempMember.CurrentBasic = Convert.ToDouble(dr["Basic Salary"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Basic Salary.", nRow, "Basic Salary can't be Emplty")); } //Fill User Record Information UserRecord oUserRecord = orecords.FirstOrDefault(x => x.Field1 == tempMember.EmpCode); if (oUserRecord != null) { tempMember.userRecord = new UserRecord(); tempMember.userRecord = oUserRecord; tempMember.userRecord.Field1 = tempMember.EmpCode; // Name Will Update If Name Spelling Changes tempMember.userRecord.Field2 = tempMember.Name; // Name Will Update If Name Spelling Changes } else { tempMember.userRecord = new UserRecord(GlobalFunctions.Fund_UserObject_Member, fundTypeID, tempMember.EmpCode, tempMember.Name, ""); } DateTime effectDate = GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(dr["Contribution Month"])); if (effectDate != ofundType.CurrentMonth) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Contribution Month.", nRow, "Contribution Month:" + effectDate.ToString("dd MMM yyyy") + " must be between System Current Month.")); continue; } voucherDate = effectDate; voucher.FundTypeID = fundTypeID; voucher.VoucherDate = voucherDate; voucher.Description = "EPF & CPF contribution for the month " + voucherDate.ToString("MMM yyyy"); voucher.GLTranType = EnumGLTranType.MonthlyContribution; // Check Data is already Uploaded or Not if (isProcessedMonth) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Month Processed", nRow, "Contribution Month:" + effectDate.ToString("dd MMM yyyy") + " Contribution data is Already uploaded for this month")); continue; } // EPF tempAmount = Convert.ToDouble(dr["EPF"]); MembersTransactionDetail efp = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.EPF, tempAmount, effectDate, EnumFundCategory.EPF); efp.EmpCode = tempMember.EmpCode; membertrans.Add(efp); ActivityVoucherSetup epfgl = oActivityVoucherSetups.FirstOrDefault(x => x.FundProcessType == EnumFundProcessType.Monthly_Contribution && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.EPF); // EPF if (epfgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF GL not found in the system")); continue; } GL vgl = gls.FirstOrDefault(x => x.ID == epfgl.GLID); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF GL not found")); continue; } GLTranDetail vefp = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vefp == null) { vefp = new GLTranDetail(vgl.ID, (EnumTranSide)epfgl.GLSide, tempAmount, ""); voucherDetails.Add(vefp); vefp.GLTranUserRecords = new List(); } else { vefp.Amount = vefp.Amount + tempAmount; } GLTranUserRecord vur = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, tempMember.userRecord.ID, tempAmount); vur.UserRecord1 = tempMember.userRecord; vefp.GLTranUserRecords.Add(vur); voucher.CreditAmount += (double)tempAmount; TotalAmount += tempAmount; //CPF tempAmount = Convert.ToDouble(dr["CPF"]); MembersTransactionDetail cpf = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.CPF, tempAmount, effectDate, EnumFundCategory.CPF); cpf.EmpCode = tempMember.EmpCode; membertrans.Add(cpf); ActivityVoucherSetup cpfgl = oActivityVoucherSetups.FirstOrDefault(x => x.FundProcessType == EnumFundProcessType.Monthly_Contribution && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.CPF); if (cpfgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "CPF GL not found in the system")); continue; } vgl = gls.FirstOrDefault(x => x.ID == cpfgl.GLID); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "CPF GL not found")); continue; } GLTranDetail vcpf = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vcpf == null) { vcpf = new GLTranDetail(vgl.ID, (EnumTranSide)cpfgl.GLSide, tempAmount, ""); voucherDetails.Add(vcpf); vcpf.GLTranUserRecords = new List(); } else { vcpf.Amount = vcpf.Amount + tempAmount; } GLTranUserRecord vur2 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, tempMember.userRecord.ID, tempAmount); vur2.UserRecord1 = tempMember.userRecord; vcpf.GLTranUserRecords.Add(vur2); voucher.CreditAmount += (double)tempAmount; TotalAmount += tempAmount; //Bank GL ActivityVoucherSetup bankVS = oActivityVoucherSetups.FirstOrDefault(x => x.FundProcessType == EnumFundProcessType.Monthly_Contribution && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Bank || x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Contra); if (bankVS == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Bank GL not found in system")); continue; } vgl = gls.FirstOrDefault(x => x.ID == bankVS.GLID); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Bank GL not found")); continue; } GLTranDetail bank = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (bank == null) { bank = new GLTranDetail(vgl.ID, (EnumTranSide)bankVS.GLSide, TotalAmount, ""); voucherDetails.Add(bank); } bank.Amount = TotalAmount; voucher.DebitAmount = (double)TotalAmount; memberList.Add(tempMember); voucher.GlTranDetails = voucherDetails; } if (_errorOrSuccessList.Count == 0) { voucher.VoucherDate = voucherDate; voucher.CreditAmount = voucher.GlTranDetails.Where(x => x.Transide == EnumTranSide.Credit).Sum(x => x.Amount); voucher.DebitAmount = voucher.GlTranDetails.Where(x => x.Transide == EnumTranSide.Debit).Sum(x => x.Amount); foreach (var item in memberList) { if (item.IsNew == true) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } else { item.ModifiedBy = this._userID; item.ModifiedDate = DateTime.Now; } } foreach (var item in membertrans) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } voucher.CreatedBy = this._userID; voucher.CreatedDate = DateTime.Now; foreach (var item in voucher.GlTranDetails) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; if (item.GLTranUserRecords != null) { foreach (var record in item.GLTranUserRecords) { record.CreatedBy = this._userID; record.CreatedDate = DateTime.Now; } } } new MemberService().UploadOpeningBalance(memberList, membertrans, voucher, fundTypeID, _userID); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportMemberVoluntaryContribution(DataUploadColumnDefinition _columnDefinition) { //Variable int fundTypeID = _columnDefinition.SelectedItemOneID; int nRow = 0; double TotalAmount = 0; FundType ofundType = new FundTypeService().Get(fundTypeID); //Objects List oMembers = new List(); List memberList = new List(); List membertrans = new List(); GLTran voucher = new GLTran(); List voucherDetails = new List(); List gls = new GLService().GetbyFundType(fundTypeID); List oActivityVoucherSetups = new ActivityVoucherSetupService().GetByProcessType(fundTypeID, EnumFundProcessType.Voluntary_Contribution); // fundProcessType List orecords = new UserRecordService().Get(GlobalFunctions.Fund_UserObject_Member, fundTypeID); DateTime voucherDate = GlobalFunctions.LastDateOfMonth(ofundType.CurrentMonth); bool isProcessedMonth = new GLTranService().VoucherExist(EnumGLTranType.MonthlyContribution, GlobalFunctions.FirstDateOfMonth(voucherDate), GlobalFunctions.LastDateOfMonth(voucherDate), fundTypeID); try { oMembers = new MemberService().GetByFundType(fundTypeID); foreach (DataRow dr in _uplodedData.Rows) { Member tempMember = new Member(); nRow = nRow + 1; double tempAmount = 0; if (Convert.ToString(dr["Employee No"]) != string.Empty) { Member findMember = oMembers.Find(x => x.EmpCode == Convert.ToString(dr["Employee No"])); if (findMember != null) tempMember = findMember; else { tempMember.EmpCode = Convert.ToString(dr["Employee No"]); tempMember.FundTypeID = fundTypeID; tempMember.MemberStatus = EnumEmpStatus.Live; } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "EmloyeeID/Code cant' be Empty")); if (tempMember.IsNew == true) { if (Convert.ToString(dr["Employee Name"]) != string.Empty) { tempMember.Name = Convert.ToString(dr["Employee Name"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Name.", nRow, "(" + dr["Employee Name"].ToString() + ")" + "Name Cant be Empty")); } if (tempMember.IsNew == true) { if (Convert.ToString(dr["Designation"]) != string.Empty) { tempMember.Designation = Convert.ToString(dr["Designation"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Name.", nRow, "(" + dr["Employee Name"].ToString() + ")" + "Designation can't be empty")); } if (tempMember.IsNew == true) { if (Convert.ToString(dr["Joining Date"]).ToString() != string.Empty) { tempMember.DOJ = Convert.ToDateTime(dr["Joining Date"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Name.", nRow, "(" + dr["Employee Name"].ToString() + ")" + "Designation can't be empty")); } if (tempMember.IsNew == true) { if (Convert.ToString(dr["PF MembershipDate"]).ToString() != string.Empty) { tempMember.MembershipDate = Convert.ToDateTime(dr["PF MembershipDate"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF MembershipDate.", nRow, "PF Membership Date cant be Empty")); } if (tempMember.IsNew == true) { if (Convert.ToString(dr["Basic Salary"]).ToString() != string.Empty) { tempMember.CurrentBasic = Convert.ToDouble(dr["Basic Salary"]); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Basic Salary.", nRow, "Basic Salary can't be Emplty")); } //Fill User Record Information UserRecord oUserRecord = orecords.FirstOrDefault(x => x.Field1 == tempMember.EmpCode); if (oUserRecord != null) { tempMember.userRecord = new UserRecord(); tempMember.userRecord = oUserRecord; tempMember.userRecord.Field1 = tempMember.EmpCode; // Name Will Update If Name Spelling Changes tempMember.userRecord.Field2 = tempMember.Name; // Name Will Update If Name Spelling Changes } else { tempMember.userRecord = new UserRecord(GlobalFunctions.Fund_UserObject_Member, fundTypeID, tempMember.EmpCode, tempMember.Name, ""); } DateTime effectDate = GlobalFunctions.LastDateOfMonth(Convert.ToDateTime(dr["Contribution Month"])); if (effectDate != ofundType.CurrentMonth) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Contribution Month.", nRow, "Contribution Month:" + effectDate.ToString("dd MMM yyyy") + " must be between System Current Month.")); continue; } voucherDate = effectDate; voucher.FundTypeID = fundTypeID; voucher.VoucherDate = voucherDate; voucher.Description = "EPF & CPF contribution for the month " + voucherDate.ToString("MMM yyyy"); voucher.GLTranType = EnumGLTranType.MonthlyContribution; // Check Data is already Uploaded or Not if (isProcessedMonth) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Month Processed", nRow, "Contribution Month:" + effectDate.ToString("dd MMM yyyy") + " Contribution data is Already uploaded for this month")); continue; } // EPF tempAmount = Convert.ToDouble(dr["EPF"]); MembersTransactionDetail efp = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.EPF, tempAmount, effectDate, EnumFundCategory.EPF); efp.EmpCode = tempMember.EmpCode; membertrans.Add(efp); ActivityVoucherSetup epfgl = oActivityVoucherSetups.FirstOrDefault(x => x.FundProcessType == EnumFundProcessType.Voluntary_Contribution && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.EPF); // EPF if (epfgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF GL not found in the system")); continue; } GL vgl = gls.FirstOrDefault(x => x.ID == epfgl.GLID); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF GL not found")); continue; } GLTranDetail vefp = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vefp == null) { vefp = new GLTranDetail(vgl.ID, (EnumTranSide)epfgl.GLSide, tempAmount, ""); voucherDetails.Add(vefp); vefp.GLTranUserRecords = new List(); } else { vefp.Amount = vefp.Amount + tempAmount; } GLTranUserRecord vur = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, tempMember.userRecord.ID, tempAmount); vur.UserRecord1 = tempMember.userRecord; vefp.GLTranUserRecords.Add(vur); voucher.CreditAmount += (double)tempAmount; TotalAmount += tempAmount; // Voluntary EPF tempAmount = Convert.ToDouble(dr["Voluntary EPF"]); MembersTransactionDetail voluntaryEfp = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.Voluntary_EFP, tempAmount, effectDate, EnumFundCategory.Voluntary); voluntaryEfp.EmpCode = tempMember.EmpCode; membertrans.Add(voluntaryEfp); ActivityVoucherSetup voluntaryEpfGl = oActivityVoucherSetups.FirstOrDefault(x => x.FundProcessType == EnumFundProcessType.Voluntary_Contribution && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Voluntary_EPF); if (voluntaryEpfGl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "EPF GL not found in the system")); continue; } GL voluntaryGl = gls.FirstOrDefault(x => x.ID == voluntaryEpfGl.GLID); if (voluntaryGl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Voluntary EPF GL not found")); continue; } GLTranDetail voluntaryGlTD = voucherDetails.FirstOrDefault(x => x.GLID == voluntaryGl.ID); if (voluntaryGlTD == null) { voluntaryGlTD = new GLTranDetail(voluntaryGl.ID, (EnumTranSide)voluntaryEpfGl.GLSide, tempAmount, ""); voucherDetails.Add(voluntaryGlTD); voluntaryGlTD.GLTranUserRecords = new List(); } else { voluntaryGlTD.Amount = voluntaryGlTD.Amount + tempAmount; } GLTranUserRecord voluntaryur = new GLTranUserRecord(voluntaryGl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, tempMember.userRecord.ID, tempAmount); voluntaryur.UserRecord1 = tempMember.userRecord; voluntaryGlTD.GLTranUserRecords.Add(voluntaryur); voucher.CreditAmount += (double)tempAmount; TotalAmount += tempAmount; //CPF tempAmount = Convert.ToDouble(dr["CPF"]); MembersTransactionDetail cpf = new MembersTransactionDetail(0, fundTypeID, EnumMemberTranType.CPF, tempAmount, effectDate, EnumFundCategory.CPF); cpf.EmpCode = tempMember.EmpCode; membertrans.Add(cpf); ActivityVoucherSetup cpfgl = oActivityVoucherSetups.FirstOrDefault(x => x.FundProcessType == EnumFundProcessType.Voluntary_Contribution && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.CPF); if (cpfgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "CPF GL not found in the system")); continue; } vgl = gls.FirstOrDefault(x => x.ID == cpfgl.GLID); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "CPF GL not found")); continue; } GLTranDetail vcpf = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (vcpf == null) { vcpf = new GLTranDetail(vgl.ID, (EnumTranSide)cpfgl.GLSide, tempAmount, ""); voucherDetails.Add(vcpf); vcpf.GLTranUserRecords = new List(); } else { vcpf.Amount = vcpf.Amount + tempAmount; } GLTranUserRecord vur2 = new GLTranUserRecord(vgl.ID, 0, 0, GlobalFunctions.Fund_UserObject_Member, tempMember.userRecord.ID, tempAmount); vur2.UserRecord1 = tempMember.userRecord; vcpf.GLTranUserRecords.Add(vur2); voucher.CreditAmount += (double)tempAmount; TotalAmount += tempAmount; //Bank GL ActivityVoucherSetup bankVS = oActivityVoucherSetups.FirstOrDefault(x => x.FundProcessType == EnumFundProcessType.Monthly_Contribution && x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Bank || x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Contra); if (bankVS == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Bank GL not found in system")); continue; } vgl = gls.FirstOrDefault(x => x.ID == bankVS.GLID); if (vgl == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("GL.", nRow, "Bank GL not found")); continue; } GLTranDetail bank = voucherDetails.FirstOrDefault(x => x.GLID == vgl.ID); if (bank == null) { bank = new GLTranDetail(vgl.ID, (EnumTranSide)bankVS.GLSide, TotalAmount, ""); voucherDetails.Add(bank); } bank.Amount = TotalAmount; voucher.DebitAmount = (double)TotalAmount; memberList.Add(tempMember); voucher.GlTranDetails = voucherDetails; } if (_errorOrSuccessList.Count == 0) { voucher.VoucherDate = voucherDate; voucher.CreditAmount = voucher.GlTranDetails.Where(x => x.Transide == EnumTranSide.Credit).Sum(x => x.Amount); voucher.DebitAmount = voucher.GlTranDetails.Where(x => x.Transide == EnumTranSide.Debit).Sum(x => x.Amount); foreach (var item in memberList) { if (item.IsNew == true) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } else { item.ModifiedBy = this._userID; item.ModifiedDate = DateTime.Now; } } foreach (var item in membertrans) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; } voucher.CreatedBy = this._userID; voucher.CreatedDate = DateTime.Now; foreach (var item in voucher.GlTranDetails) { item.CreatedBy = this._userID; item.CreatedDate = DateTime.Now; if (item.GLTranUserRecords != null) { foreach (var record in item.GLTranUserRecords) { record.CreatedBy = this._userID; record.CreatedDate = DateTime.Now; } } } new MemberService().UploadOpeningBalance(memberList, membertrans, voucher, fundTypeID, _userID); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportCV(DataUploadColumnDefinition _columnDefinition) { List oemployees = new EmployeeService().GetAllEmps(); _TaxChallans = new List(); Employee oemployee = null; int nRow = 0; List cvs = new List(); try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; if (_columnDefinition.SelectedItemOneID != 0) { CV cv = new CV(); cv.PositionID = _columnDefinition.SelectedItemOneID; cv.Name = Convert.ToString(dr["Name"]); cv.Email = Convert.ToString(dr["Email"]); cv.Mobile = Convert.ToString(dr["Mobile"]); cv.Education = Convert.ToString(dr["Education"]); cv.Experience = Convert.ToString(dr["Experience"]); cv.Skill = Convert.ToString(dr["Skill"]); cv.CreatedBy = _userID; cv.CreatedDate = DateTime.Today; cvs.Add(cv); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Candidate Name ", nRow, "(" + dr["Name"].ToString() + ")" + " not found for in the existing data")); } if (_errorOrSuccessList.Count == 0) { new CVService().SaveCVs(cvs); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportSalaryComponent(DataUploadColumnDefinition _columnDefinition) { List oemployees = new EmployeeService().Get(EnumEmployeeStatus.Live, this._payrollTypeID); List osalaryDetails = new List(); List incomeTaxes = new List(); PayrollType ptype = new PayrollTypeService().Get(this._payrollTypeID); Employee oemployee = null; int nRow = 0; double tempAmount = 0; List salaries = new SalaryMonthlyService().Get(ptype.NextPayProcessDate, this._payrollTypeID); try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["EmployeeNo"].ToString(); }); EnumSalaryItemCode itemCode = (EnumSalaryItemCode)Convert.ToInt32(dr["ItemCode"]); EnumSalaryGroup groupCode = (EnumSalaryGroup)Convert.ToInt32(dr["ItemGroup"]); int ItemID = (int)Convert.ToInt32(dr["ItemID"]); if (oemployee != null) { SalaryMonthly oMonthly; oMonthly = salaries.Find(x => x.EmployeeID == oemployee.ID); if (oMonthly == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + " salary not yet processed.")); continue; } SalaryMonthlyDetail oDetail = oMonthly.Details.Find(delegate (SalaryMonthlyDetail oSMD) { return oSMD.ItemCode == itemCode && oSMD.itemGroupCode == groupCode && oSMD.ItemID == ItemID; }); if (oDetail == null) { oDetail = new SalaryMonthlyDetail(); oDetail.SalaryMonthlyID = oMonthly.Details[0].SalaryMonthlyID; oDetail.itemGroupCode = groupCode; oDetail.ItemID = ItemID; oDetail.ItemCode = itemCode; oDetail.CalculatedAmount = 0; //oDetail.Description SalaryMonthlyDetail gitem = oMonthly.Details.Find(delegate (SalaryMonthlyDetail oSMD) { return oSMD.ItemCode == itemCode && oSMD.ItemID == ItemID; }); if (gitem == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + " salary component not foun")); continue; } oDetail.Description = gitem.Description; oDetail.Position = gitem.Position; oDetail.SupportID = gitem.SupportID; oDetail.ChangedAmount = Convert.ToDouble(dr["Amount"]); } else { tempAmount = oDetail.ChangedAmount; oDetail.ChangedAmount = Convert.ToDouble(dr["Amount"]); } osalaryDetails.Add(oDetail); SalaryMonthlyDetail onetpaydetail = oMonthly.Details.Find(delegate (SalaryMonthlyDetail oSMD) { return oSMD.ItemCode == EnumSalaryItemCode.Net_Payable && oSMD.itemGroupCode == EnumSalaryGroup.OtherItem && oSMD.ItemID == (int)EnumSalaryItemCode.Net_Payable; }); if (onetpaydetail == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "net pay item not found")); continue; } // if detail not found, generate an errror and continue // same way, get the net pay // if net pay item not found, generate an error //SalaryMonthlyDetail onetpaydetail = _SalaryMonthly.Details.Find( // if net pay goes negative, generate an error if (groupCode == EnumSalaryGroup.Gross || groupCode == EnumSalaryGroup.Arrear) { onetpaydetail.ChangedAmount = onetpaydetail.ChangedAmount - tempAmount + oDetail.ChangedAmount; osalaryDetails.Add(onetpaydetail); } else if (groupCode == EnumSalaryGroup.Deductions || groupCode == EnumSalaryGroup.UnauthLeave) { onetpaydetail.ChangedAmount = onetpaydetail.ChangedAmount + tempAmount - oDetail.ChangedAmount; osalaryDetails.Add(onetpaydetail); } if (onetpaydetail.ChangedAmount <= 0) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "net pay can't be less then zero")); continue; } // if the item is tax item, update tax card deducted column. if (itemCode == EnumSalaryItemCode.Inc_Tax_Deduction) { IncomeTax otaxItem = new IncomeTax(); otaxItem.EmployeeID = oemployee.ID; otaxItem.ThisMonthAmount = oDetail.ChangedAmount; incomeTaxes.Add(otaxItem); } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Employee not found for in the existing data")); } if (osalaryDetails.Count > 0) { new SalaryMonthlyService().UpdateDetail(osalaryDetails, incomeTaxes); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } private static DataTable ExtractFromExcel(System.IO.Stream fileStream, string sheetName = "") { ImportHelper iHelper = new ImportHelper(); DataSet dDataSet = iHelper.Import(ImportHelper.Formats.Excel, fileStream, true); try { return dDataSet.Tables[0].Copy(); } catch (Exception) { if (string.IsNullOrEmpty(sheetName)) { throw new Exception("No sheet Found in Excel"); } else { throw new Exception("Could not Find sheet with name:" + sheetName); } } } #region Import Employee Profile Info public void ImportEmployeeProfileInfo() { int nRow = 0; HREmployee oHREmployee = null; List oHREmployees = new List(); List oemployees = new HREmployeeService().GetWithPayrollType(_payrollTypeID); try { foreach (DataRow dr in _uplodedData.Rows) { nRow += 1; oHREmployee = oemployees.Find(item => item.EmployeeNo == dr["Employee No"].ToString().Trim()); if (oHREmployee != null) { oHREmployee.EmailAddress = dr["Email"].ToString().Trim() != string.Empty ? dr["Email"].ToString().Trim() : string.Empty; oHREmployee.MobileNo = dr["Mobile"].ToString().Trim() != string.Empty ? dr["Mobile"].ToString().Trim() : string.Empty; switch (dr["Blood Group"].ToString().Trim().ToLower()) { case "ab-": oHREmployee.BloodGroup = EnumBloodGroup.ABNeg; break; case "ab+": oHREmployee.BloodGroup = EnumBloodGroup.ABPos; break; case "a-": oHREmployee.BloodGroup = EnumBloodGroup.ANeg; break; case "a+": oHREmployee.BloodGroup = EnumBloodGroup.APos; break; case "b-": oHREmployee.BloodGroup = EnumBloodGroup.BNeg; break; case "b+": oHREmployee.BloodGroup = EnumBloodGroup.BPos; break; case "o-": oHREmployee.BloodGroup = EnumBloodGroup.ONeg; break; case "o+": oHREmployee.BloodGroup = EnumBloodGroup.OPos; break; default: oHREmployee.BloodGroup = EnumBloodGroup.None; break; } oHREmployee.NationalID = dr["National ID"].ToString().Trim() != string.Empty ? dr["National ID"].ToString().Trim() : string.Empty; oHREmployee.TinNo = dr["TIN"].ToString().Trim() != string.Empty ? dr["TIN"].ToString().Trim() : string.Empty; oHREmployees.Add(oHREmployee); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } } if (_errorOrSuccessList.Count == 0) { new HREmployeeService().SaveEmployeeProfileUpload(oHREmployees); } } catch (Exception e) { throw new ServiceException("Error occurred. Reason:" + e.Message); } } #endregion #region Import Employee Basic Information public void ImportEmpBasicInfo(int uploadid) { _columndefinfationService = new DataUploadColumnDefinationService(); _columndefinfationService.ImportEmpBasicInfo(_uplodedData, _payrollTypeID, _userID, (EnumRegularDataUpload)uploadid); _errorOrSuccessList = _columndefinfationService.ErrorOrSuccessList; if (_errorOrSuccessList.Count == 0) { _columndefinfationService.Save(this._payrollTypeID, this._userID, (EnumRegularDataUpload)uploadid); } } #endregion public List GetBonusData(int uploadId, DataUploadColumnDefinition oColumnDefination, System.IO.Stream fileStream, int payrollTypeID) { List bdetails = new List(); _uplodedData = ExtractFromExcel(fileStream, oColumnDefination.SheetName); _errorOrSuccessList = this.ValidateUploadedData(oColumnDefination, _uplodedData); oColumnDefination.PayrollTypeID = payrollTypeID; this._payrollTypeID = oColumnDefination.PayrollTypeID; if (_errorOrSuccessList.Count > 0) { string str = ""; _errorOrSuccessList.ForEach(x => { str = str + x.RowNo + " " + x.Message; }); throw new Exception(str); } PayrollType ptype = new PayrollTypeService().Get(this._payrollTypeID); List oemployees = new EmployeeService().Get(); Employee oemployee = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; BonusProcess.BonusProcessDetail item = new BonusProcess.BonusProcessDetail(); oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { item.Employee = oemployee; item.EmployeeID = oemployee.ID; item.BasicSalary = oemployee.BasicSalary; item.GrossSalary = oemployee.GrossSalary; item.BonusAmount = dr["Amount"].ToString() != string.Empty ? Convert.ToDouble(dr["Amount"]) : 0.0; item.BonusAmount = GlobalFunctions.Round(item.BonusAmount); item.ChangeBonusAmount = item.BonusAmount; } else { throw new ServiceException("Employee not found:" + nRow + " Reason:" + dr["Employee No"].ToString()); } bdetails.Add(item); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } return bdetails; } #region Import Employee Individual Allowence public void ImportEmpIndividualAllowanceDeduction(DataUploadColumnDefinition _columnDefinition, EnumAllowOrDeduct type) { List oadparamemployees = new List(); PayrollType ptype = new PayrollTypeService().Get(this._payrollTypeID); List oemployees = new EmployeeService().Get(); SystemInformation sysInfo = new SystemInformationService().Get(); List oadparameters = new ADParameterService().GetWithDetail(EnumStatus.Active, _payrollTypeID); Employee oemployee = null; ADParameterEmployee oadparamemp = null; List allows = new AllowanceDeductionService().Get(EnumStatus.Regardless, this._payrollTypeID); int nRow = 0; try { bool autoaprov = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "finantialaproval", "finantialaprovalrequired"); foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { oadparamemp = new ADParameterEmployee(); oadparamemp.EmployeeID = oemployee.ID; if (!autoaprov) { oadparamemp.ApprovalStatus = EnumAuthStatus.Approved; } //if (_columnDefinition.SelectedItemOneID) //oadparamemp.FormDate = Convert.ToDateTime(dr["From Date"]); //oadparamemp.TillDate = Convert.ToDateTime(dr["Till Date"]); if (dr["Amount"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Amount can not be Empty" + " Row : ", nRow, "Amount can not be Empty", oemployee.EmployeeNo, oemployee.Name)); continue; } oadparamemp.MonthlyAmount = dr["Amount"].ToString() != string.Empty ? Convert.ToDouble(dr["Amount"]) : 0.0; oadparamemp.AllowDeductID = (int)_columnDefinition.uploadItemID; //ID.FromInteger(Convert.ToInt32(EnumAllowOrDeduct.Deduction)); var allow = allows.FirstOrDefault(x => x.ID == oadparamemp.AllowDeductID); if (oemployee.GradeID == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Grade.", nRow, "(" + dr["Grade"].ToString() + ")" + "Grade Id not found in the current context", oemployee.EmployeeNo, oemployee.Name)); continue; } List oparamters = oadparameters.FindAll(x => x.AllowDeductID == oadparamemp.AllowDeductID); ADParameter oparamter = new ADParameterService().GetApplicableParameter(oemployee, oemployee.GradeID ?? -1, oadparameters, oadparamemp.AllowDeductID); if (oparamter == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No :" + dr["Employee No"].ToString() + " Row : ", nRow, "Employee applicable parameter not found.", oemployee.EmployeeNo, oemployee.Name)); continue; } oadparamemp.ADParameterID = oparamter.ID; oadparamemp.Periodicity = oparamter.Periodicity; if (oadparamemp.Periodicity == EnumPeriodicity.OneOff) { oadparamemp.FormDate = GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate); oadparamemp.TillDate = ptype.NextPayProcessDate; } else if (oadparamemp.Periodicity == EnumPeriodicity.Monthly && oparamter.EntitleType == EnumEntitleType.Individual) { // from date can't prior to fist date of current month // till date can't be less to from date // from date can't be greater to last date of current month if (dr["From Date"].ToString() == "") { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date Can't be Empty" + " Row : ", nRow, "From date can not be Empty", oemployee.EmployeeNo, oemployee.Name)); continue; } if (dr["From Date"].ToString() != "" && Convert.ToDateTime(dr["From Date"]) < GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate) && allow.AllowOrDeductType != EnumAllowOrDeduct.Allowance) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date :" + dr["From Date"].ToString() + " Row : ", nRow, "From date can not be less than first date of current month", oemployee.EmployeeNo, oemployee.Name)); continue; } if (dr["From Date"].ToString() != "" && Convert.ToDateTime(dr["From Date"]) > GlobalFunctions.LastDateOfMonth(ptype.NextPayProcessDate)) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date :" + dr["From Date"].ToString() + " Row : ", nRow, "From date can not be greater than last date of current month", oemployee.EmployeeNo, oemployee.Name)); continue; } if (dr["Till Date"].ToString() != "" && Convert.ToDateTime(dr["Till Date"]) < Convert.ToDateTime(dr["From Date"])) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Till Date :" + dr["Till Date"].ToString() + " Row : ", nRow, "Till date can not be less than From date", oemployee.EmployeeNo, oemployee.Name)); continue; } oadparamemp.FormDate = dr["From Date"].ToString() != "" ? Convert.ToDateTime(dr["From Date"]) : GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate); if (dr["Till Date"].ToString() != "") oadparamemp.TillDate = Convert.ToDateTime(dr["Till Date"]); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No :" + dr["Employee No"].ToString() + " Row : ", nRow, "Employee applicable parameter is defined greade wise")); continue; } //if (oparamter.MaxAmount < oadparamemp.MonthlyAmount && oparamter.IsFractionateApplicable == true) // oadparamemp.MonthlyAmount = oadparamemp.MonthlyAmount - oparamter.MaxAmount; //else if (oparamter.MaxAmount != 0 && oparamter.MaxAmount < oadparamemp.MonthlyAmount) oadparamemp.MonthlyAmount = oparamter.MaxAmount; if (oparamter.MinAmount != 0 && oparamter.MinAmount > oadparamemp.MonthlyAmount) oadparamemp.MonthlyAmount = oparamter.MinAmount; oadparamemp.ADEmpType = EnumADEmpType.AppliedToIndividual; oadparamemp.Arreartype = EnumArrearType.NotPresent; oadparamemp.ValueType = EnumValueType.Amount; oadparamemp.CreatedBy = _userID; oadparamemp.ModifiedDate = null; oadparamemp.ModifiedBy = null; oadparamemployees.Add(oadparamemp); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } if (_errorOrSuccessList.Count == 0) { new ADParameterEmployeeService().Save(oadparamemployees, ptype.LastPayProcessDate); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } public void ImportEmpIndvAllowDeductExcess(DataUploadColumnDefinition _columnDefinition, EnumAllowOrDeduct type) { List oadparamemployees = new List(); PayrollType ptype = new PayrollTypeService().Get(this._payrollTypeID); List oemployees = new EmployeeService().Get(); SystemInformation sysInfo = new SystemInformationService().Get(); List oadparameters = new ADParameterService().GetWithDetail(EnumStatus.Active, _payrollTypeID); Employee oemployee = null; ADParameterEmployee oadparamemp = null; List allows = new AllowanceDeductionService().Get(EnumStatus.Regardless, this._payrollTypeID); int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { oadparamemp = new ADParameterEmployee(); oadparamemp.EmployeeID = oemployee.ID; //if (_columnDefinition.SelectedItemOneID) //oadparamemp.FormDate = Convert.ToDateTime(dr["From Date"]); //oadparamemp.TillDate = Convert.ToDateTime(dr["Till Date"]); if (dr["Amount"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Amount can not be Empty" + " Row : ", nRow, "Amount can not be Empty", oemployee.EmployeeNo, oemployee.Name)); continue; } oadparamemp.MonthlyAmount = dr["Amount"].ToString() != string.Empty ? Convert.ToDouble(dr["Amount"]) : 0.0; oadparamemp.AllowDeductID = (int)_columnDefinition.uploadItemID; //ID.FromInteger(Convert.ToInt32(EnumAllowOrDeduct.Deduction)); var allow = allows.FirstOrDefault(x => x.ID == oadparamemp.AllowDeductID); if (oemployee.GradeID == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Grade.", nRow, "(" + dr["Grade"].ToString() + ")" + "Grade Id not found in the current context", oemployee.EmployeeNo, oemployee.Name)); continue; } List oparamters = oadparameters.FindAll(x => x.AllowDeductID == oadparamemp.AllowDeductID); ADParameter oparamter = new ADParameterService().GetApplicableParameter(oemployee, oemployee.GradeID ?? -1, oadparameters, oadparamemp.AllowDeductID); if (oparamter == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No :" + dr["Employee No"].ToString() + " Row : ", nRow, "Employee applicable parameter not found.", oemployee.EmployeeNo, oemployee.Name)); continue; } if (oparamter.MaxAmount < oadparamemp.MonthlyAmount) oadparamemp.MonthlyAmount = oadparamemp.MonthlyAmount - oparamter.MaxAmount; oadparamemp.ADParameterID = oparamter.ID; oadparamemp.Periodicity = oparamter.Periodicity; //if(oadparamemp.AllowDeductID!=ID.FromInteger(14)) //{ if (oadparamemp.Periodicity == EnumPeriodicity.OneOff) { oadparamemp.FormDate = GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate); oadparamemp.TillDate = ptype.NextPayProcessDate; } else if (oadparamemp.Periodicity == EnumPeriodicity.Monthly && oparamter.EntitleType == EnumEntitleType.Individual) { // from date can't prior to fist date of current month // till date can't be less to from date // from date can't be greater to last date of current month if (dr["From Date"].ToString() == "") { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date Can't be Empty" + " Row : ", nRow, "From date can not be Empty", oemployee.EmployeeNo, oemployee.Name)); continue; } if (dr["From Date"].ToString() != "" && Convert.ToDateTime(dr["From Date"]) < GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate) && allow.AllowOrDeductType != EnumAllowOrDeduct.Allowance) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date :" + dr["From Date"].ToString() + " Row : ", nRow, "From date can not be less than first date of current month", oemployee.EmployeeNo, oemployee.Name)); continue; } if (dr["From Date"].ToString() != "" && Convert.ToDateTime(dr["From Date"]) > GlobalFunctions.LastDateOfMonth(ptype.NextPayProcessDate)) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date :" + dr["From Date"].ToString() + " Row : ", nRow, "From date can not be greater than last date of current month", oemployee.EmployeeNo, oemployee.Name)); continue; } if (dr["Till Date"].ToString() != "" && Convert.ToDateTime(dr["Till Date"]) < Convert.ToDateTime(dr["From Date"])) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Till Date :" + dr["Till Date"].ToString() + " Row : ", nRow, "Till date can not be less than From date", oemployee.EmployeeNo, oemployee.Name)); continue; } oadparamemp.FormDate = dr["From Date"].ToString() != "" ? Convert.ToDateTime(dr["From Date"]) : GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate); if (dr["Till Date"].ToString() != "") oadparamemp.TillDate = Convert.ToDateTime(dr["Till Date"]); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No :" + dr["Employee No"].ToString() + " Row : ", nRow, "Employee applicable parameter is defined greade wise")); continue; } //} oadparamemp.ADEmpType = EnumADEmpType.AppliedToIndividual; oadparamemp.Arreartype = EnumArrearType.NotPresent; oadparamemp.ValueType = EnumValueType.Amount; oadparamemp.CreatedBy = _userID; oadparamemp.ModifiedDate = null; oadparamemp.ModifiedBy = null; oadparamemployees.Add(oadparamemp); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } if (_errorOrSuccessList.Count == 0) { new ADParameterEmployeeService().Save(oadparamemployees, ptype.LastPayProcessDate); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } #endregion #region Taxinvestment public void ImportAitData(DataUploadColumnDefinition _columnDefination) { List employees = new EmployeeService().Get(); SystemInformation sysInfo = new SystemInformationService().Get(); // EmpTaxAit empTaxAit = null; _EmpTaxAitList = new List(); Employee oemployee = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = employees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { EmpTaxAit empTaxAit = new EmpTaxAit(); empTaxAit.EmployeeId = oemployee.ID; empTaxAit.TaxParamId = (int)_columnDefination.uploadItemID; empTaxAit.CheckedDate = DateTime.Today; empTaxAit.CheckedBy = this._userID; empTaxAit.Amount = Convert.ToDouble(dr["Amount"]); _EmpTaxAitList.Add(empTaxAit); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } } if (_errorOrSuccessList.Count == 0) { foreach (EmpTaxAit item in _EmpTaxAitList) { new EmpTaxAitService().Save(item); } } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } public void ImportTaxInvestmentData(DataUploadColumnDefinition _columnDefination, int Type) { List employees = new EmployeeService().Get(); SystemInformation sysInfo = new SystemInformationService().Get(); EmployeeTaxInvestment oEmployeeTaxInvestment = null; _EmployeeTaxInvestments = new List(); Employee oemployee = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = employees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { oEmployeeTaxInvestment = new EmployeeTaxInvestment(); oEmployeeTaxInvestment.EntryFrom = EnumTaxInvestment.Admin; oEmployeeTaxInvestment.submitStatus = EnumTaxInvestmentStatus.Approve; oEmployeeTaxInvestment.EmployeeID = oemployee.ID; oEmployeeTaxInvestment.TypeID = _columnDefination.SelectedItemTwoID; oEmployeeTaxInvestment.TaxparameterId = _columnDefination.SelectedItemOneID; oEmployeeTaxInvestment.Amount = Convert.ToDouble(dr["Amount"]); oEmployeeTaxInvestment.CreatedBy = this._userID; oEmployeeTaxInvestment.CreatedDate = DateTime.Today; _EmployeeTaxInvestments.Add(oEmployeeTaxInvestment); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } } if (_errorOrSuccessList.Count == 0) { new EmployeeTaxInvestmentService().AdminSave(_EmployeeTaxInvestments); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } #endregion #region Import Individual Employee Deductions //public void ImportEmpIndividualDeduction(DataUploadColumnDefinition _columnDefinition) //{ // List oadparamemployees = new List(); // List oemployees = new EmployeeService().Get(); // SystemInformation sysInfo = new SystemInformationService().Get(); // List _adparams = new ADParameterService().Get(EnumStatus.Active, EnumAllowOrDeduct.Deduction, _payrollTypeID); // Employee oemployee = null; // oadparamemployees = new List(); // ADParameterEmployee oadparamemp = null; // int nRow = 0; // try // { // foreach (DataRow dr in _uplodedData.Rows) // { // nRow = nRow + 1; // oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); // if (oemployee != null) // { // oadparamemp = new ADParameterEmployee(); // oadparamemp.EmployeeID = oemployee.ID; // //oadparamemp.FormDate = Convert.ToDateTime(dr["From Date"]); // //oadparamemp.TillDate = Convert.ToDateTime(dr["Till Date"]); // oadparamemp.MonthlyAmount = dr["Amount"].ToString() != string.Empty ? Convert.ToDouble(dr["Amount"]) : 0.0; // oadparamemp.AllowDeductID = _columnDefinition.SelectedItemOneID; //ID.FromInteger(Convert.ToInt32(EnumAllowOrDeduct.Deduction)); // if (oemployee.GradeID == null) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No :" + oemployee.EmployeeNo + " Row : ", nRow, "Employee grade id not found.")); // continue; // } // List oparamters = new ADParameterService().Get(EnumStatus.Active, oadparamemp.AllowDeductID); // ADParameter oparamter = new ADParameterService().GetApplicableParameter(oemployee, oemployee.GradeID ?? -1, oparamters, oadparamemp.AllowDeductID); // if (oparamter == null) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee applicable parameter not found.")); // continue; // } // oadparamemp.ADParameterID = oparamter.ID; // oadparamemp.Periodicity = oparamter.Periodicity; // if (oadparamemp.Periodicity == EnumPeriodicity.OneOff) // { // oadparamemp.FormDate = GlobalFunctions.FirstDateOfMonth(sysInfo.CurrentSysInfo.NextPayProcessDate); // oadparamemp.TillDate = sysInfo.CurrentSysInfo.NextPayProcessDate; // } // else if (oadparamemp.Periodicity == EnumPeriodicity.Monthly && oparamter.EntitleType == EnumEntitleType.Individual) // { // // from date can't prior to fist date of current month // // till date can't be less to from date // // from date can't be greater to last date of current month // if (dr["From Date"].ToString() != "" && Convert.ToDateTime(dr["From Date"]) < GlobalFunctions.FirstDateOfMonth(sysInfo.CurrentSysInfo.NextPayProcessDate)) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date :" + dr["From Date"].ToString() + " Row : ", nRow, "From date can not be less than first date of current month")); // continue; // } // if (dr["From Date"].ToString() != "" && Convert.ToDateTime(dr["From Date"]) > GlobalFunctions.LastDateOfMonth(sysInfo.CurrentSysInfo.NextPayProcessDate)) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date :" + dr["From Date"].ToString() + " Row : ", nRow, "From date can not be greater than last date of current month")); // continue; // } // if (dr["Till Date"].ToString() != "" && Convert.ToDateTime(dr["Till Date"]) < Convert.ToDateTime(dr["From Date"])) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Till Date :" + dr["Till Date"].ToString() + " Row : ", nRow, "Till date can not be less than From date")); // continue; // } // oadparamemp.FormDate = dr["From Date"].ToString() != "" ? Convert.ToDateTime(dr["From Date"]) : GlobalFunctions.FirstDateOfMonth(sysInfo.CurrentSysInfo.NextPayProcessDate); // if (dr["Till Date"].ToString() != "") // oadparamemp.TillDate = Convert.ToDateTime(dr["Till Date"]); // } // else // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No :" + dr["Employee No"].ToString() + " Row : ", nRow, "Employee applicable parameter is defined greade wise")); // continue; // } // oadparamemp.ADEmpType = EnumADEmpType.AppliedToIndividual; // oadparamemp.Arreartype = EnumArrearType.NotPresent; // oadparamemployees.Add(oadparamemp); // } // else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); // } // } // catch (Exception ex) // { // throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); // } //} #endregion #region Import Employee Bank Account Information public void ImportEmpBankAccount(DataUploadColumnDefinition _columnDefinition) { List oemployees = new EmployeeService().GetAllEmps(this._payrollTypeID); Employee oemployee = null; SystemInformation sysInfo = new SystemInformationService().Get(); List obranches = new BranchService().Get(EnumStatus.Regardless, this._payrollTypeID); Branch obranch = null; List oempbankaccounts = new List(); EmployeeBankAccount oempbankaccount = null; PayrollType ptype = new PayrollTypeService().Get(this._payrollTypeID); int nRow = 0; List banks = new BankService().Get(); try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { //if (oemployee.Status != EnumEmployeeStatus.Live) //{ // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee", nRow, "Employee is not Live")); // continue; //} oempbankaccount = new EmployeeBankAccount(); oempbankaccount.EmployeeID = oemployee.ID; Bank obank = banks.Find(delegate (Bank item) { return item.Name == dr["Bank Name"].ToString(); }); if (obank == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Bank Name", nRow, "Bank not found in the existing Banks")); continue; } obranch = obranches.Find(delegate (Branch item) { return item.Name == dr["Branch Name"].ToString() && item.BankID == obank.ID; }); if (obranch != null) { oempbankaccount.BranchID = obranch.ID; } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Branch Name", nRow, "Branch name not found in the existing branches")); oempbankaccount.EffectDate = GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate); oempbankaccount.AccountNo = dr["Account No"].ToString(); oempbankaccounts.Add(oempbankaccount); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } if (_errorOrSuccessList.Count == 0) { new EmployeeBankAccountService().Save(oempbankaccounts); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } #endregion #region Import Exception Data public void ImportException(int uploadId, DataUploadColumnDefinition oColumnDefinition) { _uploadException = new DataUploadException(); _uploadException.UploadException(uploadId, _uplodedData, oColumnDefinition); _errorOrSuccessList = _uploadException.ErrorOrSuccessList; } #endregion //public void SaveEmpBasicInformation(int PayrollTypeID) //{ // try // { // _columndefinfationService = new DataUploadColumnDefinationService(); // _columndefinfationService.Insert(PayrollTypeID); // } // catch (Exception ex) // { // throw new ServiceException(ex.Message); // } //} public void Save(List categorys, List grades, List departments, List locations, List religions, List designations, List banks, List branches, List employees, List oaccessCards, int payrollTypeID, EnumRegularDataUpload uploaid) { bool IsFinantialAprovalRequired = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "finantialaproval", "finantialaprovalrequired"); List segments = new GradeSegmentService().Get(EnumStatus.Regardless); TransactionContext tc = null; _payrollTypeID = payrollTypeID; try { // SubCategoryService.SaveForUpload(tc, subcategorys); if (segments.Count == 0) { GradeSegment osg = new GradeSegment(); osg.Code = "001"; osg.Name = "Default"; osg.CreatedBy = this._userID; osg.CreatedDate = DateTime.Today; GradeSegmentService ogSrv = new GradeSegmentService(); ogSrv.Save(osg); grades.ForEach(x => { x.GradeSegmentID = osg.ID; }); } else { grades.ForEach(x => { x.GradeSegmentID = segments[0].ID; }); } List scategories = new CategoryService().Get(EnumStatus.Regardless, this._payrollTypeID); List sGrades = new GradeService().Get(EnumStatus.Regardless, this._payrollTypeID); List sLocations = new LocationService().Get(EnumStatus.Regardless, this._payrollTypeID); List sdepartments = new DepartmentService().Get(EnumStatus.Regardless, this._payrollTypeID); List sdesignation = new DesignationService().Get(EnumStatus.Regardless, this._payrollTypeID); List sReligions = new ReligionService().Get(EnumStatus.Regardless); List sBanks = new BankService().Get(); List sBrances = new BranchService().Get(EnumStatus.Regardless, this._payrollTypeID); tc = TransactionContext.Begin(true); CategoryService.SaveForUpload(tc, categorys, scategories); GradeService.SaveForUpload(tc, grades, sGrades); LocationService.SaveForUpload(tc, locations, sLocations); ReligionService.SaveForUpload(tc, religions, sReligions); DesignationService.SaveForUpload(tc, designations, payrollTypeID, sdesignation); DepartmentService.SaveForUpload(tc, departments, sdepartments); BankService.SaveForUpload(tc, banks, sBanks); BranchService.SaveForUpload(tc, branches, sBrances); EmployeeService.SaveForUpload(tc, employees, uploaid, IsFinantialAprovalRequired); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } } public void ImportAssingedCard(DataUploadColumnDefinition _columnDefinition, int payrollTypeId) { List ocards = new AccessCardService().Get(); List oemps = new EmployeeService().GetAllEmps(this._payrollTypeID); List newCards = new List(); List ops = new List(); Employee oemployee = null; CardOperation oCardOperation = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemps.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { if (dr["Employee No"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee No not found in the current context")); continue; } else { string cardNumber = dr["Card No"].ToString(); AccessCard onewCard = ocards.FirstOrDefault(x => x.CardNumber == cardNumber); if (onewCard == null) { onewCard = new AccessCard(); onewCard.CardNumber = cardNumber; onewCard.TypeID = 1; onewCard.Status = EnumCardStatus.Free; newCards.Add(onewCard); } else { var cardemp = oemps.FirstOrDefault(x => x.CardID == onewCard.ID); if (cardemp != null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + cardemp.EmployeeNo + ")" + "Employee No assinged to this card" + " " + cardNumber)); continue; } if (onewCard.Status != EnumCardStatus.Free) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Card No", nRow, "(" + onewCard.CardNumber + ")" + " is already assigned to emplolyees" + " " + cardNumber)); continue; } } CardOperation op = new CardOperation(); op.CardNumber = cardNumber; op.EmployeeID = oemployee.ID; op.Employee = oemployee; op.AccessCard = onewCard; op.AssignDate = Convert.ToDateTime(dr["Assign Date"].ToString()); ops.Add(op); } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } if (this._errorOrSuccessList.Count == 0) { new CardOperationService().Save(ops, payrollTypeId); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void SaveLifeCycle(List categorys, List grades, List departments, List locations, List religions, List designations, List crgs, List lifecycles, int payrollTypeID) { TransactionContext tc = null; _payrollTypeID = payrollTypeID; PayrollType optyp = new PayrollTypeService().Get(_payrollTypeID); try { // SubCategoryService.SaveForUpload(tc, subcategorys); if (grades != null) { List segments = new GradeSegmentService().Get(EnumStatus.Regardless); if (segments.Count == 0) { GradeSegment osg = new GradeSegment(); osg.Code = "001"; osg.Name = "Default"; osg.CreatedBy = this._userID; osg.CreatedDate = DateTime.Today; GradeSegmentService ogSrv = new GradeSegmentService(); ogSrv.Save(osg); grades.ForEach(x => { x.GradeSegmentID = osg.ID; }); } else { grades.ForEach(x => { x.GradeSegmentID = segments[0].ID; }); } } List sGrades = null; if (grades != null) sGrades = new GradeService().Get(EnumStatus.Regardless, _payrollTypeID); List sLocations = null; if (locations != null) sLocations = new LocationService().Get(EnumStatus.Regardless, _payrollTypeID); List sdepartments = null; if (departments != null) sdepartments = new DepartmentService().Get(EnumStatus.Regardless, _payrollTypeID); List sdesignation = null; if (designations != null) sdesignation = new DesignationService().Get(EnumStatus.Regardless, _payrollTypeID); List scostcenters = null; if (crgs != null) scostcenters = new CostcenterService().Get(EnumStatus.Regardless, _payrollTypeID); tc = TransactionContext.Begin(true); if (grades != null) GradeService.SaveForUpload(tc, grades, sGrades); if (locations != null) LocationService.SaveForUpload(tc, locations, sLocations); if (designations != null) DesignationService.SaveForUpload(tc, designations, payrollTypeID, sdesignation); if (departments != null) DepartmentService.SaveForUpload(tc, departments, sdepartments); if (crgs != null) CostcenterService.SaveForUpload(tc, crgs, scostcenters); foreach (EmpLifeCycle item in lifecycles) { item.SalaryMonth = optyp.NextPayProcessDate; if ((item.BasicSalary != null || item.GrossSalary != null) || (item.BasicSalary != 0 || item.GrossSalary != 0) && (item.GradeID != null)) { EmployeeGradeSalary ogs = new EmployeeGradeSalary(); ogs.BasicSalary = (item.BasicSalary == null) ? 0 : (double)item.BasicSalary; ogs.GrossSalary = (item.GrossSalary == null) ? 0 : (double)item.GrossSalary; if (item.GradeID == null) { //if (item.GradeID == null) //{ // throw new Exception("Grade not yet assigned to employee."); //} ogs.GradeID = (int)item.Employee.GradeID; ogs.Increment = item.IncrementNo; //ogs.PayScaleDetailID = cbcGrade.SelectedSlab.ID; } else { ogs.GradeID = (int)item.GradeID; ogs.Increment = item.IncrementNo; //ogs.PayScaleDetailID = cbcGrade.SelectedSlab.ID; } if (ogs.GrossSalary != 0 && ogs.BasicSalary == 0) { if (grades == null) { grades = new List(); grades.Add(new GradeService().Get(ogs.GradeID)); } Grade oGrade = grades.FirstOrDefault(x => x.ID == ogs.GradeID); if (oGrade == null) { oGrade = new GradeService().Get(ogs.GradeID); grades.Add(oGrade); } if (oGrade == null) throw new Exception("Calculating Basic Salary From Gross where Grade not found."); if (oGrade.BasicPercentOfGross == 0) throw new Exception(@"Calculating Basic Salary From Gross where Basic-%-Gross is Zero, Please set it from Grade Master-Data."); ogs.BasicSalary = ogs.GrossSalary * oGrade.BasicPercentOfGross / 100; item.BasicSalary = ogs.BasicSalary; } if (ogs.BasicSalary + ogs.GrossSalary == 0) { if (item.BasicSalary + item.GrossSalary == 0) { throw new Exception("Salary(HRBasic/Gross) can\'t be zero."); } else { if (item.BasicSalary != null) ogs.BasicSalary = (double)item.BasicSalary; else ogs.BasicSalary = item.Employee.BasicSalary; if (item.GrossSalary != null) ogs.GrossSalary = (double)item.GrossSalary; else ogs.GrossSalary = item.Employee.GrossSalary; } } // ogs.increment = Convert.ToInt16(numIncrement.Value); ogs.EmployeeID = item.EmployeeID; ogs.GradeSalaryTypeID = (int)item.StatusDetailID; ogs.EffectDate = item.EffectDate; item.EmployeeGradeSalary = ogs; } new EmpLifeCycleService().Save(tc, item, optyp.NextPayProcessDate, _payrollTypeID); } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } } public void Save2(List departments, List employees) { TransactionContext tc = null; try { tc = TransactionContext.Begin(true); //DepartmentService.SaveForUpload(tc, departments); //EmployeeService.SaveDepartment(tc, employees); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } } public void ImportTaxDataInfo(DataUploadColumnDefinition columnDefinition) { PayrollType ptype = new PayrollTypeService().Get(this._payrollTypeID); columnDefinition.uploadItemID = ptype.TaxParamID; List oTaxMergeMasters = new List(); oTaxMergeMasters = new TaxMergeMasterService().GetbyTaxParameter((int)columnDefinition.uploadItemID, this._payrollTypeID); Employee oemployee = null; IncomeTax oIncomeTax = null; TaxMergeMaster oTaxMergeMaster = null; List employees = new EmployeeService().GetAllEmps(); List processItems = new ProcessItemService().Get(); List incomeTaxs = new List(); #region Refresh Objects int nRow = 0; List savedData = new IncomeTaxService().Get(EnumIncomeTaxDataFrom.ProcessTempData, this._payrollTypeID); try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = employees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee Code"].ToString(); });//Employee.Get(dr["Employee Code"].ToString()); if (oemployee == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Code", nRow, "Employee Code not found: " + dr["Employee Code"].ToString())); continue; } for (int i = 1; i < _uplodedData.Columns.Count; i++) { oIncomeTax = new IncomeTax(); oTaxMergeMaster = oTaxMergeMasters.Find(delegate (TaxMergeMaster taxMerge) { return taxMerge.Description == _uplodedData.Columns[i].ColumnName; }); if (oTaxMergeMaster == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(_uplodedData.Columns[i].ColumnName, nRow, _uplodedData.Columns[i].ColumnName + " not found in the tax head groping", oemployee.EmployeeNo, oemployee.Name)); continue; } ProcessItem pitem = processItems.Find(delegate (ProcessItem item) { return item.ItemCode == (int)oTaxMergeMaster.ItemGroup; }); if (pitem == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(_uplodedData.Columns[i].ColumnName, nRow, " Tax process item code not found in the process collection; Item Code:" + oTaxMergeMaster.ItemGroup.ToString(), oemployee.EmployeeNo, oemployee.Name)); continue; } if (oTaxMergeMaster != null) { oIncomeTax.EmployeeID = oemployee.ID; double nAmount = 0; if (double.TryParse(dr[_uplodedData.Columns[i].ColumnName].ToString(), out nAmount) == false) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(_uplodedData.Columns[i].ColumnName, nRow, _uplodedData.Columns[i].ColumnName + " contains Invalid value:" + dr[_uplodedData.Columns[i].ColumnName].ToString(), oemployee.EmployeeNo, oemployee.Name)); continue; } oIncomeTax = incomeTaxs.FirstOrDefault(x => x.EmployeeID == oemployee.ID && x.ItemGroup == oTaxMergeMaster.ItemGroup && x.ItemID == oTaxMergeMaster.ItemID); if (oIncomeTax == null) oIncomeTax = new IncomeTax(); oIncomeTax.EmployeeID = oemployee.ID; oIncomeTax.ItemGroup = oTaxMergeMaster.ItemGroup; oIncomeTax.ItemID = oTaxMergeMaster.ItemID; oIncomeTax.PreviousAmount = oIncomeTax.PreviousAmount + nAmount; oIncomeTax.Description = oTaxMergeMaster.Description; oIncomeTax.Side = (EnumIncomeTaxSide)pitem.ItemGroup; oIncomeTax.Position = pitem.Position; if (oIncomeTax.PreviousAmount != 0) incomeTaxs.Add(oIncomeTax); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(_uplodedData.Columns[i].ColumnName, nRow, "Column not found in tax setup", oemployee.EmployeeNo, oemployee.Name)); } } if (_errorOrSuccessList.Count == 0) new IncomeTaxService().Save(incomeTaxs, EnumIncomeTaxDataFrom.ProcessTempData); } catch (Exception ex) { throw new ServiceException("Error occered on row:" + nRow + " Reason:" + ex.Message); } #endregion } #region Import Life-Cycle public void importLifeCycle(DataUploadColumnDefinition _columnDefinition) { EmployeeStatus ostatus = new EmployeeStatusService().Get((int)_columnDefinition.uploadItemID); List _oemployees = new EmployeeService().GetAllEmps(this._payrollTypeID); _employeesForSave = new List(); List lifeCycles = new List(); List depts = null; List grades = null; List designations = null; List locations = null; List crgs = null; Employee oemployee = null; int nRow = 0; int nIndex = 0; List deptConfig = new SystemConfigarationService().GetAllChildrenByParentNode(EnumConfigurationType.Logic, "department"); List locConfig = new SystemConfigarationService().GetAllChildrenByParentNode(EnumConfigurationType.Logic, "location"); List crgConfig = new SystemConfigarationService().GetAllChildrenByParentNode(EnumConfigurationType.Logic, "costcenter"); bool isCategoryCodeAutoGen = Convert.ToBoolean(new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "category", "codeautogenerate")); bool isGradeCodeAutoGen = Convert.ToBoolean(new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "codeautogenerate")); bool isDeptCodeAutoGen = Convert.ToBoolean(new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "department", "codeautogenerate")); bool islocCodeAutoGen = Convert.ToBoolean(new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "location", "codeautogenerate")); bool isreligionCodeAutoGen = Convert.ToBoolean(new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "religion", "codeautogenerate")); bool isdesignationCodeAutoGen = Convert.ToBoolean(new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "designation", "codeautogenerate")); bool isCostcenterAutoGen = Convert.ToBoolean(new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "costcenter", "codeautogenerate")); int departmentid = new MiscellaneousService().GetNextID("Department", "DepartmentID", ""); int gradeid = new MiscellaneousService().GetNextID("Grades", "Gradeid", ""); int locationid = new MiscellaneousService().GetNextID("location", "locationid", ""); int designationid = new MiscellaneousService().GetNextID("Designation", "DesignationID", ""); int costcenterid = new MiscellaneousService().GetNextID("crg", "crgid", ""); string description = ""; try { foreach (DataRow dr in _uplodedData.Rows) { description = ""; EmpLifeCycle lifeCycle = new EmpLifeCycle(); lifeCycle.HREmployee = new HREmployee(); lifeCycle.EmpStatusObject = ostatus; nRow = nRow + 1; oemployee = _oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { lifeCycle.Employee = oemployee; lifeCycle.EmployeeID = oemployee.ID; lifeCycle.HREmployee.Gender = oemployee.Gender; lifeCycle.HREmployee.MaritalStatus = oemployee.MaritalStatus; lifeCycle.HREmployee.BloodGroup = EnumBloodGroup.None; // default value; lifeCycle.HREmployee.ReligionID = oemployee.ReligionID; lifeCycle.HREmployee.FunctionID = null; lifeCycle.HREmployee.CompanyID = null; lifeCycle.HREmployee.Status = EnumEmployeeStatus.Live; lifeCycle.HREmployee.CategoryID = oemployee.CategoryID; lifeCycle.EffectDate = Convert.ToDateTime(dr["EffectDate"]); lifeCycle.CreatedBy = this._userID; lifeCycle.CreatedDate = DateTime.Today; description = ostatus.Description + " :"; foreach (EmployeeStatus.EmpStatusComponent comp in ostatus.EmployeeStatusComponents) { lifeCycle.StatusDetailID = ostatus.ID; switch (comp.ComponentType) { case EnumLifeCycleComponent.Category: break; case EnumLifeCycleComponent.Department: if (depts == null) { depts = new DepartmentService().Get(EnumStatus.Regardless, this._payrollTypeID); } if (lifeCycle.Employee.DepartmentID != null) description = description + depts.Find(x => x.ID == lifeCycle.Employee.DepartmentID).Name; nIndex = 0; #region Department int nparentid = 0; nIndex = 0; var dtires = deptConfig.FindAll(x => x.Node == "text"); foreach (SystemConfigaration oconfig in dtires) { //string sValue = oconfig.ConAttributes.GetAttributeValue("tier"); //if (sValue == "") continue; nIndex = nIndex + 1; if (dr[oconfig.Value + " Name"].ToString() == "") continue; Department odepartment = null; if (isDeptCodeAutoGen == false) { if (nIndex > 1) odepartment = depts.Find(delegate (Department item) { return item.Code == dr[oconfig.Value + " Code"].ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; }); else odepartment = depts.Find(delegate (Department item) { return item.Code == dr[oconfig.Value + " Code"].ToString().Trim() && item.Tier == nIndex; }); } else { if (nIndex > 1) odepartment = depts.Find(delegate (Department item) { return item.Name == dr[oconfig.Value + " Name"].ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; }); else odepartment = depts.Find(delegate (Department item) { return item.Name == dr[oconfig.Value + " Name"].ToString().Trim() && item.Tier == nIndex; }); } if (odepartment == null) { odepartment = new Department(); odepartment.Name = dr[oconfig.Value + " Name"].ToString().Trim(); odepartment.Tier = nIndex; odepartment.Status = EnumStatus.Active; odepartment.CreatedBy = this._userID; odepartment.PayrollTypeID = this._payrollTypeID; if (isDeptCodeAutoGen == false) { odepartment.Code = dr[oconfig.Value + " Code"].ToString().Trim(); if (odepartment.Code == "") _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(oconfig.Value + " Code", nRow, oconfig.Value + " Code can't be empty")); } if (nIndex > 1) odepartment.ParentID = (nparentid); departmentid = departmentid + 1; nparentid = departmentid; oemployee.DepartmentID = (departmentid); lifeCycle.HREmployee.DepartmentID = departmentid; lifeCycle.DepartmentID = departmentid; odepartment.SetObjectID(departmentid); depts.Add(odepartment); } else { nparentid = odepartment.ID; oemployee.DepartmentID = odepartment.ID; lifeCycle.DepartmentID = odepartment.ID; lifeCycle.HREmployee.DepartmentID = odepartment.ID; odepartment.ModifiedBy = this._userID; } } description = " To " + description + depts.Find(x => x.ID == lifeCycle.Employee.DepartmentID).Name; #endregion break; case EnumLifeCycleComponent.Position_With_Properties: break; case EnumLifeCycleComponent.Designation: #region Designation upload if (designations == null) designations = new DesignationService().Get(EnumStatus.Regardless, this._payrollTypeID); if (lifeCycle.Employee.DesignationID != null) { var desItem = designations.Find(x => x.ID == lifeCycle.Employee.DesignationID); if (desItem != null) description = description + desItem.Name; } Designation odesignation = null; if (isdesignationCodeAutoGen == false) odesignation = designations.Find(delegate (Designation item) { return item.Code == dr["Designation Code"].ToString().Trim(); }); else odesignation = designations.Find(delegate (Designation item) { return item.Name == dr["Designation Name"].ToString().Trim(); }); if (odesignation == null) { odesignation = new Designation(); odesignation.Name = dr["Designation Name"].ToString().Trim(); if (isdesignationCodeAutoGen == false) odesignation.Code = dr["Designation Code"].ToString().Trim(); designationid = designationid + 1; oemployee.DesignationID = (designationid); lifeCycle.DesignationID = designationid; odesignation.SetObjectID(designationid); odesignation.Status = EnumStatus.Active; odesignation.CreatedBy = this._userID; odesignation.PayrollTypeID = this._payrollTypeID; lifeCycle.HREmployee.DesignationID = designationid; designations.Add(odesignation); } else { oemployee.DesignationID = odesignation.ID; lifeCycle.DesignationID = odesignation.ID; lifeCycle.HREmployee.DesignationID = odesignation.ID; odesignation.ModifiedBy = this._userID; } description = description + " To " + designations.Find(x => x.ID == lifeCycle.Employee.DesignationID).Name; #endregion Designation upload break; case EnumLifeCycleComponent.Grade: if (grades == null) grades = new GradeService().Get(EnumStatus.Regardless, this._payrollTypeID); if (lifeCycle.Employee.GradeID != null) { var gradeItem = grades.Find(x => x.ID == lifeCycle.Employee.GradeID); if (gradeItem != null) description = description + " Grade: " + gradeItem.Name; } Grade ograde = null; if (isGradeCodeAutoGen == false) ograde = grades.Find(delegate (Grade item) { return item.Code == dr["Grade Code"].ToString(); }); else ograde = grades.Find(delegate (Grade item) { return item.Name == dr["Grade Name"].ToString(); }); if (ograde == null) { ograde = new Grade(); ograde.Status = EnumStatus.Active; ograde.GradeSegmentID = (1); ograde.HasPayscale = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "payscaleapplicable "); ograde.HasGrossConcept = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "grossapplicable"); ograde.Name = dr["Grade Name"].ToString().Trim(); if (isGradeCodeAutoGen == false) ograde.Code = dr["Grade Code"].ToString().Trim(); gradeid = gradeid + 1; oemployee.GradeID = (gradeid); lifeCycle.HREmployee.GradeID = gradeid; lifeCycle.GradeID = gradeid; ograde.SetObjectID(gradeid); ograde.CreatedBy = this._userID; ograde.PayrollTypeID = this._payrollTypeID; grades.Add(ograde); if (new GradeSegmentService().Get(ograde.Code) != null) _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Grade", nRow, "Grade already exist in other payroll type.")); } else { oemployee.GradeID = ograde.ID; lifeCycle.GradeID = ograde.ID; ograde.ModifiedBy = this._userID; lifeCycle.HREmployee.GradeID = ograde.ID; } description = description + " To " + grades.Find(x => x.ID == lifeCycle.Employee.GradeID).Name; break; case EnumLifeCycleComponent.Location: #region Location if (locations == null) locations = new LocationService().Get(EnumStatus.Regardless, this._payrollTypeID); if (lifeCycle.Employee.LocationID != null) { var locItem = locations.Find(x => x.ID == lifeCycle.Employee.LocationID); if (locItem != null) description = description + locItem.Name; } nparentid = 0; nIndex = 0; var ltires = locConfig.FindAll(x => x.Node == "text"); foreach (SystemConfigaration oconfig in ltires) { //string sValue = oconfig.ConAttributes.GetAttributeValue("tier"); //if (sValue == "") continue; nIndex = nIndex + 1; if (dr[oconfig.Value + " Name"].ToString() == "") continue; Location olocation = null; if (islocCodeAutoGen == false) { if (nIndex > 1) { olocation = locations.Find(delegate (Location item) { return item.Code == dr[oconfig.Value + " Code"].ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; }); } else { olocation = locations.Find(delegate (Location item) { return item.Code == dr[oconfig.Value + " Code"].ToString().Trim() && item.Tier == nIndex; }); } } else { if (nIndex > 1) { olocation = locations.Find(delegate (Location item) { return item.Name == dr[oconfig.Value + " Name"].ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; }); } else { olocation = locations.Find(delegate (Location item) { return item.Name == dr[oconfig.Value + " Name"].ToString().Trim() && item.Tier == nIndex; }); } } if (olocation == null) { olocation = new Location(); olocation.Name = dr[oconfig.Value + " Name"].ToString().Trim(); olocation.Tier = nIndex; olocation.Status = EnumStatus.Active; if (olocation.Name == "") _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(oconfig.Value + " Name", nRow, oconfig.Value + " Name can't be empty")); if (islocCodeAutoGen == false) { olocation.Code = dr[oconfig.Value + " Code"].ToString().Trim(); if (olocation.Code == "") _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(oconfig.Value + " Code", nRow, oconfig.Value + " Code can't be empty")); } if (nIndex > 1) olocation.ParentID = (nparentid); locationid = locationid + 1; nparentid = locationid; oemployee.LocationID = (locationid); lifeCycle.LocationID = locationid; lifeCycle.HREmployee.LocationID = locationid; olocation.SetObjectID(locationid); olocation.PayrollTypeID = this._payrollTypeID; olocation.CreatedBy = this._userID; locations.Add(olocation); } else { nparentid = olocation.ID; oemployee.LocationID = olocation.ID; olocation.ModifiedBy = this._userID; lifeCycle.HREmployee.LocationID = olocation.ID; } } description = description + " To " + locations.Find(x => x.ID == lifeCycle.Employee.LocationID).Name; #endregion break; case EnumLifeCycleComponent.Basic_salary: if (dr["Basic Salary"].ToString() == "") _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Basic Salary can't be Empty")); if (lifeCycle.Employee.BasicSalary != 0) description = description + " Basic Salary " + lifeCycle.Employee.BasicSalary.ToString(); lifeCycle.BasicSalary = Convert.ToDouble(dr["Basic Salary"].ToString()); lifeCycle.Employee.BasicSalary = (double)lifeCycle.BasicSalary; description = description + " To " + lifeCycle.Employee.BasicSalary.ToString(); break; case EnumLifeCycleComponent.PF_Member: lifeCycle.PFMemberType = EnumPFMembershipType.Live; lifeCycle.Employee.PFMemberType = EnumPFMembershipType.Live; lifeCycle.HREmployee.PFMemberType = EnumPFMembershipType.Live; lifeCycle.Employee.PFMemberShiptDate = lifeCycle.EffectDate; break; case EnumLifeCycleComponent.Continue: lifeCycle.EmployeeStatus = EnumEmployeeStatus.Live; lifeCycle.IsContinue = true; lifeCycle.Employee.Status = EnumEmployeeStatus.Live; lifeCycle.HREmployee.Status = EnumEmployeeStatus.Live; lifeCycle.Employee.DiscontinueDate = lifeCycle.EffectDate; lifeCycle.Employee.EndOfContractDate = lifeCycle.EffectDate; break; case EnumLifeCycleComponent.Confirm: lifeCycle.IsConfirm = true; lifeCycle.Employee.IsConfirmed = true; lifeCycle.HREmployee.IsConfirmed = true; lifeCycle.Employee.ConfirDate = lifeCycle.EffectDate; break; case EnumLifeCycleComponent.Discontinue: lifeCycle.IsDiscontinue = true; lifeCycle.EmployeeStatus = EnumEmployeeStatus.Discontinued; lifeCycle.Employee.Status = EnumEmployeeStatus.Discontinued; lifeCycle.HREmployee.Status = EnumEmployeeStatus.Discontinued; lifeCycle.Employee.DiscontinueDate = lifeCycle.EffectDate; lifeCycle.Employee.EndOfContractDate = lifeCycle.EffectDate; break; case EnumLifeCycleComponent.Function: break; case EnumLifeCycleComponent.Company: break; case EnumLifeCycleComponent.Gross_salary: if (dr["Gross Salary"].ToString() == "") _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Basic Salary can't be Empty")); if (lifeCycle.Employee.GrossSalary != 0) description = description + " Gross Salary : " + lifeCycle.Employee.GrossSalary.ToString(); lifeCycle.GrossSalary = Convert.ToDouble(dr["Gross Salary"].ToString()); lifeCycle.Employee.GrossSalary = (double)lifeCycle.GrossSalary; description = description + " To " + lifeCycle.Employee.GrossSalary.ToString(); break; case EnumLifeCycleComponent.Cost_Center: #region Location if (crgs == null) crgs = new CostcenterService().Get(EnumStatus.Regardless, this._payrollTypeID); if (lifeCycle.Employee.CrgId != null) description = description + crgs.Find(x => x.ID == lifeCycle.Employee.CrgId).Name; nparentid = 0; nIndex = 0; var ctires = crgConfig.FindAll(x => x.Node == "text"); foreach (SystemConfigaration oconfig in ctires) { //string sValue = oconfig.ConAttributes.GetAttributeValue("tier"); //if (sValue == "") continue; nIndex = nIndex + 1; if (dr[oconfig.Value + " Name"].ToString() == "") continue; Costcenter crg = null; if (isCostcenterAutoGen == false) { if (nIndex > 1) { crg = crgs.Find(delegate (Costcenter item) { return item.Code == dr[oconfig.Value + " Code"].ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; }); } else { crg = crgs.Find(delegate (Costcenter item) { return item.Code == dr[oconfig.Value + " Code"].ToString().Trim() && item.Tier == nIndex; }); } } else { if (nIndex > 1) { crg = crgs.Find(delegate (Costcenter item) { return item.Name == dr[oconfig.Value + " Name"].ToString().Trim() && item.Tier == nIndex && item.ParentID == nparentid; }); } else { crg = crgs.Find(delegate (Costcenter item) { return item.Name == dr[oconfig.Value + " Name"].ToString().Trim() && item.Tier == nIndex; }); } } if (crg == null) { crg = new Costcenter(); crg.Name = dr[oconfig.Value + " Name"].ToString().Trim(); crg.Tier = nIndex; crg.Status = EnumStatus.Active; if (crg.Name == "") _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(oconfig.Value + " Name", nRow, oconfig.Value + " Name can't be empty")); if (isCostcenterAutoGen == false) { crg.Code = dr[oconfig.Value + " Code"].ToString().Trim(); if (crg.Code == "") _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(oconfig.Value + " Code", nRow, oconfig.Value + " Code can't be empty")); } if (nIndex > 1) crg.ParentID = (nparentid); costcenterid = costcenterid + 1; nparentid = costcenterid; lifeCycle.CostCenterID = costcenterid; lifeCycle.Employee.CrgId = costcenterid; crg.SetObjectID(costcenterid); crg.PayrollTypeID = this._payrollTypeID; crg.CreatedBy = this._userID; crgs.Add(crg); } else { nparentid = crg.ID; lifeCycle.CostCenterID = crg.ID; lifeCycle.Employee.CrgId = crg.ID; crg.ModifiedBy = this._userID; } } description = description + " To " + crgs.Find(x => x.ID == lifeCycle.Employee.CrgId).Name; #endregion break; case EnumLifeCycleComponent.Position_Without_Properties: break; case EnumLifeCycleComponent.Force_Remove_From_Position: break; case EnumLifeCycleComponent.Role: break; case EnumLifeCycleComponent.IA: break; default: break; } } if (lifeCycle.EffectDate.Date < DateTime.Today) { lifeCycle.IsProcessed = null; lifeCycle.ProcessDate = null; } else { lifeCycle.IsProcessed = false; } lifeCycle.Description = description; _employeesForSave.Add(oemployee); lifeCycles.Add(lifeCycle); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found in the Employee List")); } if (_errorOrSuccessList.Count == 0) { this.SaveLifeCycle(null, grades, depts, locations, null, designations, crgs, lifeCycles, this._payrollTypeID); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } #endregion private void ImportOPIDataNew(DataUploadColumnDefinition _columnDefinition) { List oemployees = new EmployeeService().GetAllEmps(); ADParameter _adparam = null; Employee oemployee = null; List _oPIParameterIndividual = new List(); OpiParameterIndividual oopiParamIndividual = null; List oparamters = new OpiParameterService().Get(EnumStatus.Active, this._payrollTypeID); PayrollType ptype = new PayrollTypeService().Get(this._payrollTypeID); int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { oopiParamIndividual = new OpiParameterIndividual(); oopiParamIndividual.EmployeeId = oemployee.ID; //oadparamemp.FormDate = Convert.ToDateTime(dr["From Date"]); //oadparamemp.TillDate = Convert.ToDateTime(dr["Till Date"]); oopiParamIndividual.Value = dr["Amount"].ToString() != string.Empty ? Convert.ToDouble(dr["Amount"]) : 0.0; oopiParamIndividual.OpiItemId = _columnDefinition.SelectedItemOneID; //ID.FromInteger(Convert.ToInt32(EnumAllowOrDeduct.Deduction)); if (oemployee.GradeID == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No :" + oemployee.EmployeeNo + " Row : ", nRow, "Employee grade id not found.")); continue; } List opiAppParams = new OpiParameterService().GetApplicableParameters( oemployee, (int)oemployee.GradeID, oparamters); OpiParameter opiAppParam = opiAppParams.FirstOrDefault(o => o.OpiItemID == oopiParamIndividual.OpiItemId); if (opiAppParam == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee applicable parameter not found.")); continue; } oopiParamIndividual.PayrollTypeID = this._payrollTypeID; oopiParamIndividual.ArrearType = EnumArrearType.ToCalculate; oopiParamIndividual.OpiParameterID = opiAppParam.ID; oopiParamIndividual.OpiPeriodicity = opiAppParam.OpiPeriodicity; oopiParamIndividual.IndividualType = EnumOPIIndivdualType.AppliedToIndividual; if (oopiParamIndividual.OpiPeriodicity == EnumOpiPeriodicity.OnceOff) { oopiParamIndividual.FromDate = GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate); oopiParamIndividual.ToDate = ptype.NextPayProcessDate; } else if (oopiParamIndividual.OpiPeriodicity == EnumOpiPeriodicity.Monthly && opiAppParam.EntitleType == EnumEntitleType.Individual) { // from date can't prior to fist date of current month // till date can't be less to from date // from date can't be greater to last date of current month if (dr["From Date"].ToString() != "" && Convert.ToDateTime(dr["From Date"]) < GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate)) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date :" + dr["From Date"].ToString() + " Row : ", nRow, "From date can not be less than first date of current month")); continue; } if (dr["From Date"].ToString() != "" && Convert.ToDateTime(dr["From Date"]) > GlobalFunctions.LastDateOfMonth(ptype.NextPayProcessDate)) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("From Date :" + dr["From Date"].ToString() + " Row : ", nRow, "From date can not be greater than last date of current month")); continue; } if (dr["Till Date"].ToString() != "" && Convert.ToDateTime(dr["Till Date"]) < Convert.ToDateTime(dr["From Date"])) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Till Date :" + dr["Till Date"].ToString() + " Row : ", nRow, "Till date can not be less than From date")); continue; } oopiParamIndividual.FromDate = dr["From Date"].ToString() != "" ? Convert.ToDateTime(dr["From Date"]) : GlobalFunctions.FirstDateOfMonth(ptype.NextPayProcessDate); if (dr["Till Date"].ToString() != "") oopiParamIndividual.ToDate = Convert.ToDateTime(dr["Till Date"]); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No :" + dr["Employee No"].ToString() + " Row : ", nRow, "Employee applicable parameter is defined greade wise")); continue; } oopiParamIndividual.ValueType = EnumValueType.Amount; _oPIParameterIndividual.Add(oopiParamIndividual); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } if (_errorOrSuccessList.Count == 0) { new OpiParameterIndividualService().BulkSave(_oPIParameterIndividual); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } #region Import LineManager public void ImportLineManager(DataUploadColumnDefinition _columnDefinition) { List _oemployees = new EmployeeService().GetAllEmps(); _employeesForSave = new List(); Employee oemployee = null; Employee lineManager = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = _oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { if (dr["Line Manager"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Line Manager", nRow, "(" + dr["Line Manager"].ToString() + ")" + "Line Manager not found in the current context")); continue; } lineManager = _oemployees.Where(o => o.EmployeeNo == dr["Line Manager"].ToString().Trim()).FirstOrDefault(); if (lineManager == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Line Manager", nRow, "(" + dr["Line Manager"].ToString() + ")" + "Line Manager is not found in Employee List.")); continue; } oemployee.LineManagerID = lineManager.ID; if (dr["Second Line Manager"].ToString() != string.Empty) { lineManager = _oemployees.Where(o => o.EmployeeNo == dr["Second Line Manager"].ToString().Trim()).FirstOrDefault(); if (lineManager == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Second Line Manager.", nRow, "(" + dr["Second Line Manager"].ToString() + ")" + "Second Line Manager is not found in Employee List.")); continue; } oemployee.SecondLineManagerID = lineManager.ID; } _employeesForSave.Add(oemployee); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found in the Employee List")); } if (_errorOrSuccessList.Count == 0) { new EmployeeService().UpdateLM2(_employeesForSave); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } #endregion #region Import PF public void ImportPFOpening(DataUploadColumnDefinition _columnDefinition) { List _oemployees = new EmployeeService().GetAllEmps(); _PFTransactions = new List(); Employee oemployee = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = _oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { DateTime monthDate = DateTime.MinValue; if (dr["Date"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Date", nRow, "(" + dr["Employee No"].ToString() + ")" + "Date not found.")); continue; } else { monthDate = Convert.ToDateTime(dr["Date"].ToString()).LastDateOfMonth(); } if (dr["Own Contribution"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Own Contribution", nRow, "(" + dr["Employee No"].ToString() + ")" + "Own Contribution not found.")); continue; } else { PFTransaction pFTransaction = new PFTransaction(); pFTransaction.EmployeeID = oemployee.ID; pFTransaction.TranType = EnumPFTranType.OpeningPFAmount; pFTransaction.TranAmount = Convert.ToDouble(dr["Own Contribution"].ToString()); pFTransaction.MonthDate = monthDate; _PFTransactions.Add(pFTransaction); } if (dr["Company Contribution"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Company Contribution", nRow, "(" + dr["Employee No"].ToString() + ")" + "Company Contribution not found.")); continue; } else { PFTransaction pFTransaction = new PFTransaction(); pFTransaction.EmployeeID = oemployee.ID; pFTransaction.TranType = EnumPFTranType.OpeningCPFAmount; pFTransaction.TranAmount = Convert.ToDouble(dr["Own Contribution"].ToString()); pFTransaction.MonthDate = monthDate; _PFTransactions.Add(pFTransaction); } if (dr["Own Interest"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Own Interest", nRow, "(" + dr["Employee No"].ToString() + ")" + "Own Interest not found.")); continue; } else { PFTransaction pFTransaction = new PFTransaction(); pFTransaction.EmployeeID = oemployee.ID; pFTransaction.TranType = EnumPFTranType.OpeningOwnInt; pFTransaction.TranAmount = Convert.ToDouble(dr["Own Contribution"].ToString()); pFTransaction.MonthDate = monthDate; _PFTransactions.Add(pFTransaction); } if (dr["Company Interest"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Company Interest", nRow, "(" + dr["Employee No"].ToString() + ")" + "Company Interest not found.")); continue; } else { PFTransaction pFTransaction = new PFTransaction(); pFTransaction.EmployeeID = oemployee.ID; pFTransaction.TranType = EnumPFTranType.OpeningCompInt; pFTransaction.TranAmount = Convert.ToDouble(dr["Own Contribution"].ToString()); pFTransaction.MonthDate = monthDate; _PFTransactions.Add(pFTransaction); } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found in the Employee List")); } if (_errorOrSuccessList.Count == 0) { new PFTransactionService().SaveAll(_PFTransactions); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } public void ImportPFYearlyInterest(DataUploadColumnDefinition _columnDefinition) { List _oemployees = new EmployeeService().GetAllEmps(); _PFTransactions = new List(); Employee oemployee = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = _oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { DateTime monthDate = DateTime.MinValue; if (dr["Date"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Date", nRow, "(" + dr["Employee No"].ToString() + ")" + "Date not found.")); continue; } else { monthDate = Convert.ToDateTime(dr["Date"].ToString()).LastDateOfMonth(); } if (dr["Own Yearly Interest"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Own Yearly Interest", nRow, "(" + dr["Employee No"].ToString() + ")" + "Own Yearly Interest not found.")); continue; } else { PFTransaction pFTransaction = new PFTransaction(); pFTransaction.EmployeeID = oemployee.ID; pFTransaction.TranType = EnumPFTranType.OwnYearlyInt; pFTransaction.TranAmount = Convert.ToDouble(dr["Own Yearly Interest"].ToString()); pFTransaction.MonthDate = monthDate; _PFTransactions.Add(pFTransaction); } if (dr["Company Yearly Interest"].ToString() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Company Yearly Interest", nRow, "(" + dr["Employee No"].ToString() + ")" + "Company Yearly Interest not found.")); continue; } else { PFTransaction pFTransaction = new PFTransaction(); pFTransaction.EmployeeID = oemployee.ID; pFTransaction.TranType = EnumPFTranType.CompYearlyInt; pFTransaction.TranAmount = Convert.ToDouble(dr["Company Yearly Interest"].ToString()); pFTransaction.MonthDate = monthDate; _PFTransactions.Add(pFTransaction); } } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found in the Employee List")); } if (_errorOrSuccessList.Count == 0) { new PFTransactionService().SaveAll(_PFTransactions); } } catch (Exception ex) { throw new ServiceException("Error occurred on row:" + nRow + " Reason:" + ex.Message); } } #endregion public void ImportLeaveBalance(DataUploadColumnDefinition _columnDefinition) { LeaveYear currLeaveYear = new LeaveYearService().GetCurrentYear(this._payrollTypeID); LeaveYear prevLeaveYear = new LeaveYearService().GetLastYear(this._payrollTypeID); int prevLeaveYearId = 0; if (prevLeaveYear == null) { prevLeaveYear = new LeaveYear(); prevLeaveYear.StartDate = new DateTime(currLeaveYear.StartDate.Year - 1, 1, 1); prevLeaveYear.EndDate = new DateTime(currLeaveYear.EndDate.Year - 1, 12, 31); prevLeaveYear.IsCurrent = false; prevLeaveYear.IsEnded = true; prevLeaveYear.Name = prevLeaveYear.StartDate.ToString("dd MMM yyyy") + " - " + prevLeaveYear.EndDate.ToString("dd MMM yyyy"); prevLeaveYear.Status = EnumStatus.Active; prevLeaveYearId = new LeaveYearService().Save(prevLeaveYear); } List oLeaves = new LeaveService().GetAll(); var arrayNames = (from DataColumn x in _uplodedData.Columns select x.ColumnName).ToArray(); List sNames = new List(); sNames.Add("Employee No"); sNames.Add("Leave Code"); sNames.Add("CFDays"); bool bFound = false; string sErrorColumnName = ""; foreach (string ss in sNames) { bFound = false; var result = arrayNames.Where(le => le.ToString() == ss); foreach (string sss in result) { bFound = true; } if (!bFound) { if (sErrorColumnName == "") sErrorColumnName = ss; else sErrorColumnName += ", " + ss; } } if (sErrorColumnName != "") { return; } EmpLeaveStatus status; List statuss = new List(); LeaveEntry leaveEntry = new LeaveEntry(); List leaveEntrys = new List(); List lparameters = new List(); LeaveParameter oLDetail = new LeaveParameter(); int nrow = 0; int ncolumn = 1; LeaveProcess oProcess = new LeaveProcessService().Get(prevLeaveYear == null ? 0 : prevLeaveYear.ID, _columnDefinition.PayrollTypeID); if (oProcess == null) { oProcess = new LeaveProcess(); oProcess.ProcessDate = prevLeaveYear.EndDate; oProcess.LeaveYearID = prevLeaveYear.ID; oProcess.ProcessYearDescription = prevLeaveYear.Name; oProcess.IsYearEnd = true; oProcess.CreatedBy = this._userID; oProcess.CreatedDate = DateTime.Today; oProcess.PayrollTypeID = this._payrollTypeID; oProcess.LeaveYear = prevLeaveYear; oProcess.CreatedBy = this._userID; oProcess.CreatedDate = DateTime.Today; oProcess.PayrollTypeID = _columnDefinition.PayrollTypeID; new LeaveProcessService().SaveLeaveProcess(oProcess); } List employees = new EmployeeService().GetAllEmps(this._payrollTypeID); //List leaves = Payroll.BO.Leave.GetLeaves(); Leave leave = oLeaves.Where(x => x.ID == _columnDefinition.SelectedItemOneID).FirstOrDefault(); if (prevLeaveYear != null) { string[] statusArray = new string[5]; string ErrorMsg = string.Empty; foreach (DataRow dr in _uplodedData.Rows) { nrow = nrow + 1; try { string Empcode = ""; string leaveCode = ""; double CFDays = 0.0; // double EncashDays = 0.0; if (Convert.ToString(dr[0].ToString().Trim()) != "") { try { Empcode = (Convert.ToString(dr[0].ToString().Trim())); ncolumn = 2; leaveCode = Convert.ToString(dr[1].ToString().Trim()); ncolumn = 3; CFDays = Convert.ToDouble(dr[2].ToString().Trim()); } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, "(" + ")" + "unknow error found")); //MessageBox.Show("Invalid data in row: " + nrow.ToString() + " Column:" + ncolumn.ToString() + " Reason :" + ex.Message, "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } if (leaveCode != leave.Code) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, "(" + dr[1].ToString() + ")" + "leave code not match in the system ")); //MessageBox.Show("Invalid leave code", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } status = new EmpLeaveStatus(); lparameters = new List(); oLDetail = new LeaveParameter(); leaveEntry = new LeaveEntry(); if (leave == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, "(" + dr[1].ToString() + ")" + "Leave Code Not found")); //MessageBox.Show("Leave Code : " + leaveCode + " " + " not found in database, Excel row: " + nrow.ToString() + " Column : 2", "Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Employee employee = employees.Find(delegate (Employee em) { return em.EmployeeNo == Empcode; }); if (employee != null) { status.EmpId = employee.ID; status.CFDays = CFDays; status.YearEndBalance = CFDays; status.EncashDays = 0; status.LeaveId = leave.ID; status.ProcessId = oProcess.ID; status.LeaveYearID = oProcess.LeaveYearID; status.CarryFromPrvYear = 0; status.EncashAmount = 0; status.NormalLeaveDays = 0; statuss.Add(status); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, "(" + dr[0].ToString() + ")" + "Employee Not found")); //MessageBox.Show("Employee Code : " + Empcode + " is not found in database, Excel Row:" + nrow.ToString() + " Column : 1", "Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } } } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, ex.Message)); throw new Exception(ex.Message); } } status = new EmpLeaveStatus(); try { new LeaveProcessService().DeleteByPayrollType(prevLeaveYear.ID, _columnDefinition.PayrollTypeID, leave.ID); //foreach (EmpLeaveStatus es in statuss) //{ new LeaveProcessService().SaveStatus(statuss); //} //Cursor.Current = Cursors.Default; //MessageBox.Show("Data uploaded successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exp) { throw new Exception(exp.Message); } } } public void ImportEmpLoanInformation(DataUploadColumnDefinition _columnDefinition) { List oemployees = new EmployeeService().GetAllEmps((int)_columnDefinition.PayrollTypeID); Employee oemployee = null; List loanissues = new List(); List loans = new LoanService().Get(EnumStatus.Active); Loan loan = null; EnumLoanFraction _Fractionate = EnumLoanFraction.WithFraction; string _Method = string.Empty; LoanIssue loanissue = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["EmployeeNo"].ToString(); }); if (oemployee != null) { loanissue = new LoanIssue(); loanissue.EmployeeID = oemployee.ID; loanissue.InterestRate = Convert.ToDouble(dr["Interest"]); loanissue.IssueDate = Convert.ToDateTime(dr["Loan Issue Date"]); loanissue.StartPaybackMonthDate = Convert.ToDateTime(dr["Disburse from Month"]); loanissue.LoanAmount = Convert.ToDouble(dr["Loan Amount"]); loanissue.CreatedBy = this._userID; loanissue.CreatedDate = DateTime.Today; loan = new Loan(); loan = loans.Find(delegate (Loan ln) { return ln.Name == dr["LoanType"].ToString(); }); if (loan != null) { loanissue.LoanID = loan.ID; } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("LoanType", nRow, "Loan type not found in the existing loans")); continue; } loanissue.NoOfInstallments = Convert.ToInt32(dr["Schedule"]); //loanissue.StartPaybackMonthDate = GlobalFunctions.LastDateOfMonth(loanissue.IssueDate); if (loan.LoanGroup == EnumLoanGroup.PF_Loan) { loanissue.loan = loan; loanissue.Schedules = new List(); loanissue.Schedules = loanissue.PreparePFLoanSchedule(loanissue); } else if (loan.LoanGroup == EnumLoanGroup.Flat_Amount) { loanissue.loan = loan; loanissue.Schedules = new List(); loanissue.Schedules = loanissue.PrepareFlatAmountSchedule(loanissue); } else { loanissue.Schedules = new List(); loanissue.Schedules = loanissue.PrepareEMISchedule(loanissue); } loanissues.Add(loanissue); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["EmployeeNo"].ToString() + ")" + "Employee not found for in the existing data")); } } if (_errorOrSuccessList.Count == 0) { new LoanIssueService().SaveAll(loanissues); } } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportLeaveEncashDays(DataUploadColumnDefinition _columnDefinition) { EmpLeaveStatus status; int nrow = 0; List leavestatuses = new LeaveProcessService().GetByYearType(_columnDefinition.SelectedItemTwoID, _columnDefinition.SelectedItemOneID); List employees = new EmployeeService().GetAllEmps(this._payrollTypeID); string[] statusArray = new string[5]; string ErrorMsg = string.Empty; foreach (DataRow dr in _uplodedData.Rows) { nrow = nrow + 1; try { string Empcode = ""; double EncashDays = 0.0; if (Convert.ToString(dr[0].ToString().Trim()) != "") { try { Empcode = (Convert.ToString(dr[0].ToString().Trim())); EncashDays = Convert.ToDouble(dr[1].ToString().Trim()); } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, "(" + ")" + "unknow error found")); continue; } status = new EmpLeaveStatus(); Employee employee = employees.Find(delegate (Employee em) { return em.EmployeeNo == Empcode; }); if (employee != null) { status = leavestatuses.FirstOrDefault(x => x.EmpId == employee.ID); if (status == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, "(" + dr[0].ToString() + ")" + " Leave process record not found.")); continue; } status.YearEndBalance = status.YearEndBalance + status.EncashDays; status.EncashDays = EncashDays; status.YearEndBalance = status.YearEndBalance - EncashDays; if (status.YearEndBalance < 0) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, "(" + dr[0].ToString() + ")" + "Year-End balance can't be less Zero")); continue; } } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, "(" + dr[0].ToString() + ")" + "Employee Not found")); continue; } } } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nrow, ex.Message)); throw new Exception(ex.Message); } } try { if (_errorOrSuccessList.Count == 0) new LeaveProcessService().SaveStatus(leavestatuses); } catch (Exception exp) { throw new Exception(exp.Message); } } public void ImportLeaveEntry(DataUploadColumnDefinition _columnDefinition) { LeaveYear currLeaveYear = new LeaveYearService().GetCurrentYear(this._payrollTypeID); var arrayNames = (from DataColumn x in _uplodedData.Columns select x.ColumnName).ToArray(); List sNames = new List(); sNames.Add("Employee No"); sNames.Add("Leave Code"); sNames.Add("From Date"); sNames.Add("To Date"); sNames.Add("Leave Availed"); sNames.Add("Remarks"); bool bFound = false; string sErrorColumnName = ""; foreach (string ss in sNames) { bFound = false; var result = arrayNames.Where(le => le.ToString() == ss); foreach (string sss in result) { bFound = true; } if (!bFound) { if (sErrorColumnName == "") sErrorColumnName = ss; else sErrorColumnName += ", " + ss; } } if (sErrorColumnName != "") { //MessageBox.Show("Column(" + sErrorColumnName + ") not found", "From Excel", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { List leaveentries = new LeaveEntryService().GetByLeaveYear(currLeaveYear.ID); int nRowCount = 1; LeaveEntry leaveEntry = new LeaveEntry(); List leaveEntrys = new List(); List employees = new EmployeeService().GetAllEmps(); List oLeaves = new LeaveService().GetAll(); List oLeaveParameters = new List(); List leaveParamss = new LeaveParameterService().Get(EnumStatus.Regardless, _columnDefinition.PayrollTypeID, null, true); Leave leave = oLeaves.Where(x => x.ID == _columnDefinition.SelectedItemOneID).FirstOrDefault(); string[] statusArray = new string[5]; string ErrorMsg = string.Empty; int nRow = 0; foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; //employee = new Employee(); //leave = new Leave(); try { leaveEntry = new LeaveEntry(); string Empcode = Convert.ToString(dr[0].ToString().Trim()); string leaveCode = Convert.ToString(dr[1].ToString().Trim()); //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); DateTime fromDate = DateTime.Parse(dr[2].ToString().Trim()); DateTime toDate = DateTime.Parse(dr[3].ToString().Trim()); double totalDays = Convert.ToDouble(dr[4].ToString().Trim()); string remarks = dr[5].ToString().Trim(); //Leave leave = leaves.Find(delegate(Payroll.BO.Leave le) { return le.Code == leaveCode; }); Employee employee = employees.Find(delegate (Employee em) { return em.EmployeeNo == Empcode; }); if (employee == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee Not found")); continue; } if (leave == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Leave not found")); continue; } if (leaveCode != leave.Code) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Leave code not match")); continue; } List tempLS = leaveentries.Where(x => x.AppliedFromDate >= fromDate && x.AppliedFromDate <= toDate && x.EmpID == employee.ID && x.LeaveStatus != EnumLeaveStatus.Declined && x.LeaveStatus != EnumLeaveStatus.Cancel).ToList(); if (tempLS.Count > 0) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + " Overlap with previously applied leaves.")); continue; } oLeaveParameters = new LeaveParameterService().GetApplicableParam(leaveParamss, oLeaves, (int)employee.GradeID, EnumLeaveparamOn.Grade, employee); if (oLeaveParameters != null && oLeaveParameters.Count > 0) { LeaveParameter param = oLeaveParameters.FirstOrDefault(x => x.LeaveId == leave.ID); if (param != null) { leaveEntry.AppliedParamId = param.ID; leaveEntry.ApprovedParamId = param.ID; } } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Leave Setup not found")); //MessageBox.Show("Leave Parameter not found for leave:" + leaveCode + " For Employee:" + employee.EmployeeNo, "Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } leaveEntry.EmpID = employee.ID; leaveEntry.AppliedLeaveDate = fromDate; leaveEntry.AppliedFromDate = fromDate; leaveEntry.AppliedToDate = toDate; leaveEntry.ApprovedFromDate = fromDate; leaveEntry.ApprovedToDate = toDate; leaveEntry.AppliedTotalDays = totalDays; leaveEntry.ApprovedTotalDays = totalDays; leaveEntry.AvailFromDate = fromDate; leaveEntry.AvailToDate = toDate; leaveEntry.AvailTotalDays = totalDays; leaveEntry.LeaveID = leave.ID; leaveEntry.SbuID = 0; leaveEntry.FunctionID = 0; leaveEntry.DepartmentID = employee.DepartmentID != null ? (int)employee.DepartmentID : 0; leaveEntry.DesignationID = employee.DesignationID != null ? (int)employee.DesignationID : 0; leaveEntry.LocationID = 0; leaveEntry.EmpGradeId = employee.GradeID != null ? (int)employee.GradeID : 0; leaveEntry.LeaveYearId = currLeaveYear.ID; leaveEntry.LeaveStatus = EnumLeaveStatus.Approved; leaveEntry.Remarks = remarks; leaveEntrys.Add(leaveEntry); } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + ex.Message)); } nRowCount++; } if (_errorOrSuccessList.Count == 0) new LeaveEntryService().SaveLeaveEntry(leaveEntrys); } catch (Exception ex) { } } //public void ImportLeaveEntryLf(DataUploadColumnDefinition _columnDefinition, int userID) //{ // try // { // LeaveYear currLeaveYear = new LeaveYearService().GetCurrentYear(this._payrollTypeID); // List leaveentries = new LeaveEntryService().GetByLeaveYear(currLeaveYear.ID); // int nRowCount = 1; // LeaveEntry leaveEntry = new LeaveEntry(); // List leaveEntrys = new List(); // List employees = new EmployeeService().GetAllEmps(); // List oLeaves = new LeaveService().GetAll(); // List oLeaveParameters = new List(); // List leaveParamss = new LeaveParameterService().Get(EnumStatus.Regardless, _columnDefinition.PayrollTypeID, null, true); // string[] statusArray = new string[5]; // string ErrorMsg = string.Empty; // int nRow = 0; // DateTime dateTime; // string[] dateFormats = {"dd/MM/yyyy HH:mm:ss", "d/M/yyyy HH:mm:ss", "dd/MM/yyyy hh:mm:ss tt", "d/M/yyyy hh:mm:ss tt", "dd/MM/yyyy HH:mm", // "d/M/yyyy HH:mm", "dd/MM/yyyy hh:mm tt", "d/M/yyyy hh:mm tt", // "dd/MM/yyyy", "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy"}; // foreach (DataRow dr in _uplodedData.Rows) // { // nRow = nRow + 1; // try // { // leaveEntry = new LeaveEntry(); // string Empcode = Convert.ToString(dr[0].ToString().Trim()); // string leaveCode = Convert.ToString(dr[1].ToString().Trim()); // DateTime fromDate = new DateTime(); // DateTime toDate = new DateTime(); // Leave leave = oLeaves.Where(x => x.Description == leaveCode).FirstOrDefault(); // if (dr[2] != null) // { // fromDate = DateTime.ParseExact(dr[2].ToString().Trim(), dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None); // } // if (dr[3] != null) // { // toDate = DateTime.ParseExact(dr[3].ToString().Trim(), dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None); // } // double totalDays = Convert.ToDouble(dr[4].ToString().Trim()); // string remarks = dr[10].ToString().Trim(); // Employee employee = employees.Find(delegate (Employee em) { return em.EmployeeNo == Empcode; }); // if (employee == null) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["EMPNO"].ToString() + "]" + "Employee Not found")); // continue; // } // if (leave == null) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["LEAVE_TYPE"].ToString() + "]" + "Leave Type not found")); // continue; // } // //if (leaveCode != leave.Description) // //{ // // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Leave code not match")); // // continue; // //} // List tempLS = leaveentries.Where(x => x.AppliedFromDate >= fromDate // && x.AppliedFromDate <= toDate // && x.EmpID == employee.ID // && x.LeaveStatus != EnumLeaveStatus.Declined // && x.LeaveStatus != EnumLeaveStatus.Cancel).ToList(); // if (tempLS.Count > 0) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["EMPNO"].ToString() + "]" + " Overlap with previously applied leaves.")); // continue; // } // oLeaveParameters = new LeaveParameterService().GetApplicableParam(leaveParamss, (int)employee.GradeID, EnumLeaveparamOn.Grade, employee); // if (oLeaveParameters != null && oLeaveParameters.Count > 0) // { // LeaveParameter param = oLeaveParameters.FirstOrDefault(x => x.LeaveId == leave.ID); // if (param != null) // { // leaveEntry.AppliedParamId = param.ID; // leaveEntry.ApprovedParamId = param.ID; // } // } // else // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["EMPNO"].ToString() + "]" + "Leave Parameter not found")); // continue; // } // leaveEntry.EmpID = employee.ID; // leaveEntry.AppliedLeaveDate = fromDate; // leaveEntry.AppliedFromDate = fromDate; // leaveEntry.AppliedToDate = toDate; // leaveEntry.ApprovedFromDate = fromDate; // leaveEntry.ApprovedToDate = toDate; // leaveEntry.AppliedTotalDays = totalDays; // leaveEntry.ApprovedTotalDays = totalDays; // leaveEntry.AvailFromDate = fromDate; // leaveEntry.AvailToDate = toDate; // leaveEntry.AvailTotalDays = totalDays; // leaveEntry.LeaveID = leave.ID; // leaveEntry.SbuID = 0; // leaveEntry.CreatedBy = userID; // leaveEntry.FunctionID = 0; // leaveEntry.DepartmentID = employee.DepartmentID != null ? (int)employee.DepartmentID : 0; // leaveEntry.DesignationID = employee.DesignationID != null ? (int)employee.DesignationID : 0; // leaveEntry.LocationID = 0; // leaveEntry.EmpGradeId = employee.GradeID != null ? (int)employee.GradeID : 0; // leaveEntry.LeaveYearId = currLeaveYear.ID; // leaveEntry.LeaveStatus = EnumLeaveStatus.Approved; // leaveEntry.Remarks = remarks; // leaveEntrys.Add(leaveEntry); // } // catch (Exception ex) // { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["EMPNO"].ToString() + ")" + ex.Message)); // } // nRowCount++; // } // if (_errorOrSuccessList.Count == 0) // new LeaveEntryService().SaveLeaveEntry(leaveEntrys); // } // catch (Exception ex) // { // } //} public void ImportEmpCC(DataUploadColumnDefinition _columnDefinition, int userID) { List oemployees = new EmployeeService().GetAllEmps(_columnDefinition.PayrollTypeID); Employee oemployee = null; List oCostcenters = new CostcenterService().Get(EnumStatus.Regardless, _columnDefinition.PayrollTypeID); Costcenter oCC = null; List oempCostCenters = new List(); PayrollType ptype = new PayrollTypeService().Get(_columnDefinition.PayrollTypeID); EmployeeCostCenter oempCostCenter = null; int nRow = 0; try { foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); if (oemployee != null) { oCC = oCostcenters.Find(delegate (Costcenter item) { return item.Code == dr["Costcenter Code"].ToString(); }); if (oCC != null) { oempCostCenter = new EmployeeCostCenter(); oempCostCenter.EmployeeID = oemployee.ID; oempCostCenter.CostCenterID = oCC.ID; oempCostCenter.Percentage = Convert.ToDouble(dr["Involve Percent"]); oempCostCenter.IsCurrentCC = true; oempCostCenter.MonthDate = ptype.NextPayProcessDate; oempCostCenter.CreatedBy = userID; oempCostCenters.Add(oempCostCenter); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("CostCenter Code", nRow, "Cost center code not found in the existing Cost Centers")); } else _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); } foreach (var employee in _uplodedData.AsEnumerable().GroupBy(r => r["Employee No"].ToString())) { double totalPercent = employee.Sum(r => Convert.ToDouble(r["Involve Percent"])); if (totalPercent != 100) _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", 0, $"Total involvement percent is not 100 for Employee No. {employee.Key}")); } if (_errorOrSuccessList.Count == 0) new EmployeeCostCenterService().Save(oempCostCenters); } catch (Exception ex) { throw new ServiceException("Error occured on row:" + nRow + " Reason:" + ex.Message); } } public void ImportLeaveEntryLf(DataUploadColumnDefinition _columnDefinition, int userID) { try { LeaveYear lfcurrLeaveYear = new LeaveYearService().GetCurrentYear(1); List lfleaveentries = new LeaveEntryService().GetByLeaveYear(1); LeaveYear ccurrLeaveYear = new LeaveYearService().GetCurrentYear(2); List cleaveentries = new LeaveEntryService().GetByLeaveYear(2); LeaveYear gspcurrLeaveYear = new LeaveYearService().GetCurrentYear(3); List gspleaveentries = new LeaveEntryService().GetByLeaveYear(3); int nRowCount = 1; LeaveEntry leaveEntry = new LeaveEntry(); List leaveEntrys = new List(); List employees = new EmployeeService().GetAllEmps(); List oLeaves = new LeaveService().GetAll(); List oLeaveParameters = new List(); List leaveParamss = new LeaveParameterService().Get(EnumStatus.Regardless, _columnDefinition.PayrollTypeID, null, true); string[] statusArray = new string[5]; string ErrorMsg = string.Empty; int nRow = 0; DateTime dateTime; string[] dateFormats = {"dd/MM/yyyy HH:mm:ss", "d/M/yyyy HH:mm:ss", "dd/MM/yyyy hh:mm:ss tt", "d/M/yyyy hh:mm:ss tt", "dd/MM/yyyy HH:mm", "d/M/yyyy HH:mm", "dd/MM/yyyy hh:mm tt", "d/M/yyyy hh:mm tt", "dd/MM/yyyy", "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy"}; LeaveYear currLeaveYear = null; List leaveentries = null; foreach (DataRow dr in _uplodedData.Rows) { nRow = nRow + 1; try { leaveEntry = new LeaveEntry(); string Empcode = Convert.ToString(dr[0].ToString().Trim()); string leaveCode = Convert.ToString(dr[1].ToString().Trim()); DateTime fromDate = new DateTime(); DateTime toDate = new DateTime(); Leave leave = oLeaves.Where(x => x.Description == leaveCode).FirstOrDefault(); Employee employee = employees.Find(delegate (Employee em) { return em.EmployeeNo == Empcode; }); if (employee == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["EMPNO"].ToString() + "]" + "Employee Not found")); continue; } if (employee.PayrollTypeID == 1) { currLeaveYear = lfcurrLeaveYear; leaveentries = lfleaveentries; } else if (employee.PayrollTypeID == 2) { currLeaveYear = ccurrLeaveYear; leaveentries = cleaveentries; } else { currLeaveYear = gspcurrLeaveYear; leaveentries = gspleaveentries; } if (dr[2] != null) { DateTime parsedDate = DateTime.Parse(dr[2].ToString()); if (parsedDate != null) { fromDate = parsedDate; } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["EMPNO"].ToString() + "]" + "Invalid/Null LEAVE_START_DATE date")); continue; } //fromDate = DateTime.ParseExact(dr[2].ToString().Trim(), dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None); } if (fromDate < currLeaveYear.StartDate) { continue; } if (dr[3] != null) { DateTime parsedDate = DateTime.Parse(dr[3].ToString()); if (parsedDate != null) { toDate = parsedDate; } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["EMPNO"].ToString() + "]" + "Invalid/Null LEAVE_END_DATE date")); continue; } //toDate = DateTime.ParseExact(dr[3].ToString().Trim(), dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None); } double totalDays = Convert.ToDouble(dr[4].ToString().Trim()); string remarks = dr[10].ToString().Trim(); if (leave == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["LEAVE_TYPE"].ToString() + "]" + "Leave Type not found")); continue; } //if (leaveCode != leave.Description) //{ // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Leave code not match")); // continue; //} //List tempLS = leaveentries.Where(x => x.AppliedFromDate >= fromDate //validation to prevent duplicate data entry //&& x.AppliedFromDate <= toDate //&& x.EmpID == employee.ID //&& x.LeaveStatus != EnumLeaveStatus.Declined //&& x.LeaveStatus != EnumLeaveStatus.Cancel).ToList(); string status = dr["status"].ToString(); status = dr["status"].ToString(); if (status == "N" || status == "n") { List tempLS = leaveentries.Where(x => x.AppliedFromDate >= fromDate //validation to prevent duplicate data entry && x.AppliedFromDate <= toDate && x.EmpID == employee.ID && x.LeaveStatus == EnumLeaveStatus.Approved).ToList(); if (tempLS.Count > 0) { // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["EMPNO"].ToString() + "]" + " Overlap with previously applied leaves.")); continue; } } oLeaveParameters = new LeaveParameterService().GetApplicableParam(leaveParamss, oLeaves, (int)employee.GradeID, EnumLeaveparamOn.Grade, employee); if (oLeaveParameters != null && oLeaveParameters.Count > 0) { LeaveParameter param = oLeaveParameters.FirstOrDefault(x => x.LeaveId == leave.ID); if (param != null) { leaveEntry.AppliedParamId = param.ID; leaveEntry.ApprovedParamId = param.ID; } } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "[" + dr["EMPNO"].ToString() + "]" + "Leave Parameter not found")); continue; } leaveEntry.EmpID = employee.ID; leaveEntry.AppliedLeaveDate = fromDate; leaveEntry.AppliedFromDate = fromDate; leaveEntry.AppliedToDate = toDate; leaveEntry.ApprovedFromDate = fromDate; leaveEntry.ApprovedToDate = toDate; leaveEntry.AppliedTotalDays = totalDays; leaveEntry.ApprovedTotalDays = totalDays; leaveEntry.AvailFromDate = fromDate; leaveEntry.AvailToDate = toDate; leaveEntry.AvailTotalDays = totalDays; leaveEntry.LeaveID = leave.ID; leaveEntry.SbuID = 0; leaveEntry.CreatedBy = userID; leaveEntry.FunctionID = 0; leaveEntry.DepartmentID = employee.DepartmentID != null ? (int)employee.DepartmentID : 0; leaveEntry.DesignationID = employee.DesignationID != null ? (int)employee.DesignationID : 0; leaveEntry.LocationID = 0; leaveEntry.EmpGradeId = employee.GradeID != null ? (int)employee.GradeID : 0; leaveEntry.LeaveYearId = currLeaveYear.ID; leaveEntry.LeaveStatus = EnumLeaveStatus.Approved; if (status == "V" || status == "v") { leaveEntry.LeaveStatus = EnumLeaveStatus.Cancelled_by_user; } leaveEntry.Remarks = remarks; leaveEntrys.Add(leaveEntry); } catch (Exception ex) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["EMPNO"].ToString() + ")" + ex.Message)); } nRowCount++; } //if (_errorOrSuccessList.Count == 0) new LeaveEntryService().SaveLeaveEntryLifFung(leaveEntrys); } catch (Exception ex) { } } #region Import LineManager //public void SaveEmpLineManager2() //{ // try // { // new Employee().UpdateLM2(_employeesForSave); // } // catch (Exception ex) // { // throw new ServiceException(ex.Message); // } //} #endregion //public void UpdateLocation( List employees) //{ // TransactionContext tc = null; // try // { // tc = TransactionContext.Begin(true); // List olocations = new List(); // int locID =50; // Location op = Location.Get(ID.FromInteger(5)); // olocations.Add(op); // foreach (Employee emp in employees) // { // //oemployee = oemployees.Find(delegate(Employee emp) { return emp.EmployeeNo == dr["Employee No"].ToString(); }); // Location onewloc= olocations.Find(delegate (Location item) {return item.Name == emp.Location.Name ;}); // if (onewloc == null) // { // locID = locID + 1; // emp.Location.SetObjectID(locID); // olocations.Add(emp.Location); // } // else // { // emp.Location.SetObjectID(onewloc.ID.Integer); // } // } // if (olocations.Count>0) // LocationService.SaveForUpload(tc, olocations); // //foreach (Employee emp in employees) // //{ // // MiscellaneousDA.updateLocation(tc, emp.ID, emp.Location.ID); // //} // tc.End(); // } // catch (Exception e) // { // #region Handle Exception // if (tc != null) // tc.HandleError(); // ExceptionLog.Write(e); // throw new ServiceException(e.Message, e); // #endregion // } //} #region Import Objective public void ImportObjectiveUpload(DataUploadColumnDefinition columnDefinition, int payrollTypeId, int pmpYearID) { //List objectiveTypes = new List(); List objSets = new List(); List objectives = new List(); try { Employee oemployee = null; ObjectiveType oObjectiveType = null; Objective obj = null; List oemployees = new EmployeeService().GetAllEmps(); List oObjectiveTypes = new ObjectiveTypeService().Get(EnumStatus.Active); PMPProcess pmp = new PMPProcessService().GetPmpProcessByPmpProcesId(pmpYearID); if (pmp?.PmpStatus != EnumPMPStatus.Objective_Setting) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create(string.Empty, 0, "Uploaded PMS Year data should be in Objective Setting Status")); return; } int nRow = 0; Dictionary weightageTracker = new Dictionary(); foreach (DataRow oDR in _uplodedData.Rows) { nRow = nRow + 1; #region check Empty fields //if (oDR["Objective Date"].ToString().Trim() == string.Empty) //{ // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Objective Date", nRow, "(" + oDR["Objective Date"].ToString() + ")" + "Objective Date not found in the current context")); // continue; //} if (oDR["Employee No"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + oDR["Employee No"].ToString() + ")" + "Employee No not found in the current context")); continue; } if (oDR["KPI Type"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("KPI Type", nRow, "(" + oDR["KPI Type"].ToString() + ")" + "KPI Type not found in the current context")); continue; } if (oDR["Weightage"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Weightage", nRow, "(" + oDR["Weightage"].ToString() + ")" + "Weightage not found in the current context")); continue; } if (oDR["KPI Title"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("KPI Title", nRow, "(" + oDR["KPI Title"].ToString() + ")" + "KPI Title not found in the current context")); continue; } if (oDR["KPI Description"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("KPI Description", nRow, "(" + oDR["KPI Description"].ToString() + ")" + "KPI Description not found in the current context")); continue; } if (oDR["Start Date"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Start Date", nRow, "(" + oDR["Start Date"].ToString() + ")" + "Start Date not found in the current context")); continue; } if (oDR["End Date"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("End Date", nRow, "(" + oDR["End Date"].ToString() + ")" + "End Date not found in the current context")); continue; } //if (oDR["Employee Mid Year Status"].ToString().Trim() == string.Empty) //{ // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee Mid Year Status", nRow, "(" + oDR["Employee Mid Year Status"].ToString() + ")" + "Employee Mid Year Status not found in the current context")); // continue; //} //if (oDR["LM Mid Year Status"].ToString().Trim() == string.Empty) //{ // _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("LM Mid Year Status", nRow, "(" + oDR["LM Mid Year Status"].ToString() + ")" + "LM Mid Year Status not found in the current context")); // continue; //} #endregion oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == oDR["Employee No"].ToString(); }); if (oemployee == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + oDR["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); continue; } oObjectiveType = oObjectiveTypes.Find(delegate (ObjectiveType objt) { return objt.Name.ToLower().Trim() == oDR["KPI Type"].ToString().ToLower().Trim(); }); if (oObjectiveType == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("KPI Type.", nRow, "(" + oDR["KPI Type"].ToString() + ")" + "KPI Type not found for in the existing data")); continue; } #region check weightage string employeeNo = oDR["Employee No"].ToString().Trim(); double weightage; // Try to parse the Weightage value, and handle parsing errors if (!double.TryParse(oDR["Weightage"].ToString(), out weightage)) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Weightage", nRow, "Invalid Weightage value")); continue; } // Accumulate Weightage for the Employee No if (weightageTracker.ContainsKey(employeeNo)) { weightageTracker[employeeNo] += weightage; } else { weightageTracker[employeeNo] = weightage; } #endregion obj = new Objective(); obj.PMPYearID = pmpYearID; obj.EmployeeID = oemployee.ID; //obj.ObjectiveDate = Convert.ToDateTime(oDR["Objective Date"], true, DateTime.MinValue); //obj.RagingDate = Convert.ToDateTime(oDR["Objective Date"]); obj.ObjectiveType = oObjectiveType.ID; obj.Weightages = Convert.ToDouble(oDR["Weightage"]); obj.Title = Convert.ToString(oDR["KPI Title"]); obj.Description = Convert.ToString(oDR["KPI Description"]); obj.StartDate = Convert.ToDateTime(oDR["Start Date"]); obj.EndDate = Convert.ToDateTime(oDR["End Date"]); obj.MYEmployeeComments = Convert.ToString(oDR["Employee Mid Year Comment"]); obj.MYLMComments = Convert.ToString(oDR["LM Mid Year Comment"]); //string normalizedInput = oDR["Employee Mid Year Status"].ToString().Replace(" ", ""); //EnumAssessment result; //Enum.TryParse(normalizedInput, ignoreCase: true, out result); obj.MYAssessRating = EnumAssessment.None; //string normalizedInput2 = oDR["LM Mid Year Status"].ToString().Replace(" ", ""); //EnumAssessment result2; //Enum.TryParse(normalizedInput2, ignoreCase: true, out result2); obj.MYLMAssessRating = EnumAssessment.None; objectives.Add(obj); } foreach (var entry in weightageTracker) { if (entry.Value != 100) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Weightage", 0, $"Total Weightage for Employee No {entry.Key} is {entry.Value}, but it should be 100.")); continue; } oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == entry.Key.ToString(); }); if (oemployee != null) { ObjectiveSet obs = new ObjectiveSetService().GetObjectiveSetWithChild(oemployee.ID, pmpYearID, false); if (obs != null) { if (obs.Objectives == null) obs.Objectives = objectives.FindAll(o => o.EmployeeID == oemployee.ID); if (obs.ObjectiveSetRemarks == null) obs.ObjectiveSetRemarks = new ObjectiveSetRemarks(); if (obs.ValuesRatings == null) obs.ValuesRatings = new List(); } else { obs = new ObjectiveSet(); obs.PMPYearID = pmpYearID; obs.EmployeeID = oemployee.ID; //obs.Objectives = new List(); obs.Objectives = objectives.FindAll(o => o.EmployeeID == oemployee.ID); obs.ObjectiveSetRemarks = new ObjectiveSetRemarks(); obs.ValuesRatings = new List(); } if (obs.IsNew) { if (!objSets.Any(x => x.EmployeeID == obs.EmployeeID)) { objSets.Add(obs); } } else { ObjectiveSet foundObjectiveSet = objSets.Find(x => x.ID == obs.ID); if (foundObjectiveSet == null) objSets.Add(obs); else objSets.ForEach(element => { if (element.ID == obs.ID) { //element.Objectives = new List(); element.Objectives = obs.Objectives; } }); } } } } catch (Exception e) { Console.WriteLine(e); throw; } if (_errorOrSuccessList.Count == 0) { List objectiveSetIDsInt = new List(); objSets.ForEach(o => objectiveSetIDsInt.Add(o.ID)); string objectiveIDs = string.Join(",", objectiveSetIDsInt); if (objectiveIDs != "" && objectiveIDs != null) new ObjectiveService().DeletebyObjectiveSetIDs(objectiveIDs); string empIDs = string.Join(",", objSets.Select(x => x.EmployeeID)); if (empIDs != "" && empIDs != null) new ObjectiveService().DeleteObjByEmpIDsAndPMPYear(objSets[0].PMPYearID, empIDs); objSets.ForEach(obs => { new ObjectiveSetService().SaveWithChild(obs); }); } } #endregion #region Import Second Line Manager Rating public void ImportSecondLineManagerRatingUpload(DataUploadColumnDefinition columnDefinition, int payrollTypeId, int pmpYearID) { List objSets = new List(); try { Employee oemployee = null; ObjectiveType oObjectiveType = null; Objective obj = null; List oemployees = new EmployeeService().GetAllEmps(); List oObjectiveTypes = new ObjectiveTypeService().Get(EnumStatus.Active); int nRow = 0; Dictionary weightageTracker = new Dictionary(); foreach (DataRow oDR in _uplodedData.Rows) { nRow = nRow + 1; #region check Empty fields if (oDR["Employee No"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + oDR["Employee No"].ToString() + ")" + "Employee No not found in the current context")); continue; } if (oDR["Rating"].ToString().Trim() == string.Empty) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Rating", nRow, "(" + oDR["Rating"].ToString() + ")" + "Rating not found in the current context")); continue; } #endregion oemployee = oemployees.Find(delegate (Employee emp) { return emp.EmployeeNo == oDR["Employee No"].ToString(); }); if (oemployee == null) { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + oDR["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); continue; } if (oemployee != null) { ObjectiveSet obs = new ObjectiveSetService().GetByEmployeeID(oemployee.ID, pmpYearID); if (obs != null) { obs.SecondLMOverallRating = Convert.ToDouble(oDR["Rating"]); objSets.Add(obs); } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Objective Set.", nRow, "(" + oDR["Employee No"].ToString() + ")" + "ObjectiveSet was not found for in the existing data")); continue; } } else { _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No.", nRow, "(" + oDR["Employee No"].ToString() + ")" + "Employee not found for in the existing data")); continue; } } } catch (Exception e) { Console.WriteLine(e); throw; } if (_errorOrSuccessList.Count == 0) { objSets.ForEach(obs => { new ObjectiveSetService().Save(obs); }); } } #endregion #endregion protected override T CreateObject(Ease.Core.DataAccess.DataReader dr) { throw new NotImplementedException(); } } }