Esempio n. 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();
                        }
                    }
                }
            }
        }
Esempio n. 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();
                    }
                
                }
               

            }
        }
Esempio n. 3
0
        /// <summary>
        /// [Hieu.Van] - Tạo mới một đối tượng return model
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public TEntity Add <TEntity>(TEntity entity, ref string status) where TEntity : class
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repo       = new CustomBaseRepository <TEntity>(unitOfWork);
                try
                {
                    entity.SetPropertyValue(Constant.DateCreate, DateTime.Now);
                    repo.Add(entity);
                    var saveStatus = repo.SaveChanges();

                    if (saveStatus == DataErrorCode.Locked)
                    {
                        status = NotificationType.Locked.ToString();
                    }
                    else
                    {
                        status = NotificationType.Success.ToString();
                    }

                    return(entity);
                }
                catch (Exception ex)
                {
                    status = NotificationType.Error + "," + ex.Message;
                    return(null);
                }
            }
        }
Esempio n. 4
0
 public string SaveList(List<Att_RosterEntity> lstModel)
 {
     using (var context = new VnrHrmDataContext())
     {
         List<Att_Roster> lstSave = new List<Att_Roster>();
         lstSave = lstModel.Translate<Att_Roster>();
         var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
         var repo = new CustomBaseRepository<Att_Roster>(unitOfWork);
         //int count = 0;
         foreach (var item in lstSave)
         {
             //count += 1;
             item.ID = Guid.NewGuid();
             repo.Add(item);
         }
         try
         {
             repo.SaveChanges();
             return "Success";
         }
         catch (Exception)
         {
             return "Error";
         }
     }
 }
Esempio n. 5
0
        /// <summary>
        /// [Hieu.Van]
        /// Xử lý Gửi yêu cầu phê duyệt
        /// </summary>
        /// <param name="LoginID"></param>
        /// <param name="userApprovedID"></param>
        /// <param name="recordID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string ProcessSendRequest(string host, Guid LoginID, Guid userApprovedID, Guid recordID, string type)
        {
            DataErrorCode status = DataErrorCode.Success;

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoFIN_PurchaseRequest = new CustomBaseRepository <FIN_PurchaseRequest>(unitOfWork);
                var repoSys_UserApprove     = new CustomBaseRepository <Sys_UserApprove>(unitOfWork);

                var record = repoFIN_PurchaseRequest.FindBy(s => s.ID == recordID).FirstOrDefault();
                if (record.UserCreateID != LoginID)
                {
                    return(DataErrorCode.NoPermission.ToString());
                }
                if (record.Status == EnumDropDown.Status.E_REJECTED.ToString())
                {
                    return(DataErrorCode.Error_Reject.ToString());
                }
                if (record.Status != null)
                {
                    return(DataErrorCode.Error_SendRequest.ToString());
                }
                var userApproved = repoSys_UserApprove.FindBy(s => s.ID == userApprovedID).FirstOrDefault();
                // Lấy status hiện tại của bản ghi
                string currentStatus = record.Status;

                // truyền từ Dropdownlist chọn người duyệt, lấy ra giá trị Status tiếp theo
                string nextStatus = userApproved.CurrentStatus;

                record.Status        = nextStatus;
                record.UserApproveID = userApprovedID;
                repoFIN_PurchaseRequest.Edit(record);
                status = repoFIN_PurchaseRequest.SaveChanges();


                if (status == DataErrorCode.Success)
                {
                    if (nextStatus != "Approved")
                    {
                        status = SendMail_ToNextApproved(host, recordID, userApprovedID, nextStatus, type);
                    }

                    var repoSys_ConfigProcessApprove = new CustomBaseRepository <Sys_ConfigProcessApprove>(unitOfWork);
                    var configProcess = repoSys_ConfigProcessApprove.FindBy(s => s.IsDelete == null && s.Function == type && s.CurrentStatus == record.Status).FirstOrDefault();
                    if (configProcess == null)
                    {
                        return(DataErrorCode.Success.ToString());
                    }
                    else
                    {
                        return(DataErrorCode.Success_Forward.ToString());
                    }
                }

                return(status.ToString());
            }
        }
Esempio n. 6
0
        public bool AddList(List <Att_AnnualLeaveDetailEntity> models)
        {
            bool isSuccess = false;
            var  leaveType = string.Empty;
            var  status    = string.Empty;
            var  year      = 2013;

            if (models != null && models.FirstOrDefault() != null && models.FirstOrDefault().Year != null)
            {
                year      = Convert.ToInt32(models.FirstOrDefault().Year);
                leaveType = models.FirstOrDefault().Type;
            }

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repo       = new CustomBaseRepository <Att_AnnualLeaveDetail>(unitOfWork);
                try
                {
                    var annualLeaveDetails = GetAllUseEntity <Att_AnnualLeaveDetail>(ref status).Where(p => p.Type == leaveType && p.Year == year).ToList().AsQueryable();
                    foreach (var attAnnualLeaveDetail in models)
                    {
                        var addSuccess        = false;
                        var existAnnualDetail = annualLeaveDetails.Where(p => p.ProfileID == attAnnualLeaveDetail.ProfileID).FirstOrDefault();
                        if (existAnnualDetail != null)
                        {
                            existAnnualDetail.Month1  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month2  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month3  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month4  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month5  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month6  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month7  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month8  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month9  = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month10 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month11 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month12 = attAnnualLeaveDetail.Month1;

                            repo.Edit(existAnnualDetail);
                        }
                        else
                        {
                            Att_AnnualLeaveDetail temp = new Att_AnnualLeaveDetail();
                            temp = attAnnualLeaveDetail.CopyData <Att_AnnualLeaveDetail>();
                            repo.Add(temp);
                        }
                    }
                    repo.SaveChanges();
                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
Esempio n. 7
0
        public void AddDataForBasicSalary(string ProfileIDs, string BasicSalary, DateTime DateHire, Guid SalaryRankID, string UserLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var                    unitOfWork      = (IUnitOfWork)(new UnitOfWork(context));
                string                 status          = string.Empty;
                var                    repoBasicSalary = new CustomBaseRepository <Sal_BasicSalary>(unitOfWork);
                List <Guid>            lstProfileIDs   = ProfileIDs.Split(',').Select(x => Guid.Parse(x)).ToList();
                List <Sal_BasicSalary> lstBasicSalary  = new List <Sal_BasicSalary>();
                //chua co cach giai quyet nen hard code lay mac dinh la VND
                var repoCurrency = new CustomBaseRepository <Cat_Currency>(unitOfWork);
                var currency     = repoCurrency.FindBy(s => s.IsDelete == null && s.CurrencyName == "VND").FirstOrDefault();
                //var repoSalaryRank = new CustomBaseRepository<Cat_SalaryRank>(unitOfWork);
                //var repoSalaryClass = new CustomBaseRepository<Cat_SalaryClass>(unitOfWork);
                //var salaryRank = repoSalaryRank.FindBy(s => s.IsDelete == null && s.ID == SalaryRankID).FirstOrDefault();
                //var salaryClass = repoSalaryClass.FindBy(s => s.IsDelete == null && s.ID == salaryRank.SalaryClassID).FirstOrDefault();
                var salaryRankServices = new Cat_SalaryRankServices();
                var lstObjRank         = new List <object>();
                lstObjRank.Add(null);
                lstObjRank.Add(null);
                lstObjRank.Add(1);
                lstObjRank.Add(int.MaxValue - 1);
                var lstRank    = salaryRankServices.GetData <Cat_SalaryRankEntity>(lstObjRank, ConstantSql.hrm_cat_sp_get_SalaryRank, UserLogin, ref status).ToList().Translate <Cat_SalaryRank>();
                var rankEntity = lstRank.Where(s => s.ID == SalaryRankID).FirstOrDefault();

                var salaryClassServices = new Cat_SalaryClassServices();
                var lstObjClass         = new List <object>();
                lstObjClass.Add(null);
                lstObjClass.Add(1);
                lstObjClass.Add(int.MaxValue - 1);
                var salaryClass = salaryClassServices.GetData <Cat_SalaryClassEntity>(lstObjClass, ConstantSql.hrm_cat_sp_get_SalaryClass, UserLogin, ref status).ToList().Translate <Cat_SalaryClass>();

                var salaryClassEntity = salaryClass.Where(s => rankEntity.SalaryClassID == s.ID).FirstOrDefault();

                foreach (var item in lstProfileIDs)
                {
                    Sal_BasicSalary objBasicSalary = new Sal_BasicSalary();
                    objBasicSalary.ProfileID    = item;
                    objBasicSalary.GrossAmount  = BasicSalary;
                    objBasicSalary.Amount       = BasicSalary.Encrypt();
                    objBasicSalary.DateOfEffect = DateHire;
                    objBasicSalary.RankRateID   = SalaryRankID;
                    objBasicSalary.CurrencyID   = currency.ID;
                    objBasicSalary.ClassRateID  = salaryClassEntity == null ? Guid.Empty : salaryClassEntity.ID;
                    lstBasicSalary.Add(objBasicSalary);
                }

                repoBasicSalary.Add(lstBasicSalary);
                repoBasicSalary.SaveChanges();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// [Chuc.Nguyen] - Chỉnh sửa một danh sách đối tượng
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="listEntity"></param>
        /// <returns></returns>
        public string Edit <TEntity>(List <TEntity> listEntity) where TEntity : class
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repo       = new CustomBaseRepository <TEntity>(unitOfWork);
                try
                {
                    repo.Edit(listEntity);
                    var status = repo.SaveChanges();

                    if (status == DataErrorCode.Locked)
                    {
                        return(NotificationType.Locked.ToString());
                    }
                    else
                    {
                        return(NotificationType.Success.ToString());
                    }
                }
                catch (DbEntityValidationException ex)
                {
                    // Retrieve the error messages as a list of strings.
                    var errorMessages = ex.EntityValidationErrors
                                        .SelectMany(x => x.ValidationErrors)
                                        .Select(x => x.ErrorMessage);

                    // Join the list to a single string.
                    var fullErrorMessage = string.Join("; ", errorMessages);

                    // Combine the original exception message with the new one.
                    var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                    // Throw a new DbEntityValidationException with the improved exception message.
                    return(NotificationType.Error + "," + exceptionMessage);
                }
                catch (Exception ex)
                {
                    return(NotificationType.Error + "," + ex.Message);
                }
            }
        }
Esempio n. 9
0
 public void AddDataForGrade(string ProfileIDs, Guid GradePayrollID, DateTime DateHire)
 {
     using (var context = new VnrHrmDataContext())
     {
         var              unitOfWork    = (IUnitOfWork)(new UnitOfWork(context));
         var              repoGrade     = new CustomBaseRepository <Sal_Grade>(unitOfWork);
         List <Guid>      lstProfileIDs = ProfileIDs.Split(',').Select(x => Guid.Parse(x)).ToList();
         List <Sal_Grade> lstGrade      = new List <Sal_Grade>();
         foreach (var item in lstProfileIDs)
         {
             Sal_Grade Grade = new Sal_Grade();
             Grade.ProfileID      = item;
             Grade.GradePayrollID = GradePayrollID;
             Grade.MonthStart     = DateHire;
             lstGrade.Add(Grade);
         }
         repoGrade.Add(lstGrade);
         repoGrade.SaveChanges();
     }
 }
Esempio n. 10
0
 public void AddDataForGrade(string ProfileIDs, Guid GradePayrollID, DateTime DateHire)
 {
     using (var context = new VnrHrmDataContext())
     {
         var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
         var repoGrade = new CustomBaseRepository<Sal_Grade>(unitOfWork);
         List<Guid> lstProfileIDs = ProfileIDs.Split(',').Select(x => Guid.Parse(x)).ToList();
         List<Sal_Grade> lstGrade = new List<Sal_Grade>();
         foreach (var item in lstProfileIDs)
         {
             Sal_Grade Grade = new Sal_Grade();
             Grade.ProfileID = item;
             Grade.GradePayrollID = GradePayrollID;
             Grade.MonthStart = DateHire;
             lstGrade.Add(Grade);
         }
         repoGrade.Add(lstGrade);
         repoGrade.SaveChanges();
     }
 }
Esempio n. 11
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();
                        }
                    }
                }
            }
        }
Esempio n. 12
0
        /// <summary>
        /// [Hieu.Van]
        /// Xử lý Từ Chối
        /// </summary>
        /// <param name="LoginID"></param>
        /// <param name="userApprovedID"></param>
        /// <param name="recordID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string ProcessReject(string host, Guid LoginID, Guid recordID, string type)
        {
            DataErrorCode status = DataErrorCode.Success;

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoFIN_PurchaseRequest = new CustomBaseRepository <FIN_PurchaseRequest>(unitOfWork);
                var repoSys_UserApprove     = new CustomBaseRepository <Sys_UserApprove>(unitOfWork);
                var repoSys_UserInfo        = new CustomBaseRepository <Sys_UserInfo>(unitOfWork);

                var record = repoFIN_PurchaseRequest.FindBy(s => s.ID == recordID).FirstOrDefault();
                if (record.Status == EnumDropDown.Status.E_REJECTED.ToString())
                {
                    return(DataErrorCode.Error_Reject.ToString());
                }
                var userApproved = repoSys_UserApprove.FindBy(s => s.ID == record.UserApproveID).FirstOrDefault();
                // Kiểm tra tài khoản login có được phép Duyệt hay ko?
                if (LoginID == Guid.Empty || userApproved.UserApproveID != LoginID)
                {
                    // kiểm tra nếu bản ghi có tk duyệt trống (tức bản ghi mới tạo) và tk login = tk tạo thì cho duyệt tiếp tục
                    if (record.UserApproveID == null && record.UserCreateID == LoginID)
                    {
                    }
                    else
                    {
                        return(DataErrorCode.NoPermission.ToString());
                    }
                }

                record.Status = EnumDropDown.Status.E_REJECTED.ToString();
                repoFIN_PurchaseRequest.Edit(record);
                status = repoFIN_PurchaseRequest.SaveChanges();

                return(status.ToString());
            }
        }
Esempio n. 13
0
        public string Set_RejectRoster_ByModuleApprove(string host, List<Guid> lstRoster, Guid UserLoginID, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                string status = string.Empty;
                string statusSendMail = DataErrorCode.Error.ToString();
                BaseService service = new BaseService();
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_Roster = new CustomBaseRepository<Att_Roster>(unitOfWork);

                #region getdata

                List<object> lstParamUser = new List<object>();
                lstParamUser.AddRange(new object[4]);
                lstParamUser[3] = Int32.MaxValue;
                var lstUserAll = service.GetData<Sys_UserInfo>(lstParamUser, ConstantSql.hrm_sys_sp_get_users, userLogin, ref status);
                var lstUser = lstUserAll.Where(m => !string.IsNullOrEmpty(m.Email)).Select(m => new { m.ID, m.Email }).ToList();
                #endregion

                #region process

                string E_REJECTED = RosterStatus.E_REJECTED.ToString();
                List<Att_Roster> lstRosterSendMail = new List<Att_Roster>();
                foreach (var rosID in lstRoster)
                {
                    var Roster = repoAtt_Roster.GetById(rosID);
                    lstRosterSendMail.Add(Roster);
                    Roster.Status = E_REJECTED;
                }
                var stt = repoAtt_Roster.SaveChanges();

                #endregion

                if (stt == DataErrorCode.Success)
                {
                    #region getdata

                    List<Hre_ProfileEntity> lstProfile = new List<Hre_ProfileEntity>();
                    List<Sys_TemplateSendMail> template = new List<Sys_TemplateSendMail>();
                    Sys_TemplateSendMail tempApprove = new Sys_TemplateSendMail();
                    Sys_TemplateSendMail tempReturn = new Sys_TemplateSendMail();
                    string[] strsParaKey = null;
                    string bodyContent = null;
                    string titleMail = null;
                    string[] strsParaValues = null;
                    string[] strsParaValues_Return = null;

                    string _typeTemplate = EnumDropDown.EmailType.E_APPROVED_ROSTER.ToString();
                    string _typeTemplate_return = EnumDropDown.EmailType.E_APPROVED_ROSTER_RETURN.ToString();
                    var repoSys_TemplateSendMail = new CustomBaseRepository<Sys_TemplateSendMail>(unitOfWork);
                    template = repoSys_TemplateSendMail.FindBy(s => s.Type == _typeTemplate || s.Type == _typeTemplate_return).ToList();
                    if (template.Count < 2)
                        return DataErrorCode.Error_NoTemplateMail.ToString();
                    tempApprove = template.Where(s => s.Type == _typeTemplate).FirstOrDefault();
                    tempReturn = template.Where(s => s.Type == _typeTemplate_return).FirstOrDefault();

                    string proIDS = string.Join(",", lstRosterSendMail.Select(s => s.ProfileID.ToString()).Distinct().ToList());
                    proIDS = Common.DotNetToOracle(proIDS);
                    lstProfile = GetData<Hre_ProfileEntity>(proIDS, ConstantSql.hrm_hr_sp_get_ProfileByIds, userLogin, ref status);

                    strsParaKey = new string[] 
                    { 

                        EnumDropDown.EmailType_APPROVED_ROSTER.E_UserName.ToString(), 
                        EnumDropDown.EmailType_APPROVED_ROSTER.E_ProfileName.ToString(), 
                        EnumDropDown.EmailType_APPROVED_ROSTER.E_CodeEmp.ToString(), 
                        EnumDropDown.EmailType_APPROVED_ROSTER.E_DateStart.ToString(), 
                        EnumDropDown.EmailType_APPROVED_ROSTER.E_DateEnd.ToString(), 
                        EnumDropDown.EmailType_APPROVED_ROSTER.E_Status.ToString(), 
                        EnumDropDown.EmailType_APPROVED_ROSTER.E_Type.ToString(), 
                        EnumDropDown.EmailType_APPROVED_ROSTER.E_LinkContent.ToString(), 
                    };

                    #endregion

                    foreach (var Roster in lstRosterSendMail)
                    {
                        List<Guid> lstDelegateApproveUserID = new List<Guid>();
                        var UserRegister = lstUserAll.Where(m => m.ProfileID == Roster.ProfileID).FirstOrDefault();
                        if (UserRegister != null)
                        {
                            lstDelegateApproveUserID.Add(UserRegister.ID);
                        }
                        lstDelegateApproveUserID = lstDelegateApproveUserID.Distinct().ToList();



                        var lstUserInfoCanView = lstUser.Where(m => lstDelegateApproveUserID.Contains(m.ID)).ToList();
                        List<Att_EmailRequireEntity> lstEmailRequire = new List<Att_EmailRequireEntity>();
                        foreach (var UserInfoCanView in lstUserInfoCanView)
                        {
                            if (UserInfoCanView.Email == null)
                                continue;
                            Att_EmailRequireEntity EmailRequireEntity = new Att_EmailRequireEntity();
                            EmailRequireEntity.IdObject = Roster.ID;
                            EmailRequireEntity.EmailUserApprove = UserInfoCanView.Email;
                            EmailRequireEntity.IdUserApprove = UserInfoCanView.ID;
                            if (UserRegister != null && UserInfoCanView.ID == UserRegister.ID)
                            {
                                EmailRequireEntity.IsRegister = true;
                            }
                            lstEmailRequire.Add(EmailRequireEntity);
                        }

                        if (lstEmailRequire.Count > 0)
                        {
                            Guid ID = Roster.ID;
                            var lstEmailToSend_ByOT = lstEmailRequire.Where(m => m.IdObject == ID).ToList();
                            var profile = lstProfile.Where(s => s.ID == Roster.ProfileID).FirstOrDefault();
                            var userApproved1 = lstUserAll.Where(s => s.ID == Roster.UserApproveID).FirstOrDefault();
                            var userApproved2 = lstUserAll.Where(s => s.ID == Roster.UserApproveID2).FirstOrDefault();
                            foreach (var mail in lstEmailRequire)
                            {
                                bodyContent = string.Empty;

                                if (mail.IsRegister == true)
                                {
                                    #region Send Cho nguoi đăng ký
                                    titleMail = tempReturn.Subject;
                                    strsParaValues_Return = new string[]{
                                            profile.ProfileName,
                                            profile.ProfileName,
                                            profile.CodeEmp,
                                            Roster.DateStart.ToString("dd/MM/yyyy"),
                                            Roster.DateEnd.ToString("dd/MM/yyyy"),
                                            Roster.Status,
                                            Roster.Type,
                                            string.Empty,
                                        };
                                    bodyContent = LibraryService.ReplaceContentFile(tempReturn.Content, strsParaKey, strsParaValues_Return);
                                    #endregion
                                }
                                else
                                {
                                    #region Send cho ngươi duyệt
                                    string UserNameNext = lstUserAll.Where(m => m.ID == mail.IdUserApprove).Select(m => m.UserInfoName).FirstOrDefault();
                                    titleMail = tempApprove.Subject;
                                    string linkcontent = "<br/> <a href='" + host + "Att_ApprovedOvertime/ProcessApprovedPage?loginID=" + mail.IdUserApprove + "&recordID=" + Roster.ID + "'>Click this link to approve<a/><br /><br />";
                                    linkcontent += "<br/> <a href='" + host + "Att_ApprovedOvertime/ProcessRejectPage?loginID=" + mail.IdUserApprove + "&recordID=" + Roster.ID + "'>Click this link to Reject<a/><br /><br />";
                                    strsParaValues_Return = new string[]{
                                            UserNameNext,
                                            profile.ProfileName,
                                            profile.CodeEmp,
                                            Roster.DateStart.ToString("dd/MM/yyyy"),
                                            Roster.DateEnd.ToString("dd/MM/yyyy"),
                                            Roster.Status,
                                            Roster.Type,
                                            string.Empty,
                                        };
                                    bodyContent = LibraryService.ReplaceContentFile(tempApprove.Content, strsParaKey, strsParaValues);
                                    #endregion
                                }
                                var sta = service.SendMail(titleMail, mail.EmailUserApprove, bodyContent, null);
                                if (sta == true)
                                {
                                    statusSendMail = DataErrorCode.Success.ToString();
                                }
                            }
                        }
                    }
                }
                return statusSendMail;
            }
        }
        public string SaveOvertimePermitConfig(OvertimePermitEntity entity, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoSys_AllSetting = new CustomBaseRepository<Sys_AllSetting>(unitOfWork);
                Sys_AllSetting sys = new Sys_AllSetting();

                string HRM_ATT_OT_OTPERMIT_ = AppConfig.HRM_ATT_OT_OTPERMIT_.ToString();
                string status = string.Empty;
                List<object> lstO = new List<object>();
                lstO.Add(HRM_ATT_OT_OTPERMIT_);
                lstO.Add(null);
                lstO.Add(null);

                var config = GetData<Sys_AllSetting>(lstO, ConstantSql.hrm_sys_sp_get_AllSetting, userLogin, ref status);
                if (config != null)
                {
                    if (entity.limitHour_ByDay.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByDay.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByDay.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY.ToString();
                            objConfig.Value1 = entity.limitHour_ByDay.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByDay_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByDay_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByDay_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY_LEV1.ToString();
                            objConfig.Value1 = entity.limitHour_ByDay_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByDay_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByDay_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByDay_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY_LEV2.ToString();
                            objConfig.Value1 = entity.limitHour_ByDay_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByWeek.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByWeek.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByWeek.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK.ToString();
                            objConfig.Value1 = entity.limitHour_ByWeek.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByWeek_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByWeek_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByWeek_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK_LEV1.ToString();
                            objConfig.Value1 = entity.limitHour_ByWeek_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByWeek_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByWeek_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByWeek_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK_LEV2.ToString();
                            objConfig.Value1 = entity.limitHour_ByWeek_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByMonth.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByMonth.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByMonth.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH.ToString();
                            objConfig.Value1 = entity.limitHour_ByMonth.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByMonth_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByMonth_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByMonth_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH_LEV1.ToString();
                            objConfig.Value1 = entity.limitHour_ByMonth_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByMonth_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByMonth_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByMonth_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH_LEV2.ToString();
                            objConfig.Value1 = entity.limitHour_ByMonth_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByYear.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByYear.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByYear.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR.ToString();
                            objConfig.Value1 = entity.limitHour_ByYear.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByYear_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByYear_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByYear_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR_LEV1.ToString();
                            objConfig.Value1 = entity.limitHour_ByYear_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByYear_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByYear_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByYear_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR_LEV2.ToString();
                            objConfig.Value1 = entity.limitHour_ByYear_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (!string.IsNullOrEmpty(entity.limitColor))
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitColor)
                            {
                                objConfig.Value1 = entity.limitColor;
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR.ToString();
                            objConfig.Value1 = entity.limitColor;
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (!string.IsNullOrEmpty(entity.limitColor_Lev1))
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitColor_Lev1)
                            {
                                objConfig.Value1 = entity.limitColor_Lev1;
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR_LEV1.ToString();
                            objConfig.Value1 = entity.limitColor_Lev1;
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (!string.IsNullOrEmpty(entity.limitColor_Lev2))
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitColor_Lev2)
                            {
                                objConfig.Value1 = entity.limitColor_Lev2;
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR_LEV2.ToString();
                            objConfig.Value1 = entity.limitColor_Lev2;
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_Normal.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_Normal.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_Normal.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_Normal.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_Normal_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_Normal_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_Normal_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL_LEV1.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_Normal_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_Normal_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_Normal_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_Normal_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL_LEV2.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_Normal_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_AllowOver.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_AllowOver.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_AllowOver.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_AllowOver.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_AllowOver_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_AllowOver_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_AllowOver_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER_LEV1.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_AllowOver_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_AllowOver_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_AllowOver_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_AllowOver_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER_LEV2.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_AllowOver_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowSplit.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWSPLIT.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowSplit.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowSplit.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID = Guid.NewGuid();
                            objConfig.Name = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWSPLIT.ToString();
                            objConfig.Value1 = entity.IsAllowSplit.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                }
                

                repoSys_AllSetting.SaveChanges();
                return "0";
            }
        }
Esempio n. 15
0
        ///// <summary>
        ///// Lấy toàn bộ data
        ///// </summary>
        ///// <returns></returns>
        //public IQueryable<Att_AnnualLeave> Get()
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        return repo.Get().Where(i => i.IsDelete == null);
        //    }
        //}

        ///// <summary>
        ///// Lấy dữ liệu theo Id
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public Att_AnnualLeaveEntity Get(int id)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var data = repo.GetAnnualLeaveById(id);
        //        if (data.IsDelete == true) data = null;
        //        return data;
        //    }
        //}

        //public List<Att_AnnualLeaveEntity> GetAnnualLeaveByIds(string selectedIds)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        return repo.GetAnnualLeaveByIds(selectedIds);
        //    }
        //}

        ///// <summary>
        ///// Thêm mới một record
        ///// </summary>
        ///// <param name="cat"></param>
        ///// <returns></returns>
        //public bool Add(Att_AnnualLeave model)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        try
        //        {
        //            repo.Add(model);
        //            repo.SaveChanges();
        //            return true;
        //        }
        //        catch
        //        {
        //            return false;
        //        }
        //    }
        //}

        ///// <summary>
        ///// Edit một record
        ///// </summary>
        ///// <param name="cat"></param>
        ///// <returns></returns>
        //public bool Edit(Att_AnnualLeave model)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        try
        //        {
        //            repo.Edit(model);
        //            repo.SaveChanges();
        //            return true;
        //        }
        //        catch
        //        {
        //            return false;
        //        }

        //    }
        //}

        ///// <summary>
        ///// Remove 1 record là chuyển trạng thái IsDelete=true
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public bool Remove(int id)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var data = repo.GetById(id);
        //        try
        //        {
        //            repo.Remove(data);
        //            repo.SaveChanges();
        //            return true;
        //        }
        //        catch
        //        {
        //            return false;
        //        }

        //    }
        //}

        ///// <summary>
        ///// Delete 1 record là xóa luôn record khỏi database
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public bool Delete(int id)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var data = repo.GetById(id);
        //        try
        //        {
        //            repo.Delete(data);
        //            repo.SaveChanges();
        //            return true;
        //        }
        //        catch
        //        {
        //            return false;
        //        }

        //    }
        //}

        //#region Store Procedure

        //#region Danh sách

        ///// <summary>
        ///// Lấy danh sách dữ liệu AnnualLeaves [Tung.Ly - 2014/05/09]
        ///// </summary>
        ///// <returns></returns>
        //public IQueryable<Att_AnnualLeaveEntity> GetAnnualLeaves(ListQueryModel model)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        IAtt_AnnualLeaveRepository repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var rs = repo.GetAnnualLeaves(model);
        //        return rs;
        //    }
        //}

        //#endregion

        //#region Chi tiet

        ///// <summary>
        ///// Lấy dữ liệu AnnualLeave theo Id [Tung.Ly - 2014/05/09]
        ///// </summary>
        ///// <param name="annualLeaveId"></param>
        ///// <returns></returns>
        //public Att_AnnualLeaveEntity GetAnnualLeaveById(int annualLeaveId)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        IAtt_AnnualLeaveRepository repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var data = repo.GetAnnualLeaveById(annualLeaveId);
        //        return data;
        //    }
        //}

        //#endregion

        //#endregion
        #endregion

        #region thanh toán phép năm đầu kỳ

        public void SetAnnualLeaveBeginYear(List <Guid> lstProfileIDs, double?limitMaximum, int Year, int?MonthResetANL, Guid?AllowanceTypeID, Guid?CuttOffDurationID)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork               = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_AnnualLeave      = new CustomBaseRepository <Att_AnnualLeave>(unitOfWork);
                var repoAtt_AnnualDetail     = new CustomBaseRepository <Att_AnnualDetail>(unitOfWork);
                var repoSal_UnusualAllowance = new CustomBaseRepository <Sal_UnusualAllowance>(unitOfWork);
                var repoAtt_CutOffDuration   = new CustomBaseRepository <Att_CutOffDuration>(unitOfWork);
                //nếu có rồi thì chỉ cần Update
                //Nếu chưa có thì tạo mới
                Att_CutOffDuration CutOffDuration = new Att_CutOffDuration();
                if (CuttOffDurationID != null)
                {
                    CutOffDuration = repoAtt_CutOffDuration.FindBy(m => m.ID == CuttOffDurationID).FirstOrDefault();
                }


                int      LastYear = Year - 1;
                DateTime?MaxTime  = repoAtt_AnnualDetail.FindBy(m => m.IsDelete != null && m.Year == LastYear).OrderByDescending(m => m.MonthYear).Select(m => m.MonthYear).FirstOrDefault();
                List <Att_AnnualDetail> lstAnnualDetail = new List <Att_AnnualDetail>();
                if (MaxTime != null)
                {
                    lstAnnualDetail = repoAtt_AnnualDetail.FindBy(m => m.MonthYear == MaxTime &&
                                                                  m.ProfileID != null &&
                                                                  lstProfileIDs.Contains(m.ProfileID.Value)).ToList();
                }
                var lstAnnualLeaveInDB = repoAtt_AnnualLeave.FindBy(m => m.IsDelete == null && m.Year == Year && lstProfileIDs.Contains(m.ProfileID)).ToList();


                foreach (var ProfileID in lstProfileIDs)
                {
                    Att_AnnualLeave AnnualLeaveByProfile = lstAnnualLeaveInDB.Where(m => m.ProfileID == ProfileID).FirstOrDefault();
                    bool            IsNew = false;
                    if (AnnualLeaveByProfile == null)
                    {
                        IsNew = true;
                        AnnualLeaveByProfile            = new Att_AnnualLeave();
                        AnnualLeaveByProfile.ID         = Guid.NewGuid();
                        AnnualLeaveByProfile.ProfileID  = ProfileID;
                        AnnualLeaveByProfile.Year       = Year;
                        AnnualLeaveByProfile.MonthStart = 1;
                    }
                    AnnualLeaveByProfile.MonthResetAnlOfBeforeYear = MonthResetANL;
                    double RemainLastYear = lstAnnualDetail.Where(m => m.ProfileID == ProfileID).Select(m => m.Remain ?? 0).FirstOrDefault();
                    if (limitMaximum != null)
                    {
                        AnnualLeaveByProfile.InitAnlValue       = RemainLastYear > limitMaximum.Value ? limitMaximum.Value : RemainLastYear;
                        AnnualLeaveByProfile.SurplusAnllastYear = RemainLastYear > limitMaximum ? RemainLastYear - limitMaximum : 0;
                        if (CutOffDuration.ID != null && CutOffDuration.ID != Guid.Empty && AllowanceTypeID != null)
                        {
                            Sal_UnusualAllowance UnusualAllowance = new Sal_UnusualAllowance();
                            UnusualAllowance.ProfileID       = ProfileID;
                            UnusualAllowance.MonthStart      = CutOffDuration.DateStart;
                            UnusualAllowance.MonthEnd        = CutOffDuration.DateEnd;
                            UnusualAllowance.UnusualEDTypeID = AllowanceTypeID;
                            UnusualAllowance.Amount          = AnnualLeaveByProfile.SurplusAnllastYear;
                            repoSal_UnusualAllowance.Add(UnusualAllowance);
                        }
                    }
                    else
                    {
                        AnnualLeaveByProfile.InitAnlValue       = RemainLastYear;
                        AnnualLeaveByProfile.SurplusAnllastYear = 0;
                    }
                    //Sửa lại theo phần tử mới mà Sơn build
                    if (IsNew)
                    {
                        repoAtt_AnnualLeave.Add(AnnualLeaveByProfile);
                    }
                    else
                    {
                        repoAtt_AnnualLeave.Edit(AnnualLeaveByProfile);
                    }
                }
                repoAtt_AnnualLeave.SaveChanges();
                repoSal_UnusualAllowance.SaveChanges();
            }
        }
Esempio n. 16
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();
                        }

                    }
                }
                    
                
            }
        }
Esempio n. 17
0
        public bool ComputeInsuranceLeaveDetail(int Year, string orgStructure, string LstProfileStatus, string UserLogin)
        {
            /*
             * -get leaveDetail : type , year
             *   - get List Profile :
             *      + Theo phong ban
             *      + Theo trạng thai StatusEmpleaveDetail
             *
             */

            var    result = false;
            string status = string.Empty;


            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_AnnualLeaveDetail = new CustomBaseRepository <Att_AnnualLeaveDetail>(unitOfWork);
                var repoHre_Profile           = new CustomBaseRepository <Hre_Profile>(unitOfWork);
                var repoHre_HDTJob            = new CustomBaseRepository <Hre_HDTJob>(unitOfWork);
                var repoSys_AppConfig         = new CustomBaseRepository <Sys_AppConfig>(unitOfWork);
                var repoCat_DayOff            = new CustomBaseRepository <Cat_DayOff>(unitOfWork);
                var repoCat_LeaveDayType      = new CustomBaseRepository <Cat_LeaveDayType>(unitOfWork);
                var repoAtt_LeaveDay          = new CustomBaseRepository <Att_LeaveDay>(unitOfWork);
                var repoCat_JobTitle          = new CustomBaseRepository <Cat_JobTitle>(unitOfWork);

                #region get Data
                string        HRM_ATT_ANNUALINSURANCELEAVE_ = AppConfig.HRM_ATT_ANNUALINSURANCELEAVE_.ToString();
                List <object> lstO = new List <object>();
                lstO.Add(HRM_ATT_ANNUALINSURANCELEAVE_);
                lstO.Add(null);
                lstO.Add(null);
                var config = GetData <Sys_AllSettingEntity>(lstO, ConstantSql.hrm_sys_sp_get_AllSetting, UserLogin, ref status);

                var formular1 = config.Where(s => s.Name == AppConfig.HRM_ATT_ANNUALINSURANCELEAVE_FORMULARCONFIG.ToString()).FirstOrDefault();
                var formular2 = config.Where(s => s.Name == AppConfig.HRM_ATT_ANNUALINSURANCELEAVE_FORMULARCOMPUTE.ToString()).FirstOrDefault();

                if (config == null || string.IsNullOrEmpty(formular1.Value1) || string.IsNullOrEmpty(formular2.Value1))
                {
                    //Common.MessageBoxs(Messages.Msg, Messages.PleaseConfigAnnualLeaveAtTotalConfig, MessageBox.Icon.WARNING, string.Empty);
                    return(result);
                }


                List <object> lstPro = new List <object>();
                lstPro.Add(orgStructure);
                lstPro.Add(null);
                lstPro.Add(null);
                var lstProfileQuery = GetData <Hre_ProfileEntity>(lstPro, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrg, UserLogin, ref status).ToList();

                string            formularConfig  = formular1.Value1;
                string            formularCompute = formular2.Value1;
                ParamGetConfigANL configAnl       = new ParamGetConfigANL();
                (new Att_AttendanceServices()).GetConfigANL(formularConfig, out configAnl);

                int           MonthBegin             = 1;
                List <string> lstCodeLeaveTypeNonAnl = new List <string>();
                if (configAnl != null && configAnl.monthBeginYear != null)
                {
                    MonthBegin = configAnl.monthBeginYear;
                }
                if (configAnl != null && configAnl.lstCodeLeaveNonANL != null)
                {
                    lstCodeLeaveTypeNonAnl = configAnl.lstCodeLeaveNonANL;
                }
                DateTime BeginYear = new DateTime(Year, MonthBegin, 1);
                DateTime EndYear   = BeginYear.AddYears(1).AddMinutes(-1);

                string          E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();
                List <DateTime> lstDayOff  = repoCat_DayOff
                                             .FindBy(m => m.IsDelete == null && m.DateOff > BeginYear && m.DateOff <= EndYear)
                                             .Select(m => m.DateOff).Distinct().ToList <DateTime>();
                List <Hre_ProfileEntity> lstprofile = lstProfileQuery
                                                      .Where(m => m.DateQuit == null || (m.DateQuit != null && m.DateQuit > BeginYear)).ToList();
                List <Guid> lstProfileID          = lstprofile.Select(m => m.ID).ToList();
                List <Guid> lstLeavedayTypeNonAnl = repoCat_LeaveDayType
                                                    .FindBy(m => m.IsDelete == null && lstCodeLeaveTypeNonAnl.Contains(m.Code)).Select(m => m.ID).ToList <Guid>();
                List <Att_LeaveDay> lstleavedayNonANl = repoAtt_LeaveDay
                                                        .FindBy(m => m.IsDelete == null && m.Status == E_APPROVED && lstLeavedayTypeNonAnl.Contains(m.LeaveDayTypeID) && lstProfileID.Contains(m.ProfileID)).ToList <Att_LeaveDay>();
                List <Att_LeaveDay> lstleavedayNonANlInYear = lstleavedayNonANl.Where(m => m.DateStart <= EndYear && m.DateEnd >= BeginYear).ToList <Att_LeaveDay>();
                List <Hre_HDTJob>   lstHDTJob = repoHre_HDTJob
                                                .FindBy(m => m.IsDelete == null && m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value)).ToList <Hre_HDTJob>();
                List <Cat_JobTitle> lstJobtitle = repoCat_JobTitle.FindBy(s => s.IsDelete == null).ToList();
                string E_INSURANCE_LEAVE        = AnnualLeaveDetailType.E_INSURANCE_LEAVE.ToString();
                #endregion

                List <Att_AnnualLeaveDetail> lstInsDetail = new List <Att_AnnualLeaveDetail>();
                foreach (var item in lstprofile)
                {
                    List <Att_LeaveDay>   lstLeavedayNonAnlByProfile       = lstleavedayNonANl.Where(m => m.ProfileID == item.ID).ToList();
                    List <Att_LeaveDay>   lstLeavedayNonAnlByProfileInYear = lstleavedayNonANlInYear.Where(m => m.ProfileID == item.ID).ToList();
                    List <Hre_HDTJob>     lstHDTJobByProfile = lstHDTJob.Where(m => m.ProfileID == item.ID).ToList();
                    Att_AnnualLeaveDetail annualProfile      = new Att_AnnualLeaveDetail();
                    annualProfile.ID         = Guid.NewGuid();
                    annualProfile.ProfileID  = item.ID;
                    annualProfile.MonthStart = BeginYear;
                    annualProfile.MonthEnd   = EndYear;
                    annualProfile.Year       = Year;
                    annualProfile.Type       = E_INSURANCE_LEAVE;
                    for (DateTime Month = BeginYear; Month < EndYear; Month = Month.AddMonths(1))
                    {
                        double AvailabelInYear = (new Att_AttendanceServices()).GetAnnualLeaveAvailableAllYear(Year, Month.Month, item.DateHire,
                                                                                                               item.DateEndProbation, item.DateQuit, formularConfig,
                                                                                                               formularCompute, lstLeavedayNonAnlByProfileInYear, lstJobtitle, lstDayOff, lstHDTJobByProfile, lstLeavedayNonAnlByProfile);
                        if (Month.Month == 1)
                        {
                            annualProfile.Month1 = AvailabelInYear;
                        }
                        if (Month.Month == 2)
                        {
                            annualProfile.Month2 = AvailabelInYear;
                        }
                        if (Month.Month == 3)
                        {
                            annualProfile.Month3 = AvailabelInYear;
                        }
                        if (Month.Month == 4)
                        {
                            annualProfile.Month4 = AvailabelInYear;
                        }
                        if (Month.Month == 5)
                        {
                            annualProfile.Month5 = AvailabelInYear;
                        }
                        if (Month.Month == 6)
                        {
                            annualProfile.Month6 = AvailabelInYear;
                        }
                        if (Month.Month == 7)
                        {
                            annualProfile.Month7 = AvailabelInYear;
                        }
                        if (Month.Month == 8)
                        {
                            annualProfile.Month8 = AvailabelInYear;
                        }
                        if (Month.Month == 9)
                        {
                            annualProfile.Month9 = AvailabelInYear;
                        }
                        if (Month.Month == 10)
                        {
                            annualProfile.Month10 = AvailabelInYear;
                        }
                        if (Month.Month == 11)
                        {
                            annualProfile.Month11 = AvailabelInYear;
                        }
                        if (Month.Month == 12)
                        {
                            annualProfile.Month12 = AvailabelInYear;
                        }
                    }
                    lstInsDetail.Add(annualProfile);
                }

                DataErrorCode DataErr = DataErrorCode.Unknown;

                if (lstInsDetail.Count > 0)
                {
                    #region lấy dữ liệu dưới DB xóa đi
                    List <Guid> lstProfileID_InDB = lstInsDetail.Where(m => m.ProfileID != null).Select(m => m.ProfileID.Value).ToList();


                    List <Att_AnnualLeaveDetail> lstAnnualLeaveDetail_InDB = repoAtt_AnnualLeaveDetail
                                                                             .FindBy(m => m.IsDelete == null && m.Type == E_INSURANCE_LEAVE && m.Year == Year && m.ProfileID != null &&
                                                                                     lstProfileID_InDB.Contains(m.ProfileID.Value)).ToList();
                    foreach (var item in lstAnnualLeaveDetail_InDB)
                    {
                        item.IsDelete = true;
                    }
                    #endregion

                    repoAtt_AnnualLeaveDetail.Add(lstInsDetail);
                    try
                    {
                        repoAtt_AnnualLeaveDetail.SaveChanges();
                    }
                    catch (Exception)
                    {
                        return(false);
                    }

                    //EntityService.AddEntity<Att_AnnualLeaveDetail>(GuidContext, lstInsDetail.ToArray());
                    //DataErr = EntityService.SubmitChanges(GuidContext, LoginUserID);

                    //if (DataErr == DataErrorCode.Success)
                    //{
                    //    Common.MessageBoxs(Messages.Msg, Messages.SaveSuccess, MessageBox.Icon.INFO, string.Empty);
                    //}
                    //else
                    //{
                    //    Common.MessageBoxs(Messages.Msg, Messages.SaveUnSuccess, MessageBox.Icon.INFO, string.Empty);
                    //}
                }
                //else
                //{
                //    Common.MessageBoxs(Messages.Msg, Messages.NoDataToCompute, MessageBox.Icon.WARNING, string.Empty);
                //}
                result = true;
            }
            return(result);
        }
        public string ValidateSaveWorkday(Att_WorkdayEntity WorkdaySave, Att_WorkdayEntity WorkdayOld, string UserLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoHre_CardHistory = new CustomBaseRepository<Hre_CardHistory>(unitOfWork);
                var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoAtt_TAMScanLog = new CustomBaseRepository<Att_TAMScanLog>(unitOfWork);
                var repoCat_Shift = new CustomBaseRepository<Cat_Shift>(unitOfWork);
                var repoCat_TAMScanReasonMiss = new CustomBaseRepository<Cat_TAMScanReasonMiss>(unitOfWork);
                var repoAtt_Workday = new CustomBaseRepository<Att_Workday>(unitOfWork);

                string message = "";
                List<Att_TAMScanLog> lstTamScanLog = new List<Att_TAMScanLog>();
                string Notes = string.Empty;
                #region cập nhật giờ intime va outtime
                //1. xử lí việc insert vào TamScanlog
                //2. xử lí việc chuyển in và out theo logic in phải nhỏ hơn out
                //3. xử lý việc Validate inout không thẻ lơn hơn workday 1 ngày
                DateTime? Intime1 = null;
                if (WorkdaySave.InTime1 != null)
                {
                    Intime1 = WorkdaySave.InTime1.Value.Date;
                }
                if (!string.IsNullOrEmpty(WorkdaySave.TempTimeIn) && Intime1.HasValue)
                {
                    DateTime TimeScan = DateTime.ParseExact(WorkdaySave.TempTimeIn, "HH:mm:ss", null);
                    Intime1 = Intime1.Value.AddHours(TimeScan.Hour).AddMinutes(TimeScan.Minute).AddSeconds(TimeScan.Second);
                }
                DateTime? OutTime1 = null;
                if (WorkdaySave.OutTime1 != null)
                {
                    OutTime1 = WorkdaySave.InTime1.Value.Date;
                }
                if (!string.IsNullOrEmpty(WorkdaySave.TempTimeOut) && OutTime1.HasValue)
                {
                    DateTime TimeScan = DateTime.ParseExact(WorkdaySave.TempTimeOut, "HH:mm:ss", null);
                    OutTime1 = OutTime1.Value.AddHours(TimeScan.Hour).AddMinutes(TimeScan.Minute).AddSeconds(TimeScan.Second);
                }

                Guid? MissInOutReason = WorkdaySave.MissInOutReason;

                //Check validate ko cho phép Intime hoặc out time
                if (((WorkdayOld.InTime1 == null && Intime1 != null) || (WorkdayOld.OutTime1 == null && OutTime1 != null)) && (MissInOutReason == null || MissInOutReason == Guid.Empty))
                {
                    message = ConstantMessages.plsInputTAMScanReasonMissBeforeChangeInOut.TranslateString();
                    return message;
                }
                //Chuyển dổi vị trí in và out
                if (Intime1 != null && OutTime1 != null && (Intime1 > OutTime1))
                {
                    DateTime DateChange = Intime1.Value;
                    Intime1 = OutTime1;
                    OutTime1 = DateChange;
                    // DataBeChangedBecauseInTimeIsAfterOutTime
                }
                bool isChangeTamScan = false;
                if (Intime1 != null)
                {
                    if (WorkdayOld.InTime1 != Intime1)
                    {
                        Notes += "Intime1:" + string.Format("{0:dd/MM/yyyy hh:mm:ss}", Intime1);
                    }

                    if (WorkdayOld.InTime1 == null) //Thiếu Intime. Thì cập nhật vào lstTamscanLog
                    {
                        Att_TAMScanLog Tams = new Att_TAMScanLog();
                        Tams.ID = Guid.NewGuid();
                        Tams.TimeLog = Intime1;
                        Tams.Status = TAMScanStatus.E_MANUAL.ToString();
                        lstTamScanLog.Add(Tams);
                        isChangeTamScan = true;
                    }
                    else
                    {
                        string E_MANUAL = TAMScanStatus.E_MANUAL.ToString();
                        Att_TAMScanLog tamScan = repoAtt_TAMScanLog.FindBy(m => m.TimeLog == WorkdayOld.InTime1.Value && m.ProfileID == WorkdayOld.ProfileID && m.Status == E_MANUAL).FirstOrDefault();
                        if (tamScan != null)
                        {
                            tamScan.TimeLog = Intime1;
                            isChangeTamScan = true;
                        }
                    }
                    WorkdaySave.InTime1 = Intime1; //Cập nhật vào workday
                }
                else if (WorkdayOld.InTime1 != null && Intime1 == null)
                {
                    Notes += "Intime1:" + "Null";
                    WorkdaySave.InTime1 = Intime1; //Cập nhật vào workday
                    string E_MANUAL = TAMScanStatus.E_MANUAL.ToString();
                    //Att_TAMScanLog tamScan = EntityService.CreateQueryable<Att_TAMScanLog>(false, GuidContext, Guid.Empty, m => m.TimeLog == WorkDay.InTime1.Value && m.ProfileID == WorkDay.ProfileID && m.Status == E_MANUAL).FirstOrDefault();
                    Att_TAMScanLog tamScan = repoAtt_TAMScanLog.FindBy(m => m.TimeLog == WorkdayOld.InTime1.Value && m.ProfileID == WorkdayOld.ProfileID && m.Status == E_MANUAL).FirstOrDefault();
                    if (tamScan != null)
                    {
                        tamScan.IsDelete = true;
                    }
                }
                if (OutTime1 != null)
                {
                    if (WorkdayOld.OutTime1 != OutTime1)
                    {
                        Notes += "OutTime1:" + string.Format("{0:dd/MM/yyyy hh:mm:ss}", OutTime1);
                    }
                    if (WorkdayOld.OutTime1 == null) //Thiếu OutTime. Thì cập nhật vào lstTamscanLog
                    {
                        Att_TAMScanLog Tams = new Att_TAMScanLog();
                        Tams.ID = Guid.NewGuid();
                        Tams.TimeLog = OutTime1;
                        Tams.Status = TAMScanStatus.E_MANUAL.ToString();
                        lstTamScanLog.Add(Tams);
                        isChangeTamScan = true;
                    }
                    WorkdaySave.OutTime1 = OutTime1;
                }
                else if (WorkdayOld.OutTime1 != null && OutTime1 == null)
                {
                    Notes += "OutTime1:" + "Null";
                    WorkdaySave.OutTime1 = OutTime1; //Cập nhật vào workday
                    //Att_TAMScanLog tamScan = EntityService.CreateQueryable<Att_TAMScanLog>(false, GuidContext, Guid.Empty, m => m.TimeLog == WorkDay.OutTime1.Value && m.ProfileID == WorkDay.ProfileID && m.Status == E_MANUAL).FirstOrDefault();
                    Att_TAMScanLog tamScan = repoAtt_TAMScanLog.FindBy(m => m.TimeLog == WorkdayOld.InTime1.Value && m.ProfileID == WorkdayOld.ProfileID && m.Status == TAMScanStatus.E_MANUAL.ToString()).FirstOrDefault();
                    if (tamScan != null)
                    {
                        tamScan.TimeLog = OutTime1;
                        isChangeTamScan = true;
                    }
                }
                #endregion
                #region xử lý tamsCanLog
                DateTime workdate = WorkdayOld.WorkDate;
                string cardCode = string.Empty;
                var Card = repoHre_CardHistory.FindBy(m => (!m.IsDelete.HasValue || m.IsDelete != true) && m.ProfileID == WorkdayOld.ProfileID && m.CardCode != null && m.DateEffect <= workdate).OrderByDescending(m => m.DateEffect).FirstOrDefault();
                //Hre_CardHistoryEntity Card = EntityService.CreateQueryable<Hre_CardHistory>(false, GuidContext, Guid.Empty, m => m.ProfileID == WorkDay.ProfileID && m.CardCode != null && m.DateEffect <= workdate).OrderByDescending(m => m.DateEffect).FirstOrDefault();
                if (Card != null)
                {
                    cardCode = Card.CardCode;
                }
                else
                {
                    string CodeAttendance = repoHre_Profile.FindBy(m => m.IsDelete == null && m.ID == WorkdayOld.ProfileID).Select(m => m.CodeAttendance).FirstOrDefault();
                    //string CodeAttendance = EntityService.CreateQueryable<Hre_Profile>(false, GuidContext, Guid.Empty, m => m.ID == WorkDay.ProfileID).Select(m => m.CodeAttendance).FirstOrDefault();
                    cardCode = CodeAttendance;
                }
                if (cardCode == string.Empty)
                {
                    //return new { valid = true };
                    message = ConstantMessages.Error.TranslateString();
                    return message;
                }


                if (lstTamScanLog.Count > 0)
                {
                    foreach (var Tam in lstTamScanLog)
                    {
                        Tam.CardCode = cardCode;
                        Tam.ProfileID = WorkdayOld.ProfileID;
                    }
                    //EntityService.AddEntity<Att_TAMScanLog>(GuidContext, lstTamScanLog.ToArray());
                    repoAtt_TAMScanLog.Add(lstTamScanLog);
                }
                #endregion
                #region Xử lý Xóa Trong tamsCanLog

                if (WorkdayOld.InTime1 != null && Intime1 == null)
                {
                    string E_MANUAL = TAMScanStatus.E_MANUAL.ToString();
                    List<Att_TAMScanLog> tamScan = repoAtt_TAMScanLog.FindBy(m => m.IsDelete == null && m.TimeLog == WorkdayOld.InTime1 && m.CardCode == cardCode).ToList();
                    //List<Att_TAMScanLog> tamScan = EntityService.CreateQueryable<Att_TAMScanLog>(false, GuidContext, Guid.Empty, m => m.TimeLog == InTimeBeforeChanges.Value && m.CardCode == cardCode
                    //    && m.Status == E_MANUAL).ToList<Att_TAMScanLog>();
                    if (tamScan != null && tamScan.Count > 0)
                    {
                        foreach (var item in tamScan)
                        {
                            item.IsDelete = true;
                        }
                    }
                }
                if (WorkdayOld.OutTime1 != null && OutTime1 == null)
                {
                    string E_MANUAL = TAMScanStatus.E_MANUAL.ToString();
                    List<Att_TAMScanLog> tamScan = repoAtt_TAMScanLog.FindBy(m => m.IsDelete == null && m.TimeLog == WorkdayOld.OutTime1 && m.CardCode == cardCode).ToList();
                    //List<Att_TAMScanLog> tamScan = EntityService.CreateQueryable<Att_TAMScanLog>(false, GuidContext, Guid.Empty, m => m.TimeLog == OutTimeBeforeChanges.Value && m.CardCode == cardCode
                    //   && m.Status == E_MANUAL).ToList<Att_TAMScanLog>();
                    if (tamScan.Count > 0)
                    {
                        foreach (var item in tamScan)
                        {
                            item.IsDelete = true;
                        }
                    }
                }

                #endregion

                #region Thay đổi Shift
                var ShiftAll = repoCat_Shift.FindBy(m => m.IsDelete == null).ToList();
                Guid ShiftIDActual = Guid.Empty;
                Guid ShiftIDApprove = Guid.Empty;
                string ShiftCodeActual = string.Empty;
                string ShiftCodeApprove = string.Empty;
                var ShiftActual = ShiftAll.Where(m => m.ID == WorkdaySave.ShiftActual).FirstOrDefault();
                var ShiftApprove = ShiftAll.Where(m => m.ID == WorkdaySave.ShiftApprove).FirstOrDefault();
                if (ShiftActual != null)
                {
                    ShiftIDActual = ShiftActual.ID;
                    ShiftCodeActual = ShiftActual.Code;
                }
                if (ShiftApprove != null)
                {
                    ShiftIDApprove = ShiftApprove.ID;
                    ShiftCodeApprove = ShiftApprove.Code;
                }
                if (WorkdayOld.ShiftActual != ShiftIDActual)
                {
                    Notes += "ShiftCodeActual:" + ShiftActual.Code;
                    Notes += "ShiftCodeApprove:" + ShiftActual.Code;
                    if (ShiftActual != null) // nếu như ShiftActual thay đổi thì thay đổi 
                    {
                        ShiftIDActual = ShiftActual.ID;
                        ShiftCodeActual = ShiftActual.Code;
                        ShiftIDApprove = ShiftActual.ID;
                        ShiftCodeApprove = ShiftActual.Code;
                    }
                }
                else if (WorkdayOld.ShiftApprove != ShiftIDApprove)
                {
                    Notes += "ShiftCodeApprove:" + ShiftCodeApprove;
                }

                WorkdaySave.ShiftActual = ShiftIDActual;
                WorkdaySave.ShiftApprove = ShiftIDApprove;
                #endregion
                #region thay dổi lateEarly
                string LateEarLyModify = string.Empty;
                double MinuteLateEarly = 0;
                if (WorkdaySave.LateEarlyDuration != null)
                {
                    MinuteLateEarly = WorkdaySave.LateEarlyDuration.Value;
                }
                string LateEarlyReason = string.Empty;
                if (!string.IsNullOrEmpty(WorkdaySave.LateEarlyReason))
                {
                    LateEarlyReason = WorkdaySave.LateEarlyReason;
                }


                bool IsChangeLateEarly = false;
                if (WorkdayOld.LateEarlyDuration != null && (WorkdayOld.LateEarlyDuration != MinuteLateEarly))
                {
                    IsChangeLateEarly = true;
                    Notes += "LateEarlyDuration:" + MinuteLateEarly;
                    WorkdaySave.LateEarlyDuration = MinuteLateEarly;
                }
                if ((WorkdayOld.LateEarlyReason == null && !string.IsNullOrEmpty(LateEarlyReason)) || WorkdayOld.LateEarlyReason != LateEarlyReason)
                {
                    Notes += "LateEarlyReason:" + LateEarlyReason;
                    WorkdaySave.LateEarlyReason = LateEarlyReason;
                }
                //Cat_TAMScanReasonMiss TAMScanReasonMiss = EntityService.CreateQueryable<Cat_TAMScanReasonMiss>(false, GuidContext, Guid.Empty, m => m.TAMScanReasonMissName == MissInOutReason).FirstOrDefault();
                Cat_TAMScanReasonMiss TAMScanReasonMiss = repoCat_TAMScanReasonMiss.FindBy(m => m.IsDelete == null && m.ID == MissInOutReason).FirstOrDefault();
                if (TAMScanReasonMiss != null)
                {
                    if (WorkdayOld.MissInOutReason == Guid.Empty || WorkdayOld.MissInOutReason != TAMScanReasonMiss.ID)
                    {
                        Notes += "MissInOutReason:" + TAMScanReasonMiss.TAMScanReasonMissName;
                    }
                    WorkdaySave.TAMScanReasonMissName = TAMScanReasonMiss.TAMScanReasonMissName;
                }
                else
                {
                    Notes += "MissInOutReason:" + "NULL";
                    WorkdaySave.MissInOutReason = null;
                }
                #endregion
                #region Đăng Ký Nghỉ LeaveDay

                string LeavedayCode = string.Empty;
                if (WorkdaySave.udLeavedayCode1 != null && WorkdayOld.udLeavedayCode1 != WorkdaySave.udLeavedayCode1)
                {
                    LeavedayCode = WorkdaySave.udLeavedayCode1;
                    if (LeavedayCode == "CO")
                    {
                        message = ConstantMessages.CantRegisterCO.TranslateString();
                        return message;
                        //Common.MessageBoxs(Messages.Msg, LanguageManager.GetString(Messages.CantRegisterCO), MessageBox.Icon.WARNING, string.Empty);
                        //return new { valid = true };
                    }
                }
                if (WorkdayOld != null && (!string.IsNullOrEmpty(WorkdayOld.udLeavedayCode1) || !string.IsNullOrEmpty(WorkdayOld.udLeavedayCode2)))
                {
                    if (!string.IsNullOrEmpty(WorkdayOld.udLeavedayStatus1) && WorkdayOld.udLeavedayStatus1 == LeaveDayStatus.E_APPROVED.ToString())
                    {
                        message = ConstantMessages.StatusApproveCannotEdit.TranslateString();
                        return message;
                        //Common.MessageBoxs(Messages.Msg, LanguageManager.GetString(Messages.DataCantBeModify), MessageBox.Icon.WARNING, string.Empty);
                        //return new { valid = true };
                    }
                }

                #endregion
                string TypeOld = WorkdaySave.Type;
                //if (isChangeTamScan)
                //{
                //    WorkdaySave.udIsManualFromTamScan = true;
                //}
                List<Att_WorkdayEntity> lstWorkdaySave = new List<Att_WorkdayEntity>() { WorkdaySave };
                List<Att_Workday> lstWorkdayNew = ComputeWorkday(lstWorkdaySave.Translate<Att_Workday>(), ShiftAll, isChangeTamScan, UserLogin);
                WorkdaySave.Type = TypeOld;
                if (lstWorkdayNew.Count > 0)
                {
                    Att_Workday workdayNew = lstWorkdayNew.FirstOrDefault();
                    if (workdayNew != null)
                    {
                        if (LeavedayCode != "")
                        {
                            string ErrLeave = SaveLeaveDay(workdayNew, LeavedayCode, UserLogin);
                            if (ErrLeave != string.Empty)
                            {
                                return ErrLeave;
                                //Common.MessageBoxs(Messages.Msg, ErrLeave, MessageBox.Icon.WARNING, string.Empty);
                                //return new { valid = true };
                            }
                        }
                        workdayNew.Type = TypeOld;
                        if (IsChangeLateEarly)
                            workdayNew.LateEarlyDuration = MinuteLateEarly;
                        //if (Notes != string.Empty)
                        //{
                        //    Notes = "(" + UserLogin + "-" + string.Format("{0:dd/MM/yyyy hh:mm:ss}", DateTime.Now) + "-[" + Notes + "])";
                        //}
                        string NoteValidated = workdayNew.Note + Notes;
                        if (NoteValidated.Length > 2000)
                        {
                            NoteValidated = NoteValidated.Substring(NoteValidated.Length - 2000, 2000);
                        }
                        if (Notes != string.Empty)
                        {
                            workdayNew.SrcType = WorkdaySrcType.E_MANUAL.ToString();
                        }
                        workdayNew.Note = NoteValidated;
                        if (workdayNew.Type == string.Empty)
                        {
                            workdayNew.Type = WorkdayType.E_NORMAL.ToString();
                        }
                        DateTime DateNew = workdayNew.WorkDate;
                        Guid ProfileID = workdayNew.ProfileID;
                    }
                }
                repoAtt_Workday.Edit(lstWorkdayNew);
                //EntityService.AddEntity<Att_Workday>(GuidContext, lstWorkdayNew.ToArray());
                //EntityService.SubmitChanges(GuidContext, LoginUserID);
                repoAtt_Workday.SaveChanges();
                //unitOfWork.SaveChanges();
                return message;
            }
        }
        public string SaveLeaveDay(Att_Workday Workday, string LeaveTypeCode, string UserLogin)
        {
            if (Workday == null)
                return string.Empty;
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoCat_Shift = new CustomBaseRepository<Cat_Shift>(unitOfWork);
                var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(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 repoAtt_Roster = new CustomBaseRepository<Att_Roster>(unitOfWork);
                var repoAtt_RosterGroup = new CustomBaseRepository<Att_RosterGroup>(unitOfWork);
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
                var shifts = repoCat_Shift.FindBy(s => s.IsDelete == null).ToList();
                Att_LeavedayServices leavedayServices = new Att_LeavedayServices();
                LeaveTypeCode = LeaveTypeCode.Replace("...", string.Empty);

                Guid? ShiftID = Workday.ShiftApprove ?? Workday.ShiftID;
                double DurationHour = 8;
                var shift = repoCat_Shift.FindBy(m => m.ID == ShiftID).FirstOrDefault();
                //Cat_Shift shift = EntityService.CreateQueryable<Cat_Shift>(false, GuidContext, Guid.Empty, m => m.ID == ShiftID).FirstOrDefault();
                if (shift != null)
                    DurationHour = shift.WorkHours ?? 8;
                var leaveType = new List<Cat_LeaveDayType>().Select(m => new { m.ID, m.Code, m.CodeStatistic }).FirstOrDefault();
                if (!string.IsNullOrEmpty(LeaveTypeCode))
                {
                    leaveType = repoCat_LeaveDayType.FindBy(m => m.Code == LeaveTypeCode).Select(m => new { m.ID, m.Code, m.CodeStatistic }).FirstOrDefault();
                    //leaveType = EntityService.CreateQueryable<Cat_LeaveDayType>(false, GuidContext, Guid.Empty, m => m.CodeStatistic == LeaveTypeCode).Select(m => new { m.ID, m.Code, m.CodeStatistic }).FirstOrDefault();
                }

                DateTime workday = Workday.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);
                string E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();
                string E_REJECTED = LeaveDayStatus.E_REJECTED.ToString();
                List<Att_LeaveDay> lstLeaveDayInDbUpdate = repoAtt_LeaveDay.FindBy(m => m.DateStart <= endDate && m.DateEnd >= beginDate && m.ProfileID == Workday.ProfileID && m.Status != E_REJECTED).ToList<Att_LeaveDay>();
                List<Att_LeaveDay> lstLeaveDayInsert = new List<Att_LeaveDay>();

                if (lstLeaveDayInDbUpdate.Count > 0)
                {
                    if (!lstLeaveDayInDbUpdate.Any(m => m.Status == LeaveDayStatus.E_APPROVED.ToString()))
                    {
                        if (leaveType != null)
                        {
                            lstLeaveDayInDbUpdate.ForEach(m => m.LeaveDayTypeID = leaveType.ID);
                        }
                        else
                        {
                            lstLeaveDayInDbUpdate.ForEach(m => m.IsDelete = true);
                        }
                    }
                    else
                        lstLeaveDayInDbUpdate = new List<Att_LeaveDay>();
                }
                else
                {
                    if (leaveType != null)
                    {
                        Att_LeaveDay LeavedayInsert = new Att_LeaveDay();
                        LeavedayInsert.ID = Guid.Empty;
                        LeavedayInsert.ProfileID = Workday.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 = leaveType.ID;
                        LeavedayInsert.Status = LeaveDayStatus.E_SUBMIT.ToString();
                        lstLeaveDayInsert.Add(LeavedayInsert);
                    }
                }
                //Cap nhat leavedayID cho workday o day
                if (lstLeaveDayInsert.Count > 0)
                {
                    if (lstLeaveDayInsert.Count > 1)
                    {
                        Workday.LeaveDayID1 = lstLeaveDayInsert[0].ID;
                        Workday.LeaveDayID2 = lstLeaveDayInsert[1].ID;
                        //Workday.udLeavedayCode1 = LeaveTypeCode;
                        //Workday.udLeavedayCode2 = LeaveTypeCode;
                        //Workday.udLeavedayStatus1 = lstLeaveDayInsert.FirstOrDefault().Status.TranslateString();
                        //Workday.udLeavedayStatus2 = lstLeaveDayInsert.FirstOrDefault().Status.TranslateString();
                    }
                    else
                    {
                        Workday.LeaveDayID1 = lstLeaveDayInsert[0].ID;
                        //Workday.udLeavedayCode1 = LeaveTypeCode;
                        //Workday.udLeavedayStatus1 = lstLeaveDayInsert.FirstOrDefault().Status.TranslateString();
                    }
                }
                //else if (lstLeaveDayInDbUpdate.Count > 0)
                //{
                //    if (lstLeaveDayInDbUpdate.Count >= 2)
                //    {
                //        Workday.udLeavedayCode1 = LeaveTypeCode;
                //        Workday.udLeavedayCode2 = LeaveTypeCode;
                //        Workday.udLeavedayStatus1 = lstLeaveDayInDbUpdate.FirstOrDefault().Status.TranslateString();
                //        Workday.udLeavedayStatus2 = lstLeaveDayInDbUpdate.FirstOrDefault().Status.TranslateString();
                //    }
                //    else
                //    {
                //        Workday.udLeavedayCode1 = LeaveTypeCode;
                //        Workday.udLeavedayStatus1 = lstLeaveDayInDbUpdate.FirstOrDefault().Status.TranslateString();
                //        Workday.udLeavedayStatus2 = lstLeaveDayInDbUpdate.FirstOrDefault().Status.TranslateString();
                //    }
                //}

                #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>();
                    //List<Guid> LeaveTypeDayOffID = EntityService.CreateQueryable<Cat_LeaveDayType>(false, GuidContext, Guid.Empty, 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))
                    {
                        string Error = leavedayServices.ValidateLeaveDayTimeOff(lstLeaveDayInsert.Select(m => m.ProfileID).Distinct().ToList(), lstLeaveDayInsert);
                        if (Error != string.Empty)
                        {
                            return Error;
                        }
                    }
                }
                #endregion

                #region triet.mai validate vấn đề ngày nghỉ dành cho nhân viên thực tập

                string E_STANDARD_WORKDAY = AppConfig.E_STANDARD_WORKDAY.ToString();
                string status = string.Empty;
                List<object> lstO = new List<object>();
                lstO.Add(E_STANDARD_WORKDAY);
                lstO.Add(null);
                lstO.Add(null);

                Sys_AllSetting config = GetData<Sys_AllSetting>(lstO, ConstantSql.hrm_sys_sp_get_AllSetting, UserLogin, ref status).FirstOrDefault();
                //Sys_AppConfig config = EntityService.GetEntity<Sys_AppConfig>(false, GuidContext, Guid.Empty, m => m.Info == E_STANDARD_WORKDAY);
                string validateEmpProbation = leavedayServices.ValidateLeaveTypeByNewEmployee(config, lstLeaveDayInsert);
                if (validateEmpProbation != string.Empty)
                {
                    return validateEmpProbation;
                }
                #endregion

                #region triet.mai cap nhat leaveDays va leaveHours
                lstLeaveDayInsert.AddRange(lstLeaveDayInDbUpdate);
                if (lstLeaveDayInsert.Count > 0)
                {
                    List<Cat_LeaveDayType> lstLeaveDayType = repoCat_LeaveDayType.FindBy(m => m.IsDelete == null).ToList<Cat_LeaveDayType>();
                    //List<Cat_LeaveDayType> lstLeaveDayType = EntityService.CreateQueryable<Cat_LeaveDayType>(false, GuidContext, Guid.Empty).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>();
                    //List<Hre_Profile> lstProfile = EntityService.CreateQueryable<Hre_Profile>(false, GuidContext, Guid.Empty, 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(m.ProfileID.Value))
                        .Select(m => new { m.ID, m.ProfileID, m.MonthStart, m.GradeAttendanceID })
                        .OrderByDescending(m => m.MonthStart).ToList();
                    //var lstGrade = EntityService.CreateQueryable<Sal_Grade>(false, GuidContext, Guid.Empty, m => lstProfileID1.Contains(m.ProfileID))
                    //    .Select(m => new { m.ID, m.ProfileID, m.MonthStart, m.GradeID })
                    //    .OrderByDescending(m => m.MonthStart)
                    //    .Execute();
                    List<Cat_GradeAttendance> lstGradeAttendance = repoCat_GradeAttendance.FindBy(m => m.IsDelete == null).ToList();
                    //List<Cat_GradeCfg> lstGradeCfg = EntityService.CreateQueryable<Cat_GradeCfg>(false, GuidContext, Guid.Empty).ToList<Cat_GradeCfg>();
                    List<Hre_WorkHistory> listWorkHistory = repoHre_WorkHistory.FindBy(m => m.DateEffective <= dateMax1 && lstProfileID1.Contains(m.ProfileID)).OrderByDescending(m => m.DateEffective).ToList<Hre_WorkHistory>();
                    //List<Hre_WorkHistory> listWorkHistory = EntityService.CreateQueryable<Hre_WorkHistory>(false, GuidContext, Guid.Empty, m => m.DateEffective <= dateMax1 && lstProfileID1.Contains(m.ProfileID)).OrderByDescending(m => m.DateEffective).ToList<Hre_WorkHistory>();

                    E_APPROVED = RosterStatus.E_APPROVED.ToString();
                    string E_ROSTERGROUP = RosterType.E_ROSTERGROUP.ToString();

                    if (dateMin1 == null || dateMax1 == null)
                    {
                        lstRosterTypeGroup = repoAtt_Roster.FindBy(m => lstProfileID1.Contains(m.ProfileID) && m.Status == E_APPROVED && m.Type == E_ROSTERGROUP).ToList<Att_Roster>();
                        //lstRosterTypeGroup = EntityService.Instance.CreateQueryable<Att_Roster>(false, guidContext, Guid.Empty, m => lstProfileID.Contains(m.ProfileID) && m.Status == E_APPROVED && m.Type == E_ROSTERGROUP).ToList<Att_Roster>();
                        lstRosterGroup = repoAtt_RosterGroup.FindBy(m => m.DateStart != null && m.DateEnd != null).ToList<Att_RosterGroup>();
                        //lstRosterGroup = EntityService.Instance.CreateQueryable<Att_RosterGroup>(false, guidContext, Guid.Empty, m => m.DateStart != null && m.DateEnd != null).ToList<Att_RosterGroup>();
                    }
                    else
                    {
                        lstRosterTypeGroup = repoAtt_Roster.FindBy(m => lstProfileID1.Contains(m.ProfileID) && m.Status == E_APPROVED && m.Type == E_ROSTERGROUP && m.DateStart <= dateMax1).ToList<Att_Roster>();
                        //lstRosterTypeGroup = EntityService.Instance.CreateQueryable<Att_Roster>(false, guidContext, Guid.Empty, m => lstProfileID.Contains(m.ProfileID) && m.Status == E_APPROVED && m.Type == E_ROSTERGROUP && m.DateStart <= DateTo).ToList<Att_Roster>();
                        lstRosterGroup = repoAtt_RosterGroup.FindBy(m => m.DateStart != null && m.DateEnd != null && m.DateStart <= dateMax1 && m.DateEnd >= dateMin1).ToList<Att_RosterGroup>();
                        //lstRosterGroup = EntityService.Instance.CreateQueryable<Att_RosterGroup>(false, guidContext, Guid.Empty, m => m.DateStart != null && m.DateEnd != null && m.DateStart <= DateTo && m.DateEnd >= DateFrom).ToList<Att_RosterGroup>();
                    }
                    //RosterDAO.GetRosterGroup(GuidContext, lstProfileID1, dateMin1, dateMax1, out lstRosterTypeGroup, out lstRosterGroup);
                    List<Cat_DayOff> lstHoliday = repoCat_DayOff.FindBy(m => m.IsDelete == null).ToList<Cat_DayOff>();
                    //List<Cat_DayOff> lstHoliday = EntityService.CreateQueryable<Cat_DayOff>(false, GuidContext, Guid.Empty).ToList<Cat_DayOff>();
                    string E_APPROVED1 = RosterStatus.E_APPROVED.ToString();
                    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<Att_Roster> lstRoster = EntityService.CreateQueryable<Att_Roster>(false, GuidContext, Guid.Empty, 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 GradeAttendanceID = lstGrade.Where(m => m.ProfileID == profileInLeave.ID && m.MonthStart <= dateMax1 && m.GradeAttendanceID.HasValue).Select(m => m.GradeAttendanceID.Value).FirstOrDefault();
                        Cat_GradeAttendance gradeAttendance = lstGradeAttendance.Where(m => m.ID == GradeAttendanceID).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();
                        leavedayServices.AnalyseTotalLeaveDaysAndHours(item, leaveDayType, profileInLeave, gradeAttendance, lstRosterByProfile, lstRosterGroup, listWorkHistoryByProfile, lstHoliday, shifts);
                        if (item.ID == Guid.Empty)
                        {
                            item.ID = Guid.NewGuid();
                            repoAtt_LeaveDay.Add(item);
                        }
                        else
                            repoAtt_LeaveDay.Edit(item);
                    }
                }
                #endregion

                //repoAtt_LeaveDay.Add(lstLeaveDayInsert);
                repoAtt_LeaveDay.SaveChanges();
                //EntityService.AddEntity<Att_LeaveDay>(GuidContext, lstLeaveDayInsert.ToArray());
                return string.Empty;
            }
        }
        public bool ComputeInsuranceLeaveDetail(int Year, string orgStructure, string LstProfileStatus,string UserLogin)
        {
            /*
           * -get leaveDetail : type , year
           *   - get List Profile :
           *      + Theo phong ban
           *      + Theo trạng thai StatusEmpleaveDetail
           * 
           */

            var result = false;
        string status = string.Empty;


        using (var context = new VnrHrmDataContext())
        {
            var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
            var repoAtt_AnnualLeaveDetail = new CustomBaseRepository<Att_AnnualLeaveDetail>(unitOfWork);
            var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
            var repoHre_HDTJob = new CustomBaseRepository<Hre_HDTJob>(unitOfWork);
            var repoSys_AppConfig = new CustomBaseRepository<Sys_AppConfig>(unitOfWork);
            var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
            var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
            var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
            var repoCat_JobTitle = new CustomBaseRepository<Cat_JobTitle>(unitOfWork);
                
            #region get Data
            string HRM_ATT_ANNUALINSURANCELEAVE_ = AppConfig.HRM_ATT_ANNUALINSURANCELEAVE_.ToString();
            List<object> lstO = new List<object>();
            lstO.Add(HRM_ATT_ANNUALINSURANCELEAVE_);
            lstO.Add(null);
            lstO.Add(null);
            var config = GetData<Sys_AllSettingEntity>(lstO, ConstantSql.hrm_sys_sp_get_AllSetting, UserLogin, ref status);

            var formular1 = config.Where(s => s.Name == AppConfig.HRM_ATT_ANNUALINSURANCELEAVE_FORMULARCONFIG.ToString()).FirstOrDefault();
            var formular2 = config.Where(s => s.Name == AppConfig.HRM_ATT_ANNUALINSURANCELEAVE_FORMULARCOMPUTE.ToString()).FirstOrDefault();

            if (config == null || string.IsNullOrEmpty(formular1.Value1) || string.IsNullOrEmpty(formular2.Value1))
            {
                //Common.MessageBoxs(Messages.Msg, Messages.PleaseConfigAnnualLeaveAtTotalConfig, MessageBox.Icon.WARNING, string.Empty);
                return result;
            }


            List<object> lstPro = new List<object>();
            lstPro.Add(orgStructure);
            lstPro.Add(null);
            lstPro.Add(null);
            var lstProfileQuery = GetData<Hre_ProfileEntity>(lstPro, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrg, UserLogin, ref status).ToList();

            string formularConfig = formular1.Value1;
            string formularCompute = formular2.Value1;
            ParamGetConfigANL configAnl = new ParamGetConfigANL();
            (new Att_AttendanceServices()).GetConfigANL(formularConfig, out configAnl);

            int MonthBegin = 1;
            List<string> lstCodeLeaveTypeNonAnl = new List<string>();
            if (configAnl != null && configAnl.monthBeginYear != null)
            {
                MonthBegin = configAnl.monthBeginYear;
            }
            if (configAnl != null && configAnl.lstCodeLeaveNonANL != null)
            {
                lstCodeLeaveTypeNonAnl = configAnl.lstCodeLeaveNonANL;
            }
            DateTime BeginYear = new DateTime(Year, MonthBegin, 1);
            DateTime EndYear = BeginYear.AddYears(1).AddMinutes(-1);

            string E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();
            List<DateTime> lstDayOff = repoCat_DayOff
                    .FindBy(m => m.IsDelete == null && m.DateOff > BeginYear && m.DateOff <= EndYear)
                    .Select(m => m.DateOff).Distinct().ToList<DateTime>();
            List<Hre_ProfileEntity> lstprofile = lstProfileQuery
                .Where(m => m.DateQuit == null || (m.DateQuit != null && m.DateQuit > BeginYear)).ToList();
            List<Guid> lstProfileID = lstprofile.Select(m => m.ID).ToList();
            List<Guid> lstLeavedayTypeNonAnl = repoCat_LeaveDayType
                    .FindBy(m => m.IsDelete == null && lstCodeLeaveTypeNonAnl.Contains(m.Code)).Select(m => m.ID).ToList<Guid>();
            List<Att_LeaveDay> lstleavedayNonANl = repoAtt_LeaveDay
                    .FindBy(m => m.IsDelete == null && m.Status == E_APPROVED && lstLeavedayTypeNonAnl.Contains(m.LeaveDayTypeID) && lstProfileID.Contains(m.ProfileID)).ToList<Att_LeaveDay>();
            List<Att_LeaveDay> lstleavedayNonANlInYear = lstleavedayNonANl.Where(m => m.DateStart <= EndYear && m.DateEnd >= BeginYear).ToList<Att_LeaveDay>();
            List<Hre_HDTJob> lstHDTJob = repoHre_HDTJob
                    .FindBy(m => m.IsDelete == null && m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value)).ToList<Hre_HDTJob>();
            List<Cat_JobTitle> lstJobtitle = repoCat_JobTitle.FindBy(s => s.IsDelete == null).ToList();
            string E_INSURANCE_LEAVE = AnnualLeaveDetailType.E_INSURANCE_LEAVE.ToString();
            #endregion

            List<Att_AnnualLeaveDetail> lstInsDetail = new List<Att_AnnualLeaveDetail>();
            foreach (var item in lstprofile)
            {
                List<Att_LeaveDay> lstLeavedayNonAnlByProfile = lstleavedayNonANl.Where(m => m.ProfileID == item.ID).ToList();
                List<Att_LeaveDay> lstLeavedayNonAnlByProfileInYear = lstleavedayNonANlInYear.Where(m => m.ProfileID == item.ID).ToList();
                List<Hre_HDTJob> lstHDTJobByProfile = lstHDTJob.Where(m => m.ProfileID == item.ID).ToList();
                Att_AnnualLeaveDetail annualProfile = new Att_AnnualLeaveDetail();
                annualProfile.ID = Guid.NewGuid();
                annualProfile.ProfileID = item.ID;
                annualProfile.MonthStart = BeginYear;
                annualProfile.MonthEnd = EndYear;
                annualProfile.Year = Year;
                annualProfile.Type = E_INSURANCE_LEAVE;
                for (DateTime Month = BeginYear; Month < EndYear; Month = Month.AddMonths(1))
                {
                    double AvailabelInYear = (new Att_AttendanceServices()).GetAnnualLeaveAvailableAllYear( Year, Month.Month, item.DateHire,
                        item.DateEndProbation, item.DateQuit, formularConfig,
                        formularCompute, lstLeavedayNonAnlByProfileInYear, lstJobtitle, lstDayOff, lstHDTJobByProfile, lstLeavedayNonAnlByProfile);
                    if (Month.Month == 1)
                        annualProfile.Month1 = AvailabelInYear;
                    if (Month.Month == 2)
                        annualProfile.Month2 = AvailabelInYear;
                    if (Month.Month == 3)
                        annualProfile.Month3 = AvailabelInYear;
                    if (Month.Month == 4)
                        annualProfile.Month4 = AvailabelInYear;
                    if (Month.Month == 5)
                        annualProfile.Month5 = AvailabelInYear;
                    if (Month.Month == 6)
                        annualProfile.Month6 = AvailabelInYear;
                    if (Month.Month == 7)
                        annualProfile.Month7 = AvailabelInYear;
                    if (Month.Month == 8)
                        annualProfile.Month8 = AvailabelInYear;
                    if (Month.Month == 9)
                        annualProfile.Month9 = AvailabelInYear;
                    if (Month.Month == 10)
                        annualProfile.Month10 = AvailabelInYear;
                    if (Month.Month == 11)
                        annualProfile.Month11 = AvailabelInYear;
                    if (Month.Month == 12)
                        annualProfile.Month12 = AvailabelInYear;

                }
                lstInsDetail.Add(annualProfile);

            }

            DataErrorCode DataErr = DataErrorCode.Unknown;

            if (lstInsDetail.Count > 0)
            {
                #region lấy dữ liệu dưới DB xóa đi
                List<Guid> lstProfileID_InDB = lstInsDetail.Where(m => m.ProfileID != null).Select(m => m.ProfileID.Value).ToList();


                List<Att_AnnualLeaveDetail> lstAnnualLeaveDetail_InDB = repoAtt_AnnualLeaveDetail
                        .FindBy(m => m.IsDelete == null && m.Type == E_INSURANCE_LEAVE && m.Year == Year && m.ProfileID != null 
                            && lstProfileID_InDB.Contains(m.ProfileID.Value)).ToList();
                foreach (var item in lstAnnualLeaveDetail_InDB)
                {
                    item.IsDelete = true;
                }
                #endregion

                repoAtt_AnnualLeaveDetail.Add(lstInsDetail);
                try
                {
                    repoAtt_AnnualLeaveDetail.SaveChanges();
                }
                catch (Exception)
                {
                    return false;
                }

                //EntityService.AddEntity<Att_AnnualLeaveDetail>(GuidContext, lstInsDetail.ToArray());
                //DataErr = EntityService.SubmitChanges(GuidContext, LoginUserID);

                //if (DataErr == DataErrorCode.Success)
                //{
                //    Common.MessageBoxs(Messages.Msg, Messages.SaveSuccess, MessageBox.Icon.INFO, string.Empty);
                //}
                //else
                //{
                //    Common.MessageBoxs(Messages.Msg, Messages.SaveUnSuccess, MessageBox.Icon.INFO, string.Empty);
                //}
            }
            //else
            //{
            //    Common.MessageBoxs(Messages.Msg, Messages.NoDataToCompute, MessageBox.Icon.WARNING, string.Empty);
            //}
            result = true;
        }
        return result;    
        }
Esempio n. 21
0
        public void ComputeComissionService(Guid?ShopID, DateTime Month, string UserLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                string status                    = string.Empty;
                var    unitOfWork                = (IUnitOfWork) new UnitOfWork(context);
                var    repoShop                  = new CustomBaseRepository <Cat_Shop>(unitOfWork);
                var    repoRevenueForShop        = new CustomBaseRepository <Sal_RevenueForShopEntity>(unitOfWork);
                var    repoItemForShopEntity     = new CustomBaseRepository <Sal_ItemForShopEntity>(unitOfWork);
                var    repoLineItemForShopEntity = new CustomBaseRepository <Sal_LineItemForShopEntity>(unitOfWork);
                var    repoRevenueRecord         = new CustomBaseRepository <Sal_RevenueRecord>(unitOfWork);

                #region Get Data


                List <object> listModel = new List <object>();
                listModel.AddRange(new object[5]);
                listModel[3] = 1;
                listModel[4] = Int32.MaxValue - 1;
                List <Cat_Shop> listShop = GetData <Cat_Shop>(listModel, ConstantSql.hrm_cat_sp_get_Shop, UserLogin, ref status).ToList();

                listModel = new List <object>();
                listModel.AddRange(new object[4]);
                listModel[2] = 1;
                listModel[3] = Int32.MaxValue - 1;
                List <Cat_ShopGroupEntity> listGroupShop = GetData <Cat_ShopGroupEntity>(listModel, ConstantSql.hrm_cat_sp_get_ShopGroup, UserLogin, ref status).ToList();

                listModel = new List <object>();
                listModel.AddRange(new object[6]);
                listModel[4] = 1;
                listModel[5] = Int32.MaxValue - 1;
                List <Sal_RevenueForShopEntity> listRevenueForShop = GetData <Sal_RevenueForShopEntity>(listModel, ConstantSql.hrm_sal_sp_get_RevenueForShop, UserLogin, ref status).ToList();

                listModel = new List <object>();
                listModel.AddRange(new object[5]);
                listModel[3] = 1;
                listModel[4] = Int32.MaxValue - 1;
                List <Sal_ItemForShopEntity> listItemForShop = GetData <Sal_ItemForShopEntity>(listModel, ConstantSql.hrm_sal_sp_get_ItemForShop, UserLogin, ref status).ToList();

                listModel = new List <object>();
                listModel.AddRange(new object[5]);
                listModel[3] = 1;
                listModel[4] = Int32.MaxValue - 1;
                List <Sal_LineItemForShopEntity> listLineItemForShop = GetData <Sal_LineItemForShopEntity>(listModel, ConstantSql.hrm_sal_sp_get_LineItemForShop, UserLogin, ref status).ToList();

                listModel = new List <object>();
                listModel.AddRange(new object[4]);
                listModel[0] = Month;
                listModel[2] = 1;
                listModel[3] = Int32.MaxValue - 1;
                List <Sal_RevenueRecord> listRevenueRecord = GetData <Sal_RevenueRecord>(listModel, ConstantSql.hrm_sal_sp_get_RevenueRecord, UserLogin, ref status).ToList();

                listModel = new List <object>();
                listModel.AddRange(new object[18]);
                listModel[16] = 1;
                listModel[17] = int.MaxValue - 1;
                List <Hre_ProfileEntity> listProfile = GetData <Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_Profile, UserLogin, ref status).ToList();

                List <Cat_KPIBonusEntity> listKPIBonus = new List <Cat_KPIBonusEntity>();
                listModel = new List <object>();
                listModel.AddRange(new object[4]);
                listModel[2] = 1;
                listModel[3] = Int32.MaxValue - 1;
                listKPIBonus = GetData <Cat_KPIBonusEntity>(listModel, ConstantSql.hrm_cat_sp_get_KPIBonus, UserLogin, ref status).ToList();

                List <Cat_KPIBonusItemEntity> listKPIBonusItem = new List <Cat_KPIBonusItemEntity>();
                listModel = new List <object>();
                listModel.AddRange(new object[4]);
                listModel[2]     = 1;
                listModel[3]     = Int32.MaxValue - 1;
                listKPIBonusItem = GetData <Cat_KPIBonusItemEntity>(listModel, ConstantSql.hrm_cat_sp_get_KPIBonusItem, UserLogin, ref status).ToList();


                #endregion

                List <Guid> ListShopID = new List <Guid>();
                if (ShopID == null)
                {
                    ListShopID = listShop.Select(m => m.ID).ToList();
                }
                else
                {
                    if (!listShop.Any(m => m.ID == ShopID))
                    {
                        if (!listGroupShop.Any(m => m.ID == ShopID))
                        {
                            ListShopID = listShop.Select(m => m.ID).ToList();
                        }
                        else
                        {
                            ListShopID = listShop.Where(m => m.ShopGroupID == ShopID).Select(m => m.ID).ToList();
                        }
                    }
                    else
                    {
                        ListShopID.Add((Guid)ShopID);
                    }
                }

                List <Sal_RevenueRecord> _tmpRevenueRecord;
                List <ElementFormula>    listElementFormula = new List <ElementFormula>();

                foreach (Guid Guid in ListShopID)
                {
                    #region Xóa tháng đã tính trước đó nếu có
                    _tmpRevenueRecord = new List <Sal_RevenueRecord>();
                    _tmpRevenueRecord = listRevenueRecord.Where(m => m.ShopID == Guid && m.Month.Value.Month == Month.Month && m.Month.Value.Year == Month.Year).ToList();
                    if (_tmpRevenueRecord.Count > 0)
                    {
                        foreach (var j in _tmpRevenueRecord)
                        {
                            repoRevenueRecord.Remove(j);
                        }
                    }
                    #endregion

                    #region Lấy các phần tử là Enum
                    Sal_RevenueForShopEntity RevenueForShopItem = new Sal_RevenueForShopEntity();
                    RevenueForShopItem = listRevenueForShop.Where(m => m.ShopID == Guid && m.KPIBonusID == listKPIBonus.Where(t => t.IsTotalRevenue == true).FirstOrDefault().ID&& (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).FirstOrDefault();

                    if (RevenueForShopItem != null)
                    {
                        listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_TAGET_SHOP.ToString(), RevenueForShopItem.Target, 0));
                        listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_ACTUAL_SHOP.ToString(), RevenueForShopItem.Actual, 0));
                        listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_PRECENT_REVENUE.ToString(), RevenueForShopItem.Actual / RevenueForShopItem.Target, 0));
                    }
                    else
                    {
                        continue;
                    }

                    listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_COUNT_SHOPMEMBER.ToString(), listProfile.Where(m => m.ShopID == Guid).Count(), 0));

                    listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_COUNT_SL.ToString(), listShop.Where(m => m.ID == Guid).FirstOrDefault().NoShiftLeader, 0));

                    listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_RANK.ToString(), listShop.Where(m => m.ID == Guid).FirstOrDefault().Rank, 0));

                    #endregion


                    #region Lấy giá trị cho các loại phần tử là Hoa Hồng

                    double TotalMoney_RevenueForShop = 0;//biến lưu tổng doanh thu cửa hàng sau khi đã trừ tiền SL
                    if (listKPIBonus != null && listKPIBonus.Count > 0)
                    {
                        #region tính số tổng doanh thu sau khi trừ tiền SL

                        RevenueForShopItem = new Sal_RevenueForShopEntity();
                        RevenueForShopItem = listRevenueForShop.Where(m => m.ShopID == Guid && m.KPIBonusID == listKPIBonus.Where(t => t.IsTotalRevenue == true).FirstOrDefault().ID&& (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).FirstOrDefault();

                        double Money_SL = 0;
                        if (RevenueForShopItem != null)
                        {
                            Money_SL = (double)GetObjectValue(new List <Cat_ElementEntity>(), listElementFormula, listShop.Single(m => m.ID == Guid).Formular1).Value;
                            double Money_Revenue = (double)RevenueForShopItem.Actual * ((double)GetObjectValue(new List <Cat_ElementEntity>(), listElementFormula, listShop.Single(m => m.ID == Guid).Formular).Value / 100);
                            TotalMoney_RevenueForShop = Money_Revenue - Money_SL;
                        }

                        #endregion
                        Sal_RevenueRecord RecordItem = new Sal_RevenueRecord();
                        foreach (var j in listKPIBonus)
                        {
                            RevenueForShopItem = listRevenueForShop.Where(m => m.ShopID == Guid && m.KPIBonusID == j.ID && (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).FirstOrDefault();

                            RecordItem            = new Sal_RevenueRecord();
                            RecordItem.ShopID     = Guid;
                            RecordItem.Month      = Month;
                            RecordItem.KPIBonusID = j.ID;
                            RecordItem.Type       = EnumDropDown.SalesType.E_SALE.ToString();
                            RecordItem.Note       = string.Format("{0:n0}", Money_SL);

                            if ((RevenueForShopItem != null && RevenueForShopItem.Target <= RevenueForShopItem.Actual) || (RevenueForShopItem != null && RevenueForShopItem.IsPass != null && RevenueForShopItem.IsPass == true))
                            {
                                Cat_KPIBonusItemEntity bonusItem = listKPIBonusItem.Where(m => m.ShopID == Guid && m.KPIBonusID == j.ID).FirstOrDefault();
                                if (bonusItem != null)
                                {
                                    RecordItem.Amount = TotalMoney_RevenueForShop * (bonusItem.Value / 100);
                                }
                                else
                                {
                                    RecordItem.Amount = 0;
                                }
                            }
                            else
                            {
                                RecordItem.Amount = 0;
                            }
                            repoRevenueRecord.Add(RecordItem);
                        }

                        #region Lấy giá trị cho 2 enum là dòng sản phẩm và sản phẩm

                        //SAL_COM_PERCENT_SHOP_5
                        List <Sal_LineItemForShopEntity> listLineItem = listLineItemForShop.Where(m => m.ShopID == Guid && (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).ToList();

                        RecordItem        = new Sal_RevenueRecord();
                        RecordItem.ShopID = Guid;
                        RecordItem.Month  = Month;
                        RecordItem.Type   = EnumDropDown.SalesType.E_LINEITEM_MAJOR.ToString();

                        if (listLineItem != null && listLineItem.Count > 0 && listLineItem.Any(m => m.Actual < m.Target && m.IsPass != true))
                        {
                            int NumberPass = 0;
                            foreach (var lineItem in listLineItem)
                            {
                                if ((lineItem.IsPass != null && lineItem.IsPass == true) || lineItem.Actual >= lineItem.Target)
                                {
                                    NumberPass++;
                                }
                            }
                            if (NumberPass >= 3)
                            {
                                RecordItem.Amount = TotalMoney_RevenueForShop * (listShop.Single(m => m.ID == Guid).MainLineProduct / 100);
                            }
                            else
                            {
                                RecordItem.Amount = 0;
                            }
                        }
                        else
                        {
                            RecordItem.Amount = TotalMoney_RevenueForShop * (listShop.Single(m => m.ID == Guid).MainLineProduct / 100);
                        }
                        repoRevenueRecord.Add(RecordItem);

                        //SAL_COM_PERCENT_SHOP_6
                        List <Sal_ItemForShopEntity> listItem = listItemForShop.Where(m => m.ShopID == Guid && (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).ToList();

                        RecordItem        = new Sal_RevenueRecord();
                        RecordItem.ShopID = Guid;
                        RecordItem.Month  = Month;
                        RecordItem.Type   = EnumDropDown.SalesType.E_ITEM_MAJOR.ToString();

                        if (listItem != null && listItem.Count > 0 && listItem.Any(m => m.Actual < m.Target && m.IsPass != true))
                        {
                            RecordItem.Amount = 0;
                        }
                        else
                        {
                            RecordItem.Amount = TotalMoney_RevenueForShop * (listShop.Single(m => m.ID == Guid).PromoteProduct / 100);
                        }
                        repoRevenueRecord.Add(RecordItem);

                        #endregion
                    }
                    #endregion
                }
                repoRevenueRecord.SaveChanges();
            }
        }
Esempio n. 22
0
        private List <Att_AnnualDetail> AnalyzeAnnualDetail(List <Hre_ProfileMultiField> lstProfile, int Year, bool?isFullEmp, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork           = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_AnnualDetail = new CustomBaseRepository <Att_AnnualDetail>(unitOfWork);

                List <Att_AnnualDetail> lstResult    = new List <Att_AnnualDetail>();
                List <Guid>             lstProfileID = lstProfile.Select(m => m.ID).ToList();
                int      BeginMonth         = MonthStartAnl;
                DateTime BeginYear          = new DateTime(Year, BeginMonth, 1);
                DateTime EndYear            = BeginYear.AddYears(1).AddMinutes(-1);
                DateTime BeginYearToGetData = BeginYear.AddMonths(-1); //trừ một tháng để lấy data (bao những data thuộc những ngày trước tháng dành cho chế độ lương ko phải từ ngày 1)

                var         lstGradeCgf           = unitOfWork.CreateQueryable <Cat_GradeAttendance>().ToList();
                var         lstLeaveDayTypeAnnual = unitOfWork.CreateQueryable <Cat_LeaveDayType>(s => s.IsAnnualLeave == true).ToList();
                List <Guid> lstAnnualTypeID       = lstLeaveDayTypeAnnual.Select(s => s.ID).ToList();
                string      E_APPROVED            = LeaveDayStatus.E_APPROVED.ToString();



                var lstAnnualDetailInDB_Query = unitOfWork.CreateQueryable <Att_AnnualDetail>(m => m.ProfileID != null && m.Year == Year);
                var lstLeaveDayAnl_Query      = unitOfWork.CreateQueryable <Att_LeaveDay>(m =>
                                                                                          m.Status == E_APPROVED &&
                                                                                          m.DateStart <= EndYear &&
                                                                                          m.DateEnd >= BeginYearToGetData &&
                                                                                          m.LeaveDayTypeID != null &&
                                                                                          lstAnnualTypeID.Contains(m.LeaveDayTypeID));
                var lstAttGrade_Query      = unitOfWork.CreateQueryable <Att_Grade>();
                var lstAnualLeaveCfg_Query = unitOfWork.CreateQueryable <Att_AnnualLeave>(m => m.Year == Year);
                var lstlstRoster_Query     = unitOfWork.CreateQueryable <Att_Roster>(m =>
                                                                                     m.Status == E_APPROVED &&
                                                                                     m.DateStart <= EndYear &&
                                                                                     m.DateEnd >= BeginYearToGetData);
                if (isFullEmp != null && isFullEmp.Value == false)
                {
                    lstAnnualDetailInDB_Query = lstAnnualDetailInDB_Query.Where(m => m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value));
                    lstLeaveDayAnl_Query      = lstLeaveDayAnl_Query.Where(m => lstProfileID.Contains(m.ProfileID));
                    lstAttGrade_Query         = lstAttGrade_Query.Where(m => m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value));
                    lstAnualLeaveCfg_Query    = lstAnualLeaveCfg_Query.Where(m => lstProfileID.Contains(m.ProfileID));
                    lstlstRoster_Query        = lstlstRoster_Query.Where(m => lstProfileID.Contains(m.ProfileID));
                }

                var lstAnnualDetailInDB = lstAnnualDetailInDB_Query.ToList();
                var lstLeaveDayAnl      = lstLeaveDayAnl_Query.Select(m => new Att_LeaveDayInfo()
                {
                    ID = m.ID
                    ,
                    ProfileID = m.ProfileID
                    ,
                    DateStart = m.DateStart
                    ,
                    DateEnd = m.DateEnd
                    ,
                    LeaveDayTypeID = m.LeaveDayTypeID
                    ,
                    TotalDuration = m.TotalDuration
                    ,
                    Duration = m.Duration
                    ,
                    DurationType = m.DurationType
                    ,
                    LeaveDays = m.LeaveDays
                    ,
                    LeaveHours = m.LeaveHours
                }).ToList();
                var lstAttGrade      = lstAttGrade_Query.ToList();
                var lstAnualLeaveCfg = lstAnualLeaveCfg_Query.ToList();
                var lstRoster        = lstlstRoster_Query.Select(m => new Att_RosterInfo()
                {
                    ID = m.ID, ProfileID = m.ProfileID, Type = m.Type, MonShiftID = m.MonShiftID, TueShiftID = m.TueShiftID, WedShiftID = m.WedShiftID, ThuShiftID = m.ThuShiftID, FriShiftID = m.FriShiftID, SatShiftID = m.SatShiftID, SunShiftID = m.SunShiftID
                }).ToList();


                var lstRosterGroup = unitOfWork.CreateQueryable <Att_RosterGroup>(m => m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData).ToList();
                var lstDayOff      = unitOfWork.CreateQueryable <Cat_DayOff>(m => m.DateOff >= BeginYearToGetData && m.DateOff <= EndYear).ToList();

                // Phép Năm chốt Từ Ngày 1 -> 31 Hàng Tháng
                bool           IsFrom1To31 = false;
                string         type2       = AppConfig.HRM_ATT_ANNUALLEAVE_ANNUALBEGINMONTHTOENDMONTH.ToString();
                Sys_AllSetting sys_ANNUAL_BEGINMONTHTO_ENDMONTH = unitOfWork.CreateQueryable <Sys_AllSetting>(sy => sy.Name == type2).FirstOrDefault();
                if (sys_ANNUAL_BEGINMONTHTO_ENDMONTH != null && sys_ANNUAL_BEGINMONTHTO_ENDMONTH.Value1 == bool.TrueString)
                {
                    IsFrom1To31 = true;
                }
                List <Guid>         lstPositionIDs = lstProfile.Where(m => m.PositionID != null).Select(m => m.PositionID.Value).Distinct().ToList();
                List <Cat_Position> lstPosition    = unitOfWork.CreateQueryable <Cat_Position>(m => lstPositionIDs.Contains(m.ID)).ToList <Cat_Position>();
                var lstAllSetting = unitOfWork.CreateQueryable <Sys_AllSetting>().ToList();

                var lstHDTJob = new List <Hre_HDTJob>();
                foreach (var templstProfileId in lstProfileID.Chunk(1000))
                {
                    lstHDTJob.AddRange(unitOfWork.CreateQueryable <Hre_HDTJob>(Guid.Empty, m => m.ProfileID != null && templstProfileId.Contains(m.ProfileID.Value)).ToList());
                }
                foreach (var profile in lstProfile)
                {
                    var lstGradeByProfile    = lstAttGrade.Where(m => m.ProfileID == profile.ID).OrderByDescending(m => m.MonthStart).ToList();
                    var lstLeaveDayByprofile = lstLeaveDayAnl.Where(m => m.ProfileID == profile.ID).ToList();
                    var AnualLeaveCfg        = lstAnualLeaveCfg.Where(m => m.ProfileID == profile.ID).FirstOrDefault();
                    var lstRosterByProfile   = lstRoster.Where(m => m.ProfileID == profile.ID).ToList();
                    var position             = lstPosition.Where(m => m.ID == profile.PositionID).FirstOrDefault();

                    List <Att_AnnualDetail> lstAnnualDetailByProfile_Update = new List <Att_AnnualDetail>();

                    List <Att_AnnualDetail> lstAnnualDetailByProfile = AnalyzeAnnualDetailPerProfile(profile,
                                                                                                     lstGradeCgf, lstGradeByProfile, BeginYear, EndYear, lstLeaveDayByprofile, lstAnnualDetailInDB,
                                                                                                     AnualLeaveCfg, lstRosterByProfile, lstRosterGroup, lstDayOff, IsFrom1To31,
                                                                                                     position, lstAllSetting, lstHDTJob, out lstAnnualDetailByProfile_Update, userLogin);
                    lstResult.AddRange(lstAnnualDetailByProfile);
                    lstResult.AddRange(lstAnnualDetailByProfile_Update);
                    repoAtt_AnnualDetail.Add(lstAnnualDetailByProfile);
                    repoAtt_AnnualDetail.Edit(lstAnnualDetailByProfile_Update);
                }
                repoAtt_AnnualDetail.SaveChanges();
                return(lstResult);
            }
        }
Esempio n. 23
0
        public void SetSickLeaveBeginYear(List <Guid> lstProfileIDs, double?limitMaximum, int Year)
        {
            //Đối với phép ốm thì tạm thời tính từ đầu năm đến cuối năm
            using (var context = new VnrHrmDataContext())
            {
                var         unitOfWork           = (IUnitOfWork)(new UnitOfWork(context));
                var         repoAtt_AnnualLeave  = new CustomBaseRepository <Att_AnnualLeave>(unitOfWork);
                var         repoCat_LeaveDayType = new CustomBaseRepository <Cat_LeaveDayType>(unitOfWork);
                var         repoAtt_LeaveDay     = new CustomBaseRepository <Att_LeaveDay>(unitOfWork);
                int         LastYear             = Year - 1;
                DateTime    beginLastYear        = new DateTime(LastYear, 1, 1);
                DateTime    endLastYear          = beginLastYear.AddYears(1).AddMinutes(-1);
                List <Guid> SickLeaveType        = repoCat_LeaveDayType.FindBy(m => m.IsDelete == null && m.Code == "SICK").Select(m => m.ID).ToList();
                string      Approve     = LeaveDayStatus.E_APPROVED.ToString();
                var         lstLeaveDay = repoAtt_LeaveDay.FindBy(m =>
                                                                  m.IsDelete == null &&
                                                                  m.Status == Approve &&
                                                                  m.DateStart < endLastYear &&
                                                                  m.DateEnd >= beginLastYear &&
                                                                  SickLeaveType.Contains(m.LeaveDayTypeID) &&
                                                                  lstProfileIDs.Contains(m.ProfileID)).Select(m => new { m.ProfileID, m.TotalDuration }).ToList();

                List <Att_AnnualLeave> lstAnnualLeaveInDB = repoAtt_AnnualLeave.FindBy(m => m.IsDelete == null && (m.Year == Year || m.Year == LastYear) && lstProfileIDs.Contains(m.ProfileID)).ToList();

                foreach (var ProfileID in lstProfileIDs)
                {
                    Att_AnnualLeave AnnualLeaveByProfile      = lstAnnualLeaveInDB.Where(m => m.ProfileID == ProfileID && m.Year == Year).FirstOrDefault();
                    Att_AnnualLeave AnnualLeaveByProfile_Last = lstAnnualLeaveInDB.Where(m => m.ProfileID == ProfileID && m.Year == LastYear).FirstOrDefault();
                    bool            IsNew = false;
                    if (AnnualLeaveByProfile == null)
                    {
                        IsNew = true;
                        AnnualLeaveByProfile            = new Att_AnnualLeave();
                        AnnualLeaveByProfile.ID         = Guid.NewGuid();
                        AnnualLeaveByProfile.ProfileID  = ProfileID;
                        AnnualLeaveByProfile.Year       = Year;
                        AnnualLeaveByProfile.MonthStart = 1;
                    }

                    double InitLastYear = 0;
                    if (AnnualLeaveByProfile_Last != null)
                    {
                        InitLastYear = AnnualLeaveByProfile_Last.InitSickValue;
                    }
                    double remainLastYear = InitLastYear - lstLeaveDay.Where(m => m.ProfileID == ProfileID).Sum(m => m.TotalDuration ?? 0);
                    if (limitMaximum != null)
                    {
                        AnnualLeaveByProfile.InitSickValue       = remainLastYear > limitMaximum.Value ? limitMaximum.Value : remainLastYear;
                        AnnualLeaveByProfile.SurplusSicklastYear = remainLastYear > limitMaximum ? remainLastYear - limitMaximum : 0;
                    }
                    else
                    {
                        AnnualLeaveByProfile.InitSickValue       = remainLastYear;
                        AnnualLeaveByProfile.SurplusSicklastYear = 0;
                    }
                    if (IsNew)
                    {
                        repoAtt_AnnualLeave.Add(AnnualLeaveByProfile);
                    }
                    else
                    {
                        repoAtt_AnnualLeave.Edit(AnnualLeaveByProfile);
                    }
                }
                repoAtt_AnnualLeave.SaveChanges();
            }
        }
Esempio n. 24
0
        /// <summary>
        /// [Hieu.Van]
        /// Xử lý duyệt động đa cấp
        /// ProcessApproved (Tài khoản Login - LoginID, Value Dropdownlist - userApprovedID, Id Bản ghi - recordID, Enum màn hình - type)
        /// </summary>
        /// <param name="LoginID"></param>
        /// <param name="userApprovedID"></param>
        /// <param name="recordID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string ProcessApproved(string host, Guid LoginID, Guid userApprovedID, Guid recordID, string type)
        {
            DataErrorCode status = DataErrorCode.Success;
            string stt = string.Empty;
            var Services = new BaseService();
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoFIN_PurchaseRequest = new CustomBaseRepository<FIN_PurchaseRequest>(unitOfWork);
                var repoSys_UserApprove = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);
                var repoSys_ConfigProcessApprove = new CustomBaseRepository<Sys_ConfigProcessApprove>(unitOfWork);
                var UserLogin = string.Empty;
                var record = GetData<FIN_PurchaseRequestEntity>(recordID, ConstantSql.hrm_hr_sp_get_PurchaseRequestById, UserLogin, ref stt).FirstOrDefault();
                var configProcess = repoSys_ConfigProcessApprove.FindBy(s => s.IsDelete == null && s.Function == type && s.CurrentStatus == record.Status).FirstOrDefault();
                double total = record.Total != null ? record.Total.Value : 0.0;
                List<ElementFormula> listFomula = new List<ElementFormula>();
                ElementFormula FomulaItem = new ElementFormula("Total", total, 0);
                ElementFormula statusItem = new ElementFormula(configProcess.NextStatusFormular, configProcess.NextStatusFormular, 1);
                listFomula.Add(FomulaItem);
                listFomula.Add(statusItem);
                string nextStatus = Services.GetObjectValue(new List<Cat_ElementEntity>(), listFomula, configProcess.NextStatusFormular).ToString();


                if (configProcess != null && userApprovedID == Guid.Empty && nextStatus != "Approved")
                {
                    return DataErrorCode.Error_NoUserApproved.ToString();
                }
                if (record.Status == EnumDropDown.Status.E_REJECTED.ToString())
                {
                    return DataErrorCode.Error_Reject.ToString();
                }
                var recordEdit = repoFIN_PurchaseRequest.FindBy(s => s.ID == recordID).FirstOrDefault();
                // lấy UserInfoID hiện tại của bản ghi
                var userApprovedCurrent = repoSys_UserApprove.FindBy(s => s.ID == recordEdit.UserApproveID).FirstOrDefault();
                // Kiểm tra tài khoản login có được phép Duyệt hay ko?
                if (LoginID == Guid.Empty || userApprovedCurrent.UserApproveID != LoginID)
                {
                    // kiểm tra nếu bản ghi có tk duyệt trống (tức bản ghi mới tạo) và tk login = tk tạo thì cho duyệt tiếp tục
                    if (recordEdit.UserApproveID == null && record.UserCreateID == LoginID)
                    {
                    }
                    else
                    {
                        return DataErrorCode.NoPermission.ToString();
                    }
                }
                recordEdit.Status = nextStatus;
                if (userApprovedID == Guid.Empty)
                {
                    recordEdit.UserApproveID = null;
                }
                else
                {
                    recordEdit.UserApproveID = userApprovedID;
                }
                repoFIN_PurchaseRequest.Edit(recordEdit);
                status = repoFIN_PurchaseRequest.SaveChanges();

                if (nextStatus != "Approved")
                {
                    status = SendMail_ToNextApproved(host, recordID, userApprovedID, nextStatus, type);
                }

                if (status == DataErrorCode.Success)
                {
                    //var configProcess = repoSys_ConfigProcessApprove.FindBy(s => s.IsDelete == null && s.Function == type && s.CurrentStatus == nextStatus).FirstOrDefault();
                    if (nextStatus == "Approved")
                    {
                        return DataErrorCode.Success.ToString();
                    }
                    else
                    {
                        return DataErrorCode.Success_Forward.ToString();
                    }
                }

                return status.ToString();
            }
        }
Esempio n. 25
0
        /// <summary>
        /// [Hieu.Van]
        /// Xử lý Gửi yêu cầu phê duyệt
        /// </summary>
        /// <param name="LoginID"></param>
        /// <param name="userApprovedID"></param>
        /// <param name="recordID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string ProcessSendRequest(string host, Guid LoginID, Guid userApprovedID, Guid recordID, string type)
        {
            DataErrorCode status = DataErrorCode.Success;
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoFIN_PurchaseRequest = new CustomBaseRepository<FIN_PurchaseRequest>(unitOfWork);
                var repoSys_UserApprove = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);

                var record = repoFIN_PurchaseRequest.FindBy(s => s.ID == recordID).FirstOrDefault();
                if (record.UserCreateID != LoginID)
                {
                    return DataErrorCode.NoPermission.ToString();
                }
                if (record.Status == EnumDropDown.Status.E_REJECTED.ToString())
                {
                    return DataErrorCode.Error_Reject.ToString();
                }
                if (record.Status != null)
                {
                    return DataErrorCode.Error_SendRequest.ToString();
                }
                var userApproved = repoSys_UserApprove.FindBy(s => s.ID == userApprovedID).FirstOrDefault();
                // Lấy status hiện tại của bản ghi
                string currentStatus = record.Status;

                // truyền từ Dropdownlist chọn người duyệt, lấy ra giá trị Status tiếp theo
                string nextStatus = userApproved.CurrentStatus;

                record.Status = nextStatus;
                record.UserApproveID = userApprovedID;
                repoFIN_PurchaseRequest.Edit(record);
                status = repoFIN_PurchaseRequest.SaveChanges();

                
                if (status == DataErrorCode.Success)
                {
                    if (nextStatus != "Approved")
                    {
                        status = SendMail_ToNextApproved(host, recordID, userApprovedID, nextStatus, type);
                    }

                    var repoSys_ConfigProcessApprove = new CustomBaseRepository<Sys_ConfigProcessApprove>(unitOfWork);
                    var configProcess = repoSys_ConfigProcessApprove.FindBy(s => s.IsDelete == null && s.Function == type && s.CurrentStatus == record.Status).FirstOrDefault();
                    if (configProcess == null)
                    {
                        return DataErrorCode.Success.ToString();
                    }
                    else
                    {
                        return DataErrorCode.Success_Forward.ToString();
                    }
                }

                return status.ToString();
            }
        }
Esempio n. 26
0
        public void AddDataForBasicSalary(string ProfileIDs, string BasicSalary, DateTime DateHire, Guid SalaryRankID,string UserLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                string status = string.Empty;
                var repoBasicSalary = new CustomBaseRepository<Sal_BasicSalary>(unitOfWork);
                List<Guid> lstProfileIDs = ProfileIDs.Split(',').Select(x => Guid.Parse(x)).ToList();
                List<Sal_BasicSalary> lstBasicSalary = new List<Sal_BasicSalary>();
                //chua co cach giai quyet nen hard code lay mac dinh la VND
                var repoCurrency = new CustomBaseRepository<Cat_Currency>(unitOfWork);
                var currency = repoCurrency.FindBy(s => s.IsDelete == null && s.CurrencyName == "VND").FirstOrDefault();
                //var repoSalaryRank = new CustomBaseRepository<Cat_SalaryRank>(unitOfWork);
                //var repoSalaryClass = new CustomBaseRepository<Cat_SalaryClass>(unitOfWork);
                //var salaryRank = repoSalaryRank.FindBy(s => s.IsDelete == null && s.ID == SalaryRankID).FirstOrDefault();
                //var salaryClass = repoSalaryClass.FindBy(s => s.IsDelete == null && s.ID == salaryRank.SalaryClassID).FirstOrDefault();
                var salaryRankServices = new Cat_SalaryRankServices();
                var lstObjRank = new List<object>();
                lstObjRank.Add(null);
                lstObjRank.Add(null);
                lstObjRank.Add(1);
                lstObjRank.Add(int.MaxValue -1);
                var lstRank = salaryRankServices.GetData<Cat_SalaryRankEntity>(lstObjRank, ConstantSql.hrm_cat_sp_get_SalaryRank, UserLogin, ref status).ToList().Translate<Cat_SalaryRank>();
                var rankEntity = lstRank.Where(s => s.ID == SalaryRankID).FirstOrDefault();

                var salaryClassServices = new Cat_SalaryClassServices();
                var lstObjClass = new List<object>();
                lstObjClass.Add(null);
                lstObjClass.Add(1);
                lstObjClass.Add(int.MaxValue -1);
                var salaryClass = salaryClassServices.GetData<Cat_SalaryClassEntity>(lstObjClass, ConstantSql.hrm_cat_sp_get_SalaryClass, UserLogin, ref status).ToList().Translate<Cat_SalaryClass>();
                
                var salaryClassEntity = salaryClass.Where(s => rankEntity.SalaryClassID == s.ID).FirstOrDefault();
               
                foreach (var item in lstProfileIDs)
                {
                    Sal_BasicSalary objBasicSalary = new Sal_BasicSalary();
                    objBasicSalary.ProfileID = item;
                    objBasicSalary.GrossAmount = BasicSalary;
                    objBasicSalary.Amount = BasicSalary.Encrypt(); 
                    objBasicSalary.DateOfEffect = DateHire;
                    objBasicSalary.RankRateID = SalaryRankID;
                    objBasicSalary.CurrencyID = currency.ID;
                    objBasicSalary.ClassRateID = salaryClassEntity == null ? Guid.Empty : salaryClassEntity.ID;
                    lstBasicSalary.Add(objBasicSalary);
                }

                repoBasicSalary.Add(lstBasicSalary);
                repoBasicSalary.SaveChanges();


            }
        }
        /// <summary>
        /// Button Tính Phép Bệnh
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="orgStructure"></param>
        /// <param name="LstProfileStatus"></param>
        /// <returns></returns>
        public bool ComputeAnnualSickLeaveDetail(int Year, string orgStructure, string LstProfileStatus, string UserLogin)
        {
            var result = false;
            using (var context = new VnrHrmDataContext())
            {
                string status = string.Empty;
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoAtt_AnnualLeaveDetail = new CustomBaseRepository<Att_AnnualLeaveDetail>(unitOfWork);
                var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoHre_HDTJob = new CustomBaseRepository<Hre_HDTJob>(unitOfWork);
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
                var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
                var repoCat_JobTitle = new CustomBaseRepository<Cat_JobTitle>(unitOfWork);


                #region FilterInfo
                string E_SICK_LEAVE = AnnualLeaveDetailType.E_SICK_LEAVE.ToString();

                Att_AnnualLeaveDetail AnnualLeaveDetailTop = repoAtt_AnnualLeaveDetail
                    .FindBy(m => m.IsDelete == null && m.Type == E_SICK_LEAVE && m.Year == Year).FirstOrDefault();

                DateTime beginyear = (AnnualLeaveDetailTop == null || AnnualLeaveDetailTop.MonthStart == null) ? new DateTime(Year, 1, 1) : AnnualLeaveDetailTop.MonthStart.Value;
                DateTime endYear = beginyear.AddYears(1).AddMinutes(-1);

                List<object> lstObj = new List<object>();
                lstObj.Add(orgStructure);
                lstObj.Add(null);
                lstObj.Add(null);
                var lstProfileQuery = GetData<Hre_ProfileEntity>(lstObj, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrg, UserLogin, ref status).ToList();

                if (LstProfileStatus != null)
                {
                    if (LstProfileStatus == StatusEmpLeaveDetail.E_NEWEMPINYEAR.ToString())
                    {
                        lstProfileQuery = lstProfileQuery.Where(m => m.DateHire != null && m.DateHire >= beginyear && m.DateHire <= endYear).ToList();
                    }
                    if (LstProfileStatus == StatusEmpLeaveDetail.E_RESIGNEMPINYEAR.ToString())
                    {
                        lstProfileQuery = lstProfileQuery.Where(m => m.DateQuit != null && m.DateQuit >= beginyear && m.DateQuit <= endYear).ToList();
                    }
                    if (LstProfileStatus == StatusEmpLeaveDetail.E_EMPOFHDT4.ToString())
                    {
                        string Job4 = HDTJobType.E_Four.ToString();
                        List<Guid> lstprofileHDT4 = repoHre_HDTJob
                            .FindBy(m => m.IsDelete == null && m.Type == Job4 && m.DateFrom <= endYear && m.DateTo >= beginyear && m.ProfileID != null)
                            .Select(m => m.ProfileID.Value).ToList<Guid>();
                        lstProfileQuery = lstProfileQuery.Where(m => lstprofileHDT4.Contains(m.ID)).ToList();
                    }
                    if (LstProfileStatus == StatusEmpLeaveDetail.E_EMPOFHDT5.ToString())
                    {
                        string Job5 = HDTJobType.E_Five.ToString();
                        List<Guid> lstprofileHDT5 = repoHre_HDTJob
                            .FindBy(m => m.IsDelete == null && m.Type == Job5 && m.DateFrom <= endYear && m.DateTo >= beginyear && m.ProfileID != null)
                            .Select(m => m.ProfileID.Value).ToList<Guid>();
                        lstProfileQuery = lstProfileQuery.Where(m => lstprofileHDT5.Contains(m.ID)).ToList();
                    }
                }

                List<Guid> lstProfileID = lstProfileQuery.Select(m => m.ID).Distinct().ToList<Guid>();
                #endregion
                #region get Data
                //string E_STANDARD_WORKDAY = AppConfig.E_STANDARD_WORKDAY.ToString();
                //Sys_AppConfig appconfig = EntityService.CreateQueryable<Sys_AppConfig>(false, GuidContext, Guid.Empty, m => m.Info == E_STANDARD_WORKDAY).FirstOrDefault();
                //if (appconfig == null || string.IsNullOrEmpty(appconfig.Value76) || string.IsNullOrEmpty(appconfig.Value77))
                //{
                //    Common.MessageBoxs(Messages.Msg, Messages.PleaseConfigSickLeaveAtTotalConfig, MessageBox.Icon.WARNING, string.Empty);
                //    return;
                //}

                string HRM_ATT_ANNUALSICKLEAVE_ = AppConfig.HRM_ATT_ANNUALSICKLEAVE_.ToString();
                List<object> lstO = new List<object>();
                lstO.Add(HRM_ATT_ANNUALSICKLEAVE_);
                lstO.Add(null);
                lstO.Add(null);
                var config = GetData<Sys_AllSettingEntity>(lstO, ConstantSql.hrm_sys_sp_get_AllSetting, UserLogin, ref status);

                var formular1 = config.Where(s => s.Name == AppConfig.HRM_ATT_ANNUALSICKLEAVE_FORMULARCONFIG.ToString()).FirstOrDefault();
                var formular2 = config.Where(s => s.Name == AppConfig.HRM_ATT_ANNUALSICKLEAVE_FORMULARCOMPUTE.ToString()).FirstOrDefault();

                if (config == null || string.IsNullOrEmpty(formular1.Value1) || string.IsNullOrEmpty(formular2.Value1))
                {
                    //Common.MessageBoxs(Messages.Msg, Messages.PleaseConfigAnnualLeaveAtTotalConfig, MessageBox.Icon.WARNING, string.Empty);
                    return result;
                }

                string formularConfig = formular1.Value1;
                string formularCompute = formular2.Value1;

                ParamGetConfigANL configAnl = new ParamGetConfigANL();
                (new Att_AttendanceServices()).GetConfigANL(formularConfig, out configAnl);

                int MonthBegin = 1;
                List<string> lstCodeLeaveTypeNonAnl = new List<string>();
                if (configAnl != null && configAnl.monthBeginYear != null)
                {
                    MonthBegin = configAnl.monthBeginYear;
                }
                if (configAnl != null && configAnl.lstCodeLeaveNonANL != null)
                {
                    lstCodeLeaveTypeNonAnl = configAnl.lstCodeLeaveNonANL;
                }
                DateTime BeginYear = new DateTime(Year, MonthBegin, 1);
                DateTime EndYear = BeginYear.AddYears(1).AddMinutes(-1);

                string E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();
                List<DateTime> lstDayOff = repoCat_DayOff
                    .FindBy(m => m.IsDelete == null && m.DateOff > BeginYear && m.DateOff <= EndYear)
                    .Select(m => m.DateOff).Distinct().ToList<DateTime>();
                List<Hre_ProfileEntity> lstprofile = lstProfileQuery
                    .Where(m => m.DateQuit == null || (m.DateQuit != null && m.DateQuit > BeginYear))
                    .ToList<Hre_ProfileEntity>();
                List<Guid> lstLeavedayTypeNonAnl = repoCat_LeaveDayType
                    .FindBy(m => m.IsDelete == null && lstCodeLeaveTypeNonAnl.Contains(m.Code)).Select(m => m.ID).ToList<Guid>();
                List<Att_LeaveDay> lstleavedayNonANl = repoAtt_LeaveDay
                    .FindBy(m => m.IsDelete == null && m.Status == E_APPROVED && lstLeavedayTypeNonAnl.Contains(m.LeaveDayTypeID)
                        && lstProfileID.Contains(m.ProfileID)).ToList<Att_LeaveDay>();
                List<Att_LeaveDay> lstleavedayNonANlInYear = lstleavedayNonANl.Where(m => m.DateStart <= EndYear && m.DateEnd >= BeginYear).ToList<Att_LeaveDay>();
                List<Hre_HDTJob> lstHDTJob = repoHre_HDTJob
                    .FindBy(m => m.IsDelete == null && m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value)).ToList<Hre_HDTJob>();
                List<Cat_JobTitle> lstJobtitle = repoCat_JobTitle.FindBy(s => s.IsDelete == null).ToList();
                #endregion

                List<Att_AnnualLeaveDetail> lstAnnualDetail = new List<Att_AnnualLeaveDetail>();
                foreach (var item in lstprofile)
                {
                    List<Att_LeaveDay> lstLeavedayNonAnlByProfile = lstleavedayNonANl.Where(m => m.ProfileID == item.ID).ToList();
                    List<Att_LeaveDay> lstLeavedayNonAnlByProfileInYear = lstleavedayNonANlInYear.Where(m => m.ProfileID == item.ID).ToList();
                    List<Hre_HDTJob> lstHDTJobByProfile = lstHDTJob.Where(m => m.ProfileID == item.ID).ToList();
                    double AvailabelInYear = (new Att_AttendanceServices()).GetAnnualLeaveAvailableAllYear(Year, null, item.DateHire,
                        item.DateEndProbation, item.DateQuit, formularConfig,
                        formularCompute, lstLeavedayNonAnlByProfileInYear, lstJobtitle, lstDayOff, lstHDTJobByProfile, lstLeavedayNonAnlByProfile);
                    Att_AnnualLeaveDetail annualProfile = new Att_AnnualLeaveDetail();
                    annualProfile.ID = Guid.NewGuid();
                    annualProfile.ProfileID = item.ID;
                    annualProfile.MonthStart = BeginYear;
                    annualProfile.MonthEnd = EndYear;
                    annualProfile.Year = Year;
                    annualProfile.Type = E_SICK_LEAVE;
                    annualProfile.Month1 = AvailabelInYear;
                    annualProfile.Month2 = AvailabelInYear;
                    annualProfile.Month3 = AvailabelInYear;
                    annualProfile.Month4 = AvailabelInYear;
                    annualProfile.Month5 = AvailabelInYear;
                    annualProfile.Month6 = AvailabelInYear;
                    annualProfile.Month7 = AvailabelInYear;
                    annualProfile.Month8 = AvailabelInYear;
                    annualProfile.Month9 = AvailabelInYear;
                    annualProfile.Month10 = AvailabelInYear;
                    annualProfile.Month11 = AvailabelInYear;
                    annualProfile.Month12 = AvailabelInYear;
                    lstAnnualDetail.Add(annualProfile);
                }

                DataErrorCode DataErr = DataErrorCode.Unknown;

                if (lstAnnualDetail.Count > 0)
                {
                    #region lấy dữ liệu dưới DB xóa đi
                    List<Guid> lstProfileID_InDB = lstAnnualDetail.Where(m => m.ProfileID != null).Select(m => m.ProfileID.Value).ToList();


                    List<Att_AnnualLeaveDetail> lstAnnualLeaveDetail_InDB = repoAtt_AnnualLeaveDetail
                        .FindBy(m => m.IsDelete == null && m.Year == Year && m.Type == E_SICK_LEAVE && m.ProfileID != null && lstProfileID_InDB.Contains(m.ProfileID.Value)).ToList<Att_AnnualLeaveDetail>();
                    foreach (var item in lstAnnualLeaveDetail_InDB)
                    {
                        item.IsDelete = true;
                    }
                    #endregion

                    repoAtt_AnnualLeaveDetail.Add(lstAnnualDetail);
                    try
                    {
                        repoAtt_AnnualLeaveDetail.SaveChanges();
                    }
                    catch (Exception)
                    {
                        return false;
                    }

                    //EntityService.AddEntity<Att_AnnualLeaveDetail>(GuidContext, lstAnnualDetail.ToArray());
                    //DataErr = EntityService.SubmitChanges(GuidContext, LoginUserID);

                    //if (DataErr == DataErrorCode.Success)
                    //{
                    //    Common.MessageBoxs(Messages.Msg, Messages.SaveSuccess, MessageBox.Icon.INFO, string.Empty);
                    //}
                    //else
                    //{
                    //    Common.MessageBoxs(Messages.Msg, Messages.SaveUnSuccess, MessageBox.Icon.INFO, string.Empty);
                    //}
                }
                //else
                //{
                //    Common.MessageBoxs(Messages.Msg, Messages.NoDataToCompute, MessageBox.Icon.WARNING, string.Empty);
                //}
                result = true;
            }
            return result;
        }
Esempio n. 28
0
        public void UpdateStatusApprovedProfile(string selectedIds)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoProfile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoWorkHistory = new CustomBaseRepository<Hre_WorkHistory>(unitOfWork);
                var repoContract = new CustomBaseRepository<Hre_Contract>(unitOfWork);
                var repoBasicSalary = new CustomBaseRepository<Sal_BasicSalary>(unitOfWork);
                List<Guid> lstProfileIds = selectedIds.Split(',').Select(x => Guid.Parse(x)).ToList();
                List<Hre_Profile> lstProfile = repoProfile.FindBy(x => lstProfileIds.Contains(x.ID)).ToList();
                var lstWorkHistoty = repoWorkHistory.FindBy(x => lstProfileIds.Contains(x.ProfileID) && x.IsDelete == null).ToList();
                var lstContract = repoContract.FindBy(x => lstProfileIds.Contains(x.ProfileID) && x.IsDelete == null).ToList();
                var lstBasicSalary = repoBasicSalary.FindBy(x => lstProfileIds.Contains(x.ProfileID) && x.IsDelete == null).ToList();
                // cập nhật StatusSyn="E_HIRE"
                foreach (var item in lstProfile)
                {
                    item.StatusSyn = ProfileStatusSyn.E_HIRE.ToString();
                }
                repoProfile.SaveChanges();
                if (lstWorkHistoty != null && lstWorkHistoty.Count != 0)
                {
                    // lấy ngày mới nhất để cập nhật Status là E_Approved (Hre_WorkHistory) dửa vào DateEffective
                    var WorkHistoty = lstWorkHistoty.OrderByDescending(x => x.DateEffective).FirstOrDefault();
                    WorkHistoty.Status = WorkHistoryStatus.E_APPROVED.ToString();
                    repoWorkHistory.SaveChanges();

                }
                if (lstContract != null && lstContract.Count != 0)
                {
                    // lấy ngày mới nhất để cập nhật Status là E_Approved (Hre_Contract) dựa vào DateSigned
                    var Contract = lstContract.OrderByDescending(x => x.DateSigned).FirstOrDefault();
                    Contract.Status = "E_APPROVED";
                    repoContract.SaveChanges();

                }
                if (lstBasicSalary != null && lstBasicSalary.Count != 0)
                {
                    // lấy ngày mới nhất để cập nhật Status là E_Approved (Sal_BasicSalary) dựa vào DateOfEffect
                    var BasicSalary = lstBasicSalary.OrderByDescending(x => x.DateOfEffect).FirstOrDefault();
                    BasicSalary.Status = "E_APPROVED";
                    repoBasicSalary.SaveChanges();

                }

            }

        }
Esempio n. 29
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;
                }
            }
        }
Esempio n. 30
0
        private List<Att_AnnualDetail> AnalyzeAnnualDetail(List<Hre_ProfileMultiField> lstProfile, int Year, bool? isFullEmp, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_AnnualDetail = new CustomBaseRepository<Att_AnnualDetail>(unitOfWork);

                List<Att_AnnualDetail> lstResult = new List<Att_AnnualDetail>();
                List<Guid> lstProfileID = lstProfile.Select(m => m.ID).ToList();
                int BeginMonth = MonthStartAnl;
                DateTime BeginYear = new DateTime(Year, BeginMonth, 1);
                DateTime EndYear = BeginYear.AddYears(1).AddMinutes(-1);
                DateTime BeginYearToGetData = BeginYear.AddMonths(-1); //trừ một tháng để lấy data (bao những data thuộc những ngày trước tháng dành cho chế độ lương ko phải từ ngày 1)

                var lstGradeCgf = unitOfWork.CreateQueryable<Cat_GradeAttendance>().ToList();
                var lstLeaveDayTypeAnnual = unitOfWork.CreateQueryable<Cat_LeaveDayType>(s => s.IsAnnualLeave == true).ToList();
                List<Guid> lstAnnualTypeID = lstLeaveDayTypeAnnual.Select(s => s.ID).ToList();
                string E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();



                var lstAnnualDetailInDB_Query = unitOfWork.CreateQueryable<Att_AnnualDetail>(m => m.ProfileID != null && m.Year == Year);
                var lstLeaveDayAnl_Query = unitOfWork.CreateQueryable<Att_LeaveDay>(m =>
                    m.Status == E_APPROVED
                    && m.DateStart <= EndYear
                    && m.DateEnd >= BeginYearToGetData
                    && m.LeaveDayTypeID != null
                    && lstAnnualTypeID.Contains(m.LeaveDayTypeID));
                var lstAttGrade_Query = unitOfWork.CreateQueryable<Att_Grade>();
                var lstAnualLeaveCfg_Query = unitOfWork.CreateQueryable<Att_AnnualLeave>(m => m.Year == Year);
                var lstlstRoster_Query = unitOfWork.CreateQueryable<Att_Roster>(m =>
                    m.Status == E_APPROVED
                    && m.DateStart <= EndYear
                    && m.DateEnd >= BeginYearToGetData);
                if (isFullEmp != null && isFullEmp.Value == false)
                {
                    lstAnnualDetailInDB_Query = lstAnnualDetailInDB_Query.Where(m => m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value));
                    lstLeaveDayAnl_Query = lstLeaveDayAnl_Query.Where(m => lstProfileID.Contains(m.ProfileID));
                    lstAttGrade_Query = lstAttGrade_Query.Where(m => m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value));
                    lstAnualLeaveCfg_Query = lstAnualLeaveCfg_Query.Where(m => lstProfileID.Contains(m.ProfileID));
                    lstlstRoster_Query = lstlstRoster_Query.Where(m => lstProfileID.Contains(m.ProfileID));
                }

                var lstAnnualDetailInDB = lstAnnualDetailInDB_Query.ToList();
                var lstLeaveDayAnl = lstLeaveDayAnl_Query.Select(m => new Att_LeaveDayInfo()
                {
                    ID = m.ID
                    ,
                    ProfileID = m.ProfileID
                    ,
                    DateStart = m.DateStart
                    ,
                    DateEnd = m.DateEnd
                    ,
                    LeaveDayTypeID = m.LeaveDayTypeID
                    ,
                    TotalDuration = m.TotalDuration
                    ,
                    Duration = m.Duration
                    ,
                    DurationType = m.DurationType
                    ,
                    LeaveDays = m.LeaveDays
                    ,
                    LeaveHours = m.LeaveHours
                }).ToList();
                var lstAttGrade = lstAttGrade_Query.ToList();
                var lstAnualLeaveCfg = lstAnualLeaveCfg_Query.ToList();
                var lstRoster = lstlstRoster_Query.Select(m => new Att_RosterInfo() { ID = m.ID, ProfileID = m.ProfileID, Type = m.Type, MonShiftID = m.MonShiftID, TueShiftID = m.TueShiftID, WedShiftID = m.WedShiftID, ThuShiftID = m.ThuShiftID, FriShiftID = m.FriShiftID, SatShiftID = m.SatShiftID, SunShiftID = m.SunShiftID }).ToList();


                var lstRosterGroup = unitOfWork.CreateQueryable<Att_RosterGroup>(m => m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData).ToList();
                var lstDayOff = unitOfWork.CreateQueryable<Cat_DayOff>(m => m.DateOff >= BeginYearToGetData && m.DateOff <= EndYear).ToList();

                // Phép Năm chốt Từ Ngày 1 -> 31 Hàng Tháng 
                bool IsFrom1To31 = false;
                string type2 = AppConfig.HRM_ATT_ANNUALLEAVE_ANNUALBEGINMONTHTOENDMONTH.ToString();
                Sys_AllSetting sys_ANNUAL_BEGINMONTHTO_ENDMONTH = unitOfWork.CreateQueryable<Sys_AllSetting>(sy => sy.Name == type2).FirstOrDefault();
                if (sys_ANNUAL_BEGINMONTHTO_ENDMONTH != null && sys_ANNUAL_BEGINMONTHTO_ENDMONTH.Value1 == bool.TrueString)
                {
                    IsFrom1To31 = true;
                }
                List<Guid> lstPositionIDs = lstProfile.Where(m => m.PositionID != null).Select(m => m.PositionID.Value).Distinct().ToList();
                List<Cat_Position> lstPosition = unitOfWork.CreateQueryable<Cat_Position>(m => lstPositionIDs.Contains(m.ID)).ToList<Cat_Position>();
                var lstAllSetting = unitOfWork.CreateQueryable<Sys_AllSetting>().ToList();

                var lstHDTJob=new List<Hre_HDTJob>();
                foreach (var templstProfileId in lstProfileID.Chunk(1000))
                {
                    lstHDTJob.AddRange(unitOfWork.CreateQueryable<Hre_HDTJob>(Guid.Empty, m => m.ProfileID != null && templstProfileId.Contains(m.ProfileID.Value)).ToList());
                }
                foreach (var profile in lstProfile)
                {
                    var lstGradeByProfile = lstAttGrade.Where(m => m.ProfileID == profile.ID).OrderByDescending(m => m.MonthStart).ToList();
                    var lstLeaveDayByprofile = lstLeaveDayAnl.Where(m => m.ProfileID == profile.ID).ToList();
                    var AnualLeaveCfg = lstAnualLeaveCfg.Where(m => m.ProfileID == profile.ID).FirstOrDefault();
                    var lstRosterByProfile = lstRoster.Where(m => m.ProfileID == profile.ID).ToList();
                    var position = lstPosition.Where(m => m.ID == profile.PositionID).FirstOrDefault();

                    List<Att_AnnualDetail> lstAnnualDetailByProfile_Update = new List<Att_AnnualDetail>();

                    List<Att_AnnualDetail> lstAnnualDetailByProfile = AnalyzeAnnualDetailPerProfile(profile,
                        lstGradeCgf, lstGradeByProfile, BeginYear, EndYear, lstLeaveDayByprofile, lstAnnualDetailInDB,
                        AnualLeaveCfg, lstRosterByProfile, lstRosterGroup, lstDayOff, IsFrom1To31,
                        position, lstAllSetting, lstHDTJob, out  lstAnnualDetailByProfile_Update, userLogin);
                    lstResult.AddRange(lstAnnualDetailByProfile);
                    lstResult.AddRange(lstAnnualDetailByProfile_Update);
                    repoAtt_AnnualDetail.Add(lstAnnualDetailByProfile);
                    repoAtt_AnnualDetail.Edit(lstAnnualDetailByProfile_Update);
                }
                repoAtt_AnnualDetail.SaveChanges();
                return lstResult;
            }
        }
Esempio n. 31
0
        /// <summary>
        /// [Hieu.Van]
        /// Xử lý duyệt động đa cấp
        /// ProcessApproved (Tài khoản Login - LoginID, Value Dropdownlist - userApprovedID, Id Bản ghi - recordID, Enum màn hình - type)
        /// </summary>
        /// <param name="LoginID"></param>
        /// <param name="userApprovedID"></param>
        /// <param name="recordID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string ProcessApproved(string host, Guid LoginID, Guid userApprovedID, Guid recordID, string type)
        {
            DataErrorCode status   = DataErrorCode.Success;
            string        stt      = string.Empty;
            var           Services = new BaseService();

            using (var context = new VnrHrmDataContext())
            {
                var    unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var    repoFIN_PurchaseRequest      = new CustomBaseRepository <FIN_PurchaseRequest>(unitOfWork);
                var    repoSys_UserApprove          = new CustomBaseRepository <Sys_UserApprove>(unitOfWork);
                var    repoSys_ConfigProcessApprove = new CustomBaseRepository <Sys_ConfigProcessApprove>(unitOfWork);
                var    UserLogin                 = string.Empty;
                var    record                    = GetData <FIN_PurchaseRequestEntity>(recordID, ConstantSql.hrm_hr_sp_get_PurchaseRequestById, UserLogin, ref stt).FirstOrDefault();
                var    configProcess             = repoSys_ConfigProcessApprove.FindBy(s => s.IsDelete == null && s.Function == type && s.CurrentStatus == record.Status).FirstOrDefault();
                double total                     = record.Total != null ? record.Total.Value : 0.0;
                List <ElementFormula> listFomula = new List <ElementFormula>();
                ElementFormula        FomulaItem = new ElementFormula("Total", total, 0);
                ElementFormula        statusItem = new ElementFormula(configProcess.NextStatusFormular, configProcess.NextStatusFormular, 1);
                listFomula.Add(FomulaItem);
                listFomula.Add(statusItem);
                string nextStatus = Services.GetObjectValue(new List <Cat_ElementEntity>(), listFomula, configProcess.NextStatusFormular).ToString();


                if (configProcess != null && userApprovedID == Guid.Empty && nextStatus != "Approved")
                {
                    return(DataErrorCode.Error_NoUserApproved.ToString());
                }
                if (record.Status == EnumDropDown.Status.E_REJECTED.ToString())
                {
                    return(DataErrorCode.Error_Reject.ToString());
                }
                var recordEdit = repoFIN_PurchaseRequest.FindBy(s => s.ID == recordID).FirstOrDefault();
                // lấy UserInfoID hiện tại của bản ghi
                var userApprovedCurrent = repoSys_UserApprove.FindBy(s => s.ID == recordEdit.UserApproveID).FirstOrDefault();
                // Kiểm tra tài khoản login có được phép Duyệt hay ko?
                if (LoginID == Guid.Empty || userApprovedCurrent.UserApproveID != LoginID)
                {
                    // kiểm tra nếu bản ghi có tk duyệt trống (tức bản ghi mới tạo) và tk login = tk tạo thì cho duyệt tiếp tục
                    if (recordEdit.UserApproveID == null && record.UserCreateID == LoginID)
                    {
                    }
                    else
                    {
                        return(DataErrorCode.NoPermission.ToString());
                    }
                }
                recordEdit.Status = nextStatus;
                if (userApprovedID == Guid.Empty)
                {
                    recordEdit.UserApproveID = null;
                }
                else
                {
                    recordEdit.UserApproveID = userApprovedID;
                }
                repoFIN_PurchaseRequest.Edit(recordEdit);
                status = repoFIN_PurchaseRequest.SaveChanges();

                if (nextStatus != "Approved")
                {
                    status = SendMail_ToNextApproved(host, recordID, userApprovedID, nextStatus, type);
                }

                if (status == DataErrorCode.Success)
                {
                    //var configProcess = repoSys_ConfigProcessApprove.FindBy(s => s.IsDelete == null && s.Function == type && s.CurrentStatus == nextStatus).FirstOrDefault();
                    if (nextStatus == "Approved")
                    {
                        return(DataErrorCode.Success.ToString());
                    }
                    else
                    {
                        return(DataErrorCode.Success_Forward.ToString());
                    }
                }

                return(status.ToString());
            }
        }
Esempio n. 32
0
        public List<Can_MealRecordEntity> GetMealRecordSummary(string _line, string _catering, string _canteen, DateTime dateStart, DateTime dateEnd, List<Hre_ProfileEntity> lstProfileIDs, string UserLogin)
        {
            dateStart = dateStart.Date;
            dateEnd = dateEnd.Date.AddDays(1).AddMilliseconds(-1);

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoCan_MealRecord = new CustomBaseRepository<Can_MealRecord>(unitOfWork);
                var repoCan_TamScanLog = new CustomBaseRepository<Can_TamScanLogCMS>(unitOfWork);
                var repoCan_Line = new CustomBaseRepository<Can_Line>(unitOfWork);
                var repoCan_Canteen = new CustomBaseRepository<Can_Canteen>(unitOfWork);
                var repoCan_Catering = new CustomBaseRepository<Can_Catering>(unitOfWork);
                var repoSys_AllSetting = new CustomBaseRepository<Sys_AllSetting>(unitOfWork);
                string status = string.Empty;
                //string strIDs = string.Join(",", lstProfileIDs.ToArray());
                #region xử lý cấu hình giờ kết thúc ăn - DateStart & DateEnd
                DateTime dateConfig = DateTime.MinValue;
                var rsTimeConfig = GetData<Sys_AllSettingEntity>(AppConfig.HRM_CAN_MEALRECORD_EATEND_CONFIG.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();
                if (rsTimeConfig != null && rsTimeConfig.Value1 != null)
                {
                    dateConfig = DateTimeHelper.ConvertStringToDateTime(rsTimeConfig.Value1, ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond_ffffff.ToString());
                }
                double hourConfig = dateConfig.Hour + (((double)dateConfig.Minute) / 60);
                dateStart = dateStart.Date.AddHours(hourConfig);
                dateEnd = dateEnd.Date.AddDays(1).AddHours(hourConfig).AddMilliseconds(-1);
                #endregion

                #region cấu hình số phút xử lý trùng
                int rsScanMulti = 0;
                var rsScanMultiConfig = GetData<Sys_AllSettingEntity>(AppConfig.HRM_CAN_MEALRECORD_SCANMULTI_CONFIG.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();

                if (rsScanMultiConfig != null)
                {
                    rsScanMulti = rsScanMultiConfig.Value1 != null ? int.Parse(rsScanMultiConfig.Value1.ToString()) : 0;
                }
                #endregion

                var tamScanLogs = repoCan_TamScanLog
                    .FindBy(s => dateStart <= s.TimeLog && s.TimeLog <= dateEnd)
                    .Select(s => new { s.MachineCode, s.CardCode, s.TimeLog, s.ID })
                    .ToList();
                var cardCodes = tamScanLogs.Select(s => s.CardCode).ToList();

                //strIDs = Common.DotNetToOracle(strIDs);
                //var profiles = GetData<Hre_ProfileEntity>(strIDs, ConstantSql.hrm_hr_sp_get_ProfileByIds, ref status)
                //    .Where(s => cardCodes.Contains(s.CodeAttendance) && lstProfileIDs.Contains(s.ID))
                var profiles = lstProfileIDs
                    .Where(s => cardCodes.Contains(s.CodeAttendance))
                    .Select(s => new { s.ID, s.CodeAttendance, s.CodeEmp, s.ProfileName, s.OrgStructureName }).ToList();

                tamScanLogs = tamScanLogs.Where(s => profiles.Select(p => p.CodeAttendance).Contains(s.CardCode)).OrderBy(s => s.CardCode).ThenBy(s=>s.TimeLog).ToList();
                var lines = repoCan_Line.FindBy(s => s.IsDelete == null).ToList();
                var canteens = repoCan_Canteen.FindBy(s => s.IsDelete == null).ToList();
                var caterings = repoCan_Catering.FindBy(s => s.IsDelete == null).ToList();
                if (_line != null)
                {
                    List<Guid> lstLine = _line.Split(',').Select(Guid.Parse).ToList();
                    lines = lines.Where(s => lstLine.Contains(s.ID)).ToList();
                }
                if (_canteen != null)
                {
                    List<Guid> lstcanteen = _canteen.Split(',').Select(Guid.Parse).ToList();
                    canteens = canteens.Where(s => lstcanteen.Contains(s.ID)).ToList();
                }
                if (_catering != null)
                {
                    List<Guid> lstcatering = _catering.Split(',').Select(Guid.Parse).ToList();
                    caterings = caterings.Where(s => lstcatering.Contains(s.ID)).ToList();
                }

                List<object> lstObj = new List<object>();
                lstObj.Add(dateStart);
                lstObj.Add(dateEnd);
                List<Can_MealRecordCheckEntity> mealRecordCheckList = GetData<Can_MealRecordCheckEntity>(lstObj, ConstantSql.hrm_can_sp_get_MealRecord_ByDateFromDateTo, UserLogin, ref status);
                Can_MealRecordEntity record = new Can_MealRecordEntity();
                List<Can_MealRecordEntity> lstRecord = new List<Can_MealRecordEntity>();
                List<Can_MealRecord> lstEdit = new List<Can_MealRecord>();
                List<Can_MealRecord> lstAdd = new List<Can_MealRecord>();

                List<Guid> lstDuplicateTamScan = new List<Guid>();
                foreach (var tamScanLog in tamScanLogs)
                {
                    if (lstDuplicateTamScan.Contains(tamScanLog.ID))
                        continue;

                    record = new Can_MealRecordEntity();
                    var profile = profiles.FirstOrDefault(s => s.CodeAttendance == tamScanLog.CardCode);
                    var line = lines.FirstOrDefault(s => tamScanLog.MachineCode == s.MachineCode);

                    if (profile != null && line != null)
                    { 
                        #region xử lý quẹt thẻ trùng theo HRM_CAN_MEALRECORD_SCANMULTI_CONFIG
                        var tamScanLogProfiles = tamScanLogs
                            .Where(s => s.CardCode == tamScanLog.CardCode && s.TimeLog.Value.Date == tamScanLog.TimeLog.Value.Date && s.MachineCode == tamScanLog.MachineCode)
                            .OrderBy(s => s.TimeLog)
                            .ToList();

                        if (tamScanLogProfiles.Count > 1 && rsScanMulti > 0)
                        {
                            for (int i = 0; i < tamScanLogProfiles.Count; i++)
                            {
                                var tamsanFirst = tamScanLogProfiles[i];
                                int j = i + 1;
                                if (j > tamScanLogProfiles.Count - 1)
                                {
                                    j = i;
                                }
                                var tamsanNear = tamScanLogProfiles[j];

                                if (tamsanNear.TimeLog.Value.Subtract(tamsanFirst.TimeLog.Value).TotalMinutes < rsScanMulti 
                                        && tamsanFirst.ID != tamsanNear.ID )
                                {
                                    if (tamsanFirst.MachineCode == tamsanNear.MachineCode)
                                    { 
                                        lstDuplicateTamScan.Add(tamsanNear.ID);
                                        break;
                                    }
                                }
                            }
                        }
                        #endregion
                        
                        #region xử lý add record
                        record.TimeLog = tamScanLog.TimeLog.HasValue ? tamScanLog.TimeLog.Value : DateTime.MinValue;
                        if (record.TimeLog < record.TimeLog.Value.Date.AddHours(hourConfig))
                        {
                            record.WorkDay = record.TimeLog.Value.AddDays(-1);
                        }
                        else
                        {
                            record.WorkDay = record.TimeLog;
                        }

                        if (tamScanLog.MachineCode != null)
                        {
                            record.MachineCode = tamScanLog.MachineCode;
                            if (line != null)
                            {
                                record.LineName = line.LineName;
                                record.LineID = line.ID;
                                record.Amount = (decimal)line.Amount;
                                if (line.CanteenID != null)
                                {
                                    var cant = canteens.Where(c => c.ID == line.CanteenID).FirstOrDefault();
                                    record.CanteenName = cant.CanteenName;
                                    record.CanteenID = line.CanteenID;
                                }
                                if (line.CateringID != null)
                                {
                                    var cater = caterings.Where(c => c.ID == line.CateringID).FirstOrDefault();
                                    record.CateringName = cater.CateringName;
                                    record.CateringID = line.CateringID;
                                }
                            }
                        }
                            
                        record.ProfileName = profile.ProfileName;
                        record.CodeEmp = profile.CodeEmp;
                        record.OrgStructureName = profile.OrgStructureName;
                        record.CodeAttendance = profile.CodeAttendance;
                        record.DateCreate = DateTime.Now;

                        var recordAdd = record.CopyData<Can_MealRecord>();
                        recordAdd.ProfileID = profile.ID;
                        var CheckList = mealRecordCheckList.Where(s => s.ProfileID == profile.ID && s.TimeLog == tamScanLog.TimeLog).ToList();
                        if (CheckList != null)
                        {
                            if (CheckList.Count() > 0)
                            {
                                var idUpdate = CheckList.FirstOrDefault();
                                recordAdd.ID = idUpdate.ID;
                                //lstEdit.Add(recordAdd);
                                repoCan_MealRecord.Edit(recordAdd);
                            }
                            else
                            {
                                recordAdd.ID = Guid.NewGuid();
                                repoCan_MealRecord.Add(recordAdd);
                                //lstAdd.Add(recordAdd);
                            }
                        }
                        record.ID = tamScanLog.ID;
                        lstRecord.Add(record);
                        #endregion
                        
                    }
                }

                repoCan_MealRecord.SaveChanges();


                if (lstRecord.Count > 0)
                {
                    Sys_AllSetting sys = new Sys_AllSetting();
                    Sys_AllSetting rs = GetData<Sys_AllSetting>(AppConfig.HRM_CAN_MEALRECORD_SUMMARY.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();
                    sys.Value1 = dateStart.ToString(ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond.ToString());
                    sys.Value2 = dateEnd.ToString(ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond.ToString());
                    sys.Name = AppConfig.HRM_CAN_MEALRECORD_SUMMARY.ToString();

                    if (rs != null)
                    {
                        sys.ID = rs.ID;
                        repoSys_AllSetting.Edit(sys);
                    }
                    else
                    {
                        sys.ID = Guid.NewGuid();
                        repoSys_AllSetting.Add(sys);
                    }
                    repoSys_AllSetting.SaveChanges();
                }
                //lstRecord.Where().(s => s.MealAllowanceTypeName = ConstantDisplay.HRM_Enum_Submit.TranslateString()).ToList();
                return lstRecord;
            }
        }
Esempio n. 33
0
        /// <summary>
        /// [Hieu.van] Tổng Hợp giặt là
        /// </summary>
        /// <param name="dateStart"></param>
        /// <param name="dateEnd"></param>
        /// <param name="lstProfileIDs"></param>
        /// <returns></returns>
        public List<LMS_LaundryRecordEntity> GetLaundryRecordSummary(string _line, string _locker, string _marker, DateTime dateStart, DateTime dateEnd, List<Hre_ProfileEntity> lstProfileIDs,string UserLogin)
        {
            dateStart = dateStart.Date;
            dateEnd = dateEnd.Date.AddDays(1).AddMilliseconds(-1);

            string status = string.Empty;
            //string strIDs = string.Join(",", lstProfileIDs.ToArray());

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoLau_TamScanLog = new CustomBaseRepository<LMS_TamScanLogLMS>(unitOfWork);
                var repoLau_Line = new CustomBaseRepository<LMS_LineLMS>(unitOfWork);
                var repoLau_Locker = new CustomBaseRepository<LMS_LockerLMS>(unitOfWork);
                var repoLau_Marker = new CustomBaseRepository<LMS_Marker>(unitOfWork);
                var repoLau_LaundryRecord = new CustomBaseRepository<LMS_LaundryRecord>(unitOfWork);
                var repoSys_AllSetting = new CustomBaseRepository<Sys_AllSetting>(unitOfWork);

                #region cấu hình số phút xử lý trùng
                int rsScanMulti = 0;
                var rsScanMultiConfig = GetData<Sys_AllSetting>(AppConfig.HRM_LAU_LAUNDRYRECORD_SCANMULTI_CONFIG.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey,UserLogin, ref status).FirstOrDefault();
                if (rsScanMultiConfig != null)
                {
                    rsScanMulti = rsScanMultiConfig.Value1 != null ? int.Parse(rsScanMultiConfig.Value1.ToString()) : 0;
                    dateStart = dateStart.Date.AddHours(rsScanMulti);
                    dateEnd = dateEnd.Date.AddDays(1).AddHours(rsScanMulti).AddMilliseconds(-1);
                }
                #endregion
                

                var tamScanLogs = repoLau_TamScanLog
                    .FindBy(s => dateStart <= s.TimeLog && s.TimeLog <= dateEnd)
                    .Select(s => new { s.Code, s.TimeLog, s.ID, s.MachineCode })
                    //.Select(s => new { s.MachineCode, s.CardCode, s.TimeLog, s.Id })
                    .ToList();
                var cardCodes = tamScanLogs.Select(s => s.Code).ToList();
                //strIDs = Common.DotNetToOracle(strIDs);
                //var profiles = GetData<Hre_ProfileEntity>(strIDs, ConstantSql.hrm_hr_sp_get_ProfileByIds, ref status)
                //    .Where(s => cardCodes.Contains(s.CodeAttendance) && lstProfileIDs.Contains(s.ID))
                var profiles = lstProfileIDs
                    .Where(s => cardCodes.Contains(s.CodeAttendance))
                    .Select(s => new { s.ID, s.CodeAttendance, s.CodeEmp, s.ProfileName, s.OrgStructureName }).ToList();
                tamScanLogs = tamScanLogs
                    .Where(s => profiles.Select(p => p.CodeAttendance).Contains(s.Code))
                    .OrderBy(s => s.Code)
                    .ThenBy(s => s.TimeLog)
                    .ToList();

                #region lấy line-locker-marker và xử lý khi tìm kiếm
                var lines = repoLau_Line.FindBy(s => s.IsDelete == null).ToList();
                var Lockers = repoLau_Locker.FindBy(s => s.IsDelete == null).ToList();
                var Markers = repoLau_Marker.FindBy(s => s.IsDelete == null).ToList();
                if (_line != null)
                {
                    List<Guid> lstLine = _line.Split(',').Select(Guid.Parse).ToList();
                    lines = lines.Where(s => lstLine.Contains(s.ID)).ToList();
                }
                if (_locker != null)
                {
                    List<Guid> lstLocker = _locker.Split(',').Select(Guid.Parse).ToList();
                    Lockers = Lockers.Where(s => lstLocker.Contains(s.ID)).ToList();
                }
                if (_marker != null)
                {
                    List<Guid> lstMarker = _marker.Split(',').Select(Guid.Parse).ToList();
                    Markers = Markers.Where(s => lstMarker.Contains(s.ID)).ToList();
                }
                #endregion

                List<object> lstObj = new List<object>();
                lstObj.Add(dateStart);
                lstObj.Add(dateEnd);
                List<Lau_LaundryRecordCheckEntity> laundryCheckList = GetData<Lau_LaundryRecordCheckEntity>(lstObj, ConstantSql.hrm_lau_sp_get_LaundryRecord_ByDateFromDateTo, UserLogin, ref status);

                LMS_LaundryRecordEntity laundry = new LMS_LaundryRecordEntity();
                List<LMS_LaundryRecordEntity> lstRecord = new List<LMS_LaundryRecordEntity>();
                List<LMS_LaundryRecord> lstAdd = new List<LMS_LaundryRecord>();
                List<LMS_LaundryRecord> lstEdit = new List<LMS_LaundryRecord>();
                List<Guid> lstDuplicateTamScan = new List<Guid>();
                foreach (var tamScanLog in tamScanLogs)
                {
                    if (lstDuplicateTamScan.Contains(tamScanLog.ID))
                        continue;

                    laundry = new LMS_LaundryRecordEntity();
                    var profile = profiles.FirstOrDefault(s => s.CodeAttendance == tamScanLog.Code);
                    var line = lines.FirstOrDefault(s => tamScanLog.MachineCode == s.MachineCode);

                    if (profile != null && line != null)
                    {
                        #region xử lý bản ghi trùng 
                        var tamScanLogProfiles = tamScanLogs
                            .Where(s => s.Code == tamScanLog.Code && s.TimeLog.Value.Date == tamScanLog.TimeLog.Value.Date && s.MachineCode == tamScanLog.MachineCode)
                            .OrderBy(s => s.TimeLog)
                            .ToList();
                        if (tamScanLogProfiles.Count > 1 && rsScanMulti > 0)
                        {
                            for (int i = 0; i < tamScanLogProfiles.Count; i++)
                            {
                                var tamsanFirst = tamScanLogProfiles[i];
                                int j = i + 1;
                                if (j > tamScanLogProfiles.Count - 1)
                                {
                                    j = i;
                                }
                                var tamsanNear = tamScanLogProfiles[j];
                                if (tamsanNear.TimeLog.Value.Subtract(tamsanFirst.TimeLog.Value).TotalMinutes < rsScanMulti && tamsanFirst.ID != tamsanNear.ID)
                                {
                                    if (tamsanFirst.MachineCode == tamsanNear.MachineCode)
                                    {
                                        lstDuplicateTamScan.Add(tamsanNear.ID);
                                        break;
                                    }
                                }
                            }
                        }
                        #endregion
                        
                        #region xử lý add record
                        laundry.ProfileID = profile.ID;
                        laundry.ProfileName = profile.ProfileName;
                        laundry.CodeAttendance = profile.CodeAttendance;
                        laundry.TimeLog = tamScanLog.TimeLog;
                        laundry.Status = HRM.Infrastructure.Utilities.LaundryRecordStatus.E_SUBMIT.ToString();
                        laundry.Type = LaundryRecordType.E_AUTO.ToString();
                        if (tamScanLog.MachineCode != null)
                        {
                            laundry.MachineCode = tamScanLog.MachineCode;
                            if (line != null)
                            {
                                laundry.LineLMSName = line.LineLMSName;
                                laundry.LineID = line.ID;
                                laundry.Amount = (decimal)line.Amount;

                                if (line.LockerID != null)
                                {
                                    var locker = Lockers.Where(c => c.ID == line.LockerID).FirstOrDefault();
                                    laundry.LockerLMSName = locker.LockerLMSName;
                                    laundry.LockerID = locker.ID;
                                }
                                if (line.MarkerID != null)
                                {
                                    var marker = Markers.Where(c => c.ID == line.MarkerID).FirstOrDefault();
                                    laundry.MarkerName = marker.MarkerName;
                                    laundry.MarkerID = marker.ID;
                                }


                            }
                        }

                        laundry.DateCreate = DateTime.Now;
                        var recordAdd = laundry.CopyData<LMS_LaundryRecord>();
                        var CheckList = laundryCheckList.Where(s => s.ProfileID == laundry.ProfileID.Value && s.TimeLog == laundry.TimeLog).ToList();
                        if (CheckList != null)
                        {
                            if (CheckList.Count() > 0)
                            {
                                var idUpdate = CheckList.FirstOrDefault();
                                recordAdd.ID = idUpdate.ID;
                                repoLau_LaundryRecord.Edit(recordAdd);
                                //lstEdit.Add(recordAdd);
                            }
                            else
                            {
                                recordAdd.ID = Guid.NewGuid();
                                repoLau_LaundryRecord.Add(recordAdd);
                                //lstAdd.Add(recordAdd);
                            }
                        }
                        laundry.ID = tamScanLog.ID;
                        lstRecord.Add(laundry);
                        #endregion
                    }
                }
                repoLau_LaundryRecord.SaveChanges();
                //if (lstAdd.Any())
                //{
                //    repoLau_LaundryRecord.Add(lstAdd);
                //    repoLau_LaundryRecord.SaveChanges();
                //}
                //if (lstEdit.Any())
                //{
                //    repoLau_LaundryRecord.Edit(lstEdit);
                //    repoLau_LaundryRecord.SaveChanges();
                //}
                if (lstRecord.Count > 0)
                {
                    Sys_AllSetting sys = new Sys_AllSetting();
                    Sys_AllSetting rs = GetData<Sys_AllSetting>(AppConfig.HRM_LAU_LAUNDRYRECORD_SUMMARY.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey,UserLogin, ref status).FirstOrDefault();

                    sys.Value1 = dateStart.ToString(ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond.ToString());
                    sys.Value2 = dateEnd.ToString(ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond.ToString());
                    sys.Name = AppConfig.HRM_LAU_LAUNDRYRECORD_SUMMARY.ToString();

                    if (rs != null)
                    {
                        sys.ID = rs.ID;
                        repoSys_AllSetting.Edit(sys);
                    }
                    else
                    {
                        sys.ID = Guid.NewGuid();
                        repoSys_AllSetting.Add(sys);
                    }
                    repoSys_AllSetting.SaveChanges();
                }


                return lstRecord;
            }
        }
Esempio n. 34
0
        ///// <summary>
        ///// Lấy toàn bộ data
        ///// </summary>
        ///// <returns></returns>
        //public IQueryable<Att_AnnualLeave> Get()
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        return repo.Get().Where(i => i.IsDelete == null);
        //    }
        //}

        ///// <summary>
        ///// Lấy dữ liệu theo Id
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public Att_AnnualLeaveEntity Get(int id)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var data = repo.GetAnnualLeaveById(id);
        //        if (data.IsDelete == true) data = null;
        //        return data;
        //    }
        //}

        //public List<Att_AnnualLeaveEntity> GetAnnualLeaveByIds(string selectedIds)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        return repo.GetAnnualLeaveByIds(selectedIds);
        //    }
        //}

        ///// <summary>
        ///// Thêm mới một record
        ///// </summary>
        ///// <param name="cat"></param>
        ///// <returns></returns>
        //public bool Add(Att_AnnualLeave model)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        try
        //        {
        //            repo.Add(model);
        //            repo.SaveChanges();
        //            return true;
        //        }
        //        catch
        //        {
        //            return false;
        //        }
        //    }
        //}

        ///// <summary>
        ///// Edit một record
        ///// </summary>
        ///// <param name="cat"></param>
        ///// <returns></returns>
        //public bool Edit(Att_AnnualLeave model)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        try
        //        {
        //            repo.Edit(model);
        //            repo.SaveChanges();
        //            return true;
        //        }
        //        catch
        //        {
        //            return false;
        //        }

        //    }
        //}

        ///// <summary>
        ///// Remove 1 record là chuyển trạng thái IsDelete=true
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public bool Remove(int id)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var data = repo.GetById(id);
        //        try
        //        {
        //            repo.Remove(data);
        //            repo.SaveChanges();
        //            return true;
        //        }
        //        catch
        //        {
        //            return false;
        //        }

        //    }
        //}

        ///// <summary>
        ///// Delete 1 record là xóa luôn record khỏi database
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public bool Delete(int id)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        var repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var data = repo.GetById(id);
        //        try
        //        {
        //            repo.Delete(data);
        //            repo.SaveChanges();
        //            return true;
        //        }
        //        catch
        //        {
        //            return false;
        //        }

        //    }
        //}

        //#region Store Procedure

        //#region Danh sách

        ///// <summary>
        ///// Lấy danh sách dữ liệu AnnualLeaves [Tung.Ly - 2014/05/09]
        ///// </summary>
        ///// <returns></returns>
        //public IQueryable<Att_AnnualLeaveEntity> GetAnnualLeaves(ListQueryModel model)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        IAtt_AnnualLeaveRepository repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var rs = repo.GetAnnualLeaves(model);
        //        return rs;
        //    }
        //}

        //#endregion

        //#region Chi tiet

        ///// <summary>
        ///// Lấy dữ liệu AnnualLeave theo Id [Tung.Ly - 2014/05/09]
        ///// </summary>
        ///// <param name="annualLeaveId"></param>
        ///// <returns></returns>
        //public Att_AnnualLeaveEntity GetAnnualLeaveById(int annualLeaveId)
        //{
        //    using (var context = new VnrHrmDataContext())
        //    {
        //        var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
        //        IAtt_AnnualLeaveRepository repo = new Att_AnnualLeaveRepository(unitOfWork);
        //        var data = repo.GetAnnualLeaveById(annualLeaveId);
        //        return data;
        //    }
        //}

        //#endregion

        //#endregion
        #endregion

        #region thanh toán phép năm đầu kỳ

        public void SetAnnualLeaveBeginYear(List<Guid> lstProfileIDs, double? limitMaximum, int Year, int? MonthResetANL, Guid? AllowanceTypeID, Guid? CuttOffDurationID)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_AnnualLeave = new CustomBaseRepository<Att_AnnualLeave>(unitOfWork);
                var repoAtt_AnnualDetail = new CustomBaseRepository<Att_AnnualDetail>(unitOfWork);
                var repoSal_UnusualAllowance = new CustomBaseRepository<Sal_UnusualAllowance>(unitOfWork);
                var repoAtt_CutOffDuration = new CustomBaseRepository<Att_CutOffDuration>(unitOfWork);
                //nếu có rồi thì chỉ cần Update
                //Nếu chưa có thì tạo mới
                Att_CutOffDuration CutOffDuration = new Att_CutOffDuration();
                if (CuttOffDurationID != null)
                {
                    CutOffDuration = repoAtt_CutOffDuration.FindBy(m => m.ID == CuttOffDurationID).FirstOrDefault();
                }


                int LastYear = Year - 1;
                DateTime? MaxTime = repoAtt_AnnualDetail.FindBy(m => m.IsDelete != null && m.Year == LastYear).OrderByDescending(m => m.MonthYear).Select(m => m.MonthYear).FirstOrDefault();
                List<Att_AnnualDetail> lstAnnualDetail = new List<Att_AnnualDetail>();
                if (MaxTime != null)
                {
                    lstAnnualDetail = repoAtt_AnnualDetail.FindBy(m => m.MonthYear == MaxTime
                        && m.ProfileID != null
                        && lstProfileIDs.Contains(m.ProfileID.Value)).ToList();
                }
                var lstAnnualLeaveInDB = repoAtt_AnnualLeave.FindBy(m => m.IsDelete == null && m.Year == Year && lstProfileIDs.Contains(m.ProfileID)).ToList();


                foreach (var ProfileID in lstProfileIDs)
                {
                    Att_AnnualLeave AnnualLeaveByProfile = lstAnnualLeaveInDB.Where(m => m.ProfileID == ProfileID).FirstOrDefault();
                    bool IsNew = false;
                    if (AnnualLeaveByProfile == null)
                    {
                        IsNew = true;
                        AnnualLeaveByProfile = new Att_AnnualLeave();
                        AnnualLeaveByProfile.ID = Guid.NewGuid();
                        AnnualLeaveByProfile.ProfileID = ProfileID;
                        AnnualLeaveByProfile.Year = Year;
                        AnnualLeaveByProfile.MonthStart = 1;

                    }
                    AnnualLeaveByProfile.MonthResetAnlOfBeforeYear = MonthResetANL;
                    double RemainLastYear = lstAnnualDetail.Where(m => m.ProfileID == ProfileID).Select(m => m.Remain ?? 0).FirstOrDefault();
                    if (limitMaximum != null)
                    {
                        AnnualLeaveByProfile.InitAnlValue = RemainLastYear > limitMaximum.Value ? limitMaximum.Value : RemainLastYear;
                        AnnualLeaveByProfile.SurplusAnllastYear = RemainLastYear > limitMaximum ? RemainLastYear - limitMaximum : 0;
                        if (CutOffDuration.ID != null && CutOffDuration.ID != Guid.Empty && AllowanceTypeID != null)
                        {
                            Sal_UnusualAllowance UnusualAllowance = new Sal_UnusualAllowance();
                            UnusualAllowance.ProfileID = ProfileID;
                            UnusualAllowance.MonthStart = CutOffDuration.DateStart;
                            UnusualAllowance.MonthEnd = CutOffDuration.DateEnd;
                            UnusualAllowance.UnusualEDTypeID = AllowanceTypeID;
                            UnusualAllowance.Amount = AnnualLeaveByProfile.SurplusAnllastYear;
                            repoSal_UnusualAllowance.Add(UnusualAllowance);
                        }
                    }
                    else
                    {
                        AnnualLeaveByProfile.InitAnlValue = RemainLastYear;
                        AnnualLeaveByProfile.SurplusAnllastYear = 0;
                    }
                    //Sửa lại theo phần tử mới mà Sơn build
                    if (IsNew)
                    {
                        repoAtt_AnnualLeave.Add(AnnualLeaveByProfile);
                    }
                    else
                    {
                        repoAtt_AnnualLeave.Edit(AnnualLeaveByProfile);
                    }
                }
                repoAtt_AnnualLeave.SaveChanges();
                repoSal_UnusualAllowance.SaveChanges();
            }
        }
Esempio n. 35
0
        public string Set_ApproveLeaveDay_ByModuleApprove(string host, List<Guid> lstLeaveDay, Guid UserLoginID, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                string status = string.Empty;
                string statusSendMail = DataErrorCode.Error.ToString();
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                BaseService service = new BaseService();
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);

                #region getdata

                List<object> lstParamUser = new List<object>();
                lstParamUser.AddRange(new object[4]);
                lstParamUser[3] = Int32.MaxValue;
                var lstUserAll = service.GetData<Sys_UserInfo>(lstParamUser, ConstantSql.hrm_sys_sp_get_users, userLogin, ref status);
                var lstUser = lstUserAll.Where(m => !string.IsNullOrEmpty(m.Email)).Select(m => new { m.ID, m.Email }).ToList();

                //Step1 : Check 1 Approve or 2 approve
                DateTime today = DateTime.Today;
                string E_LEAVEDAY = DelegateApproveType.E_LEAVE_DAY.ToString();

                List<object> lstParam = new List<object>();
                lstParam.AddRange(new object[10]);
                var lstDelegateApproveAll = service.GetData<Sys_DelegateApprove>(lstParam, ConstantSql.hrm_sys_sp_get_DelegateApprove, userLogin, ref status);

                var lstDelegateApprove = lstDelegateApproveAll.Where(m => m.UserID != null
                    && m.UserDelegateID != null
                    && m.DataTypeDelegate == E_LEAVEDAY
                    && m.DateFrom <= today
                    && m.DateTo >= today).ToList();

                List<Guid> lstUserCanView = lstDelegateApprove.Where(m => m.UserDelegateID == UserLoginID).Select(m => m.UserID.Value).ToList();
                lstUserCanView.Add(UserLoginID);

                #endregion

                #region process

                string E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();
                string E_FIRST_APPROVED = LeaveDayStatus.E_FIRST_APPROVED.ToString();
                List<Att_LeaveDay> lstLeaveDaySendMail = new List<Att_LeaveDay>();
                foreach (var leaID in lstLeaveDay)
                {
                    var LeaveDay = repoAtt_LeaveDay.GetById(leaID);
                    lstLeaveDaySendMail.Add(LeaveDay);
                    if (LeaveDay.UserApproveID2 != null && lstUserCanView.Contains(LeaveDay.UserApproveID2.Value))
                    {
                        LeaveDay.Status = E_APPROVED;
                    }
                    if (LeaveDay.UserApproveID != null && lstUserCanView.Contains(LeaveDay.UserApproveID.Value))
                    {
                        LeaveDay.Status = E_FIRST_APPROVED;
                    }
                }
                var stt = repoAtt_LeaveDay.SaveChanges();

                #endregion


                if (stt == DataErrorCode.Success)
                {
                    #region getdata

                    List<Hre_ProfileEntity> lstProfile = new List<Hre_ProfileEntity>();
                    List<Sys_TemplateSendMail> template = new List<Sys_TemplateSendMail>();
                    Sys_TemplateSendMail tempApprove = new Sys_TemplateSendMail();
                    Sys_TemplateSendMail tempReturn = new Sys_TemplateSendMail();
                    List<Cat_LeaveDayType> lstLeaveDayType = new List<Cat_LeaveDayType>();
                    string[] strsParaKey = null;
                    string bodyContent = null;
                    string titleMail = null;
                    string[] strsParaValues = null;
                    string[] strsParaValues_Return = null;

                    string _typeTemplate = EnumDropDown.EmailType.E_APPROVED_LEAVEDAY.ToString();
                    string _typeTemplate_return = EnumDropDown.EmailType.E_APPROVED_LEAVEDAY_RETURN.ToString();
                    var repoSys_TemplateSendMail = new CustomBaseRepository<Sys_TemplateSendMail>(unitOfWork);
                    template = repoSys_TemplateSendMail.FindBy(s => s.Type == _typeTemplate || s.Type == _typeTemplate_return).ToList();
                    if (template.Count < 2)
                        return DataErrorCode.Error_NoTemplateMail.ToString();

                     var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
                    lstLeaveDayType = repoCat_LeaveDayType.FindBy(s => s.IsDelete == null).ToList();

                    tempApprove = template.Where(s => s.Type == _typeTemplate).FirstOrDefault();
                    tempReturn = template.Where(s => s.Type == _typeTemplate_return).FirstOrDefault();

                    string proIDS = string.Join(",", lstLeaveDaySendMail.Select(s => s.ProfileID.ToString()).Distinct().ToList());
                    proIDS = Common.DotNetToOracle(proIDS);
                    lstProfile = GetData<Hre_ProfileEntity>(proIDS, ConstantSql.hrm_hr_sp_get_ProfileByIds, userLogin, ref status);

                    strsParaKey = new string[] 
                    { 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_UserName.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_ProfileName.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_CodeEmp.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_DateStart.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_DateEnd.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_Status.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_LeaveDayTypeName.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_LeaveHours.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_LeaveDays.ToString(), 
                        EnumDropDown.EmailType_APPROVED_LEAVEDAY.E_LinkContent.ToString(), 
                    };

                    #endregion

                    foreach (var Leaveday in lstLeaveDaySendMail)
                    {
                        Guid? UserNextApprove = null;
                        if (Leaveday.Status == E_FIRST_APPROVED)
                        {
                            UserNextApprove = Leaveday.UserApproveID2;
                        }
                         string LeaveDayType = string.Empty;
                        var leavedayTypeObject = lstLeaveDayType.Where(m=>m.ID==Leaveday.ID).FirstOrDefault();
                        if(leavedayTypeObject!= null)
                        {
                            LeaveDayType = leavedayTypeObject.LeaveDayTypeName;
                        }
                        List<Guid> lstDelegateApproveUserID = new List<Guid>();
                        if (UserNextApprove != null)
                        {
                            lstDelegateApproveUserID = lstDelegateApprove.Where(m => m.UserID == UserNextApprove).Select(m => m.UserDelegateID.Value).ToList();
                            lstDelegateApproveUserID.Add(UserNextApprove.Value);
                        }
                        var UserRegister = lstUserAll.Where(m => m.ProfileID == Leaveday.ProfileID).FirstOrDefault();
                        if (UserRegister != null)
                        {
                            lstDelegateApproveUserID.Add(UserRegister.ID);
                        }
                        lstDelegateApproveUserID = lstDelegateApproveUserID.Distinct().ToList();

                        var lstUserInfoCanView = lstUser.Where(m => lstDelegateApproveUserID.Contains(m.ID)).ToList();
                        List<Att_EmailRequireEntity> lstEmailRequire = new List<Att_EmailRequireEntity>();
                        foreach (var UserInfoCanView in lstUserInfoCanView)
                        {
                            if (UserInfoCanView.Email == null)
                                continue;
                            Att_EmailRequireEntity EmailRequireEntity = new Att_EmailRequireEntity();
                            EmailRequireEntity.IdObject = Leaveday.ID;
                            EmailRequireEntity.EmailUserApprove = UserInfoCanView.Email;
                            EmailRequireEntity.IdUserApprove = UserInfoCanView.ID;
                            if (UserRegister != null && UserInfoCanView.ID == UserRegister.ID)
                            {
                                EmailRequireEntity.IsRegister = true;
                            }
                            lstEmailRequire.Add(EmailRequireEntity);
                        }
                        if (lstEmailRequire.Count > 0)
                        {
                            Guid ID = Leaveday.ID;
                            var lstEmailToSend_ByOT = lstEmailRequire.Where(m => m.IdObject == ID).ToList();
                            var profile = lstProfile.Where(s => s.ID == Leaveday.ProfileID).FirstOrDefault();
                            var userApproved1 = lstUserAll.Where(s => s.ID == Leaveday.UserApproveID).FirstOrDefault();
                            var userApproved2 = lstUserAll.Where(s => s.ID == Leaveday.UserApproveID2).FirstOrDefault();
                            foreach (var mail in lstEmailRequire)
                            {
                                bodyContent = string.Empty;

                                if (mail.IsRegister == true)
                                {
                                    #region Send Cho nguoi đăng ký
                                    titleMail = tempReturn.Subject;
                                    strsParaValues_Return = new string[]{
                                            profile.ProfileName,
                                            profile.ProfileName,
                                            profile.CodeEmp,
                                            Leaveday.DateStart.ToString("dd/MM/yyyy"),
                                            Leaveday.DateEnd.ToString("dd/MM/yyyy"),
                                            Leaveday.Status,
                                            LeaveDayType,
                                            (Leaveday.LeaveHours??0).ToString(),
                                            (Leaveday.LeaveDays??0).ToString(),
                                            string.Empty,
                                        };
                                    bodyContent = LibraryService.ReplaceContentFile(tempReturn.Content, strsParaKey, strsParaValues_Return);
                                    #endregion
                                }
                                else
                                {
                                    #region Send cho ngươi duyệt
                                    titleMail = tempApprove.Subject;
                                    string UserName = lstUserAll.Where(m => m.ID == mail.IdUserApprove).Select(m => m.UserInfoName).FirstOrDefault();
                                    string linkcontent = "<br/> <a href='" + host + "Att_ApprovedLeaveday/ProcessApprovedPage?loginID=" + mail.IdUserApprove + "&recordID=" + Leaveday.ID + "'>Click this link to approve<a/><br /><br />";
                                    linkcontent += "<br/> <a href='" + host + "Att_ApprovedLeaveday/ProcessRejectPage?loginID=" + mail.IdUserApprove + "&recordID=" + Leaveday.ID + "'>Click this link to Reject<a/><br /><br />";
                                    strsParaValues = new string[]{
                                            UserName,
                                            profile.ProfileName,
                                            profile.CodeEmp,
                                            Leaveday.DateStart.ToString("dd/MM/yyyy"),
                                            Leaveday.DateEnd.ToString("dd/MM/yyyy"),
                                            Leaveday.Status,
                                            LeaveDayType,
                                            (Leaveday.LeaveHours??0).ToString(),
                                            (Leaveday.LeaveDays??0).ToString(),
                                            linkcontent
                                        };
                                    bodyContent = LibraryService.ReplaceContentFile(tempApprove.Content, strsParaKey, strsParaValues);
                                    #endregion
                                }
                                var sta = service.SendMail(titleMail, mail.EmailUserApprove, bodyContent, null);
                                if (sta == true)
                                {
                                    statusSendMail = DataErrorCode.Success.ToString();
                                }
                            }
                        }
                    }
                }
                return statusSendMail;
            }


        }
Esempio n. 36
0
        public void SetSickLeaveBeginYear(List<Guid> lstProfileIDs, double? limitMaximum, int Year)
        {
            //Đối với phép ốm thì tạm thời tính từ đầu năm đến cuối năm
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_AnnualLeave = new CustomBaseRepository<Att_AnnualLeave>(unitOfWork);
                var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
                int LastYear = Year - 1;
                DateTime beginLastYear = new DateTime(LastYear, 1, 1);
                DateTime endLastYear = beginLastYear.AddYears(1).AddMinutes(-1);
                List<Guid> SickLeaveType = repoCat_LeaveDayType.FindBy(m => m.IsDelete == null && m.Code == "SICK").Select(m => m.ID).ToList();
                string Approve = LeaveDayStatus.E_APPROVED.ToString();
                var lstLeaveDay = repoAtt_LeaveDay.FindBy(m =>
                    m.IsDelete == null
                    && m.Status == Approve
                    && m.DateStart < endLastYear
                    && m.DateEnd >= beginLastYear
                    && SickLeaveType.Contains(m.LeaveDayTypeID)
                    && lstProfileIDs.Contains(m.ProfileID)).Select(m => new { m.ProfileID, m.TotalDuration }).ToList();

                List<Att_AnnualLeave> lstAnnualLeaveInDB = repoAtt_AnnualLeave.FindBy(m => m.IsDelete == null && (m.Year == Year || m.Year == LastYear) && lstProfileIDs.Contains(m.ProfileID)).ToList();

                foreach (var ProfileID in lstProfileIDs)
                {
                    Att_AnnualLeave AnnualLeaveByProfile = lstAnnualLeaveInDB.Where(m => m.ProfileID == ProfileID && m.Year == Year).FirstOrDefault();
                    Att_AnnualLeave AnnualLeaveByProfile_Last = lstAnnualLeaveInDB.Where(m => m.ProfileID == ProfileID && m.Year == LastYear).FirstOrDefault();
                    bool IsNew = false;
                    if (AnnualLeaveByProfile == null)
                    {
                        IsNew = true;
                        AnnualLeaveByProfile = new Att_AnnualLeave();
                        AnnualLeaveByProfile.ID = Guid.NewGuid();
                        AnnualLeaveByProfile.ProfileID = ProfileID;
                        AnnualLeaveByProfile.Year = Year;
                        AnnualLeaveByProfile.MonthStart = 1;
                    }

                    double InitLastYear = 0;
                    if (AnnualLeaveByProfile_Last != null)
                        InitLastYear = AnnualLeaveByProfile_Last.InitSickValue;
                    double remainLastYear = InitLastYear - lstLeaveDay.Where(m => m.ProfileID == ProfileID).Sum(m => m.TotalDuration ?? 0);
                    if (limitMaximum != null)
                    {
                        AnnualLeaveByProfile.InitSickValue = remainLastYear > limitMaximum.Value ? limitMaximum.Value : remainLastYear;
                        AnnualLeaveByProfile.SurplusSicklastYear = remainLastYear > limitMaximum ? remainLastYear - limitMaximum : 0;
                    }
                    else
                    {
                        AnnualLeaveByProfile.InitSickValue = remainLastYear;
                        AnnualLeaveByProfile.SurplusSicklastYear = 0;
                    }
                    if (IsNew)
                    {
                        repoAtt_AnnualLeave.Add(AnnualLeaveByProfile);
                    }
                    else
                    {
                        repoAtt_AnnualLeave.Edit(AnnualLeaveByProfile);
                    }
                }
                repoAtt_AnnualLeave.SaveChanges();
            }
        }
Esempio n. 37
0
        public bool AddList(List<Att_AnnualLeaveDetailEntity> models)
        {
            bool isSuccess = false;
            var leaveType = string.Empty;
            var status = string.Empty;
            var year = 2013;
            if (models != null && models.FirstOrDefault() != null && models.FirstOrDefault().Year != null) 
            {
                year = Convert.ToInt32(models.FirstOrDefault().Year);
                leaveType = models.FirstOrDefault().Type;
            }

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repo = new CustomBaseRepository<Att_AnnualLeaveDetail>(unitOfWork);
                try
                {
                    var annualLeaveDetails = GetAllUseEntity<Att_AnnualLeaveDetail>(ref status).Where(p => p.Type == leaveType && p.Year == year).ToList().AsQueryable();
                    foreach (var attAnnualLeaveDetail in models)
                    {
                        var addSuccess = false;
                        var existAnnualDetail = annualLeaveDetails.Where(p => p.ProfileID == attAnnualLeaveDetail.ProfileID ).FirstOrDefault();
                        if (existAnnualDetail != null)
                        {
                            existAnnualDetail.Month1 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month2 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month3 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month4 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month5 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month6 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month7 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month8 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month9 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month10 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month11 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month12 = attAnnualLeaveDetail.Month1;

                            repo.Edit(existAnnualDetail);
                        }
                        else
                        {
                            Att_AnnualLeaveDetail temp = new Att_AnnualLeaveDetail();
                            temp = attAnnualLeaveDetail.CopyData<Att_AnnualLeaveDetail>();
                            repo.Add(temp);
                        }
                    }
                    repo.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }

            }
        }
        public string SaveOvertimePermitConfig(OvertimePermitEntity entity, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var            unitOfWork         = (IUnitOfWork)(new UnitOfWork(context));
                var            repoSys_AllSetting = new CustomBaseRepository <Sys_AllSetting>(unitOfWork);
                Sys_AllSetting sys = new Sys_AllSetting();

                string        HRM_ATT_OT_OTPERMIT_ = AppConfig.HRM_ATT_OT_OTPERMIT_.ToString();
                string        status = string.Empty;
                List <object> lstO   = new List <object>();
                lstO.Add(HRM_ATT_OT_OTPERMIT_);
                lstO.Add(null);
                lstO.Add(null);

                var config = GetData <Sys_AllSetting>(lstO, ConstantSql.hrm_sys_sp_get_AllSetting, userLogin, ref status);
                if (config != null)
                {
                    if (entity.limitHour_ByDay.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByDay.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByDay.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY.ToString();
                            objConfig.Value1 = entity.limitHour_ByDay.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByDay_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByDay_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByDay_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY_LEV1.ToString();
                            objConfig.Value1 = entity.limitHour_ByDay_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByDay_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByDay_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByDay_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYDAY_LEV2.ToString();
                            objConfig.Value1 = entity.limitHour_ByDay_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByWeek.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByWeek.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByWeek.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK.ToString();
                            objConfig.Value1 = entity.limitHour_ByWeek.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByWeek_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByWeek_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByWeek_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK_LEV1.ToString();
                            objConfig.Value1 = entity.limitHour_ByWeek_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByWeek_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByWeek_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByWeek_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYWEEK_LEV2.ToString();
                            objConfig.Value1 = entity.limitHour_ByWeek_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByMonth.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByMonth.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByMonth.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH.ToString();
                            objConfig.Value1 = entity.limitHour_ByMonth.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByMonth_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByMonth_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByMonth_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH_LEV1.ToString();
                            objConfig.Value1 = entity.limitHour_ByMonth_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByMonth_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByMonth_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByMonth_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYMONTH_LEV2.ToString();
                            objConfig.Value1 = entity.limitHour_ByMonth_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByYear.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByYear.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByYear.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR.ToString();
                            objConfig.Value1 = entity.limitHour_ByYear.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByYear_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByYear_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByYear_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR_LEV1.ToString();
                            objConfig.Value1 = entity.limitHour_ByYear_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.limitHour_ByYear_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitHour_ByYear_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.limitHour_ByYear_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITHOUR_BYYEAR_LEV2.ToString();
                            objConfig.Value1 = entity.limitHour_ByYear_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (!string.IsNullOrEmpty(entity.limitColor))
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitColor)
                            {
                                objConfig.Value1 = entity.limitColor;
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR.ToString();
                            objConfig.Value1 = entity.limitColor;
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (!string.IsNullOrEmpty(entity.limitColor_Lev1))
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitColor_Lev1)
                            {
                                objConfig.Value1 = entity.limitColor_Lev1;
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR_LEV1.ToString();
                            objConfig.Value1 = entity.limitColor_Lev1;
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (!string.IsNullOrEmpty(entity.limitColor_Lev2))
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.limitColor_Lev2)
                            {
                                objConfig.Value1 = entity.limitColor_Lev2;
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_LIMITCOLOR_LEV2.ToString();
                            objConfig.Value1 = entity.limitColor_Lev2;
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_Normal.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_Normal.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_Normal.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_Normal.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_Normal_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_Normal_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_Normal_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL_LEV1.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_Normal_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_Normal_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_Normal_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_Normal_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_NORMAL_LEV2.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_Normal_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_AllowOver.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_AllowOver.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_AllowOver.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_AllowOver.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_AllowOver_Lev1.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER_LEV1.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_AllowOver_Lev1.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_AllowOver_Lev1.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER_LEV1.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_AllowOver_Lev1.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowOverLimit_AllowOver_Lev2.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER_LEV2.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowOverLimit_AllowOver_Lev2.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowOverLimit_AllowOver_Lev2.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWOVERLIMIT_ALLOWOVER_LEV2.ToString();
                            objConfig.Value1 = entity.IsAllowOverLimit_AllowOver_Lev2.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                    if (entity.IsAllowSplit.HasValue)
                    {
                        var objConfig = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWSPLIT.ToString()).FirstOrDefault();
                        if (objConfig != null)
                        {
                            if (objConfig.Value1 != entity.IsAllowSplit.Value.ToString())
                            {
                                objConfig.Value1 = entity.IsAllowSplit.Value.ToString();
                                repoSys_AllSetting.Edit(objConfig);
                            }
                        }
                        else
                        {
                            objConfig.ID     = Guid.NewGuid();
                            objConfig.Name   = AppConfig.HRM_ATT_OT_OTPERMIT_ISALLOWSPLIT.ToString();
                            objConfig.Value1 = entity.IsAllowSplit.Value.ToString();
                            repoSys_AllSetting.Add(objConfig);
                        }
                    }
                }


                repoSys_AllSetting.SaveChanges();
                return("0");
            }
        }
Esempio n. 39
0
        /// <summary>
        /// [Hieu.van] Tổng Hợp giặt là
        /// </summary>
        /// <param name="dateStart"></param>
        /// <param name="dateEnd"></param>
        /// <param name="lstProfileIDs"></param>
        /// <returns></returns>
        public List <LMS_LaundryRecordEntity> GetLaundryRecordSummary(string _line, string _locker, string _marker, DateTime dateStart, DateTime dateEnd, List <Hre_ProfileEntity> lstProfileIDs, string UserLogin)
        {
            dateStart = dateStart.Date;
            dateEnd   = dateEnd.Date.AddDays(1).AddMilliseconds(-1);

            string status = string.Empty;

            //string strIDs = string.Join(",", lstProfileIDs.ToArray());

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork            = (IUnitOfWork)(new UnitOfWork(context));
                var repoLau_TamScanLog    = new CustomBaseRepository <LMS_TamScanLogLMS>(unitOfWork);
                var repoLau_Line          = new CustomBaseRepository <LMS_LineLMS>(unitOfWork);
                var repoLau_Locker        = new CustomBaseRepository <LMS_LockerLMS>(unitOfWork);
                var repoLau_Marker        = new CustomBaseRepository <LMS_Marker>(unitOfWork);
                var repoLau_LaundryRecord = new CustomBaseRepository <LMS_LaundryRecord>(unitOfWork);
                var repoSys_AllSetting    = new CustomBaseRepository <Sys_AllSetting>(unitOfWork);

                #region cấu hình số phút xử lý trùng
                int rsScanMulti       = 0;
                var rsScanMultiConfig = GetData <Sys_AllSetting>(AppConfig.HRM_LAU_LAUNDRYRECORD_SCANMULTI_CONFIG.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();
                if (rsScanMultiConfig != null)
                {
                    rsScanMulti = rsScanMultiConfig.Value1 != null?int.Parse(rsScanMultiConfig.Value1.ToString()) : 0;

                    dateStart = dateStart.Date.AddHours(rsScanMulti);
                    dateEnd   = dateEnd.Date.AddDays(1).AddHours(rsScanMulti).AddMilliseconds(-1);
                }
                #endregion


                var tamScanLogs = repoLau_TamScanLog
                                  .FindBy(s => dateStart <= s.TimeLog && s.TimeLog <= dateEnd)
                                  .Select(s => new { s.Code, s.TimeLog, s.ID, s.MachineCode })
                                  //.Select(s => new { s.MachineCode, s.CardCode, s.TimeLog, s.Id })
                                  .ToList();
                var cardCodes = tamScanLogs.Select(s => s.Code).ToList();
                //strIDs = Common.DotNetToOracle(strIDs);
                //var profiles = GetData<Hre_ProfileEntity>(strIDs, ConstantSql.hrm_hr_sp_get_ProfileByIds, ref status)
                //    .Where(s => cardCodes.Contains(s.CodeAttendance) && lstProfileIDs.Contains(s.ID))
                var profiles = lstProfileIDs
                               .Where(s => cardCodes.Contains(s.CodeAttendance))
                               .Select(s => new { s.ID, s.CodeAttendance, s.CodeEmp, s.ProfileName, s.OrgStructureName }).ToList();
                tamScanLogs = tamScanLogs
                              .Where(s => profiles.Select(p => p.CodeAttendance).Contains(s.Code))
                              .OrderBy(s => s.Code)
                              .ThenBy(s => s.TimeLog)
                              .ToList();

                #region lấy line-locker-marker và xử lý khi tìm kiếm
                var lines   = repoLau_Line.FindBy(s => s.IsDelete == null).ToList();
                var Lockers = repoLau_Locker.FindBy(s => s.IsDelete == null).ToList();
                var Markers = repoLau_Marker.FindBy(s => s.IsDelete == null).ToList();
                if (_line != null)
                {
                    List <Guid> lstLine = _line.Split(',').Select(Guid.Parse).ToList();
                    lines = lines.Where(s => lstLine.Contains(s.ID)).ToList();
                }
                if (_locker != null)
                {
                    List <Guid> lstLocker = _locker.Split(',').Select(Guid.Parse).ToList();
                    Lockers = Lockers.Where(s => lstLocker.Contains(s.ID)).ToList();
                }
                if (_marker != null)
                {
                    List <Guid> lstMarker = _marker.Split(',').Select(Guid.Parse).ToList();
                    Markers = Markers.Where(s => lstMarker.Contains(s.ID)).ToList();
                }
                #endregion

                List <object> lstObj = new List <object>();
                lstObj.Add(dateStart);
                lstObj.Add(dateEnd);
                List <Lau_LaundryRecordCheckEntity> laundryCheckList = GetData <Lau_LaundryRecordCheckEntity>(lstObj, ConstantSql.hrm_lau_sp_get_LaundryRecord_ByDateFromDateTo, UserLogin, ref status);

                LMS_LaundryRecordEntity        laundry   = new LMS_LaundryRecordEntity();
                List <LMS_LaundryRecordEntity> lstRecord = new List <LMS_LaundryRecordEntity>();
                List <LMS_LaundryRecord>       lstAdd    = new List <LMS_LaundryRecord>();
                List <LMS_LaundryRecord>       lstEdit   = new List <LMS_LaundryRecord>();
                List <Guid> lstDuplicateTamScan          = new List <Guid>();
                foreach (var tamScanLog in tamScanLogs)
                {
                    if (lstDuplicateTamScan.Contains(tamScanLog.ID))
                    {
                        continue;
                    }

                    laundry = new LMS_LaundryRecordEntity();
                    var profile = profiles.FirstOrDefault(s => s.CodeAttendance == tamScanLog.Code);
                    var line    = lines.FirstOrDefault(s => tamScanLog.MachineCode == s.MachineCode);

                    if (profile != null && line != null)
                    {
                        #region xử lý bản ghi trùng
                        var tamScanLogProfiles = tamScanLogs
                                                 .Where(s => s.Code == tamScanLog.Code && s.TimeLog.Value.Date == tamScanLog.TimeLog.Value.Date && s.MachineCode == tamScanLog.MachineCode)
                                                 .OrderBy(s => s.TimeLog)
                                                 .ToList();
                        if (tamScanLogProfiles.Count > 1 && rsScanMulti > 0)
                        {
                            for (int i = 0; i < tamScanLogProfiles.Count; i++)
                            {
                                var tamsanFirst = tamScanLogProfiles[i];
                                int j           = i + 1;
                                if (j > tamScanLogProfiles.Count - 1)
                                {
                                    j = i;
                                }
                                var tamsanNear = tamScanLogProfiles[j];
                                if (tamsanNear.TimeLog.Value.Subtract(tamsanFirst.TimeLog.Value).TotalMinutes < rsScanMulti && tamsanFirst.ID != tamsanNear.ID)
                                {
                                    if (tamsanFirst.MachineCode == tamsanNear.MachineCode)
                                    {
                                        lstDuplicateTamScan.Add(tamsanNear.ID);
                                        break;
                                    }
                                }
                            }
                        }
                        #endregion

                        #region xử lý add record
                        laundry.ProfileID      = profile.ID;
                        laundry.ProfileName    = profile.ProfileName;
                        laundry.CodeAttendance = profile.CodeAttendance;
                        laundry.TimeLog        = tamScanLog.TimeLog;
                        laundry.Status         = HRM.Infrastructure.Utilities.LaundryRecordStatus.E_SUBMIT.ToString();
                        laundry.Type           = LaundryRecordType.E_AUTO.ToString();
                        if (tamScanLog.MachineCode != null)
                        {
                            laundry.MachineCode = tamScanLog.MachineCode;
                            if (line != null)
                            {
                                laundry.LineLMSName = line.LineLMSName;
                                laundry.LineID      = line.ID;
                                laundry.Amount      = (decimal)line.Amount;

                                if (line.LockerID != null)
                                {
                                    var locker = Lockers.Where(c => c.ID == line.LockerID).FirstOrDefault();
                                    laundry.LockerLMSName = locker.LockerLMSName;
                                    laundry.LockerID      = locker.ID;
                                }
                                if (line.MarkerID != null)
                                {
                                    var marker = Markers.Where(c => c.ID == line.MarkerID).FirstOrDefault();
                                    laundry.MarkerName = marker.MarkerName;
                                    laundry.MarkerID   = marker.ID;
                                }
                            }
                        }

                        laundry.DateCreate = DateTime.Now;
                        var recordAdd = laundry.CopyData <LMS_LaundryRecord>();
                        var CheckList = laundryCheckList.Where(s => s.ProfileID == laundry.ProfileID.Value && s.TimeLog == laundry.TimeLog).ToList();
                        if (CheckList != null)
                        {
                            if (CheckList.Count() > 0)
                            {
                                var idUpdate = CheckList.FirstOrDefault();
                                recordAdd.ID = idUpdate.ID;
                                repoLau_LaundryRecord.Edit(recordAdd);
                                //lstEdit.Add(recordAdd);
                            }
                            else
                            {
                                recordAdd.ID = Guid.NewGuid();
                                repoLau_LaundryRecord.Add(recordAdd);
                                //lstAdd.Add(recordAdd);
                            }
                        }
                        laundry.ID = tamScanLog.ID;
                        lstRecord.Add(laundry);
                        #endregion
                    }
                }
                repoLau_LaundryRecord.SaveChanges();
                //if (lstAdd.Any())
                //{
                //    repoLau_LaundryRecord.Add(lstAdd);
                //    repoLau_LaundryRecord.SaveChanges();
                //}
                //if (lstEdit.Any())
                //{
                //    repoLau_LaundryRecord.Edit(lstEdit);
                //    repoLau_LaundryRecord.SaveChanges();
                //}
                if (lstRecord.Count > 0)
                {
                    Sys_AllSetting sys = new Sys_AllSetting();
                    Sys_AllSetting rs  = GetData <Sys_AllSetting>(AppConfig.HRM_LAU_LAUNDRYRECORD_SUMMARY.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();

                    sys.Value1 = dateStart.ToString(ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond.ToString());
                    sys.Value2 = dateEnd.ToString(ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond.ToString());
                    sys.Name   = AppConfig.HRM_LAU_LAUNDRYRECORD_SUMMARY.ToString();

                    if (rs != null)
                    {
                        sys.ID = rs.ID;
                        repoSys_AllSetting.Edit(sys);
                    }
                    else
                    {
                        sys.ID = Guid.NewGuid();
                        repoSys_AllSetting.Add(sys);
                    }
                    repoSys_AllSetting.SaveChanges();
                }


                return(lstRecord);
            }
        }
Esempio n. 40
0
        public void ComputeComissionService(Guid? ShopID, DateTime Month, string UserLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                string status = string.Empty;
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoShop = new CustomBaseRepository<Cat_Shop>(unitOfWork);
                var repoRevenueForShop = new CustomBaseRepository<Sal_RevenueForShopEntity>(unitOfWork);
                var repoItemForShopEntity = new CustomBaseRepository<Sal_ItemForShopEntity>(unitOfWork);
                var repoLineItemForShopEntity = new CustomBaseRepository<Sal_LineItemForShopEntity>(unitOfWork);
                var repoRevenueRecord = new CustomBaseRepository<Sal_RevenueRecord>(unitOfWork);

                #region Get Data


                List<object> listModel = new List<object>();
                listModel.AddRange(new object[5]);
                listModel[3] = 1;
                listModel[4] = Int32.MaxValue - 1;
                List<Cat_Shop> listShop = GetData<Cat_Shop>(listModel, ConstantSql.hrm_cat_sp_get_Shop, UserLogin, ref status).ToList();

                listModel = new List<object>();
                listModel.AddRange(new object[4]);
                listModel[2] = 1;
                listModel[3] = Int32.MaxValue - 1;
                List<Cat_ShopGroupEntity> listGroupShop = GetData<Cat_ShopGroupEntity>(listModel, ConstantSql.hrm_cat_sp_get_ShopGroup, UserLogin, ref status).ToList();

                listModel = new List<object>();
                listModel.AddRange(new object[6]);
                listModel[4] = 1;
                listModel[5] = Int32.MaxValue - 1;
                List<Sal_RevenueForShopEntity> listRevenueForShop = GetData<Sal_RevenueForShopEntity>(listModel, ConstantSql.hrm_sal_sp_get_RevenueForShop, UserLogin, ref status).ToList();

                listModel = new List<object>();
                listModel.AddRange(new object[5]);
                listModel[3] = 1;
                listModel[4] = Int32.MaxValue - 1;
                List<Sal_ItemForShopEntity> listItemForShop = GetData<Sal_ItemForShopEntity>(listModel, ConstantSql.hrm_sal_sp_get_ItemForShop, UserLogin, ref status).ToList();

                listModel = new List<object>();
                listModel.AddRange(new object[5]);
                listModel[3] = 1;
                listModel[4] = Int32.MaxValue - 1;
                List<Sal_LineItemForShopEntity> listLineItemForShop = GetData<Sal_LineItemForShopEntity>(listModel, ConstantSql.hrm_sal_sp_get_LineItemForShop, UserLogin, ref status).ToList();

                listModel = new List<object>();
                listModel.AddRange(new object[4]);
                listModel[0] = Month;
                listModel[2] = 1;
                listModel[3] = Int32.MaxValue - 1;
                List<Sal_RevenueRecord> listRevenueRecord = GetData<Sal_RevenueRecord>(listModel, ConstantSql.hrm_sal_sp_get_RevenueRecord, UserLogin, ref status).ToList();

                listModel = new List<object>();
                listModel.AddRange(new object[18]);
                listModel[16] = 1;
                listModel[17] = int.MaxValue - 1;
                List<Hre_ProfileEntity> listProfile = GetData<Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_Profile, UserLogin, ref status).ToList();

                List<Cat_KPIBonusEntity> listKPIBonus = new List<Cat_KPIBonusEntity>();
                listModel = new List<object>();
                listModel.AddRange(new object[4]);
                listModel[2] = 1;
                listModel[3] = Int32.MaxValue - 1;
                listKPIBonus = GetData<Cat_KPIBonusEntity>(listModel, ConstantSql.hrm_cat_sp_get_KPIBonus, UserLogin, ref status).ToList();

                List<Cat_KPIBonusItemEntity> listKPIBonusItem = new List<Cat_KPIBonusItemEntity>();
                listModel = new List<object>();
                listModel.AddRange(new object[4]);
                listModel[2] = 1;
                listModel[3] = Int32.MaxValue - 1;
                listKPIBonusItem = GetData<Cat_KPIBonusItemEntity>(listModel, ConstantSql.hrm_cat_sp_get_KPIBonusItem, UserLogin, ref status).ToList();


                #endregion

                List<Guid> ListShopID = new List<Guid>();
                if (ShopID == null)
                {
                    ListShopID = listShop.Select(m => m.ID).ToList();
                }
                else
                {
                    if (!listShop.Any(m => m.ID == ShopID))
                    {
                        if (!listGroupShop.Any(m => m.ID == ShopID))
                        {
                            ListShopID = listShop.Select(m => m.ID).ToList();
                        }
                        else
                        {
                            ListShopID = listShop.Where(m => m.ShopGroupID == ShopID).Select(m => m.ID).ToList();
                        }
                    }
                    else
                    {
                        ListShopID.Add((Guid)ShopID);
                    }
                }

                List<Sal_RevenueRecord> _tmpRevenueRecord;
                List<ElementFormula> listElementFormula = new List<ElementFormula>();

                foreach (Guid Guid in ListShopID)
                {
                    #region Xóa tháng đã tính trước đó nếu có
                    _tmpRevenueRecord = new List<Sal_RevenueRecord>();
                    _tmpRevenueRecord = listRevenueRecord.Where(m => m.ShopID == Guid && m.Month.Value.Month == Month.Month && m.Month.Value.Year == Month.Year).ToList();
                    if (_tmpRevenueRecord.Count > 0)
                    {
                        foreach (var j in _tmpRevenueRecord)
                        {
                            repoRevenueRecord.Remove(j);
                        }
                    }
                    #endregion

                    #region Lấy các phần tử là Enum
                    Sal_RevenueForShopEntity RevenueForShopItem = new Sal_RevenueForShopEntity();
                    RevenueForShopItem = listRevenueForShop.Where(m => m.ShopID == Guid && m.KPIBonusID == listKPIBonus.Where(t => t.IsTotalRevenue == true).FirstOrDefault().ID && (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).FirstOrDefault();

                    if (RevenueForShopItem != null)
                    {
                        listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_TAGET_SHOP.ToString(), RevenueForShopItem.Target, 0));
                        listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_ACTUAL_SHOP.ToString(), RevenueForShopItem.Actual, 0));
                        listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_PRECENT_REVENUE.ToString(), RevenueForShopItem.Actual / RevenueForShopItem.Target, 0));
                    }
                    else
                    {
                        continue;
                    }

                    listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_COUNT_SHOPMEMBER.ToString(), listProfile.Where(m => m.ShopID == Guid).Count(), 0));

                    listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_COUNT_SL.ToString(), listShop.Where(m => m.ID == Guid).FirstOrDefault().NoShiftLeader, 0));

                    listElementFormula.Add(new ElementFormula(PayrollElement.SAL_COM_RANK.ToString(), listShop.Where(m => m.ID == Guid).FirstOrDefault().Rank, 0));

                    #endregion


                    #region Lấy giá trị cho các loại phần tử là Hoa Hồng

                    double TotalMoney_RevenueForShop = 0;//biến lưu tổng doanh thu cửa hàng sau khi đã trừ tiền SL
                    if (listKPIBonus != null && listKPIBonus.Count > 0)
                    {
                        #region tính số tổng doanh thu sau khi trừ tiền SL

                        RevenueForShopItem = new Sal_RevenueForShopEntity();
                        RevenueForShopItem = listRevenueForShop.Where(m => m.ShopID == Guid && m.KPIBonusID == listKPIBonus.Where(t => t.IsTotalRevenue == true).FirstOrDefault().ID && (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).FirstOrDefault();

                        double Money_SL = 0;
                        if (RevenueForShopItem != null)
                        {
                            Money_SL = (double)GetObjectValue(new List<Cat_ElementEntity>(), listElementFormula, listShop.Single(m => m.ID == Guid).Formular1).Value;
                            double Money_Revenue = (double)RevenueForShopItem.Actual * ((double)GetObjectValue(new List<Cat_ElementEntity>(), listElementFormula, listShop.Single(m => m.ID == Guid).Formular).Value / 100);
                            TotalMoney_RevenueForShop = Money_Revenue - Money_SL;
                        }

                        #endregion
                        Sal_RevenueRecord RecordItem = new Sal_RevenueRecord();
                        foreach (var j in listKPIBonus)
                        {
                            RevenueForShopItem = listRevenueForShop.Where(m => m.ShopID == Guid && m.KPIBonusID == j.ID && (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).FirstOrDefault();

                            RecordItem = new Sal_RevenueRecord();
                            RecordItem.ShopID = Guid;
                            RecordItem.Month = Month;
                            RecordItem.KPIBonusID = j.ID;
                            RecordItem.Type = EnumDropDown.SalesType.E_SALE.ToString();
                            RecordItem.Note = string.Format("{0:n0}", Money_SL);

                            if ((RevenueForShopItem != null && RevenueForShopItem.Target <= RevenueForShopItem.Actual) || (RevenueForShopItem != null && RevenueForShopItem.IsPass != null && RevenueForShopItem.IsPass == true))
                            {
                                Cat_KPIBonusItemEntity bonusItem = listKPIBonusItem.Where(m => m.ShopID == Guid && m.KPIBonusID == j.ID).FirstOrDefault();
                                if (bonusItem != null)
                                {
                                    RecordItem.Amount = TotalMoney_RevenueForShop * (bonusItem.Value / 100);
                                }
                                else
                                {
                                    RecordItem.Amount = 0;
                                }
                            }
                            else
                            {
                                RecordItem.Amount = 0;
                            }
                            repoRevenueRecord.Add(RecordItem);
                        }

                        #region Lấy giá trị cho 2 enum là dòng sản phẩm và sản phẩm

                        //SAL_COM_PERCENT_SHOP_5
                        List<Sal_LineItemForShopEntity> listLineItem = listLineItemForShop.Where(m => m.ShopID == Guid && (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).ToList();

                        RecordItem = new Sal_RevenueRecord();
                        RecordItem.ShopID = Guid;
                        RecordItem.Month = Month;
                        RecordItem.Type = EnumDropDown.SalesType.E_LINEITEM_MAJOR.ToString();

                        if (listLineItem != null && listLineItem.Count > 0 && listLineItem.Any(m => m.Actual < m.Target && m.IsPass != true))
                        {
                            int NumberPass = 0;
                            foreach (var lineItem in listLineItem)
                            {
                                if ((lineItem.IsPass != null && lineItem.IsPass == true) || lineItem.Actual >= lineItem.Target)
                                {
                                    NumberPass++;
                                }
                            }
                            if (NumberPass >= 3)
                            {
                                RecordItem.Amount = TotalMoney_RevenueForShop * (listShop.Single(m => m.ID == Guid).MainLineProduct / 100);
                            }
                            else
                            {
                                RecordItem.Amount = 0;
                            }
                        }
                        else
                        {
                            RecordItem.Amount = TotalMoney_RevenueForShop * (listShop.Single(m => m.ID == Guid).MainLineProduct / 100);
                        }
                        repoRevenueRecord.Add(RecordItem);

                        //SAL_COM_PERCENT_SHOP_6
                        List<Sal_ItemForShopEntity> listItem = listItemForShop.Where(m => m.ShopID == Guid && (m.DateFrom.Value.Month == Month.Month && m.DateFrom.Value.Year == Month.Year) && (m.DateTo.Value.Month == Month.Month && m.DateTo.Value.Year == Month.Year)).ToList();

                        RecordItem = new Sal_RevenueRecord();
                        RecordItem.ShopID = Guid;
                        RecordItem.Month = Month;
                        RecordItem.Type = EnumDropDown.SalesType.E_ITEM_MAJOR.ToString();

                        if (listItem != null && listItem.Count > 0 && listItem.Any(m => m.Actual < m.Target && m.IsPass != true))
                        {
                            RecordItem.Amount = 0;
                        }
                        else
                        {
                            RecordItem.Amount = TotalMoney_RevenueForShop * (listShop.Single(m => m.ID == Guid).PromoteProduct / 100);
                        }
                        repoRevenueRecord.Add(RecordItem);

                        #endregion
                    }
                    #endregion

                }
                repoRevenueRecord.SaveChanges();
            }
        }
Esempio n. 41
0
        /// <summary>
        /// [Hieu.Van]
        /// Xử lý Từ Chối
        /// </summary>
        /// <param name="LoginID"></param>
        /// <param name="userApprovedID"></param>
        /// <param name="recordID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string ProcessReject(string host, Guid LoginID, Guid recordID, string type)
        {
            DataErrorCode status = DataErrorCode.Success;
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoFIN_PurchaseRequest = new CustomBaseRepository<FIN_PurchaseRequest>(unitOfWork);
                var repoSys_UserApprove = new CustomBaseRepository<Sys_UserApprove>(unitOfWork);
                var repoSys_UserInfo = new CustomBaseRepository<Sys_UserInfo>(unitOfWork);

                var record = repoFIN_PurchaseRequest.FindBy(s => s.ID == recordID).FirstOrDefault();
                if (record.Status == EnumDropDown.Status.E_REJECTED.ToString())
                {
                    return DataErrorCode.Error_Reject.ToString();
                }
                var userApproved = repoSys_UserApprove.FindBy(s => s.ID == record.UserApproveID).FirstOrDefault();
                // Kiểm tra tài khoản login có được phép Duyệt hay ko?
                if (LoginID == Guid.Empty || userApproved.UserApproveID != LoginID)
                {
                    // kiểm tra nếu bản ghi có tk duyệt trống (tức bản ghi mới tạo) và tk login = tk tạo thì cho duyệt tiếp tục
                    if (record.UserApproveID == null && record.UserCreateID == LoginID)
                    {
                    }
                    else
                    {
                        return DataErrorCode.NoPermission.ToString();
                    }
                }

                record.Status = EnumDropDown.Status.E_REJECTED.ToString();
                repoFIN_PurchaseRequest.Edit(record);
                status = repoFIN_PurchaseRequest.SaveChanges();

                return status.ToString();
            }
        }
Esempio n. 42
0
        /// <summary>
        /// Lấy tất cả các bản ghi 
        /// Get by key
        /// </summary>
        /// <returns></returns>
        public void SaveConfig(List<Dictionary<string,string>> lstModel)
        {
            using (var context = new VnrHrmDataContext())
            {
                IUnitOfWork unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repo = new CustomBaseRepository<Sys_AllSetting>(unitOfWork);


                string status = string.Empty;
                List<Dictionary<Guid, string>> lstUpdate = new List<Dictionary<Guid, string>>();
                var valueTemp = new Sys_AllSetting();
                var modelTemp = new Sys_AllSetting();
                List<Guid> lstConfigIds = new List<Guid>();
                List<Sys_AllSetting> lstAdd = new List<Sys_AllSetting>();
                List<Sys_AllSetting> lstEdit = new List<Sys_AllSetting>();
                List<Sys_AllSetting> lstDel = new List<Sys_AllSetting>();

                var getdata = repo.FindBy(s => s.IsDelete == null).ToList();

                if (lstModel[0].FirstOrDefault().Value.Length > 0)
                {
                    var lstStr = lstModel.FirstOrDefault()["lstConfigIds"].Split(',');
                    lstConfigIds = lstStr.Select(Guid.Parse).ToList();
                }

                foreach (var item in lstConfigIds)
                {
                    modelTemp = GetById<Sys_AllSetting>(item, ref status);
                    lstUpdate.Add(new Dictionary<Guid, string>() { { modelTemp.ID, modelTemp.Name } });
                }
                for (int i = 1; i < lstModel.Count; i++)
                {
                    var lstEntity = getdata.Where(s => s.Name == lstModel[i].FirstOrDefault().Key).ToList();

                    if (lstEntity.Count == 0)
                    {
                        valueTemp = new Sys_AllSetting();
                        valueTemp.ID = Guid.NewGuid();
                        valueTemp.Name = lstModel[i].FirstOrDefault().Key;
                        valueTemp.Value1 = lstModel[i].FirstOrDefault().Value;
                        lstAdd.Add(valueTemp);
                        continue;
                    }
                    if (lstEntity.Count > 0)
                    {
                        valueTemp = new Sys_AllSetting();
                        foreach (var item in lstEntity)
                        {
                            item.IsDelete = true;
                            lstDel.Add(item);
                            //repo.Edit(item);
                        }
                        var isUpdate = lstUpdate.Where(s => s.FirstOrDefault().Value == lstModel[i].FirstOrDefault().Key).FirstOrDefault();
                        if (isUpdate != null)
                        {
                            valueTemp.ID = lstEntity.FirstOrDefault().ID;
                            valueTemp.Name = lstModel[i].FirstOrDefault().Key;
                            valueTemp.Value1 = lstModel[i].FirstOrDefault().Value;
                            valueTemp.IsDelete = null;
                            lstEdit.Add(valueTemp);
                        }
                        else
                        {
                            valueTemp.ID = Guid.NewGuid();
                            valueTemp.Name = lstModel[i].FirstOrDefault().Key;
                            valueTemp.Value1 = lstModel[i].FirstOrDefault().Value;
                            lstAdd.Add(valueTemp);
                        }
                    }
                }
                repo.Edit(lstDel);
                repo.Add(lstAdd);
                repo.Edit(lstEdit);
                repo.SaveChanges();

                
            }
        }
Esempio n. 43
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();
                        }
                    }
                    
                }

            }
        }
        /// <summary>
        /// Button Tính Phép Bệnh
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="orgStructure"></param>
        /// <param name="LstProfileStatus"></param>
        /// <returns></returns>
        public bool ComputeAnnualSickLeaveDetail(int Year, string orgStructure, string LstProfileStatus, string UserLogin)
        {
            var result = false;

            using (var context = new VnrHrmDataContext())
            {
                string status     = string.Empty;
                var    unitOfWork = (IUnitOfWork) new UnitOfWork(context);
                var    repoAtt_AnnualLeaveDetail = new CustomBaseRepository <Att_AnnualLeaveDetail>(unitOfWork);
                var    repoHre_Profile           = new CustomBaseRepository <Hre_Profile>(unitOfWork);
                var    repoHre_HDTJob            = new CustomBaseRepository <Hre_HDTJob>(unitOfWork);
                var    repoCat_DayOff            = new CustomBaseRepository <Cat_DayOff>(unitOfWork);
                var    repoCat_LeaveDayType      = new CustomBaseRepository <Cat_LeaveDayType>(unitOfWork);
                var    repoAtt_LeaveDay          = new CustomBaseRepository <Att_LeaveDay>(unitOfWork);
                var    repoCat_JobTitle          = new CustomBaseRepository <Cat_JobTitle>(unitOfWork);


                #region FilterInfo
                string E_SICK_LEAVE = AnnualLeaveDetailType.E_SICK_LEAVE.ToString();

                Att_AnnualLeaveDetail AnnualLeaveDetailTop = repoAtt_AnnualLeaveDetail
                                                             .FindBy(m => m.IsDelete == null && m.Type == E_SICK_LEAVE && m.Year == Year).FirstOrDefault();

                DateTime beginyear = (AnnualLeaveDetailTop == null || AnnualLeaveDetailTop.MonthStart == null) ? new DateTime(Year, 1, 1) : AnnualLeaveDetailTop.MonthStart.Value;
                DateTime endYear   = beginyear.AddYears(1).AddMinutes(-1);

                List <object> lstObj = new List <object>();
                lstObj.Add(orgStructure);
                lstObj.Add(null);
                lstObj.Add(null);
                var lstProfileQuery = GetData <Hre_ProfileEntity>(lstObj, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrg, UserLogin, ref status).ToList();

                if (LstProfileStatus != null)
                {
                    if (LstProfileStatus == StatusEmpLeaveDetail.E_NEWEMPINYEAR.ToString())
                    {
                        lstProfileQuery = lstProfileQuery.Where(m => m.DateHire != null && m.DateHire >= beginyear && m.DateHire <= endYear).ToList();
                    }
                    if (LstProfileStatus == StatusEmpLeaveDetail.E_RESIGNEMPINYEAR.ToString())
                    {
                        lstProfileQuery = lstProfileQuery.Where(m => m.DateQuit != null && m.DateQuit >= beginyear && m.DateQuit <= endYear).ToList();
                    }
                    if (LstProfileStatus == StatusEmpLeaveDetail.E_EMPOFHDT4.ToString())
                    {
                        string      Job4           = HDTJobType.E_Four.ToString();
                        List <Guid> lstprofileHDT4 = repoHre_HDTJob
                                                     .FindBy(m => m.IsDelete == null && m.Type == Job4 && m.DateFrom <= endYear && m.DateTo >= beginyear && m.ProfileID != null)
                                                     .Select(m => m.ProfileID.Value).ToList <Guid>();
                        lstProfileQuery = lstProfileQuery.Where(m => lstprofileHDT4.Contains(m.ID)).ToList();
                    }
                    if (LstProfileStatus == StatusEmpLeaveDetail.E_EMPOFHDT5.ToString())
                    {
                        string      Job5           = HDTJobType.E_Five.ToString();
                        List <Guid> lstprofileHDT5 = repoHre_HDTJob
                                                     .FindBy(m => m.IsDelete == null && m.Type == Job5 && m.DateFrom <= endYear && m.DateTo >= beginyear && m.ProfileID != null)
                                                     .Select(m => m.ProfileID.Value).ToList <Guid>();
                        lstProfileQuery = lstProfileQuery.Where(m => lstprofileHDT5.Contains(m.ID)).ToList();
                    }
                }

                List <Guid> lstProfileID = lstProfileQuery.Select(m => m.ID).Distinct().ToList <Guid>();
                #endregion
                #region get Data
                //string E_STANDARD_WORKDAY = AppConfig.E_STANDARD_WORKDAY.ToString();
                //Sys_AppConfig appconfig = EntityService.CreateQueryable<Sys_AppConfig>(false, GuidContext, Guid.Empty, m => m.Info == E_STANDARD_WORKDAY).FirstOrDefault();
                //if (appconfig == null || string.IsNullOrEmpty(appconfig.Value76) || string.IsNullOrEmpty(appconfig.Value77))
                //{
                //    Common.MessageBoxs(Messages.Msg, Messages.PleaseConfigSickLeaveAtTotalConfig, MessageBox.Icon.WARNING, string.Empty);
                //    return;
                //}

                string        HRM_ATT_ANNUALSICKLEAVE_ = AppConfig.HRM_ATT_ANNUALSICKLEAVE_.ToString();
                List <object> lstO = new List <object>();
                lstO.Add(HRM_ATT_ANNUALSICKLEAVE_);
                lstO.Add(null);
                lstO.Add(null);
                var config = GetData <Sys_AllSettingEntity>(lstO, ConstantSql.hrm_sys_sp_get_AllSetting, UserLogin, ref status);

                var formular1 = config.Where(s => s.Name == AppConfig.HRM_ATT_ANNUALSICKLEAVE_FORMULARCONFIG.ToString()).FirstOrDefault();
                var formular2 = config.Where(s => s.Name == AppConfig.HRM_ATT_ANNUALSICKLEAVE_FORMULARCOMPUTE.ToString()).FirstOrDefault();

                if (config == null || string.IsNullOrEmpty(formular1.Value1) || string.IsNullOrEmpty(formular2.Value1))
                {
                    //Common.MessageBoxs(Messages.Msg, Messages.PleaseConfigAnnualLeaveAtTotalConfig, MessageBox.Icon.WARNING, string.Empty);
                    return(result);
                }

                string formularConfig  = formular1.Value1;
                string formularCompute = formular2.Value1;

                ParamGetConfigANL configAnl = new ParamGetConfigANL();
                (new Att_AttendanceServices()).GetConfigANL(formularConfig, out configAnl);

                int           MonthBegin             = 1;
                List <string> lstCodeLeaveTypeNonAnl = new List <string>();
                if (configAnl != null && configAnl.monthBeginYear != null)
                {
                    MonthBegin = configAnl.monthBeginYear;
                }
                if (configAnl != null && configAnl.lstCodeLeaveNonANL != null)
                {
                    lstCodeLeaveTypeNonAnl = configAnl.lstCodeLeaveNonANL;
                }
                DateTime BeginYear = new DateTime(Year, MonthBegin, 1);
                DateTime EndYear   = BeginYear.AddYears(1).AddMinutes(-1);

                string          E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();
                List <DateTime> lstDayOff  = repoCat_DayOff
                                             .FindBy(m => m.IsDelete == null && m.DateOff > BeginYear && m.DateOff <= EndYear)
                                             .Select(m => m.DateOff).Distinct().ToList <DateTime>();
                List <Hre_ProfileEntity> lstprofile = lstProfileQuery
                                                      .Where(m => m.DateQuit == null || (m.DateQuit != null && m.DateQuit > BeginYear))
                                                      .ToList <Hre_ProfileEntity>();
                List <Guid> lstLeavedayTypeNonAnl = repoCat_LeaveDayType
                                                    .FindBy(m => m.IsDelete == null && lstCodeLeaveTypeNonAnl.Contains(m.Code)).Select(m => m.ID).ToList <Guid>();
                List <Att_LeaveDay> lstleavedayNonANl = repoAtt_LeaveDay
                                                        .FindBy(m => m.IsDelete == null && m.Status == E_APPROVED && lstLeavedayTypeNonAnl.Contains(m.LeaveDayTypeID) &&
                                                                lstProfileID.Contains(m.ProfileID)).ToList <Att_LeaveDay>();
                List <Att_LeaveDay> lstleavedayNonANlInYear = lstleavedayNonANl.Where(m => m.DateStart <= EndYear && m.DateEnd >= BeginYear).ToList <Att_LeaveDay>();
                List <Hre_HDTJob>   lstHDTJob = repoHre_HDTJob
                                                .FindBy(m => m.IsDelete == null && m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value)).ToList <Hre_HDTJob>();
                List <Cat_JobTitle> lstJobtitle = repoCat_JobTitle.FindBy(s => s.IsDelete == null).ToList();
                #endregion

                List <Att_AnnualLeaveDetail> lstAnnualDetail = new List <Att_AnnualLeaveDetail>();
                foreach (var item in lstprofile)
                {
                    List <Att_LeaveDay> lstLeavedayNonAnlByProfile       = lstleavedayNonANl.Where(m => m.ProfileID == item.ID).ToList();
                    List <Att_LeaveDay> lstLeavedayNonAnlByProfileInYear = lstleavedayNonANlInYear.Where(m => m.ProfileID == item.ID).ToList();
                    List <Hre_HDTJob>   lstHDTJobByProfile = lstHDTJob.Where(m => m.ProfileID == item.ID).ToList();
                    double AvailabelInYear = (new Att_AttendanceServices()).GetAnnualLeaveAvailableAllYear(Year, null, item.DateHire,
                                                                                                           item.DateEndProbation, item.DateQuit, formularConfig,
                                                                                                           formularCompute, lstLeavedayNonAnlByProfileInYear, lstJobtitle, lstDayOff, lstHDTJobByProfile, lstLeavedayNonAnlByProfile);
                    Att_AnnualLeaveDetail annualProfile = new Att_AnnualLeaveDetail();
                    annualProfile.ID         = Guid.NewGuid();
                    annualProfile.ProfileID  = item.ID;
                    annualProfile.MonthStart = BeginYear;
                    annualProfile.MonthEnd   = EndYear;
                    annualProfile.Year       = Year;
                    annualProfile.Type       = E_SICK_LEAVE;
                    annualProfile.Month1     = AvailabelInYear;
                    annualProfile.Month2     = AvailabelInYear;
                    annualProfile.Month3     = AvailabelInYear;
                    annualProfile.Month4     = AvailabelInYear;
                    annualProfile.Month5     = AvailabelInYear;
                    annualProfile.Month6     = AvailabelInYear;
                    annualProfile.Month7     = AvailabelInYear;
                    annualProfile.Month8     = AvailabelInYear;
                    annualProfile.Month9     = AvailabelInYear;
                    annualProfile.Month10    = AvailabelInYear;
                    annualProfile.Month11    = AvailabelInYear;
                    annualProfile.Month12    = AvailabelInYear;
                    lstAnnualDetail.Add(annualProfile);
                }

                DataErrorCode DataErr = DataErrorCode.Unknown;

                if (lstAnnualDetail.Count > 0)
                {
                    #region lấy dữ liệu dưới DB xóa đi
                    List <Guid> lstProfileID_InDB = lstAnnualDetail.Where(m => m.ProfileID != null).Select(m => m.ProfileID.Value).ToList();


                    List <Att_AnnualLeaveDetail> lstAnnualLeaveDetail_InDB = repoAtt_AnnualLeaveDetail
                                                                             .FindBy(m => m.IsDelete == null && m.Year == Year && m.Type == E_SICK_LEAVE && m.ProfileID != null && lstProfileID_InDB.Contains(m.ProfileID.Value)).ToList <Att_AnnualLeaveDetail>();
                    foreach (var item in lstAnnualLeaveDetail_InDB)
                    {
                        item.IsDelete = true;
                    }
                    #endregion

                    repoAtt_AnnualLeaveDetail.Add(lstAnnualDetail);
                    try
                    {
                        repoAtt_AnnualLeaveDetail.SaveChanges();
                    }
                    catch (Exception)
                    {
                        return(false);
                    }

                    //EntityService.AddEntity<Att_AnnualLeaveDetail>(GuidContext, lstAnnualDetail.ToArray());
                    //DataErr = EntityService.SubmitChanges(GuidContext, LoginUserID);

                    //if (DataErr == DataErrorCode.Success)
                    //{
                    //    Common.MessageBoxs(Messages.Msg, Messages.SaveSuccess, MessageBox.Icon.INFO, string.Empty);
                    //}
                    //else
                    //{
                    //    Common.MessageBoxs(Messages.Msg, Messages.SaveUnSuccess, MessageBox.Icon.INFO, string.Empty);
                    //}
                }
                //else
                //{
                //    Common.MessageBoxs(Messages.Msg, Messages.NoDataToCompute, MessageBox.Icon.WARNING, string.Empty);
                //}
                result = true;
            }
            return(result);
        }
Esempio n. 45
0
        public List <Can_MealRecordEntity> GetMealRecordSummary(string _line, string _catering, string _canteen, DateTime dateStart, DateTime dateEnd, List <Hre_ProfileEntity> lstProfileIDs, string UserLogin)
        {
            dateStart = dateStart.Date;
            dateEnd   = dateEnd.Date.AddDays(1).AddMilliseconds(-1);

            using (var context = new VnrHrmDataContext())
            {
                var    unitOfWork         = (IUnitOfWork)(new UnitOfWork(context));
                var    repoCan_MealRecord = new CustomBaseRepository <Can_MealRecord>(unitOfWork);
                var    repoCan_TamScanLog = new CustomBaseRepository <Can_TamScanLogCMS>(unitOfWork);
                var    repoCan_Line       = new CustomBaseRepository <Can_Line>(unitOfWork);
                var    repoCan_Canteen    = new CustomBaseRepository <Can_Canteen>(unitOfWork);
                var    repoCan_Catering   = new CustomBaseRepository <Can_Catering>(unitOfWork);
                var    repoSys_AllSetting = new CustomBaseRepository <Sys_AllSetting>(unitOfWork);
                string status             = string.Empty;
                //string strIDs = string.Join(",", lstProfileIDs.ToArray());
                #region xử lý cấu hình giờ kết thúc ăn - DateStart & DateEnd
                DateTime dateConfig   = DateTime.MinValue;
                var      rsTimeConfig = GetData <Sys_AllSettingEntity>(AppConfig.HRM_CAN_MEALRECORD_EATEND_CONFIG.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();
                if (rsTimeConfig != null && rsTimeConfig.Value1 != null)
                {
                    dateConfig = DateTimeHelper.ConvertStringToDateTime(rsTimeConfig.Value1, ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond_ffffff.ToString());
                }
                double hourConfig = dateConfig.Hour + (((double)dateConfig.Minute) / 60);
                dateStart = dateStart.Date.AddHours(hourConfig);
                dateEnd   = dateEnd.Date.AddDays(1).AddHours(hourConfig).AddMilliseconds(-1);
                #endregion

                #region cấu hình số phút xử lý trùng
                int rsScanMulti       = 0;
                var rsScanMultiConfig = GetData <Sys_AllSettingEntity>(AppConfig.HRM_CAN_MEALRECORD_SCANMULTI_CONFIG.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();

                if (rsScanMultiConfig != null)
                {
                    rsScanMulti = rsScanMultiConfig.Value1 != null?int.Parse(rsScanMultiConfig.Value1.ToString()) : 0;
                }
                #endregion

                var tamScanLogs = repoCan_TamScanLog
                                  .FindBy(s => dateStart <= s.TimeLog && s.TimeLog <= dateEnd)
                                  .Select(s => new { s.MachineCode, s.CardCode, s.TimeLog, s.ID })
                                  .ToList();
                var cardCodes = tamScanLogs.Select(s => s.CardCode).ToList();

                //strIDs = Common.DotNetToOracle(strIDs);
                //var profiles = GetData<Hre_ProfileEntity>(strIDs, ConstantSql.hrm_hr_sp_get_ProfileByIds, ref status)
                //    .Where(s => cardCodes.Contains(s.CodeAttendance) && lstProfileIDs.Contains(s.ID))
                var profiles = lstProfileIDs
                               .Where(s => cardCodes.Contains(s.CodeAttendance))
                               .Select(s => new { s.ID, s.CodeAttendance, s.CodeEmp, s.ProfileName, s.OrgStructureName }).ToList();

                tamScanLogs = tamScanLogs.Where(s => profiles.Select(p => p.CodeAttendance).Contains(s.CardCode)).OrderBy(s => s.CardCode).ThenBy(s => s.TimeLog).ToList();
                var lines     = repoCan_Line.FindBy(s => s.IsDelete == null).ToList();
                var canteens  = repoCan_Canteen.FindBy(s => s.IsDelete == null).ToList();
                var caterings = repoCan_Catering.FindBy(s => s.IsDelete == null).ToList();
                if (_line != null)
                {
                    List <Guid> lstLine = _line.Split(',').Select(Guid.Parse).ToList();
                    lines = lines.Where(s => lstLine.Contains(s.ID)).ToList();
                }
                if (_canteen != null)
                {
                    List <Guid> lstcanteen = _canteen.Split(',').Select(Guid.Parse).ToList();
                    canteens = canteens.Where(s => lstcanteen.Contains(s.ID)).ToList();
                }
                if (_catering != null)
                {
                    List <Guid> lstcatering = _catering.Split(',').Select(Guid.Parse).ToList();
                    caterings = caterings.Where(s => lstcatering.Contains(s.ID)).ToList();
                }

                List <object> lstObj = new List <object>();
                lstObj.Add(dateStart);
                lstObj.Add(dateEnd);
                List <Can_MealRecordCheckEntity> mealRecordCheckList = GetData <Can_MealRecordCheckEntity>(lstObj, ConstantSql.hrm_can_sp_get_MealRecord_ByDateFromDateTo, UserLogin, ref status);
                Can_MealRecordEntity             record    = new Can_MealRecordEntity();
                List <Can_MealRecordEntity>      lstRecord = new List <Can_MealRecordEntity>();
                List <Can_MealRecord>            lstEdit   = new List <Can_MealRecord>();
                List <Can_MealRecord>            lstAdd    = new List <Can_MealRecord>();

                List <Guid> lstDuplicateTamScan = new List <Guid>();
                foreach (var tamScanLog in tamScanLogs)
                {
                    if (lstDuplicateTamScan.Contains(tamScanLog.ID))
                    {
                        continue;
                    }

                    record = new Can_MealRecordEntity();
                    var profile = profiles.FirstOrDefault(s => s.CodeAttendance == tamScanLog.CardCode);
                    var line    = lines.FirstOrDefault(s => tamScanLog.MachineCode == s.MachineCode);

                    if (profile != null && line != null)
                    {
                        #region xử lý quẹt thẻ trùng theo HRM_CAN_MEALRECORD_SCANMULTI_CONFIG
                        var tamScanLogProfiles = tamScanLogs
                                                 .Where(s => s.CardCode == tamScanLog.CardCode && s.TimeLog.Value.Date == tamScanLog.TimeLog.Value.Date && s.MachineCode == tamScanLog.MachineCode)
                                                 .OrderBy(s => s.TimeLog)
                                                 .ToList();

                        if (tamScanLogProfiles.Count > 1 && rsScanMulti > 0)
                        {
                            for (int i = 0; i < tamScanLogProfiles.Count; i++)
                            {
                                var tamsanFirst = tamScanLogProfiles[i];
                                int j           = i + 1;
                                if (j > tamScanLogProfiles.Count - 1)
                                {
                                    j = i;
                                }
                                var tamsanNear = tamScanLogProfiles[j];

                                if (tamsanNear.TimeLog.Value.Subtract(tamsanFirst.TimeLog.Value).TotalMinutes < rsScanMulti &&
                                    tamsanFirst.ID != tamsanNear.ID)
                                {
                                    if (tamsanFirst.MachineCode == tamsanNear.MachineCode)
                                    {
                                        lstDuplicateTamScan.Add(tamsanNear.ID);
                                        break;
                                    }
                                }
                            }
                        }
                        #endregion

                        #region xử lý add record
                        record.TimeLog = tamScanLog.TimeLog.HasValue ? tamScanLog.TimeLog.Value : DateTime.MinValue;
                        if (record.TimeLog < record.TimeLog.Value.Date.AddHours(hourConfig))
                        {
                            record.WorkDay = record.TimeLog.Value.AddDays(-1);
                        }
                        else
                        {
                            record.WorkDay = record.TimeLog;
                        }

                        if (tamScanLog.MachineCode != null)
                        {
                            record.MachineCode = tamScanLog.MachineCode;
                            if (line != null)
                            {
                                record.LineName = line.LineName;
                                record.LineID   = line.ID;
                                record.Amount   = (decimal)line.Amount;
                                if (line.CanteenID != null)
                                {
                                    var cant = canteens.Where(c => c.ID == line.CanteenID).FirstOrDefault();
                                    record.CanteenName = cant.CanteenName;
                                    record.CanteenID   = line.CanteenID;
                                }
                                if (line.CateringID != null)
                                {
                                    var cater = caterings.Where(c => c.ID == line.CateringID).FirstOrDefault();
                                    record.CateringName = cater.CateringName;
                                    record.CateringID   = line.CateringID;
                                }
                            }
                        }

                        record.ProfileName      = profile.ProfileName;
                        record.CodeEmp          = profile.CodeEmp;
                        record.OrgStructureName = profile.OrgStructureName;
                        record.CodeAttendance   = profile.CodeAttendance;
                        record.DateCreate       = DateTime.Now;

                        var recordAdd = record.CopyData <Can_MealRecord>();
                        recordAdd.ProfileID = profile.ID;
                        var CheckList = mealRecordCheckList.Where(s => s.ProfileID == profile.ID && s.TimeLog == tamScanLog.TimeLog).ToList();
                        if (CheckList != null)
                        {
                            if (CheckList.Count() > 0)
                            {
                                var idUpdate = CheckList.FirstOrDefault();
                                recordAdd.ID = idUpdate.ID;
                                //lstEdit.Add(recordAdd);
                                repoCan_MealRecord.Edit(recordAdd);
                            }
                            else
                            {
                                recordAdd.ID = Guid.NewGuid();
                                repoCan_MealRecord.Add(recordAdd);
                                //lstAdd.Add(recordAdd);
                            }
                        }
                        record.ID = tamScanLog.ID;
                        lstRecord.Add(record);
                        #endregion
                    }
                }

                repoCan_MealRecord.SaveChanges();


                if (lstRecord.Count > 0)
                {
                    Sys_AllSetting sys = new Sys_AllSetting();
                    Sys_AllSetting rs  = GetData <Sys_AllSetting>(AppConfig.HRM_CAN_MEALRECORD_SUMMARY.ToString(), ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();
                    sys.Value1 = dateStart.ToString(ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond.ToString());
                    sys.Value2 = dateEnd.ToString(ConstantFormat.HRM_Format_YearMonthDay_HoursMinSecond.ToString());
                    sys.Name   = AppConfig.HRM_CAN_MEALRECORD_SUMMARY.ToString();

                    if (rs != null)
                    {
                        sys.ID = rs.ID;
                        repoSys_AllSetting.Edit(sys);
                    }
                    else
                    {
                        sys.ID = Guid.NewGuid();
                        repoSys_AllSetting.Add(sys);
                    }
                    repoSys_AllSetting.SaveChanges();
                }
                //lstRecord.Where().(s => s.MealAllowanceTypeName = ConstantDisplay.HRM_Enum_Submit.TranslateString()).ToList();
                return(lstRecord);
            }
        }
        /// <summary>
        /// Button Tính Phép Bệnh (Cơ Chế Mới)
        /// Lưu vào Att_AnnualDetail
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="orgStructure"></param>
        /// <param name="LstProfileStatus"></param>
        /// <returns></returns>
        public bool ComputeAnnualSick(int Year, string orgStructure, string LstProfileStatus, bool isFullEmp, string UserLogin)
        {
            var result = false;

            using (var context = new VnrHrmDataContext())
            {
                string status     = string.Empty;
                var    unitOfWork = (IUnitOfWork) new UnitOfWork(context);
                var    repoCat_GradeAttendance = new CustomBaseRepository <Cat_GradeAttendance>(unitOfWork);
                var    repoCat_DayOff          = new CustomBaseRepository <Cat_DayOff>(unitOfWork);
                var    repoCat_Shift           = new CustomBaseRepository <Cat_Shift>(unitOfWork);
                var    repoAtt_AnnualDetail    = new CustomBaseRepository <Att_AnnualDetail>(unitOfWork);
                var    repoAtt_RosterGroup     = new CustomBaseRepository <Att_RosterGroup>(unitOfWork);
                var    repoAtt_AnnualLeave     = new CustomBaseRepository <Att_AnnualLeave>(unitOfWork);
                var    repoAtt_Grade           = new CustomBaseRepository <Att_Grade>(unitOfWork);
                var    repoSys_AllSetting      = new CustomBaseRepository <Sys_AllSetting>(unitOfWork);

                List <Guid> lstLeaveDayApproveIDs = new List <Guid>();
                List <Guid> lstLeaveDayRejectIDs  = new List <Guid>();
                var         shifts = repoCat_Shift.FindBy(s => s.IsDelete == null).ToList();

                List <object> lstObj = new List <object>();
                lstObj.Add(orgStructure);
                lstObj.Add(null);
                lstObj.Add(null);
                var lstProfile = GetData <Hre_ProfileEntity>(lstObj, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrg, UserLogin, ref status);

                List <Att_AnnualDetail> lstResult    = new List <Att_AnnualDetail>();
                List <Guid>             lstProfileID = lstProfile.Select(m => m.ID).ToList();
                int      BeginMonth         = MonthStartAnl;
                DateTime BeginYear          = new DateTime(Year, BeginMonth, 1);
                DateTime EndYear            = BeginYear.AddYears(1).AddMinutes(-1);
                DateTime BeginYearToGetData = BeginYear.AddMonths(-1); //trừ một tháng để lấy data (bao những data thuộc những ngày trước tháng dành cho chế độ lương ko phải từ ngày 1)

                var    lstGradeCgf = repoCat_GradeAttendance.FindBy(s => s.ID != null).ToList();
                string E_APPROVED  = LeaveDayStatus.E_APPROVED.ToString();

                var lstAnnualDetailInDB = new List <Att_AnnualDetail>();
                var lstLeaveDaySick     = new List <Att_LeaveDay>();
                var lstAttGrade         = new List <Att_Grade>();
                var lstAnualLeaveCfg    = new List <Att_AnnualLeave>();
                var lstWorkingHistory   = new List <Hre_WorkHistory>();
                var lstRoster           = new List <Att_Roster>();

                #region Lấy Dữ Liệu
                List <object> lst2Param = new List <object>();
                lst2Param.Add(null);
                lst2Param.Add(EndYear);

                List <object> lst3Param = new List <object>();
                lst3Param.Add(null);
                lst3Param.Add(null);
                lst3Param.Add(null);

                List <object> lst4Param = new List <object>();
                lst4Param.Add(null);
                lst4Param.Add(BeginYearToGetData);
                lst4Param.Add(EndYear);
                lst4Param.Add(E_APPROVED);

                var dataAtt_LeaveDay     = GetData <Att_LeaveDay>(lst3Param, ConstantSql.hrm_att_getdata_LeaveDay_Inner, UserLogin, ref status).ToList();
                var dataHre_WorkHistory  = GetData <Hre_WorkHistory>(lst2Param, ConstantSql.hrm_hre_getdata_WorkHistory, UserLogin, ref status).ToList();
                var dataAtt_Roster_Inner = GetData <Att_Roster>(lst4Param, ConstantSql.hrm_att_getdata_Roster_Inner, UserLogin, ref status).ToList();
                #endregion

                if (isFullEmp != null && isFullEmp == true)
                {
                    lstAnnualDetailInDB = repoAtt_AnnualDetail.FindBy(m => m.IsDelete == null && m.ProfileID != null && m.Year == Year).ToList <Att_AnnualDetail>();
                    lstLeaveDaySick     = dataAtt_LeaveDay
                                          .Where(m => m.Status == E_APPROVED && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData && m.Cat_LeaveDayType != null && m.Cat_LeaveDayType.Code == LeavedayTypeCode.SICK.ToString() && lstProfileID.Contains(m.ProfileID)).ToList <Att_LeaveDay>();
                    lstAttGrade       = repoAtt_Grade.FindBy(m => m.IsDelete == null).ToList();
                    lstAnualLeaveCfg  = repoAtt_AnnualLeave.FindBy(m => m.IsDelete == null && m.Year == Year).ToList <Att_AnnualLeave>();
                    lstWorkingHistory = dataHre_WorkHistory.Where(m => m.DateEffective <= EndYear).OrderByDescending(m => m.DateEffective).ToList();
                    lstRoster         = dataAtt_Roster_Inner.Where(m => m.Status == E_APPROVED && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData).ToList <Att_Roster>();
                }
                else
                {
                    lstAnnualDetailInDB = repoAtt_AnnualDetail.FindBy(m => m.IsDelete == null && m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value) && m.Year == Year).ToList <Att_AnnualDetail>();
                    lstLeaveDaySick     = dataAtt_LeaveDay
                                          .Where(m => m.Status == E_APPROVED && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData && m.Cat_LeaveDayType != null && m.Cat_LeaveDayType.Code == LeavedayTypeCode.SICK.ToString() && lstProfileID.Contains(m.ProfileID)).ToList <Att_LeaveDay>();
                    lstAttGrade       = repoAtt_Grade.FindBy(m => m.IsDelete == null && lstProfileID.Contains(m.ProfileID.Value)).ToList <Att_Grade>();
                    lstAnualLeaveCfg  = repoAtt_AnnualLeave.FindBy(m => m.IsDelete == null && m.Year == Year && lstProfileID.Contains(m.ProfileID)).ToList <Att_AnnualLeave>();
                    lstWorkingHistory = dataHre_WorkHistory.Where(m => m.DateEffective <= EndYear && lstProfileID.Contains(m.ProfileID)).OrderByDescending(m => m.DateEffective).ToList <Hre_WorkHistory>();
                    lstRoster         = dataAtt_Roster_Inner.Where(m => m.Status == E_APPROVED && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData && lstProfileID.Contains(m.ProfileID)).ToList <Att_Roster>();
                }

                if (lstLeaveDayApproveIDs != null && lstLeaveDayApproveIDs.Count > 0)
                {
                    lstLeaveDaySick.AddRange(dataAtt_LeaveDay.Where(m => lstLeaveDayApproveIDs.Contains(m.ID)).ToList <Att_LeaveDay>());
                    lstLeaveDaySick = lstLeaveDaySick.Distinct().ToList();
                }
                if (lstLeaveDayRejectIDs != null && lstLeaveDayRejectIDs.Count > 0)
                {
                    lstLeaveDaySick = lstLeaveDaySick.Where(m => !lstLeaveDayRejectIDs.Contains(m.ID)).ToList();
                }
                var lstRosterGroup = repoAtt_RosterGroup.FindBy(m => m.IsDelete == null && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData).ToList <Att_RosterGroup>();
                var lstDayOff      = repoCat_DayOff.FindBy(m => m.IsDelete == null && m.DateOff >= BeginYearToGetData && m.DateOff <= EndYear).ToList <Cat_DayOff>();

                // Phép Năm chốt Từ Ngày 1 -> 31 Hàng Tháng
                bool           IsFrom1To31 = false;
                string         type2       = AppConfig.HRM_ATT_ANNUALLEAVE_ANNUALBEGINMONTHTOENDMONTH.ToString();
                Sys_AllSetting sys_ANNUAL_BEGINMONTHTO_ENDMONTH = repoSys_AllSetting.FindBy(sy => sy.IsDelete == null && sy.Name == type2).FirstOrDefault();
                if (sys_ANNUAL_BEGINMONTHTO_ENDMONTH != null && sys_ANNUAL_BEGINMONTHTO_ENDMONTH.Value1 == bool.TrueString)
                {
                    IsFrom1To31 = true;
                }

                foreach (var profile in lstProfile)
                {
                    var lstGradeByProfile        = lstAttGrade.Where(m => m.ProfileID == profile.ID).OrderByDescending(m => m.MonthStart).ToList();
                    var lstLeaveDaySickByprofile = lstLeaveDaySick.Where(m => m.ProfileID == profile.ID).ToList();
                    var AnualLeaveCfg            = lstAnualLeaveCfg.Where(m => m.ProfileID == profile.ID).FirstOrDefault();
                    var lstRosterByProfile       = lstRoster.Where(m => m.ProfileID == profile.ID).ToList();
                    var lstWorkHistoryByProfile  = lstWorkingHistory.Where(m => m.ProfileID == profile.ID).ToList();

                    List <Att_AnnualDetail> lstAnnualDetailByProfile = AnalyzeAnnualSickPerProfile(profile, lstGradeCgf, lstGradeByProfile,
                                                                                                   BeginYear, EndYear, lstLeaveDaySickByprofile, lstAnnualDetailInDB, AnualLeaveCfg, lstRosterByProfile,
                                                                                                   lstRosterGroup, lstWorkHistoryByProfile, lstDayOff, IsFrom1To31, shifts);

                    //lstResult.AddRange(lstAnnualDetailByProfile);
                    repoAtt_AnnualDetail.Add(lstAnnualDetailByProfile);
                }
                repoAtt_AnnualDetail.SaveChanges();


                //DataErrorCode DataErr = DataErrorCode.Unknown;
                //if (lstAnnualDetail.Count > 0)
                //{
                //    #region lấy dữ liệu dưới DB xóa đi
                //    List<Guid> lstProfileID_InDB = lstAnnualDetail.Where(m => m.ProfileID != null).Select(m => m.ProfileID.Value).ToList();


                //    List<Att_AnnualDetail> lstAnnualLeaveDetail_InDB = repoAtt_AnnualDetail
                //        .FindBy(m => m.IsDelete == null && m.Year == Year && m.Type == E_SICK_LEAVE && m.ProfileID != null && lstProfileID_InDB.Contains(m.ProfileID.Value)).ToList<Att_AnnualDetail>();
                //    foreach (var item in lstAnnualLeaveDetail_InDB)
                //    {
                //        item.IsDelete = true;
                //    }
                //    #endregion

                //    repoAtt_AnnualDetail.Add(lstAnnualDetail);
                //    try
                //    {
                //        repoAtt_AnnualDetail.SaveChanges();
                //    }
                //    catch (Exception)
                //    {
                //        return false;
                //    }
                //}
                result = true;
            }
            return(result);
        }
        /// <summary>
        /// Button Tính Phép Bệnh (Cơ Chế Mới)
        /// Lưu vào Att_AnnualDetail
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="orgStructure"></param>
        /// <param name="LstProfileStatus"></param>
        /// <returns></returns>
        public bool ComputeAnnualSick(int Year, string orgStructure, string LstProfileStatus, bool isFullEmp, string UserLogin)
        {
            var result = false;
            using (var context = new VnrHrmDataContext())
            {
                string status = string.Empty;
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoCat_GradeAttendance = new CustomBaseRepository<Cat_GradeAttendance>(unitOfWork);
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
                var repoCat_Shift = new CustomBaseRepository<Cat_Shift>(unitOfWork);
                var repoAtt_AnnualDetail = new CustomBaseRepository<Att_AnnualDetail>(unitOfWork);
                var repoAtt_RosterGroup = new CustomBaseRepository<Att_RosterGroup>(unitOfWork);
                var repoAtt_AnnualLeave = new CustomBaseRepository<Att_AnnualLeave>(unitOfWork);
                var repoAtt_Grade = new CustomBaseRepository<Att_Grade>(unitOfWork);
                var repoSys_AllSetting = new CustomBaseRepository<Sys_AllSetting>(unitOfWork);

                List<Guid> lstLeaveDayApproveIDs = new List<Guid>();
                List<Guid> lstLeaveDayRejectIDs = new List<Guid>();
                var shifts = repoCat_Shift.FindBy(s => s.IsDelete == null).ToList();

                List<object> lstObj = new List<object>();
                lstObj.Add(orgStructure);
                lstObj.Add(null);
                lstObj.Add(null);
                var lstProfile = GetData<Hre_ProfileEntity>(lstObj, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrg, UserLogin, ref status);

                List<Att_AnnualDetail> lstResult = new List<Att_AnnualDetail>();
                List<Guid> lstProfileID = lstProfile.Select(m => m.ID).ToList();
                int BeginMonth = MonthStartAnl;
                DateTime BeginYear = new DateTime(Year, BeginMonth, 1);
                DateTime EndYear = BeginYear.AddYears(1).AddMinutes(-1);
                DateTime BeginYearToGetData = BeginYear.AddMonths(-1); //trừ một tháng để lấy data (bao những data thuộc những ngày trước tháng dành cho chế độ lương ko phải từ ngày 1)

                var lstGradeCgf = repoCat_GradeAttendance.FindBy(s => s.ID != null).ToList();
                string E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();

                var lstAnnualDetailInDB = new List<Att_AnnualDetail>();
                var lstLeaveDaySick = new List<Att_LeaveDay>();
                var lstAttGrade = new List<Att_Grade>();
                var lstAnualLeaveCfg = new List<Att_AnnualLeave>();
                var lstWorkingHistory = new List<Hre_WorkHistory>();
                var lstRoster = new List<Att_Roster>();

                #region Lấy Dữ Liệu
                List<object> lst2Param = new List<object>();
                lst2Param.Add(null);
                lst2Param.Add(EndYear);

                List<object> lst3Param = new List<object>();
                lst3Param.Add(null);
                lst3Param.Add(null);
                lst3Param.Add(null);

                List<object> lst4Param = new List<object>();
                lst4Param.Add(null);
                lst4Param.Add(BeginYearToGetData);
                lst4Param.Add(EndYear);
                lst4Param.Add(E_APPROVED);

                var dataAtt_LeaveDay = GetData<Att_LeaveDay>(lst3Param, ConstantSql.hrm_att_getdata_LeaveDay_Inner, UserLogin, ref status).ToList();
                var dataHre_WorkHistory = GetData<Hre_WorkHistory>(lst2Param, ConstantSql.hrm_hre_getdata_WorkHistory, UserLogin, ref status).ToList();
                var dataAtt_Roster_Inner = GetData<Att_Roster>(lst4Param, ConstantSql.hrm_att_getdata_Roster_Inner, UserLogin, ref status).ToList();
                #endregion

                if (isFullEmp != null && isFullEmp == true)
                {
                    lstAnnualDetailInDB = repoAtt_AnnualDetail.FindBy(m => m.IsDelete == null && m.ProfileID != null && m.Year == Year).ToList<Att_AnnualDetail>();
                    lstLeaveDaySick = dataAtt_LeaveDay
                                        .Where(m => m.Status == E_APPROVED && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData && m.Cat_LeaveDayType != null && m.Cat_LeaveDayType.Code == LeavedayTypeCode.SICK.ToString() && lstProfileID.Contains(m.ProfileID)).ToList<Att_LeaveDay>();
                    lstAttGrade = repoAtt_Grade.FindBy(m => m.IsDelete == null).ToList();
                    lstAnualLeaveCfg = repoAtt_AnnualLeave.FindBy(m => m.IsDelete == null && m.Year == Year).ToList<Att_AnnualLeave>();
                    lstWorkingHistory = dataHre_WorkHistory.Where(m => m.DateEffective <= EndYear).OrderByDescending(m => m.DateEffective).ToList();
                    lstRoster = dataAtt_Roster_Inner.Where(m => m.Status == E_APPROVED && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData).ToList<Att_Roster>();
                }
                else
                {
                    lstAnnualDetailInDB = repoAtt_AnnualDetail.FindBy(m => m.IsDelete == null && m.ProfileID != null && lstProfileID.Contains(m.ProfileID.Value) && m.Year == Year).ToList<Att_AnnualDetail>();
                    lstLeaveDaySick = dataAtt_LeaveDay
                                        .Where(m => m.Status == E_APPROVED && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData && m.Cat_LeaveDayType != null && m.Cat_LeaveDayType.Code == LeavedayTypeCode.SICK.ToString() && lstProfileID.Contains(m.ProfileID)).ToList<Att_LeaveDay>();
                    lstAttGrade = repoAtt_Grade.FindBy(m => m.IsDelete == null && lstProfileID.Contains(m.ProfileID.Value)).ToList<Att_Grade>();
                    lstAnualLeaveCfg = repoAtt_AnnualLeave.FindBy(m => m.IsDelete == null && m.Year == Year && lstProfileID.Contains(m.ProfileID)).ToList<Att_AnnualLeave>();
                    lstWorkingHistory = dataHre_WorkHistory.Where(m => m.DateEffective <= EndYear && lstProfileID.Contains(m.ProfileID)).OrderByDescending(m => m.DateEffective).ToList<Hre_WorkHistory>();
                    lstRoster = dataAtt_Roster_Inner.Where(m => m.Status == E_APPROVED && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData && lstProfileID.Contains(m.ProfileID)).ToList<Att_Roster>();
                }

                if (lstLeaveDayApproveIDs != null && lstLeaveDayApproveIDs.Count > 0)
                {
                    lstLeaveDaySick.AddRange(dataAtt_LeaveDay.Where(m => lstLeaveDayApproveIDs.Contains(m.ID)).ToList<Att_LeaveDay>());
                    lstLeaveDaySick = lstLeaveDaySick.Distinct().ToList();
                }
                if (lstLeaveDayRejectIDs != null && lstLeaveDayRejectIDs.Count > 0)
                {
                    lstLeaveDaySick = lstLeaveDaySick.Where(m => !lstLeaveDayRejectIDs.Contains(m.ID)).ToList();
                }
                var lstRosterGroup = repoAtt_RosterGroup.FindBy(m => m.IsDelete == null && m.DateStart <= EndYear && m.DateEnd >= BeginYearToGetData).ToList<Att_RosterGroup>();
                var lstDayOff = repoCat_DayOff.FindBy(m => m.IsDelete == null && m.DateOff >= BeginYearToGetData && m.DateOff <= EndYear).ToList<Cat_DayOff>();

                // Phép Năm chốt Từ Ngày 1 -> 31 Hàng Tháng 
                bool IsFrom1To31 = false;
                string type2 = AppConfig.HRM_ATT_ANNUALLEAVE_ANNUALBEGINMONTHTOENDMONTH.ToString();
                Sys_AllSetting sys_ANNUAL_BEGINMONTHTO_ENDMONTH = repoSys_AllSetting.FindBy(sy => sy.IsDelete == null && sy.Name == type2).FirstOrDefault();
                if (sys_ANNUAL_BEGINMONTHTO_ENDMONTH != null && sys_ANNUAL_BEGINMONTHTO_ENDMONTH.Value1 == bool.TrueString)
                {
                    IsFrom1To31 = true;
                }

                foreach (var profile in lstProfile)
                {
                    var lstGradeByProfile = lstAttGrade.Where(m => m.ProfileID == profile.ID).OrderByDescending(m => m.MonthStart).ToList();
                    var lstLeaveDaySickByprofile = lstLeaveDaySick.Where(m => m.ProfileID == profile.ID).ToList();
                    var AnualLeaveCfg = lstAnualLeaveCfg.Where(m => m.ProfileID == profile.ID).FirstOrDefault();
                    var lstRosterByProfile = lstRoster.Where(m => m.ProfileID == profile.ID).ToList();
                    var lstWorkHistoryByProfile = lstWorkingHistory.Where(m => m.ProfileID == profile.ID).ToList();

                    List<Att_AnnualDetail> lstAnnualDetailByProfile = AnalyzeAnnualSickPerProfile(profile, lstGradeCgf, lstGradeByProfile,
                        BeginYear, EndYear, lstLeaveDaySickByprofile, lstAnnualDetailInDB, AnualLeaveCfg, lstRosterByProfile,
                        lstRosterGroup, lstWorkHistoryByProfile, lstDayOff, IsFrom1To31, shifts);

                    //lstResult.AddRange(lstAnnualDetailByProfile);
                    repoAtt_AnnualDetail.Add(lstAnnualDetailByProfile);
                }
                repoAtt_AnnualDetail.SaveChanges();


                //DataErrorCode DataErr = DataErrorCode.Unknown;
                //if (lstAnnualDetail.Count > 0)
                //{
                //    #region lấy dữ liệu dưới DB xóa đi
                //    List<Guid> lstProfileID_InDB = lstAnnualDetail.Where(m => m.ProfileID != null).Select(m => m.ProfileID.Value).ToList();


                //    List<Att_AnnualDetail> lstAnnualLeaveDetail_InDB = repoAtt_AnnualDetail
                //        .FindBy(m => m.IsDelete == null && m.Year == Year && m.Type == E_SICK_LEAVE && m.ProfileID != null && lstProfileID_InDB.Contains(m.ProfileID.Value)).ToList<Att_AnnualDetail>();
                //    foreach (var item in lstAnnualLeaveDetail_InDB)
                //    {
                //        item.IsDelete = true;
                //    }
                //    #endregion

                //    repoAtt_AnnualDetail.Add(lstAnnualDetail);
                //    try
                //    {
                //        repoAtt_AnnualDetail.SaveChanges();
                //    }
                //    catch (Exception)
                //    {
                //        return false;
                //    }
                //}
                result = true;
            }
            return result;
        }
Esempio n. 48
0
        /// <summary>
        /// Lấy tất cả các bản ghi
        /// Get by key
        /// </summary>
        /// <returns></returns>
        public void SaveConfig(List <Dictionary <string, string> > lstModel)
        {
            using (var context = new VnrHrmDataContext())
            {
                IUnitOfWork unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var         repo       = new CustomBaseRepository <Sys_AllSetting>(unitOfWork);


                string status = string.Empty;
                List <Dictionary <Guid, string> > lstUpdate = new List <Dictionary <Guid, string> >();
                var                   valueTemp             = new Sys_AllSetting();
                var                   modelTemp             = new Sys_AllSetting();
                List <Guid>           lstConfigIds          = new List <Guid>();
                List <Sys_AllSetting> lstAdd  = new List <Sys_AllSetting>();
                List <Sys_AllSetting> lstEdit = new List <Sys_AllSetting>();
                List <Sys_AllSetting> lstDel  = new List <Sys_AllSetting>();

                var getdata = repo.FindBy(s => s.IsDelete == null).ToList();

                if (lstModel[0].FirstOrDefault().Value.Length > 0)
                {
                    var lstStr = lstModel.FirstOrDefault()["lstConfigIds"].Split(',');
                    lstConfigIds = lstStr.Select(Guid.Parse).ToList();
                }

                foreach (var item in lstConfigIds)
                {
                    modelTemp = GetById <Sys_AllSetting>(item, ref status);
                    lstUpdate.Add(new Dictionary <Guid, string>()
                    {
                        { modelTemp.ID, modelTemp.Name }
                    });
                }
                for (int i = 1; i < lstModel.Count; i++)
                {
                    var lstEntity = getdata.Where(s => s.Name == lstModel[i].FirstOrDefault().Key).ToList();

                    if (lstEntity.Count == 0)
                    {
                        valueTemp        = new Sys_AllSetting();
                        valueTemp.ID     = Guid.NewGuid();
                        valueTemp.Name   = lstModel[i].FirstOrDefault().Key;
                        valueTemp.Value1 = lstModel[i].FirstOrDefault().Value;
                        lstAdd.Add(valueTemp);
                        continue;
                    }
                    if (lstEntity.Count > 0)
                    {
                        valueTemp = new Sys_AllSetting();
                        foreach (var item in lstEntity)
                        {
                            item.IsDelete = true;
                            lstDel.Add(item);
                            //repo.Edit(item);
                        }
                        var isUpdate = lstUpdate.Where(s => s.FirstOrDefault().Value == lstModel[i].FirstOrDefault().Key).FirstOrDefault();
                        if (isUpdate != null)
                        {
                            valueTemp.ID       = lstEntity.FirstOrDefault().ID;
                            valueTemp.Name     = lstModel[i].FirstOrDefault().Key;
                            valueTemp.Value1   = lstModel[i].FirstOrDefault().Value;
                            valueTemp.IsDelete = null;
                            lstEdit.Add(valueTemp);
                        }
                        else
                        {
                            valueTemp.ID     = Guid.NewGuid();
                            valueTemp.Name   = lstModel[i].FirstOrDefault().Key;
                            valueTemp.Value1 = lstModel[i].FirstOrDefault().Value;
                            lstAdd.Add(valueTemp);
                        }
                    }
                }
                repo.Edit(lstDel);
                repo.Add(lstAdd);
                repo.Edit(lstEdit);
                repo.SaveChanges();
            }
        }