public void NUnit_CardHistory_Domain_Get()
        {
            string             status  = string.Empty;
            Att_RosterServices service = new Att_RosterServices();
            var repo = service.GetAllUseEntity <Att_RosterEntity>(ref status);

            Console.Write("Total Record: " + repo.Count());
        }
        public void NUnit_CardHistory_Domain_GetById()
        {
            Att_RosterServices service = new Att_RosterServices();
            var model = new Att_Roster {
                Id = 1
            };
            string status = string.Empty;
            var    result = service.GetById <Att_RosterEntity>(model.Id, ref status) as Att_RosterEntity;

            NUnit.Framework.Assert.IsNotNull(result);
            Console.Write("SearchResult: " + result.Id
                          + " | " + result.ProfileID
                          + " | " + result.Comment
                          );
        }
        public void NUnit_CardHistory_Domain_Delete()
        {
            Att_RosterServices service = new Att_RosterServices();
            int rs    = 0;
            var model = new Att_Roster {
                Id = 2
            };
            string result = service.Delete <Att_RosterEntity>(model.Id);

            if (result != null)
            {
                rs += 1;
                Console.WriteLine("Process Success >>> Delete >>> " + model.Id);
            }
        }
        public void NUnit_CardHistory_Domain_Remove()
        {
            Att_RosterServices service = new Att_RosterServices();
            int rs    = 0;
            var model = new Att_Roster {
                Id = 1
            };
            string result = service.Remove <Att_RosterEntity>(model.Id);

            if (result != string.Empty)
            {
                rs += 1;
                Console.WriteLine("Process Success >>> Remove >>> " + model.Id);
            }
        }
Example #5
0
        //SonVo - 20140617 - chuyển thành trạng thái Sumit
        public ActionResult SubmitRoster(string selectedIds)
        {
            List <Guid> ids = new List <Guid>();

            if (selectedIds != null)
            {
                ids = selectedIds
                      .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                      .Select(x => new Guid(x))
                      .ToList();
            }
            Att_RosterServices service = new Att_RosterServices();

            service.SubmitRoster(ids);
            return(Json(""));
        }
        public void NUnit_CardHistory_Domain_Edit()
        {
            Att_RosterServices service = new Att_RosterServices();
            var model = new Att_Roster
            {
                Id        = 1,
                ProfileID = 1,
                Comment   = "Update Name ",
            };
            string result = service.Edit(model);

            if (result != string.Empty)
            {
                Console.WriteLine("Process Success >>> Update >>> " + model.Id
                                  + " | " + model.ProfileID
                                  + " | " + model.Comment
                                  );
            }
        }
        public void NUnit_CardHistory_Domain_Add()
        {
            Att_RosterServices service = new Att_RosterServices();
            string             result  = string.Empty;
            int countSC = 0;

            for (int i = 1; i <= 10; i++)
            {
                var model = new Att_Roster
                {
                    ProfileID = 1,
                    Comment   = "Comment " + i
                };
                result = service.Add(model);
                if (result != string.Empty)
                {
                    countSC += 1;
                    Console.WriteLine("Process Success >>> Create >>> " + model.Id
                                      + " | " + model.Comment
                                      );
                }
            }
            Console.WriteLine("Total success record: " + countSC);
        }
        public Cat_OvertimeType getOTType(DateTime dateWorkDate, bool isNightShift, Hre_Profile profile, List <Cat_DayOff> list_dayOff, List <Att_RosterGroup> lstRosterGroup, List <Att_Roster> lstRosterTypeGroup)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork           = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_LeaveDay     = new CustomBaseRepository <Att_LeaveDay>(unitOfWork);
                var repoCat_OvertimeType = new CustomBaseRepository <Cat_OvertimeType>(unitOfWork);

                Cat_OvertimeType otType = null;
                try
                {
                    dateWorkDate = dateWorkDate.Date;

                    //LamLe : Them chuc nang neu tang ca vao ngay nghi thi chon loai tang ca phu thuoc vao cau hinh Tang ca trong ngay nghi.
                    List <Att_LeaveDay> lstLeave = repoAtt_LeaveDay
                                                   .FindBy(lv => lv.IsDelete == null && lv.DateStart <= dateWorkDate && lv.DateEnd >= dateWorkDate && lv.ProfileID == profile.ID)
                                                   .ToList();
                    if (lstLeave.Count > 0)
                    {
                        Att_LeaveDay leave = lstLeave[0];
                        if (leave != null && leave.Cat_LeaveDayType != null && leave.Cat_LeaveDayType.Cat_OvertimeType != null)
                        {
                            otType = leave.Cat_LeaveDayType.Cat_OvertimeType;
                            return(otType);
                        }
                    }

                    Att_Grade grade = Att_GradeServices.GetGrade(profile, dateWorkDate);
                    if (grade == null)
                    {
                        string status = OverTimeType.E_WORKDAY.ToString();
                        otType = repoCat_OvertimeType.FindBy(dayoff => dayoff.IsDelete == null && dayoff.Code == status).FirstOrDefault();
                        return(otType);
                    }
                    list_dayOff = list_dayOff.Where(df => df.DateOff.Date == dateWorkDate.Date).ToList();
                    Cat_GradeCfg gradecfg = grade.Cat_GradeCfg;

                    //Check overtime holiday
                    //List<Cat_DayOff> list_dayOff = EntityService.Instance.GetEntityList<Cat_DayOff>(GuidContext, _userId, dayoff => dayoff.DateOff == dateWorkDate);

                    if (list_dayOff.Count > 0)
                    {
                        //Cat_GradeCfg.FieldNames.Cat_OvertimeType1
                        bool isDayOffHollyDay = false;
                        foreach (var item in list_dayOff)
                        {
                            if (item.DateOff.Date == dateWorkDate.Date && item.Type == HolidayType.E_HOLIDAY_HLD.ToString())
                            {
                                isDayOffHollyDay = true;
                            }
                        }
                        //Ca dem ngay le
                        if (isDayOffHollyDay && isNightShift)
                        {
                            otType = gradecfg.Cat_OvertimeType5;
                        }
                        //Ca dem ngay nghi cuoi tuan
                        else if (!isDayOffHollyDay && isNightShift)
                        {
                            otType = gradecfg.Cat_OvertimeType4;
                        }
                        ////Ca ngay ngay le
                        else if (isDayOffHollyDay && !isNightShift)
                        {
                            otType = gradecfg.Cat_OvertimeType2;
                        }
                        ////Ca ngay ngay nghi cuoi tuan
                        else
                        {
                            otType = gradecfg.Cat_OvertimeType1;
                        }
                    }
                    else
                    {
                        Hashtable hsRoster = Att_RosterServices.GetRosterTable(false, profile, dateWorkDate, dateWorkDate, lstRosterGroup, lstRosterTypeGroup);

                        bool isWorkday = Att_AttendanceServices.IsWorkDay(grade.Cat_GradeAttendance, hsRoster, list_dayOff, dateWorkDate);
                        if (isWorkday)
                        {
                            if (isNightShift)
                            {
                                otType = gradecfg.Cat_OvertimeType3;
                            }
                            else
                            {
                                otType = gradecfg.Cat_OvertimeType;
                            }
                            //if (gradecfg.Cat_OvertimeType == null)
                            //{

                            //    string workday = OverTimeType.E_WORKDAY.ToString();
                            //    otType = EntityService.Instance.GetEntity<Cat_OvertimeType>(GuidContext, _userId, dayoff => dayoff.Code == workday);
                            //}
                            //else
                            //    otType = gradecfg.Cat_OvertimeType;
                        }
                        else
                        {
                            if (isNightShift)
                            {
                                otType = gradecfg.Cat_OvertimeType4;
                            }
                            else
                            {
                                otType = gradecfg.Cat_OvertimeType1;
                            }
                            //if (gradecfg.Cat_OvertimeType1 == null)
                            //{
                            //    string workday = OverTimeType.E_WORKDAY.ToString();
                            //    otType = EntityService.Instance.GetEntity<Cat_OvertimeType>(GuidContext, _userId, dayoff => dayoff.Code == workday);
                            //}
                            //else
                            //    otType = gradecfg.Cat_OvertimeType1;
                        }
                    }
                }
                catch (Exception ex)
                {
                }
                return(otType);
            }
        }
        /// <summary>
        /// Tách thời gian làm việc thành các khoản theo cấu hình.
        /// </summary>
        /// <param name="guidContext"></param>
        /// <param name="userID"></param>
        /// <param name="parameter">Điền đủ thông tin cho tất cả thuộc tính trong OvertimeInfo</param>
        /// <returns></returns>
        public List <Att_OvertimeEntity> AnalysisOvertime(Att_OvertimeEntity BaseDataOvertimeTemplate, OvertimeInfo parameter)
        {
            List <TimeSpan> listTimePoints = new List <TimeSpan>();

            if (parameter.DayShiftPoints != null)
            {
                listTimePoints.AddRange(parameter.DayShiftPoints.Select(d => d.TimeOfDay).ToList());
            }
            if (parameter.NightShiftPoints != null)
            {
                listTimePoints.AddRange(parameter.NightShiftPoints.Select(d => d.TimeOfDay).ToList());
            }

            if (parameter.BreaktPoints != null)
            {
                foreach (var item in parameter.BreaktPoints)
                {
                    TimeSpan breakStart = item.Key.TimeOfDay;
                    TimeSpan breakEnd   = item.Key.AddHours(item.Value).TimeOfDay;

                    listTimePoints.Add(breakStart);
                    listTimePoints.Add(breakEnd);
                }
            }

            listTimePoints = listTimePoints.Distinct().ToList();
            List <Att_OvertimeEntity> listOvertimeInsert = new List <Att_OvertimeEntity>();
            List <Guid>            lstProfileIDs         = listOvertimeInsert.Select(m => m.ProfileID).ToList();
            List <Att_Roster>      lstRosterTypeGroup    = new List <Att_Roster>();
            List <Att_RosterGroup> lstRosterGroup        = new List <Att_RosterGroup>();

            Att_RosterServices.GetRosterGroup(lstProfileIDs, parameter.DateFrom, parameter.DateTo, out lstRosterTypeGroup, out lstRosterGroup);

            DateTime currentPoint = parameter.DateFrom;

            while (currentPoint < parameter.DateTo)
            {
                TimeSpan           greaterTime      = listTimePoints.Min();
                Att_OvertimeEntity baseDataOvertime = new Att_OvertimeEntity();
                //string[] strExclude = new string[] { BaseDataOvertime.FieldNames.ID, BaseDataOvertime.FieldNames.Can_Food, BaseDataOvertime.FieldNames.Can_Food2, BaseDataOvertime.FieldNames.Can_Menu, BaseDataOvertime.FieldNames.Can_Menu1 };
                //BaseDataOvertimeTemplate.CopyTo(baseDataOvertime, strExclude);
                baseDataOvertime.ID       = Guid.NewGuid();
                baseDataOvertime.WorkDate = currentPoint;

                if (listTimePoints.Any(d => d > currentPoint.TimeOfDay))
                {
                    greaterTime  = listTimePoints.Where(d => d > currentPoint.TimeOfDay).OrderBy(d => d).FirstOrDefault();
                    currentPoint = currentPoint.Date.Add(greaterTime);
                }
                else
                {
                    currentPoint = currentPoint.Date.AddDays(1).Add(greaterTime);
                }

                currentPoint = currentPoint > parameter.DateTo ? parameter.DateTo : currentPoint;
                baseDataOvertime.RegisterHours = currentPoint.Subtract(baseDataOvertime.WorkDate).TotalHours;

                baseDataOvertime.WorkDateEnd  = currentPoint;//thới gian kết thúc ca
                baseDataOvertime.IsNightShift = IsNightShift(baseDataOvertime, parameter);
                baseDataOvertime.ProfileID    = parameter.Hre_Profile.ID;
                if (!IsBreakTime(baseDataOvertime, parameter))
                {
                    if (parameter.Hre_Profile != null && parameter.ListDayOff != null)
                    {
                        baseDataOvertime.OvertimeTypeID = getOTType(baseDataOvertime.WorkDate, baseDataOvertime.IsNightShift,
                                                                    parameter.Hre_Profile, parameter.ListDayOff, lstRosterGroup, lstRosterTypeGroup).ID;
                    }

                    listOvertimeInsert.Add(baseDataOvertime);
                }
            }

            return(listOvertimeInsert);
        }
        /// <summary>
        /// Edit comment Trung.le 20120529
        /// Them thuoc tinh Khong cat Overtime qua ngày E_STANDARD_WORKDAY - Value37 Trung.le 20120529
        /// </summary>
        /// <param name="overtime"></param>
        /// <param name="lstDayOff"></param>
        /// <param name="_LstPregnancy"></param>
        /// <param name="GuidContext"></param>
        /// <param name="_userId"></param>
        /// <param name="isByShift">Lấy theo ca làm việc của từng người</param>
        /// <returns></returns>
        public List <Att_OvertimeEntity> AnalysisOvertime(Att_OvertimeEntity overtime, List <Cat_DayOff> lstDayOff,
                                                          List <Att_Pregnancy> _LstPregnancy, bool isByShift, bool isAllowCutBreakHour, string UserLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork    = (IUnitOfWork)(new UnitOfWork(context));
                var repoCat_Shift = new CustomBaseRepository <Cat_Shift>(unitOfWork);

                Cat_Shift ShiftOfOT = repoCat_Shift.FindBy(s => s.ID == overtime.ShiftID).FirstOrDefault();


                string status = string.Empty;

                Att_OvertimeEntity baseOT = null;
                if (overtime != null)
                {
                    //overtime.SerialCode = overtime.Workdate.ToString("ddMMyyyy");
                }

                List <Att_OvertimeEntity> listOvertimeInsert = new List <Att_OvertimeEntity>();
                Hre_Profile profile = new Hre_Profile();
                profile.ID = overtime.ProfileID;
                DateTime _workDate    = overtime.WorkDate;
                DateTime dateWorkDate = _workDate;

                string        key      = "HRM_ATT_OT";
                List <object> lstSysOT = new List <object>();
                lstSysOT.Add(key);
                lstSysOT.Add(null);
                lstSysOT.Add(null);
                var config = GetData <Sys_AllSettingEntity>(lstSysOT, ConstantSql.hrm_sys_sp_get_AllSetting, UserLogin, ref status);
                if (config == null)
                {
                    return(listOvertimeInsert);
                }
                var  NoCutOvertimePassDay   = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_NOCUTOVERTIMEPASSDAY.ToString()).FirstOrDefault();
                var  ByPeriodOfTime         = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_BYPERIODOFTIME.ToString()).FirstOrDefault();
                var  nightShiftFrom         = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_NIGHTSHIFTFROM.ToString()).FirstOrDefault();
                var  nightShiftTo           = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_NIGHTSHIFTTO.ToString()).FirstOrDefault();
                bool isNocutOvertimePassDay = Convert.ToBoolean(NoCutOvertimePassDay.Value1);//Không cắt Overtime qua ngày


                List <Hre_Profile> lstProfile = new List <Hre_Profile>()
                {
                    profile
                };
                List <Guid>            lstProfileIDs      = lstProfile.Select(m => m.ID).ToList();
                List <Att_Roster>      lstRosterTypeGroup = new List <Att_Roster>();
                List <Att_RosterGroup> lstRosterGroup     = new List <Att_RosterGroup>();
                Att_RosterServices.GetRosterGroup(lstProfileIDs, _workDate.Date, _workDate.Date, out lstRosterTypeGroup, out lstRosterGroup);

                string registryCode  = "OT_" + overtime.CodeEmp + "_" + overtime.WorkDate.ToString("ddMMyyyyHHmmss");
                double basicHours    = overtime.RegisterHours;
                double durationHours = overtime.RegisterHours;
                //overtime.BasicHours = basicHours;
                //overtime.RegisterCode = registryCode;
                bool                isWorkDay       = true;
                DateTime            dateWorkDateEnd = dateWorkDate.AddHours(durationHours);
                Att_Grade           grade           = Att_GradeServices.GetGrade(profile, _workDate.Date);
                Cat_GradeAttendance gradeCfg        = grade == null ? null : grade.Cat_GradeAttendance;
                if (gradeCfg == null)
                {
                    return(listOvertimeInsert);
                }
                Hashtable htable = null;
                htable    = Att_RosterServices.GetRosterTable(false, profile, _workDate.Date, _workDate.Date, lstRosterGroup, lstRosterTypeGroup);
                isWorkDay = Att_AttendanceServices.IsWorkDay(gradeCfg, htable, lstDayOff, _workDate.Date);
                if (isByShift)//Lấy theo ca làm việc của từng người
                {
                    #region Lấy theo ca làm việc của từng người

                    Cat_Shift ship = Att_AttendanceServices.GetShift(gradeCfg, htable, _workDate.Date);
                    if (ship != null)
                    {
                        if (isWorkDay)
                        {
                            if (overtime.DurationType == EnumDropDown.OvertimeDurationType.E_OT_LATE.ToString() && ship != null)
                            {
                                DateTime timeOut = ship.InTime.AddHours(ship.CoOut);
                                dateWorkDate    = _workDate.Date.AddHours(timeOut.Hour).AddMinutes(timeOut.Minute);
                                dateWorkDateEnd = dateWorkDate.AddHours(durationHours);
                            }
                            else if (overtime.DurationType == EnumDropDown.OvertimeDurationType.E_OT_EARLY.ToString() && ship != null)
                            {
                                DateTime timeIn = ship.InTime;
                                dateWorkDate    = _workDate.Date.AddHours(timeIn.Hour).AddMinutes(timeIn.Minute);
                                dateWorkDateEnd = dateWorkDate;
                                dateWorkDate    = dateWorkDate.AddHours(-durationHours);
                            }
                        }
                        else
                        {
                            DateTime timeIn = ship.InTime;
                            dateWorkDate = _workDate.Date.AddHours(timeIn.Hour).AddMinutes(timeIn.Minute);
                        }
                    }
                    else
                    {
                        dateWorkDate    = dateWorkDate.Date;
                        dateWorkDateEnd = dateWorkDate.AddHours(durationHours);
                    }
                    ShiftOfOT = ship;


                    htable    = Att_RosterServices.GetRosterTable(false, profile, dateWorkDate, dateWorkDate.AddHours(durationHours), lstRosterGroup, lstRosterTypeGroup);
                    isWorkDay = Att_AttendanceServices.IsWorkDay(gradeCfg, htable, lstDayOff, dateWorkDate.AddHours(durationHours));

                    #endregion
                }

                //Kiem tra xem co trong thoi gian nghi thai san khong?
                if (isWorkDay && overtime.DurationType == EnumDropDown.OvertimeDurationType.E_OT_LATE.ToString() &&
                    _LstPregnancy != null && _LstPregnancy.Exists(pc => pc.ProfileID == profile.ID && pc.DateEnd >= dateWorkDate && pc.DateStart <= dateWorkDateEnd))
                {
                    dateWorkDate    = dateWorkDate.AddHours(-1);
                    dateWorkDateEnd = dateWorkDate.AddHours(durationHours);
                }
                overtime.WorkDate = dateWorkDate;



                string strHoursNightFrom = string.Empty;
                string strHoursNightTo   = string.Empty;


                if (!Att_AttendanceServices.IsNightShiftByConfig(ByPeriodOfTime) && ShiftOfOT != null &&
                    ShiftOfOT.NightTimeStart != null &&
                    ShiftOfOT.NightTimeEnd != null)
                {
                    strHoursNightFrom = ShiftOfOT.NightTimeStart.Value.ToString("HH:mm:ss");
                    strHoursNightTo   = ShiftOfOT.NightTimeEnd.Value.ToString("HH:mm:ss");
                }
                else
                {
                    strHoursNightFrom = string.IsNullOrEmpty(nightShiftFrom.Value1) == true ? "21:00:00" : nightShiftFrom.Value1 + ":00";
                    strHoursNightTo   = string.IsNullOrEmpty(nightShiftTo.Value1) == true ? "05:00:00" : nightShiftTo.Value1 + ":00";
                }

                DateTime dateNightFrom = Common.ConvertStringToDateTime(dateWorkDate.Date.ToString("MM/dd/yyyy") + " " + strHoursNightFrom, CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern);
                DateTime dateNightTo   = Common.ConvertStringToDateTime(dateWorkDate.Date.AddDays(1).ToString("MM/dd/yyyy") + " " + strHoursNightTo, CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern);


                OvertimeInfo overtimeInfo = new OvertimeInfo(true);
                overtimeInfo.DateFrom   = dateWorkDate;
                overtimeInfo.TotalHours = overtime.RegisterHours;

                overtimeInfo.DayShiftPoints = new DateTime[] { dateNightTo };

                if (isNocutOvertimePassDay)
                {
                    overtimeInfo.NightShiftPoints = new DateTime[] { dateNightFrom };
                }
                else
                {
                    //truong hop cat khi qua ngay hom sau
                    overtimeInfo.NightShiftPoints = new DateTime[] { dateNightFrom, dateNightFrom.Date };
                }

                if (ShiftOfOT != null && isAllowCutBreakHour)
                {
                    Cat_Shift shift      = ShiftOfOT;
                    DateTime  coBreakOut = shift.InTime.AddHours(shift.CoBreakIn);

                    if (shift.CoBreakOut - shift.CoBreakIn > 0)
                    {
                        overtimeInfo.BreaktPoints.Add(coBreakOut, shift.CoBreakOut - shift.CoBreakIn);
                    }
                }
                Hre_Profile temp = new Hre_Profile();
                temp.ID = overtime.ProfileID;

                overtimeInfo.Hre_Profile = temp;
                overtimeInfo.ListDayOff  = lstDayOff;

                listOvertimeInsert = AnalysisOvertime(overtime, overtimeInfo);



                return(listOvertimeInsert);
            }
        }
Example #11
0
        public Att_RosterModel Post([Bind] Att_RosterModel model)
        {
            ActionService service               = new ActionService(UserLogin);
            var           baseService           = new BaseService();
            string        status                = string.Empty;
            var           hrService             = new Hre_ProfileServices();
            string        strMessages           = string.Empty;
            var           rosterService         = new Att_RosterServices();
            var           sysAllSetttingService = new Sys_AllSettingServices();

            #region Validate
            string message       = string.Empty;
            var    checkValidate = HRM.Business.Main.Domain.ValidatorService.OnValidateData <Att_RosterModel>(model, "Att_Roster", ref message);
            if (!checkValidate)
            {
                model.ActionStatus = message;
                return(model);
            }
            checkValidate = HRM.Business.Main.Domain.ValidatorService.OnValidateData <Att_RosterModel>(model, "Att_ProfileNotRoster", ref message);
            if (!checkValidate)
            {
                model.ActionStatus = message;
                return(model);
            }
            if (string.IsNullOrEmpty(model.OrgStructureIDs) && string.IsNullOrEmpty(model.ProfileIds) && model.ProfileID == Guid.Empty)
            {
                message            = string.Format(ConstantMessages.FieldNotAllowNull.TranslateString(), ("ProfileID").TranslateString());
                model.ActionStatus = message;
                return(model);
            }
            #endregion

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

            if (!string.IsNullOrEmpty(model.OrgStructureIDs))
            {
                List <object> listObj = new List <object>();
                listObj.Add(model.OrgStructureIDs);
                listObj.Add(string.Empty);
                listObj.Add(string.Empty);
                var lstProfile = hrService.GetData <Hre_ProfileEntity>(listObj, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrgStructure, UserLogin, ref status).Select(s => s.ID).ToList();
                lstProfileIDs.AddRange(lstProfile);
            }
            else if (model.ProfileIds != null && model.ProfileIds != "")
            {
                var listGuid = model.ProfileIds.Split(',').Select(s => Guid.Parse(s)).ToArray();
                lstProfileIDs.AddRange(listGuid);
            }
            var lstRosterEntity_Validate = new List <Att_RosterEntity>();
            foreach (var item in lstProfileIDs)
            {
                Att_RosterEntity rosterEntity = model.CopyData <Att_RosterEntity>();
                rosterEntity.ProfileID = item;
                if (rosterEntity.ID != null && rosterEntity.ID != Guid.Empty)
                {
                }
                else
                {
                    rosterEntity.ID = Guid.NewGuid();
                }
                lstRosterEntity_Validate.Add(rosterEntity);
            }
            var key = AppConfig.HRM_ATT_ALLOWSAVEDUPLICATE.ToString();
            var lstSysAllSetting = sysAllSetttingService.GetData <Sys_AllSettingEntity>(key, ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();


            var ValidateLess12Hour = AppConfig.HRM_ATT_VALIDATE_ROSTER_NON_CONTINUE_12HOUR.ToString();
            var lstSysSetting_ValidateLess12Hour = sysAllSetttingService.GetData <Sys_AllSettingEntity>(ValidateLess12Hour, ConstantSql.hrm_sys_sp_get_AllSettingByKey, UserLogin, ref status).FirstOrDefault();
            if (lstSysSetting_ValidateLess12Hour != null && lstSysSetting_ValidateLess12Hour.Value1 == bool.TrueString)
            {
                string Err = string.Empty;
                Err = rosterService.ValidateShiftHourContinue(lstRosterEntity_Validate);
                if (Err != string.Empty)
                {
                    model.SetPropertyValue(Constant.ActionStatus, NotificationType.Error + "," + Err);
                    return(model);
                }
            }

            if (!string.IsNullOrEmpty(model.OrgStructureIDs))
            {
                List <object> listObj = new List <object>();
                listObj.Add(model.OrgStructureIDs);
                listObj.Add(string.Empty);
                listObj.Add(string.Empty);
                var lstProfile = hrService.GetData <Hre_ProfileEntity>(listObj, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrgStructure, UserLogin, ref status).Select(s => s.ID).ToList();
                if (lstProfile.Count == 0 || lstProfile == null)
                {
                    model.SetPropertyValue(Constant.ActionStatus, NotificationType.Info + "," + strMessages + ConstantMessages.FieldDuplicate);
                    return(model);
                }
                if (lstProfile != null && model.ProfileIds != null)
                {
                    Guid[] listGuid = null;
                    listGuid   = model.ProfileIds.Split(',').Select(s => Guid.Parse(s)).ToArray();
                    lstProfile = lstProfile.Where(s => !listGuid.Contains(s)).ToList();
                }
                List <Att_RosterEntity> lstRosterEntity = new List <Att_RosterEntity>();
                List <object>           paraRoster      = new List <object>();
                paraRoster.AddRange(new object[4]);
                paraRoster[0] = (object)model.OrgStructureIDs;
                paraRoster[1] = null;
                paraRoster[2] = null;
                paraRoster[3] = null;
                var listRosterData = rosterService.GetData <Att_RosterEntity>(paraRoster, ConstantSql.hrm_att_getdata_Roster, UserLogin, ref status);
                foreach (var item in lstProfile)
                {
                    Att_RosterModel modelSave  = model.CopyData <Att_RosterModel>();
                    var             listRoster = listRosterData.Where(s => s.ProfileID == item);
                    if (modelSave.Type != RosterType.E_CHANGE_SHIFT.ToString() &&
                        modelSave.Type != RosterType.E_TIME_OFF.ToString() &&
                        listRoster != null &&
                        listRoster.Any(d => d.DateStart <= model.DateEnd && d.DateEnd >= model.DateStart))
                    {
                        strMessages += listRoster.FirstOrDefault().ProfileName + ", ";
                        continue;
                    }
                    modelSave.ProfileID = item;
                    Att_RosterEntity rosterEntity = modelSave.CopyData <Att_RosterEntity>();
                    lstRosterEntity.Add(rosterEntity);
                }
                if (strMessages == "" && lstRosterEntity.Count > 0)
                {
                    model.ActionStatus = rosterService.Add(lstRosterEntity);
                }
                else
                {
                    if (lstSysAllSetting != null && lstSysAllSetting.Value1 == bool.TrueString && lstRosterEntity.Count > 0)
                    {
                        model.ActionStatus = rosterService.Add(lstRosterEntity);
                    }
                    else if (lstSysAllSetting.Value1 == bool.FalseString)
                    {
                        model.SetPropertyValue(Constant.ActionStatus, NotificationType.Error + "," + strMessages + ConstantMessages.FieldDuplicate);
                        return(model);
                    }
                    else if (lstRosterEntity.Count == 0)
                    {
                        model.SetPropertyValue(Constant.ActionStatus, NotificationType.Info + "," + strMessages + ConstantMessages.FieldDuplicate);
                        return(model);
                    }
                }
                return(model);
            }
            //Xử lý khi chọn nhiều nhân viên
            if (model.ProfileIds != null && model.ProfileIds.IndexOf(',') > 0 && model.OrgStructureIDs == null)
            {
                Guid[] listGuid = null;
                listGuid = model.ProfileIds.Split(',').Select(s => Guid.Parse(s)).ToArray();
                List <Att_RosterEntity> lstRosterEntity = new List <Att_RosterEntity>();
                foreach (var item in listGuid)
                {
                    Att_RosterModel modelSave  = model.CopyData <Att_RosterModel>();
                    var             listRoster = service.GetData <Att_RosterEntity>(item, ConstantSql.hrm_att_sp_get_RosterByProfileId, ref status);
                    if (modelSave.Type != RosterType.E_CHANGE_SHIFT.ToString() &&
                        modelSave.Type != RosterType.E_TIME_OFF.ToString() &&
                        listRoster != null &&
                        listRoster.Any(d => d.DateStart <= model.DateEnd && d.DateEnd >= model.DateStart))
                    {
                        strMessages += listRoster.FirstOrDefault().ProfileName + ", ";
                        continue;
                    }
                    modelSave.ProfileID = item;
                    Att_RosterEntity rosterEntity = modelSave.CopyData <Att_RosterEntity>();
                    lstRosterEntity.Add(rosterEntity);
                }
                if (strMessages == "")
                {
                    model.ActionStatus = rosterService.Add(lstRosterEntity);
                }
                else
                {
                    if (lstSysAllSetting != null && lstSysAllSetting.Value1 == bool.TrueString)
                    {
                        model.ActionStatus = rosterService.Add(lstRosterEntity);
                    }
                    else
                    {
                        model.SetPropertyValue(Constant.ActionStatus, NotificationType.Error + "," + strMessages + ConstantMessages.FieldDuplicate);
                        return(model);
                    }
                }
                return(model);
            }
            //Xử lý khi chỉ chọn 1 nhân viên
            if (model.ID == Guid.Empty)
            {
                var lstRoster = service.GetData <Att_RosterEntity>(model.ProfileID, ConstantSql.hrm_att_sp_get_RosterByProfileId, ref status);
                if (model.Type != RosterType.E_CHANGE_SHIFT.ToString() &&
                    model.Type != RosterType.E_TIME_OFF.ToString() &&
                    lstRoster != null &&
                    lstRoster.Any(d => d.DateStart <= model.DateEnd && d.DateEnd >= model.DateStart))
                {
                    strMessages = lstRoster.FirstOrDefault().ProfileName + ",";
                    model.SetPropertyValue(Constant.ActionStatus, NotificationType.Error + "," + strMessages + ConstantMessages.FieldDuplicate);
                    return(model);
                }
                return(service.UpdateOrCreate <Att_RosterEntity, Att_RosterModel>(model));
            }
            return(service.UpdateOrCreate <Att_RosterEntity, Att_RosterModel>(model));
        }
        public List <Att_RptExceptionDataEntity> GetAtt_RptExceptionData(DateTime DateStart, DateTime DateEnd, String OrgStructureIDs, bool NoScan, bool DifferenceMoreRoster, double Difference, double LessHours, bool MissInOut, out string message, string userExport, string userLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork) new UnitOfWork(context);
                message = "";
                var repoHre_Profile          = new CustomBaseRepository <Hre_Profile>(unitOfWork);
                var repoCat_OrgStructure     = new CustomBaseRepository <Cat_OrgStructure>(unitOfWork);
                var repoCat_DayOff           = new CustomBaseRepository <Cat_DayOff>(unitOfWork);
                var repoAtt_Roster           = new CustomBaseRepository <Att_Roster>(unitOfWork);
                var repoAtt_InOut            = new CustomBaseRepository <Att_InOut>(unitOfWork);
                var repoAtt_LeaveDay         = new CustomBaseRepository <Att_LeaveDay>(unitOfWork);
                var repoAtt_Grade            = new CustomBaseRepository <Att_Grade>(unitOfWork);
                var repoHre_WorkHistory      = new CustomBaseRepository <Hre_WorkHistory>(unitOfWork);
                var repoCat_OrgStructureType = new Cat_OrgStructureTypeRepository(unitOfWork);
                var repoCat_Position         = new Cat_PositionRepository(unitOfWork);


                List <Hre_ProfileEntity> lstProfile = new List <Hre_ProfileEntity>();
                List <object>            lstOrgIDs  = new List <object>();
                lstOrgIDs.AddRange(new object[3]);
                lstOrgIDs[0] = OrgStructureIDs;
                lstOrgIDs[1] = null;
                lstOrgIDs[2] = null;
                lstProfile   = GetData <Hre_ProfileEntity>(lstOrgIDs, ConstantSql.hrm_hr_sp_get_ProfileIdsByOrg, userLogin, ref message);

                List <Att_RptExceptionDataEntity> Result = new List <Att_RptExceptionDataEntity>();
                string waitStatus = ProfileStatusSyn.E_WAITING.ToString();
                lstProfile = lstProfile.Where(d => d.StatusSyn != waitStatus && (d.DateQuit == null || d.DateQuit.Value > DateEnd)).ToList();
                List <Guid>      lstProfileID = lstProfile.Select(d => d.ID).ToList();
                List <Att_InOut> lstInOutAll  = repoAtt_InOut.FindBy(wd => wd.WorkDate >= DateStart &&
                                                                     wd.WorkDate <= DateEnd).OrderBy(wd => wd.Hre_Profile.ProfileName).ToList();
                var positions = repoCat_Position.FindBy(s => s.IsDelete == null && s.Code != null).Select(s => new { s.ID, s.Code, s.PositionName }).ToList();
                var orgTypes  = repoCat_OrgStructureType.FindBy(s => s.IsDelete == null).ToList();
                List <Cat_OrgStructure> lstOrg = new List <Cat_OrgStructure>();
                if (!string.IsNullOrEmpty(OrgStructureIDs)) // Chỉ lấy phòng ban theo sự lựa chọn
                {
                    List <int> lstOrderNumber = OrgStructureIDs.Split(',').Distinct().Select(s => int.Parse(s)).ToList();
                    lstOrg = repoCat_OrgStructure.FindBy(m => m.IsDelete == null && lstOrderNumber.Contains(m.OrderNumber)).ToList();
                }
                else //Lấy hêt phòng ban
                {
                    lstOrg = repoCat_OrgStructure.FindBy(m => m.IsDelete == null).ToList();
                }
                if (NoScan)
                {
                    List <Cat_DayOff> lstHoliday       = repoCat_DayOff.FindBy(d => d.IsDelete == null).ToList();
                    String            RosterTypeAbsent = RosterType.E_TIME_OFF.ToString();
                    List <Att_Roster> lstRoster        = repoAtt_Roster.FindBy(prop => prop.DateStart <= DateEnd && prop.DateEnd >= DateStart &&
                                                                               prop.Type != RosterTypeAbsent).ToList();

                    List <Att_LeaveDay> lstLeaveDayAll = repoAtt_LeaveDay.FindBy(prop => prop.DateStart <= DateEnd && prop.DateEnd >= DateStart).ToList();
                    List <Att_Grade>    lstAtt_Grade   = repoAtt_Grade.FindBy(d => d.MonthStart <= DateEnd && d.MonthEnd >= DateStart && d.ProfileID.HasValue && lstProfileID.Contains(d.ProfileID.Value)).ToList();
                    //List<Sal_Grade> lstGradeAll = GradeDAO.getAllGrade(EntityService.GuidMainContext
                    //                                                , lstProfileID
                    //                                                , DateEnd
                    //                                                , LoginUserID);
                    List <Hre_WorkHistory> lstWHistory        = repoHre_WorkHistory.FindBy(d => d.IsDelete == null).ToList();
                    List <Att_Roster>      lstRosterTypeGroup = new List <Att_Roster>();
                    List <Att_RosterGroup> lstRosterGroup     = new List <Att_RosterGroup>();
                    Att_RosterServices.GetRosterGroup(lstProfileID, DateStart, DateEnd, out lstRosterTypeGroup, out lstRosterGroup);
                    //RosterDAO.GetRosterGroup(GuidContext, lstProfileIDs, DateStart, DateEnd, out lstRosterTypeGroup, out lstRosterGroup);


                    foreach (Hre_ProfileEntity profile in lstProfile)
                    {
                        List <Att_LeaveDay> lstProfileLeaveDay = lstLeaveDayAll.Where(ld => ld.ProfileID == profile.ID).ToList();
                        List <Att_InOut>    lstProfileInOut    = lstInOutAll.Where(ld => ld.ProfileID == profile.ID).ToList();
                        //Sal_Grade grade = lstGradeAll.Where(grad => grad.ProfileID == profile.ID).SingleOrDefault();
                        Att_Grade              grade            = lstAtt_Grade.Where(d => d.ProfileID == profile.ID).FirstOrDefault();
                        List <Att_Roster>      lstProfileRoster = lstRoster.Where(rt => rt.ProfileID == profile.ID).ToList();
                        List <Hre_WorkHistory> lstWHistoryPro   = lstWHistory.Where(wh => wh.ProfileID == profile.ID).ToList();
                        Cat_GradeAttendance    gradeCfg         = grade == null ? null : grade.Cat_GradeAttendance;
                        //Hashtable htRoster = RosterDAO.GetRosterTable(profile, lstProfileRoster, lstWHistoryPro, gradeCfg, DateStart, DateEnd, lstRosterGroup, lstRosterTypeGroup);
                        Hre_Profile objProfile = profile.CopyData <Hre_Profile>();
                        Hashtable   htRoster   = Att_RosterServices.GetRosterTable(objProfile, lstProfileRoster, lstWHistoryPro, gradeCfg, DateStart, DateEnd, lstRosterGroup, lstRosterTypeGroup);
                        //string[] strDepartment = GradeCfgDAO.getLinkDepartment(ListCacheOrgStructure, profile.Cat_OrgStructure);
                        //profile.udLinkDepartmentName = strDepartment[0];
                        if (grade == null)
                        {
                            continue;
                        }
                        if (grade.Cat_GradeAttendance.AttendanceMethod != AttendanceMethod.E_TAM.ToString())
                        {
                            continue;
                        }

                        for (DateTime idx = DateStart; idx <= DateEnd
                             ; idx = idx.AddDays(1))
                        {
                            // kiểm tra nếu nghỉ việc trong tháng, các ngày sau không hiển thị lên
                            if (profile.DateQuit != null && idx > profile.DateQuit.Value)
                            {
                                continue;
                            }

                            //In-Out
                            if (lstHoliday.Where(hol => hol.DateOff == idx).Count() > 0)
                            {
                                continue;
                            }

                            if (!Att_AttendanceServices.IsWorkDay(grade.Cat_GradeAttendance, htRoster, lstHoliday, idx) ||
                                idx < profile.DateHire ||
                                idx >= profile.DateQuit)
                            {
                                continue;
                            }

                            Att_RptExceptionDataEntity exceptionData       = null;
                            List <Att_InOut>           lstDateProfileInOut = lstProfileInOut.Where(inout => inout.WorkDate == idx).ToList();
                            //ko di lam, ko quet the
                            if (lstDateProfileInOut.Count <= 0)
                            {
                                //ko thong bao nghi
                                if (lstProfileLeaveDay.Where(ld => ld.ProfileID == profile.ID &&
                                                             ld.DateStart.Date <= idx && ld.DateEnd.Date >= idx).Count() <= 0)
                                {
                                    exceptionData = SetExceptionData(null, objProfile, null, idx, userExport);
                                    var OrgC = lstOrg.Where(m => m.ID == profile.OrgStructureID).FirstOrDefault();
                                    exceptionData.Department = OrgC != null ? OrgC.OrgStructureName : string.Empty;
                                    var orgSection = LibraryService.GetNearestParent(profile.OrgStructureID, OrgUnit.E_SECTION, lstOrg, orgTypes);
                                    exceptionData.Section = orgSection != null ? orgSection.OrgStructureName : string.Empty;
                                    var positon = positions.FirstOrDefault(s => s.ID == profile.PositionID);
                                    exceptionData.Position = positon != null ? positon.Code : string.Empty;
                                    //exceptionData.DataType = LanguageManager.GetString(ClassNames.Att_InOut);
                                    //exceptionData.Exception = LanguageManager.GetString(Messages.MissingInOut);
                                    exceptionData.DataType    = ("Att_InOut").TranslateString();
                                    exceptionData.Exception   = ConstantMessages.MissingInOut.TranslateString();
                                    exceptionData.Description = "? - ?";
                                    Result.Add(exceptionData);
                                }
                            }
                        }
                    }
                }
                if (DifferenceMoreRoster)
                {
                    foreach (Att_InOut InOut in lstInOutAll)
                    {
                        if (InOut.InTime != null && InOut.OutTime != null)
                        {
                            if (Difference < Att_AttendanceServices.GetShiftRosterShiftInOutHour(InOut, InOut.Cat_Shift))
                            {
                                Att_RptExceptionDataEntity exceptionData = SetExceptionData(InOut, InOut.Hre_Profile
                                                                                            , InOut.Cat_Shift, InOut.WorkDate, userExport);
                                var OrgC = lstOrg.Where(m => m.ID == InOut.Hre_Profile.OrgStructureID).FirstOrDefault();
                                exceptionData.Department = OrgC != null ? OrgC.OrgStructureName : string.Empty;
                                var orgSection = LibraryService.GetNearestParent(InOut.Hre_Profile.OrgStructureID, OrgUnit.E_SECTION, lstOrg, orgTypes);
                                exceptionData.Section = orgSection != null ? orgSection.OrgStructureName : string.Empty;
                                var positon = positions.FirstOrDefault(s => s.ID == InOut.Hre_Profile.PositionID);
                                exceptionData.Position = positon != null ? positon.Code : string.Empty;
                                //exceptionData.DataType = LanguageManager.GetString(ClassNames.Att_InOut);
                                //exceptionData.Exception = LanguageManager.GetString(Messages.DifferenceShiftRosterAndInOut) + " " + Difference + " " + LanguageManager.GetString(Messages.Hour);
                                exceptionData.DataType  = ("Att_InOut").TranslateString();
                                exceptionData.Exception = ConstantMessages.DifferenceShiftRosterAndInOut.TranslateString() + " " + Difference + " " + ConstantMessages.Hour.TranslateString();
                                String desc = "InOut: ";
                                desc += InOut.InTime.Value.ToString(ConstantFormat.HRM_Format_HourMinSecond);
                                desc += " - ";
                                desc += InOut.OutTime.Value.ToString(ConstantFormat.HRM_Format_HourMinSecond);
                                desc += " / Shift: ";
                                desc += InOut.Cat_Shift.ShiftName;

                                exceptionData.Description = desc;
                                Result.Add(exceptionData);
                            }
                        }
                    }
                }
                if (LessHours > 0)
                {
                    Double minHrs = 0;
                    //Get Hours
                    try
                    {
                        minHrs = LessHours;
                    }
                    catch (System.Exception ex)
                    {
                    }


                    List <Att_InOut> lstInOutAllLessHours = lstInOutAll.Where(d => d.InTime.HasValue && d.OutTime.HasValue).ToList();

                    foreach (Att_InOut InOut in lstInOutAllLessHours)
                    {
                        Double workHours = Att_AttendanceServices.GetInOutWorkingHour(InOut, InOut.Cat_Shift);
                        if (minHrs > workHours)
                        {
                            Att_RptExceptionDataEntity exceptionData = SetExceptionData(InOut, InOut.Hre_Profile
                                                                                        , InOut.Cat_Shift, InOut.WorkDate, userExport);
                            var OrgC = lstOrg.Where(m => m.ID == InOut.Hre_Profile.OrgStructureID).FirstOrDefault();
                            exceptionData.Department = OrgC != null ? OrgC.OrgStructureName : string.Empty;
                            var orgSection = LibraryService.GetNearestParent(InOut.Hre_Profile.OrgStructureID, OrgUnit.E_SECTION, lstOrg, orgTypes);
                            exceptionData.Section = orgSection != null ? orgSection.OrgStructureName : string.Empty;
                            var positon = positions.FirstOrDefault(s => s.ID == InOut.Hre_Profile.PositionID);
                            exceptionData.Position = positon != null ? positon.Code : string.Empty;
                            //exceptionData.DataType = LanguageManager.GetString(ClassNames.Att_InOut);
                            //exceptionData.Exception = LanguageManager.GetString(Messages.WorkingHoursLess) + " " + Difference + " " + LanguageManager.GetString(Messages.Hour);
                            exceptionData.DataType  = ("Att_InOut").TranslateString();
                            exceptionData.Exception = ConstantMessages.WorkingHoursLess.TranslateString() + " " + Difference + " " + ConstantMessages.Hour.TranslateString();
                            String desc = "";
                            desc  = InOut.InTime.Value.ToString(ConstantFormat.HRM_Format_HourMinSecond);
                            desc += " - ";
                            desc += InOut.OutTime.Value.ToString(ConstantFormat.HRM_Format_HourMinSecond);

                            exceptionData.Description = desc;
                            Result.Add(exceptionData);
                        }
                    }
                }
                if (MissInOut)
                {
                    List <Att_InOut> lstInOutAllMissInOut = lstInOutAll.Where(wd => (wd.InTime.HasValue &&
                                                                                     !wd.OutTime.HasValue)
                                                                              ||
                                                                              (!wd.InTime.HasValue &&
                                                                               wd.OutTime.HasValue)).ToList();
                    foreach (Att_InOut InOut in lstInOutAll)
                    {
                        if (InOut.InTime == null || InOut.OutTime == null)
                        {
                            Att_RptExceptionDataEntity exceptionData = SetExceptionData(InOut, InOut.Hre_Profile, InOut.Cat_Shift, InOut.WorkDate, userExport);
                            var OrgC = lstOrg.Where(m => m.ID == InOut.Hre_Profile.OrgStructureID).FirstOrDefault();
                            exceptionData.Department = OrgC != null ? OrgC.OrgStructureName : string.Empty;
                            var orgSection = LibraryService.GetNearestParent(InOut.Hre_Profile.OrgStructureID, OrgUnit.E_SECTION, lstOrg, orgTypes);
                            exceptionData.Section = orgSection != null ? orgSection.OrgStructureName : string.Empty;
                            var positon = positions.FirstOrDefault(s => s.ID == InOut.Hre_Profile.PositionID);
                            exceptionData.Position = positon != null ? positon.Code : string.Empty;
                            //exceptionData.DataType = LanguageManager.GetString(ClassNames.Att_InOut);
                            //exceptionData.Exception = LanguageManager.GetString(Messages.MissingInOut);
                            exceptionData.DataType  = ("Att_InOut").TranslateString();
                            exceptionData.Exception = ConstantMessages.MissingInOut.TranslateString();
                            String desc = "";
                            if (InOut.InTime != null)
                            {
                                desc = InOut.InTime.Value.ToString(ConstantFormat.HRM_Format_HourMinSecond);
                            }
                            else
                            {
                                desc = "?";
                            }
                            desc += " - ";
                            if (InOut.OutTime != null)
                            {
                                desc += InOut.OutTime.Value.ToString(ConstantFormat.HRM_Format_HourMinSecond);
                            }
                            else
                            {
                                desc += "?";
                            }
                            exceptionData.Description = desc;
                            Result.Add(exceptionData);
                        }
                    }
                }
                return(Result);
            }
        }