Example #1
0
        public void ActionApprovedAll(List <Guid> lstId, string status, Guid userId)
        {
            var    statusMes        = string.Empty;
            var    objTravelRequest = new List <object>();
            string UserLogin        = string.Empty;

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork    = (IUnitOfWork)(new UnitOfWork(context));
                var repoClaimItem = new CustomBaseRepository <FIN_ClaimItem>(unitOfWork);
                var repoClaim     = new CustomBaseRepository <FIN_Claim>(unitOfWork);
                var lstClaimId    = repoClaim.GetAll().Where(s => s.IsDelete == null && lstId.Contains(s.ID)).Select(s => s.ID).ToList();

                var lstClaimItem = repoClaimItem.GetAll().Where(s => s.IsDelete == null).ToList();


                var objApprovedClaim = new List <object>();
                objApprovedClaim.AddRange(new object[6]);
                objApprovedClaim[4] = 1;
                objApprovedClaim[5] = int.MaxValue - 1;
                var lstApprovedClaim = GetData <FIN_ApproverECLAIMEntity>(objApprovedClaim, ConstantSql.hrm_fin_sp_get_ApproverECLAIM, UserLogin, ref statusMes).ToList();

                var approvedType1  = FinApproverType.FIN_Claim_Profile.ToString();
                var approvedType2  = FinApproverType.FIN_Claim_Manufacture.ToString();
                var approvedEntity = lstApprovedClaim.Where(s => s.ApprovedID != null && s.ApprovedID.Value == userId && (s.ApprovedType == approvedType1 || s.ApprovedType == approvedType2)).FirstOrDefault();

                if (status == "E_REQUEST")
                {
                    if (lstClaimId.Count > 0)
                    {
                        lstClaimItem = lstClaimItem.Where(s => s.ClaimID != null && lstClaimId.Contains(s.ClaimID.Value)).ToList();
                        foreach (var item in lstClaimItem)
                        {
                            item.Description2 = status;
                        }
                        repoClaimItem.SaveChanges();
                    }
                }

                if (status == "E_APPROVED")
                {
                    if (lstClaimId.Count > 0)
                    {
                        if (approvedEntity != null)
                        {
                            lstClaimItem = lstClaimItem.Where(s => s.ClaimID != null && lstClaimId.Contains(s.ClaimID.Value)).ToList();
                            foreach (var item in lstClaimItem)
                            {
                                item.Description2 = status + "_" + approvedEntity.OrderNo.ToString();
                            }
                            repoClaimItem.SaveChanges();
                        }
                    }
                }
            }
        }
Example #2
0
        public void ActionApproved(List<Guid> lstId, string status, Guid userId)
        {
            var statusMes = string.Empty;
            var objTravelRequest = new List<object>();
            string UserLogin = string.Empty;
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoTravelRequestItem = new CustomBaseRepository<FIN_ClaimItem>(unitOfWork);
                var lstTravelRequestItem = repoTravelRequestItem.GetAll().Where(s => s.IsDelete == null).ToList();

                if(status == "E_APPROVED")
                {
                    var objApprovedClaim = new List<object>();
                    objApprovedClaim.AddRange(new object[6]);
                    objApprovedClaim[4] = 1;
                    objApprovedClaim[5] = int.MaxValue - 1;
                    var lstApprovedClaim = GetData<FIN_ApproverECLAIMEntity>(objApprovedClaim, ConstantSql.hrm_fin_sp_get_ApproverECLAIM, UserLogin, ref statusMes).ToList();

                    var approvedType1 = FinApproverType.FIN_Claim_Profile.ToString();
                    var approvedType2 = FinApproverType.FIN_Claim_Manufacture.ToString();

                    var approvedEntity = lstApprovedClaim.Where(s => s.ApprovedID != null && s.ApprovedID.Value == userId && (s.ApprovedType == approvedType1 || s.ApprovedType == approvedType2)).FirstOrDefault();
                    if (lstId.Count > 0)
                    {
                        if (approvedEntity != null)
                        {
                            lstTravelRequestItem = lstTravelRequestItem.Where(s => lstId.Contains(s.ID)).ToList();
                            foreach (var item in lstTravelRequestItem)
                            {
                                item.Description2 = status;
                            }
                            repoTravelRequestItem.SaveChanges();
                        }
                        
                    }
                }

                if(status == "E_REJECTED")
                {
                    if (lstId.Count > 0)
                    {
                        lstTravelRequestItem = lstTravelRequestItem.Where(s => lstId.Contains(s.ID)).ToList();
                        foreach (var item in lstTravelRequestItem)
                        {
                            item.Description2 = status;
                        }
                        repoTravelRequestItem.SaveChanges();
                    }
                
                }
               

            }
        }
        public Eva_PerformanceExtendEntity GetPerformanceExtendByPerID(string ID,string userLogin)
        {
            Guid perID = Guid.Empty;
            Guid.TryParse( ID, out perID);
            BaseService service = new BaseService();
            string status = string.Empty;

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoEva_Performance = new CustomBaseRepository<Eva_Performance>(unitOfWork);
                var repoEva_PerformanceExtend = new CustomBaseRepository<Eva_PerformanceExtend>(unitOfWork);

                var performance = repoEva_Performance.GetAll().Where(s => s.ID == perID).FirstOrDefault();
                var extend = repoEva_PerformanceExtend.GetAll().Where(s => s.ID == performance.PerformanceExtendID).FirstOrDefault();

                var result = extend.Copy<Eva_PerformanceExtendEntity>();
                string proID = Common.DotNetToOracle(performance.ProfileID.Value.ToString());
                var profile = service.GetData<Hre_ProfileEntity>(proID, ConstantSql.hrm_hr_sp_get_ProfileById,userLogin, ref status).FirstOrDefault();

                if (profile != null && result == null)
                {
                    result = new Eva_PerformanceExtendEntity();
                }
                
                result.ProfileName = profile.ProfileName ?? string.Empty;
                result.CodeEmp = profile.CodeEmp ?? string.Empty;
                result.PositionName = profile.PositionName ?? string.Empty;
                result.JobTitleName = profile.JobTitleName ?? string.Empty;
                result.DateOfBirth = profile.DateOfBirth;
                result.DateHire = profile.DateHire;
                result.PayrollGroupName = profile.PayrollGroupName ?? string.Empty;
                result.SupervisorName = profile.SupervisorName ?? string.Empty;
                result.HighSupervisorName = profile.HighSupervisorName ?? string.Empty;
                result.WorkPlaceName = profile.WorkPlaceName ?? string.Empty;
                result.TCountryName = profile.TCountryName ?? string.Empty;
                result.TProvinceName = profile.TProvinceName ?? string.Empty;
                result.Channel = profile.Channel ?? string.Empty;
                result.Region = profile.Region ?? string.Empty;
                result.Area = profile.Area ?? string.Empty;
                result.DateOfEffect = profile.DateOfEffect;

                return result;

            }
        }
Example #4
0
        public string ActionRejectTraineeRegister(List <Guid> selectedIds, Guid UserId, string Reason)
        {
            using (var context = new VnrHrmDataContext())
            {
                var message    = string.Empty;
                var status     = string.Empty;
                var UserLogin  = string.Empty;
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));

                var objTraineeRegister = new List <object>();
                objTraineeRegister.AddRange(new object[12]);
                objTraineeRegister[10] = 1;
                objTraineeRegister[11] = int.MaxValue - 1;
                var lstTraineeRegister = GetData <Tra_TraineeRegisterEntity>(objTraineeRegister, ConstantSql.hrm_tra_sp_get_TraineeRegister, UserLogin, ref status).ToList();

                var repo_UserApproved = new CustomBaseRepository <Sys_UserApprove>(unitOfWork);
                var lstUserApproved   = repo_UserApproved.GetAll().Where(s => s.IsDelete != null).ToList();

                if (selectedIds.Count > 0)
                {
                    lstTraineeRegister = lstTraineeRegister.Where(s => selectedIds.Contains(s.ID)).ToList();
                }

                foreach (var item in lstTraineeRegister)
                {
                    #region Check Loại Người Duyệt
                    if (item.UserApproveID1 != null && item.UserApproveID1.Value == UserId)
                    {
                        item.Status  = EnumDropDown.TraineeRegisterStatus.E_REJECTED.ToString();
                        item.Reason1 = Reason;
                        message      = Edit(item);
                    }
                    #endregion

                    #region Người duyệt cuối
                    if (item.UserApproveID2 != null && item.UserApproveID2.Value == UserId)
                    {
                        item.Status  = EnumDropDown.TraineeRegisterStatus.E_REJECTED.ToString();
                        item.Reason2 = Reason;
                        message      = Edit(item);
                    }
                    #endregion
                }
                return(message);
            }
        }
        public Eva_PerformanceExtendEntity GetPerformanceExtendByPerID(string ID, string userLogin)
        {
            Guid perID = Guid.Empty;

            Guid.TryParse(ID, out perID);
            BaseService service = new BaseService();
            string      status  = string.Empty;

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork                = (IUnitOfWork)(new UnitOfWork(context));
                var repoEva_Performance       = new CustomBaseRepository <Eva_Performance>(unitOfWork);
                var repoEva_PerformanceExtend = new CustomBaseRepository <Eva_PerformanceExtend>(unitOfWork);

                var performance = repoEva_Performance.GetAll().Where(s => s.ID == perID).FirstOrDefault();
                var extend      = repoEva_PerformanceExtend.GetAll().Where(s => s.ID == performance.PerformanceExtendID).FirstOrDefault();

                var    result  = extend.Copy <Eva_PerformanceExtendEntity>();
                string proID   = Common.DotNetToOracle(performance.ProfileID.Value.ToString());
                var    profile = service.GetData <Hre_ProfileEntity>(proID, ConstantSql.hrm_hr_sp_get_ProfileById, userLogin, ref status).FirstOrDefault();

                if (profile != null && result == null)
                {
                    result = new Eva_PerformanceExtendEntity();
                }

                result.ProfileName        = profile.ProfileName ?? string.Empty;
                result.CodeEmp            = profile.CodeEmp ?? string.Empty;
                result.PositionName       = profile.PositionName ?? string.Empty;
                result.JobTitleName       = profile.JobTitleName ?? string.Empty;
                result.DateOfBirth        = profile.DateOfBirth;
                result.DateHire           = profile.DateHire;
                result.PayrollGroupName   = profile.PayrollGroupName ?? string.Empty;
                result.SupervisorName     = profile.SupervisorName ?? string.Empty;
                result.HighSupervisorName = profile.HighSupervisorName ?? string.Empty;
                result.WorkPlaceName      = profile.WorkPlaceName ?? string.Empty;
                result.TCountryName       = profile.TCountryName ?? string.Empty;
                result.TProvinceName      = profile.TProvinceName ?? string.Empty;
                result.Channel            = profile.Channel ?? string.Empty;
                result.Region             = profile.Region ?? string.Empty;
                result.Area         = profile.Area ?? string.Empty;
                result.DateOfEffect = profile.DateOfEffect;

                return(result);
            }
        }
Example #6
0
        /// <summary>
        /// [Chuc.Nguyen] - Lấy tất cả dữ liệu của một đối tượng bất kỳ dùng Entity
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="status"></param>
        /// <returns></returns>
        public List <TEntity> GetAllUseEntity <TEntity>(ref string status) where TEntity : class
        {
            List <TEntity> entity = null;

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repo       = new CustomBaseRepository <TEntity>(unitOfWork);
                try
                {
                    entity = repo.GetAll().ToList();
                    status = NotificationType.Success.ToString();
                }
                catch (Exception ex)
                {
                    status = NotificationType.Error + "," + ex.Message;
                }
            }

            return(entity);
        }
Example #7
0
        public void ActionSubmit(List <Guid> lstId, string status, Guid userId)
        {
            var    statusMes        = string.Empty;
            var    objTravelRequest = new List <object>();
            string UserLogin        = string.Empty;

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork            = (IUnitOfWork)(new UnitOfWork(context));
                var repoTravelRequestItem = new CustomBaseRepository <FIN_ClaimItem>(unitOfWork);
                var lstTravelRequestItem  = repoTravelRequestItem.GetAll().Where(s => s.IsDelete == null).ToList();

                var claimID    = lstTravelRequestItem.Where(s => s.ClaimID != null && lstId.Contains(s.ID)).Select(s => s.ClaimID).Distinct().FirstOrDefault();
                var userEntity = GetData <Sys_UserInfoEntity>(userId, ConstantSql.hrm_sys_sp_get_UserbyId, UserLogin, ref statusMes).FirstOrDefault();

                var claimEntity = new FIN_ClaimEntity();
                if (claimID != null)
                {
                    claimEntity = GetData <FIN_ClaimEntity>(claimID.Value, ConstantSql.hrm_hr_sp_get_ClaimById, UserLogin, ref statusMes).FirstOrDefault();
                }

                if (lstId.Count > 0)
                {
                    if (userEntity != null && claimEntity != null)
                    {
                        if (userEntity.ProfileID.Value == claimEntity.ProfileID.Value)
                        {
                            lstTravelRequestItem = lstTravelRequestItem.Where(s => lstId.Contains(s.ID)).ToList();
                            foreach (var item in lstTravelRequestItem)
                            {
                                item.Description2 = status;
                            }
                            repoTravelRequestItem.SaveChanges();
                        }
                    }
                }
            }
        }
        public void ComputeDepartment(Guid departmentID)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (UnitOfWork)(new UnitOfWork(context));
                var repoSal_SalaryDepartment = new CustomBaseRepository<Sal_SalaryDepartment>(unitOfWork);
                var repoSal_SalaryDepartmentItem = new CustomBaseRepository<Sal_SalaryDepartmentItem>(unitOfWork);
                var repoAtt_CutOffDuration = new CustomBaseRepository<Att_CutOffDurationEntity>(unitOfWork);

                Sal_SalaryDepartment item = new Sal_SalaryDepartment();
                item = repoSal_SalaryDepartment.GetById(departmentID);

                //xóa các item nếu đã tính trước đó
                List<Sal_SalaryDepartmentItem> listDepartmentItem = new List<Sal_SalaryDepartmentItem>();
                listDepartmentItem = repoSal_SalaryDepartmentItem.GetAll().Where(m => m.SalaryDepartmentID == departmentID).ToList();
                repoSal_SalaryDepartmentItem.Delete(listDepartmentItem);
                unitOfWork.SaveChanges();

                //nếu chọn theo cutoff thì lấy datefrom dateto của cutoff
                if (item.CutOffDurationID != null)
                {
                    var cutoff= repoAtt_CutOffDuration.GetById((Guid)item.CutOffDurationID);
                    item.MonthYear = cutoff.MonthYear;
                    item.DateFrom = cutoff.DateStart;
                    item.DateTo = cutoff.DateEnd;
                }

                Hashtable hasTable = new Hashtable();
                List<Sal_SalaryDepartment> listSalaryDepartment = new List<Sal_SalaryDepartment>(); 
                listSalaryDepartment.Add(item);

                ComputeSalaryDepartment(item.MonthYear, (DateTime)item.DateFrom, (DateTime)item.DateTo, listSalaryDepartment, ref hasTable);

              
            }
        }
Example #9
0
        public void ActionApprovedAll(List<Guid> lstId, string status, Guid userId)
        {
            var statusMes = string.Empty;
            var objTravelRequest = new List<object>();
            var UserLogin = string.Empty;
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoCashAdvanceItem = new CustomBaseRepository<Fin_CashAdvanceItem>(unitOfWork);
                var repoCashAdvance = new CustomBaseRepository<Fin_CashAdvance>(unitOfWork);

                var lstCashAdvanceId = repoCashAdvance.GetAll().Where(s => s.IsDelete == null && lstId.Contains(s.ID)).Select(s => s.ID).ToList();

                var lstCashAdvanceItem = repoCashAdvanceItem.GetAll().Where(s => s.IsDelete == null).ToList();

               
                    var objApprovedClaim = new List<object>();
                    objApprovedClaim.AddRange(new object[6]);
                    objApprovedClaim[4] = 1;
                    objApprovedClaim[5] = int.MaxValue - 1;
                    var lstApprovedClaim = GetData<FIN_ApproverECLAIMEntity>(objApprovedClaim, ConstantSql.hrm_fin_sp_get_ApproverECLAIM, UserLogin, ref statusMes).ToList();

                    var approvedType = FinApproverType.Fin_CashAdvance.ToString();

                    var approvedEntity = lstApprovedClaim.Where(s => s.ApprovedID != null && s.ApprovedID.Value == userId && s.ApprovedType == approvedType).FirstOrDefault();

                if(status == "E_REQUEST")
                {
                if (lstCashAdvanceId.Count > 0)
                    {
                       
                            lstCashAdvanceItem = lstCashAdvanceItem.Where(s => s.CashAdvanceID != null && lstCashAdvanceId.Contains(s.CashAdvanceID.Value)).ToList();
                            foreach (var item in lstCashAdvanceItem)
                            {
                                item.Status = status ;
                            }
                            repoCashAdvanceItem.SaveChanges();
                        

                    }
                }
                if(status == "E_APPROVED")
                {
                    if (lstCashAdvanceId.Count > 0)
                    {
                        if (approvedEntity != null)
                        {
                            lstCashAdvanceItem = lstCashAdvanceItem.Where(s => s.CashAdvanceID != null && lstCashAdvanceId.Contains(s.CashAdvanceID.Value)).ToList();
                            foreach (var item in lstCashAdvanceItem)
                            {
                                item.Status = status + "_" + approvedEntity.OrderNo.ToString();
                            }
                            repoCashAdvanceItem.SaveChanges();
                        }

                    }
                }
                    
                
            }
        }
Example #10
0
        public DataErrorCode SendMaToNextApproved(string host, Guid recordID, Guid userApprovedID)
        {
            using (var context = new VnrHrmDataContext())
            {
                string statusMess = string.Empty;
                var Services = new BaseService();
                string status = string.Empty;
                var UserLogin = string.Empty;
                string typeApprover = FinApproverType.Fin_CashAdvance.ToString();

                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoSys_UserApprove = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);
                var repoFin_Approver = new CustomBaseRepository<FIN_ApproverECLAIM>(unitOfWork);
                var lstApprover = repoFin_Approver.GetAll().Where(s => s.IsDelete == null).ToList();

                var repoSys_UserInfo = new CustomBaseRepository<Sys_UserInfo>(unitOfWork);
                var repoSys_ConfigProcessApprove = new CustomBaseRepository<Sys_ConfigProcessApprove>(unitOfWork);
                var repoSys_TemplateSendMail = new CustomBaseRepository<Sys_TemplateSendMail>(unitOfWork);

                var repo_JobTitle = new CustomBaseRepository<Cat_JobTitle>(unitOfWork);
                var lstJobTitle = repo_JobTitle.GetAll().Where(s => s.IsDelete == null).ToList();
                var repoOrg = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var lstOrg = repoOrg.GetAll().Where(s => s.IsDelete == null).ToList();
                var repoProfile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var lstProfile = repoProfile.GetAll().Where(s => s.IsDelete == null).ToList();

                var repoCashItem = new CustomBaseRepository<Fin_CashAdvanceItem>(unitOfWork);
                var totalItem = repoCashItem.GetAll().Where(s => s.CashAdvanceID == recordID && s.Status.Contains("E_APPROVED")).Sum(s => s.Amount);

                var repoFIN_TravelRequest = new CustomBaseRepository<Fin_CashAdvance>(unitOfWork);
                var record = repoFIN_TravelRequest.FindBy(s => s.ID == recordID).FirstOrDefault();

                string _typeTemplate = EnumDropDown.EmailType.E_REQUEST_CASHADVANCE.ToString();
                var template = repoSys_TemplateSendMail.FindBy(s => s.Type == _typeTemplate).FirstOrDefault();
                if (template == null)
                    return DataErrorCode.Error_NoTemplateMail;

                #region KT nếu là nguoi duyet cuoi thì gui email lại cho người yêu cầu duyệt
                if (userApprovedID == Guid.Empty)
                {
                   
                    if (record != null)
                    {
                        string _typeTemplateApproved = EnumDropDown.EmailType.E_APPROVED_CASHADVANCE.ToString();
                        var typeTemplateApproved = repoSys_TemplateSendMail.FindBy(s => s.Type == _typeTemplateApproved).FirstOrDefault();
                        if (typeTemplateApproved == null)
                        {
                            return DataErrorCode.Error_NoTemplateMail;

                        }
                        var lastApprover = lstApprover.Where(s => s.ProfileID == record.ProfileID && s.ApprovedID != null).OrderByDescending(s => s.OrderNo).FirstOrDefault();
                        var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == lastApprover.ApprovedID.Value).FirstOrDefault();
                        var lastProfileEntity = lstProfile.Where(s => userInfo != null && userInfo.ProfileID.Value == s.ID).FirstOrDefault();
                        var profileEntity = lstProfile.Where(s => record.ProfileID != null && record.ProfileID.Value == s.ID).FirstOrDefault();
                        if (profileEntity != null)
                        {
                            var jobTitleEntity = lstJobTitle.Where(s => profileEntity.JobTitleID != null && s.ID == profileEntity.JobTitleID.Value).FirstOrDefault();
                            var orgEntity = lstOrg.Where(s => profileEntity.OrgStructureID != null && s.ID == profileEntity.OrgStructureID.Value).FirstOrDefault();
                            if (template != null)
                            {
                                string MailTo = profileEntity.Email;
                                string urlClickHere = host + "#Hrm_Main_Web/Fin_SendMailApprovedCashAdvance/DetailTravelRequest/" + recordID + "#NewTab";

                                try
                                {
                                    #region magreData

                                    string[] strsParaKey = null;
                                    string[] strsParaValues = null;
                                    strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_PROFILENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_AREA.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCECODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_TOTALADVANCE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_DENIES.ToString(),
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_REJECTLINK.ToString(), 

                                    };
                                    strsParaValues = new string[] 
                                    { 
                                        lastProfileEntity != null? lastProfileEntity.ProfileName : string.Empty, 
                                        jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        profileEntity.ProfileName, 
                                        record.CashAdvanceName, 
                                        record.Code != null ? record.Code:"" , 
                                        totalItem.ToString(),
                                        "Đã được duyệt.",
                                        "",
                                        ""
                                    };
                                    string body = LibraryService.ReplaceContentFile(typeTemplateApproved.Content, strsParaKey, strsParaValues);

                                    #endregion
                                    string titleMail = typeTemplateApproved.Subject;
                                    bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                    if (isSuccess)
                                        return DataErrorCode.Success;
                                    else
                                        return DataErrorCode.Error;
                                }
                                catch (Exception ex)
                                {

                                    throw;
                                }

                            }

                        }
                    }


                    return DataErrorCode.Success;
                }
                #endregion

                var approverEntity = repoFin_Approver.GetAll().Where(s => s.IsDelete == null && s.ID == userApprovedID).FirstOrDefault();

                if (approverEntity != null && approverEntity.OrderNo != null)
                {
                    var profileInfoEntity = lstProfile.Where(s => s.ID == approverEntity.ProfileID.Value).FirstOrDefault();
                    var jobTitleEntity = lstJobTitle.Where(s => profileInfoEntity.JobTitleID != null && s.ID == profileInfoEntity.JobTitleID.Value).FirstOrDefault();
                    var orgEntity = lstOrg.Where(s => profileInfoEntity.OrgStructureID != null && s.ID == profileInfoEntity.OrgStructureID.Value).FirstOrDefault();
                    var lastApprover = lstApprover.Where(s => s.ProfileID == approverEntity.ProfileID && s.ApprovedType == typeApprover && s.ApprovedID != null).OrderByDescending(s => s.OrderNo).FirstOrDefault();

                    var lstApproverByClaim = lstApprover.Where(s => s.ProfileID == approverEntity.ProfileID && s.ApprovedType == typeApprover && s.ApprovedID != null && s.OrderNo > approverEntity.OrderNo).OrderBy(s => s.OrderNo).ToList();
                    var nextApprover = new FIN_ApproverECLAIM();

                    foreach (var item in lstApproverByClaim)
                    {
                        if (approverEntity.OrderNo == item.OrderNo)
                        {
                            continue;
                        }
                        nextApprover = item;
                        break;
                    }

                    #region Nguoi duyet cuoi
                    if (lastApprover != null && lastApprover.OrderNo != null && lastApprover.OrderNo == approverEntity.OrderNo)
                    {
                        var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == approverEntity.ApprovedID.Value).FirstOrDefault();

                        if (userInfo != null)
                        {
                            var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();

                            var profileRequester = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(approverEntity.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();

                            if (template != null)
                            {
                                try
                                {
                                    string MailTo = profileEntity.Email;

                                    string urlClickHere = host + "#Hrm_Main_Web/Fin_SendMailApprovedCashAdvance/DetailTravelRequest/" + recordID + "#NewTab";

                                    string linkcontent = string.Empty;

                                    string linkcontentReject = string.Empty;

                                    linkcontent += "Nhấn vào " + "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessApprovedPage"
                                   + "?loginID=" + approverEntity.ApprovedID
                                   + "&userApprovedID=" + Guid.Empty
                                   + "&recordID=" + recordID
                                   + "'>đây" + "<a/>" + " để đồng ý.";

                                    linkcontentReject += "Nhấn vào " + "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessRejectPage"
                            + "?loginID=" + approverEntity.ApprovedID
                            + "&userApprovedID=" + approverEntity.ID
                            + "&recordID=" + recordID
                            + "'>đây" + "<a/>" + " để từ chối.";

                                    #region magreData

                                    string[] strsParaKey = null;
                                    string[] strsParaValues = null;
                                    strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_PROFILENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_AREA.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCECODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_TOTALADVANCE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_DENIES.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_REJECTLINK.ToString(), 
                                    };
                                    strsParaValues = new string[] 
                                    { 
                                        profileEntity.ProfileName, 
                                         jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        profileInfoEntity != null ? profileInfoEntity.ProfileName : string.Empty, 
                                        record.CashAdvanceName, 
                                        record.Code,
                                        totalItem.ToString(),
                                        "",
                                        linkcontent,
                                        linkcontentReject
                                    };
                                    string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);
                                    #endregion

                                    string titleMail = template.Subject;
                                    bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                    if (isSuccess)
                                        return DataErrorCode.Success;
                                    else
                                        return DataErrorCode.Error;
                                }
                                catch (Exception ex)
                                {

                                    throw;
                                }
                            }

                        }
                    }
                    #endregion

                  //  var nextApprover = repoFin_Approver.GetAll().Where(s => s.IsDelete == null && s.ProfileID == approverEntity.ProfileID && s.ApprovedType == typeApprover && s.OrderNo == approverEntity.OrderNo + 1).FirstOrDefault();

                    if (nextApprover != null)
                    {
                        var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == approverEntity.ApprovedID.Value).FirstOrDefault();

                        var nextUserInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == nextApprover.ApprovedID.Value).FirstOrDefault();

                        if (userInfo != null)
                        {
                            var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();
                            var profileEntityForRecord = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(nextUserInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();
                            if (profileEntity != null)
                            {
                                if (template != null)
                                {
                                    try
                                    {
                                        string MailTo = profileEntity.Email;

                                        string urlClickHere = host + "#Hrm_Main_Web/Fin_SendMailApprovedCashAdvance/DetailTravelRequest/" + recordID + "#NewTab";

                                        string linkcontent = string.Empty;
                                        string linkcontentReject = string.Empty;


                                        var name = nextUserInfo != null ? nextUserInfo.UserInfoName : nextUserInfo.UserLogin;

                                        linkcontent += "Nhấn vào " + "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessApprovedPage"
                                       + "?loginID=" + nextApprover.ApprovedID
                                       + "&userApprovedID=" + nextApprover.ID
                                       + "&recordID=" + recordID
                                       + "'>đây" + "<a/>" + " để đồng ý.";

                                        linkcontentReject += "Nhấn vào " + "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessRejectPage"
                                  + "?loginID=" + approverEntity.ApprovedID
                                  + "&userApprovedID=" + approverEntity.ID
                                  + "&recordID=" + recordID
                                  + "'>đây" + "<a/>" + " để từ chối.";

                                        #region magreData

                                        string[] strsParaKey = null;
                                        string[] strsParaValues = null;
                                        strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_PROFILENAME.ToString(),
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_AREA.ToString(), 
 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCECODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_TOTALADVANCE.ToString(), 

                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_DENIES.ToString(), 

                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_REJECTLINK.ToString(), 

                                    };
                                        strsParaValues = new string[] 
                                    { 
                                        profileEntity.ProfileName, 
                                        jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        profileInfoEntity != null ? profileInfoEntity.ProfileName : string.Empty, 
                                        record.CashAdvanceName, 
                                        record.Code,
                                        totalItem.ToString(),
                                        "",
                                        linkcontent ,
                                        linkcontentReject
                        
                                    };
                                        string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);
                                        #endregion

                                        string titleMail = template.Subject;
                                        bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                        if (isSuccess)
                                            return DataErrorCode.Success;
                                        else
                                            return DataErrorCode.Error;
                                    }
                                    catch (Exception ex)
                                    {
                                        return DataErrorCode.Error_NoConfigMail;
                                    }

                                }
                            }

                        }
                    }
                    else {
                        var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == approverEntity.ApprovedID.Value).FirstOrDefault();
                        if(userInfo != null)
                        {
                            var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();
                            if (profileEntity != null)
                            {
                                if(template != null)
                                {
                                    try
                                    {
                                        string MailTo = profileEntity.Email;

                                        string urlClickHere = host + "#Hrm_Main_Web/Fin_SendMailApprovedCashAdvance/DetailTravelRequest/" + recordID + "#NewTab";

                                        string linkcontent = string.Empty;
                                        string linkcontentReject = string.Empty;

                                        linkcontent += "Nhấn vào " + "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessApprovedPage"
                                       + "?loginID=" + approverEntity.ApprovedID
                                       + "&userApprovedID=" + Guid.Empty
                                       + "&recordID=" + recordID
                                       + "'>đây" + "<a/>" + " để đồng ý.";


                                        linkcontentReject += "Nhấn vào " + "<a href='" + host + "Fin_ApprovedTravelRequest/ProcessRejectPage"
                                  + "?loginID=" + approverEntity.ApprovedID
                                  + "&userApprovedID=" + approverEntity.ID
                                  + "&recordID=" + recordID
                                  + "'>đây" + "<a/>" + " để từ chối.";

                                        #region magreData

                                        string[] strsParaKey = null;
                                        string[] strsParaValues = null;
                                        strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_PROFILENAME.ToString(),
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_AREA.ToString(), 
 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCECODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_TOTALADVANCE.ToString(), 

                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_DENIES.ToString(), 

                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_REJECTLINK.ToString(), 

                                    };
                                        strsParaValues = new string[] 
                                    { 
                                        profileEntity.ProfileName, 
                                        jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        profileInfoEntity != null ? profileInfoEntity.ProfileName : string.Empty, 
                                        record.CashAdvanceName, 
                                        record.Code,
                                        totalItem.ToString(),
                                        "",
                                        linkcontent ,
                                        linkcontentReject
                        
                                    };
                                        string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);
                                        #endregion

                                        string titleMail = template.Subject;
                                        bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                        if (isSuccess)
                                            return DataErrorCode.Success;
                                        else
                                            return DataErrorCode.Error;
                                    }
                                    catch (Exception ex)
                                    {
                                        return DataErrorCode.Error_NoConfigMail;
                                    }
                                }
                            }                            
                        }
                    
                    }

                }
                return DataErrorCode.Error;
            }
        }
Example #11
0
        public DataTable ReportTransferBonusHold(List<Hre_ProfileEntity> lstProfile, List<String> lstElementCode, DateTime monthStart, DateTime monthEnd, string UserLogin, bool isCreateTemplate, String nameReport)
        {
            using (var context = new VnrHrmDataContext())
            {

                #region Get Data
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoOrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var repoCostCentre = new CustomBaseRepository<Cat_CostCentre>(unitOfWork);
                var repoElement = new CustomBaseRepository<Cat_Element>(unitOfWork);

                //ds phần tử
                string statusEl = string.Empty;
                var lstObjElement = new List<object>();
                lstObjElement.Add(null);
                lstObjElement.Add(null);
                lstObjElement.Add(null);
                lstObjElement.Add(null);
                lstObjElement.Add(null);
                lstObjElement.Add(1);
                lstObjElement.Add(int.MaxValue - 1);
                List<Cat_ElementEntity> lstElement = GetData<Cat_ElementEntity>(lstObjElement, ConstantSql.hrm_cat_sp_get_Element, UserLogin, ref statusEl);

                lstElement = lstElement.Where(m => lstElementCode.Contains(m.ElementCode)).ToList(); ;
                DataTable tb = GetSchemaTransferBonusHold(lstElement, nameReport);
                if (isCreateTemplate)
                {
                    return tb.ConfigTable();
                }

                //ds thông tin lương
                string statusSI = string.Empty;
                var lstObjSalInfo = new List<object>();
                lstObjSalInfo.AddRange(new object[8]);
                lstObjSalInfo[6] = 1;
                lstObjSalInfo[7] = Int32.MaxValue - 1;
                List<Sal_SalaryInformationEntity> lstSalaryInformation = GetData<Sal_SalaryInformationEntity>(lstObjSalInfo, ConstantSql.hrm_sal_sp_get_Sal_SalaryInformation, UserLogin, ref statusSI);

                //Bảng lương
                string statusTb = string.Empty;
                List<object> listModelprtb = new List<object>();
                listModelprtb = new List<object>();
                listModelprtb.AddRange(new object[6]);
                listModelprtb[2] = monthStart;
                listModelprtb[3] = monthEnd;
                listModelprtb[4] = 1;
                listModelprtb[5] = Int32.MaxValue - 1;
                List<Sal_PayrollTableEntity> listPayrollTable = GetData<Sal_PayrollTableEntity>(listModelprtb, ConstantSql.hrm_sal_sp_get_PayrollTable, UserLogin, ref statusTb);

                List<object> listModel = new List<object>();
                listModel.AddRange(new object[10]);
                listModel[4] = monthStart;
                listModel[5] = monthEnd;
                listModel[8] = 1;
                listModel[9] = Int32.MaxValue - 1;
                List<Sal_HoldSalaryEntity> listHoldSalary = GetData<Sal_HoldSalaryEntity>(listModel, ConstantSql.hrm_sal_sp_get_HoldSalary, UserLogin, ref statusTb);

                string statusTbit = string.Empty;
                List<object> listModelprtbit = new List<object>();
                listModelprtbit = new List<object>();
                listModelprtbit.AddRange(new object[9]);
                listModelprtbit[2] = monthStart;
                listModelprtbit[3] = monthEnd;
                listModelprtbit[7] = 1;
                listModelprtbit[8] = Int32.MaxValue - 1;
                List<Sal_PayrollTableItemEntity> listPayrollTableItem = GetData<Sal_PayrollTableItemEntity>(listModelprtbit, ConstantSql.hrm_sal_sp_get_PayrollTableItem, UserLogin, ref statusTbit);
                listPayrollTableItem = listPayrollTableItem.Where(it => it.Value != null && it.Value != string.Empty).ToList();

                var lstOrgStructure = repoOrgStructure.GetAll().Where(org => org.IsDelete == null).Select(org => new { org.ID, org.Code, org.OrgStructureName }).ToList();
                var lstCostcentre = repoCostCentre.GetAll().Where(cost => cost.IsDelete == null).Select(cost => new { cost.ID, cost.Code, cost.CostCentreName }).ToList();
                #endregion

                #region Process

                lstProfile = lstProfile.Where(m => listHoldSalary.Any(t => t.ProfileID == m.ID)).ToList();
                foreach (var profile in lstProfile)
                {
                    if (profile == null)
                    {
                        continue;
                    }

                    DataRow dr = tb.NewRow();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeEmp] = profile.CodeEmp;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.ProfileName] = profile.ProfileName;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_UNIT] = profile.E_UNIT;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_DIVISION] = profile.E_DIVISION;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_DEPARTMENT] = profile.E_DEPARTMENT;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_TEAM] = profile.E_TEAM;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_SECTION] = profile.E_SECTION;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.WorkingPlace] = profile.WorkPlaceName;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeTax] = profile.CodeTax;

                    #region Add lý do bị giữ lương, ngày nghỉ việc và ngày bắt đầu giữ lương.
                    string remark = string.Empty;
                    string dayleave = string.Empty;
                    string monthsalary = string.Empty;
                    Sal_HoldSalaryEntity HoldSalaryByID = listHoldSalary.Where(m => m.ProfileID == profile.ID).FirstOrDefault();
                    remark = HoldSalaryByID.DayLeave != null ? "Nghỉ " + HoldSalaryByID.DayLeave.ToString() + " ngày\n" : string.Empty;
                    remark += HoldSalaryByID.IsLeaveContinuous == true ? "Nghỉ liên tục 3 ngày\n" : string.Empty;
                    remark += HoldSalaryByID.Terminate == true ? "Có thông tin nghỉ việc" : string.Empty;
                    dayleave = HoldSalaryByID.DayLeave != null ? HoldSalaryByID.DayLeave.ToString() : string.Empty;
                    monthsalary = HoldSalaryByID.MonthSalary != null ? HoldSalaryByID.MonthSalary.ToString() : string.Empty;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.MonthHoldSalary] = HoldSalaryByID.MonthSalary;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.Description] = remark;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DayLeave] = dayleave;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.MonthSalary] = monthsalary;
                    if (profile.DateQuit != null)
                    {
                        dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateQuit] = profile.DateQuit;
                    }


                    #endregion


                    var salaryInfo = lstSalaryInformation.Where(s => s.ProfileID == profile.ID).FirstOrDefault();
                    if (salaryInfo != null)
                    {
                        dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BankName] = salaryInfo.BankName;
                        dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BankAccountNo] = salaryInfo.AccountNo;
                    }

                    if (profile.DateHire != null)
                    {
                        dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateHire] = profile.DateHire.Value;
                    }

                    var orgStructure = lstOrgStructure.Where(org => org.ID == profile.OrgStructureID).FirstOrDefault();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureCode] = orgStructure != null ? orgStructure.Code : string.Empty;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureName] = orgStructure != null ? orgStructure.OrgStructureName : string.Empty;

                    var costcentre = lstCostcentre.Where(cost => cost.ID == profile.CostCentreID).FirstOrDefault();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenterCode] = costcentre != null ? costcentre.Code : string.Empty;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenter] = costcentre != null ? costcentre.CostCentreName : string.Empty;

                    //Bảng lương mỗi profile
                    var payrollTbID_Profile = listPayrollTable.Where(sal => sal.ProfileID == profile.ID).Select(sal => sal.ID).FirstOrDefault();
                    var payrollTbItem_Profile = listPayrollTableItem.Where(salit => salit.PayrollTableID == payrollTbID_Profile).ToList();
                    if (payrollTbItem_Profile != null && payrollTbItem_Profile.Count > 0)
                    {
                        foreach (var element in lstElementCode)
                        {
                            var prItem = payrollTbItem_Profile.Where(salIt => salIt.Code == element).FirstOrDefault();
                            if (prItem != null)
                            {
                                if (prItem.ValueType != null && prItem.ValueType.ToUpper() == typeof(Double).Name.ToUpper())
                                {
                                    dr[element] = Convert.ToDouble(prItem.Value);
                                }
                                else if (prItem.ValueType != null && prItem.ValueType.ToUpper() == typeof(DateTime).Name.ToUpper())
                                {
                                    dr[element] = Convert.ToDateTime(prItem.Value);
                                }
                                else
                                    dr[element] = prItem.Value;
                            }
                        }
                    }
                    tb.Rows.Add(dr);
                }
                #endregion

                var configs = new Dictionary<string, Dictionary<string, object>>();
                var config90 = new Dictionary<string, object>();
                var config130 = new Dictionary<string, object>();
                var config100 = new Dictionary<string, object>();
                config90.Add("width", 90);
                config100.Add("width", 100);
                config130.Add("width", 130);
                configs.Add(Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeEmp, config90);
                configs.Add(Sal_ReportBasicSalaryMonthlyEntity.FieldNames.ProfileName, config130);
                configs.Add(Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateHire, config100);
                configs.Add(Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureCode, config100);
                configs.Add(Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureName, config100);
                configs.Add(Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenter, config100);
                configs.Add(Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenterCode, config100);

                return tb.ConfigTable(configs);
            }
        }
Example #12
0
        public DataTable GetReportProfileInformation(List<Guid> listOrgID, DateTime monthStart, DateTime monthEnd,
            string codeEmp, string profileName, bool isCreateTemplate, string nameReport, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var status = string.Empty;
                var objContractExtend = new List<object>();
                objContractExtend.AddRange(new object[10]);
                objContractExtend[8] = 1;
                objContractExtend[9] = int.MaxValue - 1;
                var lstContractExtend = GetData<Hre_ContractExtendEntity>(objContractExtend, ConstantSql.hrm_hr_sp_get_ContractExtendList, userLogin, ref status).ToList();
                IUnitOfWork unitOfWork = new UnitOfWork(context);
                var repoCat_ContractType = new CustomBaseRepository<Cat_ContractType>(unitOfWork);
                var repoHre_Contract = new CustomBaseRepository<Hre_Contract>(unitOfWork);
                var repoHre_AppendixContract = new CustomBaseRepository<Hre_AppendixContract>(unitOfWork);
                var repoCat_OrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var repoCat_OrgStructureType = new CustomBaseRepository<Cat_OrgStructureType>(unitOfWork);

                var lstContracType = repoCat_ContractType.FindBy(s => s.IsDelete == null).ToList();
                DataTable tb = GetSchema_ProfileInformation(nameReport, lstContracType);

                if (isCreateTemplate)
                {
                    return tb.ConfigTable();
                }
              
                List<object> listModel = new List<object>();

                listModel = new List<object>();
                listModel.AddRange(new object[18]);
                listModel[16] = 1;
                listModel[17] = Int32.MaxValue - 1;
                List<Hre_ProfileEntity> lstProfile = GetData<Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_Profile, userLogin, ref status);

                //var profileQueryable = unitOfWork.CreateQueryable<Hre_Profile>(Guid.Empty,
                //    d => d.DateHire >= monthStart && d.DateHire <= monthEnd);

                if (!string.IsNullOrWhiteSpace(codeEmp))
                {
                    lstProfile = lstProfile.Where(d => d.CodeEmp.Contains(codeEmp)).ToList();
                }

                if (!string.IsNullOrWhiteSpace(profileName))
                {
                    lstProfile = lstProfile.Where(d => d.ProfileName.Contains(profileName)).ToList();
                }

                if (listOrgID != null && listOrgID.Count() > 0)
                {
                    lstProfile = lstProfile.Where(d => d.OrgStructureID.HasValue && listOrgID.Contains(d.OrgStructureID.Value)).ToList();
                }

                lstProfile = lstProfile.Where(d => (DateTime?)d.DateHire >= monthStart && (DateTime?)d.DateHire <= monthEnd).ToList();





                //var profileQueryable = unitOfWork.CreateQueryable<Hre_Profile>(Guid.Empty,
                //    d => d.DateHire >= monthStart && d.DateHire <= monthEnd);

                //if (!string.IsNullOrWhiteSpace(codeEmp))
                //{
                //    profileQueryable = profileQueryable.Where(d => d.CodeEmp.Contains(codeEmp));
                //}

                //if (!string.IsNullOrWhiteSpace(profileName))
                //{
                //    profileQueryable = profileQueryable.Where(d => d.ProfileName.Contains(profileName));
                //}

                //if (listOrgID != null && listOrgID.Count() > 0)
                //{
                //    profileQueryable = profileQueryable.Where(d => d.OrgStructureID.HasValue && listOrgID.Contains(d.OrgStructureID.Value));
                //}

                //List<Hre_ProfileEntity> lstProfile = profileQueryable.Select(d => new Hre_ProfileEntity
                //{
                //    ID = d.ID,
                //    CodeEmp = d.CodeEmp,
                //    CodeAttendance = d.CodeAttendance,
                //    ProfileName = d.ProfileName,
                //    DateOfBirth = d.DateOfBirth,
                //    Gender = d.Gender,
                //    PlaceOfBirth = d.PlaceOfBirth,
                //    PAddress = d.PAddress,
                //    IDNo = d.IDNo,
                //    IDDateOfIssue = d.IDDateOfIssue,
                //    IDPlaceOfIssue = d.IDPlaceOfIssue,
                //    DateHire = d.DateHire,
                //    DateQuit = d.DateQuit,
                //    StatusSyn = d.StatusSyn,
                //    PositionName = d.Cat_Position.PositionName,
                //    SalaryClassName = d.Cat_SalaryClass.SalaryClassName,
                //    EducationLevelName = d.Cat_NameEntity.NameEntityName,
                //    GraduatedLevelName = d.Cat_NameEntity1.NameEntityName,
                //    CostCentreName = d.Cat_CostCentre.CostCentreName,
                //    EthnicGroupName = d.Cat_EthnicGroup.EthnicGroupName,
                //    OrgStructureID=d.OrgStructureID


                //}).ToList();

                #region code BC
                List<Guid> lstProfileIDs = lstProfile.Select(m => m.ID).Distinct().ToList();
                string E_APPROVED = HRM.Infrastructure.Utilities.EnumDropDown.Status.E_APPROVED.ToString();

                var lstContractAll = new List<Hre_Contract>().Select(m => new
                {
                    m.ID,
                    m.ContractTypeID,
                    m.ProfileID,
                    m.DateStart,
                    m.DateEnd,
                    m.ContractNo
                }).ToList();

                foreach (var lstProfileID in lstProfileIDs.Chunk(1000))
                {
                    lstContractAll.AddRange(unitOfWork.CreateQueryable<Hre_Contract>(Guid.Empty, m => m.Status == E_APPROVED
                        && lstProfileID.Contains(m.ProfileID) && m.DateStart <= monthEnd && m.DateEnd >= monthStart).Select(m => new
                        {
                            m.ID,
                            m.ContractTypeID,
                            m.ProfileID,
                            m.DateStart,
                            m.DateEnd,
                            m.ContractNo
                        }).ToList());
                }

                List<Guid> lstContractIDs = lstContractAll.Select(m => m.ID).ToList();
                var lstAppendixContract = new List<Hre_AppendixContract>().Select(m => new
                {
                    m.ID,
                    m.ContractID,
                    m.Code,
                    m.DateofEffect,
                    m.DateEndAppendixContract
                }).ToList();

                foreach (var lstContractID in lstContractIDs.Chunk(1000))
                {
                    lstAppendixContract.AddRange(unitOfWork.CreateQueryable<Hre_AppendixContract>(Guid.Empty,
                        m => lstContractID.Contains(m.ContractID)).Select(m => new
                        {
                            m.ID,
                            m.ContractID,
                            m.Code,
                            m.DateofEffect,
                            m.DateEndAppendixContract
                        }).ToList());
                }


                var lstOrg = repoCat_OrgStructure.GetAll().ToList();
                var orgTypes = repoCat_OrgStructureType.GetAll().ToList();


                int stt = 0;
                foreach (var profile in lstProfile)
                {
                    stt++;
                    
                    DataRow dr = tb.NewRow();
                    dr["Stt"] = stt;
                    dr["CodeEmp"] = profile.CodeEmp;
                    dr["ProfileName"] = profile.ProfileName;

                    dr["NameFamily"] = profile.NameFamily;
                    dr["FirstName"] = profile.FirstName;
                    dr["CodeAttendance"] = profile.CodeAttendance;
                    dr["DateApplyAttendanceCode"] = profile.DateApplyAttendanceCode != null ? profile.DateApplyAttendanceCode.Value.ToString("dd/MM/yyyy") : null;
                    dr["DateHire"] = profile.DateHire != null ? profile.DateHire.Value.ToString("dd/MM/yyyy") : null;
                    dr["DateEndProbation"] = profile.DateEndProbation != null ? profile.DateEndProbation.Value.ToString("dd/MM/yyyy") : null;
                    dr["CodeTax"] = profile.CodeTax;
                    dr["DateOfIssuedTaxCode"] = profile.DateOfIssuedTaxCode != null ? profile.DateOfIssuedTaxCode.Value.ToString("dd/MM/yyyy") : null;
                    dr["ContractTypeID"] = profile.ContractTypeID;
                    dr["IDNo"] = profile.IDNo;
                    dr["IDDateOfIssue"] = profile.IDDateOfIssue != null ? profile.IDDateOfIssue.Value.ToString("dd/MM/yyyy") : null;
                    dr["IDPlaceOfIssue"] = profile.IDPlaceOfIssue;
                    dr["Origin"] = profile.Origin;
                    dr["Gender"] = profile.Gender;
                    dr["BirthDay"] = profile.Birthday;
                    dr["DayOfBirth"] = profile.DayOfBirth;
                    dr["MonthOfBirth"] = profile.MonthOfBirth;
                    dr["YearOfBirth"] = profile.YearOfBirth;
                    dr["PlaceOfBirth"] = profile.PlaceOfBirth;
                    dr["CountryName"] = profile.NationalityName;
                    dr["NameEnglish"] = profile.NameEnglish;
                    dr["Cat_ReqDocument"] = profile.StoredDocuments;
                    dr["MarriageStatus"] = profile.MarriageStatus;
                    dr["Cat_NameEntity-Name"] = profile.GraduatedLevelName;
                    dr["Cat_NameEntity1-Name"] = profile.EducationLevelName;
                    dr["Cat_Region-Name"] = profile.RegionName;
                    dr["Cat_EthnicGroup-Name"] = profile.EthnicGroupName;
                    dr["Cat_Religion-Name"] = profile.ReligionName;
                    dr["Height(Cm)"] = profile.Height;
                    dr["Weight(Kg)"] = profile.Weight;
                    dr["BloodType"] = profile.BloodType;
                    dr["SocialInsIssuePlace_WorkPlace"] = profile.WorkPlaceName;

                    dr["Notes"] = profile.Notes;
                    dr["Email"] = profile.Email;
                    dr["Email2"] = profile.Email2;
                    dr["Cellphone"] = profile.Cellphone;
                    dr["ContactPhone1"] = profile.HomePhone;
                    dr["ContactPhone2"] = profile.BusinessPhone;
                    dr["Cat_Country1-Name"] = profile.TCountryName;
                    dr["Cat_Province8-Name"] = profile.TProvinceName;
                    dr["Cat_Distric3-Name"] = profile.TDistrictName;
                    dr["Cat_Village-Name"] = profile.TVillageName;
                    dr["Taddress"] = profile.TAddress;
                    dr["Cat_Contry2-Name"] = profile.PCountryName;
                    dr["Cat_Province7-Name"] = profile.PProvinceName;
                    dr["Cat_District1-Name"] = profile.PDistrictName;
                    dr["Cat_Village1-Name"] = profile.PVillageName;
                    dr["Paddress"] = profile.PAddress;
                    dr["AddressEmergency"] = profile.AddressEmergency;
                    dr["DateOfEffect"] = profile.DateOfEffect != null ? profile.DateOfEffect.Value.ToString("dd/MM/yyyy") : null;






                    dr["Cat_OrgStructure-Name"] = profile.E_DEPARTMENT;

                    dr["E_UNIT"] = profile.E_UNIT;

                    dr["E_TEAM"] = profile.E_TEAM;

                    dr["E_DIVISION"] = profile.E_DIVISION;

                    dr["E_SECTION"] = profile.E_SECTION;


                    dr["Cat_Shop-Name"] = profile.ShopName;
                    dr["Cat_JobTitle-Name"] = profile.JobTitleName;
                    dr["Cat_Position-Name"] = profile.PositionName;
                    dr["Hre_Profile2-CodeEmp"] = profile.SupervisorName;
                    dr["Hre_Profile3-CodeEmp"] = profile.HighSupervisorName;
                    dr["Cat_EmployeeType-Name"] = profile.EmployeeTypeName;
                    dr["Cat_PayrollGroup-Name"] = profile.PayrollGroupName;
                    dr["Cat_SalaryClassType-Name"] = profile.SalaryClassCode;
                    dr["Cat_CostCentre-Name"] = profile.CostCentreCode;
                    dr["Cat_WorkPlace-WorkPlaceName"] = profile.WorkPlaceName;
                    dr["PassportNo"] = profile.PassportNo;
                    dr["PassportPlaceOfIssue"] = profile.PassportPlaceOfIssue;
                    dr["PassportDateOfIssue"] = profile.PassportDateOfIssue != null ? profile.PassportDateOfIssue.Value.ToString("dd/MM/yyyy") : null;
                    dr["PassportDateOfExpiry"] = profile.PassportDateOfExpiry;
                    dr["WorkPermitStatus"] = profile.WorkPermitStatus;
                    dr["WorkPermitNo"] = profile.WorkPermitNo;
                    dr["WorkPermitInsDate"] = profile.WorkPermitInsDate != null ? profile.WorkPermitInsDate.Value.ToString("dd/MM/yyyy") : null;
                    dr["WorkPermitExpiredDate"] = profile.WorkPermitExpiredDate != null ? profile.WorkPermitExpiredDate.Value.ToString("dd/MM/yyyy") : null;
                    dr["IsRegisterSocialIns"] = profile.IsRegisterSocialIns;
                    dr["SocialInsNo"] = profile.SocialInsNo;
                    dr["SocialInsOldNo"] = profile.SocialInsOldNo;
                    dr["SocialInsIssueDate"] = profile.SocialInsIssueDate != null ? profile.SocialInsIssueDate.Value.ToString("dd/MM/yyyy") : null;
                    dr["SocialInsDateReg"] = profile.SocialInsDateReg != null ? profile.SocialInsDateReg.Value.ToString("dd/MM/yyyy") : null;
                    dr["SocialInsIssuePlace"] = profile.SocialInsIssuePlace;
                    dr["ReceiveSocialIns"] = profile.ReceiveSocialIns;
                    dr["ReceiveSocialInsDate"] = profile.ReceiveSocialInsDate != null ? profile.ReceiveSocialInsDate.Value.ToString("dd/MM/yyyy") : null;
                    dr["SocialInsSubmitBookStatus"] = profile.SocialInsSubmitBookStatus;
                    dr["SocialInsSubmitBookDate"] = profile.SocialInsSubmitBookDate != null ? profile.SocialInsSubmitBookDate.Value.ToString("dd/MM/yyyy") : null;
                    dr["IsRegisterHealthIns"] = profile.IsRegisterHealthIns;
                    dr["HealthInsNo"] = profile.HealthInsNo;
                    dr["HealthInsIssueDate"] = profile.HealthInsIssueDate != null ? profile.HealthInsIssueDate.Value.ToString("dd/MM/yyyy") : null;
                    dr["HealthInsExpiredDate"] = profile.HealthInsExpiredDate != null ? profile.HealthInsExpiredDate.Value.ToString("dd/MM/yyyy") : null;
                    dr["HealthTreatmentPlace"] = profile.HealthTreatmentPlace;
                    dr["HealthTreatmentPlaceCode"] = profile.HealthTreatmentPlaceCode;
                    dr["IsRegisterUnEmploymentIns"] = profile.IsRegisterUnEmploymentIns;
                    dr["UnEmpInsDateReg"] = profile.UnEmpInsDateReg != null ? profile.UnEmpInsDateReg.Value.ToString("dd/MM/yyyy") : null;
                    dr["UnEmpInsCountMonthOld"] = profile.UnEmpInsCountMonthOld;
                    dr["CommentIns"] = profile.CommentIns;
                    dr["StatusSyn"] = profile.StatusSyn;
                    dr["TypeOfStop"] = profile.TypeOfStop;
                    //  dr["TypeOfStop"] = profile.TypeOfStop;
                    dr["TypeSuspense"] = profile.TypeSuspense;
                    //  dr["TypeSuspense"] = profile.TypeSuspense;
                    dr["Cat_ResignReason-Name"] = profile.ResignReasonName;
                    dr["RequestDate"] = profile.RequestDate != null ? profile.RequestDate.Value.ToString("dd/MM/yyyy") : null;
                    dr["DateQuitRequest"] = profile.DateQuitRequest != null ? profile.DateQuitRequest.Value.ToString("dd/MM/yyyy") : null;
                    dr["ProfileSign"] = profile.ProfileSign;
                    dr["DateQuit"] = profile.DateQuit != null ? profile.DateQuit.Value.ToString("dd/MM/yyyy") : null;
                    dr["ResignNo"] = profile.ResignNo;
                    dr["DateQuitSign"] = profile.DateQuitSign != null ? profile.DateQuitSign.Value.ToString("dd/MM/yyyy") : null;
                    dr["ReceiveHealthIns"] = profile.ReceiveHealthIns;
                    dr["ReceiveHealthInsDate"] = profile.ReceiveHealthInsDate;
                    dr["IsBlackList"] = profile.IsBlackList;
                    dr["ResonBackList"] = profile.ResonBackList;

                    if (profile.DateOfBirth != null)
                    {
                        dr["DateOfBirth"] = profile.DateOfBirth.Value;
                    }

                    var lstContractByProfile = lstContractAll.Where(m => m.ProfileID == profile.ID).OrderBy(m => m.DateStart).ToList();
                    var lstContractByProfileID = lstContractByProfile.Select(m => m.ID).ToList();
                    var lstAppendixContractByProfile = lstAppendixContract.Where(m => lstContractByProfileID.Contains(m.ContractID)).ToList();
                    var lstContractExtendByContractID = lstContractExtend.Where(s => s.ContractID != null && lstContractByProfileID.Contains((Guid)s.ContractID)).ToList();
                    foreach (var ContractType in lstContracType)
                    {
                        string ContractCode = ContractType.Code;
                        if (string.IsNullOrEmpty(ContractCode))
                            continue;

                        var ContractOfProfileByType = lstContractByProfile.Where(m =>
                            m.ContractTypeID == ContractType.ID).FirstOrDefault();

                        if (ContractOfProfileByType != null)
                        {
                            dr[ContractCode + "_" + "ContractNo"] = ContractOfProfileByType.ContractNo;
                            dr[ContractCode + "_" + "DateStart"] = ContractOfProfileByType.DateStart != null ? ContractOfProfileByType.DateStart.ToString("dd/MM/yyyy") : null;
                            dr[ContractCode + "_" + "DateEnd"] = ContractOfProfileByType.DateEnd != null ? ContractOfProfileByType.DateEnd.Value.ToString("dd/MM/yyyy") : null;

                            var lstAppendixContractByContract = lstAppendixContractByProfile.Where(m =>
                                m.ContractID == ContractOfProfileByType.ID).OrderBy(m => m.DateofEffect).ToList();

                            int numAppendix = 0;
                            foreach (var AppendixContract in lstAppendixContractByContract)
                            {
                                numAppendix++;
                                if (numAppendix > 3)
                                    continue;
                                if (string.IsNullOrEmpty(AppendixContract.Code))
                                    continue;
                                dr[ContractCode + "_" + numAppendix + "_" + "Code"] = AppendixContract.Code;
                                if (AppendixContract.DateofEffect != null)
                                {
                                    dr[ContractCode + "_" + numAppendix + "_" + "DateofEffect"] = AppendixContract.DateofEffect;
                                }
                                if (AppendixContract.DateEndAppendixContract != null)
                                {
                                    dr[ContractCode + "_" + numAppendix + "_" + "DateEndAppendixContract"] = AppendixContract.DateEndAppendixContract;
                                }
                            }
                        }
                    }
                    if (lstContractExtendByContractID.Count > 0)
                    {
                        var count = 0;
                        foreach (var contractExtend in lstContractExtendByContractID)
                        {
                            count++;
                            var annexCodeTitle = "AnnexCode" + count;
                            var dateStartTitle = "DateStart" + count;
                            var dateEndTitle = "DateEnd" + count;

                            if (!tb.Columns.Contains(annexCodeTitle))
                            {
                                tb.Columns.Add(annexCodeTitle);
                            }

                            if (!tb.Columns.Contains(dateStartTitle))
                            {
                                tb.Columns.Add(dateStartTitle, typeof(DateTime));
                            }

                            if (!tb.Columns.Contains(dateEndTitle))
                            {
                                tb.Columns.Add(dateEndTitle, typeof(DateTime));
                            }

                            if (tb.Columns.Contains(annexCodeTitle))
                            {
                                dr[annexCodeTitle] = contractExtend.AnnexCode;
                            }
                            if (tb.Columns.Contains(dateStartTitle))
                            {
                                if (contractExtend.DateStart != null)
                                {
                                    dr[dateStartTitle] = contractExtend.DateStart;
                                }
                            }
                            if (tb.Columns.Contains(dateEndTitle))
                            {
                                if (contractExtend.DateEnd != null)
                                {
                                    dr[dateEndTitle] = contractExtend.DateEnd;
                                }
                            }
                        }
                    }
                    tb.Rows.Add(dr);
                }
                #endregion
                var configs = new Dictionary<string, Dictionary<string, object>>();
                return tb.ConfigTable(configs);
            }
        }
Example #13
0
        public DataTable GetReportContractExpired(List<Hre_ProfileEntity> lstProfile, DateTime? _DateSignedStart, DateTime? _DateSignedEnd, string _ContractNo, Guid? _ContractTypeID, bool isCreateTemplate, String nameReport)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoCat_ContractType = new CustomBaseRepository<Cat_ContractType>(unitOfWork);
                var repoHre_Contract = new CustomBaseRepository<Hre_Contract>(unitOfWork);
                var repoHre_AppendixContract = new CustomBaseRepository<Hre_AppendixContract>(unitOfWork);
                var lstContracType = repoCat_ContractType.FindBy(s => s.IsDelete == null).ToList();
                DataTable tb = GetSchema_ContractExpired(nameReport, lstContracType);
                if (isCreateTemplate)
                {
                    return tb.ConfigTable();
                }
                #region code BC
                string E_APPROVED = HRM.Infrastructure.Utilities.EnumDropDown.Status.E_APPROVED.ToString();
                var lstContractAll = repoHre_Contract.FindBy(m => m.IsDelete == null && m.Status == E_APPROVED)
                    .Select(m => new { m.ID, m.ContractTypeID, m.ProfileID, m.DateStart, m.DateEnd, m.ContractNo, m.DateSigned }).ToList();
                if (_DateSignedStart != null)
                    lstContractAll = lstContractAll.Where(s => s.DateSigned != null && s.DateSigned >= _DateSignedStart).ToList();
                if (_DateSignedEnd != null)
                    lstContractAll = lstContractAll.Where(s => s.DateSigned != null && s.DateSigned <= _DateSignedEnd).ToList();
                if (_ContractNo != string.Empty && _ContractNo != null)
                    lstContractAll = lstContractAll.Where(s => s.ContractNo != null && s.ContractNo == _ContractNo).ToList();
                if (_ContractTypeID != null && _ContractTypeID != Guid.Empty)
                    lstContractAll = lstContractAll.Where(s => s.ContractTypeID == _ContractTypeID).ToList();
                List<Guid> lstProfileIDs = lstContractAll.Select(m => m.ProfileID).Distinct().ToList();
                lstProfile = lstProfile.Where(m => lstProfileIDs.Contains(m.ID)).ToList();
                List<Guid> lstContractIDs = lstContractAll.Select(m => m.ID).ToList();
                var lstAppendixContract = repoHre_AppendixContract.GetAll().Where(m => lstContractIDs.Contains(m.ContractID))
                    .Select(m => new { m.ID, m.ContractID, m.Code, m.DateofEffect, m.DateEndAppendixContract }).ToList();
                #region Phu luc hd
                var lstContractExtend = new List<Hre_ContractExtend>().Select(s => new
                {
                    s.ContractID,
                    s.AnnexCode,
                    s.DateStart,
                    s.DateEnd
                }).ToList();
                foreach (var lstContractID in lstContractIDs.Chunk(1000))
                {
                    lstContractExtend.AddRange(unitOfWork.CreateQueryable<Hre_ContractExtend>(Guid.Empty, s => lstContractID.Contains(s.ContractID.Value)).Select(s => new
                    {
                        s.ContractID,
                        s.AnnexCode,
                        s.DateStart,
                        s.DateEnd
                    }).ToList());
                }
                #endregion
                int stt = 0;
                foreach (var profile in lstProfile)
                {
                    stt++;
                    DataRow dr = tb.NewRow();
                    dr["Stt"] = stt;
                    dr["CodeEmp"] = profile.CodeEmp;
                    dr["ProfileName"] = profile.ProfileName;
                    dr["E_DIVISION"] = profile.E_DIVISION;
                    dr["E_UNIT"] = profile.E_UNIT;
                    dr["E_DEPARTMENT"] = profile.E_DEPARTMENT;
                    dr["E_TEAM"] = profile.E_TEAM;
                    dr["E_SECTION"] = profile.E_SECTION;
                    if (profile.PositionName != null)
                    {
                        dr["Position"] = profile.PositionName;
                    }
                    if (profile.DateOfBirth != null)
                    {
                        dr["DateOfBirth"] = profile.DateOfBirth;
                    }
                    if (profile.Gender != null)
                    {
                        dr["Gender"] = profile.Gender.TranslateString();
                    }

                    if (profile.PlaceOfBirth != null)
                    {
                        dr["PlaceOfBirth"] = profile.PlaceOfBirth;
                    }
                    if (profile.PAddress != null)
                    {
                        dr["PAddress"] = profile.PAddress;
                    }
                    if (profile.IDNo != null)
                    {
                        dr["IDNo"] = profile.IDNo;
                    }
                    if (profile.IDDateOfIssue != null)
                    {
                        dr["IDDateOfIssue"] = profile.IDDateOfIssue;
                    }
                    if (profile.IDPlaceOfIssue != null)
                    {
                        dr["IDPlaceOfIssue"] = profile.IDPlaceOfIssue;
                    }
                    if (profile.DateHire != null)
                    {
                        dr["DateHire"] = profile.DateHire;
                    }
                    if (profile.DateHire != null)
                    {
                        dr["DateHire"] = profile.DateHire;
                    }
                    if (profile.SalaryClassName != null)
                    {
                        dr["SalaryClass"] = profile.SalaryClassName;
                    }
                    dr["EducationLevelName"] = profile.EducationLevelName;
                    dr["StatusSynView"] = profile.StatusSynView;

                    var lstContractByProfile = lstContractAll.Where(m => m.ProfileID == profile.ID).OrderByDescending(m => m.DateStart).ToList();
                    var lstContractByProfileID = lstContractByProfile.Select(m => m.ID).ToList();
                    var lstAppendixContractByProfile = lstAppendixContract.Where(m => lstContractByProfileID.Contains(m.ContractID)).ToList();
                    foreach (var ContractType in lstContracType)
                    {
                        string ContractCode = ContractType.Code;
                        if (string.IsNullOrEmpty(ContractCode))
                            continue;
                        var contractByProfile_ByType = lstContractByProfile.Where(m => m.ContractTypeID == ContractType.ID).FirstOrDefault();
                        if (contractByProfile_ByType != null)
                        {
                            if (contractByProfile_ByType.ContractNo != null)
                                dr[ContractCode + "_" + "ContractNo"] = contractByProfile_ByType.ContractNo;
                            if (contractByProfile_ByType.DateStart != null)
                                dr[ContractCode + "_" + "DateStart"] = contractByProfile_ByType.DateStart;
                            if (contractByProfile_ByType.DateEnd != null)
                                dr[ContractCode + "_" + "DateEnd"] = contractByProfile_ByType.DateEnd;

                            var lstAppendixContractByContract = lstAppendixContractByProfile.Where(m => m.ContractID == contractByProfile_ByType.ID).OrderBy(m => m.DateofEffect).ToList();
                            int numAppendix = 0;
                            foreach (var AppendixContract in lstAppendixContractByContract)
                            {
                                numAppendix++;
                                if (numAppendix > 3)
                                    continue;
                                if (string.IsNullOrEmpty(AppendixContract.Code))
                                    continue;
                                if (AppendixContract.Code != null)
                                    dr[ContractCode + "_" + numAppendix + "_" + "Code"] = AppendixContract.Code;
                                if (AppendixContract.DateofEffect != null)
                                    dr[ContractCode + "_" + numAppendix + "_" + "DateofEffect"] = AppendixContract.DateofEffect;
                                if (AppendixContract.DateEndAppendixContract != null)
                                    dr[ContractCode + "_" + numAppendix + "_" + "DateEndAppendixContract"] = AppendixContract.DateEndAppendixContract;
                            }
                            var lstContractExtendByContract = lstContractExtend.Where(s => s.ContractID == contractByProfile_ByType.ID).OrderBy(s => s.DateStart).ToList();
                            int numContractExtend = 0;
                            foreach (var objContractExtend in lstContractExtendByContract)
                            {
                                numContractExtend++;
                                if (numContractExtend > 5)
                                    continue;
                                if (objContractExtend.AnnexCode != null)
                                    dr[ContractCode + "_" + numContractExtend + "_" + "CodeExtend"] = objContractExtend.AnnexCode;
                                if (objContractExtend.DateStart != null)
                                    dr[ContractCode + "_" + numContractExtend + "_" + "DateStartExtend"] = objContractExtend.DateStart;
                                if (objContractExtend.DateEnd != null)
                                    dr[ContractCode + "_" + numContractExtend + "_" + "DateEndExtend"] = objContractExtend.DateEnd;
                            }
                        }
                    }
                    tb.Rows.Add(dr);
                }
                #endregion
                var configs = new Dictionary<string, Dictionary<string, object>>();
                return tb.ConfigTable(configs);
            }
        }
Example #14
0
        public DataTable GetReportProfileQuitV2(List<Guid> listOrgID, DateTime monthStart, DateTime monthEnd,
            string codeEmp, string profileName, Guid? resignReasonID, Guid? typeOfStopID, Guid? jobTitleID, Guid? positionID, Guid? workPlaceID, bool isCreateTemplate,
            string nameReport, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                IUnitOfWork unitOfWork = new UnitOfWork(context);
                var repoCat_ContractType = new CustomBaseRepository<Cat_ContractType>(unitOfWork);
                var repoHre_Contract = new CustomBaseRepository<Hre_Contract>(unitOfWork);
                var repoHre_AppendixContract = new CustomBaseRepository<Hre_AppendixContract>(unitOfWork);
                var repoCat_OrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var repoCat_OrgStructureType = new CustomBaseRepository<Cat_OrgStructureType>(unitOfWork);
                var lstContracType = repoCat_ContractType.FindBy(s => s.IsDelete == null).ToList();
                DataTable tb = GetSchema_ProfileQuitV2(nameReport, lstContracType);
                string status = string.Empty;
                List<object> listModel = new List<object>();
                listModel = new List<object>();
                listModel.AddRange(new object[19]);
                listModel[3] = positionID;
                listModel[6] = jobTitleID;
                listModel[8] = monthStart;
                listModel[9] = monthEnd;
                listModel[10] = resignReasonID;
                listModel[11] = typeOfStopID;
                listModel[12] = workPlaceID;
                listModel[17] = 1;
                listModel[18] = Int32.MaxValue - 1;
                List<Hre_ProfileEntity> lstProfile = GetData<Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_ProfileQuit, userLogin,ref status);

                if (!string.IsNullOrWhiteSpace(codeEmp))
                {
                    lstProfile = lstProfile.Where(d => d.CodeEmp != null && d.CodeEmp.Contains(codeEmp)).ToList();
                }

                if (!string.IsNullOrWhiteSpace(profileName))
                {
                    lstProfile = lstProfile.Where(d => d.ProfileName.Contains(profileName)).ToList();
                }

                if (listOrgID != null && listOrgID.Count() > 0)
                {
                    lstProfile = lstProfile.Where(d => d.OrgStructureID.HasValue && listOrgID.Contains(d.OrgStructureID.Value)).ToList();
                }

                #region code BC

                string E_APPROVED = HRM.Infrastructure.Utilities.EnumDropDown.Status.E_APPROVED.ToString();
                List<Guid> lstProfileIDs = lstProfile.Select(m => m.ID).Distinct().ToList();

                var lstContractAll = new List<Hre_Contract>().Select(m => new
                {
                    m.ID,
                    m.ContractTypeID,
                    m.ProfileID,
                    m.DateStart,
                    m.DateEnd,
                    m.ContractNo,
                    m.DateUpdate
                }).ToList();

                foreach (var lstProfileID in lstProfileIDs.Chunk(1000))
                {
                    lstContractAll.AddRange(unitOfWork.CreateQueryable<Hre_Contract>(Guid.Empty, m => m.Status == E_APPROVED
                        && lstProfileID.Contains(m.ProfileID) && m.DateStart <= monthEnd && m.DateEnd >= monthStart).Select(m => new
                        {
                            m.ID,
                            m.ContractTypeID,
                            m.ProfileID,
                            m.DateStart,
                            m.DateEnd,
                            m.ContractNo,
                            m.DateUpdate
                        }).ToList());
                }

                List<Guid> lstContractIDs = lstContractAll.Select(m => m.ID).ToList();
                var lstAppendixContract = new List<Hre_AppendixContract>().Select(m => new
                {
                    m.ID,
                    m.ContractID,
                    m.Code,
                    m.DateofEffect,
                    m.DateEndAppendixContract
                }).ToList();

                foreach (var lstContractID in lstContractIDs.Chunk(1000))
                {
                    lstAppendixContract.AddRange(unitOfWork.CreateQueryable<Hre_AppendixContract>(Guid.Empty,
                        m => lstContractID.Contains(m.ContractID)).Select(m => new
                        {
                            m.ID,
                            m.ContractID,
                            m.Code,
                            m.DateofEffect,
                            m.DateEndAppendixContract
                        }).ToList());
                }

                var lstOrg = repoCat_OrgStructure.GetAll().ToList();
                var orgTypes = repoCat_OrgStructureType.GetAll().ToList();
                int stt = 0;
                var lstContractExtend = new List<Hre_ContractExtend>().Select(s => new
                {
                    s.ContractID,
                    s.AnnexCode,
                    s.DateStart,
                    s.DateEnd
                }).ToList();

                foreach (var lstContractID in lstContractIDs.Chunk(1000))
                {
                    lstContractExtend.AddRange(unitOfWork.CreateQueryable<Hre_ContractExtend>(Guid.Empty, s => lstContractID.Contains(s.ContractID.Value)).Select(s => new
                    {
                        s.ContractID,
                        s.AnnexCode,
                        s.DateStart,
                        s.DateEnd
                    }).ToList());
                }
                foreach (var profile in lstProfile)
                {
                    stt++;
                    DataRow dr = tb.NewRow();
                    dr["Stt"] = stt;
                    dr["CodeEmp"] = profile.CodeEmp;
                    dr["ProfileName"] = profile.ProfileName;
                    dr["E_DIVISION"] = profile.E_DIVISION;
                    dr["E_UNIT"] = profile.E_UNIT;
                    dr["E_DEPARTMENT"] = profile.E_DEPARTMENT;
                    dr["E_TEAM"] = profile.E_TEAM;
                    dr["E_SECTION"] = profile.E_SECTION;
                    if (!string.IsNullOrWhiteSpace(profile.PositionName))
                    {
                        dr["Position"] = profile.PositionName;
                    }
                    if (profile.DateOfBirth != null)
                    {
                        dr["DateOfBirth"] = profile.DateOfBirth;
                    }
                    if (profile.Gender != null)
                    {
                        dr["Gender"] = profile.Gender.TranslateString();
                    }
                    if (profile.PlaceOfBirth != null)
                    {
                        dr["PlaceOfBirth"] = profile.PlaceOfBirth;
                    }
                    if (profile.WorkPlaceName != null)
                        dr["WorkPlaceName"] = profile.WorkPlaceName;
                    if (profile.PAddress != null)
                    {
                        dr["PAddress"] = profile.PAddress;
                    }
                    if (profile.IDNo != null)
                    {
                        dr["IDNo"] = profile.IDNo;
                    }
                    if (profile.IDDateOfIssue != null)
                    {
                        dr["IDDateOfIssue"] = profile.IDDateOfIssue;
                    }
                    if (profile.IDPlaceOfIssue != null)
                    {
                        dr["IDPlaceOfIssue"] = profile.IDPlaceOfIssue;
                    }
                    if (profile.DateHire != null)
                    {
                        dr["DateHire"] = profile.DateHire;
                    }
                    if (profile.DateQuit != null)
                    {
                        dr["DateWorkFinal"] = profile.DateQuit.Value.AddDays(-1);
                        dr["ResignNo"] = profile.ResignNo.ToString();
                        dr["DateQuit"] = profile.DateQuit;
                    }
                    if (!string.IsNullOrWhiteSpace(profile.SalaryClassName))
                    {
                        dr["SalaryClassName"] = profile.SalaryClassName;
                    }
                    if (!string.IsNullOrWhiteSpace(profile.ResignReasonName))
                    {
                        dr["ResignReasonName"] = profile.ResignReasonName;
                    }
                    if (!string.IsNullOrWhiteSpace(profile.EducationLevelName))
                    {
                        dr["E_EDUCATIONLEVEL"] = profile.EducationLevelName;
                    }
                    if (!string.IsNullOrWhiteSpace(profile.GraduatedLevelName))
                    {
                        dr["QualificationName"] = profile.GraduatedLevelName;
                    }
                    var lstContractByProfile = lstContractAll.Where(m => m.ProfileID == profile.ID).OrderBy(m => m.DateStart).ToList();
                    foreach (var ContractType in lstContracType)
                    {
                        var contractByContractType = lstContractByProfile.Where(m => m.ContractTypeID == ContractType.ID).OrderByDescending(s => s.DateUpdate).FirstOrDefault();
                        if (contractByContractType != null)
                        {
                            string ContractCode = ContractType.Code;
                            if (string.IsNullOrEmpty(ContractCode))
                            {
                                continue;
                            }

                            // Son.Vo - 20150610 - sửa lại lấy thông tin gia hạn hđ. Max là 5 dòng gia hạn. - theo task 0049132
                            //if (ContractType.Type == EnumDropDown.TypeContract.E_DURATION.ToString())
                            //{
                            var lstContractByType = lstContractByProfile.Where(s => s.ContractTypeID == ContractType.ID).ToList();
                            foreach (var item in lstContractByType)
                            {
                                dr[ContractCode + "_" + "ContractNo"] = item.ContractNo;
                                if (item.DateStart != null)
                                {
                                    dr[ContractCode + "_" + "DateStart"] = item.DateStart;
                                }
                                if (contractByContractType.DateEnd != null)
                                {
                                    dr[ContractCode + "_" + "DateEnd"] = item.DateEnd;
                                }
                                //var contractByProfile_ByType = lstContractByProfile.Where(m => m.ContractTypeID == ContractType.ID).FirstOrDefault();
                                var lstContractExtendByContract = lstContractExtend.Where(s => s.ContractID == item.ID).OrderBy(s => s.DateStart).ToList();
                                int numContractExtend = 0;
                                foreach (var objContractExtend in lstContractExtendByContract)
                                {
                                    numContractExtend++;
                                    if (numContractExtend > 5)
                                        continue;
                                    if (objContractExtend != null)
                                    {
                                        if (objContractExtend.AnnexCode != null)
                                            dr[ContractCode + "_" + numContractExtend + "_" + "CodeExtend"] = objContractExtend.AnnexCode;
                                        if (objContractExtend.DateStart != null)
                                            dr[ContractCode + "_" + numContractExtend + "_" + "DateStartExtend"] = objContractExtend.DateStart;
                                        if (objContractExtend.DateEnd != null)
                                            dr[ContractCode + "_" + numContractExtend + "_" + "DateEndExtend"] = objContractExtend.DateEnd;

                                    }
                                }
                            }
                        }
                    }
                    tb.Rows.Add(dr);
                }
                #endregion

                var configs = new Dictionary<string, Dictionary<string, object>>();
                return tb.ConfigTable(configs);
            }
        }
Example #15
0
 public List <Tra_TraineeScoreEntity> GetListTraineeScore(List <Tra_TraineeScoreImport> lstTraineeScore, out List <Tra_TraineeScoreImport> DataReviewOutput)
 {
     using (var context = new VnrHrmDataContext())
     {
         var unitOfWork                       = (IUnitOfWork)(new UnitOfWork(context));
         var repoTra_Class                    = new CustomBaseRepository <Tra_Class>(unitOfWork);
         var repoTra_Trainee                  = new CustomBaseRepository <Tra_Trainee>(unitOfWork);
         var repoTra_TraineeTopic             = new CustomBaseRepository <Tra_TraineeTopic>(unitOfWork);
         var repoTra_TraineeScore             = new CustomBaseRepository <Tra_TraineeScore>(unitOfWork);
         var repoTra_ScoreType                = new CustomBaseRepository <Tra_ScoreType>(unitOfWork);
         List <Tra_TraineeScoreEntity> entity = new List <Tra_TraineeScoreEntity>();
         List <Tra_TraineeScore>       result = new List <Tra_TraineeScore>();
         DataReviewOutput = new List <Tra_TraineeScoreImport>();
         List <string> ClassCode = lstTraineeScore.Select(m => m.ClassCode).Distinct().ToList();
         //Lấy DS ClassID
         List <Guid> ClassID = repoTra_Class.GetAll().Where(m => m.IsDelete == null && ClassCode.Contains(m.Code)).Select(m => m.ID).ToList <Guid>();
         //Lấy DS TraineeID
         List <Guid> TraineeID = repoTra_Trainee.GetAll().Where(m => m.IsDelete == null && ClassID.Contains(m.ClassID)).Select(m => m.ID).ToList <Guid>();
         //Lấy DS TraineetopicID
         List <Guid> lstTraineeTopicID = repoTra_TraineeTopic.GetAll().Where(m => m.IsDelete == null && TraineeID.Contains(m.TraineeID ?? Guid.Empty)).Select(m => m.ID).ToList <Guid>();
         //Lấy DS TraineeTopic
         var TraineeTopicAll = repoTra_TraineeTopic.GetAll().Where(m => m.IsDelete == null && lstTraineeTopicID.Contains(m.ID))
                               .Select(m => new { m.ID, TopicCode = m.Cat_Topic.Code, CodeEmp = m.Tra_Trainee.Hre_Profile.CodeEmp, ClassCode = m.Tra_Trainee.Tra_Class.Code }).ToList();
         //Lấy DS TraineeScore
         List <Tra_TraineeScore> LstTraineeScoreAll = repoTra_TraineeScore.GetAll().Where(m => m.IsDelete == null && lstTraineeTopicID.Contains(m.TraineeTopicID ?? Guid.Empty)).ToList <Tra_TraineeScore>();
         List <string>           ScoreTypeCode      = lstTraineeScore.Select(m => m.TypeScore).Distinct().ToList <string>();
         List <Tra_ScoreType>    lstTypeScoreAll    = repoTra_ScoreType.GetAll().Where(m => m.IsDelete == null && ScoreTypeCode.Contains(m.Code)).ToList <Tra_ScoreType>();
         var stt = 1;
         foreach (var TraineeScore in lstTraineeScore)
         {
             var           TraineeTopic = TraineeTopicAll.Where(m => m.CodeEmp == TraineeScore.CodeEmp && m.TopicCode == TraineeScore.TopicCode).FirstOrDefault();
             Tra_ScoreType ScoreType    = lstTypeScoreAll.Where(m => m.Code == TraineeScore.TypeScore).FirstOrDefault();
             if (TraineeTopic == null) //Loi import
             {
                 TraineeScore.Stt       = stt++;
                 TraineeScore.TypeError = "Không Có Môn Học Của Học Viên";
                 DataReviewOutput.Add(TraineeScore);
             }
             else if (ScoreType == null)
             {
                 TraineeScore.Stt       = stt++;
                 TraineeScore.TypeError = "Không Có Loại Điểm Của Môn Học";
                 DataReviewOutput.Add(TraineeScore);
             }
             else
             {
                 TraineeScore.Stt = stt++;
                 DataReviewOutput.Add(TraineeScore);
                 //Kiem tra diem da co trong DB chua
                 //neu co roi thi update neu chua thi tao moi
                 Guid             TraineeTopicID       = TraineeTopic.ID;
                 Tra_TraineeScore TraineeScore_Current = LstTraineeScoreAll.Where(m => m.TraineeTopicID == TraineeTopicID && m.ScoreTypeID == ScoreType.ID).FirstOrDefault();
                 if (TraineeScore_Current == null)
                 {
                     TraineeScore_Current    = new Tra_TraineeScore();
                     TraineeScore_Current.ID = Guid.NewGuid();
                 }
                 TraineeScore_Current.TraineeTopicID = TraineeTopicID;
                 TraineeScore_Current.ScoreTypeID    = ScoreType.ID;
                 TraineeScore_Current.Score          = TraineeScore.Score;
                 result.Add(TraineeScore_Current);
             }
             entity = result.Translate <Tra_TraineeScoreEntity>();
         }
         return(entity);
     }
 }
Example #16
0
        public  string ApprovedTraineeRegister (List<Guid> selectedIds , Guid UserId)
        {
            using (var context = new VnrHrmDataContext())
            {
                var message = string.Empty;
                var status = string.Empty;
                var UserLogin = string.Empty;
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var firstApproved = EnumDropDown.TraineeRegisterStatus.E_SUBMIT.ToString();
                var approved = EnumDropDown.TraineeRegisterStatus.E_APPROVED.ToString();
                var objTraineeRegister = new List<object>();
                objTraineeRegister.AddRange(new object[12]);
                objTraineeRegister[10] = 1;
                objTraineeRegister[11] = int.MaxValue - 1;
                var lstTraineeRegister = GetData<Tra_TraineeRegisterEntity>(objTraineeRegister, ConstantSql.hrm_tra_sp_get_TraineeRegister,UserLogin, ref status).ToList();

               var repo_UserApproved = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);
               var lstUserApproved = repo_UserApproved.GetAll().Where(s => s.IsDelete == null).ToList();

                if (selectedIds.Count > 0)
                {
                    lstTraineeRegister = lstTraineeRegister.Where(s => selectedIds.Contains(s.ID)).ToList();
                }

                var traineeServices = new Tra_TraineeServices();
                var isTraineeInRequireDetail = traineeServices.IsAddTraineeDependOnRequirementDetail();
                var traineeTopicServices = new Tra_TraineeTopicServices();
                var planServices = new Tra_PlanServices();
                var lstObjPlan = new List<object>();
                lstObjPlan.Add(null);
                lstObjPlan.Add(null);
                lstObjPlan.Add(null);
                lstObjPlan.Add(null);
                lstObjPlan.Add(1);
                lstObjPlan.Add(int.MaxValue - 1);
                var lstPlan = planServices.GetData<Tra_PlanEntity>(lstObjPlan, ConstantSql.hrm_tra_sp_get_Plan,UserLogin, ref status).ToList();


                var planDetailServices = new Tra_PlanDetailServices();
                var lstObjPlanDetail = new List<object>();
                lstObjPlanDetail.Add(null);
                lstObjPlanDetail.Add(1);
                lstObjPlanDetail.Add(int.MaxValue - 1);
                var lstPlanDetail = planDetailServices.GetData<Tra_PlanDetailEntity>(lstObjPlanDetail, ConstantSql.hrm_tra_sp_get_PlanDetail, UserLogin, ref status).ToList();

                var classServices = new Tra_ClassServices();
                var lstObjClass = new List<object>();
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(1);
                lstObjClass.Add(int.MaxValue - 1);
                var lstClass = classServices.GetData<Tra_ClassEntity>(lstObjClass, ConstantSql.hrm_tra_sp_get_Class, UserLogin, ref status).ToList();

                //var lstObjTraineeInClass = new List<object>();
                //lstObjTraineeInClass.Add(model.ClassID);
                //var lstTraineeInClass = classServices.GetData<Tra_ClassEntity>(lstObjTraineeInClass, ConstantSql.hrm_cat_sp_get_TraineeByClassID, ref status).ToList();

                var courseTopicServices = new Tra_TraineeTopicServices();
                var objCourseTopic = new List<object>();
                objCourseTopic.Add(1);
                objCourseTopic.Add(int.MaxValue - 1);
                var lstCourseTopic = courseTopicServices.GetData<Tra_CourseTopicEntity>(objCourseTopic, ConstantSql.hrm_tra_sp_get_CourseTopic, UserLogin, ref status);


                //var classEntity = lstClass.Where(s => s.ID == model.ClassID).FirstOrDefault();
                var profileServices = new Hre_ProfileServices();

                var requirementServices = new Tra_RequirementTrainServices();
                var objRequirement = new List<object>();
                objRequirement.AddRange(new object[7]);
                objRequirement[5] = 1;
                objRequirement[6] = int.MaxValue - 1;
                var lstRequirement = requirementServices.GetData<Tra_RequirementTrainEntity>(objRequirement, ConstantSql.hrm_tra_sp_get_RequirementTrain, UserLogin, ref status).ToList();

                var requirementDetailServices = new Tra_RequirementTrainDetailServices();
                var objRequirementDetail = new List<object>();
                objRequirementDetail.Add(null);
                objRequirementDetail.Add(1);
                objRequirementDetail.Add(int.MaxValue - 1);
                var lstRequirementDetail = requirementDetailServices.GetData<Tra_RequirementTrainDetailEntity>(objRequirementDetail, ConstantSql.hrm_tra_sp_get_RequirementDetail, UserLogin, ref status).ToList();

                var objTrainee = new List<object>();
                objTrainee.AddRange(new object[15]);
                objTrainee[13] = 1;
                objTrainee[14] = int.MaxValue - 1;
                var lstObjTrainee = traineeServices.GetData<Tra_TraineeEntity>(objTrainee, ConstantSql.hrm_tra_sp_get_Trainee, UserLogin, ref status).ToList();

                foreach (var registerEntity in lstTraineeRegister)
                {
                    var classEntity = lstClass.Where(s => s.ID == registerEntity.ClassID).FirstOrDefault();
                    var traineeEntityInClass = lstObjTrainee.Where(s => s.ClassID == registerEntity.ClassID && registerEntity.ProfileID == s.ProfileID).ToList();

                    #region người duyệt đầu
                    if (registerEntity.UserApproveID1 != null && registerEntity.UserApproveID1.Value == UserId)
                    {
                        var userApprovedEntity = lstUserApproved.Where(s => registerEntity.UserApproveID1.Value == s.UserApproveID && s.Type == ApproveType.E_TRA_TRAINEEREGISTER.ToString()).FirstOrDefault();
                        if (userApprovedEntity != null)
                        {
                            if (userApprovedEntity.IsMasterApprove == null || userApprovedEntity.IsMasterApprove.Value == false)
                            {
                                registerEntity.Status = firstApproved;
                                message = Edit(registerEntity);
                            }
                        }
                    }
	                #endregion

                    #region người duyệt cuối
                    if (registerEntity.UserApproveID2 != null && registerEntity.UserApproveID2.Value == UserId)
                    {
                        var userApprovedEntity = lstUserApproved.Where(s => registerEntity.UserApproveID2.Value == s.UserApproveID && s.Type == ApproveType.E_TRA_TRAINEEREGISTER.ToString()).FirstOrDefault();
                        if (userApprovedEntity != null)
                        {
                            if (userApprovedEntity.IsMasterApprove != null && userApprovedEntity.IsMasterApprove.Value)
                            {
                                #region Cập Nhập Status lại vào bảng Tra_TraineeRegister
                                registerEntity.Status = approved;
                                message = Edit(registerEntity);
                                #endregion

                                #region Tạo hv vào bảng Tra_Trainee

                                if (isTraineeInRequireDetail)
                                {
                                    if (traineeEntityInClass.Count > 0)
                                    {
                                        message = ConstantMessages.WarningProfileHaveClass.ToString().TranslateString();
                                        return message;
                                    }
                                    if (registerEntity.ClassID != null)
                                    {
                                        if (classEntity != null && classEntity.PlanID != null)
                                        {
                                            var lstRequirementByPlanID = lstRequirement.Where(s => s.PlanID != null && s.PlanID.Value == classEntity.PlanID).ToList();
                                            foreach (var item in lstRequirementByPlanID)
                                            {
                                                var requirementDetailEntity = lstRequirementDetail.Where(s => item.ID == s.RequirementTrainID && s.CourseID == classEntity.CourseID && s.ProfileID == item.ProfileID).FirstOrDefault();
                                                if (requirementDetailEntity != null)
                                                {
                                                    var traineeEntity = new Tra_TraineeEntity();
                                                    traineeEntity.ProfileID = registerEntity.ProfileID.Value;
                                                    traineeEntity.ClassID = registerEntity.ClassID.Value;
                                                    traineeEntity.TraineeRegisterID = (Guid?)registerEntity.ID;
                                                    traineeServices.Add(traineeEntity);

                                                    var lstCourseTopicByCourseID = lstCourseTopic.Where(s => s.CourseID == classEntity.CourseID).ToList();
                                                    foreach (var courseTopic in lstCourseTopicByCourseID)
                                                    {
                                                        var traineeTopicEntity = new Tra_TraineeTopicEntity();
                                                        traineeTopicEntity.TopicID = courseTopic.TopicID;
                                                        traineeTopicEntity.TraineeID = traineeEntity.ID;
                                                        message = traineeTopicServices.Add(traineeTopicEntity);
                                                    }

                                                }
                                                else
                                                {
                                                    message = ConstantMessages.WarningProfileNotInRequirement.ToString().TranslateString();
                                                }
                                            }
                                        }
                                    }
                                }

                                if (classEntity != null)
                                {
                                    if (traineeEntityInClass.Count > 0)
                                    {
                                        message = ConstantMessages.WarningProfileHaveClass.ToString().TranslateString();
                                        return message;
                                    }

                                    var traineeEntity = new Tra_TraineeEntity();
                                    traineeEntity.ProfileID = registerEntity.ProfileID.Value;
                                    traineeEntity.ClassID = registerEntity.ClassID.Value;
                                    traineeEntity.TraineeRegisterID = (Guid?)registerEntity.ID;
                                    traineeServices.Add(traineeEntity);

                                    var lstCourseTopicByCourseID = lstCourseTopic.Where(s => s.CourseID == classEntity.CourseID).ToList();
                                    foreach (var courseTopic in lstCourseTopicByCourseID)
                                    {
                                        var traineeTopicEntity = new Tra_TraineeTopicEntity();
                                        traineeTopicEntity.TopicID = courseTopic.TopicID;
                                        traineeTopicEntity.TraineeID = traineeEntity.ID;
                                        message = traineeTopicServices.Add(traineeTopicEntity);
                                    }



                                }
                                #endregion
                            }
                        }
                    }
                    #endregion

                }
                return message;
            }
            
        }
Example #17
0
        public string ActionRejectTraineeRegister(List<Guid> selectedIds, Guid UserId, string Reason)
        {
            using (var context = new VnrHrmDataContext())
            {
                var message = string.Empty;
                var status = string.Empty;
                var UserLogin = string.Empty;
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));

                var objTraineeRegister = new List<object>();
                objTraineeRegister.AddRange(new object[12]);
                objTraineeRegister[10] = 1;
                objTraineeRegister[11] = int.MaxValue - 1;
                var lstTraineeRegister = GetData<Tra_TraineeRegisterEntity>(objTraineeRegister, ConstantSql.hrm_tra_sp_get_TraineeRegister, UserLogin, ref status).ToList();

                var repo_UserApproved = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);
                var lstUserApproved = repo_UserApproved.GetAll().Where(s => s.IsDelete != null).ToList();

                if (selectedIds.Count > 0)
                {
                    lstTraineeRegister = lstTraineeRegister.Where(s => selectedIds.Contains(s.ID)).ToList();
                }

                foreach (var item in lstTraineeRegister)
                {
                    #region Check Loại Người Duyệt
                    if (item.UserApproveID1 != null && item.UserApproveID1.Value == UserId)
                    {
                    
                                item.Status = EnumDropDown.TraineeRegisterStatus.E_REJECTED.ToString();
                                item.Reason1 = Reason;
                                message = Edit(item);
                            
                          
                        
                    }
                    #endregion

                    #region Người duyệt cuối
                    if (item.UserApproveID2 != null && item.UserApproveID2.Value == UserId)
                    {
                      
                                item.Status = EnumDropDown.TraineeRegisterStatus.E_REJECTED.ToString();
                                item.Reason2 = Reason;
                                message = Edit(item);
                            
                            
                        
                    }
                    #endregion
                }
                return message;
            }
        }
Example #18
0
        public string ApprovedTraineeRegister(List <Guid> selectedIds, Guid UserId)
        {
            using (var context = new VnrHrmDataContext())
            {
                var message            = string.Empty;
                var status             = string.Empty;
                var UserLogin          = string.Empty;
                var unitOfWork         = (IUnitOfWork)(new UnitOfWork(context));
                var firstApproved      = EnumDropDown.TraineeRegisterStatus.E_SUBMIT.ToString();
                var approved           = EnumDropDown.TraineeRegisterStatus.E_APPROVED.ToString();
                var objTraineeRegister = new List <object>();
                objTraineeRegister.AddRange(new object[12]);
                objTraineeRegister[10] = 1;
                objTraineeRegister[11] = int.MaxValue - 1;
                var lstTraineeRegister = GetData <Tra_TraineeRegisterEntity>(objTraineeRegister, ConstantSql.hrm_tra_sp_get_TraineeRegister, UserLogin, ref status).ToList();

                var repo_UserApproved = new CustomBaseRepository <Sys_UserApprove>(unitOfWork);
                var lstUserApproved   = repo_UserApproved.GetAll().Where(s => s.IsDelete == null).ToList();

                if (selectedIds.Count > 0)
                {
                    lstTraineeRegister = lstTraineeRegister.Where(s => selectedIds.Contains(s.ID)).ToList();
                }

                var traineeServices          = new Tra_TraineeServices();
                var isTraineeInRequireDetail = traineeServices.IsAddTraineeDependOnRequirementDetail();
                var traineeTopicServices     = new Tra_TraineeTopicServices();
                var planServices             = new Tra_PlanServices();
                var lstObjPlan = new List <object>();
                lstObjPlan.Add(null);
                lstObjPlan.Add(null);
                lstObjPlan.Add(null);
                lstObjPlan.Add(null);
                lstObjPlan.Add(1);
                lstObjPlan.Add(int.MaxValue - 1);
                var lstPlan = planServices.GetData <Tra_PlanEntity>(lstObjPlan, ConstantSql.hrm_tra_sp_get_Plan, UserLogin, ref status).ToList();


                var planDetailServices = new Tra_PlanDetailServices();
                var lstObjPlanDetail   = new List <object>();
                lstObjPlanDetail.Add(null);
                lstObjPlanDetail.Add(1);
                lstObjPlanDetail.Add(int.MaxValue - 1);
                var lstPlanDetail = planDetailServices.GetData <Tra_PlanDetailEntity>(lstObjPlanDetail, ConstantSql.hrm_tra_sp_get_PlanDetail, UserLogin, ref status).ToList();

                var classServices = new Tra_ClassServices();
                var lstObjClass   = new List <object>();
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(null);
                lstObjClass.Add(1);
                lstObjClass.Add(int.MaxValue - 1);
                var lstClass = classServices.GetData <Tra_ClassEntity>(lstObjClass, ConstantSql.hrm_tra_sp_get_Class, UserLogin, ref status).ToList();

                //var lstObjTraineeInClass = new List<object>();
                //lstObjTraineeInClass.Add(model.ClassID);
                //var lstTraineeInClass = classServices.GetData<Tra_ClassEntity>(lstObjTraineeInClass, ConstantSql.hrm_cat_sp_get_TraineeByClassID, ref status).ToList();

                var courseTopicServices = new Tra_TraineeTopicServices();
                var objCourseTopic      = new List <object>();
                objCourseTopic.Add(1);
                objCourseTopic.Add(int.MaxValue - 1);
                var lstCourseTopic = courseTopicServices.GetData <Tra_CourseTopicEntity>(objCourseTopic, ConstantSql.hrm_tra_sp_get_CourseTopic, UserLogin, ref status);


                //var classEntity = lstClass.Where(s => s.ID == model.ClassID).FirstOrDefault();
                var profileServices = new Hre_ProfileServices();

                var requirementServices = new Tra_RequirementTrainServices();
                var objRequirement      = new List <object>();
                objRequirement.AddRange(new object[7]);
                objRequirement[5] = 1;
                objRequirement[6] = int.MaxValue - 1;
                var lstRequirement = requirementServices.GetData <Tra_RequirementTrainEntity>(objRequirement, ConstantSql.hrm_tra_sp_get_RequirementTrain, UserLogin, ref status).ToList();

                var requirementDetailServices = new Tra_RequirementTrainDetailServices();
                var objRequirementDetail      = new List <object>();
                objRequirementDetail.Add(null);
                objRequirementDetail.Add(1);
                objRequirementDetail.Add(int.MaxValue - 1);
                var lstRequirementDetail = requirementDetailServices.GetData <Tra_RequirementTrainDetailEntity>(objRequirementDetail, ConstantSql.hrm_tra_sp_get_RequirementDetail, UserLogin, ref status).ToList();

                var objTrainee = new List <object>();
                objTrainee.AddRange(new object[15]);
                objTrainee[13] = 1;
                objTrainee[14] = int.MaxValue - 1;
                var lstObjTrainee = traineeServices.GetData <Tra_TraineeEntity>(objTrainee, ConstantSql.hrm_tra_sp_get_Trainee, UserLogin, ref status).ToList();

                foreach (var registerEntity in lstTraineeRegister)
                {
                    var classEntity          = lstClass.Where(s => s.ID == registerEntity.ClassID).FirstOrDefault();
                    var traineeEntityInClass = lstObjTrainee.Where(s => s.ClassID == registerEntity.ClassID && registerEntity.ProfileID == s.ProfileID).ToList();

                    #region người duyệt đầu
                    if (registerEntity.UserApproveID1 != null && registerEntity.UserApproveID1.Value == UserId)
                    {
                        var userApprovedEntity = lstUserApproved.Where(s => registerEntity.UserApproveID1.Value == s.UserApproveID && s.Type == ApproveType.E_TRA_TRAINEEREGISTER.ToString()).FirstOrDefault();
                        if (userApprovedEntity != null)
                        {
                            if (userApprovedEntity.IsMasterApprove == null || userApprovedEntity.IsMasterApprove.Value == false)
                            {
                                registerEntity.Status = firstApproved;
                                message = Edit(registerEntity);
                            }
                        }
                    }
                    #endregion

                    #region người duyệt cuối
                    if (registerEntity.UserApproveID2 != null && registerEntity.UserApproveID2.Value == UserId)
                    {
                        var userApprovedEntity = lstUserApproved.Where(s => registerEntity.UserApproveID2.Value == s.UserApproveID && s.Type == ApproveType.E_TRA_TRAINEEREGISTER.ToString()).FirstOrDefault();
                        if (userApprovedEntity != null)
                        {
                            if (userApprovedEntity.IsMasterApprove != null && userApprovedEntity.IsMasterApprove.Value)
                            {
                                #region Cập Nhập Status lại vào bảng Tra_TraineeRegister
                                registerEntity.Status = approved;
                                message = Edit(registerEntity);
                                #endregion

                                #region Tạo hv vào bảng Tra_Trainee

                                if (isTraineeInRequireDetail)
                                {
                                    if (traineeEntityInClass.Count > 0)
                                    {
                                        message = ConstantMessages.WarningProfileHaveClass.ToString().TranslateString();
                                        return(message);
                                    }
                                    if (registerEntity.ClassID != null)
                                    {
                                        if (classEntity != null && classEntity.PlanID != null)
                                        {
                                            var lstRequirementByPlanID = lstRequirement.Where(s => s.PlanID != null && s.PlanID.Value == classEntity.PlanID).ToList();
                                            foreach (var item in lstRequirementByPlanID)
                                            {
                                                var requirementDetailEntity = lstRequirementDetail.Where(s => item.ID == s.RequirementTrainID && s.CourseID == classEntity.CourseID && s.ProfileID == item.ProfileID).FirstOrDefault();
                                                if (requirementDetailEntity != null)
                                                {
                                                    var traineeEntity = new Tra_TraineeEntity();
                                                    traineeEntity.ProfileID         = registerEntity.ProfileID.Value;
                                                    traineeEntity.ClassID           = registerEntity.ClassID.Value;
                                                    traineeEntity.TraineeRegisterID = (Guid?)registerEntity.ID;
                                                    traineeServices.Add(traineeEntity);

                                                    var lstCourseTopicByCourseID = lstCourseTopic.Where(s => s.CourseID == classEntity.CourseID).ToList();
                                                    foreach (var courseTopic in lstCourseTopicByCourseID)
                                                    {
                                                        var traineeTopicEntity = new Tra_TraineeTopicEntity();
                                                        traineeTopicEntity.TopicID   = courseTopic.TopicID;
                                                        traineeTopicEntity.TraineeID = traineeEntity.ID;
                                                        message = traineeTopicServices.Add(traineeTopicEntity);
                                                    }
                                                }
                                                else
                                                {
                                                    message = ConstantMessages.WarningProfileNotInRequirement.ToString().TranslateString();
                                                }
                                            }
                                        }
                                    }
                                }

                                if (classEntity != null)
                                {
                                    if (traineeEntityInClass.Count > 0)
                                    {
                                        message = ConstantMessages.WarningProfileHaveClass.ToString().TranslateString();
                                        return(message);
                                    }

                                    var traineeEntity = new Tra_TraineeEntity();
                                    traineeEntity.ProfileID         = registerEntity.ProfileID.Value;
                                    traineeEntity.ClassID           = registerEntity.ClassID.Value;
                                    traineeEntity.TraineeRegisterID = (Guid?)registerEntity.ID;
                                    traineeServices.Add(traineeEntity);

                                    var lstCourseTopicByCourseID = lstCourseTopic.Where(s => s.CourseID == classEntity.CourseID).ToList();
                                    foreach (var courseTopic in lstCourseTopicByCourseID)
                                    {
                                        var traineeTopicEntity = new Tra_TraineeTopicEntity();
                                        traineeTopicEntity.TopicID   = courseTopic.TopicID;
                                        traineeTopicEntity.TraineeID = traineeEntity.ID;
                                        message = traineeTopicServices.Add(traineeTopicEntity);
                                    }
                                }
                                #endregion
                            }
                        }
                    }
                    #endregion
                }
                return(message);
            }
        }
Example #19
0
        public DataTable ReportUnusualPay(DateTime monthYear, List<Guid> listProfileIDs, Guid? payrollGroupID, Boolean isIncludeQuitEmp, string codeEmp, string orderNumber, string UserLogin)
        {
            try
            {
                using (var context = new VnrHrmDataContext())
                {


                    #region " Load dữ liệu"
                    string status = string.Empty;
                    var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));

                    //kỳ lương (hiện tại mặc định đầu tháng -> cuối tháng)
                    DateTime from = new DateTime(monthYear.Year, monthYear.Month, 1);
                    DateTime to = new DateTime(monthYear.Year, monthYear.Month, DateTime.DaysInMonth(monthYear.Year, monthYear.Month));

                    //Ds tất cả phòng ban
                    var orgServices = new Cat_OrgStructureServices();
                    var lstObjOrg = new List<object>();
                    //  var reposOrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                    var listOrgAll = orgServices.GetDataNotParam<Cat_OrgStructure>(ConstantSql.hrm_cat_sp_get_AllOrg, UserLogin, ref status).ToList();

                    var lstObjOrgNumber = new List<object>();
                    lstObjOrgNumber.Add(orderNumber);
                    var lstOrgID = orgServices.GetData<Cat_OrgStructureEntity>(lstObjOrgNumber, ConstantSql.hrm_cat_sp_get_OrgStructureByOrderNumber, UserLogin, ref status).Select(s => s.ID).ToList();


                    //Ds cửa Hàng
                    var shopServices = new Cat_ShopServices();
                    var lstObjShop = new List<object>();
                    lstObjShop.Add(null);
                    lstObjShop.Add(null);
                    lstObjShop.Add(null);
                    lstObjShop.Add(1);
                    lstObjShop.Add(int.MaxValue - 1);
                    var lstShop = shopServices.GetData<Cat_ShopEntity>(lstObjShop, ConstantSql.hrm_cat_sp_get_Shop, UserLogin, ref status).ToList();

                    //Ds tất cả loại PB
                    var orgTypeServices = new Cat_OrgStructureTypeServices();
                    var lstObjOrgType = new List<object>();
                    lstObjOrgType.Add(string.Empty);
                    lstObjOrgType.Add(string.Empty);
                    lstObjOrgType.Add(1);
                    lstObjOrgType.Add(int.MaxValue - 1);
                    //    var reposOrgStructureType = new CustomBaseRepository<Cat_OrgStructureType>(unitOfWork);
                    var listOrgType = orgTypeServices.GetData<Cat_OrgStructureType>(lstObjOrgType, ConstantSql.hrm_cat_sp_get_OrgStructureType, UserLogin, ref status).ToList();

                    //Ds nhân viên
                    var reposProfile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                    var profileServices = new Hre_ProfileServices();
                    var lstObjProfile = new List<object>();
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(string.Empty);
                    lstObjProfile.Add(1);
                    lstObjProfile.Add(int.MaxValue - 1);

                    //lọc theo phòng ban
                    //var listProfile = reposProfile.GetAll().Where(hr => hr.IsDelete == null
                    // && hr.OrgStructureID.HasValue
                    // && listOrgIDs.Contains(hr.OrgStructureID.Value)).ToList();
                    var listProfile = reposProfile.GetAll().Where(s => s.IsDelete != true).ToList();
                    if (listProfileIDs != null)
                    {
                        listProfile = listProfile.Where(s => listProfileIDs.Contains(s.ID)).ToList();
                    }


                    //lọc theo nhóm lương
                    // listProfile = listProfile.Where(hr => hr.PayrollGroupID.HasValue && listPrGroupIDs.Contains(hr.PayrollGroupID.Value)).ToList();
                    List<Guid> listProfileID = listProfile.Select(s => s.ID).Distinct().ToList();

                    //lọc nhân viên nghỉ việc
                    if (!isIncludeQuitEmp)
                    {
                        listProfile = listProfile.Where(pro => pro.DateHire <= to && (pro.DateQuit == null || pro.DateQuit.Value > from)).ToList();
                    }
                    if (payrollGroupID != null && payrollGroupID != Guid.Empty)
                    {
                        listProfile = listProfile.Where(s => s.PayrollGroupID == payrollGroupID).ToList();
                    }

                    //lọc theo tên nhân viên
                    if (!string.IsNullOrEmpty(codeEmp))
                    {
                        listProfile = listProfile.Where(s => s.CodeEmp == codeEmp).ToList();
                    }

                    //ds chế độ lương
                    var saleGradeServices = new Sal_GradeServices();
                    var lstObjSalGrade = new List<object>();
                    lstObjSalGrade.Add(string.Empty);
                    lstObjSalGrade.Add(string.Empty);
                    lstObjSalGrade.Add(string.Empty);
                    lstObjSalGrade.Add(string.Empty);
                    lstObjSalGrade.Add(string.Empty);
                    lstObjSalGrade.Add(1);
                    lstObjSalGrade.Add(int.MaxValue - 1);

                    var reposSalGrade = new CustomBaseRepository<Sal_Grade>(unitOfWork);
                    var lstGradeAll = reposSalGrade.GetAll().Where(s => s.IsDelete != true).ToList();
                    // var lstGradeAll = saleGradeServices.GetData<Sal_Grade>(lstObjSalGrade, ConstantSql.hrm_sal_sp_get_Sal_Grade, UserLogin,ref status).ToList();
                    //ds thông tin lương

                    var salInfoServices = new Sal_SalaryInformationServices();
                    var lstObjSalInfo = new List<object>();
                    lstObjSalInfo.Add(string.Empty);
                    lstObjSalInfo.Add(string.Empty);
                    lstObjSalInfo.Add(string.Empty);
                    lstObjSalInfo.Add(string.Empty);
                    lstObjSalInfo.Add(string.Empty);
                    lstObjSalInfo.Add(string.Empty);
                    lstObjSalInfo.Add(1);
                    lstObjSalInfo.Add(int.MaxValue - 1);

                    var salInfoServices1 = new Sal_SalaryInformationServices();
                    var lstSalaryInformation = salInfoServices.GetData<Sal_SalaryInformationEntity>(lstObjSalInfo, ConstantSql.hrm_sal_sp_get_Sal_SalaryInformation, UserLogin, ref status).OrderByDescending(sal => sal.DateUpdate).ToList().Translate<Sal_SalaryInformation>();

                    //var reposSalaryInformation = new CustomBaseRepository<Sal_SalaryInformation>(unitOfWork);
                    //var lstSalaryInformation = salInfoServices.GetData<Sal_SalaryInformation>(lstObjSalInfo, ConstantSql.hrm_sal_sp_get_Sal_SalaryInformation,UserLogin,ref status).OrderByDescending(sal => sal.DateUpdate).ToList();
                    //       var lstSalaryInformation = new Sal_SalaryInformation();

                    //ds hợp đồng
                    var contractServices = new Hre_ContractServices();
                    var lstObjContract = new List<object>();
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(string.Empty);
                    lstObjContract.Add(1);
                    lstObjContract.Add(int.MaxValue - 1);
                    var reposHreContract = new CustomBaseRepository<Hre_Contract>(unitOfWork);
                    //  var lstHreContractAll = contractServices.GetData<Hre_ContractEntity>(lstObjContract, ConstantSql.hrm_hr_sp_get_Contract, UserLogin,ref status).ToList().Translate<Hre_Contract>();
                    var lstHreContractAll = reposHreContract.GetAll().Where(s => s.IsDelete != true).ToList();

                    //ds mức lươn64864866498*-*/-*/7896543564555555978g
                    var salaryRankServices = new Cat_SalaryRankServices();
                    var lstObjSalaryRank = new List<object>();
                    lstObjSalaryRank.Add(string.Empty);
                    lstObjSalaryRank.Add(null);
                    lstObjSalaryRank.Add(1);
                    lstObjSalaryRank.Add(int.MaxValue - 1);
                    var reposSalaryRank = new CustomBaseRepository<Cat_SalaryRank>(unitOfWork);
                    var lstSalaryRankAll = salaryRankServices.GetData<Cat_SalaryRankEntity>(lstObjSalaryRank, ConstantSql.hrm_cat_sp_get_SalaryRank, UserLogin, ref status).ToList().Translate<Cat_SalaryRank>();

                    var revenueProfileServices = new Sal_RevenueForProfileServices();
                    var lstObjRevenueForProfile = new List<object>();
                    lstObjRevenueForProfile.Add(null);
                    lstObjRevenueForProfile.Add(1);
                    lstObjRevenueForProfile.Add(int.MaxValue - 1);
                    var lstRevenueForProfile = revenueProfileServices.GetData<Sal_RevenueForProfileEntity>(lstObjRevenueForProfile, ConstantSql.hrm_sal_sp_get_RevenueForProfile, UserLogin, ref status).ToList();

                    //Ds phần tử lương
                    var elementServices = new Cat_ElementServices();
                    var methodPayroll = MethodPayroll.E_ADNVANCE_PAYMENT.ToString();
                    var lstObjElement = new List<object>();
                    lstObjElement.Add("");
                    lstObjElement.Add("");
                    lstObjElement.Add("");
                    lstObjElement.Add(1);
                    lstObjElement.Add(int.MaxValue - 1);
                    var reposPayrollElement = new CustomBaseRepository<Cat_Element>(unitOfWork);
                    //var reposPayrollElement = new CustomBaseRepository<Cat_ElementMultiEntity>(unitOfWork);
                    // var listPayrollElement = elementServices.GetData<Cat_ElementMultiEntity>(lstObjElement, ConstantSql.hrm_cat_sp_get_Element,UserLogin,ref status).ToList();
                    var listPayrollElement = reposPayrollElement.GetAll().Where(s => s.MethodPayroll == methodPayroll && s.IsDelete != true).ToList();


                    // ds Bảng Ứng Lương
                    var repoUnusualPay = new CustomBaseRepository<Sal_UnusualPay>(unitOfWork);
                    var lstUnusualPay = repoUnusualPay.GetAll().Where(s => s.IsDelete != true && s.MonthYear == monthYear && listProfileID.Contains(s.ProfileID)).ToList();
                    List<Guid> lstUnusualPayIDs = lstUnusualPay.Select(s => s.ID).ToList();

                    //Ds Bảng Ứng Lương Chi Tiết
                    var repoUnusualPayItem = new CustomBaseRepository<Sal_UnusualPayItem>(unitOfWork);
                    var lstUnusualPayItem = repoUnusualPayItem.GetAll().Where(s => s.IsDelete != true && lstUnusualPayIDs.Contains(s.UnusualPayID)).ToList();

                    //      //ds bảng lương
                    //      var payrollTableServices = new Sal_PayrollTableServices();
                    //      var lstObjPayrollTable = new List<object>();
                    //      lstObjPayrollTable.Add(string.Empty);
                    //      lstObjPayrollTable.Add(string.Empty);
                    //      lstObjPayrollTable.Add(1);
                    //      lstObjPayrollTable.Add(int.MaxValue -1);
                    //      var reposSalPayrollTb = new CustomBaseRepository<Sal_PayrollTable>(unitOfWork);
                    ////      var lstSalPayrollTb = payrollTableServices.GetData<Sal_PayrollTableEntity>(lstObjPayrollTable, ConstantSql.hrm_sal_sp_get_PayrollTable, UserLogin,ref status).Where(pr => pr.IsDelete == null && pr.MonthYear == monthYear && listProfileID.Contains(pr.ProfileID)).ToList();
                    //      var lstSalPayrollTb = reposSalPayrollTb.GetAll().Where(pr => pr.IsDelete == null && pr.MonthYear == monthYear && listProfileID.Contains(pr.ProfileID)).ToList();
                    //      List<Guid> listSalPayrollIDs = lstSalPayrollTb.Select(p => p.ID).ToList();
                    //      //order theo pb
                    //      lstSalPayrollTb = lstSalPayrollTb.OrderBy(m => m.Hre_Profile.Cat_OrgStructure.OrderOrg != null ? m.Hre_Profile.Cat_OrgStructure.OrderOrg.Value : 0).ToList();

                    // //ds bảng lương chi tiết
                    // var payrollTableItemServices = new Sal_PayrollTableItemServices();
                    // var lstObjPayrollTableItem = new List<object>();
                    // lstObjPayrollTableItem.Add(string.Empty);
                    // lstObjPayrollTableItem.Add(string.Empty);
                    // lstObjPayrollTableItem.Add(1);
                    // lstObjPayrollTableItem.Add(int.MaxValue -1);
                    // var reposSalPayrollTbItem = new CustomBaseRepository<Sal_PayrollTableItem>(unitOfWork);
                    //// var lstSalPayrollTbItem = payrollTableItemServices.GetData<Sal_PayrollTableItem>(lstObjPayrollTableItem, ConstantSql.hrm_sal_sp_get_PayrollTableItem, UserLogin,ref status).Where(it => it.IsDelete == null && listSalPayrollIDs.Contains(it.PayrollTableID)).ToList();
                    // var lstSalPayrollTbItem = reposSalPayrollTbItem.GetAll().Where(it => it.IsDelete == null && listSalPayrollIDs.Contains(it.PayrollTableID)).ToList();

                    //Tạo cột dữ liệu cho table
                    DataTable tblData = GetSchemaReportUnusualPay();
                    #endregion
                    #region " Không có dữ liệu Sal_PayrollTable"
                    if (lstUnusualPay == null || lstUnusualPay.Count <= 0)
                    {
                        foreach (Hre_Profile profile in listProfile)
                        {
                            DataRow dr = tblData.NewRow();
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.MonthYear] = monthYear;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeEmp] = profile.CodeEmp;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeAttendance] = profile.CodeAttendance;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.ProfileName] = profile.ProfileName;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.LaborType] = profile.LaborType;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.EmployeeType] = profile.Cat_EmployeeType != null ? profile.Cat_EmployeeType.EmployeeTypeName : string.Empty;

                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.Supervisor] = profile.Supervisor != null ? profile.Supervisor : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.HighSupervisor] = profile.HighSupervisor != null ? profile.HighSupervisor : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.WorkPlace] = profile.Cat_WorkPlace != null ? profile.Cat_WorkPlace.WorkPlaceName : string.Empty;
                            //   dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.WorkingPlace] = profile.WorkingPlace != null ? profile.WorkingPlace : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.TaxCode] = profile.CodeTax != null ? profile.CodeTax : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.IDNo] = profile.IDNo != null ? profile.IDNo : string.Empty;

                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenter] = profile.Cat_CostCentre != null ? profile.Cat_CostCentre.CostCentreName : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenterCode] = profile.Cat_CostCentre != null ? profile.Cat_CostCentre.Code : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.PositionName] = profile.Cat_Position != null ? profile.Cat_Position.PositionName : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.JobtitleName] = profile.Cat_JobTitle != null ? profile.Cat_JobTitle.JobTitleName : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.Email] = profile.Email != null ? profile.Email : string.Empty;
                            if (profile.DateHire != null)
                                dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateHire] = profile.DateHire.Value;
                            if (profile.DateQuit != null)
                                dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateQuit] = profile.DateQuit;
                            if (profile.DateEndProbation != null)
                                dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateEndProbation] = profile.DateEndProbation.Value;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.SocialInsNo] = profile.SocialInsNo != null ? profile.SocialInsNo : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.PayrollGroup] = profile.Cat_PayrollGroup != null ? profile.Cat_PayrollGroup.PayrollGroupName : string.Empty;

                            if (profile.OrgStructureID != null)
                            {
                                var orgName = GetParentOrg(listOrgAll, listOrgType, profile.OrgStructureID);
                                if (orgName.Count < 3)
                                {
                                    orgName.Insert(0, string.Empty);
                                    if (orgName.Count < 3)
                                    {
                                        orgName.Insert(0, string.Empty);
                                    }
                                }
                                dr[Hre_ReportHCSalesEntity.FieldNames.Channel] = orgName[2];
                                dr[Hre_ReportHCSalesEntity.FieldNames.Region] = orgName[1];
                                dr[Hre_ReportHCSalesEntity.FieldNames.Area] = orgName[0];

                                //var orgBranch = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_BRANCH, listOrgAll, listOrgType);
                                //var orgOrg = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_DEPARTMENT, listOrgAll, listOrgType);
                                //var orgTeam = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_TEAM, listOrgAll, listOrgType);
                                //var orgSection = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_SECTION, listOrgAll, listOrgType);
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BranchCode] = orgBranch != null ? orgBranch.Code : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DepartmentCode] = orgOrg != null ? orgOrg.Code : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.TeamCode] = orgTeam != null ? orgTeam.Code : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.SectionCode] = orgSection != null ? orgSection.Code : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BranchName] = orgBranch != null ? orgBranch.OrgStructureName : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DepartmentName] = orgOrg != null ? orgOrg.OrgStructureName : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.TeamName] = orgTeam != null ? orgTeam.OrgStructureName : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.SectionName] = orgSection != null ? orgSection.OrgStructureName : string.Empty;
                            }

                            Hre_Contract hrcontract = lstHreContractAll.Where(hr => hr.ProfileID == profile.ID && hr.IsDelete == null).FirstOrDefault();
                            if (hrcontract != null && hrcontract.RankRateID != null)
                            {
                                Cat_SalaryRank salrank = lstSalaryRankAll.Where(rk => rk.ID == hrcontract.RankRateID.Value && rk.IsDelete == null).FirstOrDefault();
                                dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.SalaryRankName] = salrank != null ? salrank.SalaryRankName : string.Empty;
                            }

                            #region Insurance, Bank
                            var salaryInformationList = lstSalaryInformation.Where(sal => sal.ProfileID == profile.ID).ToList();
                            if (salaryInformationList.Count > 0)
                            {
                                Sal_SalaryInformation bankSalary = salaryInformationList[0];
                                string accountTemp = string.Empty;
                                string accountNo = string.Empty;
                                string accountNo2 = string.Empty;
                                string bankNameTemp = string.Empty;
                                string bankCode = string.Empty;

                                accountTemp = bankSalary.AccountNo == null ? string.Empty : bankSalary.AccountNo;
                                accountNo = bankSalary.AccountNo == null ? string.Empty : bankSalary.AccountNo;
                                accountNo2 = bankSalary.AccountNo2 == null ? string.Empty : bankSalary.AccountNo2;
                                bankNameTemp = bankSalary.Cat_Bank == null ? string.Empty : bankSalary.Cat_Bank.BankName;
                                bankCode = bankSalary.Cat_Bank == null ? string.Empty : bankSalary.Cat_Bank.BankCode;

                                if (!string.IsNullOrEmpty(accountTemp))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BankAccountNo] = accountTemp.Trim();
                                if (!string.IsNullOrEmpty(accountNo))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.AccountNo] = accountNo.Trim();
                                if (!string.IsNullOrEmpty(accountNo2))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.AccountNo2] = accountNo2.Trim();
                                if (!string.IsNullOrEmpty(bankCode))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BankCode] = bankCode.Trim();
                                if (!string.IsNullOrEmpty(bankNameTemp))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BankName] = bankNameTemp.Trim();
                            }
                            #endregion

                            tblData.Rows.Add(dr);
                        }
                    }
                    #endregion
                    #region " Có dữ liệu tính lương Sal_PayrollTable"
                    else
                    {
                        foreach (Sal_UnusualPay payroll in lstUnusualPay)
                        {
                            Hre_Profile profile = listProfile.Where(s => s.ID == payroll.ProfileID).FirstOrDefault();
                            // var lstRevenueByProfileId = lstRevenueForProfile.Where(s => s.ProfileID == payroll.ProfileID).FirstOrDefault();
                            //  var lstRankByProfileId = lstShop.Where(s => s.ID == profile.ShopID).FirstOrDefault();
                            List<Sal_UnusualPayItem> listItem = lstUnusualPayItem.Where(pi => pi.UnusualPayID == payroll.ID).ToList();
                            if (profile == null)
                                continue;

                            DataRow dr = tblData.NewRow();
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.MonthYear] = monthYear;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeEmp] = profile.CodeEmp;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeAttendance] = profile.CodeAttendance;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.ProfileName] = profile.ProfileName;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.LaborType] = profile.LaborType;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.EmployeeType] = profile.Cat_EmployeeType != null ? profile.Cat_EmployeeType.EmployeeTypeName : string.Empty;

                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.Supervisor] = profile.Supervisor != null ? profile.Supervisor : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.HighSupervisor] = profile.HighSupervisor != null ? profile.HighSupervisor : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.WorkPlace] = profile.Cat_WorkPlace != null ? profile.Cat_WorkPlace.WorkPlaceName : string.Empty;
                            //  dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.WorkingPlace] = profile.WorkingPlace != null ? profile.WorkingPlace : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.TaxCode] = profile.CodeTax != null ? profile.CodeTax : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.IDNo] = profile.IDNo != null ? profile.IDNo : string.Empty;

                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenter] = profile.Cat_CostCentre != null ? profile.Cat_CostCentre.CostCentreName : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenterCode] = profile.Cat_CostCentre != null ? profile.Cat_CostCentre.Code : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.PositionName] = profile.Cat_Position != null ? profile.Cat_Position.PositionName : string.Empty;
                            dr["PositionCode"] = profile.Cat_Position != null ? profile.Cat_Position.Code : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.JobtitleName] = profile.Cat_JobTitle != null ? profile.Cat_JobTitle.JobTitleName : string.Empty;
                            dr["JobtitleCode"] = profile.Cat_JobTitle != null ? profile.Cat_JobTitle.Code : string.Empty;
                            //      dr["Rank"] = lstRankByProfileId != null ? lstRankByProfileId.Rank : string.Empty;
                            //   dr["Target"] = lstRevenueByProfileId != null ? lstRevenueByProfileId.Target : 0;
                            //     dr["Actual"] = lstRevenueByProfileId != null ? lstRevenueByProfileId.Actual : 0;

                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.Email] = profile.Email != null ? profile.Email : string.Empty;
                            if (profile.DateHire != null)
                                dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateHire] = profile.DateHire.Value;
                            if (profile.DateQuit != null)
                                dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateQuit] = profile.DateQuit;
                            if (profile.DateEndProbation != null)
                                dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateEndProbation] = profile.DateEndProbation.Value;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.SocialInsNo] = profile.SocialInsNo != null ? profile.SocialInsNo : string.Empty;
                            dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.PayrollGroup] = profile.Cat_PayrollGroup != null ? profile.Cat_PayrollGroup.PayrollGroupName : string.Empty;

                            if (profile.OrgStructureID != null)
                            {

                                var orgName = GetParentOrgNameForShiseido(listOrgAll, listOrgType, profile.OrgStructureID);
                                if (orgName.Count < 5)
                                {
                                    orgName.Insert(0, string.Empty);
                                    if (orgName.Count < 5)
                                    {
                                        orgName.Insert(0, string.Empty);
                                    }
                                    if (orgName.Count < 5)
                                    {
                                        orgName.Insert(0, string.Empty);
                                    }
                                    if (orgName.Count < 5)
                                    {
                                        orgName.Insert(0, string.Empty);
                                    }
                                    if (orgName.Count < 5)
                                    {
                                        orgName.Insert(0, string.Empty);
                                    }

                                }

                                dr["Công Ty"] = orgName[4];
                                dr["Chi Nhánh"] = orgName[3];
                                dr[Hre_ReportHCSalesEntity.FieldNames.Channel] = orgName[2];
                                dr[Hre_ReportHCSalesEntity.FieldNames.Region] = orgName[1];
                                dr[Hre_ReportHCSalesEntity.FieldNames.Area] = orgName[0];

                                var orgCode = GetParentOrgCodeForShiseido(listOrgAll, listOrgType, profile.OrgStructureID);
                                if (orgCode.Count < 5)
                                {
                                    orgCode.Insert(0, string.Empty);
                                    if (orgCode.Count < 5)
                                    {
                                        orgCode.Insert(0, string.Empty);
                                    }
                                    if (orgCode.Count < 5)
                                    {
                                        orgCode.Insert(0, string.Empty);
                                    }
                                    if (orgCode.Count < 5)
                                    {
                                        orgCode.Insert(0, string.Empty);
                                    }
                                    if (orgCode.Count < 5)
                                    {
                                        orgCode.Insert(0, string.Empty);
                                    }
                                }
                                dr["Mã Công Ty"] = orgCode[4];
                                dr["Mã Chi Nhánh"] = orgCode[3];
                                dr["Mã Channel"] = orgCode[2];
                                dr["Mã Region"] = orgCode[1];
                                dr["Mã Area"] = orgCode[0];

                                //var orgBranch = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_BRANCH, listOrgAll, listOrgType);
                                //var orgOrg = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_DEPARTMENT, listOrgAll, listOrgType);
                                //var orgTeam = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_TEAM, listOrgAll, listOrgType);
                                //var orgSection = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_SECTION, listOrgAll, listOrgType);
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BranchCode] = orgBranch != null ? orgBranch.Code : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DepartmentCode] = orgOrg != null ? orgOrg.Code : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.TeamCode] = orgTeam != null ? orgTeam.Code : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.SectionCode] = orgSection != null ? orgSection.Code : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BranchName] = orgBranch != null ? orgBranch.OrgStructureName : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DepartmentName] = orgOrg != null ? orgOrg.OrgStructureName : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.TeamName] = orgTeam != null ? orgTeam.OrgStructureName : string.Empty;
                                //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.SectionName] = orgSection != null ? orgSection.OrgStructureName : string.Empty;
                            }

                            Hre_Contract hrcontract = lstHreContractAll.Where(hr => hr.ProfileID == profile.ID && hr.IsDelete == null).FirstOrDefault();
                            if (hrcontract != null && hrcontract.RankRateID != null)
                            {
                                Cat_SalaryRank salrank = lstSalaryRankAll.Where(rk => rk.ID == hrcontract.RankRateID.Value && rk.IsDelete == null).FirstOrDefault();
                                if (salrank != null)
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.SalaryRankName] = salrank.SalaryRankName;
                            }

                            #region Insurance, Bank
                            List<Sal_SalaryInformation> salaryInformationList = lstSalaryInformation.Where(sal => sal.ProfileID == profile.ID).ToList();
                            if (salaryInformationList.Count > 0)
                            {
                                Sal_SalaryInformation bankSalary = salaryInformationList[0];
                                string accountTemp = string.Empty;
                                string accountNo = string.Empty;
                                string accountNo2 = string.Empty;
                                string bankNameTemp = string.Empty;
                                string bankCode = string.Empty;

                                accountTemp = bankSalary.AccountNo == null ? string.Empty : bankSalary.AccountNo;
                                accountNo = bankSalary.AccountNo == null ? string.Empty : bankSalary.AccountNo;
                                accountNo2 = bankSalary.AccountNo2 == null ? string.Empty : bankSalary.AccountNo2;
                                bankNameTemp = bankSalary.Cat_Bank == null ? string.Empty : bankSalary.Cat_Bank.BankName;
                                bankCode = bankSalary.Cat_Bank == null ? string.Empty : bankSalary.Cat_Bank.BankCode;

                                if (!string.IsNullOrEmpty(accountTemp))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BankAccountNo] = accountTemp.Trim();
                                if (!string.IsNullOrEmpty(accountNo))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.AccountNo] = accountNo.Trim();
                                if (!string.IsNullOrEmpty(accountNo2))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.AccountNo2] = accountNo2.Trim();
                                if (!string.IsNullOrEmpty(bankCode))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BankCode] = bankCode.Trim();
                                if (!string.IsNullOrEmpty(bankNameTemp))
                                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.BankName] = bankNameTemp.Trim();
                            }
                            #endregion

                            #region sal grade
                            //   Sal_Grade grade = lstGradeAll.Where(gr => gr.IsDelete == null && gr.ProfileID == profile.ID
                            //                                           && gr.MonthStart < to).OrderByDescending(gr => gr.MonthStart).FirstOrDefault();
                            // if (grade != null)
                            //  {
                            // Cat_GradePayroll gradepayroll = grade.Cat_GradePayroll1;
                            // if (gradepayroll != null && gradepayroll.IsFormulaSalary == true)
                            //   {
                            try
                            {
                                var lstSalPrItem = lstUnusualPayItem.Where(sal => sal.UnusualPayID == payroll.ID).ToList();
                                //  var lstelement = listPayrollElement.Where(pr => pr.GradePayrollID == gradepayroll.ID).ToList();
                                if (listPayrollElement != null && listPayrollElement.Count > 0)
                                {
                                    foreach (Cat_Element payrollElement in listPayrollElement)
                                    {
                                        if (payrollElement != null && !String.IsNullOrEmpty(payrollElement.ElementCode))
                                        {
                                            //Add phần tử vào cột dữ liệu nếu chưa có
                                            if (!tblData.Columns.Contains(payrollElement.ElementCode))
                                            {
                                                tblData.Columns.Add(payrollElement.ElementCode, typeof(Double));
                                            }
                                            //Lấy value của phần tử 
                                            if (tblData.Columns.Contains(payrollElement.ElementCode))
                                            {
                                                Sal_UnusualPayItem item = lstSalPrItem.Where(it => it.Element == payrollElement.ElementCode).FirstOrDefault();
                                                Double value = 0;
                                                if (item != null)
                                                {
                                                    //if (item.ValueType == typeof(Double).Name)
                                                    //  {
                                                    Double.TryParse(item.Amount.ToString(), out value);
                                                    // }
                                                }
                                                dr[payrollElement.ElementCode] = value;
                                            }
                                        }
                                    }
                                }
                            }
                            catch { }
                            // }
                            // }
                            #endregion

                            tblData.Rows.Add(dr);
                        }
                    }
                    #endregion
                    return tblData.ConfigTable(true);
                }
            }
            catch (Exception ex)
            {
                return new DataTable();
            }
        }
Example #20
0
        public String SaveLeaveDataItem(Guid workDayID, Guid LeaveTypeID, Guid? userApprove, string comment, bool IsAllowModify)
        {
            var message = "";
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
                var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
                var repoCat_Shift = new CustomBaseRepository<Cat_Shift>(unitOfWork);
                var repoAtt_Workday = new CustomBaseRepository<Att_Workday>(unitOfWork);
                var repoSys_AllSeting = new CustomBaseRepository<Sys_AllSetting>(unitOfWork);
                var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoAtt_Grade = new CustomBaseRepository<Att_Grade>(unitOfWork);
                var repoCat_GradeAttendance = new CustomBaseRepository<Cat_GradeAttendance>(unitOfWork);
                var repoHre_WorkHistory = new CustomBaseRepository<Hre_WorkHistory>(unitOfWork);
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
                var repoAtt_Roster = new CustomBaseRepository<Att_Roster>(unitOfWork);

                var shifts = repoCat_Shift.FindBy(s => s.IsDelete == null).ToList();
                Att_WorkdayEntity WorkDayInDB = repoAtt_Workday.FindBy(m => m.ID == workDayID).FirstOrDefault().CopyData<Att_WorkdayEntity>();
                if (WorkDayInDB == null || LeaveTypeID == Guid.Empty)
                {
                    //return WorkDayInDB.CopyData<Att_WorkdayEntity>();
                    message = ConstantMessages.PlsSelectLeaveType.TranslateString();
                    return message;
                }
                #region [Hien.Nguyen] - Nếu ngày đó đã có loại ngày nghỉ này rồi thì out function
                var tmp = repoAtt_LeaveDay.FindBy(m => m.IsDelete == null && m.ProfileID == WorkDayInDB.ProfileID && m.LeaveDayTypeID == LeaveTypeID && m.DateStart <= WorkDayInDB.WorkDate && m.DateEnd >= WorkDayInDB.WorkDate).FirstOrDefault();
                if (tmp != null)
                {
                    message = "Đã Có Ngày Nghỉ";
                    return message;
                    //return WorkDayInDB.CopyData<Att_WorkdayEntity>();
                }
                #endregion



                Cat_Shift shift = repoCat_Shift.FindBy(m => m.ID == WorkDayInDB.ShiftID).FirstOrDefault();
                if (shift == null)
                {
                    //return WorkDayInDB.CopyData<Att_WorkdayEntity>();
                    message = ConstantMessages.Error.TranslateString();
                    return message;
                }
                var leaveType = repoCat_LeaveDayType.FindBy(m => m.ID == LeaveTypeID).Select(m => new { m.Code, m.CodeStatistic }).FirstOrDefault();
                var leaveTypeCode = string.Empty;
                if (leaveType != null)
                {
                    leaveTypeCode = leaveType.CodeStatistic ?? leaveType.Code;
                }
                DateTime workday = WorkDayInDB.WorkDate;
                DateTime beginDate = workday.Date;
                DateTime endDate = beginDate.AddDays(1).AddMinutes(-1);

                DateTime beginShift = workday.AddHours(shift.InTime.Hour).AddMinutes(shift.InTime.Minute);
                DateTime endShift = beginShift.AddHours(shift.CoOut);
                List<Att_LeaveDay> lstLeaveDayInDbUpdate = repoAtt_LeaveDay.FindBy(m =>
                    m.DateStart <= endDate && m.DateEnd >= beginDate && m.ProfileID == WorkDayInDB.ProfileID).ToList<Att_LeaveDay>();

                List<Att_LeaveDay> lstLeaveDayInsert = new List<Att_LeaveDay>();
                if (WorkDayInDB.InTime1 == null || WorkDayInDB.OutTime1 == null)
                //Thiếu 1 trong 2 la tao nghi full ca
                {
                    if (IsAllowModify && lstLeaveDayInDbUpdate.Count > 0 && !lstLeaveDayInDbUpdate.Any(m => m.Status == LeaveDayStatus.E_APPROVED.ToString()))
                    {
                        lstLeaveDayInDbUpdate.ForEach(m => m.LeaveDayTypeID = LeaveTypeID);
                    }
                    else
                    {
                        Att_LeaveDay LeavedayInsert = new Att_LeaveDay();
                        LeavedayInsert.ID = Guid.NewGuid();
                        LeavedayInsert.ProfileID = WorkDayInDB.ProfileID;
                        LeavedayInsert.TotalDuration = 1;
                        LeavedayInsert.LeaveDays = 1;
                        LeavedayInsert.Duration = shift.WorkHours ?? 8;
                        LeavedayInsert.LeaveHours = shift.WorkHours ?? 8;
                        LeavedayInsert.DurationType = LeaveDayDurationType.E_FULLSHIFT.ToString();
                        LeavedayInsert.DateStart = workday;
                        LeavedayInsert.DateEnd = workday;
                        LeavedayInsert.LeaveDayTypeID = LeaveTypeID;
                        LeavedayInsert.Status = LeaveDayStatus.E_SUBMIT.ToString();
                        lstLeaveDayInsert.Add(LeavedayInsert);
                    }
                }
                else // thuộc loại trễ sớm
                {
                    if (IsAllowModify && lstLeaveDayInDbUpdate.Count > 0 && !lstLeaveDayInDbUpdate.Any(m => m.Status == LeaveDayStatus.E_APPROVED.ToString()))
                    {
                        lstLeaveDayInDbUpdate.ForEach(m => m.LeaveDayTypeID = LeaveTypeID);
                    }
                    else
                    {
                        if (WorkDayInDB.LateDuration1 != null && WorkDayInDB.LateDuration1 > 0) //đi trễ
                        {
                            double HourLeave = (int)(WorkDayInDB.LateDuration1 ?? 0) / 60;
                            if (((WorkDayInDB.LateDuration1 ?? 0) % 60) > 0)
                                HourLeave = HourLeave + 1;
                            //di trễ thì loại của no la nua ca dau 
                            Att_LeaveDay LeavedayInsert = new Att_LeaveDay();
                            LeavedayInsert.ID = Guid.NewGuid();
                            LeavedayInsert.ProfileID = WorkDayInDB.ProfileID;
                            LeavedayInsert.TotalDuration = 1;
                            LeavedayInsert.LeaveDays = 1;
                            LeavedayInsert.Duration = HourLeave;
                            LeavedayInsert.LeaveHours = HourLeave;
                            LeavedayInsert.DurationType = LeaveDayDurationType.E_FIRSTHALFSHIFT.ToString();
                            LeavedayInsert.DateStart = beginShift;
                            LeavedayInsert.DateEnd = beginShift.AddHours(HourLeave);
                            LeavedayInsert.LeaveDayTypeID = LeaveTypeID;
                            LeavedayInsert.Status = LeaveDayStatus.E_SUBMIT.ToString();
                            lstLeaveDayInsert.Add(LeavedayInsert);

                        }
                        else if (WorkDayInDB.EarlyDuration1 != null && WorkDayInDB.EarlyDuration1 > 0) //Về sớm
                        {
                            //về sơm thi loại cua no la nua ca sau
                            double HourLeave = (int)(WorkDayInDB.EarlyDuration1 ?? 0) / 60;
                            if (((WorkDayInDB.EarlyDuration1 ?? 0) % 60) > 0)
                                HourLeave = HourLeave + 1;
                            //di trễ thì loại của no la nua ca sai
                            Att_LeaveDay LeavedayInsert = new Att_LeaveDay();
                            LeavedayInsert.ID = Guid.NewGuid();
                            LeavedayInsert.ProfileID = WorkDayInDB.ProfileID;
                            LeavedayInsert.TotalDuration = 1;
                            LeavedayInsert.LeaveDays = 1;
                            LeavedayInsert.Duration = HourLeave;
                            LeavedayInsert.LeaveHours = HourLeave;
                            LeavedayInsert.DurationType = LeaveDayDurationType.E_FIRSTHALFSHIFT.ToString();
                            LeavedayInsert.DateStart = endShift.AddHours(-HourLeave);
                            LeavedayInsert.DateEnd = endShift;
                            LeavedayInsert.LeaveDayTypeID = LeaveTypeID;
                            LeavedayInsert.Status = LeaveDayStatus.E_SUBMIT.ToString();
                            lstLeaveDayInsert.Add(LeavedayInsert);

                        }
                    }
                }
                foreach (var item in lstLeaveDayInsert)
                {
                    if (userApprove != null)
                    {
                        item.UserApproveID = userApprove.Value;
                    }
                    item.Comment = comment;
                }
                #region Triet.Mai Validate Nghỉ Bù
                if (lstLeaveDayInsert.Count > 0)
                {
                    List<Guid> LeaveTypeDayOffID = repoCat_LeaveDayType.FindBy(m => m.IsTimeOffInLieu == true).Select(m => m.ID).ToList<Guid>();
                    if (lstLeaveDayInsert.FirstOrDefault().Status != OverTimeStatus.E_CANCEL.ToString() && LeaveTypeDayOffID.Any(m => m == lstLeaveDayInsert.FirstOrDefault().LeaveDayTypeID))
                    {
                        message = ValidateLeaveDayTimeOff(lstLeaveDayInsert.Select(m => m.ProfileID).Distinct().ToList(), lstLeaveDayInsert);
                        if (message != string.Empty)
                        {
                            //ErrorMessages = Error;
                            return message;
                        }
                    }
                }
                #endregion

                #region triet.mai validate vấn đề ngày nghỉ dành cho nhân viên thực tập
                string HRM_ATT_STAFF_PROBATION = AppConfig.HRM_ATT_STAFF_PROBATION.ToString();
                Sys_AllSetting config = repoSys_AllSeting.FindBy(m => m.Name == HRM_ATT_STAFF_PROBATION).FirstOrDefault();
                string validateEmpProbation = ValidateLeaveTypeByNewEmployee(config, lstLeaveDayInsert);
                if (validateEmpProbation != string.Empty)
                {
                    //ErrorMessages = validateEmpProbation;
                    return null;
                }
                #endregion

                //Cap nhat leavedayID cho workday o day
                if (lstLeaveDayInsert.Count > 0)
                {
                    if (lstLeaveDayInsert.Count > 1)
                    {
                        WorkDayInDB.LeaveDayID1 = lstLeaveDayInsert[0].ID;
                        WorkDayInDB.LeaveDayID2 = lstLeaveDayInsert[1].ID;
                        WorkDayInDB.udLeavedayCode1 = leaveTypeCode;
                        WorkDayInDB.udLeavedayCode2 = leaveTypeCode;
                        WorkDayInDB.udLeavedayStatus1 = lstLeaveDayInsert.FirstOrDefault().Status;
                        WorkDayInDB.udLeavedayStatus2 = lstLeaveDayInsert.FirstOrDefault().Status;
                    }
                    else
                    {
                        WorkDayInDB.LeaveDayID1 = lstLeaveDayInsert[0].ID;
                        WorkDayInDB.udLeavedayCode1 = leaveTypeCode;
                        WorkDayInDB.udLeavedayStatus1 = lstLeaveDayInsert.FirstOrDefault().Status;
                    }
                }
                else if (lstLeaveDayInDbUpdate.Count > 0)
                {
                    if (lstLeaveDayInDbUpdate.Count >= 2)
                    {
                        WorkDayInDB.udLeavedayCode1 = leaveTypeCode;
                        WorkDayInDB.udLeavedayCode2 = leaveTypeCode;
                        WorkDayInDB.udLeavedayStatus1 = lstLeaveDayInDbUpdate.FirstOrDefault().Status;
                        WorkDayInDB.udLeavedayStatus2 = lstLeaveDayInDbUpdate.FirstOrDefault().Status;
                    }
                    else
                    {
                        WorkDayInDB.udLeavedayCode1 = leaveTypeCode;
                        WorkDayInDB.udLeavedayStatus1 = lstLeaveDayInDbUpdate.FirstOrDefault().Status;
                        WorkDayInDB.udLeavedayStatus2 = lstLeaveDayInDbUpdate.FirstOrDefault().Status;
                    }
                }

                #region triet.mai cap nhat leaveDays va leaveHours
                List<Cat_LeaveDayType> lstLeaveDayType = repoCat_LeaveDayType.GetAll().ToList<Cat_LeaveDayType>();
                List<Guid> lstProfileID1 = lstLeaveDayInsert.Select(m => m.ProfileID).Distinct().ToList<Guid>();
                List<Hre_Profile> lstProfile = repoHre_Profile.FindBy(m => lstProfileID1.Contains(m.ID)).ToList<Hre_Profile>();
                DateTime dateMin1 = lstLeaveDayInsert.Min(m => m.DateStart).Date;
                DateTime dateMax1 = lstLeaveDayInsert.Max(m => m.DateEnd);
                List<Att_Roster> lstRosterTypeGroup = new List<Att_Roster>();
                List<Att_RosterGroup> lstRosterGroup = new List<Att_RosterGroup>();
                var lstGrade = repoAtt_Grade.FindBy(m => lstProfileID1.Contains((Guid)m.ProfileID))
                    .Select(m => new { m.ID, m.ProfileID, m.MonthStart, m.GradeAttendanceID })
                    .OrderByDescending(m => m.MonthStart)
                    .ToList();
                List<Cat_GradeAttendance> lstGradeCfg = repoCat_GradeAttendance.GetAll().ToList<Cat_GradeAttendance>();
                List<Hre_WorkHistory> listWorkHistory = repoHre_WorkHistory.FindBy(m => m.DateEffective <= dateMax1 && lstProfileID1.Contains(m.ProfileID)).OrderByDescending(m => m.DateEffective).ToList<Hre_WorkHistory>();
                GetRosterGroup(lstProfileID1, dateMin1, dateMax1, out lstRosterTypeGroup, out lstRosterGroup);
                List<Cat_DayOff> lstHoliday = repoCat_DayOff.GetAll().ToList();
                string E_APPROVED1 = RosterStatus.E_APPROVED.ToString();
                string E_ROSTERGROUP = RosterType.E_ROSTERGROUP.ToString();
                List<Att_Roster> lstRoster = repoAtt_Roster.FindBy(m => m.Status == E_APPROVED1 && m.DateStart <= dateMax1 && m.DateEnd >= dateMin1 && lstProfileID1.Contains(m.ProfileID)).ToList<Att_Roster>();
                List<DateTime> lstHolidayType = lstHoliday.Select(m => m.DateOff).ToList<DateTime>();
                //LeaveDayDAO ldDao = new LeaveDayDAO();
                foreach (var item in lstLeaveDayInsert)
                {
                    if (item.DurationType != null && item.DurationType != LeaveDayDurationType.E_FULLSHIFT.ToString())
                        continue;
                    Cat_LeaveDayType leaveDayType = lstLeaveDayType.Where(m => m.ID == item.LeaveDayTypeID).FirstOrDefault();
                    if (leaveDayType == null)
                        continue;
                    Hre_Profile profileInLeave = lstProfile.Where(m => m.ID == item.ProfileID).FirstOrDefault();
                    if (profileInLeave == null)
                        continue;

                    DateTime dateFrom = item.DateStart;
                    DateTime dateTo = item.DateEnd;
                    dateTo = dateTo.AddDays(1).AddMinutes(-1);

                    Guid GradeCfgID = lstGrade.Where(m => m.ProfileID.Value == profileInLeave.ID && m.MonthStart <= dateTo).Select(m => m.GradeAttendanceID.Value).FirstOrDefault();
                    Cat_GradeAttendance gradeCfg = lstGradeCfg.Where(m => m.ID == GradeCfgID).FirstOrDefault();
                    List<Att_Roster> lstRosterByProfile = lstRoster.Where(m => m.ProfileID == profileInLeave.ID).ToList();
                    List<Hre_WorkHistory> listWorkHistoryByProfile = listWorkHistory.Where(m => m.ProfileID == profileInLeave.ID && m.DateEffective < dateTo).ToList();
                    List<Att_Roster> lstRosterByProfileTypeGroup = lstRosterByProfile.Where(m => m.Type == E_ROSTERGROUP).ToList();
                    AnalyseTotalLeaveDaysAndHours(item, leaveDayType, profileInLeave, gradeCfg, lstRosterByProfile, lstRosterGroup, listWorkHistoryByProfile, lstHoliday, shifts);
                }
                #endregion

                //var listWorkDay=repoAtt_Workday.GetAll().ToList();
                //Att_Workday workdayOld = listWorkDay.Where(m => m.ProfileID == WorkDayInDB.ProfileID && m.WorkDate == WorkDayInDB.WorkDate).FirstOrDefault();
                //if (workdayOld != null)
                //{
                //    int index = listWorkDay.IndexOf(workdayOld);
                //    listWorkDay.Remove(workdayOld);
                //    listWorkDay.Insert(index, WorkDayInDB.CopyData<Att_Workday>());
                //}
                repoAtt_LeaveDay.Add(lstLeaveDayInsert);
                unitOfWork.SaveChanges();
                //EntityService.AddEntity<Att_LeaveDay>(GuidContext, lstLeaveDayInsert.ToArray());
                //message = "Susscess";
                return message;
                //return WorkDayInDB;
            }
        }
Example #21
0
        /// <summary>
        /// Hàm cập nhật lại TotalDuration cho nhân viên
        /// </summary>
        /// <param name="lstLeaveIDs"></param>
        public string UpdateTotalDuration(List<Guid> lstLeaveIDs)
        {
            string message = "";

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_Leaveday = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
                var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
                var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoAtt_Grade = new CustomBaseRepository<Att_Grade>(unitOfWork);
                var repoCat_GradeAttendance = new CustomBaseRepository<Cat_GradeAttendance>(unitOfWork);
                var repoHre_WorkHistory = new CustomBaseRepository<Hre_WorkHistory>(unitOfWork);
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
                var repoAtt_Roster = new CustomBaseRepository<Att_Roster>(unitOfWork);
                var repoCat_Shift = new Cat_ShiftRepository(unitOfWork);
                var shifts = repoCat_Shift.FindBy(s => s.IsDelete == null).ToList();

                List<Att_LeaveDay> lstLeaveDay = repoAtt_Leaveday.FindBy(m => lstLeaveIDs.Contains(m.ID)).ToList<Att_LeaveDay>();
                if (lstLeaveDay == null || lstLeaveDay.Count == 0)
                {
                    message = ConstantMessages.LeavedayIsNotExist.TranslateString();
                    return message;
                }
                foreach (var item in lstLeaveDay)
                {
                    if (item.Status == AttendanceDataStatus.E_FIRST_APPROVED.ToString() || item.Status == AttendanceDataStatus.E_APPROVED.ToString())
                    {
                        message = ConstantMessages.StatusApproveCannotEdit.TranslateString();
                        return message;
                    }
                    if (item.Status == AttendanceDataStatus.E_REJECTED.ToString())
                    {
                        message = ConstantMessages.StatusRejectcannotEdit.TranslateString();
                        return message;
                    }
                }
                List<Cat_LeaveDayType> lstLeaveDayType = repoCat_LeaveDayType.GetAll().ToList<Cat_LeaveDayType>();
                List<Guid> lstProfileIDs = lstLeaveDay.Select(m => m.ProfileID).Distinct().ToList<Guid>();
                List<Hre_Profile> lstProfile = repoHre_Profile.FindBy(m => lstProfileIDs.Contains(m.ID)).ToList<Hre_Profile>();
                DateTime dateMin = lstLeaveDay.Min(m => m.DateStart).Date;
                DateTime dateMax = lstLeaveDay.Max(m => m.DateEnd);
                List<Att_Roster> lstRosterTypeGroup = new List<Att_Roster>();
                List<Att_RosterGroup> lstRosterGroup = new List<Att_RosterGroup>();
                var lstGrade = repoAtt_Grade.FindBy(m => lstProfileIDs.Contains((Guid)m.ProfileID))
                    .Select(m => new { m.ID, m.ProfileID, m.MonthStart, m.GradeAttendanceID })
                    .OrderByDescending(m => m.MonthStart)
                    .ToList();


                List<Cat_GradeAttendance> lstGradeCfg = repoCat_GradeAttendance.GetAll().ToList<Cat_GradeAttendance>();
                List<Hre_WorkHistory> listWorkHistory = repoHre_WorkHistory.FindBy(m => m.DateEffective <= dateMax && lstProfileIDs.Contains(m.ProfileID)).OrderByDescending(m => m.DateEffective).ToList<Hre_WorkHistory>();
                GetRosterGroup(lstProfileIDs, dateMin, dateMax, out lstRosterTypeGroup, out lstRosterGroup);
                List<Cat_DayOff> lstHoliday = repoCat_DayOff.GetAll().ToList<Cat_DayOff>();
                string E_APPROVED = RosterStatus.E_APPROVED.ToString();
                string E_ROSTERGROUP = RosterType.E_ROSTERGROUP.ToString();
                List<Att_Roster> lstRoster = repoAtt_Roster.FindBy(m => m.Status == E_APPROVED && m.DateStart <= dateMax && m.DateEnd >= dateMin && lstProfileIDs.Contains(m.ProfileID)).ToList<Att_Roster>();
                List<DateTime> lstHolidayType = lstHoliday.Select(m => m.DateOff).ToList<DateTime>();
                foreach (var item in lstLeaveDay)
                {
                    if (item.DurationType == null)
                        continue;
                    Cat_LeaveDayType leaveDayType = lstLeaveDayType.Where(m => m.ID == item.LeaveDayTypeID).FirstOrDefault();
                    if (leaveDayType == null)
                        continue;
                    Hre_Profile profile = lstProfile.Where(m => m.ID == item.ProfileID).FirstOrDefault();
                    if (profile == null)
                        continue;

                    DateTime dateFrom = item.DateStart;
                    DateTime dateTo = item.DateEnd;
                    //dateTo = dateTo.AddDays(1).AddMinutes(-1);



                    Guid? GradeCfgID = lstGrade.Where(m => m.ProfileID == profile.ID && m.MonthStart <= dateTo).Select(m => m.GradeAttendanceID).FirstOrDefault();
                    Cat_GradeAttendance gradeCfg = lstGradeCfg.Where(m => m.ID == GradeCfgID).FirstOrDefault();
                    List<Att_Roster> lstRosterByProfile = lstRoster.Where(m => m.ProfileID == profile.ID).ToList();
                    List<Hre_WorkHistory> listWorkHistoryByProfile = listWorkHistory.Where(m => m.ProfileID == profile.ID && m.DateEffective < dateTo).ToList();
                    List<Att_Roster> lstRosterByProfileTypeGroup = lstRosterByProfile.Where(m => m.Type == E_ROSTERGROUP).ToList();

                    AnalyseTotalLeaveDaysAndHours(item, leaveDayType, profile, gradeCfg, lstRosterByProfile, lstRosterGroup, listWorkHistoryByProfile, lstHoliday, shifts);
                    string LeaveDayTypeCode = leaveDayType.Code;

                    if (item.DurationType == null)
                    {
                        item.DurationType = LeaveDayDurationType.E_FULLSHIFT.ToString();
                    }
                    double Totalduration = 0;
                    bool isSetFullLeaveDay = false;
                    for (DateTime idx = dateFrom.Date; idx <= dateTo.Date; idx = idx.AddDays(1))
                    {
                        if (!string.IsNullOrEmpty(LeaveDayTypeCode) && (LeaveDayTypeCode == "SICK"
                                        || LeaveDayTypeCode == "PRG"
                                        || LeaveDayTypeCode == "SU"
                                        || LeaveDayTypeCode == "SD"
                                        || LeaveDayTypeCode == "D"
                                        || LeaveDayTypeCode == "DP"
                                        || LeaveDayTypeCode == "PSN"
                                        || LeaveDayTypeCode == "M"
                                        || LeaveDayTypeCode == "DSP"))
                        {
                            if (!lstHolidayType.Any(m => m == idx))
                            {
                                Totalduration += 1;
                            }
                            isSetFullLeaveDay = true;
                        }

                    }
                    if (isSetFullLeaveDay == false)
                    {
                        if (gradeCfg == null)
                        {
                            message = ConstantMessages.GradeAttendanceIsNotExist.TranslateString();
                            return message;
                        }

                        var listRosterEntity = lstRosterByProfile.Select(d => new Att_RosterEntity
                        {
                            ID = d.ID,
                            ProfileID = d.ProfileID,
                            RosterGroupName = d.RosterGroupName,
                            Type = d.Type,
                            Status = d.Status,
                            DateEnd = d.DateEnd,
                            DateStart = d.DateStart,
                            MonShiftID = d.MonShiftID,
                            TueShiftID = d.TueShiftID,
                            WedShiftID = d.WedShiftID,
                            ThuShiftID = d.ThuShiftID,
                            FriShiftID = d.FriShiftID,
                            SatShiftID = d.SatShiftID,
                            SunShiftID = d.SunShiftID,
                            MonShift2ID = d.MonShiftID,
                            TueShift2ID = d.TueShift2ID,
                            WedShift2ID = d.WedShift2ID,
                            ThuShift2ID = d.ThuShift2ID,
                            FriShift2ID = d.FriShift2ID,
                            SatShift2ID = d.SatShift2ID,
                            SunShift2ID = d.SunShift2ID
                        }).ToList();

                        var listRosterGroupEntity = lstRosterGroup.Select(d => new Att_RosterGroupEntity
                        {
                            ID = d.ID,
                            DateEnd = d.DateEnd,
                            DateStart = d.DateStart,
                            MonShiftID = d.MonShiftID,
                            TueShiftID = d.TueShiftID,
                            WedShiftID = d.WedShiftID,
                            ThuShiftID = d.ThuShiftID,
                            FriShiftID = d.FriShiftID,
                            SatShiftID = d.SatShiftID,
                            SunShiftID = d.SunShiftID,
                            RosterGroupName = d.RosterGroupName
                        }).ToList();

                        Dictionary<DateTime, Cat_Shift> listMonthShifts = Att_AttendanceLib.GetDailyShifts(profile != null ? profile.ID : Guid.Empty, dateFrom, dateTo, listRosterEntity, listRosterGroupEntity, shifts);
                        for (DateTime idx = dateFrom.Date; idx <= dateTo.Date; idx = idx.AddDays(1))
                        {
                            if (gradeCfg != null && Att_WorkDayHelper.IsWorkDay(idx, gradeCfg, listMonthShifts, lstHoliday))
                            {
                                Totalduration += 1;
                            }
                        }
                    }

                    if (item.LeaveDays.HasChanged(Totalduration))
                    {
                        item.LeaveDays = Totalduration;
                        item.LeaveHours = 8;
                    }

                }

                unitOfWork.SaveChanges();
                message = ConstantMessages.Succeed.TranslateString();
                return message;
            }


















        }
Example #22
0
        public DataTable ReportGeneralInsuranceInYear(List<Hre_ProfileEntity> lstProfile, List<String> lstElementCode, DateTime monthStart, DateTime monthEnd, string UserLogin, bool isCreateTemplate, String nameReport)
        {
            using (var context = new VnrHrmDataContext())
            {
                #region Get Data
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoOrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);

                //ds phần tử 
                string statusEl = string.Empty;
                var lstObjElement = new List<object>();
                lstObjElement.AddRange(new object[7]);
                lstObjElement[5] = 1;
                lstObjElement[6] = Int32.MaxValue - 1;
                List<Cat_ElementEntity> lstElement = GetData<Cat_ElementEntity>(lstObjElement, ConstantSql.hrm_cat_sp_get_Element, UserLogin, ref statusEl);

                lstElement = lstElement.Where(m => lstElementCode.Contains(m.ElementCode)).ToList(); ;
                DataTable tb = GetSchema_ReportGeneralInsuranceInYear(lstElement, monthStart, monthEnd, nameReport);
                if (isCreateTemplate)
                {
                    return tb.ConfigTable();
                }

                //ds nhân viên
                var lstProfileID = lstProfile.Select(hr => hr.ID).ToList();

                //Bảng lương
                string statusTb = string.Empty;
                List<object> listModelprtb = new List<object>();
                listModelprtb = new List<object>();
                listModelprtb.AddRange(new object[6]);
                listModelprtb[2] = monthStart;
                listModelprtb[3] = monthEnd;
                listModelprtb[4] = 1;
                listModelprtb[5] = Int32.MaxValue - 1;
                List<Sal_PayrollTableEntity> listPayrollTable = GetData<Sal_PayrollTableEntity>(listModelprtb, ConstantSql.hrm_sal_sp_get_PayrollTable, UserLogin, ref statusTb);

                string statusTbit = string.Empty;
                List<object> listModelprtbit = new List<object>();
                listModelprtbit = new List<object>();
                listModelprtbit.AddRange(new object[9]);
                listModelprtbit[2] = monthStart;
                listModelprtbit[3] = monthEnd;
                listModelprtbit[7] = 1;
                listModelprtbit[8] = Int32.MaxValue - 1;
                List<Sal_PayrollTableItemEntity> listPayrollTableItem = GetData<Sal_PayrollTableItemEntity>(listModelprtbit, ConstantSql.hrm_sal_sp_get_PayrollTableItem, UserLogin, ref statusTbit);
                listPayrollTableItem = listPayrollTableItem.Where(it => it.Value != null && it.Value != string.Empty).ToList();

                var lstOrgStructure = repoOrgStructure.GetAll().Where(org => org.IsDelete == null).Select(org => new { org.ID, org.Code, org.OrgStructureName }).ToList();
                #endregion

                #region Process
                foreach (var profile in lstProfile)
                {
                    if (profile == null)
                    {
                        continue;
                    }

                    DataRow dr = tb.NewRow();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeEmp] = profile.CodeEmp;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.ProfileName] = profile.ProfileName;

                    if (profile.DateHire != null)
                    {
                        dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateHire] = profile.DateHire.Value;
                    }
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_UNIT] = profile.E_UNIT;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_DIVISION] = profile.E_DIVISION;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_DEPARTMENT] = profile.E_DEPARTMENT;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_TEAM] = profile.E_TEAM;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.E_SECTION] = profile.E_SECTION;


                    //var orgStructure = lstOrgStructure.Where(org => org.ID == profile.OrgStructureID).FirstOrDefault();
                    //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureCode] = orgStructure != null ? orgStructure.Code : string.Empty;
                    //dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureName] = orgStructure != null ? orgStructure.OrgStructureName : string.Empty;

                    //Bảng lương mỗi profile theo từng tháng
                    for (DateTime month = monthStart; month <= monthEnd; month = month.AddMonths(1))
                    {
                        var payrollTbID_Profile = listPayrollTable.Where(sal => sal.MonthYear == month && sal.ProfileID == profile.ID).Select(sal => sal.ID).FirstOrDefault();
                        var payrollTbItem_Profile = listPayrollTableItem.Where(salit => salit.PayrollTableID == payrollTbID_Profile).ToList();
                        if (payrollTbItem_Profile != null && payrollTbItem_Profile.Count > 0)
                        {
                            foreach (var element in lstElementCode)
                            {
                                var prItem = payrollTbItem_Profile.Where(salIt => salIt.Code == element).FirstOrDefault();
                                if (prItem != null)
                                {
                                    if (prItem.ValueType != null && prItem.ValueType.ToUpper() == typeof(Double).Name.ToUpper())
                                    {
                                        dr[element + month.Month.ToString()] = Convert.ToDouble(prItem.Value);
                                    }
                                    else if (prItem.ValueType != null && prItem.ValueType.ToUpper() == typeof(DateTime).Name.ToUpper())
                                    {
                                        dr[element + month.Month.ToString()] = Convert.ToDateTime(prItem.Value);
                                    }
                                    else
                                        dr[element + month.Month.ToString()] = prItem.Value;
                                }
                            }
                        }
                    }
                    tb.Rows.Add(dr);
                }
                #endregion

                return tb.ConfigTable();
            }
        }
Example #23
0
        public DataErrorCode SendMailPayslip(Guid templateID, List<Hre_ProfileEntity> lstProfile, DateTime monthStart, DateTime monthEnd, string UserLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                #region Get Data
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoOrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);

                //ds nhân viên
                var lstProfileID = lstProfile.Select(hr => hr.ID).ToList();

                //Bảng lương
                string statusTb = string.Empty;
                List<object> listModelprtb = new List<object>();
                listModelprtb = new List<object>();
                listModelprtb.AddRange(new object[6]);
                listModelprtb[2] = monthStart;
                listModelprtb[3] = monthEnd;
                listModelprtb[4] = 1;
                listModelprtb[5] = Int32.MaxValue - 1;
                List<Sal_PayrollTableEntity> listPayrollTable = GetData<Sal_PayrollTableEntity>(listModelprtb, ConstantSql.hrm_sal_sp_get_PayrollTable, UserLogin, ref statusTb);

                string statusTbit = string.Empty;
                List<object> listModelprtbit = new List<object>();
                listModelprtbit = new List<object>();
                listModelprtbit.AddRange(new object[9]);
                listModelprtbit[2] = monthStart;
                listModelprtbit[3] = monthEnd;
                listModelprtbit[7] = 1;
                listModelprtbit[8] = Int32.MaxValue - 1;
                List<Sal_PayrollTableItemEntity> listPayrollTableItem = GetData<Sal_PayrollTableItemEntity>(listModelprtbit, ConstantSql.hrm_sal_sp_get_PayrollTableItem, UserLogin, ref statusTbit);
                listPayrollTableItem = listPayrollTableItem.Where(it => it.Value != null && it.Value != string.Empty).ToList();

                var lstOrgStructure = repoOrgStructure.GetAll().Where(org => org.IsDelete == null).Select(org => new { org.ID, org.Code, org.OrgStructureName }).ToList();
                #endregion

                //Đường dẫn file export
                string outPath = string.Empty;

                //Thư mục nén và đường dẫn
                string folderSave = DateTime.Now.ToString("_ddMMyyyyHHmmss");
                string dirpath = Common.GetPath(Common.DownloadURL + folderSave);

                #region Process
                bool isSuccess = false;
                foreach (var profile in lstProfile)
                {
                    if (profile == null)
                    {
                        continue;
                    }

                    DataTable tb = GetSchemaExportPayroll();
                    DataRow dr = tb.NewRow();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeEmp] = profile.CodeEmp;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.ProfileName] = profile.ProfileName;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.WorkingPlace] = profile.WorkPlaceName;

                    if (profile.DateHire != null)
                    {
                        dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.DateHire] = profile.DateHire.Value;
                    }

                    var orgStructure = lstOrgStructure.Where(org => org.ID == profile.OrgStructureID).FirstOrDefault();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureCode] = orgStructure != null ? orgStructure.Code : string.Empty;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureName] = orgStructure != null ? orgStructure.OrgStructureName : string.Empty;

                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.TaxCode] = profile.CodeTax;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.WorkingPlace] = profile.WorkingPlace;

                    //Bảng lương mỗi profile
                    var payrollTbID_Profile = listPayrollTable.Where(sal => sal.ProfileID == profile.ID).Select(sal => sal.ID).FirstOrDefault();
                    var lstpayrollTbItem_Profile = listPayrollTableItem.Where(salit => salit.PayrollTableID == payrollTbID_Profile).ToList();
                    if (lstpayrollTbItem_Profile != null && lstpayrollTbItem_Profile.Count > 0)
                    {
                        foreach (var item in lstpayrollTbItem_Profile)
                        {
                            Double value = 0;
                            if (!tb.Columns.Contains(item.Code))
                            {
                                tb.Columns.Add(item.Code, typeof(Double));
                            }
                            if (tb.Columns.Contains(item.Code))
                            {
                                if (item.ValueType != null && item.ValueType.ToUpper() == typeof(Double).Name.ToUpper())
                                {
                                    Double.TryParse(item.Value, out value);
                                }
                                dr[item.Code] = value;
                            }
                        }
                        tb.Rows.Add(dr);
                    }
                    if (tb.Rows.Count > 0)
                    {
                        outPath = ExportService.Export(templateID, tb, ExportFileType.Excel);
                        string emailTo = profile.Email;
                        if (emailTo != null && emailTo != string.Empty)
                        {
                            isSuccess = CheckSendMail(emailTo, outPath, monthStart, monthEnd, profile);
                        }
                    }
                }
                #endregion

                if (isSuccess)
                    return DataErrorCode.Success;
                else
                    return DataErrorCode.Error;
            }
        }
Example #24
0
        public DataTable GetReportProfileInformationMoment(List<Hre_ProfileEntity> lstProfile, DateTime DateCheck, bool isCreateTemplate, String nameReport, Guid? workPlaceID, Guid? salaryClassID)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));

                var repoCat_ContractType = new CustomBaseRepository<Cat_ContractType>(unitOfWork);
                var repoHre_Contract = new CustomBaseRepository<Hre_Contract>(unitOfWork);
                var repoHre_AppendixContract = new CustomBaseRepository<Hre_AppendixContract>(unitOfWork);
                var repoCat_OrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var repoCat_OrgStructureType = new CustomBaseRepository<Cat_OrgStructureType>(unitOfWork);
                var repoCat_Position = new CustomBaseRepository<Cat_Position>(unitOfWork);
                var repoCat_SalaryClass = new CustomBaseRepository<Cat_SalaryClass>(unitOfWork);

                var lstContracType = repoCat_ContractType.FindBy(s => s.IsDelete == null).ToList();

                DataTable tb = GetSchema_ReportProfileInformationMoment(nameReport);
                if (isCreateTemplate)
                {
                    return tb.ConfigTable();
                }


                #region code BC
                List<Guid> lstProfileIDs = lstProfile.Select(m => m.ID).Distinct().ToList();
                string E_APPROVED = HRM.Infrastructure.Utilities.EnumDropDown.Status.E_APPROVED.ToString();
                var lstContractAll = repoHre_Contract.GetAll().Where(m => m.Status == E_APPROVED && m.DateStart <= DateCheck && m.DateEnd >= DateCheck)
                    .Select(m => new { m.ID, m.Code, m.ProfileID, m.DateStart, m.DateEnd, m.ContractNo, m.ContractTypeID }).ToList();

                var lstProfileIDs_ByContract = lstContractAll.Select(m => m.ProfileID).Distinct().ToList();
                lstProfile = lstProfile.Where(m => lstProfileIDs_ByContract.Contains(m.ID)).ToList();

                List<Guid> lstContractIDs = lstContractAll.Select(m => m.ID).ToList();
                var bienthai = repoHre_AppendixContract.GetAll().ToList();
                var lstAppendixContract = repoHre_AppendixContract.GetAll().Where(m => lstContractIDs.Contains(m.ContractID))
                    .Select(m => new { m.ID, m.ContractID, m.Code, m.DateofEffect, m.DateEndAppendixContract }).ToList();

                var lstOrg = repoCat_OrgStructure.GetAll().ToList();
                var orgTypes = repoCat_OrgStructureType.GetAll().ToList();
                var lstPosition = repoCat_Position.GetAll().ToList();
                var lstSalaryClass = repoCat_SalaryClass.GetAll().ToList();
                if (workPlaceID != null)
                {
                    lstProfile = lstProfile.Where(s => s.WorkPlaceID == workPlaceID).ToList();
                }
                if (salaryClassID != null)
                {
                    lstProfile = lstProfile.Where(s => s.SalaryClassID == salaryClassID).ToList();
                }
                int stt = 0;
                foreach (var profile in lstProfile)
                {
                    stt++;
                    DataRow dr = tb.NewRow();
                    dr["Stt"] = stt;
                    dr["CodeEmp"] = profile.CodeEmp;
                    dr["ProfileName"] = profile.ProfileName;


                    //var orgId = profile.OrgStructureID;
                    //var orgBranch = LibraryService.GetNearestParent(orgId, OrgUnit.E_BRANCH, lstOrg, orgTypes);
                    //var orgOrg = LibraryService.GetNearestParent(orgId, OrgUnit.E_DEPARTMENT, lstOrg, orgTypes);
                    //var orgTeam = LibraryService.GetNearestParent(orgId, OrgUnit.E_TEAM, lstOrg, orgTypes);
                    //var orgSection = LibraryService.GetNearestParent(orgId, OrgUnit.E_SECTION, lstOrg, orgTypes);
                    //var orgDivision = LibraryService.GetNearestParent(orgId, OrgUnit.E_DIVISION, lstOrg, orgTypes);
                    //var orgUnit = LibraryService.GetNearestParent(orgId, OrgUnit.E_UNIT, lstOrg, orgTypes);



                    dr["E_DIVISION"] = profile.E_DIVISION;

                    dr["E_UNIT"] = profile.E_UNIT;

                    dr["E_DEPARTMENT"] = profile.E_DEPARTMENT;

                    dr["E_TEAM"] = profile.E_TEAM;

                    dr["E_SECTION"] = profile.E_SECTION;

                    if (profile.PositionID != null)
                    {
                        var Position = lstPosition.Where(m => m.ID == profile.PositionID).FirstOrDefault();
                        if (Position != null)
                        {
                            dr["Position"] = Position.PositionName;
                        }
                    }
                    if (profile.DateOfBirth != null)
                    {
                        dr["DateOfBirth"] = profile.DateOfBirth;
                    }
                    if (profile.Cellphone != null)
                    {
                        dr["CellPhone"] = profile.Cellphone;
                    }
                    if (profile.HomePhone != null)
                    {
                        dr["HomePhone"] = profile.HomePhone;
                    }
                    if (profile.Gender != null)
                    {
                        if (profile.Gender == EnumDropDown.Gender.E_FEMALE.ToString() && profile.Gender == EnumDropDown.Gender.E_MALE.ToString() && profile.Gender == EnumDropDown.Gender.E_OTHER.ToString())
                        {
                            dr["Gender"] = EnumDropDown.GetEnumDescription<EnumDropDown.Gender>((EnumDropDown.Gender)Enum.Parse(typeof(EnumDropDown.Gender), profile.Gender.TranslateString(), true));
                        }
                        else
                        {
                            dr["Gender"] = profile.Gender;
                        }
                    }

                    if (profile.PlaceOfBirth != null)
                    {
                        dr["PlaceOfBirth"] = profile.PlaceOfBirth;
                    }
                    if (profile.PAddress != null)
                    {
                        dr["PAddress"] = profile.PAddress;
                    }
                    if (profile.IDNo != null)
                    {
                        dr["IDNo"] = profile.IDNo;
                    }
                    if (profile.IDDateOfIssue != null)
                    {
                        dr["IDDateOfIssue"] = profile.IDDateOfIssue;
                    }
                    if (profile.IDPlaceOfIssue != null)
                    {
                        dr["IDPlaceOfIssue"] = profile.IDPlaceOfIssue;
                    }
                    if (profile.DateHire != null)
                    {
                        dr["DateHire"] = profile.DateHire;
                    }

                    if (profile.DateHire != null)
                    {
                        dr["DateHire"] = profile.DateHire;
                    }

                    var SalaryClass = lstSalaryClass.Where(m => m.ID == profile.SalaryClassID).FirstOrDefault();
                    if (SalaryClass != null)
                    {
                        dr["SalaryClass"] = SalaryClass.SalaryClassName;
                    }

                    var ContractByProfile = lstContractAll.Where(m => m.ProfileID == profile.ID).FirstOrDefault();
                    if (ContractByProfile == null)
                        continue;
                    var lstAppendixContractByProfile = lstAppendixContract.Where(m => m.ContractID == ContractByProfile.ID).ToList();


                    var ContractType = lstContracType.Where(m => m.ID == ContractByProfile.ContractTypeID).FirstOrDefault();
                    if (ContractType != null)
                    {
                        dr["ContractType"] = ContractType.ContractTypeName;
                    }
                    dr["ContractNo"] = ContractByProfile.ContractNo;
                    dr["DateStart"] = ContractByProfile.DateStart;
                    dr["DateEnd"] = ContractByProfile.DateEnd;

                    var lstAppendixContractByContract = lstAppendixContractByProfile.Where(m => m.ContractID == ContractByProfile.ID).OrderBy(m => m.DateofEffect).ToList();
                    int numAppendix = 0;
                    foreach (var AppendixContract in lstAppendixContractByContract)
                    {
                        numAppendix++;
                        if (numAppendix > 3)
                            continue;
                        dr["Appendix" + numAppendix + "_" + "Code"] = AppendixContract.Code;
                        if (AppendixContract.DateofEffect != null)
                        {
                            dr["Appendix" + numAppendix + "_" + "DateofEffect"] = AppendixContract.DateofEffect;
                        }
                        if (AppendixContract.DateEndAppendixContract != null)
                        {
                            dr["Appendix" + numAppendix + "_" + "DateEndAppendixContract"] = AppendixContract.DateEndAppendixContract;
                        }
                    }
                    tb.Rows.Add(dr);
                    //HRM.Infrastructure.Utilities.EnumDropDown.TypeContract
                }
                #endregion
                var configs = new Dictionary<string, Dictionary<string, object>>();
                return tb.ConfigTable(configs);
            }
        }
Example #25
0
        public DataErrorCode SendMaToNextApproved(string host, Guid recordID, Guid userApprovedID)
        {
            using (var context = new VnrHrmDataContext())
            {
                string statusMess = string.Empty;
                var UserLogin = string.Empty;
                var Services = new BaseService();
                string status = string.Empty;
                string typeApprover = FinApproverType.FIN_TravelRequest_Domestic.ToString();
               // string typeApprover2 = FinApproverType.FIN_TravelRequest_External.ToString();

                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoSys_UserApprove = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);
                var repoFin_Approver = new CustomBaseRepository<FIN_ApproverECLAIM>(unitOfWork);
                var lstApprover = repoFin_Approver.GetAll().Where(s => s.IsDelete == null).ToList();

                var repo_JobTitle = new CustomBaseRepository<Cat_JobTitle>(unitOfWork);
                var lstJobTitle = repo_JobTitle.GetAll().Where(s => s.IsDelete == null).ToList();
                var repoOrg = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var lstOrg = repoOrg.GetAll().Where(s => s.IsDelete == null).ToList();
                var repoProfile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var lstProfile = repoProfile.GetAll().Where(s => s.IsDelete == null).ToList();

                var repoSys_UserInfo = new CustomBaseRepository<Sys_UserInfo>(unitOfWork);
                var repoSys_ConfigProcessApprove = new CustomBaseRepository<Sys_ConfigProcessApprove>(unitOfWork);
                var repoSys_TemplateSendMail = new CustomBaseRepository<Sys_TemplateSendMail>(unitOfWork);


                var repoFIN_TravelRequest = new CustomBaseRepository<FIN_TravelRequest>(unitOfWork);
                var record = repoFIN_TravelRequest.FindBy(s => s.ID == recordID).FirstOrDefault();

                var repoFin_TravelRequestItem = new CustomBaseRepository<FIN_TravelRequestItem>(unitOfWork);
                var totalItem = repoFin_TravelRequestItem.FindBy(s => s.IsDelete == null && s.Description2.Contains("E_APPROVED") && s.TravelRequestID != null && s.TravelRequestID.Value == recordID).ToList();

                string _typeTemplate = EnumDropDown.EmailType.E_REQUEST_TRAVELREQUEST.ToString();
                var template = repoSys_TemplateSendMail.FindBy(s => s.Type == _typeTemplate).FirstOrDefault();
                if (template == null)
                    return DataErrorCode.Error_NoTemplateMail;

                #region KT nếu là nguoi duyet cuoi thì gui email lại cho người yêu cầu duyệt
                if (userApprovedID == Guid.Empty)
                {
                    var flag = false;
                    var des = string.Empty;
                    foreach (var item in totalItem)
                    {
                        if(item.IsBookingHotel != null && item.IsBookingHotel == true)
                        {
                            flag = true;
                            des = item.Description;
                        }
                    }

                    if (record != null)
                    {
                        string _typeTemplateApproved = EnumDropDown.EmailType.E_APPROVED_TRAVELREQUEST.ToString();
                        var typeTemplateApproved = repoSys_TemplateSendMail.FindBy(s => s.IsDelete == null && s.Type == _typeTemplateApproved).FirstOrDefault();
                        if (typeTemplateApproved == null)
                        {
                            return DataErrorCode.Error_NoTemplateMail;

                        }
                        var lastApprover = lstApprover.Where(s => record.Type != null && s.ProfileID == record.ProfileID && s.ApprovedType == record.Type && s.ApprovedID != null).OrderByDescending(s => s.OrderNo).FirstOrDefault();

                        var userInfo = repoSys_UserInfo.FindBy(s => s.IsDelete == null &&  s.ID == lastApprover.ApprovedID.Value).FirstOrDefault();

                        var lastProfileEntity = lstProfile.Where(s => userInfo != null && userInfo.ProfileID.Value == s.ID).FirstOrDefault();
                        var profileEntity = lstProfile.Where(s => record.ProfileID != null && record.ProfileID.Value == s.ID).FirstOrDefault();
                        if (profileEntity != null)
                        {
                            var jobTitleEntity = lstJobTitle.Where(s => profileEntity.JobTitleID != null && s.ID == profileEntity.JobTitleID.Value).FirstOrDefault();
                            var orgEntity = lstOrg.Where(s => profileEntity.OrgStructureID != null && s.ID == profileEntity.OrgStructureID.Value).FirstOrDefault();
                            if(template != null)
                            {
                                string MailTo = profileEntity.Email;
                                string urlClickHere = host + "#Hrm_Main_Web/Fin_ApprovedTravelRequest/DetailTravelRequest/" + recordID + "#NewTab";

                                try
                                {
                                    #region magreData

                                    string[] strsParaKey = null;
                                    string[] strsParaValues = null;
                                    strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_PROFILENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_AREA.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_TRAVELREQUESTNAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_TRAVELREQUESTCODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_DENIES.ToString(),
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_REJECTLINK.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_ISBOOKINGHOTEL.ToString(), 


                                    };
                                    strsParaValues = new string[] 
                                    { 
                                        lastProfileEntity != null ? lastProfileEntity.ProfileName : string.Empty, 
                                      
                                        jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                          profileEntity.ProfileName, 
                                        record.TravelRequestName, 
                                        record.TravelRequestCode != null ? record.TravelRequestCode:"" , 
                                        "Đã được duyệt.",
                                        "",
                                        "",
                                        "Ghi chú: chuyến đi có yêu cầu đặt khách sạn " + des + "<br/>" + "Note: hotel booking is requested " + des
                                    };
                                    string body = LibraryService.ReplaceContentFile(typeTemplateApproved.Content, strsParaKey, strsParaValues);

                                    #endregion
                                    string titleMail = typeTemplateApproved.Subject;
                                    
                                    if (flag == true)
                                    {
                                        List<string> CCMail = new List<string>();
                                        CCMail.Add("*****@*****.**");
                                        bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty, CCMail);
                                        if (isSuccess)
                                            return DataErrorCode.Success;
                                        else
                                            return DataErrorCode.Error;
                                    }
                                    else {
                                        bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                        if (isSuccess)
                                            return DataErrorCode.Success;
                                        else
                                            return DataErrorCode.Error;
                                    }
                                  
                                }
                                catch (Exception ex)
                                {
                                    
                                    throw;
                                }
                                
                            }

                        }
                    }
                    

                    return DataErrorCode.Success;
                }
                #endregion

                

                var approverEntity = repoFin_Approver.GetAll().Where(s => s.IsDelete == null && s.ID == userApprovedID).FirstOrDefault();

                if (approverEntity != null && approverEntity.OrderNo != null)
                {
                    var profileInfoEntity = lstProfile.Where(s => s.ID == approverEntity.ProfileID.Value).FirstOrDefault();
                    var jobTitleEntity = lstJobTitle.Where(s => profileInfoEntity.JobTitleID != null && s.ID == profileInfoEntity.JobTitleID.Value).FirstOrDefault();
                    var orgEntity = lstOrg.Where(s => profileInfoEntity.OrgStructureID != null && s.ID == profileInfoEntity.OrgStructureID.Value).FirstOrDefault();

                    var lastApprover = lstApprover.Where(s => record.Type != null && s.ProfileID == approverEntity.ProfileID && s.ApprovedType == record.Type && s.ApprovedID != null).OrderByDescending(s => s.OrderNo).FirstOrDefault();


                    var lstApproverByClaim = lstApprover.Where(s => record.Type != null && s.ProfileID == approverEntity.ProfileID && s.ApprovedType == record.Type && s.ApprovedID != null && s.OrderNo > approverEntity.OrderNo).OrderBy(s => s.OrderNo).ToList();
                    var nextApproverEntity = new FIN_ApproverECLAIM();

                    foreach (var item in lstApproverByClaim)
                    {
                        if (approverEntity.OrderNo == item.OrderNo)
                        {
                            continue;
                        }
                        nextApproverEntity = item;
                        break;
                    }

                    #region Nguoi duyet cuoi
                    if (lastApprover != null && lastApprover.OrderNo != null && lastApprover.OrderNo == approverEntity.OrderNo)
                    {
                        var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == approverEntity.ApprovedID.Value).FirstOrDefault();

                        if (userInfo != null)
                        {
                            var des = string.Empty;
                            foreach (var item in totalItem)
                            {
                                if (item.IsBookingHotel != null && item.IsBookingHotel == true)
                                {
                                   
                                    des = item.Description;
                                }
                            }

                            var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();

                            var profileRequester = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(approverEntity.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();

                            if (template != null)
                            {
                                try
                                {
                                    string MailTo = profileEntity.Email;

                                    string urlClickHere = host + "#Hrm_Main_Web/Fin_ApprovedTravelRequest/DetailTravelRequest/" + recordID + "#NewTab";

                                    string linkcontent = string.Empty;

                                    string linkcontentReject = string.Empty;

                                    linkcontent += "Nhấn vào " + "<a href='" + host + "Fin_ApprovedTravelRequest/ProcessApprovedPage"
                                   + "?loginID=" + approverEntity.ApprovedID
                                   + "&userApprovedID=" + Guid.Empty
                                   + "&recordID=" + recordID
                                   + "'>đây" + "<a/>" + " để đồng ý.";

                                    linkcontentReject += "Nhấn vào " + "<a href='" + host + "Fin_ApprovedTravelRequest/ProcessRejectPage"
                            + "?loginID=" + approverEntity.ApprovedID
                            + "&userApprovedID=" + approverEntity.ID
                            + "&recordID=" + recordID
                            + "'>đây" + "<a/>" + " để từ chối.";

                                    #region magreData

                                    string[] strsParaKey = null;
                                    string[] strsParaValues = null;
                                    strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_PROFILENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_AREA.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_TRAVELREQUESTNAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_TRAVELREQUESTCODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_DENIES.ToString(),
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_REJECTLINK.ToString(),  
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_ISBOOKINGHOTEL.ToString(), 

                                    };
                                    strsParaValues = new string[] 
                                    { 
                                        profileEntity.ProfileName, 
                                         jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        profileInfoEntity != null ? profileInfoEntity.ProfileName : string.Empty, 
                                        record.TravelRequestName, 
                                        record.TravelRequestCode,
                                        "",
                                        linkcontent,
                                        linkcontentReject,
                                        "Ghi chú: chuyến đi có yêu cầu đặt khách sạn " + des + "</br>" + "Note: hotel booking is requested" + des
                                    };
                                    string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);
                                    #endregion

                                    string titleMail = template.Subject;
                                    bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                    if (isSuccess)
                                        return DataErrorCode.Success;
                                    else
                                        return DataErrorCode.Error;
                                }
                                catch (Exception ex)
                                {

                                    throw;
                                }
                            }

                        }
                    }
                    #endregion

                  //  var nextApprover = repoFin_Approver.GetAll().Where(s => s.IsDelete == null && s.ProfileID == approverEntity.ProfileID && (s.ApprovedType == typeApprover1 || s.ApprovedType == typeApprover2) && s.OrderNo == approverEntity.OrderNo + 1).FirstOrDefault();
                    var preApprover = repoFin_Approver.GetAll().Where(s => record.Type != null && s.IsDelete == null && s.ProfileID == approverEntity.ProfileID && s.ApprovedType == record.Type && s.OrderNo == approverEntity.OrderNo - 1).FirstOrDefault();

                    if (nextApproverEntity != null)
                    {
                        var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == approverEntity.ApprovedID.Value).FirstOrDefault();

                        var nextUserInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == nextApproverEntity.ApprovedID.Value).FirstOrDefault();

                        if (userInfo != null)
                        {

                            var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();
                            var profileEntityForRecord = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(nextUserInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();
                            if (profileEntity != null)
                            {
                                if (template != null)
                                {
                                    try
                                    {
                                        string MailTo = profileEntity.Email;

                                        string urlClickHere = host + "#Hrm_Main_Web/Fin_ApprovedTravelRequest/DetailTravelRequest/" + recordID + "#NewTab";

                                        string linkcontent = string.Empty;

                                        string linkcontentReject = string.Empty;


                                        var name = nextUserInfo != null ? nextUserInfo.UserInfoName : nextUserInfo.UserLogin;

                                        linkcontent += "Nhấn vào " + "<a href='" + host + "Fin_ApprovedTravelRequest/ProcessApprovedPage"
                                       + "?loginID=" + nextApproverEntity.ApprovedID
                                       + "&userApprovedID=" + nextApproverEntity.ID
                                       + "&recordID=" + recordID
                                       + "'>đây" + "<a/>" + " để đồng ý.";

                                        linkcontentReject += "Nhấn vào " + "<a href='" + host + "Fin_ApprovedTravelRequest/ProcessRejectPage"
                                      + "?loginID=" + approverEntity.ApprovedID
                                      + "&userApprovedID=" + approverEntity.ID
                                      + "&recordID=" + recordID
                                      + "'>đây" + "<a/>" + " để từ chối.";

                                        #region magreData

                                        string[] strsParaKey = null;
                                        string[] strsParaValues = null;
                                        strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_PROFILENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_AREA.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_TRAVELREQUESTNAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_TRAVELREQUESTCODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_DENIES.ToString(),
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_REJECTLINK.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_ISBOOKINGHOTEL.ToString(), 


                                    };
                                        strsParaValues = new string[] 
                                    { 
                                        profileEntity.ProfileName, 
                                        jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        profileInfoEntity != null ? profileInfoEntity.ProfileName : string.Empty, 
                                        record.TravelRequestName, 
                                        record.TravelRequestCode, 
                                        "",
                                        linkcontent,
                                        linkcontentReject,
                                        ""
                                    };
                                        string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);
                                        #endregion

                                        string titleMail = template.Subject;
                                        bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                        if (isSuccess)
                                            return DataErrorCode.Success;
                                        else
                                            return DataErrorCode.Error;
                                    }
                                    catch (Exception ex)
                                    {
                                        return DataErrorCode.Error_NoConfigMail;
                                    }

                                }
                            }

                        }
                    }
                    else {
                        var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == approverEntity.ApprovedID.Value).FirstOrDefault();
                        if (userInfo != null)
                        {
                            var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();
                            if(profileEntity != null)
                            {
                                if(template != null)
                                {
                                try
                                    {
                                        string MailTo = profileEntity.Email;

                                        string urlClickHere = host + "#Hrm_Main_Web/Fin_ApprovedTravelRequest/DetailTravelRequest/" + recordID + "#NewTab";

                                        string linkcontent = string.Empty;

                                        string linkcontentReject = string.Empty;

                                        linkcontent += "Nhấn vào " + "<a href='" + host + "Fin_ApprovedTravelRequest/ProcessApprovedPage"
                                        + "?loginID=" + approverEntity.ApprovedID
                                        + "&userApprovedID=" + Guid.Empty
                                        + "&recordID=" + recordID
                                         + "'>đây" + "<a/>" + " để đồng ý.";
                                     

                                        linkcontentReject += "Nhấn vào " + "<a href='" + host + "Fin_ApprovedTravelRequest/ProcessRejectPage"
                                      + "?loginID=" + approverEntity.ApprovedID
                                      + "&userApprovedID=" + approverEntity.ID
                                      + "&recordID=" + recordID
                                      + "'>đây" + "<a/>" + " để từ chối.";

                                        #region magreData

                                        string[] strsParaKey = null;
                                        string[] strsParaValues = null;
                                        strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_PROFILENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_AREA.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_TRAVELREQUESTNAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_TRAVELREQUESTCODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_DENIES.ToString(),
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_REJECTLINK.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_TRAVELREQUEST.E_ISBOOKINGHOTEL.ToString(), 


                                    };
                                        strsParaValues = new string[] 
                                    { 
                                        profileEntity.ProfileName, 
                                        jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        profileInfoEntity != null ? profileInfoEntity.ProfileName : string.Empty, 
                                        record.TravelRequestName, 
                                        record.TravelRequestCode, 
                                        "",
                                        linkcontent,
                                        linkcontentReject,
                                        ""
                                    };
                                        string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);
                                        #endregion

                                        string titleMail = template.Subject;
                                        bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                        if (isSuccess)
                                            return DataErrorCode.Success;
                                        else
                                            return DataErrorCode.Error;
                                    }
                                    catch (Exception ex)
                                    {
                                        return DataErrorCode.Error_NoConfigMail;
                                    }
                                }
                            }
                        }
                    }
                    
                }
                return DataErrorCode.Success;
            }
        }
Example #26
0
        public DataTable GetReportContractDetail(List<Hre_ProfileEntity> lstProfile, DateTime? _DateSignedStart, DateTime? _DateSignedEnd, string _ContractNo, Guid? _ContractTypeID, bool isCreateTemplate, String nameReport)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoCat_ContractType = new CustomBaseRepository<Cat_ContractType>(unitOfWork);
                var repoHre_Contract = new CustomBaseRepository<Hre_Contract>(unitOfWork);
                var repoHre_AppendixContract = new CustomBaseRepository<Hre_AppendixContract>(unitOfWork);
                var repoCat_OrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var repoCat_OrgStructureType = new CustomBaseRepository<Cat_OrgStructureType>(unitOfWork);

                var lstContracType = repoCat_ContractType.FindBy(s => s.IsDelete == null).ToList();
                DataTable tb = GetSchema_ContractDetail(nameReport, lstContracType);

                if (isCreateTemplate)
                {
                    return tb.ConfigTable();
                }

                #region code BC

                //var profileQueryable = unitOfWork.CreateQueryable<Hre_Profile>(Guid.Empty,
                //    d => d.DateHire >= monthStart && d.DateHire <= monthEnd);

                //if (!string.IsNullOrWhiteSpace(codeEmp))
                //{
                //    profileQueryable = profileQueryable.Where(d => d.CodeEmp.Contains(codeEmp));
                //}

                //if (!string.IsNullOrWhiteSpace(profileName))
                //{
                //    profileQueryable = profileQueryable.Where(d => d.ProfileName.Contains(profileName));
                //}

                //if (listOrgID != null && listOrgID.Count() > 0)
                //{
                //    profileQueryable = profileQueryable.Where(d => d.OrgStructureID.HasValue && listOrgID.Contains(d.OrgStructureID.Value));
                //}

                string status = string.Empty;
                //List<object> listModel = new List<object>();

                //listModel = new List<object>();
                //listModel.AddRange(new object[16]);
                //listModel[2] = null;
                //listModel[8] = monthStart;
                //listModel[9] = monthEnd;
                //listModel[14] = null;
                //listModel[15] = Int32.MaxValue - 1;
                //List<Hre_ProfileEntity> lstProfile = GetData<Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_Profile, ref status);

                //var profileQueryable = unitOfWork.CreateQueryable<Hre_Profile>(Guid.Empty,
                //    d => d.DateHire >= monthStart && d.DateHire <= monthEnd);

                //if (!string.IsNullOrWhiteSpace(codeEmp))
                //{
                //    lstProfile = lstProfile.Where(d => d.CodeEmp.Contains(codeEmp)).ToList();
                //}

                //if (!string.IsNullOrWhiteSpace(profileName))
                //{
                //    lstProfile = lstProfile.Where(d => d.ProfileName.Contains(profileName)).ToList();
                //}

                //if (listOrgID != null && listOrgID.Count() > 0)
                //{
                //    lstProfile = lstProfile.Where(d => d.OrgStructureID.HasValue && listOrgID.Contains(d.OrgStructureID.Value)).ToList();
                //}

                //List<Hre_ProfileEntity> lstProfile = profileQueryable.Select(d => new Hre_ProfileEntity
                //{
                //    ID = d.ID,
                //    CodeEmp = d.CodeEmp,
                //    CodeAttendance = d.CodeAttendance,
                //    ProfileName = d.ProfileName,
                //    DateOfBirth = d.DateOfBirth,
                //    Gender = d.Gender,
                //    PlaceOfBirth = d.PlaceOfBirth,
                //    PAddress = d.PAddress,
                //    IDNo = d.IDNo,
                //    IDDateOfIssue = d.IDDateOfIssue,
                //    IDPlaceOfIssue = d.IDPlaceOfIssue,
                //    DateHire = d.DateHire,
                //    DateQuit = d.DateQuit,
                //    StatusSyn = d.StatusSyn,
                //    PositionName = d.Cat_Position.PositionName,
                //    SalaryClassName = d.Cat_SalaryClass.SalaryClassName,
                //    OrgStructureID=d.OrgStructureID
                //}).ToList();

                List<Guid> lstProfileIDs = lstProfile.Select(m => m.ID).Distinct().ToList();
                string E_APPROVED = HRM.Infrastructure.Utilities.EnumDropDown.Status.E_APPROVED.ToString();

                #region getdata COntract Appendix

                // string status = string.Empty;
                var hreServiceContract = new Hre_ContractServices();
                List<object> paraContract = new List<object>();
                paraContract.AddRange(new object[16]);
                paraContract[13] = E_APPROVED;
                paraContract[14] = 1;
                paraContract[15] = Int32.MaxValue - 1;

                var AppendixServices = new Hre_AppendixContractServices();
                List<object> paraAppendix = new List<object>();
                paraAppendix.AddRange(new object[7]);
                paraAppendix[5] = 1;
                paraAppendix[6] = Int32.MaxValue - 1;

                #endregion

                var lstContractAll = new List<Hre_Contract>().Select(m => new
                {
                    m.ID,
                    m.Status,
                    m.ContractTypeID,
                    m.ProfileID,
                    m.DateStart,
                    m.DateEnd,
                    m.ContractNo,
                    m.DateSigned
                }).ToList();

                foreach (var lstProfileID in lstProfileIDs.Chunk(1000))
                {
                    lstContractAll.AddRange(unitOfWork.CreateQueryable<Hre_Contract>(Guid.Empty, m => m.Status == E_APPROVED
                        && lstProfileID.Contains(m.ProfileID)).Select(m => new
                        {
                            m.ID,
                            m.Status,
                            m.ContractTypeID,
                            m.ProfileID,
                            m.DateStart,
                            m.DateEnd,
                            m.ContractNo,
                            m.DateSigned
                        }).ToList());
                }
                if (_DateSignedStart != null)
                    lstContractAll = lstContractAll.Where(s => s.DateSigned != null && s.DateSigned >= _DateSignedStart).ToList();
                if (_DateSignedEnd != null)
                    lstContractAll = lstContractAll.Where(s => s.DateSigned != null && s.DateSigned <= _DateSignedEnd).ToList();
                if (_ContractNo != string.Empty && _ContractNo != null)
                    lstContractAll = lstContractAll.Where(s => s.ContractNo != null && s.ContractNo == _ContractNo).ToList();
                if (_ContractTypeID != null && _ContractTypeID != Guid.Empty)
                    lstContractAll = lstContractAll.Where(s => s.ContractTypeID == _ContractTypeID).ToList();

                List<Guid> lstContractIDs = lstContractAll.Select(m => m.ID).ToList();

                var lstAppendixContract = new List<Hre_AppendixContractEntity>().Select(m => new
                {
                    m.ID,
                    m.ContractID,
                    m.Code,
                    m.DateofEffect,
                    m.DateEndAppendixContract
                }).ToList();

                foreach (var lstContractID in lstContractIDs.Chunk(1000))
                {
                    lstAppendixContract.AddRange(unitOfWork.CreateQueryable<Hre_AppendixContract>(Guid.Empty,
                        m => lstContractID.Contains(m.ContractID)).Select(m => new
                        {
                            m.ID,
                            m.ContractID,
                            m.Code,
                            m.DateofEffect,
                            m.DateEndAppendixContract
                        }).ToList());
                }

                var lstOrg = repoCat_OrgStructure.GetAll().ToList();
                var orgTypes = repoCat_OrgStructureType.GetAll().ToList();

                #region Phu luc hd
                var lstContractExtend = new List<Hre_ContractExtend>().Select(s => new
                {
                    s.ContractID,
                    s.AnnexCode,
                    s.DateStart,
                    s.DateEnd
                }).ToList();

                foreach (var lstContractID in lstContractIDs.Chunk(1000))
                {
                    lstContractExtend.AddRange(unitOfWork.CreateQueryable<Hre_ContractExtend>(Guid.Empty, s => lstContractID.Contains(s.ContractID.Value)).Select(s => new
                    {
                        s.ContractID,
                        s.AnnexCode,
                        s.DateStart,
                        s.DateEnd
                    }).ToList());
                }

                #endregion

                int stt = 0;
                foreach (var profile in lstProfile)
                {
                    stt++;
                    DataRow dr = tb.NewRow();
                    dr["Stt"] = stt;
                    dr["CodeEmp"] = profile.CodeEmp;
                    dr["ProfileName"] = profile.ProfileName;

                    //var orgId = profile.OrgStructureID;
                    //var orgBranch = LibraryService.GetNearestParent(orgId, OrgUnit.E_BRANCH, lstOrg, orgTypes);
                    //var orgOrg = LibraryService.GetNearestParent(orgId, OrgUnit.E_DEPARTMENT, lstOrg, orgTypes);
                    //var orgTeam = LibraryService.GetNearestParent(orgId, OrgUnit.E_TEAM, lstOrg, orgTypes);
                    //var orgSection = LibraryService.GetNearestParent(orgId, OrgUnit.E_SECTION, lstOrg, orgTypes);
                    //var orgDivision = LibraryService.GetNearestParent(orgId, OrgUnit.E_DIVISION, lstOrg, orgTypes);
                    //var orgUnit = LibraryService.GetNearestParent(orgId, OrgUnit.E_UNIT, lstOrg, orgTypes);


                    dr["E_DIVISION"] = profile.E_DIVISION;

                    dr["E_UNIT"] = profile.E_UNIT;

                    dr["E_DEPARTMENT"] = profile.E_DEPARTMENT;

                    dr["E_TEAM"] = profile.E_TEAM;

                    dr["E_SECTION"] = profile.E_SECTION;

                    //if (orgDivision != null)
                    //{
                    //    dr["E_DIVISION"] = orgDivision.OrgStructureName;
                    //}
                    //if (orgUnit != null)
                    //{
                    //    dr["E_UNIT"] = orgUnit.OrgStructureName;
                    //}
                    //if (orgOrg != null)
                    //{
                    //    dr["E_DEPARTMENT"] = orgOrg.OrgStructureName;
                    //}
                    //if (orgTeam != null)
                    //{
                    //    dr["E_TEAM"] = orgTeam.OrgStructureName;
                    //}
                    //if (orgSection != null)
                    //{
                    //    dr["E_SECTION"] = orgSection.OrgStructureName;
                    //}
                    if (!string.IsNullOrWhiteSpace(profile.PositionName))
                    {
                        dr["Position"] = profile.PositionName;
                    }
                    if (profile.DateOfBirth != null)
                    {
                        dr["DateOfBirth"] = profile.DateOfBirth;
                    }
                    if (profile.Gender != null)
                    {
                        dr["Gender"] = profile.Gender.TranslateString();
                    }

                    if (profile.PlaceOfBirth != null)
                    {
                        dr["PlaceOfBirth"] = profile.PlaceOfBirth;
                    }
                    if (profile.PAddress != null)
                    {
                        dr["PAddress"] = profile.PAddress;
                    }
                    if (profile.IDNo != null)
                    {
                        dr["IDNo"] = profile.IDNo;
                    }
                    if (profile.IDDateOfIssue != null)
                    {
                        dr["IDDateOfIssue"] = profile.IDDateOfIssue;
                    }
                    if (profile.IDPlaceOfIssue != null)
                    {
                        dr["IDPlaceOfIssue"] = profile.IDPlaceOfIssue;
                    }
                    if (profile.DateHire != null)
                    {
                        dr["DateHire"] = profile.DateHire;
                    }

                    if (!string.IsNullOrWhiteSpace(profile.SalaryClassName))
                    {
                        dr["SalaryClass"] = profile.SalaryClassName;
                    }
                    var lstContractByProfile = lstContractAll.Where(m => m.ProfileID == profile.ID).OrderBy(m => m.DateStart).ToList();
                    var lstContractByProfileID = lstContractByProfile.Select(m => m.ID).ToList();
                    var lstAppendixContractByProfile = lstAppendixContract.Where(m => lstContractByProfileID.Contains(m.ContractID)).ToList();

                    foreach (var ContractType in lstContracType)
                    {
                        string ContractCode = ContractType.Code;
                        if (string.IsNullOrEmpty(ContractCode))
                            continue;

                        var ContractOfProfileByType = lstContractByProfile.Where(m => m.ContractTypeID == ContractType.ID).FirstOrDefault();
                        if (ContractOfProfileByType != null)
                        {
                            if (ContractOfProfileByType.ContractNo != null)
                                dr[ContractCode + "_" + "ContractNo"] = ContractOfProfileByType.ContractNo;
                            if (ContractOfProfileByType.DateStart != null)
                                dr[ContractCode + "_" + "DateStart"] = ContractOfProfileByType.DateStart;
                            if (ContractOfProfileByType.DateEnd != null)
                                dr[ContractCode + "_" + "DateEnd"] = ContractOfProfileByType.DateEnd;

                            var lstAppendixContractByContract = lstAppendixContractByProfile.Where(m => m.ContractID == ContractOfProfileByType.ID).OrderBy(m => m.DateofEffect).ToList();
                            int numAppendix = 0;
                            foreach (var AppendixContract in lstAppendixContractByContract)
                            {
                                numAppendix++;
                                if (numAppendix > 3)
                                    continue;
                                if (string.IsNullOrEmpty(AppendixContract.Code))
                                    continue;
                                dr[ContractCode + "_" + numAppendix + "_" + "Code"] = AppendixContract.Code;
                                if (AppendixContract.DateofEffect != null)
                                {
                                    dr[ContractCode + "_" + numAppendix + "_" + "DateofEffect"] = AppendixContract.DateofEffect;
                                }
                                if (AppendixContract.DateEndAppendixContract != null)
                                {
                                    dr[ContractCode + "_" + numAppendix + "_" + "DateEndAppendixContract"] = AppendixContract.DateEndAppendixContract;
                                }
                            }
                            var lstContractExtendByContract = lstContractExtend.Where(s => s.ContractID == ContractOfProfileByType.ID).OrderBy(s => s.DateStart).ToList();
                            int numContractExtend = 0;
                            foreach (var objContractExtend in lstContractExtendByContract)
                            {
                                numContractExtend++;
                                if (numContractExtend > 5)
                                    continue;
                                if (objContractExtend.AnnexCode != null)
                                    dr[ContractCode + "_" + numContractExtend + "_" + "CodeExtend"] = objContractExtend.AnnexCode;
                                if (objContractExtend.DateStart != null)
                                    dr[ContractCode + "_" + numContractExtend + "_" + "DateStartExtend"] = objContractExtend.DateStart;
                                if (objContractExtend.DateEnd != null)
                                    dr[ContractCode + "_" + numContractExtend + "_" + "DateEndExtend"] = objContractExtend.DateEnd;
                            }
                        }
                    }
                    tb.Rows.Add(dr);
                }
                #endregion
                var configs = new Dictionary<string, Dictionary<string, object>>();
                return tb.ConfigTable(configs);
            }
        }
Example #27
0
        public DataTable LoadDataAnalyzeOvertime(string strOrgStructure, DateTime DateStart, DateTime DateEnd, List<Hre_ProfileEntity> lstProfile, List<string> lstTypeData, Att_OvertimeInfoFillterAnalyze _OvertimeInfoFillterAnalyzeEntity, string userLogin)
        {
            DataTable table = GetSchemaExportExcel();
            string status = string.Empty;

            DateStart = DateStart.Date;
            DateEnd = DateEnd.Date.AddDays(1).AddMilliseconds(-1);
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_WorkDay = new CustomBaseRepository<Att_Workday>(unitOfWork);
                var repoCat_Shift = new CustomBaseRepository<Cat_Shift>(unitOfWork);
                var repoCat_ShiftItem = new CustomBaseRepository<Cat_ShiftItem>(unitOfWork);
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
                var repoCat_OvertimeType = new CustomBaseRepository<Cat_OvertimeType>(unitOfWork);
                var repoCat_OrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var repoCat_OrgStructureType = new CustomBaseRepository<Cat_OrgStructureType>(unitOfWork);

                var orgTypes = repoCat_OrgStructureType.FindBy(s => s.IsDelete == null).ToList();
                var orgs = repoCat_OrgStructure.FindBy(s => s.IsDelete == null && s.Code != null).ToList();

                List<WorkdayCustom> lstWorkday = new List<WorkdayCustom>();
                List<Guid> lstProfileId = lstProfile.Select(s => s.ID).ToList();

                List<object> lst3ParamSE = new List<object>();
                lst3ParamSE.Add(strOrgStructure);
                lst3ParamSE.Add(DateStart);
                lst3ParamSE.Add(DateEnd);
                if (lstProfile.Count > 0 && strOrgStructure == null)
                {
                    var lstWD = GetData<Att_Workday>(lst3ParamSE, ConstantSql.hrm_att_getdata_Workday, userLogin, ref status);
                    //var lstWD = repoAtt_WorkDay.FindBy(s => s.IsDelete == null && s.WorkDate >= DateStart && s.WorkDate <= DateEnd && lstProfileId.Contains(s.ProfileID)).ToList();
                    if (lstWD.Count > 0)
                    {
                        lstWD = lstWD.Where(s => lstProfileId.Contains(s.ProfileID)).ToList();
                        lstWorkday = lstWD.Translate<WorkdayCustom>();
                    }
                }
                else
                {
                    lstWorkday = GetData<WorkdayCustom>(lst3ParamSE, ConstantSql.hrm_att_getdata_Workday, userLogin, ref status).ToList();
                }

                //var lstWorkdayQuery = repoAtt_WorkDay.FindBy(m => m.IsDelete == null && m.WorkDate >= DateStart && m.WorkDate <= DateEnd);
                //if (lstProfileId.Count > 0)
                //{
                //    lstWorkdayQuery = lstWorkdayQuery.Where(m => lstProfileId.Contains(m.ProfileID));
                //}
                //lstWorkday = lstWorkdayQuery.ToList().Translate<Att_WorkdayEntity>();
                List<Cat_ShiftEntity> lstShift = repoCat_Shift
                    .GetAll().ToList()
                    .Translate<Cat_ShiftEntity>();
                List<Cat_ShiftItemEntity> lstShiftItem = repoCat_ShiftItem
                    .FindBy(s => s.IsDelete == null)
                    .ToList()
                    .Translate<Cat_ShiftItemEntity>();
                List<Cat_DayOffEntity> LstDayOff = repoCat_DayOff
                    .FindBy(m => m.IsDelete == null && m.DateOff >= DateStart && m.DateOff < DateEnd)
                    .ToList()
                    .Translate<Cat_DayOffEntity>();

                List<Cat_OvertimeTypeEntity> lstOvertimeType = repoCat_OvertimeType
                    .FindBy(s => s.IsDelete == null).ToList()
                    .Translate<Cat_OvertimeTypeEntity>();

                string E_CANCEL = OverTimeStatus.E_CANCEL.ToString();
                string E_REJECTED = OverTimeStatus.E_REJECTED.ToString();
                DateTime beforeDateStart = DateStart.Date.AddDays(-1);
                DateTime afterDateEnd = DateEnd.Date.AddDays(2).AddMinutes(-1);
                // string E_HOLIDAY_HLD = HolidayType.E_HOLIDAY_HLD.ToString();
                List<DateTime> lstHoliday = repoCat_DayOff
                    .FindBy(s => s.IsDelete == null)
                    .Select(m => m.DateOff).ToList<DateTime>();
                //lstWorkday = filterData_NonAllowOT_inGrade(lstWorkday);
                List<Att_OvertimeEntity> lstOvertimeCal = AnalyzeOvertime(lstWorkday, lstShift, lstShiftItem, LstDayOff, lstOvertimeType, _OvertimeInfoFillterAnalyzeEntity, userLogin);
                if (lstOvertimeCal.Count == 0)
                {
                    lstOvertimeCache = lstOvertimeCal;
                    return table;
                }
                OvertimePermitEntity overtimePermit = getOvertimePermit(userLogin);
                FilterNonOvertimeByGradeConfig(lstOvertimeCal);
                SetNonOT(lstOvertimeCal);
                SetStatusOvertimeOnWorkday(lstOvertimeCal);
                FilterOvertimeByMaxHourPerDay(lstOvertimeCal, overtimePermit, _OvertimeInfoFillterAnalyzeEntity.MaximumOvertimeHour);
                RoundOT(lstOvertimeCal, userLogin);
                FillterAllowOvertime(context, lstOvertimeCal, overtimePermit, lstWorkday);
                RoundOT(lstOvertimeCal, userLogin);
                lstOvertimeCal = lstOvertimeCal.Where(m => m.RegisterHours != null && m.RegisterHours > 0).ToList();
                SetStatusLeaveOnWorkday(lstOvertimeCal);//Set loại ngày nghỉ cho OT

                if (lstTypeData.Count > 0)
                {
                    Expression<Func<Att_OvertimeEntity, bool>> predicate = VnResource.Helper.Linq.PredicateBuilder.False<Att_OvertimeEntity>();
                    if (lstTypeData.Any(m => m == ComputeLeavedayType.E_DATA_LEAVE.ToString()))
                    {
                        Expression<Func<Att_OvertimeEntity, bool>> predicate1 = m => m.udLeaveTypeCode != null || m.udLeaveTypeCode2 != null;
                        predicate = predicate.Or(predicate1);
                        //lstOvertimeCal = lstOvertimeCal.Where(m => (m.udLeaveTypeCode == null || m.udLeaveTypeCode == string.Empty) && (m.udLeaveTypeCode2 == null || m.udLeaveTypeCode2 == string.Empty)).ToList();
                    }
                    if (lstTypeData.Any(m => m == ComputeLeavedayType.E_DATA_NON_LEAVE.ToString()))
                    {
                        Expression<Func<Att_OvertimeEntity, bool>> predicate2 = m => (m.udLeaveTypeCode == null || m.udLeaveTypeCode == string.Empty) && (m.udLeaveTypeCode2 == null || m.udLeaveTypeCode2 == string.Empty);
                        predicate = predicate.Or(predicate2);
                        //lstOvertimeCal = lstOvertimeCal.Where(m => m.udLeaveTypeCode != null || m.udLeaveTypeCode2 != null).ToList();
                    }
                    if (lstTypeData.Any(m => m == ComputeOvertimeType.E_DATA_OT.ToString()))
                    {
                        Expression<Func<Att_OvertimeEntity, bool>> predicate2 = m => m.udOvertimeStatus != null;
                        predicate = predicate.Or(predicate2);
                    }
                    if (lstTypeData.Any(m => m == ComputeOvertimeType.E_DATA_NON_OT.ToString()))
                    {
                        Expression<Func<Att_OvertimeEntity, bool>> predicate2 = m => m.udOvertimeStatus == null;
                        predicate = predicate.Or(predicate2);
                    }
                    lstOvertimeCal = lstOvertimeCal.AsQueryable().Where(predicate).ToList();
                }

                lstOvertimeCal = lstOvertimeCal.OrderBy(m => m.WorkDate.Date).ThenBy(m => m.ProfileID).ToList();
                //lstOvertimeCache = lstOvertimeCal;
                //BindToGrid(lstOvertimeCache);

                #region process return table

                foreach (var item in lstOvertimeCal)
                {
                    #region code cu tra ve EntityModel
                    //if ((item.udIsLimitHour == null || item.udIsLimitHour == false)
                    //       && (item.udIsLimitHourLv1 == null || item.udIsLimitHourLv1 == false)
                    //       && (item.udIsLimitHourLv2 == null || item.udIsLimitHourLv2 == false))
                    //{
                    //    item.IsValid = true;
                    //}
                    //else
                    //{
                    //    item.IsValid = false;
                    //}

                    //if (item.OvertimeTypeID != Guid.Empty)
                    //{
                    //    item.OvertimeTypeName = lstOvertimeType.Where(s => s.ID == item.OvertimeTypeID).FirstOrDefault().OvertimeTypeName;
                    //}
                    //if (item.ProfileID != Guid.Empty)
                    //{
                    //    var temp = lstProfile.Where(s => s.ID == item.ProfileID).FirstOrDefault();
                    //    item.ProfileName = temp.ProfileName;
                    //    item.CodeEmp = temp.CodeEmp;
                    //    item.OrgStructureName = temp.OrgStructureName;
                    //}
                    //if (item.ShiftID != Guid.Empty)
                    //{
                    //    item.ShiftName = lstShift.Where(s => s.ID == item.ShiftID).FirstOrDefault().ShiftName;
                    //}
                    //item.TotalRow = lstOvertimeCal.Count; 
                    #endregion

                    DataRow row = table.NewRow();
                    Guid? orgId = lstProfile.Where(s => s.ID == item.ProfileID).FirstOrDefault().OrgStructureID;
                    var org = orgs.FirstOrDefault(s => s.ID == orgId);
                    var orgBranch = LibraryService.GetNearestParent(orgId, OrgUnit.E_BRANCH, orgs, orgTypes);
                    var orgOrg = LibraryService.GetNearestParent(orgId, OrgUnit.E_DEPARTMENT, orgs, orgTypes);
                    var orgTeam = LibraryService.GetNearestParent(orgId, OrgUnit.E_TEAM, orgs, orgTypes);
                    var orgSection = LibraryService.GetNearestParent(orgId, OrgUnit.E_SECTION, orgs, orgTypes);
                    row[Att_OvertimeEntity.FieldNames.BranchCode] = orgBranch != null ? orgBranch.Code : string.Empty;
                    row[Att_OvertimeEntity.FieldNames.OrgStructureCode] = orgOrg != null ? orgOrg.Code : string.Empty;
                    row[Att_OvertimeEntity.FieldNames.TeamCode] = orgTeam != null ? orgTeam.Code : string.Empty;
                    row[Att_OvertimeEntity.FieldNames.SectionCode] = orgSection != null ? orgSection.Code : string.Empty;
                    row[Att_OvertimeEntity.FieldNames.BranchName] = orgBranch != null ? orgBranch.OrgStructureName : string.Empty;
                    row[Att_OvertimeEntity.FieldNames.OrgName] = orgOrg != null ? orgOrg.OrgStructureName : string.Empty;
                    row[Att_OvertimeEntity.FieldNames.TeamName] = orgTeam != null ? orgTeam.OrgStructureName : string.Empty;
                    row[Att_OvertimeEntity.FieldNames.SectionName] = orgSection != null ? orgSection.OrgStructureName : string.Empty;

                    row[Att_OvertimeEntity.FieldNames.WorkDate] = item.WorkDate;
                    row[Att_OvertimeEntity.FieldNames.InTime] = item.InTime;
                    row[Att_OvertimeEntity.FieldNames.OutTime] = item.OutTime;

                    if (item.udIsLimitHour == true || item.udIsLimitHourLv1 == true || item.udIsLimitHourLv2 == true)
                    {
                        if (item.udIsLimitHourLv2 == true)
                        {
                            row[Att_OvertimeEntity.FieldNames.Valid] = "Level3";
                        }
                        else if (item.udIsLimitHourLv1 == true)
                        {
                            row[Att_OvertimeEntity.FieldNames.Valid] = "Level2";
                        }
                        else if (item.udIsLimitHour == true)
                        {
                            row[Att_OvertimeEntity.FieldNames.Valid] = "Level1";
                        }
                    }
                    else
                    {
                        row[Att_OvertimeEntity.FieldNames.Valid] = string.Empty;
                    }

                    if (item.OvertimeTypeID != Guid.Empty)
                    {
                        var OTType = lstOvertimeType.Where(s => s.ID == item.OvertimeTypeID).FirstOrDefault();
                        row[Att_OvertimeEntity.FieldNames.OvertimeTypeID] = item.OvertimeTypeID;
                        row[Att_OvertimeEntity.FieldNames.OvertimeTypeName] = OTType.OvertimeTypeName;

                        row[OTType.Code] = item.RegisterHours;
                        row[OTType.Code + "Confirm"] = item.ApproveHours ?? 0.0;
                    }
                    if (item.ShiftID != Guid.Empty)
                    {
                        var _shift = lstShift.Where(s => s.ID == item.ShiftID).FirstOrDefault();
                        row[Att_OvertimeEntity.FieldNames.ShiftID] = item.ShiftID;
                        row[Att_OvertimeEntity.FieldNames.ShiftName] = _shift.ShiftName;
                    }
                    if (item.ProfileID != Guid.Empty)
                    {
                        var temp = lstProfile.Where(s => s.ID == item.ProfileID).FirstOrDefault();
                        row[Att_OvertimeEntity.FieldNames.ProfileID] = item.ProfileID;
                        row[Att_OvertimeEntity.FieldNames.ProfileName] = temp.ProfileName;
                        row[Att_OvertimeEntity.FieldNames.CodeEmp] = temp.CodeEmp;
                        //row[Att_ReportDetailOvertimeEntity.FieldNames.OrgStructureName] = temp.OrgStructureName;
                    }
                    row[Att_OvertimeEntity.FieldNames.TotalRow] = lstOvertimeCal.Count;
                    row[Att_OvertimeEntity.FieldNames.DateExport] = DateTime.Now;
                    row[Att_OvertimeEntity.FieldNames.AnalyseHour] = item.AnalyseHour;
                    row[Att_OvertimeEntity.FieldNames.udHourByDate] = item.udHourByDate;
                    row[Att_OvertimeEntity.FieldNames.udHourByWeek] = item.udHourByWeek;
                    row[Att_OvertimeEntity.FieldNames.udHourByMonth] = item.udHourByMonth;
                    row[Att_OvertimeEntity.FieldNames.udHourByYear] = item.udHourByYear;
                    row[Att_OvertimeEntity.FieldNames.udLeaveTypeCode] = item.udLeaveTypeCode;
                    row[Att_OvertimeEntity.FieldNames.udOvertimeStatus] = item.udOvertimeStatus;
                    row[Att_OvertimeEntity.FieldNames.RegisterHours] = item.RegisterHours;
                    row[Att_OvertimeEntity.FieldNames.ApproveHours] = item.RegisterHours;
                    table.Rows.Add(row);
                }
                #endregion

                return table;

            }
        }
Example #28
0
        private string SaveLeaveDay(List<Att_Overtime> lstAttOvertimeInput, DateTime? date1, DateTime? date2)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_Workday = new CustomBaseRepository<Att_Workday>(unitOfWork);
                var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
                var repoCat_Shift = new CustomBaseRepository<Cat_Shift>(unitOfWork);
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
                var repoAtt_TimeOffInLieu = new CustomBaseRepository<Att_TimeOffInLieu>(unitOfWork);
                string E_TIMEOFF = MethodOption.E_TIMEOFF.ToString();
                List<Att_Overtime> lstAttOvertime = lstAttOvertimeInput.Where(m => m.MethodPayment == E_TIMEOFF && m.WorkDateRoot != null).ToList();
                //string validate 
                string Validate = validateSaveLeaveDay(lstAttOvertime, date1, date2);
                if (Validate != string.Empty)
                {
                    return Validate;
                }

                List<Guid> lstProfileIDs = lstAttOvertime.Select(m => m.ProfileID).Distinct().ToList();
                var LstWorkday1 = new List<Att_Workday>().Select(m => new { m.ProfileID, m.WorkDate, m.ShiftApprove, m.ShiftID });
                var LstWorkday2 = new List<Att_Workday>().Select(m => new { m.ProfileID, m.WorkDate, m.ShiftApprove, m.ShiftID });
                if (date1 != null)
                {
                    LstWorkday1 = repoAtt_Workday.FindBy(m => m.WorkDate == date1.Value && lstProfileIDs.Contains(m.ProfileID))
                        .Select(m => new { m.ProfileID, m.WorkDate, m.ShiftApprove, m.ShiftID });
                }
                if (date2 != null)
                {
                    LstWorkday2 = repoAtt_Workday.FindBy(m => m.WorkDate == date2.Value && lstProfileIDs.Contains(m.ProfileID))
                        .Select(m => new { m.ProfileID, m.WorkDate, m.ShiftApprove, m.ShiftID });
                }

                List<Att_LeaveDay> lstLeaveDayInsert = new List<Att_LeaveDay>();
                Guid OvertimeTypeTimeOffID = repoCat_LeaveDayType.FindBy(m => m.IsTimeOffInLieu == true).Select(m => m.ID).FirstOrDefault();
                if (OvertimeTypeTimeOffID == null || OvertimeTypeTimeOffID == Guid.Empty)
                    return string.Empty;
                var lstShift = repoCat_Shift.GetAll().Select(m => new { m.ID, m.WorkHours });
                foreach (var item in lstAttOvertime)
                {
                    if (date1 != null)
                    {
                        Att_LeaveDay leaveDay = new Att_LeaveDay();
                        leaveDay.ID = Guid.Empty;
                        leaveDay.ProfileID = item.ProfileID;
                        leaveDay.LeaveDayTypeID = OvertimeTypeTimeOffID;
                        leaveDay.DateStart = date1.Value;
                        leaveDay.DateEnd = date1.Value;
                        leaveDay.TotalDuration = 1;
                        leaveDay.LeaveDays = 1;
                        leaveDay.Att_Overtime = item;
                        if (item.Status == OverTimeStatus.E_WAIT_APPROVED.ToString())
                            leaveDay.Status = LeaveDayStatus.E_WAIT_APPROVED.ToString();
                        else if (item.Status == OverTimeStatus.E_APPROVED.ToString())
                        {
                            leaveDay.Status = LeaveDayStatus.E_APPROVED.ToString();
                        }
                        else if (item.Status == OverTimeStatus.E_CONFIRM.ToString())
                        {
                            leaveDay.Status = LeaveDayStatus.E_APPROVED.ToString();
                        }
                        else
                        {
                            leaveDay.Status = LeaveDayStatus.E_SUBMIT.ToString();
                        }

                        var workday = LstWorkday1.Where(m => m.ProfileID == item.ProfileID && m.WorkDate == date1.Value).FirstOrDefault();
                        if (workday != null)
                        {
                            Guid? ShiftID = workday.ShiftApprove ?? workday.ShiftID;
                            if (ShiftID != null)
                            {
                                var shift = lstShift.Where(m => m.ID == ShiftID).FirstOrDefault();
                                if (shift != null)
                                {
                                    leaveDay.LeaveHours = shift.WorkHours ?? 0;
                                }
                            }

                        }
                        if (leaveDay.LeaveHours == null || leaveDay.LeaveHours == 0)
                        {
                            leaveDay.LeaveHours = 8;
                        }
                        lstLeaveDayInsert.Add(leaveDay);
                    }
                    if (date2 != null)
                    {
                        Att_LeaveDay leaveDay = new Att_LeaveDay();
                        leaveDay.ID = Guid.Empty;
                        leaveDay.ProfileID = item.ProfileID;
                        leaveDay.LeaveDayTypeID = OvertimeTypeTimeOffID;
                        leaveDay.DateStart = date2.Value;
                        leaveDay.DateEnd = date2.Value;
                        leaveDay.TotalDuration = 1;
                        leaveDay.LeaveDays = 1;
                        leaveDay.Att_Overtime = item;
                        if (item.Status == OverTimeStatus.E_WAIT_APPROVED.ToString())
                            leaveDay.Status = LeaveDayStatus.E_WAIT_APPROVED.ToString();
                        else if (item.Status == OverTimeStatus.E_APPROVED.ToString())
                        {
                            leaveDay.Status = LeaveDayStatus.E_APPROVED.ToString();
                        }
                        else if (item.Status == OverTimeStatus.E_CONFIRM.ToString())
                        {
                            leaveDay.Status = LeaveDayStatus.E_APPROVED.ToString();
                        }
                        else
                        {
                            leaveDay.Status = LeaveDayStatus.E_SUBMIT.ToString();
                        }

                        var workday = LstWorkday2.Where(m => m.ProfileID == item.ProfileID && m.WorkDate == date2.Value).FirstOrDefault();
                        if (workday != null)
                        {
                            Guid? ShiftID = workday.ShiftApprove ?? workday.ShiftID;
                            if (ShiftID != null)
                            {
                                var shift = lstShift.Where(m => m.ID == ShiftID).FirstOrDefault();
                                if (shift != null)
                                {
                                    leaveDay.LeaveHours = shift.WorkHours ?? 0;
                                }
                            }

                        }
                        if (leaveDay.LeaveHours == null || leaveDay.LeaveHours == 0)
                        {
                            leaveDay.LeaveHours = 8;
                        }
                        lstLeaveDayInsert.Add(leaveDay);
                    }
                }

                if (lstLeaveDayInsert.Count > 0)
                {
                    repoAtt_LeaveDay.Add(lstLeaveDayInsert);
                    //EntityService.AddEntity<Att_LeaveDay>(GuidContext, lstLeaveDayInsert.ToArray());
                }

                List<Att_TimeOffInLieu> lstTimeoffInlieu = new List<Att_TimeOffInLieu>();
                foreach (var item in lstLeaveDayInsert)
                {
                    if (item.Status == LeaveDayStatus.E_APPROVED.ToString())
                    {
                        Att_TimeOffInLieu timeOffLieu = AddTimeOffInLieu(item);
                        if (timeOffLieu != null)
                            lstTimeoffInlieu.Add(timeOffLieu);
                    }
                }
                if (lstTimeoffInlieu.Count > 0)
                {
                    repoAtt_TimeOffInLieu.Add(lstTimeoffInlieu);
                    //EntityService.AddEntity<Att_TimeOffInLieu>(GuidContext, lstTimeoffInlieu.ToArray());
                }
                return string.Empty;
            }
        }
Example #29
0
        public DataTable ReportBonusHoliday(List<Hre_ProfileEntity> lstProfile, List<string> lstElementCode, DateTime monthStart, DateTime monthEnd, string UserLogin, bool isCreateTemplate)
        {
            using (var context = new VnrHrmDataContext())
            {
                #region Get Data
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoElement = new CustomBaseRepository<Cat_Element>(unitOfWork);

                //ds phần tử
                string statusEl = string.Empty;
                var lstObjElement = new List<object>();
                lstObjElement.Add(null);
                lstObjElement.Add(null);
                lstObjElement.Add(null);
                lstObjElement.Add(null);
                lstObjElement.Add(null);
                lstObjElement.Add(1);
                lstObjElement.Add(int.MaxValue - 1);
                List<Cat_ElementEntity> lstElement = GetData<Cat_ElementEntity>(lstObjElement, ConstantSql.hrm_cat_sp_get_Element, UserLogin, ref statusEl);
                lstElement = lstElement.Where(m => lstElementCode.Contains(m.ElementCode)).ToList();

                DataTable table = GetSchemaBonusHoliday(lstElement);
                if (isCreateTemplate)
                {
                    return table;
                }

                var repoOrgStructure = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var repoCostCentre = new CustomBaseRepository<Cat_CostCentre>(unitOfWork);

                //ds nhân viên
                var lstProfileID = lstProfile.Select(hr => hr.ID).ToList();

                //Bảng lương
                string statusTb = string.Empty;
                List<object> listModelprtb = new List<object>();
                listModelprtb = new List<object>();
                listModelprtb.AddRange(new object[9]);
                listModelprtb[2] = monthStart;
                listModelprtb[3] = monthEnd;
                listModelprtb[6] = 1;
                listModelprtb[7] = Int32.MaxValue - 1;
                List<Sal_PayrollTableEntity> listPayrollTable = GetData<Sal_PayrollTableEntity>(listModelprtb, ConstantSql.hrm_sal_sp_get_PayrollTable, UserLogin, ref statusTb);

                string statusTbit = string.Empty;
                List<object> listModelprtbit = new List<object>();
                listModelprtbit = new List<object>();
                listModelprtbit.AddRange(new object[9]);
                listModelprtbit[2] = monthStart;
                listModelprtbit[3] = monthEnd;
                listModelprtbit[6] = 1;
                listModelprtbit[7] = Int32.MaxValue - 1;
                List<Sal_PayrollTableItemEntity> listPayrollTableItem = GetData<Sal_PayrollTableItemEntity>(listModelprtbit, ConstantSql.hrm_sal_sp_get_PayrollTableItem, UserLogin, ref statusTbit);
                listPayrollTableItem = listPayrollTableItem.Where(it => it.Value != null && it.Value != string.Empty).ToList();

                var lstOrgStructure = repoOrgStructure.GetAll().Where(org => org.IsDelete == null).Select(org => new { org.ID, org.Code, org.OrgStructureName }).ToList();
                var lstCostcentre = repoCostCentre.GetAll().Where(cost => cost.IsDelete == null).Select(cost => new { cost.ID, cost.Code, cost.CostCentreName }).ToList();
                #endregion

                #region Process
                foreach (var profile in lstProfile)
                {
                    if (profile == null)
                    {
                        continue;
                    }

                    DataRow dr = table.NewRow();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CodeEmp] = profile.CodeEmp;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.ProfileName] = profile.ProfileName;

                    var orgStructure = lstOrgStructure.Where(org => org.ID == profile.OrgStructureID).FirstOrDefault();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureCode] = orgStructure != null ? orgStructure.Code : string.Empty;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.OrgStructureName] = orgStructure != null ? orgStructure.OrgStructureName : string.Empty;

                    var costcentre = lstCostcentre.Where(cost => cost.ID == profile.CostCentreID).FirstOrDefault();
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenterCode] = costcentre != null ? costcentre.Code : string.Empty;
                    dr[Sal_ReportBasicSalaryMonthlyEntity.FieldNames.CostCenter] = costcentre != null ? costcentre.CostCentreName : string.Empty;

                    //Bảng lương mỗi profile
                    var payrollTbID_Profile = listPayrollTable.Where(sal => sal.ProfileID == profile.ID).Select(sal => sal.ID).FirstOrDefault();
                    var payrollTbItem_Profile = listPayrollTableItem.Where(salit => salit.PayrollTableID == payrollTbID_Profile).ToList();
                    if (payrollTbItem_Profile != null && payrollTbItem_Profile.Count > 0)
                    {
                        foreach (var element in lstElementCode)
                        {
                            var prItem = payrollTbItem_Profile.Where(salIt => salIt.Code == element).FirstOrDefault();
                            if (prItem != null)
                            {
                                if (prItem.ValueType != null && prItem.ValueType.ToUpper() == typeof(Double).Name.ToUpper())
                                {
                                    dr[element] = Convert.ToDouble(prItem.Value);
                                }
                                else if (prItem.ValueType != null && prItem.ValueType.ToUpper() == typeof(DateTime).Name.ToUpper())
                                {
                                    dr[element] = Convert.ToDateTime(prItem.Value);
                                }
                                else
                                    dr[element] = prItem.Value;
                            }
                        }
                    }

                    table.Rows.Add(dr);
                }
                #endregion

                return table;
            }
        }
Example #30
0
        public void ActionSubmit(List<Guid> lstId, string status, Guid userId)
        {
            var statusMes = string.Empty;
            var objTravelRequest = new List<object>();
            var UserLogin = string.Empty;
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoTravelRequestItem = new CustomBaseRepository<Fin_CashAdvanceItem>(unitOfWork);
                var lstTravelRequestItem = repoTravelRequestItem.GetAll().Where(s => s.IsDelete == null).ToList();

                var cashAdvanceID = lstTravelRequestItem.Where(s => s.CashAdvanceID != null && lstId.Contains(s.ID)).Select(s => s.CashAdvanceID).Distinct().FirstOrDefault();
                var userEntity = GetData<Sys_UserInfoEntity>(userId, ConstantSql.hrm_sys_sp_get_UserbyId, UserLogin, ref statusMes).FirstOrDefault();

                var cashAdvanceEntity = new Fin_CashAdvanceEntity();
                if (cashAdvanceID != null)
                {
                    cashAdvanceEntity = GetData<Fin_CashAdvanceEntity>(cashAdvanceID.Value, ConstantSql.hrm_hr_sp_get_CashAdvanceById, UserLogin, ref statusMes).FirstOrDefault();
                }

                if (lstId.Count > 0)
                {

                    if (userEntity != null && cashAdvanceEntity != null)
                    {
                        if (userEntity.ProfileID.Value == cashAdvanceEntity.ProfileID.Value)
                        {
                            lstTravelRequestItem = lstTravelRequestItem.Where(s => lstId.Contains(s.ID)).ToList();
                            foreach (var item in lstTravelRequestItem)
                            {
                                item.Status = status;
                            }
                            repoTravelRequestItem.SaveChanges();
                        }
                    }
                    
                }

            }
        }
Example #31
0
        /// <summary>
        /// [Hien.NGuyen] - Xử lý form lưu của màn hình phân tích tăng ca
        /// </summary>
        /// <param name="updatedAtt_OvertimeModel"></param>
        /// <returns></returns>
        public bool CreateComputeOvertime(List<Att_OvertimeEntity> lstOvertimeInsert, string PaymentMethod, string strOvertimeStatus, Guid UserAppvoveID, double HourToTimeOff, double TimeRegister, string strReasonOT, Guid UserId, string userLogin)
        {
            string status = string.Empty;
            List<Att_Overtime> lstOvertimeInsertOutput = new List<Att_Overtime>();
            List<Guid> lstProID = lstOvertimeInsert.Select(s => s.ProfileID).Distinct().ToList();

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoSys_UserInfo = new CustomBaseRepository<Sys_UserInfo>(unitOfWork);
                //var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoAtt_AllowLimitOvertime = new CustomBaseRepository<Att_AllowLimitOvertime>(unitOfWork);
                var repoCat_EntityLabel = new CustomBaseRepository<Cat_EntityLabel>(unitOfWork);
                var repoSys_GroupLabel = new CustomBaseRepository<Sys_GroupLabel>(unitOfWork);
                var repoAtt_TimeOffInLieu = new CustomBaseRepository<Att_TimeOffInLieu>(unitOfWork);
                var repoAtt_OverTime = new CustomBaseRepository<Att_Overtime>(unitOfWork);

                var lstHre = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(String.Join(",", lstProID)), ConstantSql.hrm_hr_sp_get_ProfileByIds, userLogin, ref status);

                Sys_UserInfo UserAppvove = repoSys_UserInfo.FindBy(pro => pro.ID == UserAppvoveID).FirstOrDefault();
                if (UserAppvove == null)
                {
                    //errorMessage = Messages.plsChooseApproveUser.TranslateString();
                    return false;
                }
                if (strReasonOT == string.Empty)
                    strReasonOT = " ";
                foreach (var item in lstOvertimeInsert)
                {
                    item.ReasonOT = strReasonOT;
                    if (item.MethodPayment == null)
                    {
                        item.MethodPayment = EnumDropDown.PaymentType.E_CASHOUT.ToString();
                    }
                }
                #region Validate Đã Đăng Ký Rồi
                List<Guid> profileHaveOT = new List<Guid>();
                profileHaveOT = lstOvertimeInsert.Where(m => m.udOvertimeStatus != null).Select(m => m.ProfileID).Distinct().ToList();
                if (profileHaveOT.Count > 0)
                {
                    var lstProfile = lstHre.Where(m => profileHaveOT.Contains(m.ID)).Select(m => new { m.ID, m.ProfileName, m.CodeEmp });
                    string ProfileNameErr = string.Empty;
                    foreach (var item in lstProfile)
                    {
                        ProfileNameErr += item.ProfileName + " [" + item.CodeEmp + "]; ";
                    }
                    if (ProfileNameErr.Length > 0)
                    {
                        ProfileNameErr = ProfileNameErr.Substring(0, ProfileNameErr.Length - 2);
                    }
                    //errorMessage = string.Format("Nhân viên {0} Tăng Ca Trùng ", ProfileNameErr);
                    return false;
                }
                #endregion
                #region Validate Không được phép Tăng Ca
                string Err = ValidateOT_DoNotAllow(lstOvertimeInsert, lstHre);
                if (Err != string.Empty)
                {
                    //errorMessage = Err;
                    return false;
                }
                #endregion

                #region phân tích lại và validate thông báo vượt trần mức 300
                List<Att_AllowLimitOvertime> lisProfileAllowLimitOvertime = repoAtt_AllowLimitOvertime.GetAll().ToList();
                double HourInLieu = 0;
                if (PaymentMethod == EnumDropDown.PaymentType.E_CASHOUT.ToString() || PaymentMethod == EnumDropDown.PaymentType.E_CASHOUT_TIMEOFF.ToString())
                {
                    HourInLieu = HourToTimeOff;
                }
                else if (PaymentMethod == MethodOption.E_TIMEOFF.ToString())
                {
                    HourInLieu = double.MaxValue;
                }
                if (HourInLieu > 0)
                {
                    lstOvertimeInsert = SplitOvertimeByInlieuHour(lstOvertimeInsert, HourInLieu);
                }
                OvertimePermitEntity overtimePermit = getOvertimePermit(userLogin);

                List<Att_OvertimeEntity> LimitOTByYear = ValidateLimitOTByYear(lstOvertimeInsert, lisProfileAllowLimitOvertime, overtimePermit);
                if (LimitOTByYear.Count > 0)
                {
                    List<Guid> lstProfileID = LimitOTByYear.Select(m => m.ProfileID).Distinct().ToList();
                    var lstProfile = lstHre.Where(m => lstProfileID.Contains(m.ID)).Select(m => new { m.ID, m.ProfileName, m.CodeEmp });
                    string lstCodeEmpErr = string.Empty;
                    foreach (var item in lstProfile)
                    {
                        lstCodeEmpErr += item.CodeEmp + "; ";
                    }
                    if (lstCodeEmpErr.Length > 0)
                    {
                        lstCodeEmpErr = lstCodeEmpErr.Substring(0, lstCodeEmpErr.Length - 2);
                    }
                    // errorMessage = string.Format("Nhân viên {0} đã vượt trần", lstCodeEmpErr);
                    return false;
                }

                #endregion


                List<Att_TimeOffInLieu> lstTimeOffInLieu = new List<Att_TimeOffInLieu>();

                string Att_Overtime = "Att_Overtime";
                string E_OVERTIME = "E_OVERTIME";
                Cat_EntityLabel EntityLabel = repoCat_EntityLabel.FindBy(m => m.UserID == UserId && m.EntityName == Att_Overtime && m.EntityLabelName == E_OVERTIME).FirstOrDefault();
                if (EntityLabel == null)
                {
                    EntityLabel = new Cat_EntityLabel();
                    EntityLabel.ID = Guid.NewGuid();
                    EntityLabel.UserID = UserId;
                    EntityLabel.EntityName = Att_Overtime;
                    EntityLabel.EntityLabelName = E_OVERTIME;
                    repoCat_EntityLabel.Add(EntityLabel);
                    repoCat_EntityLabel.SaveChanges();
                }
                Sys_GroupLabel GroupLable = repoSys_GroupLabel.FindBy(m => m.EntityLabelID == EntityLabel.ID).FirstOrDefault();
                if (GroupLable == null)
                {
                    GroupLable = new Sys_GroupLabel();
                    GroupLable.ID = Guid.NewGuid();
                    GroupLable.EntityLabelID = EntityLabel.ID;
                    GroupLable.EntityItems = string.Empty;
                    repoSys_GroupLabel.Add(GroupLable);
                    repoSys_GroupLabel.SaveChanges();
                }
                string EntityItems = GroupLable.EntityItems;

                List<Att_Overtime> save = new List<Att_Overtime>();
                List<Att_Overtime> saveAdd = new List<Att_Overtime>();
                List<Att_Overtime> saveEdit = new List<Att_Overtime>();
                Att_Overtime saveModel = null;
                foreach (Att_OvertimeEntity Ot in lstOvertimeInsert)
                {

                    bool InsertToTimeOffInlieu = false;
                    Ot.Status = strOvertimeStatus;//OverTimeStatus.E_APPROVED.ToString();
                    Ot.udOvertimeStatus = strOvertimeStatus.TranslateString();
                    if (strOvertimeStatus == OverTimeStatus.E_APPROVED.ToString())
                    {
                        Ot.ApproveHours = Ot.RegisterHours;
                        if (Ot.MethodPayment == EnumDropDown.PaymentType.E_TIMEOFF.ToString() || Ot.MethodPayment == EnumDropDown.PaymentType.E_CASHOUT_TIMEOFF.ToString())
                            InsertToTimeOffInlieu = true;
                    }
                    else if (strOvertimeStatus == OverTimeStatus.E_CONFIRM.ToString())
                    {
                        Ot.ConfirmHours = Ot.RegisterHours;
                        if (Ot.MethodPayment == EnumDropDown.PaymentType.E_TIMEOFF.ToString() || Ot.MethodPayment == EnumDropDown.PaymentType.E_CASHOUT_TIMEOFF.ToString())
                            InsertToTimeOffInlieu = true;
                    }
                    Ot.ReasonOT = strReasonOT;
                    Ot.UserApproveID = UserAppvove.ID;
                    Guid ProfileID = Ot.ProfileID;
                    DateTime beginOt = Ot.WorkDate;
                    DateTime endOt = beginOt.AddHours(Ot.RegisterHours);
                    Att_OvertimeEntity OvertimeRemove = lstOvertimeCache.Where(m => m.ID == Ot.ID).FirstOrDefault();
                    if (OvertimeRemove != null)
                    {
                        int index = lstOvertimeCache.IndexOf(OvertimeRemove);
                        lstOvertimeCache.Remove(OvertimeRemove);
                        lstOvertimeCache.Insert(index, Ot);
                    }

                    if (InsertToTimeOffInlieu)
                    {
                        Att_TimeOffInLieu timeOffLieu = AddTimeOffInLieu(Ot.CopyData<Att_Overtime>());
                        lstTimeOffInLieu.Add(timeOffLieu);
                        //repoAtt_TimeOffInLieu.Add(timeOffLieu);
                    }
                    EntityItems += Ot.ID.ToString().ToLower() + "|";
                    //Insert vào Đính Nhãn

                    saveModel = Ot.CopyData<Att_Overtime>();
                    save.Add(saveModel);
                }
                if (EntityItems.Length > 0)
                {
                    EntityItems = EntityItems.Substring(0, EntityItems.Length - 1);
                }
                GroupLable.EntityItems = EntityItems;

                saveEdit = save.Where(s => s.ID != Guid.Empty).ToList();
                saveAdd = save.Where(s => s.ID == Guid.Empty).ToList();
                foreach (var item in saveAdd)
                {
                    item.ID = Guid.NewGuid();
                }
                if (saveAdd != null && saveAdd.Count > 0)
                    repoAtt_OverTime.Add(saveAdd);
                if (saveEdit != null && saveEdit.Count > 0)
                    repoAtt_OverTime.Edit(saveEdit);
                if (lstTimeOffInLieu != null && lstTimeOffInLieu.Count > 0)
                    repoAtt_TimeOffInLieu.Add(lstTimeOffInLieu);
                //if (EntityLabel != null)
                //    repoCat_EntityLabel.Add(EntityLabel);
                //if (GroupLable != null)
                //    repoSys_GroupLabel.Add(GroupLable);
                try
                {
                    repoAtt_OverTime.SaveChanges();
                    repoAtt_TimeOffInLieu.SaveChanges();
                    //repoCat_EntityLabel.SaveChanges();
                    //repoSys_GroupLabel.SaveChanges();
                    //unitOfWork.SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }
Example #32
0
        public string ProcessSendMailForFirstApprove(string host, Guid userId, Guid recordID)
        {
            DataErrorCode status = DataErrorCode.Success;
            using (var context = new VnrHrmDataContext())
            {
                var Services = new BaseService();
                var UserLogin = string.Empty;
                string statusMess = string.Empty;
                string type = ApproveType.E_FIN_CashAdvance.ToString();
                string typeApprover = FinApproverType.Fin_CashAdvance.ToString();
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoSys_UserApprove = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);

                var repoSys_UserInfo = new CustomBaseRepository<Sys_UserInfo>(unitOfWork);
                var lstUserInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null).ToList();
                var userInfoEntity = lstUserInfo.Where(s => userId == s.ID).FirstOrDefault();
                var repo_JobTitle = new CustomBaseRepository<Cat_JobTitle>(unitOfWork);
                var lstJobTitle = repo_JobTitle.GetAll().Where(s => s.IsDelete == null).ToList();
                var repoOrg = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var lstOrg = repoOrg.GetAll().Where(s => s.IsDelete == null).ToList();
                var repoProfile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var lstProfile = repoProfile.GetAll().Where(s => s.IsDelete == null).ToList();

                var repoFIN_TravelRequest = new CustomBaseRepository<Fin_CashAdvance>(unitOfWork);
                var record = repoFIN_TravelRequest.FindBy(s => s.ID == recordID).FirstOrDefault();

                if (record != null)
                {
                    List<Guid> lstIds = new List<Guid>();
                    lstIds.Add(record.ID);
               
                    ActionApprovedAll(lstIds, "E_REQUEST", userId);
                }

                var repoCashItem = new CustomBaseRepository<Fin_CashAdvanceItem>(unitOfWork);
                var totalItem = repoCashItem.GetAll().Where(s => s.IsDelete == null && s.CashAdvanceID != null && s.CashAdvanceID.Value == recordID).Sum(s => s.Amount);

                var repoFin_Approver = new CustomBaseRepository<FIN_ApproverECLAIM>(unitOfWork);
                var lstApprover = repoFin_Approver.GetAll().Where(s => s.IsDelete == null).ToList();

                var repoSys_TemplateSendMail = new CustomBaseRepository<Sys_TemplateSendMail>(unitOfWork);

                string _typeTemplate = EnumDropDown.EmailType.E_REQUEST_CASHADVANCE.ToString();
                var template = repoSys_TemplateSendMail.FindBy(s => s.Type == _typeTemplate).FirstOrDefault();

                if (userInfoEntity != null)
                {
                    var profileInfoEntity = lstProfile.Where(s => s.ID == userInfoEntity.ProfileID.Value).FirstOrDefault();
                    var jobTitleEntity = lstJobTitle.Where(s => profileInfoEntity.JobTitleID != null && s.ID == profileInfoEntity.JobTitleID.Value).FirstOrDefault();
                    var orgEntity = lstOrg.Where(s => profileInfoEntity.OrgStructureID != null && s.ID == profileInfoEntity.OrgStructureID.Value).FirstOrDefault();
                    var lstApproverByClaim = lstApprover.Where(s => s.ProfileID == userInfoEntity.ProfileID && s.ApprovedType == typeApprover && s.ApprovedID != null).OrderBy(s => s.OrderNo).ToList();
                    var approvedEntity = new FIN_ApproverECLAIM();

                   // var firstApprover = lstApprover.Where(s => s.ProfileID == userInfoEntity.ProfileID && s.ApprovedType == typeApprover).OrderBy(s => s.OrderNo).FirstOrDefault();


                    var firstApprover = lstApproverByClaim.FirstOrDefault();
                    foreach (var item in lstApproverByClaim)
                    {
                        if (firstApprover.OrderNo == item.OrderNo)
                        {
                            continue;
                        }
                        approvedEntity = item;
                        break;
                    }

                  //  var userIdSecondApprover = lstApprover.Where(s => s.ProfileID == userInfoEntity.ProfileID && s.ApprovedType == typeApprover && s.OrderNo == 2).FirstOrDefault();
                    var userIdSecondApprover = lstApprover.Where(s => s.ID == approvedEntity.ID).FirstOrDefault();

                    if (firstApprover != null)
                    {
                        var userEnityByProfileID = lstUserInfo.Where(s => s.ID == firstApprover.ApprovedID.Value).FirstOrDefault();
                        var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userEnityByProfileID.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();
                        if (profileEntity != null)
                        {
                            if (userIdSecondApprover != null)
                            {
                                if (template != null)
                                {
                                    string MailTo = profileEntity.Email;

                                    string urlClickHere = host + "#Hrm_Main_Web/Fin_SendMailApprovedCashAdvance/DetailTravelRequest/" + recordID + "#NewTab";

                                    string linkcontent = string.Empty;
                                    string linkcontentReject = string.Empty;

                                    var temp = lstUserInfo.Where(s => s.ID == userIdSecondApprover.ApprovedID.Value).FirstOrDefault();
                                    var name = temp.UserInfoName != null ? temp.UserInfoName : temp.UserLogin;

                                    linkcontent += "Nhấn vào " + "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessApprovedPage"
                                   + "?loginID=" + firstApprover.ApprovedID
                                   + "&userApprovedID=" + userIdSecondApprover.ID
                                   + "&recordID=" + recordID
                                   + "'>đây" + "<a/>" + " để đồng ý.";


                                    linkcontentReject += "Nhấn vào " +  "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessRejectPage"
                                     + "?loginID=" + firstApprover.ApprovedID
                                     + "&userApprovedID=" + userIdSecondApprover.ID
                                     + "&recordID=" + recordID
                                     + "'>đây" + "<a/>" + " để từ chối.";

                                    #region magreData

                                    string[] strsParaKey = null;
                                    string[] strsParaValues = null;
                                    strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_PROFILENAME.ToString(),
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_AREA.ToString(), 
 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCECODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_TOTALADVANCE.ToString(), 

                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_DENIES.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_REJECTLINK.ToString(), 


                                    };
                                    strsParaValues = new string[] 
                                    { 
                                        profileEntity.ProfileName, 
                                        jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        userInfoEntity.UserInfoName, 
                                        record.CashAdvanceName, 
                                        record.Code, 
                                        totalItem.ToString(),
                                        "",
                                        linkcontent,
                                        linkcontentReject
                                    };
                                    string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);

                                    #endregion

                                    string titleMail = template.Subject;
                                    bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                }
                            }


                        }
                    }

                }

                return status.ToString();
            }
        }
Example #33
0
        private void FillAllowOTValidate(List<Att_OvertimeEntity> lstOvertime, OvertimePermitEntity OtPermit)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_Overtime = new CustomBaseRepository<Att_Overtime>(unitOfWork);
                var repoCat_Shift = new CustomBaseRepository<Cat_Shift>(unitOfWork);
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);

                if (lstOvertime.Count == 0)
                {
                    return;
                }
                if (OtPermit == null || (OtPermit.limitHour_ByDay == null
                                        && OtPermit.limitHour_ByDay_Lev1 == null
                                        && OtPermit.limitHour_ByDay_Lev2 == null
                                        && OtPermit.limitHour_ByWeek == null
                                        && OtPermit.limitHour_ByWeek_Lev1 == null
                                        && OtPermit.limitHour_ByWeek_Lev2 == null
                                        && OtPermit.limitHour_ByMonth == null
                                        && OtPermit.limitHour_ByMonth_Lev1 == null
                                        && OtPermit.limitHour_ByMonth_Lev2 == null
                                        && OtPermit.limitHour_ByYear == null
                                        && OtPermit.limitHour_ByYear_Lev1 == null
                                        && OtPermit.limitHour_ByYear_Lev2 == null)
                    )
                {
                    return;
                }
                #region getData
                DateTime DateMinInlstOvertime = lstOvertime.Min(m => m.WorkDate);
                DateTime DateMaxInlstOvertime = lstOvertime.Max(m => m.WorkDate);
                List<Guid> lstProfileID = lstOvertime.Select(m => m.ProfileID).Distinct().ToList();

                //Lấy ngày Đầu Năm, Đầu Tuần ->> Ngày nào nhỏ nhất thì lấy theo Ngày đó làm mốc
                DateTime DateMin = DateTime.MinValue;
                DateTime DateBeginYear = new DateTime(DateMinInlstOvertime.Year, 1, 1);
                DateTime DateBeginMonth = new DateTime(DateMinInlstOvertime.Year, DateMinInlstOvertime.Month, 1);
                DateTime DateBeginWeek = DateTime.MinValue;
                DateTime DateEndWeek = DateTime.MinValue;
                Common.GetStartEndWeek(DateMinInlstOvertime.Date, out DateBeginWeek, out DateEndWeek);
                DateMin = DateBeginYear < DateBeginWeek ? DateBeginYear : DateBeginWeek;
                DateTime DateMax = DateMaxInlstOvertime.AddYears(1);

                //string E_SUBMIT = OverTimeStatus.E_SUBMIT.ToString();
                //string E_SUBMIT_TEMP = OverTimeStatus.E_SUBMIT_TEMP.ToString();
                //string E_FIRST_APPROVED = OverTimeStatus.E_FIRST_APPROVED.ToString();
                //string E_WAIT_APPROVED = OverTimeStatus.E_WAIT_APPROVED.ToString();
                string E_APPROVED = OverTimeStatus.E_APPROVED.ToString();
                //string E_CONFIRM = OverTimeStatus.E_CONFIRM.ToString();
                string E_CASHOUT = MethodOption.E_CASHOUT.ToString();

                List<Guid> lstOvertimeAlreadyID = lstOvertime.Where(m => m.udAlreadyOvertimeID != null).Select(m => m.udAlreadyOvertimeID ?? Guid.Empty).Distinct().ToList();


                //var lstOvertimeInDb = repoAtt_Overtime.FindBy(m => m.IsDelete == null && m.WorkDate >= DateMin && m.WorkDate < DateMax && lstProfileID.Contains(m.ProfileID)
                //    && (m.MethodPayment == null || (m.MethodPayment != null && m.MethodPayment == E_CASHOUT))
                //&& m.Status == E_APPROVED)
                //    .Select(m => new { m.Status, m.ProfileID, m.WorkDate, m.RegisterHours, m.ApproveHours, m.ConfirmHours });
                var lstOvertimeInDb = new List<Att_Overtime>().Select(m => new { m.Status, m.ProfileID, m.WorkDate, m.RegisterHours, m.ApproveHours, m.ConfirmHours });
                if (lstProfileID.Count < 2000)
                {
                    lstOvertimeInDb = repoAtt_Overtime.FindBy(m => m.IsDelete == null && m.WorkDate >= DateMin && m.WorkDate < DateMax && lstProfileID.Contains(m.ProfileID)
                           && (m.MethodPayment == null || (m.MethodPayment != null && m.MethodPayment == E_CASHOUT))
                       && m.Status == E_APPROVED)
                       .Select(m => new { m.Status, m.ProfileID, m.WorkDate, m.RegisterHours, m.ApproveHours, m.ConfirmHours }).ToList();
                }
                else
                {
                    lstOvertimeInDb = repoAtt_Overtime.FindBy(m => m.IsDelete == null && m.WorkDate >= DateMin && m.WorkDate < DateMax
                           && (m.MethodPayment == null || (m.MethodPayment != null && m.MethodPayment == E_CASHOUT))
                       && m.Status == E_APPROVED)
                       .Select(m => new { m.Status, m.ProfileID, m.WorkDate, m.RegisterHours, m.ApproveHours, m.ConfirmHours }).ToList();
                }

                var lstShift = repoCat_Shift.GetAll().Select(m => new { m.ID, m.InTime, m.CoBreakOut, m.CoBreakIn, m.CoOut });

                string E_HOLIDAY_HLD = HolidayType.E_HOLIDAY_HLD.ToString();
                List<DateTime> lstHoliday = repoCat_DayOff.FindBy(m => m.Type == E_HOLIDAY_HLD).Select(m => m.DateOff).ToList<DateTime>();
                #endregion

                #region processing

                lstOvertime = lstOvertime.OrderBy(m => m.WorkDateRoot).ThenBy(m => m.WorkDate).ToList();
                foreach (var ProfileID in lstProfileID)
                {
                    Double RegisterPlus_Year_Validate = 0;
                    Double RegisterPlus_Month_Validate = 0;
                    Double RegisterPlus_Week_Validate = 0;

                    DateTime BeginYear = DateTime.MinValue;
                    DateTime EndYear = DateTime.MinValue;
                    DateTime BeginMonth = DateTime.MinValue;
                    DateTime EndMonth = DateTime.MinValue;
                    DateTime BeginWeek = DateTime.MinValue;
                    DateTime EndWeek = DateTime.MinValue;
                    DateTime BeginDate = DateTime.MinValue;
                    DateTime EndDate = DateTime.MinValue;

                    bool isResetYear = false;
                    bool isResetMonth = false;
                    bool isResetWeek = false;

                    List<Att_OvertimeEntity> lstOvertime_ByProfile = lstOvertime.Where(m => m.ProfileID == ProfileID).ToList();
                    var lstOvertime_ByProfile_DB = lstOvertimeInDb.Where(m => m.ProfileID == ProfileID).ToList();

                    foreach (var OT in lstOvertime_ByProfile)
                    {
                        DateTime workday = OT.WorkDateRoot ?? OT.WorkDate;
                        #region ResetPlus
                        //reset year
                        if (workday.Date > EndYear)
                        {
                            BeginYear = new DateTime(workday.Year, 1, 1);
                            EndYear = BeginYear.AddYears(1).AddMinutes(-1);
                            if (string.IsNullOrEmpty(OT.udOvertimeStatus))
                                RegisterPlus_Year_Validate = OT.RegisterHours;
                            isResetYear = true;
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(OT.udOvertimeStatus))
                                RegisterPlus_Year_Validate += OT.RegisterHours;
                            isResetYear = false;
                        }
                        //Reset Month
                        if (workday.Date > EndMonth)
                        {
                            BeginMonth = new DateTime(workday.Year, workday.Month, 1);
                            EndMonth = BeginMonth.AddMonths(1).AddMinutes(-1);
                            if (string.IsNullOrEmpty(OT.udOvertimeStatus))
                                RegisterPlus_Month_Validate = OT.RegisterHours;
                            isResetMonth = true;
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(OT.udOvertimeStatus))
                                RegisterPlus_Month_Validate += OT.RegisterHours;
                            isResetMonth = false;
                        }
                        //Reset Week
                        if (workday.Date > EndWeek)
                        {
                            Common.GetStartEndWeek(workday.Date, out BeginWeek, out EndWeek);
                            if (string.IsNullOrEmpty(OT.udOvertimeStatus))
                                RegisterPlus_Week_Validate = OT.RegisterHours;
                            isResetWeek = true;
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(OT.udOvertimeStatus))
                                RegisterPlus_Week_Validate += OT.RegisterHours;
                            isResetWeek = false;
                        }
                        //Reset Day
                        #endregion
                        #region getDataExactHour
                        if (isResetYear)
                        {
                            RegisterPlus_Year_Validate += lstOvertime_ByProfile_DB.Where(m => m.WorkDate > BeginYear && m.WorkDate < EndYear && m.Status == E_APPROVED && m.ApproveHours != null).Sum(m => m.ApproveHours.Value);
                        }
                        if (isResetMonth)
                        {
                            RegisterPlus_Month_Validate += lstOvertime_ByProfile_DB.Where(m => m.WorkDate > BeginMonth && m.WorkDate < EndMonth && m.Status == E_APPROVED && m.ApproveHours != null).Sum(m => m.ApproveHours.Value);
                        }
                        if (isResetWeek)
                        {
                            RegisterPlus_Week_Validate += lstOvertime_ByProfile_DB.Where(m => m.WorkDate > BeginWeek && m.WorkDate < EndWeek && m.Status == E_APPROVED && m.ApproveHours != null).Sum(m => m.ApproveHours.Value);
                        }

                        #endregion
                        //Cập nhật lại cho OT voi nhung trang thai can thiet
                        CalOverAllowOT(OT, RegisterPlus_Week_Validate, RegisterPlus_Month_Validate, RegisterPlus_Year_Validate, OtPermit);

                    }
                }
                //unitOfWork.SaveChanges();
                #endregion
            }
        }
Example #34
0
        public DataErrorCode SendMaToPreReject(string host, Guid recordID, Guid userApprovedID, Guid loginId)
        {
            using (var context = new VnrHrmDataContext())
            {
                string statusMess = string.Empty;
                var Services = new BaseService();
                var UserLogin = string.Empty;
                string status = string.Empty;
                string typeApprover = FinApproverType.Fin_CashAdvance.ToString();

                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoSys_UserApprove = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);
                var repoFin_Approver = new CustomBaseRepository<FIN_ApproverECLAIM>(unitOfWork);

                var repo_JobTitle = new CustomBaseRepository<Cat_JobTitle>(unitOfWork);
                var lstJobTitle = repo_JobTitle.GetAll().Where(s => s.IsDelete == null).ToList();
                var repoOrg = new CustomBaseRepository<Cat_OrgStructure>(unitOfWork);
                var lstOrg = repoOrg.GetAll().Where(s => s.IsDelete == null).ToList();

                var repoCashItem = new CustomBaseRepository<Fin_CashAdvanceItem>(unitOfWork);
                var totalItem = repoCashItem.GetAll().Where(s => s.CashAdvanceID == recordID && s.Status.Contains("E_APPROVED")).Sum(s => s.Amount);

                var repoSys_UserInfo = new CustomBaseRepository<Sys_UserInfo>(unitOfWork);
                var repoSys_ConfigProcessApprove = new CustomBaseRepository<Sys_ConfigProcessApprove>(unitOfWork);
                var repoSys_TemplateSendMail = new CustomBaseRepository<Sys_TemplateSendMail>(unitOfWork);


                var repoFIN_TravelRequest = new CustomBaseRepository<Fin_CashAdvance>(unitOfWork);
                var record = repoFIN_TravelRequest.FindBy(s => s.ID == recordID).FirstOrDefault();

                string _typeTemplate = EnumDropDown.EmailType.E_REJECTED_CASHADVANCE.ToString();
                var template = repoSys_TemplateSendMail.FindBy(s => s.Type == _typeTemplate).FirstOrDefault();
                if (template == null)
                    return DataErrorCode.Error_NoTemplateMail;

                var approverEntity = repoFin_Approver.GetAll().Where(s => s.IsDelete == null && s.ApprovedID != null && s.ApprovedID.Value == loginId).FirstOrDefault();

                if (approverEntity != null && approverEntity.OrderNo != null)
                {
                   


                        var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ID == approverEntity.ApprovedID.Value).FirstOrDefault();

                       

                        if (userInfo != null)
                        {
                            var profileRequest = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(record.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();

                            var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, UserLogin, ref statusMess).FirstOrDefault();
                           
                            if (profileEntity != null)
                            {
                                var jobTitleEntity = lstJobTitle.Where(s => profileEntity.JobTitleID != null && s.ID == profileEntity.JobTitleID.Value).FirstOrDefault();
                                var orgEntity = lstOrg.Where(s => profileEntity.OrgStructureID != null && s.ID == profileEntity.OrgStructureID.Value).FirstOrDefault();
                                if (template != null)
                                {
                                    try
                                    {
                                        string MailTo = profileRequest.Email;

                                        string urlClickHere = host + "#Hrm_Main_Web/Fin_SendMailApprovedCashAdvance/DetailTravelRequest/" + recordID + "#NewTab";

                                        string linkcontent = string.Empty;

                                        string linkcontentReject = string.Empty;


                                       

                                        linkcontent += "Nhấn vào " + "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessApprovedPage"
                                       + "?loginID=" + approverEntity.ApprovedID
                                       + "&userApprovedID=" + approverEntity.ID
                                       + "&recordID=" + recordID
                                       + "'>đây" + "<a/>" + " để đồng ý.";

                                        linkcontentReject += "Nhấn vào " + "<a href='" + host + "Fin_SendMailApprovedCashAdvance/ProcessRejectPage"
                                      + "?loginID=" + approverEntity.ApprovedID
                                      + "&userApprovedID=" + approverEntity.ID
                                      + "&recordID=" + recordID
                                      + "'>đây" + "<a/>" + " để từ chối.";

                                        #region magreData

                                        string[] strsParaKey = null;
                                        string[] strsParaValues = null;
                                        strsParaKey = new string[] 
                                    { 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_PROFILENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_JOBTITLE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_AREA.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_USERINFONAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCENAME.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCECODE.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_TOTALADVANCE.ToString(), 

                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_DENIES.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_LINKCONTENT.ToString(), 
                                        EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_REJECTLINK.ToString(), 
                                        
                                   

                                    };
                                        strsParaValues = new string[] 
                                    { 
                                         profileEntity != null ? profileEntity.ProfileName : string.Empty, 
                                       
                                        jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                                        orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                                        profileRequest.ProfileName, 
                                        record.CashAdvanceName, 
                                        record.Code, 
                                        totalItem.ToString() != null ?  totalItem.ToString(): string.Empty,
                                        "Đã Bị Từ Chối Bởi " + profileEntity.ProfileName ,
                                        "",
                                        ""
                                    };
                                        string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);
                                        #endregion

                                        string titleMail = template.Subject;
                                        bool isSuccess = Services.SendMail(titleMail, MailTo, body, string.Empty);
                                        if (isSuccess)
                                            return DataErrorCode.Success;
                                        else
                                            return DataErrorCode.Error;
                                    }
                                    catch (Exception ex)
                                    {
                                        return DataErrorCode.Error_NoConfigMail;
                                    }

                                }
                            }

                        }

                    
                    //else
                    //{
                    //    var userInfo = repoSys_UserInfo.GetAll().Where(s => s.IsDelete == null && s.ProfileID == record.ProfileID.Value).FirstOrDefault();

                    //    if (userInfo != null)
                    //    {
                    //        var profileEntity = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(userInfo.ProfileID.ToString()), ConstantSql.hrm_hr_sp_get_ProfileById, ref statusMess).FirstOrDefault();
                    //        if (profileEntity != null)
                    //        {
                    //            var jobTitleEntity = lstJobTitle.Where(s => profileEntity.JobTitleID != null && s.ID == profileEntity.JobTitleID.Value).FirstOrDefault();
                    //            var orgEntity = lstOrg.Where(s => profileEntity.OrgStructureID != null && s.ID == profileEntity.OrgStructureID.Value).FirstOrDefault();
                    //            if (template != null)
                    //            {
                    //                #region magreData

                    //                string[] strsParaKey = null;
                    //                string[] strsParaValues = null;
                    //                strsParaKey = new string[] 
                    //                { 
                    //                    EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_PROFILENAME.ToString(),
                    //                    EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_JOBTITLE.ToString(), 
                    //                    EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_AREA.ToString(),
                    //                    EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_USERINFONAME.ToString(), 
                    //                    EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCENAME.ToString(), 
                    //                    EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_CASHADVANCECODE.ToString(), 
                    //                    EnumDropDown.EmailType_APPROVED_CASHADVANCE.E_DENIES.ToString(), 
                                   

                    //                };
                    //                strsParaValues = new string[] 
                    //                { 
                    //                    profileEntity.ProfileName, 
                    //                     jobTitleEntity != null ? jobTitleEntity.JobTitleName : string.Empty,
                    //                    orgEntity != null ? orgEntity.OrgStructureName : string.Empty,
                    //                    profileEntity != null ? profileEntity.ProfileName : string.Empty, 
                    //                    record.CashAdvanceName, 
                    //                    record.Code, 
                    //                    "Đã Bị Từ Chối"
                    //                };
                    //                string body = LibraryService.ReplaceContentFile(template.Content, strsParaKey, strsParaValues);
                    //                #endregion
                    //            }
                    //        }

                    //    }

                    //}

                }
                return DataErrorCode.Error;
            }
        }
Example #35
0
        public List<Tra_TraineeScoreEntity> GetListTraineeScore(List<Tra_TraineeScoreImport> lstTraineeScore, out List<Tra_TraineeScoreImport> DataReviewOutput)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoTra_Class = new CustomBaseRepository<Tra_Class>(unitOfWork);
                var repoTra_Trainee = new CustomBaseRepository<Tra_Trainee>(unitOfWork);
                var repoTra_TraineeTopic = new CustomBaseRepository<Tra_TraineeTopic>(unitOfWork);
                var repoTra_TraineeScore = new CustomBaseRepository<Tra_TraineeScore>(unitOfWork);
                var repoTra_ScoreType = new CustomBaseRepository<Tra_ScoreType>(unitOfWork);
                List<Tra_TraineeScoreEntity> entity = new List<Tra_TraineeScoreEntity>();
                List<Tra_TraineeScore> result = new List<Tra_TraineeScore>();
                DataReviewOutput = new List<Tra_TraineeScoreImport>();
                List<string> ClassCode = lstTraineeScore.Select(m => m.ClassCode).Distinct().ToList();
                //Lấy DS ClassID
                List<Guid> ClassID = repoTra_Class.GetAll().Where(m => m.IsDelete == null && ClassCode.Contains(m.Code)).Select(m => m.ID).ToList<Guid>();
                //Lấy DS TraineeID
                List<Guid> TraineeID = repoTra_Trainee.GetAll().Where(m => m.IsDelete == null && ClassID.Contains(m.ClassID)).Select(m => m.ID).ToList<Guid>();
                //Lấy DS TraineetopicID
                List<Guid> lstTraineeTopicID = repoTra_TraineeTopic.GetAll().Where(m => m.IsDelete == null && TraineeID.Contains(m.TraineeID ?? Guid.Empty)).Select(m => m.ID).ToList<Guid>();
                //Lấy DS TraineeTopic
                var TraineeTopicAll = repoTra_TraineeTopic.GetAll().Where(m => m.IsDelete == null && lstTraineeTopicID.Contains(m.ID))
                    .Select(m => new { m.ID, TopicCode = m.Cat_Topic.Code, CodeEmp = m.Tra_Trainee.Hre_Profile.CodeEmp, ClassCode = m.Tra_Trainee.Tra_Class.Code }).ToList();
                //Lấy DS TraineeScore
                List<Tra_TraineeScore> LstTraineeScoreAll = repoTra_TraineeScore.GetAll().Where(m => m.IsDelete == null && lstTraineeTopicID.Contains(m.TraineeTopicID ?? Guid.Empty)).ToList<Tra_TraineeScore>();
                List<string> ScoreTypeCode = lstTraineeScore.Select(m => m.TypeScore).Distinct().ToList<string>();
                List<Tra_ScoreType> lstTypeScoreAll = repoTra_ScoreType.GetAll().Where(m => m.IsDelete == null && ScoreTypeCode.Contains(m.Code)).ToList<Tra_ScoreType>();
                var stt = 1;
                foreach (var TraineeScore in lstTraineeScore)
                {
                    var TraineeTopic = TraineeTopicAll.Where(m =>  m.CodeEmp == TraineeScore.CodeEmp && m.TopicCode == TraineeScore.TopicCode).FirstOrDefault();
                    Tra_ScoreType ScoreType = lstTypeScoreAll.Where(m => m.Code == TraineeScore.TypeScore).FirstOrDefault();
                    if (TraineeTopic == null) //Loi import
                    {
                        TraineeScore.Stt = stt++;
                        TraineeScore.TypeError = "Không Có Môn Học Của Học Viên";
                        DataReviewOutput.Add(TraineeScore);
                    }
                    else if (ScoreType == null)
                    {
                        TraineeScore.Stt = stt++;
                        TraineeScore.TypeError = "Không Có Loại Điểm Của Môn Học";
                        DataReviewOutput.Add(TraineeScore);
                    }
                    else
                    {
                        TraineeScore.Stt = stt++;
                        DataReviewOutput.Add(TraineeScore);
                        //Kiem tra diem da co trong DB chua
                        //neu co roi thi update neu chua thi tao moi
                        Guid TraineeTopicID = TraineeTopic.ID;
                        Tra_TraineeScore TraineeScore_Current = LstTraineeScoreAll.Where(m => m.TraineeTopicID == TraineeTopicID && m.ScoreTypeID == ScoreType.ID).FirstOrDefault();
                        if (TraineeScore_Current == null)
                        {
                            TraineeScore_Current = new Tra_TraineeScore();
                            TraineeScore_Current.ID = Guid.NewGuid();
                        }
                        TraineeScore_Current.TraineeTopicID = TraineeTopicID;
                        TraineeScore_Current.ScoreTypeID = ScoreType.ID;
                        TraineeScore_Current.Score = TraineeScore.Score;
                        result.Add(TraineeScore_Current);
                    }
                    entity = result.Translate<Tra_TraineeScoreEntity>();
                }
                return entity;
            }

            
        }
Example #36
0
        private string validateSaveLeaveDay(List<Att_Overtime> lstAttOvertimeInput, DateTime? date1, DateTime? date2)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
                var repoCat_OvertimeType = new CustomBaseRepository<Cat_OvertimeType>(unitOfWork);

                if (date1 == null && date2 == null)
                    return string.Empty;

                List<Guid> lstProfileIDs = lstAttOvertimeInput.Select(m => m.ProfileID).Distinct().ToList();
                var lstProfile = repoHre_Profile.FindBy(m => lstProfileIDs.Contains(m.ID)).Select(m => new { m.ID, m.CodeEmp, m.ProfileName });
                var lstOvertimeType = repoCat_OvertimeType.GetAll().Select(m => new { m.ID, m.TimeOffInLieuRate });
                string Error = string.Empty;

                foreach (var item in lstAttOvertimeInput)
                {
                    double RateTimeOff = lstOvertimeType.Where(m => m.ID == item.OvertimeTypeID).Select(m => m.TimeOffInLieuRate ?? 0).FirstOrDefault();
                    if (((date1 != null && date2 == null) || (date1 == null && date2 != null)))
                    {
                        double hourByDay = HourInShiftByDate(item.ProfileID, date1.Value);

                        if ((item.RegisterHours * RateTimeOff) < hourByDay)
                        {
                            var profile = lstProfile.Where(m => m.ID == item.ProfileID).FirstOrDefault();
                            if (profile != null)
                            {
                                Error += profile.ProfileName + "[" + profile.CodeEmp + "]; ";
                            }
                        }
                    }
                    else if (date1 != null && date2 != null)
                    {

                        double hourByDay1 = HourInShiftByDate(item.ProfileID, date1.Value);
                        double hourByDay2 = HourInShiftByDate(item.ProfileID, date2.Value);
                        if ((item.RegisterHours * RateTimeOff) < (hourByDay1 + hourByDay2))
                        {
                            var profile = lstProfile.Where(m => m.ID == item.ProfileID).FirstOrDefault();
                            if (profile != null)
                            {
                                Error += profile.ProfileName + "[" + profile.CodeEmp + "]; ";
                            }
                        }
                    }
                }
                if (Error != string.Empty)
                {
                    Error = Error.Substring(0, Error.Length - 2);
                    //Error = string.Format(Messages.EmpNotEnoughTimeToTimeOff.TranslateString(), Error);
                    return Error;
                }

                #region validateDuplicate
                string E_REJECTED = LeaveDayStatus.E_REJECTED.ToString();
                var lstLeaveDay1Query = repoAtt_LeaveDay.FindBy(m => m.Status != E_REJECTED && lstProfileIDs.Contains(m.ProfileID));
                var lstLeaveDay2Query = repoAtt_LeaveDay.FindBy(m => m.Status != E_REJECTED && lstProfileIDs.Contains(m.ProfileID));
                bool Isleaveday1 = false;
                bool Isleaveday2 = false;
                if (date1 != null)
                {
                    Isleaveday1 = true;
                    lstLeaveDay1Query = lstLeaveDay1Query.Where(m => m.DateStart <= date1.Value && m.DateEnd >= date1.Value);
                }
                if (date2 != null)
                {
                    Isleaveday2 = true;
                    lstLeaveDay2Query = lstLeaveDay2Query.Where(m => m.DateStart <= date2.Value && m.DateEnd >= date2.Value);
                }


                var lstLeaveday1 = new List<Att_LeaveDay>().Select(m => new { m.ProfileID, m.DateStart, m.DateEnd });
                var lstLeaveday2 = new List<Att_LeaveDay>().Select(m => new { m.ProfileID, m.DateStart, m.DateEnd });
                if (Isleaveday1)
                {
                    lstLeaveday1 = lstLeaveDay1Query.Select(m => new { m.ProfileID, m.DateStart, m.DateEnd });
                }
                if (Isleaveday2)
                {
                    lstLeaveday2 = lstLeaveDay2Query.Select(m => new { m.ProfileID, m.DateStart, m.DateEnd });
                }
                foreach (var item in lstAttOvertimeInput)
                {

                    if (date1 != null && lstLeaveday1.Any(m => m.ProfileID == item.ProfileID))
                    {
                        var profile = lstProfile.Where(m => m.ID == item.ProfileID).FirstOrDefault();
                        if (profile != null)
                        {
                            Error += profile.ProfileName + "[" + profile.CodeEmp + "]; ";
                        }
                    }
                    if (date2 != null && lstLeaveday2.Any(m => m.ProfileID == item.ProfileID))
                    {
                        var profile = lstProfile.Where(m => m.ID == item.ProfileID).FirstOrDefault();
                        if (profile != null)
                        {
                            Error += profile.ProfileName + "[" + profile.CodeEmp + "]; ";
                        }
                    }

                }
                if (Error != string.Empty)
                {
                    Error = Error.Substring(0, Error.Length - 2);
                    //Error = string.Format(Messages.EmpLeaveDuplicate.TranslateString(), Error);
                    return Error;
                }

                #endregion

                return Error;
            }
        }
Example #37
0
        public string ValidateLeaveDayTimeOff(List<Guid> lstProfileId, List<Att_LeaveDay> listleaveDayInsert)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_TimeOffInLieu = new Att_TimeOffInLieuRepository(unitOfWork);
                var repoAtt_Roster = new Att_RosterRepository(unitOfWork);
                var repoAtt_RosterGroup = new Att_RosterGroupRepository(unitOfWork);
                var repoHre_WorkHistory = new Hre_WorkHistoryRepository(unitOfWork);
                var repoCat_DayOff = new Cat_DayOffRepository(unitOfWork);
                var repoAtt_TimeOffInLieuMonth = new CustomBaseRepository<Att_TimeOffInLieuMonth>(unitOfWork);
                var repoCat_GradeAttendance = new CustomBaseRepository<Cat_GradeAttendance>(unitOfWork);
                var repoAtt_Grade = new CustomBaseRepository<Att_Grade>(unitOfWork);
                var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoCat_Shift = new Cat_ShiftRepository(unitOfWork);
                var shifts = repoCat_Shift.FindBy(s => s.IsDelete == null).ToList();
                string ErrorResult = string.Empty;
                Guid GuidContext = Guid.NewGuid();
                DateTime dateMin = listleaveDayInsert.Min(m => m.DateStart);
                DateTime Datemax = listleaveDayInsert.Min(m => m.DateEnd);
                DateTime BeginMonthOfMin = new DateTime(dateMin.Year, dateMin.Month, 1);
                DateTime EndMonthOfMax = new DateTime(Datemax.Year, Datemax.Month, 1);
                EndMonthOfMax = EndMonthOfMax.AddMonths(1).AddMinutes(-1);
                DateTime Month4Ago = BeginMonthOfMin.AddMonths(-4);
                List<Att_TimeOffInLieu> lstTimeOffInLieu = repoAtt_TimeOffInLieu.FindBy(m => m.Date >= Month4Ago && m.Date < EndMonthOfMax && lstProfileId.Contains(m.ProfileID)).ToList<Att_TimeOffInLieu>();
                List<Att_TimeOffInLieuMonth> lstTimeOffInLieu_Month = repoAtt_TimeOffInLieuMonth.FindBy(m => m.Month >= Month4Ago && m.Month < EndMonthOfMax && lstProfileId.Contains(m.ProfileID)).ToList<Att_TimeOffInLieuMonth>();

                List<Cat_GradeAttendance> lstGradeCfg = repoCat_GradeAttendance.GetAll().ToList<Cat_GradeAttendance>();
                var lstGrade = repoAtt_Grade.FindBy(m => lstProfileId.Contains((Guid)m.ProfileID) && m.MonthStart <= dateMin).Select(m => new { m.ProfileID, m.MonthStart, m.GradeAttendanceID }).OrderByDescending(m => m.MonthStart);
                string E_APPROVED_Roster = RosterStatus.E_APPROVED.ToString();
                List<Att_Roster> lstRoster = repoAtt_Roster.FindBy(m => m.Status == E_APPROVED_Roster && m.DateEnd >= dateMin && m.DateStart <= Datemax && lstProfileId.Contains(m.ProfileID)).ToList<Att_Roster>();
                List<Att_RosterGroup> lstRosterGroup = repoAtt_RosterGroup.FindBy(m => m.DateEnd >= dateMin && m.DateStart <= Datemax).ToList<Att_RosterGroup>();
                string E_ROSTERGROUP = RosterType.E_ROSTERGROUP.ToString();
                List<Att_Roster> lstRosterTypeGroup = lstRoster.Where(m => m.Type == E_ROSTERGROUP).ToList();
                List<Hre_WorkHistory> lstWorkHistory = repoHre_WorkHistory.FindBy(m => lstProfileId.Contains(m.ProfileID)).ToList<Hre_WorkHistory>();
                List<DateTime> lstDayOff = repoCat_DayOff.GetAll().Select(m => m.DateOff).ToList<DateTime>();


                //Tạo ra một list giả dữ liệu
                List<LeaveDayValidate> lstLeaveDayValidate = new List<LeaveDayValidate>();
                List<LeaveDayValidate> lstLeaveDayValidate1 = new List<LeaveDayValidate>();
                foreach (var item in listleaveDayInsert)
                {
                    LeaveDayValidate LeaveDayValid = new LeaveDayValidate();
                    LeaveDayValid.ProfileID = item.ProfileID;
                    LeaveDayValid.DateStart = item.DateStart;
                    LeaveDayValid.DateEnd = item.DateEnd;
                    LeaveDayValid.Duration = item.LeaveHours.Value;
                    LeaveDayValid.TotalDuration = item.LeaveDays ?? 1;
                    lstLeaveDayValidate1.Add(LeaveDayValid);
                }

                foreach (var item in lstLeaveDayValidate1)
                {
                    if (item.DateEnd.Date > item.DateStart.Date)
                    {
                        Dictionary<DateTime, DateTime> dicTime = new Dictionary<DateTime, DateTime>();
                        DateTime DateMinBeginMonth = new DateTime(item.DateStart.Year, item.DateStart.Month, 1);
                        DateTime DateMaxBeginMonth = new DateTime(item.DateEnd.Year, item.DateEnd.Month, 1);
                        if (DateMinBeginMonth < DateMaxBeginMonth)
                        {
                            Guid GradeID = Guid.Empty;
                            var gradeByProfile = lstGrade.Where(m => m.ProfileID == item.ProfileID).FirstOrDefault();
                            if (gradeByProfile != null)
                            {
                                GradeID = (Guid)gradeByProfile.GradeAttendanceID;
                            }
                            Cat_GradeAttendance gradeCfg = lstGradeCfg.Where(m => m.ID == GradeID).FirstOrDefault();
                            if (gradeCfg == null)
                                continue;
                            List<Att_Roster> listRosterByProfile = lstRoster.Where(m => m.ProfileID == item.ProfileID).ToList();
                            List<Hre_WorkHistory> listWorkHistoryByProfile = lstWorkHistory.Where(m => m.ProfileID == item.ProfileID).ToList();
                            List<Att_Roster> lstRosterTypeGroupByProfile = lstRosterTypeGroup.Where(m => m.ProfileID == item.ProfileID).ToList();

                            var listRosterEntity = listRosterByProfile.Select(d => new Att_RosterEntity
                            {
                                ID = d.ID,
                                ProfileID = d.ProfileID,
                                RosterGroupName = d.RosterGroupName,
                                Type = d.Type,
                                Status = d.Status,
                                DateEnd = d.DateEnd,
                                DateStart = d.DateStart,
                                MonShiftID = d.MonShiftID,
                                TueShiftID = d.TueShiftID,
                                WedShiftID = d.WedShiftID,
                                ThuShiftID = d.ThuShiftID,
                                FriShiftID = d.FriShiftID,
                                SatShiftID = d.SatShiftID,
                                SunShiftID = d.SunShiftID,
                                MonShift2ID = d.MonShiftID,
                                TueShift2ID = d.TueShift2ID,
                                WedShift2ID = d.WedShift2ID,
                                ThuShift2ID = d.ThuShift2ID,
                                FriShift2ID = d.FriShift2ID,
                                SatShift2ID = d.SatShift2ID,
                                SunShift2ID = d.SunShift2ID
                            }).ToList();

                            var listRosterGroupEntity = lstRosterGroup.Select(d => new Att_RosterGroupEntity
                            {
                                ID = d.ID,
                                DateEnd = d.DateEnd,
                                DateStart = d.DateStart,
                                MonShiftID = d.MonShiftID,
                                TueShiftID = d.TueShiftID,
                                WedShiftID = d.WedShiftID,
                                ThuShiftID = d.ThuShiftID,
                                FriShiftID = d.FriShiftID,
                                SatShiftID = d.SatShiftID,
                                SunShiftID = d.SunShiftID,
                                RosterGroupName = d.RosterGroupName
                            }).ToList();

                            Dictionary<DateTime, Cat_Shift> dailyShifts = Att_AttendanceLib.GetDailyShifts(item.ProfileID,
                                item.DateStart, item.DateEnd, listRosterEntity, listRosterGroupEntity, shifts);

                            for (DateTime DateCheck = DateMinBeginMonth; DateCheck <= DateMaxBeginMonth; DateCheck = DateCheck.AddMonths(1))
                            {
                                DateTime beginMonth = DateCheck;
                                DateTime endMonth = beginMonth.AddMonths(1).AddMinutes(-1);
                                if (DateCheck == DateMinBeginMonth)
                                {
                                    dicTime.Add(item.DateStart, endMonth);
                                }
                                else if (DateCheck == DateMaxBeginMonth)
                                {
                                    dicTime.Add(beginMonth, item.DateEnd);
                                }
                                else
                                {
                                    dicTime.Add(beginMonth, endMonth);
                                }
                            }
                            foreach (var dicTimeKey in dicTime.Keys)
                            {
                                DateTime DateS = dicTimeKey;
                                DateTime DateE = dicTime[dicTimeKey];

                                double TotalDuration = 0;
                                for (DateTime dateC = DateS; dateC <= DateE; dateC = dateC.AddDays(1))
                                {
                                    if (!lstDayOff.Contains(dateC) && dailyShifts.ContainsKey(dateC))
                                    {
                                        if (dailyShifts[dateC] != null)
                                        {
                                            TotalDuration++;
                                        }
                                    }
                                }
                                LeaveDayValidate LeaveDayValid = new LeaveDayValidate();
                                LeaveDayValid.ProfileID = item.ProfileID;
                                LeaveDayValid.DateStart = DateS;
                                LeaveDayValid.DateEnd = DateE;
                                LeaveDayValid.Duration = item.Duration;
                                LeaveDayValid.TotalDuration = TotalDuration;
                                lstLeaveDayValidate1.Add(LeaveDayValid);
                            }
                        }
                        else
                        {
                            lstLeaveDayValidate.Add(item);
                        }
                    }
                    else
                    {
                        lstLeaveDayValidate.Add(item);
                    }
                }

                List<Guid> LstProfileIDs_Error_MissImport = new List<Guid>();
                List<Guid> LstProfileIDs_Error_NotValid = new List<Guid>();

                foreach (var item in lstLeaveDayValidate)
                {
                    DateTime monthYear = new DateTime(item.DateStart.Year, item.DateStart.Month, 1);
                    List<Att_TimeOffInLieu> lstTimeOffInlieu_ByProfile = lstTimeOffInLieu.Where(m => m.ProfileID == item.ProfileID).ToList();
                    List<Att_TimeOffInLieuMonth> lstTimeOffInlieuMonth_ByProfile = lstTimeOffInLieu_Month.Where(m => m.ProfileID == item.ProfileID).ToList();
                    double? NumAvailable = CalculateTotalHourTimeOff(item.ProfileID, lstTimeOffInlieu_ByProfile, lstTimeOffInlieuMonth_ByProfile, monthYear, 1);

                    if (NumAvailable == null)
                    {
                        LstProfileIDs_Error_MissImport.Add(item.ProfileID);
                    }
                    else if ((item.Duration * item.TotalDuration) > NumAvailable.Value)
                    {
                        LstProfileIDs_Error_NotValid.Add(item.ProfileID);
                    }
                }
                if (LstProfileIDs_Error_MissImport.Count > 0)
                {
                    var profile = repoHre_Profile.FindBy(m => LstProfileIDs_Error_MissImport.Contains(m.ID)).Select(m => new { m.CodeEmp, m.ProfileName });

                    foreach (var item in profile)
                    {
                        ErrorResult += item.ProfileName + "[" + item.CodeEmp + "]; ";
                    }
                    if (ErrorResult.Length > 0)
                    {
                        ErrorResult = ErrorResult.Substring(0, ErrorResult.Length - 2);
                    }
                    ErrorResult = ConstantMessages.EmpDoNotConfigTimeOffBegin.TranslateString();
                    //ErrorResult = "EmpDoNotConfigTimeOffBegin";

                }
                else if (LstProfileIDs_Error_NotValid.Count > 0)
                {
                    var profile = repoHre_Profile.FindBy(m => LstProfileIDs_Error_NotValid.Contains(m.ID)).Select(m => new { m.CodeEmp, m.ProfileName });

                    foreach (var item in profile)
                    {
                        ErrorResult += item.ProfileName + "[" + item.CodeEmp + "]; ";
                    }
                    if (ErrorResult.Length > 0)
                    {
                        ErrorResult = ErrorResult.Substring(0, ErrorResult.Length - 2);
                    }
                    ErrorResult = ConstantMessages.DataNotEnoughToMakeLeave.TranslateString();
                    //ErrorResult = "EmpDoNotEnoughTimeOff";
                }
                return ErrorResult;
            }
        }