Ejemplo n.º 1
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";
         }
     }
 }
Ejemplo n.º 2
0
        public Guid ComputeBonusUnusualAllowance(Sal_UnusualAllowanceEntity model)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoSys_AsynTask = new CustomBaseRepository<Sys_AsynTask>(unitOfWork);
                var repoCat_Element = new CustomBaseRepository<Cat_Element>(unitOfWork);


                //tạo asynTask
                Sys_AsynTask asynTask = new Sys_AsynTask()
                {
                    ID = Guid.NewGuid(),
                    Summary = "Tính thưởng : " + model.MonthStart.Value.ToString("dd/MM/yyyy"),
                    Type = AsynTask.Payroll_Compute_BonusUnusualAllowance.ToString(),
                    Status = AsynTaskStatus.Doing.ToString(),
                    TimeStart = DateTime.Now,
                    PercentComplete = 0.01,
                };
                repoSys_AsynTask.Add(asynTask);
                unitOfWork.SaveChanges();

                Thread threadCompute = new Thread(() => ComputeBonusUnusualAllowance_Progress(asynTask.ID, model));
                threadCompute.Start();

                return asynTask.ID;
            }

        }
Ejemplo n.º 3
0
 public string SaveEvalutionData(int year, Guid?TimesGetDataID, string orgStructureID, DateTime?_dateStart, DateTime?_dateEnd, string userLogin)
 {
     using (var context = new VnrHrmDataContext())
     {
         var evaServices = new Eva_ReportServices();
         List <Eva_EvalutionDataEntity> lstEvalutionDataEntity = new List <Eva_EvalutionDataEntity>();
         lstEvalutionDataEntity = evaServices.SummaryEvalutionData(year, TimesGetDataID, orgStructureID, _dateStart, _dateEnd, userLogin);
         var unitOfWork            = (IUnitOfWork) new UnitOfWork(context);
         var repoEva_EvalutionData = new CustomBaseRepository <Eva_EvalutionData>(unitOfWork);
         List <Eva_EvalutionData> lstEvalutionData = new List <Eva_EvalutionData>();
         lstEvalutionData = lstEvalutionDataEntity.Translate <Eva_EvalutionData>();
         if (lstEvalutionData != null)
         {
             int _total     = lstEvalutionData.Count;
             int _totalPage = _total / 200 + 1;
             int _pageSize  = 200;
             for (int _page = 1; _page <= _totalPage; _page++)
             {
                 int _skip           = _pageSize * (_page - 1);
                 var _listCurrenPage = lstEvalutionData.Skip(_skip).Take(_pageSize).ToList();
                 foreach (var item in _listCurrenPage)
                 {
                     repoEva_EvalutionData.Add(item);
                 }
                 unitOfWork.SaveChanges();
             }
         }
         return("SaveSuccess");
         //    #endregion
     }
 }
Ejemplo n.º 4
0
 public string SaveEvalutionData(int year, Guid? TimesGetDataID, string orgStructureID, DateTime? _dateStart, DateTime? _dateEnd,string userLogin)
 {
     using (var context = new VnrHrmDataContext())
     {
         var evaServices = new Eva_ReportServices();
         List<Eva_EvalutionDataEntity> lstEvalutionDataEntity = new List<Eva_EvalutionDataEntity>();
         lstEvalutionDataEntity = evaServices.SummaryEvalutionData(year, TimesGetDataID, orgStructureID, _dateStart, _dateEnd,userLogin);
         var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
         var repoEva_EvalutionData = new CustomBaseRepository<Eva_EvalutionData>(unitOfWork);
         List<Eva_EvalutionData> lstEvalutionData = new List<Eva_EvalutionData>();
         lstEvalutionData = lstEvalutionDataEntity.Translate<Eva_EvalutionData>();
         if (lstEvalutionData != null)
         {
             int _total = lstEvalutionData.Count;
             int _totalPage = _total / 200 + 1;
             int _pageSize = 200;
             for (int _page = 1; _page <= _totalPage; _page++)
             {
                 int _skip = _pageSize * (_page - 1);
                 var _listCurrenPage = lstEvalutionData.Skip(_skip).Take(_pageSize).ToList();
                 foreach (var item in _listCurrenPage)
                 {
                     repoEva_EvalutionData.Add(item);
                 }
                 unitOfWork.SaveChanges();
             }
         }
         return "SaveSuccess";
         //    #endregion
     }
 }  
Ejemplo n.º 5
0
        public Guid ComputeAnnualLeaveAllowance(Sal_UnusualAllowanceEntity model)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork       = (IUnitOfWork) new UnitOfWork(context);
                var repoSys_AsynTask = new CustomBaseRepository <Sys_AsynTask>(unitOfWork);
                var repoCat_Element  = new CustomBaseRepository <Cat_Element>(unitOfWork);


                //tạo asynTask
                Sys_AsynTask asynTask = new Sys_AsynTask()
                {
                    ID              = Guid.NewGuid(),
                    Summary         = "Tính phép năm : " + model.MonthStart.Value.ToString("dd/MM/yyyy"),
                    Type            = AsynTask.Payroll_Compute_AnnualLeaveAllowance.ToString(),
                    Status          = AsynTaskStatus.Doing.ToString(),
                    TimeStart       = DateTime.Now,
                    PercentComplete = 0.01,
                };
                repoSys_AsynTask.Add(asynTask);
                unitOfWork.SaveChanges();

                Thread threadCompute = new Thread(() => ComputeBonusUnusualAllowance_Progress(asynTask.ID, model, true));
                threadCompute.Start();

                return(asynTask.ID);
            }
        }
Ejemplo n.º 6
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);
                }
            }
        }
Ejemplo n.º 7
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);
                }
            }
        }
Ejemplo n.º 8
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;
                }

            }
        }
Ejemplo n.º 9
0
        public void SaveUnusualAllowance(List <Sal_UnusualAllowanceEntity> model)
        {
            using (var context = new VnrHrmDataContext())
            {
                string status               = string.Empty;
                var    unitOfWork           = (IUnitOfWork) new UnitOfWork(context);
                var    repoUnusualAllowance = new CustomBaseRepository <Sal_UnusualAllowance>(unitOfWork);

                repoUnusualAllowance.Add(model.Translate <Sal_UnusualAllowance>());
                unitOfWork.SaveChanges();
            }
        }
Ejemplo n.º 10
0
        public void CreateFormulaTemplate(List<Cat_FormulaTemplateEntity> listFormulaTemplate,Guid GradeID)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoCat_FormulaTemplate = new CustomBaseRepository<Cat_FormulaTemplate>(unitOfWork);
                var repoCat_Element = new CustomBaseRepository<Cat_Element>(unitOfWork);

                #region Xử lý bảng template
                //lấy các phần tử template trong grade
                List<Cat_FormulaTemplate> listFormulaTemplateByGrade = repoCat_FormulaTemplate.FindBy(m => m.IsDelete != true && m.GradeID != null && m.GradeID == GradeID).ToList();
                //xóa các phần tử đó
                repoCat_FormulaTemplate.Delete(listFormulaTemplateByGrade);

                //insert lại các phần tử mới
                List<Cat_FormulaTemplate> listFormulaTemplateModel = listFormulaTemplate.Translate<Cat_FormulaTemplate>();
                listFormulaTemplateModel.ForEach(m => m.GradeID = GradeID);
                repoCat_FormulaTemplate.Add(listFormulaTemplateModel); 
                #endregion

                #region Xử lý bảng cat_element
                //lấy các phần tử có cùng mã code với template
                List<Cat_Element> listElement = repoCat_Element.FindBy(m => m.IsDelete != true && m.GradePayrollID == GradeID).ToList();
                listElement = listElement.Where(m => listFormulaTemplate.Any(t => t.ElementCode.ReplaceSpace() == m.ElementCode.ReplaceSpace())).ToList();
                //xóa các phần tử đó đi
                repoCat_Element.Delete(listElement);

                //tạo ra các element
                List<Cat_Element> listElementModel = new List<Cat_Element>();
                Cat_Element item = new Cat_Element();
                foreach (var template in listFormulaTemplate)
                {
                    item = new Cat_Element();
                    item.GradePayrollID = GradeID;
                    item.ElementCode = template.ElementCode.ReplaceSpace();
                    item.ElementName = template.ElementName;
                    item.Formula = template.Formula;
                    item.IsBold = template.IsBold;
                    item.Invisible = template.Invisible;
                    item.Description = template.Description;
                    item.TabType = CatElementType.Payroll.ToString();
                    item.MethodPayroll = MethodPayroll.E_NORMAL.ToString();
                    item.ElementType = CatElementType.Payroll.ToString();    
                    item.Type = EnumDropDown.ElementDataType.Double.ToString();
                    listElementModel.Add(item);
                }
                repoCat_Element.Add(listElementModel);

                unitOfWork.SaveChanges();
                #endregion

            }
        }
Ejemplo n.º 11
0
        public void SaveUnusualAllowance(List<Sal_UnusualAllowanceEntity> model)
        {
            using (var context = new VnrHrmDataContext())
            {
                string status = string.Empty;
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoUnusualAllowance = new CustomBaseRepository<Sal_UnusualAllowance>(unitOfWork);

                repoUnusualAllowance.Add(model.Translate<Sal_UnusualAllowance>());
                unitOfWork.SaveChanges();
            }
        }
Ejemplo n.º 12
0
        public void SetCompensationLeaveBeginYear(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_CompensationConfig = new CustomBaseRepository<Att_CompensationConfig>(unitOfWork);
                DateTime EndLastYear = new DateTime(Year - 1, 12, 1);

                List<Att_CompensationDetail> lstCompensationDetail = unitOfWork.CreateQueryable<Att_CompensationDetail>(m => m.MonthYear == EndLastYear
                                                                        && m.ProfileID != null
                                                                        && lstProfileIDs.Contains(m.ProfileID.Value)).ToList();
                var lstCompensationLeaveInDB = unitOfWork.CreateQueryable<Att_CompensationConfig>(m => m.Year == Year && m.ProfileID != null && lstProfileIDs.Contains(m.ProfileID.Value)).ToList();

                List<Att_CompensationConfig> lstNewData = new List<Att_CompensationConfig>();
                List<Att_CompensationConfig> lstEditData = new List<Att_CompensationConfig>();
                foreach (var ProfileID in lstProfileIDs)
                {
                    Att_CompensationConfig CompensationLeaveConfigByProfile = lstCompensationLeaveInDB.Where(m => m.ProfileID == ProfileID).FirstOrDefault();
                    bool IsNew = false;
                    if (CompensationLeaveConfigByProfile == null)
                    {
                        IsNew = true;
                        CompensationLeaveConfigByProfile = new Att_CompensationConfig();
                        CompensationLeaveConfigByProfile.ID = Guid.NewGuid();
                        CompensationLeaveConfigByProfile.ProfileID = ProfileID;
                        CompensationLeaveConfigByProfile.Year = Year;
                    }
                    CompensationLeaveConfigByProfile.MonthResetInitAvailable = MonthResetANL;
                    double RemainLastYear = lstCompensationDetail.Where(m => m.ProfileID == ProfileID).Select(m => m.Remain ?? 0).FirstOrDefault();
                    if (limitMaximum != null)
                    {
                        CompensationLeaveConfigByProfile.InitAvailable = RemainLastYear > limitMaximum.Value ? limitMaximum.Value : RemainLastYear;
                    }
                    else
                    {
                        CompensationLeaveConfigByProfile.InitAvailable = RemainLastYear;
                    }
                    if (IsNew)
                    {
                        lstNewData.Add(CompensationLeaveConfigByProfile);
                    }
                    else
                    {
                        lstEditData.Add(CompensationLeaveConfigByProfile);
                    }
                    //Sửa lại theo phần tử mới mà Sơn build
                }
                repoAtt_CompensationConfig.Add(lstNewData);
                repoAtt_CompensationConfig.Edit(lstEditData);
                unitOfWork.SaveChanges();
            }
        }
Ejemplo n.º 13
0
        public void CreateFormulaTemplate(List <Cat_FormulaTemplateEntity> listFormulaTemplate, Guid GradeID)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork) new UnitOfWork(context);
                var repoCat_FormulaTemplate = new CustomBaseRepository <Cat_FormulaTemplate>(unitOfWork);
                var repoCat_Element         = new CustomBaseRepository <Cat_Element>(unitOfWork);

                #region Xử lý bảng template
                //lấy các phần tử template trong grade
                List <Cat_FormulaTemplate> listFormulaTemplateByGrade = repoCat_FormulaTemplate.FindBy(m => m.IsDelete != true && m.GradeID != null && m.GradeID == GradeID).ToList();
                //xóa các phần tử đó
                repoCat_FormulaTemplate.Delete(listFormulaTemplateByGrade);

                //insert lại các phần tử mới
                List <Cat_FormulaTemplate> listFormulaTemplateModel = listFormulaTemplate.Translate <Cat_FormulaTemplate>();
                listFormulaTemplateModel.ForEach(m => m.GradeID = GradeID);
                repoCat_FormulaTemplate.Add(listFormulaTemplateModel);
                #endregion

                #region Xử lý bảng cat_element
                //lấy các phần tử có cùng mã code với template
                List <Cat_Element> listElement = repoCat_Element.FindBy(m => m.IsDelete != true && m.GradePayrollID == GradeID).ToList();
                listElement = listElement.Where(m => listFormulaTemplate.Any(t => t.ElementCode.ReplaceSpace() == m.ElementCode.ReplaceSpace())).ToList();
                //xóa các phần tử đó đi
                repoCat_Element.Delete(listElement);

                //tạo ra các element
                List <Cat_Element> listElementModel = new List <Cat_Element>();
                Cat_Element        item             = new Cat_Element();
                foreach (var template in listFormulaTemplate)
                {
                    item = new Cat_Element();
                    item.GradePayrollID = GradeID;
                    item.ElementCode    = template.ElementCode.ReplaceSpace();
                    item.ElementName    = template.ElementName;
                    item.Formula        = template.Formula;
                    item.IsBold         = template.IsBold;
                    item.Invisible      = template.Invisible;
                    item.Description    = template.Description;
                    item.TabType        = CatElementType.Payroll.ToString();
                    item.MethodPayroll  = MethodPayroll.E_NORMAL.ToString();
                    item.ElementType    = CatElementType.Payroll.ToString();
                    item.Type           = EnumDropDown.ElementDataType.Double.ToString();
                    listElementModel.Add(item);
                }
                repoCat_Element.Add(listElementModel);

                unitOfWork.SaveChanges();
                #endregion
            }
        }
Ejemplo n.º 14
0
        public void SetCompensationLeaveBeginYear(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_CompensationConfig = new CustomBaseRepository <Att_CompensationConfig>(unitOfWork);
                DateTime EndLastYear = new DateTime(Year - 1, 12, 1);

                List <Att_CompensationDetail> lstCompensationDetail = unitOfWork.CreateQueryable <Att_CompensationDetail>(m => m.MonthYear == EndLastYear &&
                                                                                                                          m.ProfileID != null &&
                                                                                                                          lstProfileIDs.Contains(m.ProfileID.Value)).ToList();
                var lstCompensationLeaveInDB = unitOfWork.CreateQueryable <Att_CompensationConfig>(m => m.Year == Year && m.ProfileID != null && lstProfileIDs.Contains(m.ProfileID.Value)).ToList();

                List <Att_CompensationConfig> lstNewData  = new List <Att_CompensationConfig>();
                List <Att_CompensationConfig> lstEditData = new List <Att_CompensationConfig>();
                foreach (var ProfileID in lstProfileIDs)
                {
                    Att_CompensationConfig CompensationLeaveConfigByProfile = lstCompensationLeaveInDB.Where(m => m.ProfileID == ProfileID).FirstOrDefault();
                    bool IsNew = false;
                    if (CompensationLeaveConfigByProfile == null)
                    {
                        IsNew = true;
                        CompensationLeaveConfigByProfile           = new Att_CompensationConfig();
                        CompensationLeaveConfigByProfile.ID        = Guid.NewGuid();
                        CompensationLeaveConfigByProfile.ProfileID = ProfileID;
                        CompensationLeaveConfigByProfile.Year      = Year;
                    }
                    CompensationLeaveConfigByProfile.MonthResetInitAvailable = MonthResetANL;
                    double RemainLastYear = lstCompensationDetail.Where(m => m.ProfileID == ProfileID).Select(m => m.Remain ?? 0).FirstOrDefault();
                    if (limitMaximum != null)
                    {
                        CompensationLeaveConfigByProfile.InitAvailable = RemainLastYear > limitMaximum.Value ? limitMaximum.Value : RemainLastYear;
                    }
                    else
                    {
                        CompensationLeaveConfigByProfile.InitAvailable = RemainLastYear;
                    }
                    if (IsNew)
                    {
                        lstNewData.Add(CompensationLeaveConfigByProfile);
                    }
                    else
                    {
                        lstEditData.Add(CompensationLeaveConfigByProfile);
                    }
                    //Sửa lại theo phần tử mới mà Sơn build
                }
                repoAtt_CompensationConfig.Add(lstNewData);
                repoAtt_CompensationConfig.Edit(lstEditData);
                unitOfWork.SaveChanges();
            }
        }
Ejemplo n.º 15
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();
            }
        }
Ejemplo n.º 16
0
        public ResultsObject SaveChangeHoldSalary(List <Sal_HoldSalaryEntity> ListEntity)
        {
            try
            {
                using (var context = new VnrHrmDataContext())
                {
                    var unitOfWork         = (IUnitOfWork) new UnitOfWork(context);
                    var repoSal_HoldSalary = new CustomBaseRepository <Sal_HoldSalary>(unitOfWork);
                    List <Sal_HoldSalary> TotalHoldSalary = repoSal_HoldSalary.FindBy(m => m.IsDelete != true).ToList();

                    foreach (var i in ListEntity)
                    {
                        #region Kiểm tra nhân viên đã có dữ liệu giữ lương hay chưa

                        Sal_HoldSalary HoldSalaryByProfile = TotalHoldSalary.FirstOrDefault(m => m.ProfileID == i.ProfileID && m.MonthSalary != null && m.MonthSalary.Value.Day == i.MonthSalary.Value.Day && m.TimeAnalyzeID != null && m.TimeAnalyzeID == i.TimeAnalyzeID);
                        if (HoldSalaryByProfile != null)
                        {
                            if (HoldSalaryByProfile.Status == EnumDropDown.HoldSalaryStatus.E_APPROVED.ToString())
                            {
                                continue;
                            }
                            else
                            {
                                HoldSalaryByProfile.AmountSalary      = i.AmountSalary;
                                HoldSalaryByProfile.IsLeaveContinuous = i.IsLeaveContinuous;
                                HoldSalaryByProfile.IsLeaveM          = i.IsLeaveM;
                                HoldSalaryByProfile.Terminate         = i.Terminate;
                                HoldSalaryByProfile.TimeAnalyzeID     = i.TimeAnalyzeID;
                            }
                        }
                        else
                        {
                            Sal_HoldSalary HoldSalary = i.Copy <Sal_HoldSalary>();
                            repoSal_HoldSalary.Add(HoldSalary);
                        }
                        #endregion
                    }
                    unitOfWork.SaveChanges();
                    return(new ResultsObject());
                }
            }
            catch (Exception ex)
            {
                return(new ResultsObject()
                {
                    Success = false, Messenger = ex.Message
                });
            }
        }
Ejemplo n.º 17
0
        public int[] ApprevedKaiZenData(List <Guid> selectedIds, DateTime MonthYear, Guid UnusualEDTypeID, Guid Currency)
        {
            using (var context = new VnrHrmDataContext())
            {
                string status                   = string.Empty;
                var    unitOfWork               = (IUnitOfWork) new UnitOfWork(context);
                var    repoKai_KaizenData       = new CustomBaseRepository <Kai_KaizenData>(unitOfWork);
                var    repoSal_UnusualAllowance = new CustomBaseRepository <Sal_UnusualAllowance>(unitOfWork);
                List <Sal_UnusualAllowance> listUnusualAllowance = new List <Sal_UnusualAllowance>();

                //lọc ra các kaizen được chọn
                List <Kai_KaizenData> listKaiZendata = repoKai_KaizenData.FindBy(m => m.IsDelete != true).ToList();
                listKaiZendata = listKaiZendata.Where(m => m.Status == EnumDropDown.Kai_KaizenDataStatus.E_APPROVED.ToString() && selectedIds.Any(t => t == m.ID)).ToList();

                int Pass = 0;
                int Fail = 0;

                Sal_UnusualAllowance item = new Sal_UnusualAllowance();
                foreach (var KaiZenItem in listKaiZendata)
                {
                    if (KaiZenItem.DateTransferPayment == null && (KaiZenItem.IsPaymentOut == null || KaiZenItem.IsPaymentOut == false))
                    {
                        item                 = new Sal_UnusualAllowance();
                        item.ProfileID       = KaiZenItem.ProfileID != null ? (Guid)KaiZenItem.ProfileID : Guid.NewGuid();
                        item.MonthStart      = new DateTime(MonthYear.Year, MonthYear.Month, 1);
                        item.MonthEnd        = new DateTime(MonthYear.Year, MonthYear.Month, 1).AddMonths(1).AddDays(-1);
                        item.Type            = EnumDropDown.EDType.E_EARNING.ToString();
                        item.UnusualEDTypeID = UnusualEDTypeID;
                        item.CurrencyID      = Currency;
                        item.Amount          = KaiZenItem.SumAmount != null ? KaiZenItem.SumAmount : 0;
                        listUnusualAllowance.Add(item);

                        KaiZenItem.DateTransferPayment = MonthYear;
                        Pass++;
                    }
                    else
                    {
                        Fail++;
                    }
                }
                repoSal_UnusualAllowance.Add(listUnusualAllowance);
                unitOfWork.SaveChanges();
                return(new int[] { Pass, Fail });
            }
        }
Ejemplo n.º 18
0
        public bool SaveTemplatePayrollEstimate(List <Sal_PayrollEstimateDetailEntity> listEntity)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork                = (IUnitOfWork) new UnitOfWork(context);
                var repoOrgStructure          = new CustomBaseRepository <Cat_OrgStructure>(unitOfWork);
                var repoPayrollEstimateDetail = new CustomBaseRepository <Sal_PayrollEstimateDetail>(unitOfWork);

                List <Sal_PayrollEstimateDetail> ListPayrollEstimateDetail = new List <Sal_PayrollEstimateDetail>();
                ListPayrollEstimateDetail = repoPayrollEstimateDetail.FindBy(m => m.IsDelete != true && m.PayrollEstimateID == null).ToList();

                foreach (var i in listEntity)
                {
                    var _tmp = ListPayrollEstimateDetail.FirstOrDefault(m => m.OrgStructureID == i.OrgStructureID);
                    if (_tmp != null)
                    {
                        _tmp.LeaveUnpaid          = i.LeaveUnpaid;
                        _tmp.OvertimeHoliday      = i.OvertimeHoliday;
                        _tmp.OvertimeNightHoliday = i.OvertimeNightHoliday;
                        _tmp.OvertimeNightNormal  = i.OvertimeNightNormal;
                        _tmp.OvertimeNightWeekend = i.OvertimeNightWeekend;
                        _tmp.OvertimeNormal       = i.OvertimeNormal;
                        _tmp.OvertimeWeekend      = i.OvertimeWeekend;
                    }
                    else
                    {
                        Sal_PayrollEstimateDetail item = new Sal_PayrollEstimateDetail();
                        item.ID                   = Guid.NewGuid();
                        item.OrgStructureID       = i.OrgStructureID;
                        item.LeaveUnpaid          = i.LeaveUnpaid;
                        item.OvertimeHoliday      = i.OvertimeHoliday;
                        item.OvertimeNightHoliday = i.OvertimeNightHoliday;
                        item.OvertimeNightNormal  = i.OvertimeNightNormal;
                        item.OvertimeNightWeekend = i.OvertimeNightWeekend;
                        item.OvertimeNormal       = i.OvertimeNormal;
                        item.OvertimeWeekend      = i.OvertimeWeekend;
                        repoPayrollEstimateDetail.Add(item);
                    }
                }
                unitOfWork.SaveChanges();
                return(true);
            }
        }
Ejemplo n.º 19
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();
     }
 }
Ejemplo n.º 20
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();
     }
 }
Ejemplo n.º 21
0
        public Guid ComputeCommission(List <Hre_ProfileEntity> listProfile, Att_CutOffDurationEntity CutOffDuration, string HeaderTemplateLog, string methodPayroll, Guid CutOffDuration2ID, string UserLogin)
        {
            Sys_AsynTask asynTask = new Sys_AsynTask()
            {
                ID              = Guid.NewGuid(),
                Summary         = "Tính Hoa Hồng Cho Tháng " + CutOffDuration.CutOffDurationName,
                Type            = AsynTask.Payroll_Computing.ToString(),
                Status          = AsynTaskStatus.Doing.ToString(),
                TimeStart       = DateTime.Now,
                PercentComplete = 0.01,
            };

            Task.Run(() =>
            {
                using (var context = new VnrHrmDataContext())
                {
                    var unitOfWork       = (IUnitOfWork) new UnitOfWork(context);
                    var repoSys_AsynTask = new CustomBaseRepository <Sys_AsynTask>(unitOfWork);

                    if (listProfile.Count == 0)
                    {
                        asynTask.TimeEnd         = DateTime.Now;
                        asynTask.Description     = "Không tồn tại nhân viên nào !";
                        asynTask.PercentComplete = 1D;
                    }

                    repoSys_AsynTask.Add(asynTask);
                    unitOfWork.SaveChanges();
                }

                if (listProfile.Count > 0)
                {
                    ComputeCommission(listProfile, CutOffDuration,
                                      asynTask.ID, HeaderTemplateLog, methodPayroll, CutOffDuration2ID, UserLogin);
                }
            });

            return(asynTask.ID);
        }
Ejemplo n.º 22
0
        /// <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);
        }
Ejemplo n.º 23
0
        public bool ComputePayrollEstimate(List <Sal_PayrollEstimateDetailEntity> listPayrollEstimateDetail, Sal_PayrollEstimateEntity model, string userLogin)
        {
            try
            {
                using (var context = new VnrHrmDataContext())
                {
                    var unitOfWork                = (IUnitOfWork) new UnitOfWork(context);
                    var repoCutOffDuration        = new CustomBaseRepository <Att_CutOffDuration>(unitOfWork);
                    var repoPayrollEstimateDetail = new CustomBaseRepository <Sal_PayrollEstimateDetail>(unitOfWork);
                    var repoPayrollEstimate       = new CustomBaseRepository <Sal_PayrollEstimate>(unitOfWork);

                    List <Att_CutOffDuration> listCutoffDuration = repoCutOffDuration.FindBy(m => m.IsDelete != true && m.MonthYear <= model.MonthEnd && m.MonthYear >= model.MonthStart).ToList();

                    #region Delete Sal_PayrollEstimate và Sal_PayrollEstimateDetail

                    List <Sal_PayrollEstimateDetail> ListPayrollEstimateDetailDelete = new List <Sal_PayrollEstimateDetail>();
                    List <Sal_PayrollEstimate>       ListPayrollEstimateDelete       = new List <Sal_PayrollEstimate>();

                    ListPayrollEstimateDelete = repoPayrollEstimate.FindBy(m => m.IsDelete != true && m.OrgStructureID == model.OrgStructureID).ToList();
                    ListPayrollEstimateDelete = ListPayrollEstimateDelete.Where(m => listCutoffDuration.Any(t => t.ID == m.CutOffDurationID)).ToList();

                    ListPayrollEstimateDetailDelete = repoPayrollEstimateDetail.FindBy(m => m.IsDelete != true).ToList();
                    ListPayrollEstimateDetailDelete = ListPayrollEstimateDetailDelete.Where(m => ListPayrollEstimateDelete.Any(t => t.ID == m.PayrollEstimateID)).ToList();

                    ListPayrollEstimateDelete.ForEach(m => m.IsDelete       = true);
                    ListPayrollEstimateDetailDelete.ForEach(m => m.IsDelete = true);

                    unitOfWork.SaveChanges();
                    #endregion

                    //Giờ công chuẩn lấy trong web config
                    double TotalAmount = 0;

                    //lay du lieu  cau hinh
                    string status = string.Empty;
                    Sys_AllSettingServices sysServices = new Sys_AllSettingServices();
                    var    AllSetting   = sysServices.GetData <Sys_AllSettingEntity>("HRM_SAL_PAYROLL_ESTIMATE_SALRYAVERAGE", ConstantSql.hrm_sys_sp_get_AllSettingByKey, userLogin, ref status).FirstOrDefault();
                    double StandardHour = 200;
                    Double.TryParse(AllSetting != null ? AllSetting.Value2 : "a", out StandardHour);

                    foreach (var CutOff in listCutoffDuration)
                    {
                        //reset tổng tiền master
                        TotalAmount = 0;
                        //tạo dữ liệu master
                        Sal_PayrollEstimate Master = new Sal_PayrollEstimate();
                        Master.ID               = Guid.NewGuid();
                        Master.OrgStructureID   = model.OrgStructureID;
                        Master.CutOffDurationID = CutOff.ID;
                        Master.PayrollGroupID   = model.PayrollGroupID;
                        Master.RateAdjust       = model.RateAdjust;
                        Master.OrgStructureType = model.OrgStructureType;
                        Master.BonusBudget      = model.BonusBudget;
                        Master.StatusEmp        = model.StatusEmp;

                        foreach (var i in listPayrollEstimateDetail)
                        {
                            #region Check null value
                            i.SalaryAverage = i.SalaryAverage != null ? (double)i.SalaryAverage : 0;
                            i.QuantityEmp   = i.QuantityEmp != null ? (double)i.QuantityEmp : 0;
                            i.LeaveUnpaid   = i.LeaveUnpaid != null ? (double)i.LeaveUnpaid : 0;

                            i.OvertimeNormal       = i.OvertimeNormal != null ? (double)i.OvertimeNormal : 0;
                            i.OvertimeNightNormal  = i.OvertimeNightNormal != null ? (double)i.OvertimeNightNormal : 0;
                            i.OvertimeWeekend      = i.OvertimeWeekend != null ? (double)i.OvertimeWeekend : 0;
                            i.OvertimeNightWeekend = i.OvertimeNightWeekend != null ? (double)i.OvertimeNightWeekend : 0;
                            i.OvertimeHoliday      = i.OvertimeHoliday != null ? (double)i.OvertimeHoliday : 0;
                            i.OvertimeNightHoliday = i.OvertimeNightHoliday != null ? (double)i.OvertimeNightHoliday : 0;

                            model.RateAdjust  = model.RateAdjust != null ? (double)model.RateAdjust : 0;
                            model.BonusBudget = model.BonusBudget != null ? (double)model.BonusBudget : 0;
                            #endregion

                            #region Tính toán số liệu
                            double AmountHour     = (double)i.SalaryAverage * (double)i.QuantityEmp;
                            double AmountLeaveDay = (double)i.SalaryAverage * (double)i.LeaveUnpaid != 0 ? ((double)i.LeaveUnpaid / StandardHour) : 1;
                            double AmountOvertime = 0;
                            AmountOvertime += (double)i.SalaryAverage * 1.5 * (double)i.OvertimeNormal;
                            AmountOvertime += (double)i.SalaryAverage * 1.95 * (double)i.OvertimeNightNormal;
                            AmountOvertime += (double)i.SalaryAverage * 2.0 * (double)i.OvertimeWeekend;
                            AmountOvertime += (double)i.SalaryAverage * 2.6 * (double)i.OvertimeNightWeekend;
                            AmountOvertime += (double)i.SalaryAverage * 3.0 * (double)i.OvertimeHoliday;
                            AmountOvertime += (double)i.SalaryAverage * 3.9 * (double)i.OvertimeNightHoliday;
                            double Percent     = (double)model.RateAdjust != 0 ? (double)model.RateAdjust / 100 : 1;
                            double AmountTotal = ((AmountHour - AmountLeaveDay + AmountOvertime) * Percent) + (double)model.BonusBudget;
                            //cập nhật tổng tiền cho master
                            TotalAmount += AmountTotal;
                            #endregion

                            //tạo dữ liệu detail
                            Sal_PayrollEstimateDetail Detail = new Sal_PayrollEstimateDetail();
                            Detail.ID                   = Guid.NewGuid();
                            Detail.SalaryAverage        = i.SalaryAverage;
                            Detail.PayrollEstimateID    = Master.ID;
                            Detail.OrgStructureID       = i.OrgStructureID;
                            Detail.LeaveUnpaid          = i.LeaveUnpaid;
                            Detail.OvertimeHoliday      = i.OvertimeHoliday;
                            Detail.OvertimeNightHoliday = i.OvertimeNightHoliday;
                            Detail.OvertimeNightNormal  = i.OvertimeNightNormal;
                            Detail.OvertimeNightWeekend = i.OvertimeNightWeekend;
                            Detail.QuantityEmp          = i.QuantityEmp;
                            Detail.OvertimeNormal       = i.OvertimeNormal;
                            Detail.OvertimeWeekend      = i.OvertimeWeekend;
                            Detail.AmountHour           = AmountHour;
                            Detail.AmountLeaveDay       = AmountLeaveDay;
                            Detail.AmountOvertime       = AmountOvertime;
                            Detail.AmountTotal          = AmountTotal;
                            repoPayrollEstimateDetail.Add(Detail);
                        }

                        //update tổng tiền
                        Master.AmountTotal = TotalAmount;
                        repoPayrollEstimate.Add(Master);
                    }
                    unitOfWork.SaveChanges();
                    return(true);
                }
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 24
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();
            }
        }
Ejemplo n.º 25
0
        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";
            }
        }
Ejemplo n.º 26
0
        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;
            }
        }
Ejemplo n.º 27
0
        public void ChangeMethodOverTime_Manual(Att_OvertimeEntity model)
        {

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_Overtime = new CustomBaseRepository<Att_Overtime>(unitOfWork);
                var repoAtt_TimeofInLieu = new CustomBaseRepository<Att_TimeOffInLieu>(unitOfWork);



                double TimeOffRealValidate = 0;
                double TimeOffValidate = 0;
                double CashOutValidate = 0;
                if (model.TimeOffReal != null)
                {
                    TimeOffRealValidate = (double)model.TimeOffReal;
                    //double.TryParse(model.TimeOffReal.ToString(), out TimeOffRealValidate);
                }
                if (model.HourToTimeOff != null)
                {
                    TimeOffValidate = (double)model.HourToTimeOff;
                    //double.TryParse(txt_TimeOff.Text, out TimeOffValidate);
                }
                if (model.TimeRegister != null)
                {
                    CashOutValidate = (double)model.TimeRegister;
                    //double.TryParse(txt_CashOut.Text, out CashOutValidate);
                }
                if (TimeOffRealValidate < 0 || TimeOffValidate < 0 || CashOutValidate < 0)
                {
                    return;
                }

                double Cashout = CashOutValidate;
                double Timeoff = TimeOffValidate;

                //if (Ot.Status == OverTimeStatus.E_APPROVED.ToString())
                //{
                //    Common.MessageBoxs(Messages.Msg, Messages.DataCantBeModify.TranslateString(), Ext.Net.MessageBox.Icon.WARNING, string.Empty);
                //    return;
                //}

                Att_Overtime OT_New = new Att_Overtime();

                if (Cashout > 0 && Timeoff <= 0)
                {
                    //Chuyển hết cho trả tiền
                    model.MethodPayment = MethodOption.E_CASHOUT.ToString();

                }
                else if (Cashout <= 0 && Timeoff > 0)
                {
                    //Chuyển hết cho nghỉ bù
                    model.MethodPayment = MethodOption.E_TIMEOFF.ToString();


                }
                else if (Cashout > 0 && Timeoff > 0)
                {
                    //Vửa chuyển tiền vừa nghỉ bù
                    model.MethodPayment = MethodOption.E_CASHOUT.ToString();
                    model.RegisterHours = Cashout;

                    if (model.Status == OverTimeStatus.E_APPROVED.ToString())
                    {
                        model.ApproveHours = Cashout;
                    }
                    if (model.Status == OverTimeStatus.E_CONFIRM.ToString())
                    {
                        model.ApproveHours = Cashout;
                        model.ConfirmHours = Cashout;
                    }
                    OT_New = model.CopyData<Att_Overtime>();
                    OT_New.ID = Guid.NewGuid();
                    OT_New.WorkDate = model.WorkDate.AddHours(model.RegisterHours);
                    OT_New.MethodPayment = MethodOption.E_TIMEOFF.ToString();
                    OT_New.RegisterHours = Timeoff;
                    if (OT_New.Status == OverTimeStatus.E_APPROVED.ToString())
                    {
                        OT_New.ApproveHours = Timeoff;
                    }
                    if (OT_New.Status == OverTimeStatus.E_CONFIRM.ToString())
                    {
                        OT_New.ApproveHours = Timeoff;
                        OT_New.ConfirmHours = Timeoff;
                    }
                    if (model.IsNonOvertime == true)
                    {
                        //model.IsNonOvertime = true;
                        OT_New.IsNonOvertime = true;
                    }
                    //repoAtt_Overtime.FindBy<Att_Overtime>();
                    repoAtt_Overtime.Add(OT_New);
                    var att_overtimeEntity = model.CopyData<Att_Overtime>();
                    repoAtt_Overtime.Edit(att_overtimeEntity);

                    //EntityService.AddEntity<Att_Overtime>(GuidContext, (new List<Att_Overtime>() { OT_New }).ToArray());
                }

                if (model.LeaveDay1 != null || model.LeaveDay2 != null)
                {
                    DateTime? date1 = null;
                    DateTime? date2 = null;
                    if (model.LeaveDay1 != null)
                    {
                        date1 = model.LeaveDay1;
                    }
                    if (model.LeaveDay2 != null)
                    {
                        date2 = model.LeaveDay2;
                    }
                    //string Error = AddTimeOffInLieu(new List<Att_Overtime>() { Ot, OT_New }, date1, date2);
                    //if (Error != string.Empty)
                    //{
                    //    return;
                    //}
                }

                if (model.Status == OverTimeStatus.E_APPROVED.ToString() || model.Status == OverTimeStatus.E_CONFIRM.ToString())
                {
                    List<Att_TimeOffInLieu> lstTimeOffInsert = new List<Att_TimeOffInLieu>();
                    //TimeOffInLieeu
                    //1 Xóa Đi những cái OT liên Quan trong TimeOff
                    //2 Insert lại nhưng cái liên quan đên TimeOff
                    List<Att_TimeOffInLieu> lstTimeOff = repoAtt_TimeofInLieu.FindBy(m => m.OvertimeID == model.ID).ToList<Att_TimeOffInLieu>();
                    foreach (var item in lstTimeOff)
                    {
                        item.IsDelete = null;
                    }

                    if (model.MethodPayment == MethodOption.E_TIMEOFF.ToString())
                    {
                        Att_TimeOffInLieu TimeOffInsert = AddTimeOffInLieu(model.CopyData<Att_Overtime>());
                        TimeOffInsert.ID = Guid.NewGuid();
                        TimeOffInsert.ProfileID = model.ProfileID;
                        lstTimeOffInsert.Add(TimeOffInsert);
                    }
                    if (OT_New.MethodPayment == MethodOption.E_TIMEOFF.ToString())
                    {
                        Att_TimeOffInLieu TimeOffInsert = AddTimeOffInLieu(OT_New);
                        TimeOffInsert.ID = Guid.NewGuid();
                        TimeOffInsert.ProfileID = model.ProfileID;
                        lstTimeOffInsert.Add(TimeOffInsert);
                    }
                    if (lstTimeOffInsert.Count > 0)
                    {
                        for (int i = 0; i < lstTimeOffInsert.Count; i++)
                        {
                            lstTimeOffInsert[i].Hre_Profile = null;
                            repoAtt_TimeofInLieu.Add(lstTimeOffInsert[i]);
                        }
                        // repoAtt_TimeofInLieu.Add(lstTimeOffInsert);
                        //EntityService.AddEntity<Att_TimeOffInLieu>(GuidContext, lstTimeOffInsert.ToArray());
                    }
                }
                unitOfWork.SaveChanges();
                // EntityService.SubmitChanges(GuidContext, LoginUserID.Value);
                //IsSave = false;

                //IsSave = false;
            }
            //return Json(new { });

        }
Ejemplo n.º 28
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;
                }
            }
        }
Ejemplo n.º 29
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);
            }
        }
Ejemplo n.º 30
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();
            }
        }
Ejemplo n.º 31
0
        public Hashtable ComputeSalGroup(IUnitOfWork unitOfWork, DateTime monthYear, List<Sal_SalaryDepartment> lstSalDep, List<Sal_SalaryDepartmentItem> lstSalDepItem, ref List<Sal_SalaryDepartmentItem> lstItemDelete,
                                         DateTime DateStart, DateTime DateEnd, List<Cat_OrgStructure> listOrg)
        {
                #region Query Data

                Hashtable htSalGroup = new Hashtable();
                //Nhân viên
                var reposProfile = new CustomBaseRepository<Hre_Profile>(unitOfWork);

                //Nhân viên
                var reposSalaryDepartmentItem = new CustomBaseRepository<Sal_SalaryDepartmentItem>(unitOfWork);

                //Bảng công
                var reposAttendanceTb = new CustomBaseRepository<Att_AttendanceTable>(unitOfWork);

                //Bảng công chi tiết
                var reposAttendanceTbItem = new CustomBaseRepository<Att_AttendanceTableItem>(unitOfWork);

                //Ca làm việc
                var reposAttRoster = new CustomBaseRepository<Att_Roster>(unitOfWork);

                //Lương cơ bản
                var reposBasicSalary = new CustomBaseRepository<Sal_BasicSalary>(unitOfWork);

                //Chế độ lương
                var reposSalGrade = new CustomBaseRepository<Sal_Grade>(unitOfWork);
                #endregion

                foreach (Sal_SalaryDepartment salDep in lstSalDep)
                {
                    List<Sal_SalaryDepartmentItem> rsDepItem = new List<Sal_SalaryDepartmentItem>();
                    DateStart = salDep.DateFrom != null ? salDep.DateFrom.Value : DateStart;
                    DateEnd = salDep.DateTo != null ? salDep.DateTo.Value : DateEnd;

                    List<Guid> guidPro = new List<Guid>();
                    List<Guid> guidOrgAllChild = new List<Guid>();
                    List<Att_Roster> lstRosterLine = new List<Att_Roster>();

                    #region Lấy danh sách nhân viên trong phòng ban hoặc chuyền
                    if (salDep.TypeCompute == MethodComputeGroupSalary.E_COMPUTE_LINE.ToString())
                    {
                        lstRosterLine = reposAttRoster.FindBy(rs => rs.ProductionLineID == salDep.ProductionLineID &&
                                                              rs.IsDelete == null && rs.DateStart <= DateEnd && rs.DateEnd >= DateStart).ToList();
                        guidPro = lstRosterLine.Select(wh => wh.ProfileID).ToList();
                    }
                    else
                    {
                        if (salDep.OrgStructureID == null)
                            continue;
                        List<Cat_OrgStructure> lstChildsStructure = null;
                        Cat_OrgStructure DepartmentFilter = listOrg.FirstOrDefault(p => p.ID == salDep.OrgStructureID);
                        if (DepartmentFilter != null)
                            lstChildsStructure = GetChilds(listOrg, DepartmentFilter.ID);
                        else
                            lstChildsStructure = listOrg.Where(o => o.ID == salDep.OrgStructureID && o.IsDelete == null).ToList();
                        guidOrgAllChild = lstChildsStructure.Select(s => s.ID).Distinct().ToList();

                        //Lấy tất cả ID nhân viên trong các phòng ban trên.
                        guidPro = reposProfile.FindBy(hr => hr.IsDelete == null && guidOrgAllChild.Contains(hr.OrgStructureID.Value)).Select(hr => hr.ID).ToList();
                    }
                    #endregion

                    //Danh sách NV bao gồm các trạng thái (new, edit, fix, remove)
                    string stNEW = EnumDropDown.StatusLoadEnumSalDepartItem.E_NEW.ToString();
                    string stEDIT = EnumDropDown.StatusLoadEnumSalDepartItem.E_EDIT.ToString();
                    string stREMOVE = EnumDropDown.StatusLoadEnumSalDepartItem.E_REMOVE.ToString();
                    string stFIX = EnumDropDown.StatusLoadEnumSalDepartItem.E_FIX.ToString();
                    string stEDIT_FIX = EnumDropDown.StatusLoadEnumSalDepartItem.E_EDIT_FIX.ToString();
                    string[] strStatus = new string[] { stNEW, stREMOVE, stEDIT, stFIX, stEDIT_FIX };

                    var lstSalDepItemStatus = lstSalDepItem.Where(st => st.SalaryDepartmentID == salDep.ID && !String.IsNullOrEmpty(st.Status) && strStatus.Contains(st.Status)).ToList();
                    List<Guid> lstProAdd = new List<Guid>();
                    List<Guid> lstProFix = new List<Guid>();
                    List<Guid> lstProEdit = new List<Guid>();
                    List<Sal_SalaryDepartmentItem> lstItemRemove = new List<Sal_SalaryDepartmentItem>();

                    if (lstSalDepItemStatus.Count > 0)
                    {
                        #region LẤY RA DS NHÂN VIÊN VỚI CÁC TRẠNG THÁI
                        //Nếu tồn tại nhân viên là Fix, thì sẽ chỉ tính những profile có trạng thái fix, bỏ qua các trạng thái khác.
                        //Bổ sung thêm trạng thái Edit_Fix
                        lstProFix = lstSalDepItemStatus.Where(st => st.Status == stFIX || st.Status == stEDIT_FIX).Select(st => st.ProfileID).ToList();

                        //Lấy danh sách NV ko phải trạng thái fix trong departmentitem để xóa đi ( vì chỉ tính lương cho NV có Fix)
                        List<Sal_SalaryDepartmentItem> lstSalDepItemStatusNotFix = lstSalDepItem.Where(st => st.SalaryDepartmentID == salDep.ID && st.IsDelete == null).ToList();
                        lstSalDepItemStatusNotFix = lstSalDepItemStatusNotFix.Where(st => st.Status == null || (st.Status != stFIX && st.Status != stEDIT_FIX)).ToList();

                        if (lstProFix != null && lstProFix.Count > 0)
                        {
                            //Lấy những nhân viên không phải là Fix đưa vào trong lstItemDelete để xóa đi.
                            if (lstSalDepItemStatusNotFix.Count > 0)
                                lstItemDelete.AddRange(lstSalDepItemStatusNotFix);

                            //Chỉ add những nhân viên có Fix vào để tính.
                            guidPro.Clear();
                            foreach (Guid id in lstProFix)
                            {
                                guidPro.Add(id);
                            }
                        }
                        //Nếu ko có nhân viên nào là Fix, bắt đầu kiểm tra: New, edit, remove
                        else
                        {
                            //New
                            lstProAdd = lstSalDepItemStatus.Where(st => st.Status == stNEW).Select(st => st.ProfileID).ToList();
                            foreach (Guid id in lstProAdd)
                            {
                                if (!guidPro.Contains(id))
                                    guidPro.Add(id);
                            }

                            //Edit
                            lstProEdit = lstSalDepItemStatus.Where(st => st.Status == stEDIT).Select(st => st.ProfileID).ToList();
                            foreach (Guid id in lstProEdit)
                            {
                                if (!guidPro.Contains(id))
                                    guidPro.Add(id);
                            }

                            //Remove
                            lstItemRemove = lstSalDepItemStatus.Where(st => st.Status == stREMOVE).ToList();
                            List<Guid> lstProRemove = lstItemRemove.Select(st => st.ProfileID).ToList();
                            foreach (Guid id in lstProRemove)
                            {
                                if (guidPro.Contains(id))
                                    guidPro.Remove(id);
                            }
                        }
                        #endregion
                    }

                    //Lấy grade theo ds nhân viên
                    var lstGradeAll = reposSalGrade.FindBy(gr => gr.IsDelete == null && guidPro.Contains(gr.ProfileID)).ToList();

                    //Lấy Lương cơ bản theo ds nhân viên
                    var lstBasicSal = reposBasicSalary.FindBy(sal => sal.IsDelete == null && sal.DateOfEffect <= DateEnd && guidPro.Contains(sal.ProfileID)).ToList(); 

                    //Lấy roster theo ds nhân viên
                    var lstAllRoster = reposAttRoster.FindBy(rs => guidPro.Contains(rs.ProfileID) && rs.IsDelete == null && rs.DateStart <= DateEnd && rs.DateEnd >= DateStart)
                                                     .Select(rs => new { rs.ID, rs.ProfileID, rs.DateStart, rs.DateEnd, rs.SalaryType, rs.Cat_Shift }).ToList();
                    //Lấy bảng công theo ds nv
                    var lstAttAtendance = reposAttendanceTb.FindBy(att => att.IsDelete == null && att.MonthYear == monthYear && guidPro.Contains(att.ProfileID)).ToList();
                    var lstAttAtendanceID = lstAttAtendance.Select(att => att.ID).ToList();

                    //Lấy bảng công chi tiết
                    var lstAttAttendanceItem = reposAttendanceTbItem.FindBy(it => it.IsDelete == null && lstAttAtendanceID.Contains(it.AttendanceTableID)).ToList();

                    //Sau khi tiến hành các bước trên, sẽ có 1 danh sách nhân viên cuối cùng để xử lý.
                    var lstProfileOrg = reposProfile.FindBy(hr => guidPro.Contains(hr.ID)).ToList();

                    #region " Nếu tồn tại trạng thái Fix"
                    if (lstProFix != null && lstProFix.Count > 0)
                    {
                        foreach (Hre_Profile _pro in lstProfileOrg)
                        {
                            //Trạng thái: EDIT_FIX
                            //Những nhân viên đã được cố định và chỉnh sửa: Hệ số, giờ làm việc, OT thì sẽ lưu lại trong sal_departmentitem, và sẽ được lấy lên từ đây để tính, ko thông qua basicsalary nữa.
                            Sal_SalaryDepartmentItem itemProEditFix = new Sal_SalaryDepartmentItem();
                            if (lstProFix.Contains(_pro.ID))
                            {
                                itemProEditFix = lstSalDepItem.Where(it => it.ProfileID == _pro.ID && it.SalaryDepartmentID == salDep.ID &&
                                                                           it.Status == stEDIT_FIX).FirstOrDefault();
                                if (itemProEditFix != null)
                                {
                                    rsDepItem.Add(itemProEditFix);
                                    continue;
                                }
                            }

                            Sal_SalaryDepartmentItem itemProFix = new Sal_SalaryDepartmentItem(); ;
                            itemProFix = lstSalDepItem.Where(it => it.ProfileID == _pro.ID && it.SalaryDepartmentID == salDep.ID && it.Status == stFIX).FirstOrDefault();

                            #region Ver8 chưa dùng
                            //Sal_Grade grade = GradeDAO.GetGrade(lstGradeAll, _pro.ID, DateEnd);
                            //if (grade == null)
                            //{
                            //    continue;
                            //}
                            //Cat_GradeCfg gradeCfg = lstGradeCfg.Where(gra => gra.ID == grade.GradeID).FirstOrDefault();
                            //if (gradeCfg == null || gradeCfg.Formula != enumFomula)
                            //    continue;
                            //AttendanceService.GetSalaryDateRange(gradeCfg, sys_AppConfig, null, monthYear, out DateStart, out DateEnd);
                            //if (salDep.DateFrom != null && salDep.DateFrom.Value >= DateStart && salDep.DateFrom.Value <= DateEnd)
                            //{
                            //    DateStart = salDep.DateFrom.Value;
                            //}
                            //if (salDep.DateTo != null && salDep.DateTo.Value >= DateStart && salDep.DateTo.Value <= DateEnd)
                            //{
                            //    DateEnd = salDep.DateTo.Value;
                            //}
                            #endregion

                            //dữ liệu công
                            var _att = lstAttAtendance.Where(att => att.ProfileID == _pro.ID).Select(att => new { att.ID }).FirstOrDefault();
                            if (_att == null)
                                continue;
                            var _attLstItem1 = lstAttAttendanceItem.Where(at => at.AttendanceTableID == _att.ID).ToList();

                            List<Att_AttendanceTableItem> _attLstItem = new List<Att_AttendanceTableItem>();
                            #region Xử lý trường hợp 1 tháng có 2 cách tính lương ( lương bộ phận và lương thời gian). Vì vậy cần kiểm tra roster để lấy công cho phù hợp.
                            if (lstAllRoster.Count > 0)
                            {
                                var roster = lstAllRoster.Where(ro => ro.ProfileID == _pro.ID && ro.DateStart.Year == monthYear.Year
                                                                                              && ro.DateEnd.Month >= monthYear.Month && ro.DateStart.Month <= monthYear.Month
                                                                                              && ro.SalaryType != null && ro.SalaryType == SalaryRosterType.E_DEPTSAL.ToString()).FirstOrDefault();
                                if (roster != null && roster.Cat_Shift != null)
                                {
                                    _attLstItem = _attLstItem1.Where(it => it.ShiftID.HasValue && it.ShiftID.Value == roster.Cat_Shift.ID
                                                                                               && it.WorkDate >= roster.DateStart && it.WorkDate <= roster.DateEnd
                                                                                               && it.DutyCode == DutyCode.E_ON.ToString()).ToList();
                                }
                                else //Trừ bớt các ngày công là timesal
                                {
                                    var rostertimesal = lstAllRoster.Where(ro => ro.ProfileID == _pro.ID && ro.DateStart.Year == monthYear.Year
                                                                                                         && ro.DateEnd.Month >= monthYear.Month && ro.DateStart.Month <= monthYear.Month
                                                                                                         && ro.SalaryType != null && ro.SalaryType == SalaryRosterType.E_TIMESAL.ToString()).FirstOrDefault();
                                    if (rostertimesal != null && rostertimesal.Cat_Shift != null)
                                    {
                                        List<Att_AttendanceTableItem> lstattitemtimesal = _attLstItem1.Where(it => it.ShiftID.HasValue && it.ShiftID.Value == rostertimesal.Cat_Shift.ID
                                                                                                             && it.WorkDate >= rostertimesal.DateStart && it.WorkDate <= rostertimesal.DateEnd
                                                                                                             && it.DutyCode == DutyCode.E_ON.ToString()).ToList();
                                        foreach (Att_AttendanceTableItem it in lstattitemtimesal)
                                        {
                                            if (it != null)
                                                _attLstItem1.Remove(it);
                                        }
                                    }
                                }
                            }
                            if (_attLstItem.Count < 1)
                                _attLstItem = _attLstItem1;
                            #endregion

                            List<Sal_BasicSalary> lstBasicSalPro = lstBasicSal.Where(sal => sal.ProfileID == _pro.ID).OrderByDescending(sal => sal.DateOfEffect).ToList();

                            //Xóa những nhân viên được Fix có lương cơ bản đã đc tính trước đó, để tính lại.
                            if (lstBasicSalPro != null && lstBasicSalPro.Count > 0)
                            {
                                List<Sal_SalaryDepartmentItem> lstItemFix = lstSalDepItem.Where(it => it.ProfileID == _pro.ID && it.SalaryDepartmentID == salDep.ID
                                                                            && (it.Status == stFIX
                                                                            || it.Status == stEDIT_FIX)).ToList();
                                if (lstItemFix != null && lstItemFix.Count > 0)
                                    lstItemDelete.AddRange(lstItemFix);
                            }

                            //Bắt đầu thêm giờ công, hệ số, giờ OT lần lượt cho từng người (XC 1.2)
                            if (salDep.TypeCompute == MethodComputeGroupSalary.E_COMPUTE_LINE.ToString())
                            {
                                List<Att_Roster> lstRosterPro = lstRosterLine.Where(rs => rs.ProfileID == _pro.ID).ToList();
                                rsDepItem.AddRange(CalSalaryLineItemProfile(salDep, _attLstItem, _pro, lstBasicSalPro, lstRosterPro, DateStart, DateEnd, monthYear, itemProFix));
                            }
                            else
                            {
                                rsDepItem.AddRange(CalSalaryDepartmentItemProfile(salDep, _attLstItem, _pro, lstBasicSalPro, DateStart, DateEnd, monthYear, itemProFix));
                            }
                        }
                    }
                    #endregion
                    #region " Không tồn tại trạng thái Fix"
                    else
                    {
                        //test
                        //lstProfileOrg = lstProfileOrg.Where(hr => hr.CodeEmp == "VPM183").ToList();
                        //end test
                        foreach (Hre_Profile _pro in lstProfileOrg)
                        {
                            //Trạng thái: NEW
                            //Những nhân viên trong trạng thái này sẽ ko thuộc phòng ban hoặc chuyền ban đầu. Khi đó các hệ số, giờ làm việc, OT sẽ được thêm vào và lưu trong sal_departmentitem
                            Sal_SalaryDepartmentItem itemProAdd = new Sal_SalaryDepartmentItem();
                            if (lstProAdd.Contains(_pro.ID))
                            {
                                itemProAdd = lstSalDepItem.Where(it => it.ProfileID == _pro.ID && it.SalaryDepartmentID == salDep.ID &&
                                                                       it.Status == stNEW).FirstOrDefault();
                                rsDepItem.Add(itemProAdd);
                                continue;
                            }

                            //Trạng thái: EDIT
                            //Những nhân viên đã được chỉnh sửa: Hệ số, giờ làm việc, OT thì sẽ lưu lại trong sal_departmentitem, và sẽ được lấy lên từ đây để tính, ko thông qua basicsalary nữa.
                            if (lstProEdit.Contains(_pro.ID))
                            {
                                itemProAdd = lstSalDepItem.Where(it => it.ProfileID == _pro.ID && it.SalaryDepartmentID == salDep.ID &&
                                                                       it.Status == stEDIT).FirstOrDefault();
                                rsDepItem.Add(itemProAdd);
                                continue;
                            }

                            #region Ver8 chưa dùng
                            //Sal_Grade grade = GradeDAO.GetGrade(lstGradeAll, _pro.ID, DateEnd);
                            //if (grade == null)
                            //{
                            //    continue;
                            //}
                            //Cat_GradeCfg gradeCfg = lstGradeCfg.Where(gra => gra.ID == grade.GradeID).FirstOrDefault();
                            //if (gradeCfg == null || gradeCfg.Formula != enumFomula)
                            //    continue;
                            //List<Sal_SalaryDepartmentItem> lstItemPro = lstSalDepItem.Where(it => it.ProfileID == _pro.ID && it.SalaryDepartmentID == salDep.ID
                            //                                            && (String.IsNullOrEmpty(it.Status) || !strStatus.Contains(it.Status))).ToList();
                            //lstItemDelete.AddRange(lstItemPro);

                            //AttendanceService.GetSalaryDateRange(gradeCfg, sys_AppConfig, null, monthYear, out DateStart, out DateEnd);
                            //if (salDep.DateFrom != null && salDep.DateFrom.Value >= DateStart && salDep.DateFrom.Value <= DateEnd)
                            //{
                            //    DateStart = salDep.DateFrom.Value;
                            //}
                            //if (salDep.DateTo != null && salDep.DateTo.Value >= DateStart && salDep.DateTo.Value <= DateEnd)
                            //{
                            //    DateEnd = salDep.DateTo.Value;
                            //}
                            #endregion

                            //dữ liệu công
                            var _att = lstAttAtendance.Where(att => att.ProfileID == _pro.ID).Select(att => new { att.ID }).FirstOrDefault();
                            if (_att == null)
                                continue;
                            var _attLstItem1 = lstAttAttendanceItem.Where(at => at.AttendanceTableID == _att.ID).ToList();

                            List<Att_AttendanceTableItem> _attLstItem = new List<Att_AttendanceTableItem>();
                            #region Xử lý trường hợp 1 tháng có 2 cách tính lương ( lương bộ phận và lương thời gian). Vì vậy cần kiểm tra roster để lấy công cho phù hợp.
                            if (lstAllRoster.Count > 0)
                            {
                                var roster = lstAllRoster.Where(ro => ro.ProfileID == _pro.ID && ro.DateStart.Year == monthYear.Year
                                                                                              && ro.DateEnd.Month >= monthYear.Month && ro.DateStart.Month <= monthYear.Month
                                                                                              && ro.SalaryType != null && ro.SalaryType == SalaryRosterType.E_DEPTSAL.ToString()).FirstOrDefault();
                                if (roster != null && roster.Cat_Shift != null)
                                {
                                    _attLstItem = _attLstItem1.Where(it => it.ShiftID.HasValue && it.ShiftID.Value == roster.Cat_Shift.ID
                                                                                               && it.WorkDate >= roster.DateStart && it.WorkDate <= roster.DateEnd
                                                                                               && it.DutyCode == DutyCode.E_ON.ToString()).ToList();
                                }
                                else //Trừ bớt các ngày công là timesal
                                {
                                    var rostertimesal = lstAllRoster.Where(ro => ro.ProfileID == _pro.ID && ro.DateStart.Year == monthYear.Year
                                                                                                         && ro.DateEnd.Month >= monthYear.Month && ro.DateStart.Month <= monthYear.Month
                                                                                                         && ro.SalaryType != null && ro.SalaryType == SalaryRosterType.E_TIMESAL.ToString()).FirstOrDefault();
                                    if (rostertimesal != null && rostertimesal.Cat_Shift != null)
                                    {
                                        List<Att_AttendanceTableItem> lstattitemtimesal = _attLstItem1.Where(it => it.ShiftID.HasValue && it.ShiftID.Value == rostertimesal.Cat_Shift.ID
                                                                                                             && it.WorkDate >= rostertimesal.DateStart && it.WorkDate <= rostertimesal.DateEnd
                                                                                                             && it.DutyCode == DutyCode.E_ON.ToString()).ToList();
                                        foreach (Att_AttendanceTableItem it in lstattitemtimesal)
                                        {
                                            if (it != null)
                                                _attLstItem1.Remove(it);
                                        }
                                    }
                                }
                            }
                            if (_attLstItem.Count < 1)
                                _attLstItem = _attLstItem1;
                            #endregion

                            List<Sal_BasicSalary> lstBasicSalPro = lstBasicSal.Where(sal => sal.ProfileID == _pro.ID).OrderByDescending(sal => sal.DateOfEffect).ToList();

                            //Bắt đầu thêm giờ công, hệ số, giờ OT lần lượt cho từng người (XC 1.2)
                            if (salDep.TypeCompute == MethodComputeGroupSalary.E_COMPUTE_LINE.ToString())
                            {
                                List<Att_Roster> lstRosterPro = lstRosterLine.Where(rs => rs.ProfileID == _pro.ID).ToList();
                                rsDepItem.AddRange(CalSalaryLineItemProfile(salDep, _attLstItem, _pro, lstBasicSalPro, lstRosterPro, DateStart, DateEnd, monthYear, itemProAdd));
                            }
                            else
                            {
                                rsDepItem.AddRange(CalSalaryDepartmentItemProfile(salDep, _attLstItem, _pro, lstBasicSalPro, DateStart, DateEnd, monthYear, itemProAdd));
                            }
                        }
                    }
                    #endregion

                    //Trả về 0 các trạng thái REMOVE đã tính lần đầu
                    lstItemRemove.ForEach(it => it.AmoutSalary = 0);

                    //Tính toán tiền lương và các loại tiền OT (XC Finished)
                    ComputeAmountPro(rsDepItem, salDep);
                    foreach (var t in rsDepItem)
                    {
                        t.ID = Guid.NewGuid();
                        reposSalaryDepartmentItem.Add(t);
                    }
                    //View lên lưới những nhân viên đã chuyển qua trạng thái là E_REMOVE.
                    //Mục đích: Nếu muốn tính lại cho những NV này thì edit chuyển trạng thái lại để tính.
                    rsDepItem.AddRange(lstItemRemove);

                    htSalGroup.Add(salDep, rsDepItem);
                }
                return htSalGroup;
        }
Ejemplo n.º 32
0
        /// <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;
        }
Ejemplo n.º 33
0
        public String SaveLeaveDataItem(Guid workDayID, Guid LeaveTypeID, Guid? userApprove, string comment, bool IsAllowModify)
        {
            var message = "";
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
                var repoCat_LeaveDayType = new CustomBaseRepository<Cat_LeaveDayType>(unitOfWork);
                var repoCat_Shift = new CustomBaseRepository<Cat_Shift>(unitOfWork);
                var repoAtt_Workday = new CustomBaseRepository<Att_Workday>(unitOfWork);
                var repoSys_AllSeting = new CustomBaseRepository<Sys_AllSetting>(unitOfWork);
                var repoHre_Profile = new CustomBaseRepository<Hre_Profile>(unitOfWork);
                var repoAtt_Grade = new CustomBaseRepository<Att_Grade>(unitOfWork);
                var repoCat_GradeAttendance = new CustomBaseRepository<Cat_GradeAttendance>(unitOfWork);
                var repoHre_WorkHistory = new CustomBaseRepository<Hre_WorkHistory>(unitOfWork);
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
                var repoAtt_Roster = new CustomBaseRepository<Att_Roster>(unitOfWork);

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



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

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

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

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

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

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

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

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

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

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

                //var listWorkDay=repoAtt_Workday.GetAll().ToList();
                //Att_Workday workdayOld = listWorkDay.Where(m => m.ProfileID == WorkDayInDB.ProfileID && m.WorkDate == WorkDayInDB.WorkDate).FirstOrDefault();
                //if (workdayOld != null)
                //{
                //    int index = listWorkDay.IndexOf(workdayOld);
                //    listWorkDay.Remove(workdayOld);
                //    listWorkDay.Insert(index, WorkDayInDB.CopyData<Att_Workday>());
                //}
                repoAtt_LeaveDay.Add(lstLeaveDayInsert);
                unitOfWork.SaveChanges();
                //EntityService.AddEntity<Att_LeaveDay>(GuidContext, lstLeaveDayInsert.ToArray());
                //message = "Susscess";
                return message;
                //return WorkDayInDB;
            }
        }
Ejemplo n.º 34
0
        public ResultsObject SaveChangeHoldSalary(List<Sal_HoldSalaryEntity> ListEntity)
        {
            try
            {
                using (var context = new VnrHrmDataContext())
                {
                    var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                    var repoSal_HoldSalary = new CustomBaseRepository<Sal_HoldSalary>(unitOfWork);
                    List<Sal_HoldSalary> TotalHoldSalary = repoSal_HoldSalary.FindBy(m => m.IsDelete != true).ToList();

                    foreach (var i in ListEntity)
                    {
                        #region Kiểm tra nhân viên đã có dữ liệu giữ lương hay chưa

                        Sal_HoldSalary HoldSalaryByProfile = TotalHoldSalary.FirstOrDefault(m => m.ProfileID == i.ProfileID && m.MonthSalary != null && m.MonthSalary.Value.Day == i.MonthSalary.Value.Day && m.TimeAnalyzeID != null && m.TimeAnalyzeID == i.TimeAnalyzeID);
                        if (HoldSalaryByProfile != null)
                        {
                            if (HoldSalaryByProfile.Status == EnumDropDown.HoldSalaryStatus.E_APPROVED.ToString())
                            {
                                continue;
                            }
                            else
                            {
                                HoldSalaryByProfile.AmountSalary = i.AmountSalary;
                                HoldSalaryByProfile.IsLeaveContinuous = i.IsLeaveContinuous;
                                HoldSalaryByProfile.IsLeaveM = i.IsLeaveM;
                                HoldSalaryByProfile.Terminate = i.Terminate;
                                HoldSalaryByProfile.TimeAnalyzeID = i.TimeAnalyzeID;
                            }
                        }
                        else
                        {
                            Sal_HoldSalary HoldSalary = i.Copy<Sal_HoldSalary>();
                            repoSal_HoldSalary.Add(HoldSalary);
                        }
                        #endregion
                    }
                    unitOfWork.SaveChanges();
                    return new ResultsObject();
                }
            }
            catch (Exception ex)
            {
                return new ResultsObject() { Success = false, Messenger = ex.Message };
            }
        }
Ejemplo n.º 35
0
        public void ComputeBonusUnusualAllowance_Progress(Guid AsynTaskID, Sal_UnusualAllowanceEntity model, bool AllowanceEvaluationYear = false)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork                  = (IUnitOfWork) new UnitOfWork(context);
                var repoSys_AsynTask            = new CustomBaseRepository <Sys_AsynTask>(unitOfWork);
                var repoCat_Element             = new CustomBaseRepository <Cat_Element>(unitOfWork);
                var repoCat_UnusualAllowanceCfg = new CustomBaseRepository <Cat_UnusualAllowanceCfg>(unitOfWork);
                var repoUnusualAllowance        = new CustomBaseRepository <Sal_UnusualAllowance>(unitOfWork);

                Sys_AsynTask asynTask = repoSys_AsynTask.GetById(AsynTaskID);

                Sal_ComputePayrollServices CumputePayrollServices = new Sal_ComputePayrollServices();
                List <object> listModel = new List <object>();
                string        status    = string.Empty;
                Sal_ComputePayrollServices        Services                 = new Sal_ComputePayrollServices();
                List <Sal_UnusualAllowanceEntity> ListResult               = new List <Sal_UnusualAllowanceEntity>();
                List <ElementFormula>             listElementFormula       = new List <ElementFormula>();
                Sal_UnusualAllowanceServices      UnusualAllowanceServices = new Sal_UnusualAllowanceServices();

                Att_CutOffDurationEntity CutOffDuration = new Att_CutOffDurationEntity();
                if (model.MonthEnd != null)
                {
                    CutOffDuration.MonthYear = model.MonthStart.Value;
                    CutOffDuration.DateStart = model.MonthStart.Value;
                    CutOffDuration.DateEnd   = model.MonthEnd.Value;
                }
                else
                {
                    CutOffDuration.MonthYear = new DateTime(model.MonthStart.Value.Year, model.MonthStart.Value.Month, 1);
                    CutOffDuration.DateStart = new DateTime(model.MonthStart.Value.Year, model.MonthStart.Value.Month, 1);
                    CutOffDuration.DateEnd   = new DateTime(model.MonthStart.Value.Year, model.MonthStart.Value.Month, 1).AddMonths(1).AddDays(-1);
                }

                List <Hre_ProfileEntity> ListProfile = new List <Hre_ProfileEntity>();

                if (model.OrgStructureIDs != null && model.OrgStructureIDs != string.Empty)
                {
                    listModel = new List <object>();
                    listModel.AddRange(new object[18]);
                    listModel[2]  = model.OrgStructureIDs;
                    listModel[16] = 1;
                    listModel[17] = Int32.MaxValue - 1;
                    ListProfile   = GetData <Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_Profile, ref status);
                    if (model.ExProfileIDs != null)
                    {
                        string[] ExProfile = model.ExProfileIDs.Split(',');
                        ListProfile = ListProfile.Where(m => ExProfile.Contains(m.ID.ToString())).ToList();
                    }
                }
                else if (model.ProfileIDs != null && model.ProfileIDs != string.Empty)
                {
                    ListProfile = GetData <Hre_ProfileEntity>(Common.DotNetToOracle(model.ProfileIDs), ConstantSql.hrm_hr_sp_get_ProfileByIds, ref status);
                }


                //lọc profile theo workplace
                if (model.WorkingPlaceID != null)
                {
                    string[] listWorkPlare = model.WorkingPlaceID.Split(',');
                    ListProfile = ListProfile.Where(m => listWorkPlare.Contains(m.WorkPlaceID.ToString())).ToList();
                }

                List <Cat_UnusualAllowanceCfg> listUnusualAllowanceCfg = new List <Cat_UnusualAllowanceCfg>();
                listUnusualAllowanceCfg = repoCat_UnusualAllowanceCfg.FindBy(m => m.IsDelete != true).ToList();

                #region Delete các phụ cấp trong năm đã có
                List <Sal_UnusualAllowance> listUnusualAllowance = repoUnusualAllowance.FindBy(m => m.IsDelete != true && m.MonthStart != null && model.MonthStart != null && m.MonthStart.Value.Year == model.MonthStart.Value.Year && m.Status != WorkHistoryStatus.E_APPROVED.ToString()).ToList();

                //nếu là tính phép năm sức khỏe tốt thì delete thêm loại GoodHealth
                if (AllowanceEvaluationYear)
                {
                    var _tmp = listUnusualAllowanceCfg.FirstOrDefault(m => m.Code == "GoodHealth");
                    listUnusualAllowance = listUnusualAllowance.Where(m => (m.UnusualEDTypeID == model.UnusualEDTypeID || m.UnusualEDTypeID == _tmp.ID) && ListProfile.Any(t => t.ID == m.ProfileID)).ToList();
                }
                else
                {
                    listUnusualAllowance = listUnusualAllowance.Where(m => m.UnusualEDTypeID == model.UnusualEDTypeID && ListProfile.Any(t => t.ID == m.ProfileID)).ToList();
                }
                //update isdelete is true
                listUnusualAllowance.ForEach(m => m.IsDelete = true);
                #endregion

                //Cat_ElementEntity ElementItem = repoCat_Element.GetById((Guid)model.Element).Copy<Cat_ElementEntity>();
                Cat_ElementEntity ElementItem = repoCat_Element.FindBy(m => m.ID == (Guid)model.Element).FirstOrDefault().Copy <Cat_ElementEntity>();


                ComputePayrollDataModel TotalData = Services.GetDataForComputeSalary(CutOffDuration);

                List <Cat_ElementEntity> listElementAll = new List <Cat_ElementEntity>();
                listElementAll = TotalData.listElement_All;

                #region Xử lý cho tính phép năm, sức khỏe tốt
                List <Cat_UnusualAllowanceCfg> ListUnusualAllowanceCfg = new List <Cat_UnusualAllowanceCfg>();
                Cat_UnusualAllowanceCfg        PaidLeave  = null;
                Cat_UnusualAllowanceCfg        GoodHealth = null;
                ElementFormula FormulaValue = new ElementFormula();
                if (AllowanceEvaluationYear)
                {
                    ListUnusualAllowanceCfg = repoCat_UnusualAllowanceCfg.FindBy(m => m.IsDelete != true).ToList();
                    PaidLeave  = ListUnusualAllowanceCfg.FirstOrDefault(m => m.Code == "PaidLeave");
                    GoodHealth = ListUnusualAllowanceCfg.FirstOrDefault(m => m.Code == "GoodHealth");
                }
                #endregion

                foreach (var profile in ListProfile)
                {
                    if (AllowanceEvaluationYear)
                    {
                        #region Tính Công Thức
                        try
                        {
                            listElementFormula        = new List <ElementFormula>();
                            TotalData.listElement_All = repoCat_Element.FindBy(m => m.IsDelete != true).ToList().Translate <Cat_ElementEntity>();
                            listElementFormula        = CumputePayrollServices.ParseFormula(ElementItem, listElementFormula, TotalData, profile, CutOffDuration, new Dictionary <Guid, ValueCount>());
                        }
                        catch
                        {
                            listElementFormula = null;
                            continue;
                        }
                        #endregion

                        if (PaidLeave != null)
                        {
                            //lưu phần tử TienBuPhepNam
                            Sal_UnusualAllowance UnusualAllowance = new Sal_UnusualAllowance();
                            UnusualAllowance.ID              = Guid.NewGuid();
                            UnusualAllowance.ProfileID       = profile.ID;
                            UnusualAllowance.UnusualEDTypeID = PaidLeave.ID;

                            UnusualAllowance.MonthStart = CutOffDuration.DateStart;
                            UnusualAllowance.MonthEnd   = CutOffDuration.DateEnd;
                            UnusualAllowance.Type       = EnumDropDown.EDType.E_EARNING.ToString();
                            UnusualAllowance.CurrencyID = model.CurrencyID;
                            FormulaValue            = listElementFormula.Where(m => m.VariableName.ReplaceSpace() == "TienPhepNam").FirstOrDefault();
                            UnusualAllowance.Amount = double.Parse(FormulaValue != null ? FormulaValue.Value.ToString() : "0");
                            repoUnusualAllowance.Add(UnusualAllowance);
                        }

                        if (GoodHealth != null)
                        {
                            //lưu phần tử TienSucKhoe
                            Sal_UnusualAllowance UnusualAllowance = new Sal_UnusualAllowance();
                            UnusualAllowance                 = new Sal_UnusualAllowance();
                            UnusualAllowance.ID              = Guid.NewGuid();
                            UnusualAllowance.ProfileID       = profile.ID;
                            UnusualAllowance.UnusualEDTypeID = GoodHealth.ID;

                            UnusualAllowance.MonthStart = CutOffDuration.DateStart;
                            UnusualAllowance.MonthEnd   = CutOffDuration.DateEnd;
                            UnusualAllowance.Type       = EnumDropDown.EDType.E_EARNING.ToString();
                            UnusualAllowance.CurrencyID = model.CurrencyID;
                            FormulaValue            = listElementFormula.Where(m => m.VariableName.ReplaceSpace() == "TienSucKhoe").FirstOrDefault();
                            UnusualAllowance.Amount = double.Parse(FormulaValue != null ? FormulaValue.Value.ToString() : "0");
                            repoUnusualAllowance.Add(UnusualAllowance);
                        }
                    }
                    else
                    {
                        Sal_UnusualAllowance UnusualAllowance = new Sal_UnusualAllowance();
                        UnusualAllowance.ID              = Guid.NewGuid();
                        UnusualAllowance.ProfileID       = profile.ID;
                        UnusualAllowance.UnusualEDTypeID = model.UnusualEDTypeID;

                        UnusualAllowance.MonthStart = CutOffDuration.DateStart;
                        UnusualAllowance.MonthEnd   = CutOffDuration.DateEnd;
                        UnusualAllowance.Type       = EnumDropDown.EDType.E_EARNING.ToString();
                        UnusualAllowance.CurrencyID = model.CurrencyID;
                        try
                        {
                            listElementFormula        = new List <ElementFormula>();
                            TotalData.listElement_All = repoCat_Element.FindBy(m => m.IsDelete != true).ToList().Translate <Cat_ElementEntity>();
                            listElementFormula        = CumputePayrollServices.ParseFormula(ElementItem, listElementFormula, TotalData, profile, CutOffDuration, new Dictionary <Guid, ValueCount>());
                            FormulaValue            = listElementFormula.Where(m => m.VariableName.ReplaceSpace() == ElementItem.ElementCode.ReplaceSpace()).FirstOrDefault();
                            UnusualAllowance.Amount = double.Parse(FormulaValue != null ? FormulaValue.Value.ToString() : "0");
                        }
                        catch
                        {
                            UnusualAllowance.Amount = 0;
                            UnusualAllowance.Notes  = "Không tính được công thức - Lỗi: " + TotalData.Status;
                        }
                        repoUnusualAllowance.Add(UnusualAllowance);
                    }

                    if (ListProfile.IndexOf(profile) % 10 == 0)
                    {
                        asynTask.PercentComplete = (double)(ListProfile.IndexOf(profile) + 1) / (double)ListProfile.Count;
                        unitOfWork.SaveChanges();
                    }
                }
                asynTask.PercentComplete = 1;
                unitOfWork.SaveChanges();
            }
        }
Ejemplo n.º 36
0
        /// <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);
        }
Ejemplo n.º 37
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();


            }
        }
Ejemplo n.º 38
0
        public void ComputeProductSalary(string OrgStructure, Guid? ProductID, Guid? ProductItemID, DateTime MonthStart, DateTime MonthEnd, string userLoginName)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoSal_ProductSalary = new CustomBaseRepository<Sal_ProductSalary>(unitOfWork);
                var repoSal_ProductSalary1 = new CustomBaseRepository<Hre_Profile>(unitOfWork);

                List<Cat_ProductEntity> ListProduct = new List<Cat_ProductEntity>();
                List<Cat_ProductItemEntity> ListProductItem = new List<Cat_ProductItemEntity>();
                List<Hre_ProfileEntity> ListProfile = new List<Hre_ProfileEntity>();
                List<Sal_ProductiveEntity> ListProductive = new List<Sal_ProductiveEntity>();
                List<Sal_ProductCapacityEntity> ListProductCapacity = new List<Sal_ProductCapacityEntity>();
                List<Sal_ProductSalaryEntity> ListProductSalary = new List<Sal_ProductSalaryEntity>();

                #region GetData
                string status = string.Empty;
                List<object> listModel = new List<object>();

                listModel = new List<object>();
                listModel.AddRange(new object[6]);
                listModel[4] = 1;
                listModel[5] = Int32.MaxValue - 1;
                ListProduct = GetData<Cat_ProductEntity>(listModel, ConstantSql.hrm_cat_sp_get_Product,userLoginName, ref status);

                listModel = new List<object>();
                listModel.AddRange(new object[3]);
                listModel[1] = 1;
                listModel[2] = Int32.MaxValue - 1;
                ListProductItem = GetData<Cat_ProductItemEntity>(listModel, ConstantSql.hrm_cat_sp_get_ProductItem,userLoginName, ref status);

                listModel = new List<object>();
                listModel.AddRange(new object[17]);
                listModel[2] = OrgStructure;
                listModel[15] = 1;
                listModel[16] = Int32.MaxValue - 1;
                ListProfile = GetData<Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_ProfileAll,userLoginName, ref status);

                listModel = new List<object>();
                listModel.AddRange(new object[6]);
                listModel[2] = MonthStart;
                listModel[3] = MonthEnd;
                listModel[4] = 1;
                listModel[5] = Int32.MaxValue - 1;
                ListProductive = GetData<Sal_ProductiveEntity>(listModel, ConstantSql.hrm_sal_sp_get_Sal_Producttive, userLoginName,ref status);

                listModel = new List<object>();
                listModel.AddRange(new object[7]);
                listModel[3] = MonthStart;
                listModel[4] = MonthEnd;
                listModel[5] = 1;
                listModel[6] = Int32.MaxValue - 1;
                ListProductCapacity = GetData<Sal_ProductCapacityEntity>(listModel, ConstantSql.hrm_sal_sp_get_ProductCapacity,userLoginName, ref status);

                listModel = new List<object>();
                listModel.AddRange(new object[7]);
                listModel[0] = OrgStructure;
                listModel[3] = MonthStart;
                listModel[4] = MonthEnd;
                listModel[5] = 1;
                listModel[6] = Int32.MaxValue - 1;
                ListProductSalary = GetData<Sal_ProductSalaryEntity>(listModel, ConstantSql.hrm_sal_sp_get_Sal_ProductSalary,userLoginName, ref status);
                #endregion

                #region Delete dữ liệu củ
                //lọc ra theo nhân viên
                List<Sal_ProductSalary> listProductSalaryByProfile = ListProductSalary.Where(m => m.ProfileID != null && ListProfile.Any(t => t.ID == m.ProfileID)).ToList().Translate<Sal_ProductSalary>();
                //bật cờ isdelete
                repoSal_ProductSalary.Delete(listProductSalaryByProfile);

                #endregion

                #region Progress
                
                //lọc Productive && ProductCapacity theo product || productitem
                ListProductive = ListProductive.Where(m => (ProductID != null && m.ProductID == ProductID) || (ProductItemID != null && m.ProductItemID == ProductItemID)).ToList();
                ListProductCapacity = ListProductCapacity.Where(m => (ProductID != null && m.ProductID == ProductID) || (ProductItemID != null && m.ProductItemID == ProductItemID)).ToList();

                //duyệt qua profile
                foreach (var profile in ListProductive)
                {
                    #region các biến lưu dữ liệu tính đc
                    //tính sản phẩm thừa của nhân viên trong tháng trước
                    double TotalQuantityProductPrevious = 0;
                    //tổng sản lượng nhân viên làm đc, chưa cộng sản phẩm thừa vào
                    double TotalQuantityProduct = 0;
                    //Tổng sản lượng dùng để tính lương
                    double TotalQuantitySalary = 0;
                    //sản phẩm thừa trong tháng tính lương
                    double TotalQuantitySalaryPrevious = 0;
                    //tổng sản phẩm của tất cả nhân viên làm trong tháng
                    double TotalQuantityTotalProfile = 0;
                    //tổng tiền của sản phẩm
                    double TotalAmountByProduct = 0;
                    //lưu lại ID của loại tiền tệ
                    Guid? CurrencyID = null; 
                    #endregion

                    //các sản phẩm mà nhân viên làm đc trong tháng
                    List<Sal_ProductiveEntity> ListProductiveByProfile = new List<Sal_ProductiveEntity>();
                    if (profile.ProductItemID != null)
                    {
                        ListProductiveByProfile = ListProductive.Where(m => m.ProfileID != null && m.ProfileID == profile.ID && m.ProductItemID != null && m.ProductItemID == profile.ProductItemID).ToList();
                        TotalQuantityTotalProfile = ListProductive.Where(m => m.ProductItemID != null && m.ProductItemID == profile.ProductItemID).Sum(m => m.Quantity != null ? (double)m.Quantity : 0);
                    }
                    else if (profile.ProductID != null)
                    {
                        ListProductiveByProfile = ListProductive.Where(m => m.ProfileID != null && m.ProfileID == profile.ID && m.ProductID != null && m.ProductID == profile.ProductID).ToList();
                        TotalQuantityTotalProfile = ListProductive.Where(m => m.ProductID != null && m.ProductID == profile.ProductID).Sum(m => m.Quantity != null ? (double)m.Quantity : 0);
                    }

                    //tổng sản lượng nhân viên làm đc, chưa cộng sản phẩm thừa vào
                    TotalQuantityProduct = ListProductiveByProfile.Sum(m => m.Quantity != null ? (double)m.Quantity : 0);

                    //tính sản phẩm thừa của nhân viên trong tháng trước
                    TotalQuantityProductPrevious = 0;
                    DateTime dateStart = new DateTime(MonthStart.Year, MonthStart.Month, MonthStart.Day);
                    //lấy ra lương sản phẩm của tháng trước để lấy sản phẩm thừa
                    var ListProductSalaryPrevious = ListProductSalary.Where(m => m.ProfileID != null && m.ProfileID == profile.ID && m.MonthYear != null && m.MonthYear < dateStart).OrderByDescending(m => m.MonthYear).ToList();
                    if (profile.ProductItemID != null)
                    {
                        ListProductSalaryPrevious = ListProductSalaryPrevious.Where(m => m.ProductID == profile.ProductID).ToList();
                    }
                    else if (profile.ProductID != null)
                    {
                        ListProductSalaryPrevious = ListProductSalaryPrevious.Where(m => m.ProductItemID == profile.ProductItemID).ToList();
                    }
                    TotalQuantityProductPrevious = ListProductSalaryPrevious.Sum(m => m.QtyNext != null ? (double)m.QtyNext : 0);
                    //sum tổng sản phẩm và sản phẩm thừa tháng trước lại
                    TotalQuantityProduct += TotalQuantityProductPrevious;

                    //lấy định mức sản phẩm
                    var ProductCapacity = ListProductCapacity.Where(m => m.DepartmentID == profile.OrgStructureID).FirstOrDefault();

                    //kiểm tra định mức phải khác null
                    if (ProductCapacity!=null && ProductCapacity.MaxCapacity != null)
                    {
                        //tổng sản lượng nhỏ hơn định mức
                        if (ProductCapacity.MaxCapacity >= TotalQuantityProduct)
                        {
                            TotalQuantitySalary = TotalQuantityProduct;
                            TotalQuantitySalaryPrevious = 0;
                        }
                        else// tổng sản lượng lớn hơn định mức
                        {
                            TotalQuantitySalary = TotalQuantityProduct / TotalQuantityTotalProfile * (double)ProductCapacity.MaxCapacity;
                            TotalQuantitySalaryPrevious = TotalQuantityProduct - TotalQuantitySalary;
                        }
                    }

                    //lấy giá tiền của sản phẩm
                    if (profile.ProductItemID != null)
                    {
                        var ProductByID=ListProductItem.Where(m => m.ID == (Guid)profile.ProductItemID).FirstOrDefault();
                        //cập nhật tiền tệ
                        CurrencyID = ProductByID != null ? ProductByID.CurrencyID : null;
                        //cập nhật tổng tiền
                        TotalAmountByProduct = TotalQuantitySalary * (ProductByID != null && ProductByID.UnitPrice != null ? (double)ProductByID.UnitPrice : 0);
                    }
                    else if (profile.ProductID != null)
                    {
                        var ProductByID = ListProduct.Where(m => m.ID == (Guid)profile.ProductID).FirstOrDefault();
                        //cập nhật tiền tệ
                        CurrencyID = ProductByID != null ? ProductByID.CurrencyID : null;
                        //câp nhật tổng tiền
                        TotalAmountByProduct = TotalQuantitySalary * (ProductByID != null && ProductByID.BonusPerUnit != null ? (double)ProductByID.BonusPerUnit : 0);
                    }
          
                    //lưu dữ liệu vào bảng sal_productsalary
                    Sal_ProductSalary ProductSalary = new Sal_ProductSalary();
                    ProductSalary.ID = Guid.NewGuid();
                    ProductSalary.ProfileID = profile.ProfileID;
                    ProductSalary.ProductID = profile.ProductID;
                    ProductSalary.ProductItemID = profile.ProductItemID;
                    ProductSalary.MonthYear = new DateTime(MonthStart.Year, MonthStart.Month, MonthStart.Day);
                    ProductSalary.QtyActual = TotalQuantityProduct;
                    ProductSalary.QtyNext = TotalQuantitySalaryPrevious;
                    ProductSalary.QtyPrevious = TotalQuantityProductPrevious;
                    ProductSalary.QtySalary = TotalQuantitySalary;
                    ProductSalary.Amount = TotalAmountByProduct;
                    ProductSalary.CurrencyID = CurrencyID;
                    repoSal_ProductSalary.Add(ProductSalary);
                }

                unitOfWork.SaveChanges();
                #endregion
            }
        }
Ejemplo n.º 39
0
        public Guid ComputePayroll(List<Hre_ProfileEntity> listProfile, Att_CutOffDurationEntity CutOffDuration, string HeaderTemplateLog, string UserLogin, bool Settlement = false)
        {
            Sys_AsynTask asynTask = new Sys_AsynTask()
            {
                ID = Guid.NewGuid(),
                Summary = "Tính Lương Cho Tháng " + CutOffDuration.CutOffDurationName,
                Type = AsynTask.Payroll_Computing.ToString(),
                Status = AsynTaskStatus.Doing.ToString(),
                TimeStart = DateTime.Now,
                PercentComplete = 0.01,
            };

            Task.Run(() =>
            {
                using (var context = new VnrHrmDataContext())
                {
                    var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                    var repoSys_AsynTask = new CustomBaseRepository<Sys_AsynTask>(unitOfWork);

                    if (listProfile.Count == 0)
                    {
                        asynTask.TimeEnd = DateTime.Now;
                        asynTask.Description = "Không tồn tại nhân viên nào !";
                        asynTask.PercentComplete = 1D;
                    }

                    repoSys_AsynTask.Add(asynTask);
                    unitOfWork.SaveChanges();
                }

                if (listProfile.Count > 0)
                {
                    ComputePayroll(listProfile, CutOffDuration,
                        asynTask.ID, HeaderTemplateLog, UserLogin, Settlement);
                }
            });

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

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

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

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

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

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

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

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

                List<Att_TimeOffInLieu> lstTimeoffInlieu = new List<Att_TimeOffInLieu>();
                foreach (var item in lstLeaveDayInsert)
                {
                    if (item.Status == LeaveDayStatus.E_APPROVED.ToString())
                    {
                        Att_TimeOffInLieu timeOffLieu = AddTimeOffInLieu(item);
                        if (timeOffLieu != null)
                            lstTimeoffInlieu.Add(timeOffLieu);
                    }
                }
                if (lstTimeoffInlieu.Count > 0)
                {
                    repoAtt_TimeOffInLieu.Add(lstTimeoffInlieu);
                    //EntityService.AddEntity<Att_TimeOffInLieu>(GuidContext, lstTimeoffInlieu.ToArray());
                }
                return string.Empty;
            }
        }
Ejemplo n.º 41
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);
            }
        }
Ejemplo n.º 42
0
        /// <summary>
        /// [Hien.Nguyen] - Chức năng không tính tăng ca - màng hình Phân Tích Tăng Ca
        /// </summary>
        /// <param name="lstOvertimeEntity"></param>
        public void CalNonAllowOvertime(List<Att_OvertimeEntity> lstOvertime, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_workday = new CustomBaseRepository<Att_Workday>(unitOfWork);
                var repoAtt_NoneOvertime = new CustomBaseRepository<Att_NonOverTime>(unitOfWork);
                if (lstOvertime.Count == 0 || lstOvertime.Where(m => m.WorkDateRoot != null).Count() == 0)
                {
                    return;
                }
                DateTime minDate = lstOvertime.Min(m => m.WorkDateRoot.Value);
                DateTime maxDate = lstOvertime.Max(m => m.WorkDateRoot.Value);
                List<Guid> lstProfileID = lstOvertime.Select(m => m.ProfileID).Distinct().ToList();
                string E_REJECTED = OverTimeStatus.E_REJECTED.ToString();
                // List<ProfileDateTime> lstWorkdayNotOT = new List<ProfileDateTime>();

                List<Guid> lstOvertimeIDChange = new List<Guid>();

                foreach (var item in lstOvertime)
                {

                    if (item.WorkDateRoot == null)
                        continue;
                    if (item.IsNonOvertime == true)
                        continue;
                    if (string.IsNullOrEmpty(item.udOvertimeStatus))
                    {
                        //ProfileDateTime workdayNotOt = new ProfileDateTime();
                        //workdayNotOt.ProfileID = item.ProfileID;
                        //workdayNotOt.WorkDate = item.WorkDateRoot.Value;
                        //workdayNotOt.OvertimeID = item.ID;
                        //lstWorkdayNotOT.Add(workdayNotOt);
                        lstOvertimeIDChange.Add(item.ID);
                    }
                }


                List<Att_OvertimeEntity> lstOvertimeInCache = lstOvertime;
                List<Att_OvertimeEntity> lstOvertimeInCache_Profile = lstOvertimeInCache.Where(m => lstOvertimeIDChange.Contains(m.ID)).ToList();

                List<Att_OvertimeEntity> lstOvertimeNonBe_Insert = new List<Att_OvertimeEntity>();
                foreach (var item in lstOvertimeInCache_Profile)
                {
                    //if (lstWorkdayNotOT.Any(m => m.ProfileID == item.ProfileID && m.WorkDate == item.WorkDateRoot))
                    //{
                    item.IsNonOvertime = true;
                    lstOvertimeNonBe_Insert.Add(item);
                    // }
                }
                lstOvertimeInCache.RemoveRange(lstOvertimeInCache_Profile);

                //Để tính lại lũy kế sau khi xong
                OvertimePermitEntity overtimePermit = getOvertimePermit(userLogin);
                List<WorkdayCustom> lstWorkday = new List<WorkdayCustom>();
                if (lstProfileID.Count < 2000)
                {
                    lstWorkday = repoAtt_workday
                        .FindBy(m => m.IsDelete == null && m.WorkDate >= minDate && m.WorkDate <= maxDate && lstProfileID.Contains(m.ProfileID))
                        .Select(m => new WorkdayCustom() { ID = m.ID, ProfileID = m.ProfileID, ShiftID = m.ShiftID, ShiftApprove = m.ShiftApprove, WorkDate = m.WorkDate, Status = m.Status, InTime1 = m.InTime1, InTime2 = m.InTime2, OutTime1 = m.OutTime1, OutTime2 = m.OutTime2 })
                        .ToList<WorkdayCustom>();
                }
                else
                {
                    lstWorkday = repoAtt_workday
                        .FindBy(m => m.IsDelete == null && m.WorkDate >= minDate && m.WorkDate <= maxDate)
                        .Select(m => new WorkdayCustom() { ID = m.ID, ProfileID = m.ProfileID, ShiftID = m.ShiftID, ShiftApprove = m.ShiftApprove, WorkDate = m.WorkDate, Status = m.Status, InTime1 = m.InTime1, InTime2 = m.InTime2, OutTime1 = m.OutTime1, OutTime2 = m.OutTime2 })
                        .ToList<WorkdayCustom>();
                }
                FillterAllowOvertime(context, lstOvertimeInCache_Profile, overtimePermit, lstWorkday);
                lstOvertimeInCache.AddRange(lstOvertimeInCache_Profile);
                lstOvertimeInCache = lstOvertimeInCache.OrderBy(m => m.WorkDate.Date).ThenBy(m => m.ProfileID).ToList();
                lstOvertimeCache = lstOvertimeInCache;

                List<Att_NonOverTime> LstNonOTInsert = new List<Att_NonOverTime>();
                foreach (var item in lstOvertimeNonBe_Insert)
                {
                    Att_NonOverTime nonOT = new Att_NonOverTime();
                    nonOT.ID = Guid.NewGuid();
                    nonOT.ProfileID = item.ProfileID;
                    nonOT.WorkDay = item.WorkDateRoot.Value;
                    nonOT.OvertimeTypeID = item.OvertimeTypeID;
                    nonOT.Type = item.udTypeBeginOTWithShift;
                    LstNonOTInsert.Add(nonOT);
                    repoAtt_NoneOvertime.Add(nonOT);
                }
                unitOfWork.SaveChanges();
            }
            //BindToGrid(lstOvertimeCache);
        }
Ejemplo n.º 43
0
        internal string GetString(object entityBase, Sys_CodeObject codeObject, DateTime date)
        {
            //var repoUser = new CustomBaseRepository<Sys_UserInfo>(unitOfWork);
            var repoObjDate = new CustomBaseRepository<Sys_CodeObjectByUserNDate>(unitOfWork);

            switch (functionType)
            {
                case FunctionTypes.DATE:
                    return date.ToString(strText);
                case FunctionTypes.OBJECT:
                    string resultObject = string.Empty;
                    if (entityBase != null)
                    {
                        object objectFieldValue = null;
                        object entityObject = null;

                        if (ListObjectTableNames != null && ListObjectTableNames.Count() > 0)
                        {
                            foreach (string resetName in ListObjectTableNames)
                            {
                                if (entityBase.HasProperty(resetName) && entityBase.HasProperty("ID"))
                                {
                                    unitOfWork.Context.Entry(entityBase).Reference(resetName).Load();
                                }

                                entityObject = entityBase.GetPropertyValue(resetName);
                                var entityID = entityObject.GetPropertyValue("ID");
                                if (entityObject != null && entityID.ToString() != Guid.Empty.ToString())
                                {
                                    objectFieldValue = entityObject.GetPropertyValue(objectFieldName);
                                }
                            }
                        }
                        else
                        {
                            objectFieldValue = entityBase.GetPropertyValue(objectFieldName);
                        }

                        if (objectFieldValue != null)
                        {
                            resultObject = GetNumberCharater(objectFieldValue.ToString());
                        }
                    }
                    return resultObject;
                case FunctionTypes.ORDINAL:
                    Sys_CodeObjectByUserNDate codeObjectByUserNDate = null;
                    if (isResetByUser || isResetByObject)
                    {
                        object objectFieldValue = null;
                        object objectFieldValue1 = null;

                        if (entityBase != null && isResetByObject)
                        {
                            if (ListResetObjectNames != null && ListResetObjectNames.Count() > 0)
                            {
                                object entityObject = null;

                                foreach (string resetName in ListResetObjectNames)
                                {
                                    if (entityBase.HasProperty(resetName) && entityBase.HasProperty("ID"))
                                    {
                                        unitOfWork.Context.Entry(entityBase).Reference(resetName).Load();
                                    }
                                    entityObject = entityBase.GetPropertyValue(resetName);
                                    var entityID = entityObject.GetPropertyValue("ID");

                                    if (entityObject != null && entityID.ToString() != Guid.Empty.ToString())
                                    {
                                        objectFieldValue = entityObject.GetPropertyValue(ResetFieldName);
                                    }
                                }
                            }
                            else if (!string.IsNullOrWhiteSpace(ResetFieldName))
                            {
                                objectFieldValue = entityBase.GetPropertyValue(ResetFieldName);
                            }

                            if (ListResetObjectNames1 != null && ListResetObjectNames1.Count() > 0)
                            {
                                object entityObject = null;

                                foreach (string resetName in ListResetObjectNames1)
                                {
                                    entityObject = entityBase.GetPropertyValue(resetName);
                                    var entityID = entityObject.GetPropertyValue("ID");
                                    if (entityObject != null && entityID.ToString() != Guid.Empty.ToString())
                                    {
                                        objectFieldValue1 = entityObject.GetPropertyValue(ResetFieldName1);
                                    }
                                }
                            }
                            else if (!string.IsNullOrWhiteSpace(ResetFieldName1))
                            {
                                objectFieldValue1 = entityBase.GetPropertyValue(ResetFieldName1);
                            }
                        }

                        //ID đối tượng reset theo người dùng hoặc theo đối tượng bất kì
                        objectFieldValue = objectFieldValue != null ? objectFieldValue : string.Empty;
                        objectFieldValue1 = objectFieldValue1 != null ? objectFieldValue1 : string.Empty;

                        string resetObjectID = objectFieldValue.ToString();
                        string resetObjectID1 = objectFieldValue1.ToString();

                        if (isResetByUser)
                        {
                            resetObjectID = _userLoginID.ToString();
                            resetObjectID1 = string.Empty;
                        }

                        if ((string.IsNullOrEmpty(resetObjectID.Trim()) || resetObjectID == Guid.Empty.ToString())
                            && (string.IsNullOrEmpty(resetObjectID1.Trim()) || resetObjectID1 == Guid.Empty.ToString()))
                        {
                            return string.Empty;
                        }

                        if (IsResetByTime)
                        {
                            codeObjectByUserNDate = repoObjDate.FindBy(cobund => cobund.CodeObjectID == _codeObjectID && cobund.ResetObjectID == resetObjectID &&
                                ((cobund.ResetObjectID1 == null && resetObjectID1 == "") || cobund.ResetObjectID1 == resetObjectID1)
                                    && cobund.Date != null).ToList().Where(cobund => cobund.Date.Value.ToString(TimeFormat) == date.ToString(TimeFormat)).FirstOrDefault();
                        }
                        else
                        {
                            codeObjectByUserNDate = repoObjDate.FindBy(cobund => cobund.CodeObjectID == _codeObjectID && cobund.ResetObjectID == resetObjectID
                               && ((cobund.ResetObjectID1 == null && resetObjectID1 == "") || cobund.ResetObjectID1 == resetObjectID1)).FirstOrDefault();
                        }

                        if (codeObjectByUserNDate == null)
                        {
                            codeObjectByUserNDate = new Sys_CodeObjectByUserNDate();
                            codeObjectByUserNDate.ID = Guid.NewGuid();
                            codeObjectByUserNDate.CodeObjectID = _codeObjectID;
                            codeObjectByUserNDate.ResetObjectID = resetObjectID;
                            codeObjectByUserNDate.ResetObjectID1 = resetObjectID1;
                            codeObjectByUserNDate.Ordinal = 1;

                            if (IsResetByTime)
                            {
                                codeObjectByUserNDate.Date = date;
                            }
                            repoObjDate.Add(codeObjectByUserNDate);
                        }
                    }
                    else if (IsResetByTime)
                    {
                        codeObjectByUserNDate = repoObjDate.FindBy(cobund => cobund.CodeObjectID == _codeObjectID && cobund.Date != null).ToList().Where(cobund =>
                            cobund.Date.Value.ToString(TimeFormat) == date.ToString(TimeFormat)).FirstOrDefault();

                        if (codeObjectByUserNDate == null)
                        {
                            codeObjectByUserNDate = new Sys_CodeObjectByUserNDate();
                            codeObjectByUserNDate.ID = Guid.NewGuid();
                            codeObjectByUserNDate.CodeObjectID = _codeObjectID;
                            codeObjectByUserNDate.Ordinal = 1;
                            codeObjectByUserNDate.Date = date;
                            repoObjDate.Add(codeObjectByUserNDate);
                        }
                    }

                    string result = string.Empty;
                    if (codeObjectByUserNDate != null)
                    {
                        int ordinal = codeObjectByUserNDate.Ordinal.GetInteger();
                        result = GetNumberCharater(ordinal.ToString());
                        codeObjectByUserNDate.Ordinal += 1;
                    }
                    else
                    {
                        int ordinal = _codeObject.Ordinal.GetInteger();
                        result = GetNumberCharater(ordinal.ToString());
                    }
                    return result;

                case FunctionTypes.TEXT:
                default:
                    return strText;
            }
        }
Ejemplo n.º 44
0
        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;
            }
        }
Ejemplo n.º 45
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);
        }
Ejemplo n.º 46
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();
            }
        }
Ejemplo n.º 47
0
        public void ComputeProductSalary(string OrgStructure, Guid?ProductID, Guid?ProductItemID, DateTime MonthStart, DateTime MonthEnd, string userLoginName)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork             = (IUnitOfWork) new UnitOfWork(context);
                var repoSal_ProductSalary  = new CustomBaseRepository <Sal_ProductSalary>(unitOfWork);
                var repoSal_ProductSalary1 = new CustomBaseRepository <Hre_Profile>(unitOfWork);

                List <Cat_ProductEntity>         ListProduct         = new List <Cat_ProductEntity>();
                List <Cat_ProductItemEntity>     ListProductItem     = new List <Cat_ProductItemEntity>();
                List <Hre_ProfileEntity>         ListProfile         = new List <Hre_ProfileEntity>();
                List <Sal_ProductiveEntity>      ListProductive      = new List <Sal_ProductiveEntity>();
                List <Sal_ProductCapacityEntity> ListProductCapacity = new List <Sal_ProductCapacityEntity>();
                List <Sal_ProductSalaryEntity>   ListProductSalary   = new List <Sal_ProductSalaryEntity>();

                #region GetData
                string        status    = string.Empty;
                List <object> listModel = new List <object>();

                listModel = new List <object>();
                listModel.AddRange(new object[6]);
                listModel[4] = 1;
                listModel[5] = Int32.MaxValue - 1;
                ListProduct  = GetData <Cat_ProductEntity>(listModel, ConstantSql.hrm_cat_sp_get_Product, userLoginName, ref status);

                listModel = new List <object>();
                listModel.AddRange(new object[3]);
                listModel[1]    = 1;
                listModel[2]    = Int32.MaxValue - 1;
                ListProductItem = GetData <Cat_ProductItemEntity>(listModel, ConstantSql.hrm_cat_sp_get_ProductItem, userLoginName, ref status);

                listModel = new List <object>();
                listModel.AddRange(new object[17]);
                listModel[2]  = OrgStructure;
                listModel[15] = 1;
                listModel[16] = Int32.MaxValue - 1;
                ListProfile   = GetData <Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_ProfileAll, userLoginName, ref status);

                listModel = new List <object>();
                listModel.AddRange(new object[6]);
                listModel[2]   = MonthStart;
                listModel[3]   = MonthEnd;
                listModel[4]   = 1;
                listModel[5]   = Int32.MaxValue - 1;
                ListProductive = GetData <Sal_ProductiveEntity>(listModel, ConstantSql.hrm_sal_sp_get_Sal_Producttive, userLoginName, ref status);

                listModel = new List <object>();
                listModel.AddRange(new object[7]);
                listModel[3]        = MonthStart;
                listModel[4]        = MonthEnd;
                listModel[5]        = 1;
                listModel[6]        = Int32.MaxValue - 1;
                ListProductCapacity = GetData <Sal_ProductCapacityEntity>(listModel, ConstantSql.hrm_sal_sp_get_ProductCapacity, userLoginName, ref status);

                listModel = new List <object>();
                listModel.AddRange(new object[7]);
                listModel[0]      = OrgStructure;
                listModel[3]      = MonthStart;
                listModel[4]      = MonthEnd;
                listModel[5]      = 1;
                listModel[6]      = Int32.MaxValue - 1;
                ListProductSalary = GetData <Sal_ProductSalaryEntity>(listModel, ConstantSql.hrm_sal_sp_get_Sal_ProductSalary, userLoginName, ref status);
                #endregion

                #region Delete dữ liệu củ
                //lọc ra theo nhân viên
                List <Sal_ProductSalary> listProductSalaryByProfile = ListProductSalary.Where(m => m.ProfileID != null && ListProfile.Any(t => t.ID == m.ProfileID)).ToList().Translate <Sal_ProductSalary>();
                //bật cờ isdelete
                repoSal_ProductSalary.Delete(listProductSalaryByProfile);

                #endregion

                #region Progress

                //lọc Productive && ProductCapacity theo product || productitem
                ListProductive      = ListProductive.Where(m => (ProductID != null && m.ProductID == ProductID) || (ProductItemID != null && m.ProductItemID == ProductItemID)).ToList();
                ListProductCapacity = ListProductCapacity.Where(m => (ProductID != null && m.ProductID == ProductID) || (ProductItemID != null && m.ProductItemID == ProductItemID)).ToList();

                //duyệt qua profile
                foreach (var profile in ListProductive)
                {
                    #region các biến lưu dữ liệu tính đc
                    //tính sản phẩm thừa của nhân viên trong tháng trước
                    double TotalQuantityProductPrevious = 0;
                    //tổng sản lượng nhân viên làm đc, chưa cộng sản phẩm thừa vào
                    double TotalQuantityProduct = 0;
                    //Tổng sản lượng dùng để tính lương
                    double TotalQuantitySalary = 0;
                    //sản phẩm thừa trong tháng tính lương
                    double TotalQuantitySalaryPrevious = 0;
                    //tổng sản phẩm của tất cả nhân viên làm trong tháng
                    double TotalQuantityTotalProfile = 0;
                    //tổng tiền của sản phẩm
                    double TotalAmountByProduct = 0;
                    //lưu lại ID của loại tiền tệ
                    Guid?CurrencyID = null;
                    #endregion

                    //các sản phẩm mà nhân viên làm đc trong tháng
                    List <Sal_ProductiveEntity> ListProductiveByProfile = new List <Sal_ProductiveEntity>();
                    if (profile.ProductItemID != null)
                    {
                        ListProductiveByProfile   = ListProductive.Where(m => m.ProfileID != null && m.ProfileID == profile.ID && m.ProductItemID != null && m.ProductItemID == profile.ProductItemID).ToList();
                        TotalQuantityTotalProfile = ListProductive.Where(m => m.ProductItemID != null && m.ProductItemID == profile.ProductItemID).Sum(m => m.Quantity != null ? (double)m.Quantity : 0);
                    }
                    else if (profile.ProductID != null)
                    {
                        ListProductiveByProfile   = ListProductive.Where(m => m.ProfileID != null && m.ProfileID == profile.ID && m.ProductID != null && m.ProductID == profile.ProductID).ToList();
                        TotalQuantityTotalProfile = ListProductive.Where(m => m.ProductID != null && m.ProductID == profile.ProductID).Sum(m => m.Quantity != null ? (double)m.Quantity : 0);
                    }

                    //tổng sản lượng nhân viên làm đc, chưa cộng sản phẩm thừa vào
                    TotalQuantityProduct = ListProductiveByProfile.Sum(m => m.Quantity != null ? (double)m.Quantity : 0);

                    //tính sản phẩm thừa của nhân viên trong tháng trước
                    TotalQuantityProductPrevious = 0;
                    DateTime dateStart = new DateTime(MonthStart.Year, MonthStart.Month, MonthStart.Day);
                    //lấy ra lương sản phẩm của tháng trước để lấy sản phẩm thừa
                    var ListProductSalaryPrevious = ListProductSalary.Where(m => m.ProfileID != null && m.ProfileID == profile.ID && m.MonthYear != null && m.MonthYear < dateStart).OrderByDescending(m => m.MonthYear).ToList();
                    if (profile.ProductItemID != null)
                    {
                        ListProductSalaryPrevious = ListProductSalaryPrevious.Where(m => m.ProductID == profile.ProductID).ToList();
                    }
                    else if (profile.ProductID != null)
                    {
                        ListProductSalaryPrevious = ListProductSalaryPrevious.Where(m => m.ProductItemID == profile.ProductItemID).ToList();
                    }
                    TotalQuantityProductPrevious = ListProductSalaryPrevious.Sum(m => m.QtyNext != null ? (double)m.QtyNext : 0);
                    //sum tổng sản phẩm và sản phẩm thừa tháng trước lại
                    TotalQuantityProduct += TotalQuantityProductPrevious;

                    //lấy định mức sản phẩm
                    var ProductCapacity = ListProductCapacity.Where(m => m.DepartmentID == profile.OrgStructureID).FirstOrDefault();

                    //kiểm tra định mức phải khác null
                    if (ProductCapacity != null && ProductCapacity.MaxCapacity != null)
                    {
                        //tổng sản lượng nhỏ hơn định mức
                        if (ProductCapacity.MaxCapacity >= TotalQuantityProduct)
                        {
                            TotalQuantitySalary         = TotalQuantityProduct;
                            TotalQuantitySalaryPrevious = 0;
                        }
                        else// tổng sản lượng lớn hơn định mức
                        {
                            TotalQuantitySalary         = TotalQuantityProduct / TotalQuantityTotalProfile * (double)ProductCapacity.MaxCapacity;
                            TotalQuantitySalaryPrevious = TotalQuantityProduct - TotalQuantitySalary;
                        }
                    }

                    //lấy giá tiền của sản phẩm
                    if (profile.ProductItemID != null)
                    {
                        var ProductByID = ListProductItem.Where(m => m.ID == (Guid)profile.ProductItemID).FirstOrDefault();
                        //cập nhật tiền tệ
                        CurrencyID = ProductByID != null ? ProductByID.CurrencyID : null;
                        //cập nhật tổng tiền
                        TotalAmountByProduct = TotalQuantitySalary * (ProductByID != null && ProductByID.UnitPrice != null ? (double)ProductByID.UnitPrice : 0);
                    }
                    else if (profile.ProductID != null)
                    {
                        var ProductByID = ListProduct.Where(m => m.ID == (Guid)profile.ProductID).FirstOrDefault();
                        //cập nhật tiền tệ
                        CurrencyID = ProductByID != null ? ProductByID.CurrencyID : null;
                        //câp nhật tổng tiền
                        TotalAmountByProduct = TotalQuantitySalary * (ProductByID != null && ProductByID.BonusPerUnit != null ? (double)ProductByID.BonusPerUnit : 0);
                    }

                    //lưu dữ liệu vào bảng sal_productsalary
                    Sal_ProductSalary ProductSalary = new Sal_ProductSalary();
                    ProductSalary.ID            = Guid.NewGuid();
                    ProductSalary.ProfileID     = profile.ProfileID;
                    ProductSalary.ProductID     = profile.ProductID;
                    ProductSalary.ProductItemID = profile.ProductItemID;
                    ProductSalary.MonthYear     = new DateTime(MonthStart.Year, MonthStart.Month, MonthStart.Day);
                    ProductSalary.QtyActual     = TotalQuantityProduct;
                    ProductSalary.QtyNext       = TotalQuantitySalaryPrevious;
                    ProductSalary.QtyPrevious   = TotalQuantityProductPrevious;
                    ProductSalary.QtySalary     = TotalQuantitySalary;
                    ProductSalary.Amount        = TotalAmountByProduct;
                    ProductSalary.CurrencyID    = CurrencyID;
                    repoSal_ProductSalary.Add(ProductSalary);
                }

                unitOfWork.SaveChanges();
                #endregion
            }
        }
Ejemplo n.º 48
0
        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");
            }
        }
Ejemplo n.º 49
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();
            }
        }
Ejemplo n.º 50
0
        public int[] ApprevedKaiZenData(List<Guid> selectedIds, DateTime MonthYear, Guid UnusualEDTypeID, Guid Currency)
        {
            using (var context = new VnrHrmDataContext())
            {
                string status = string.Empty;
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoKai_KaizenData = new CustomBaseRepository<Kai_KaizenData>(unitOfWork);
                var repoSal_UnusualAllowance = new CustomBaseRepository<Sal_UnusualAllowance>(unitOfWork);
                List<Sal_UnusualAllowance> listUnusualAllowance = new List<Sal_UnusualAllowance>();

                //lọc ra các kaizen được chọn
                List<Kai_KaizenData> listKaiZendata = repoKai_KaizenData.FindBy(m => m.IsDelete != true).ToList();
                listKaiZendata = listKaiZendata.Where(m => m.Status == EnumDropDown.Kai_KaizenDataStatus.E_APPROVED.ToString() && selectedIds.Any(t => t == m.ID)).ToList();

                int Pass = 0;
                int Fail = 0;

                Sal_UnusualAllowance item = new Sal_UnusualAllowance();
                foreach (var KaiZenItem in listKaiZendata)
                {
                    if (KaiZenItem.DateTransferPayment == null && (KaiZenItem.IsPaymentOut == null || KaiZenItem.IsPaymentOut == false))
                    {
                        item = new Sal_UnusualAllowance();
                        item.ProfileID = KaiZenItem.ProfileID != null ? (Guid)KaiZenItem.ProfileID : Guid.NewGuid();
                        item.MonthStart = new DateTime(MonthYear.Year, MonthYear.Month, 1);
                        item.MonthEnd = new DateTime(MonthYear.Year, MonthYear.Month, 1).AddMonths(1).AddDays(-1);
                        item.Type = EnumDropDown.EDType.E_EARNING.ToString();
                        item.UnusualEDTypeID = UnusualEDTypeID;
                        item.CurrencyID = Currency;
                        item.Amount = KaiZenItem.SumAmount != null ? KaiZenItem.SumAmount : 0;
                        listUnusualAllowance.Add(item);

                        KaiZenItem.DateTransferPayment = MonthYear;
                        Pass++;
                    }
                    else
                    {
                        Fail++;
                    }
                }
                repoSal_UnusualAllowance.Add(listUnusualAllowance);
                unitOfWork.SaveChanges();
                return new int[] { Pass, Fail };
            }
        }
Ejemplo n.º 51
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();
            }
        }
Ejemplo n.º 52
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;
            }
        }
Ejemplo n.º 53
0
        public void ComputeBonusUnusualAllowance_Progress(Guid AsynTaskID, Sal_UnusualAllowanceEntity model, bool AllowanceEvaluationYear = false)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)new UnitOfWork(context);
                var repoSys_AsynTask = new CustomBaseRepository<Sys_AsynTask>(unitOfWork);
                var repoCat_Element = new CustomBaseRepository<Cat_Element>(unitOfWork);
                var repoCat_UnusualAllowanceCfg = new CustomBaseRepository<Cat_UnusualAllowanceCfg>(unitOfWork);
                var repoUnusualAllowance = new CustomBaseRepository<Sal_UnusualAllowance>(unitOfWork);

                Sys_AsynTask asynTask = repoSys_AsynTask.GetById(AsynTaskID);

                Sal_ComputePayrollServices CumputePayrollServices = new Sal_ComputePayrollServices();
                List<object> listModel = new List<object>();
                string status = string.Empty;
                Sal_ComputePayrollServices Services = new Sal_ComputePayrollServices();
                List<Sal_UnusualAllowanceEntity> ListResult = new List<Sal_UnusualAllowanceEntity>();
                List<ElementFormula> listElementFormula = new List<ElementFormula>();
                Sal_UnusualAllowanceServices UnusualAllowanceServices = new Sal_UnusualAllowanceServices();

                Att_CutOffDurationEntity CutOffDuration = new Att_CutOffDurationEntity();
                if (model.MonthEnd != null)
                {
                    CutOffDuration.MonthYear = model.MonthStart.Value;
                    CutOffDuration.DateStart = model.MonthStart.Value;
                    CutOffDuration.DateEnd = model.MonthEnd.Value;
                }
                else
                {
                    CutOffDuration.MonthYear = new DateTime(model.MonthStart.Value.Year, model.MonthStart.Value.Month, 1);
                    CutOffDuration.DateStart = new DateTime(model.MonthStart.Value.Year, model.MonthStart.Value.Month, 1);
                    CutOffDuration.DateEnd = new DateTime(model.MonthStart.Value.Year, model.MonthStart.Value.Month, 1).AddMonths(1).AddDays(-1);
                }

                List<Hre_ProfileEntity> ListProfile = new List<Hre_ProfileEntity>();

                if (model.OrgStructureIDs != null && model.OrgStructureIDs != string.Empty)
                {
                    listModel = new List<object>();
                    listModel.AddRange(new object[18]);
                    listModel[2] = model.OrgStructureIDs;
                    listModel[16] = 1;
                    listModel[17] = Int32.MaxValue - 1;
                    ListProfile = GetData<Hre_ProfileEntity>(listModel, ConstantSql.hrm_hr_sp_get_Profile, ref status);
                    if (model.ExProfileIDs != null)
                    {
                        string[] ExProfile = model.ExProfileIDs.Split(',');
                        ListProfile = ListProfile.Where(m => ExProfile.Contains(m.ID.ToString())).ToList();
                    }
                }
                else if (model.ProfileIDs != null && model.ProfileIDs != string.Empty)
                {
                    ListProfile = GetData<Hre_ProfileEntity>(Common.DotNetToOracle(model.ProfileIDs), ConstantSql.hrm_hr_sp_get_ProfileByIds, ref status);
                }


                //lọc profile theo workplace
                if (model.WorkingPlaceID != null)
                {
                    string[] listWorkPlare = model.WorkingPlaceID.Split(',');
                    ListProfile = ListProfile.Where(m => listWorkPlare.Contains(m.WorkPlaceID.ToString())).ToList();
                }

                List<Cat_UnusualAllowanceCfg> listUnusualAllowanceCfg = new List<Cat_UnusualAllowanceCfg>();
                listUnusualAllowanceCfg = repoCat_UnusualAllowanceCfg.FindBy(m => m.IsDelete != true).ToList();

                #region Delete các phụ cấp trong năm đã có
                List<Sal_UnusualAllowance> listUnusualAllowance = repoUnusualAllowance.FindBy(m => m.IsDelete != true && m.MonthStart != null && model.MonthStart != null && m.MonthStart.Value.Year == model.MonthStart.Value.Year && m.Status != WorkHistoryStatus.E_APPROVED.ToString()).ToList();

                //nếu là tính phép năm sức khỏe tốt thì delete thêm loại GoodHealth
                if (AllowanceEvaluationYear)
                {
                    var _tmp = listUnusualAllowanceCfg.FirstOrDefault(m => m.Code == "GoodHealth");
                    listUnusualAllowance = listUnusualAllowance.Where(m => (m.UnusualEDTypeID == model.UnusualEDTypeID || m.UnusualEDTypeID == _tmp.ID) && ListProfile.Any(t => t.ID == m.ProfileID)).ToList();
                }
                else
                {
                    listUnusualAllowance = listUnusualAllowance.Where(m => m.UnusualEDTypeID == model.UnusualEDTypeID && ListProfile.Any(t => t.ID == m.ProfileID)).ToList();
                }
                //update isdelete is true
                listUnusualAllowance.ForEach(m => m.IsDelete = true);
                #endregion

                //Cat_ElementEntity ElementItem = repoCat_Element.GetById((Guid)model.Element).Copy<Cat_ElementEntity>();
                Cat_ElementEntity ElementItem = repoCat_Element.FindBy(m => m.ID == (Guid)model.Element).FirstOrDefault().Copy<Cat_ElementEntity>();


                ComputePayrollDataModel TotalData = Services.GetDataForComputeSalary(CutOffDuration);

                List<Cat_ElementEntity> listElementAll = new List<Cat_ElementEntity>();
                listElementAll = TotalData.listElement_All;

                #region Xử lý cho tính phép năm, sức khỏe tốt
                List<Cat_UnusualAllowanceCfg> ListUnusualAllowanceCfg = new List<Cat_UnusualAllowanceCfg>();
                Cat_UnusualAllowanceCfg PaidLeave = null;
                Cat_UnusualAllowanceCfg GoodHealth = null;
                ElementFormula FormulaValue = new ElementFormula();
                if (AllowanceEvaluationYear)
                {
                    ListUnusualAllowanceCfg = repoCat_UnusualAllowanceCfg.FindBy(m => m.IsDelete != true).ToList();
                    PaidLeave = ListUnusualAllowanceCfg.FirstOrDefault(m => m.Code == "PaidLeave");
                    GoodHealth = ListUnusualAllowanceCfg.FirstOrDefault(m => m.Code == "GoodHealth");
                }
                #endregion

                foreach (var profile in ListProfile)
                {
                    if (AllowanceEvaluationYear)
                    {
                        #region Tính Công Thức
                        try
                        {
                            listElementFormula = new List<ElementFormula>();
                            TotalData.listElement_All = repoCat_Element.FindBy(m => m.IsDelete != true).ToList().Translate<Cat_ElementEntity>();
                            listElementFormula = CumputePayrollServices.ParseFormula(ElementItem, listElementFormula, TotalData, profile, CutOffDuration, new Dictionary<Guid, ValueCount>());
                        }
                        catch
                        {
                            listElementFormula = null;
                            continue;
                        }
                        #endregion

                        if (PaidLeave != null)
                        {
                            //lưu phần tử TienBuPhepNam
                            Sal_UnusualAllowance UnusualAllowance = new Sal_UnusualAllowance();
                            UnusualAllowance.ID = Guid.NewGuid();
                            UnusualAllowance.ProfileID = profile.ID;
                            UnusualAllowance.UnusualEDTypeID = PaidLeave.ID;

                            UnusualAllowance.MonthStart = CutOffDuration.DateStart;
                            UnusualAllowance.MonthEnd = CutOffDuration.DateEnd;
                            UnusualAllowance.Type = EnumDropDown.EDType.E_EARNING.ToString();
                            UnusualAllowance.CurrencyID = model.CurrencyID;
                            FormulaValue = listElementFormula.Where(m => m.VariableName.ReplaceSpace() == "TienPhepNam").FirstOrDefault();
                            UnusualAllowance.Amount = double.Parse(FormulaValue != null ? FormulaValue.Value.ToString() : "0");
                            repoUnusualAllowance.Add(UnusualAllowance);
                        }

                        if (GoodHealth != null)
                        {
                            //lưu phần tử TienSucKhoe
                            Sal_UnusualAllowance UnusualAllowance = new Sal_UnusualAllowance();
                            UnusualAllowance = new Sal_UnusualAllowance();
                            UnusualAllowance.ID = Guid.NewGuid();
                            UnusualAllowance.ProfileID = profile.ID;
                            UnusualAllowance.UnusualEDTypeID = GoodHealth.ID;

                            UnusualAllowance.MonthStart = CutOffDuration.DateStart;
                            UnusualAllowance.MonthEnd = CutOffDuration.DateEnd;
                            UnusualAllowance.Type = EnumDropDown.EDType.E_EARNING.ToString();
                            UnusualAllowance.CurrencyID = model.CurrencyID;
                            FormulaValue = listElementFormula.Where(m => m.VariableName.ReplaceSpace() == "TienSucKhoe").FirstOrDefault();
                            UnusualAllowance.Amount = double.Parse(FormulaValue != null ? FormulaValue.Value.ToString() : "0");
                            repoUnusualAllowance.Add(UnusualAllowance);
                        }
                    }
                    else
                    {
                        Sal_UnusualAllowance UnusualAllowance = new Sal_UnusualAllowance();
                        UnusualAllowance.ID = Guid.NewGuid();
                        UnusualAllowance.ProfileID = profile.ID;
                        UnusualAllowance.UnusualEDTypeID = model.UnusualEDTypeID;

                        UnusualAllowance.MonthStart = CutOffDuration.DateStart;
                        UnusualAllowance.MonthEnd = CutOffDuration.DateEnd;
                        UnusualAllowance.Type = EnumDropDown.EDType.E_EARNING.ToString();
                        UnusualAllowance.CurrencyID = model.CurrencyID;
                        try
                        {
                            listElementFormula = new List<ElementFormula>();
                            TotalData.listElement_All = repoCat_Element.FindBy(m => m.IsDelete != true).ToList().Translate<Cat_ElementEntity>();
                            listElementFormula = CumputePayrollServices.ParseFormula(ElementItem, listElementFormula, TotalData, profile, CutOffDuration, new Dictionary<Guid, ValueCount>());
                            FormulaValue = listElementFormula.Where(m => m.VariableName.ReplaceSpace() == ElementItem.ElementCode.ReplaceSpace()).FirstOrDefault();
                            UnusualAllowance.Amount = double.Parse(FormulaValue != null ? FormulaValue.Value.ToString() : "0");
                        }
                        catch
                        {
                            UnusualAllowance.Amount = 0;
                            UnusualAllowance.Notes = "Không tính được công thức - Lỗi: " + TotalData.Status;
                        }
                        repoUnusualAllowance.Add(UnusualAllowance);
                    }

                    if (ListProfile.IndexOf(profile) % 10 == 0)
                    {
                        asynTask.PercentComplete = (double)(ListProfile.IndexOf(profile) + 1) / (double)ListProfile.Count;
                        unitOfWork.SaveChanges();
                    }
                }
                asynTask.PercentComplete = 1;
                unitOfWork.SaveChanges();
            }
        }
Ejemplo n.º 54
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);
            }
        }
Ejemplo n.º 55
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;
            }
        }
Ejemplo n.º 56
0
        /// <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;
        }
Ejemplo n.º 57
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();
            }
        }