Ejemplo n.º 1
0
        public static Att_Grade GetGrade(Hre_Profile profile, DateTime effectMonth)
        {
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoAtt_Grade = new CustomBaseRepository<Att_Grade>(unitOfWork);
                //NOTE: can modify lai cau truy van de gioi han data lay len
                List<Att_Grade> lst = repoAtt_Grade
                    .FindBy(alw => alw.IsDelete == null
                        && alw.ProfileID == profile.ID
                        && alw.MonthStart <= effectMonth)
                    .OrderByDescending(alw => alw.MonthStart).ToList();

                if (lst != null && lst.Count > 0)
                {
                    // Lấy grade có ngày đến hạn, nếu không có ngày đến hạn xem như Ok không hết hạn, nếu có ngày đến hạn
                    DateTime temp = new DateTime(effectMonth.Year, effectMonth.Month, 1);
                    if (!lst[0].MonthEnd.HasValue || (lst[0].MonthEnd.HasValue && lst[0].MonthEnd.Value >= temp))
                    {
                        return lst[0];
                    }
                }
                return null;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Tính toán thời gian làm việc thực tế của nhân viên.
        /// </summary>
        /// <param name="profile"></param>
        /// <param name="listWorkDay"></param>
        /// <param name="listAllShiftItem"></param>
        /// <param name="listRosterByProfile"></param>
        /// <param name="listPregnancy"></param>
        /// <param name="gradeByProfile"></param>
        /// <returns></returns>
        public static List<WorkDay> ComputeWorkDays(Hre_Profile profile, List<Att_Workday> listInOut, List<Cat_ShiftItem> listAllShiftItem,
            List<Att_Roster> listRosterByProfile, List<Att_Pregnancy> listPregnancy, Cat_GradeAttendance gradeCfgByProfile, string userLogin)
        {
            List<WorkDay> result = new List<WorkDay>();

            if (profile != null && listInOut != null && listInOut.Count() > 0)
            {
                listInOut = listInOut.OrderBy(inout => inout.WorkDate).ThenBy(inout => inout.InTime1).ToList();
                List<DateTime> listWorkDate = listInOut.Select(d => d.WorkDate.Date).Distinct().OrderBy(d => d).ToList();

                if (listWorkDate != null && listWorkDate.Count() > 0)
                {
                    Dictionary<DateTime, Cat_OrgStructure> listOrgStructure = Att_AttendanceLib.GetDailyLines(profile,
                        listRosterByProfile, listWorkDate.FirstOrDefault(), listWorkDate.LastOrDefault());

                    foreach (DateTime workDate in listWorkDate)
                    {
                        Cat_OrgStructure orgLine = null;

                        if (listOrgStructure.ContainsKey(workDate))
                        {
                            //luôn luôn tồn tại 1 line
                            orgLine = listOrgStructure[workDate];
                        }

                        List<Att_Workday> listInOutByWorkDate = listInOut.Where(io => io.WorkDate.Date == workDate).ToList();

                        if (listInOutByWorkDate != null && listInOutByWorkDate.Count() > 0)
                        {
                            Att_Pregnancy pregnancyByWorkDay = listPregnancy.Where(d => d.DateStart != null && d.DateEnd != null
                                && d.DateStart.Value <= workDate && d.DateEnd >= workDate).FirstOrDefault();

                            List<IGrouping<Cat_Shift, Att_Workday>> listInOutGroup = listInOutByWorkDate.Where(d =>
                                d.Cat_Shift != null).GroupBy(d => d.Cat_Shift).ToList();

                            foreach (IGrouping<Cat_Shift, Att_Workday> inOutGroup in listInOutGroup)
                            {
                                List<Cat_ShiftItem> listShiftItem = listAllShiftItem.Where(it =>
                                    it.ShiftID == inOutGroup.Key.ID).ToList();

                                WorkDay workDayItem = CreateWorkDay(profile, inOutGroup.ToList(), orgLine,
                                    inOutGroup.Key, listShiftItem, pregnancyByWorkDay, gradeCfgByProfile, userLogin);

                                if (workDayItem != null)
                                {
                                    result.Add(workDayItem);
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
Ejemplo n.º 3
0
        /// <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;
            }
        }
Ejemplo n.º 4
0
        public void UpdateStatusHireCandidate(string selectedIds, string userID, string UserLogin)
        {
            using (var context = new VnrHrmDataContext())
            {
                var baseService = new BaseService();
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                string code = "";
                string status = string.Empty;
                var repoCandidate = new Rec_CandidateRepository(unitOfWork);
                var repoHistory = new Rec_RecruitmentHistoryRepository(unitOfWork);
                var repoProfile = new Hre_ProfileRepository(unitOfWork);
                var CandidateHistoryRepository = new Hre_CandidateHistoryRepository(unitOfWork);
                var lstProfile = new List<Hre_Profile>();
                List<Guid> lstIDs = selectedIds.Split(',').Select(x => Guid.Parse(x)).ToList();
                var lstCandidates = repoCandidate.FindBy(x => lstIDs.Contains(x.ID)).ToList();
                var lstRecruimentHistory = repoHistory.FindBy(m => m.CandidateID != null && lstIDs.Contains(m.CandidateID)).ToList();
                 var objs = new List<object>();
                objs.Add(1);
                objs.Add(int.MaxValue - 1);
                var lstcandidatehistory = baseService.GetData<Hre_CandidateHistory>(objs, ConstantSql.hrm_rec_sp_get_CandidateHistory, UserLogin,ref status);
                foreach (var Candidate in lstCandidates)
                {
                    string firstname = string.Empty;
                    string namefamily = string.Empty;

                    if (Candidate.CandidateName != null)
                    {
                        var col_array = Candidate.CandidateName.Split(' ');
                        for (var i = 0; i < col_array.Length; i++)
                        {
                            if (i == col_array.Length - 1)
                                firstname = col_array[i];
                            else
                                namefamily += col_array[i] + " ";
                        }
                    }

                    Candidate.StatusHire = HRM.Infrastructure.Utilities.EnumDropDown.HireStatus.E_HIRE.ToString();
                    Candidate.Status = HRM.Infrastructure.Utilities.EnumDropDown.CandidateStatus.E_HIRE.ToString();
                    Candidate.DateUpdate = DateTime.Now; 
                    Hre_Profile Profile = new Hre_Profile();
                    Profile.ID = Guid.NewGuid();
                    Profile.CandidateID = Candidate.ID;
                    Profile.ProfileName = Candidate.CandidateName;
                    Profile.FirstName = firstname;
                    Profile.NameFamily = namefamily;
                    Profile.NameEnglish = Candidate.NameEnglish;
                    Profile.ImagePath = Candidate.ImagePath;
                    Profile.StatusSyn = ProfileStatusSyn.E_WAITING.ToString();
                    Profile.CandidateID = Candidate.ID;
                    Profile.OrgStructureID = Candidate.OrgStructureID;
                    Profile.PositionID = Candidate.PositionID;
                    Profile.Gender = Candidate.Gender;
                    Profile.DateOfBirth = Candidate.DateOfBirth;
                    if (Candidate.DateOfBirth != null)
                    {
                        Profile.DayOfBirth = Candidate.DateOfBirth.Day;
                        Profile.MonthOfBirth = Candidate.DateOfBirth.Month;
                        Profile.YearOfBirth = Candidate.DateOfBirth.Year;
                    }
                    Profile.PlaceOfBirth = Candidate.PlaceOfBirth;
                    Profile.NationalityID = Candidate.NationalityID;
                    Profile.EthnicID = Candidate.EthnicID;
                    Profile.ReligionID = Candidate.ReligionID;
                    Profile.Height = Candidate.Height;
                    Profile.Weight = Candidate.Weight;
                    Profile.IDNo = Candidate.IdentifyNumber;
                    Profile.IDDateOfIssue = Candidate.IDDateOfIssue;
                    Profile.IDPlaceOfIssue = Candidate.IDPlaceOfIssue;
                    Profile.PassportNo = Candidate.PassportNo;
                    Profile.PassportDateOfExpiry = Candidate.DateExpiresPassport;
                    Profile.Email = Candidate.Email;
                    //Profile.Cellphone = Candidate.Phone;
                    Profile.PADistrictID = Candidate.PDistrictID;
                    Profile.PAddress = Candidate.PAddress;
                    Profile.TADistrictID = Candidate.TDistrictID;
                    Profile.TAddress = Candidate.TAddress;
                    Profile.JobTitleID = Candidate.JobTitleID;
                    Profile.TagID = Candidate.TagID;
                    Profile.EducationLevelID = Candidate.EducationLevelID;
                    Profile.MarriageStatus = Candidate.MarriageStatus;
                    Profile.Origin = Candidate.Origin;
                    Profile.FileAttach = Candidate.FileAttachment;
                    Profile.SikillLevel = Candidate.SkillLevel;
                    Profile.PlaceOfIssueID = Candidate.PlaceOfIssueID;
                    Profile.PlaceOfBirth = Candidate.PlaceOfBirth;
                    Profile.ReasonDeny = Candidate.ReasonDeny;
                    Profile.StatusHire = Candidate.StatusHire;
                    Profile.StatusSyn = ProfileStatusSyn.E_WAITING.ToString();
                    Profile.PassportDateOfIssue = Candidate.DateIssuePassport;
                    Profile.Cellphone = Candidate.Mobile;
                    Profile.TCountryID = Candidate.TCountryID;
                    Profile.TProvinceID = Candidate.TProvinceID;
                    Profile.TDistrictID = Candidate.TDistrictID;
                    Profile.PCountryID = Candidate.PCountryID;
                    Profile.PProvinceID = Candidate.PProvinceID;
                    Profile.PDistrictID = Candidate.PDistrictID;
                    Profile.HomePhone = Candidate.Phone;
                    Profile.Notes = Candidate.Assessment;
                    // cập nhật trạng thái của lịch sử
                    var hisbycandidate = lstRecruimentHistory.Where(s => s.CandidateID == Candidate.ID).OrderByDescending(s => s.DateApply).FirstOrDefault();
                    hisbycandidate.Status = HRM.Infrastructure.Utilities.EnumDropDown.CandidateStatus.E_HIRE.ToString();
                    var candidateHistoryByCandidate = lstcandidatehistory.Where(s => s.CandidateID == Candidate.ID).OrderByDescending(s => s.DateStart).FirstOrDefault();
                    repoProfile.Add(Profile);
                    if (candidateHistoryByCandidate != null)
                    {
                        candidateHistoryByCandidate.ProfileID = Profile.ID;
                        CandidateHistoryRepository.Edit(candidateHistoryByCandidate);
                    }
                }
                unitOfWork.SaveChanges();
                repoHistory.SaveChanges();
            }
        }
Ejemplo n.º 5
0
        public Hre_Profile AddProfileByCandidate(Rec_Candidate Candidate)
        {

            Hre_Profile Profile = new Hre_Profile();
            Profile.ID = Guid.NewGuid();
            Profile.CandidateID = Candidate.ID;
            Profile.ProfileName = Candidate.CandidateName;
            Profile.NameEnglish = Candidate.NameEnglish;
            Profile.ImagePath = Candidate.ImagePath;
            Profile.StatusSyn = ProfileStatusSyn.E_WAITING.ToString();
            Profile.CandidateID = Candidate.ID;
            Profile.OrgStructureID = Candidate.OrgStructureID;
            Profile.PositionID = Candidate.PositionID;
            Profile.Gender = Candidate.Gender;
            Profile.DateOfBirth = Candidate.DateOfBirth;
            Profile.PlaceOfBirth = Candidate.PlaceOfBirth;
            Profile.NationalityID = Candidate.NationalityID;
            Profile.EthnicID = Candidate.EthnicID;
            Profile.ReligionID = Candidate.ReligionID;
            Profile.Height = Candidate.Height;
            Profile.Weight = Candidate.Weight;
            Profile.IDNo = Candidate.IdentifyNumber;
            Profile.IDDateOfIssue = Candidate.IDDateOfIssue;
            Profile.IDPlaceOfIssue = Candidate.IDPlaceOfIssue;
            Profile.PassportNo = Candidate.PassportNo;
            Profile.PassportDateOfExpiry = Candidate.DateExpiresPassport;
            Profile.Email = Candidate.Email;
            Profile.Cellphone = Candidate.Phone;
            Profile.TCountryID = Candidate.TCountryID;
            Profile.TProvinceID = Candidate.TProvinceID;
            Profile.TDistrictID = Candidate.TDistrictID;
            Profile.PADistrictID = Candidate.PDistrictID;
            Profile.PAddress = Candidate.PAddress;
            Profile.TADistrictID = Candidate.TDistrictID;
            Profile.TAddress = Candidate.TAddress;
            Profile.PCountryID = Candidate.PCountryID;
            Profile.PProvinceID = Candidate.PProvinceID;
            Profile.PDistrictID = Candidate.PDistrictID;
            Profile.JobTitleID = Candidate.JobTitleID;
            Profile.TagID = Candidate.TagID;
            Profile.EducationLevelID = Candidate.EducationLevelID;
            Profile.MarriageStatus = Candidate.MarriageStatus;
            Profile.Origin = Candidate.Origin;
            Profile.FileAttach = Candidate.FileAttachment;
            Profile.SikillLevel = Candidate.SkillLevel;
            Profile.PlaceOfIssueID = Candidate.PlaceOfIssueID;
            Profile.PlaceOfBirth = Candidate.PlaceOfBirth;
            Profile.ReasonDeny = Candidate.ReasonDeny;
            Profile.StatusHire = Candidate.StatusHire;
            Profile.Origin = Candidate.Origin;
            Profile.PassportDateOfIssue = Candidate.DateIssuePassport;
            return Profile;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Kiểm tra chuyền làm việc hàng ngày của nhân viên
        /// </summary>
        /// <param name="profile">Nhân viên cần kiểm tra</param>
        /// <param name="listRoster">Lịch làm việc của nhân viên</param>
        /// <param name="dateFrom">Khoảng thời gian cần kiểm tra</param>
        /// <param name="dateTo">Khoảng thời gian cần kiểm tra</param>
        /// <returns></returns>
        public static Dictionary<DateTime, Cat_OrgStructure> GetDailyLines(Hre_Profile profile,
            List<Att_Roster> listRoster, DateTime dateFrom, DateTime dateTo)
        {
            Dictionary<DateTime, Cat_OrgStructure> listOrgStructure = new Dictionary<DateTime, Cat_OrgStructure>();

            if (listRoster != null && listRoster.Count() > 0 && profile != null)
            {
                listRoster = listRoster.Where(d => d != null && d.ProfileID == profile.ID
                    && d.Status == RosterStatus.E_APPROVED.ToString()).ToList();
            }

            if (listRoster != null)
            {
                #region Data roster

                List<Att_Roster> listRosterDefault = listRoster.Where(d => d.Type == RosterType.E_DEFAULT.ToString()).ToList();
                List<Att_Roster> listRosterChanged = listRoster.Where(d => d.Type == RosterType.E_CHANGE_SHIFT.ToString()).ToList();
                List<Att_Roster> listRosterOff = listRoster.Where(d => d.Type == RosterType.E_TIME_OFF.ToString()).ToList();

                #endregion

                #region Default roster

                foreach (Att_Roster roster in listRosterDefault)
                {
                    //Đối với những roster là lịch làm việc mặc định => Ưu tiên sau cùng
                    if (roster.Type == RosterType.E_DEFAULT.ToString())
                    {
                        DateTime dateStart = dateFrom;
                        DateTime dateEnd = dateTo;

                        if (roster.DateStart != null && roster.DateStart > dateFrom)
                        {
                            dateStart = roster.DateStart;
                        }

                        if (roster.DateEnd != null && roster.DateEnd < dateTo)
                        {
                            dateEnd = roster.DateEnd;
                        }

                        for (DateTime date = dateStart.Date; date <= dateEnd; date = date.AddDays(1))
                        {
                            if (roster.Cat_OrgStructure != null)
                            {
                                if (!listOrgStructure.ContainsKey(date))
                                {
                                    listOrgStructure.Add(date, roster.Cat_OrgStructure);
                                }
                            }
                        }
                    }
                }

                #endregion

                #region Changed roster

                foreach (Att_Roster roster in listRosterChanged)
                {
                    if (roster.Type == RosterType.E_CHANGE_SHIFT.ToString())
                    {
                        DateTime dateStart = dateFrom;
                        DateTime dateEnd = dateTo;

                        if (roster.DateStart != null && roster.DateStart > dateFrom)
                        {
                            dateStart = roster.DateStart;
                        }

                        if (roster.DateEnd != null && roster.DateEnd < dateTo)
                        {
                            dateEnd = roster.DateEnd;
                        }

                        //Đối với những roster là lịch làm việc sửa đổi => Ưu tiên hơn loại default
                        for (DateTime date = dateStart.Date; date <= dateEnd; date = date.AddDays(1))
                        {
                            if (roster.Cat_OrgStructure != null)
                            {
                                if (listOrgStructure.ContainsKey(date))
                                {
                                    listOrgStructure[date] = roster.Cat_OrgStructure;
                                }
                                else
                                {
                                    listOrgStructure.Add(date, roster.Cat_OrgStructure);
                                }
                            }
                        }
                    }
                }

                #endregion

                #region TimeOff roster

                foreach (Att_Roster roster in listRosterOff)
                {
                    if (roster.Type == RosterType.E_TIME_OFF.ToString())
                    {
                        DateTime dateStart = dateFrom;
                        DateTime dateEnd = dateTo;

                        if (roster.DateStart != null && roster.DateStart > dateFrom)
                        {
                            dateStart = roster.DateStart;
                        }

                        if (roster.DateEnd != null && roster.DateEnd < dateTo)
                        {
                            dateEnd = roster.DateEnd;
                        }

                        //Đối với những roster là lịch được nghỉ làm => không sử dụng, ưu tiên nhất
                        for (DateTime date = dateStart.Date; date <= dateEnd; date = date.AddDays(1))
                        {
                            if (listOrgStructure.ContainsKey(date))
                            {
                                listOrgStructure.Remove(date);
                            }
                        }
                    }
                }

                #endregion
            }

            return listOrgStructure;
        }
Ejemplo n.º 7
0
        private Att_RptExceptionDataEntity SetExceptionData(Att_InOut InOut, Hre_Profile profile, Cat_Shift shift, DateTime idx,string userExport)
        {
            Att_RptExceptionDataEntity exceptionData = new Att_RptExceptionDataEntity();
            exceptionData.ID = Guid.NewGuid();
            exceptionData.InOutID = InOut == null ? Guid.Empty : InOut.ID;
            //exceptionData.EntityType = ClassNames.Att_InOut;
            exceptionData.EntityType = "Att_InOut";
            exceptionData.CodeEmp = profile.CodeEmp;
            exceptionData.ShiftID = shift == null ? Guid.Empty : shift.ID;
            exceptionData.ProfileID = profile.ID;
            exceptionData.ProfileName = profile.ProfileName;
            exceptionData.UserExport = userExport;
            exceptionData.DateExport = DateTime.Today;

            //exceptionData.Position = profile.Cat_Position == null ? string.Empty : profile.Cat_Position.PositionName;

            //string[] strDepartment = GradeCfgDAO.getLinkDepartment(ListCacheOrgStructure, profile.Cat_OrgStructure, true);
            //exceptionData.Department = strDepartment[1];

            exceptionData.Date = idx;
            return exceptionData;
        }
Ejemplo n.º 8
0
        public List<Sal_SalaryDepartmentItem> CalSalaryLineItemProfile(Sal_SalaryDepartment salDepartment, List<Att_AttendanceTableItem> lstAttItemPro, Hre_Profile pro,
                                                                             List<Sal_BasicSalary> lstBasicSalPro, List<Att_Roster> lstRosterPro, DateTime dfrom, DateTime dto, DateTime monthYear,
                                                                             Sal_SalaryDepartmentItem itemProAdd)
        {
            List<Sal_SalaryDepartmentItem> lstItem = new List<Sal_SalaryDepartmentItem>();
            Double ratePer = 0;

            //Lấy hệ số trong lương cơ bản
            Sal_BasicSalary basSal = new Sal_BasicSalary();
            if (lstBasicSalPro.Count == 2)
                basSal = lstBasicSalPro[1];
            else if (lstBasicSalPro.Count == 1)
                basSal = lstBasicSalPro[0];

            if (ratePer != basSal.PersonalRate)
            {
                ratePer = basSal.PersonalRate != null ? basSal.PersonalRate.Value : 0;
                Sal_SalaryDepartmentItem depItem = null;

                string stFIX = EnumDropDown.StatusLoadEnumSalDepartItem.E_FIX.ToString();
                string stEDIT_FIX = EnumDropDown.StatusLoadEnumSalDepartItem.E_EDIT_FIX.ToString();
                if (itemProAdd != null && itemProAdd.ID.ToString() != Guid.Empty.ToString() && itemProAdd.Status != stFIX && itemProAdd.Status != stEDIT_FIX)
                {
                    depItem = itemProAdd;
                }
                else
                {
                    depItem = new Sal_SalaryDepartmentItem();
                }
                depItem.Sal_SalaryDepartment = salDepartment;
                depItem.DateFrom = dfrom;
                depItem.DateTo = dto;
                depItem.ProfileID = pro.ID;
                depItem.Rate = ratePer;
                if (itemProAdd != null)
                    depItem.Status = itemProAdd.Status;

                for (DateTime idx = dfrom; idx <= dto; idx = idx.AddDays(1))
                {
                    //(3.Use general: Insert chi tiết --> Gần Finished)
                    depItem = SetItemSalDep(depItem, lstAttItemPro, idx);
                }

                //AppConfig
                var service = new Sys_AttOvertimePermitConfigServices();
                var value56 =  service.GetConfigValue<string>(AppConfig.HRM_SAL_CONFIG_VALUE56);
                var value57 =  service.GetConfigValue<string>(AppConfig.HRM_SAL_CONFIG_VALUE57);
                var value58 =  service.GetConfigValue<string>(AppConfig.HRM_SAL_CONFIG_VALUE58);

                //Nếu có check áp dụng trừ số giờ cho nữ
                string gender = EnumDropDown.Gender.E_FEMALE.ToString();
                if (value56.ToLower() == true.ToString().ToLower() && pro.Gender == gender)
                {
                    if (!value57.IsNullOrEmpty() && !value58.IsNullOrEmpty())
                    {
                        double hoursub = Convert.ToDouble(value57);
                        double daywork = Convert.ToDouble(value58);
                        if (hoursub > 0 && daywork > 0)
                        {
                            var lstAttItem = lstAttItemPro.Where(p => p.IsHavingPregTreatment == true).ToList();
                            //Nếu nhân viên không có thai sản
                            if (lstAttItem.Count <= 0)
                            {
                                if (depItem.PaidWorkHours / 8 > daywork)
                                    depItem.PaidWorkHours = depItem.PaidWorkHours - hoursub;
                            }
                        }
                    }
                }
                lstItem.Add(depItem);
            }
            return lstItem;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Lay Line trong DS roster trong khoang thoi gian. so sanh theo ngay End. Neu End ko co thi lay tru di tung ngay
        /// </summary>
        /// <param name="profile"></param>
        /// <param name="lstRoster"></param>
        /// <param name="dateStart"></param>
        /// <param name="dateEnd"></param>
        /// <returns></returns>
        public static string GetLineInRoster(Hre_Profile profile, List<Att_Roster> lstRoster, DateTime dateStart, DateTime dateEnd)
        {
            String strLine = String.Empty;
            List<Att_Roster> lstRosterRange = lstRoster.Where(roster => roster.DateStart <= dateEnd && roster.DateEnd >= dateStart).ToList();
            List<Att_Roster> lstProfileRoster = lstRosterRange.Where(rt => rt.ProfileID == profile.ID).ToList();
            DateTime timeLineNow = dateEnd.Date;
            List<Att_Roster> lstRosterLine = lstProfileRoster.Where(p => p.DateStart <= timeLineNow && p.DateEnd >= timeLineNow).OrderByDescending(p => p.DateUpdate).ToList();

            //Neu ngay timeLineNow khong co roster thi tru di 1 ngay
            while (lstRosterLine.Count <= 0 && timeLineNow >= dateStart)
            {
                timeLineNow = timeLineNow.AddDays(-1);
                lstRosterLine = lstProfileRoster.Where(p => p.DateStart <= timeLineNow && p.DateEnd >= timeLineNow).OrderByDescending(p => p.DateUpdate).ToList();
            }

            if (lstRosterLine.Count > 0)
                strLine = lstRosterLine[0].Cat_OrgStructure == null ? string.Empty : lstRosterLine[0].Cat_OrgStructure.OrgStructureName;
            return strLine;
        }
Ejemplo n.º 10
0
        /// <summary>      
        /// Lay luong trung binh dong BH 6 thang gan nhat
        /// </summary>
        /// <param name="monthYear">ngay 15</param>
        /// <param name="pro"></param>
        /// <returns></returns>
        public static Double GetAmountInsuranceSixMonth(Hre_Profile pro, DateTime monthYear, DateTime monthJoin, Double AmountMaxIns, List<Sal_BasicSalary> lstSal, List<Cat_ExchangeRate> listRateInsurance, String typeRecord)
        {
            Double _amount = 0;
            DateTime monthYearIns = new DateTime();
            int month = 0;
            //Lay thang lien ke
            //Nghi trong thang nao tinh thang do ko tinh ngay 15
            monthYearIns = new DateTime(monthYear.AddMonths(-1).Year
                                            , monthYear.AddMonths(-1).Month
                                            , PeriodInsuranceDayCurrentMonthDefault);

            if (typeRecord == InsuranceRecordType.E_PREGNANCY_EXAMINE.ToString()
            || typeRecord == InsuranceRecordType.E_PREGNANCY_LOST.ToString()
            || typeRecord == InsuranceRecordType.E_PREGNANCY_PREVENTION.ToString())
            {
                //LamLe- Update luat moi neu sinh con 1-15 thi tinh 6 thang lien ke - Neu sinh con 16-cuối tháng tinh 6 thang bat dau tu thang sinh con.
                // cac loaij lien tuan den thai san thi ap dung ngay 15
                if (monthYear.Day >= PeriodInsuranceDayCurrentMonthDefault)
                    monthYearIns = new DateTime(monthYear.Year
                                                , monthYear.Month
                                                , PeriodInsuranceDayCurrentMonthDefault);
            }
            if (typeRecord == InsuranceRecordType.E_PREGNANCY_SUCKLE.ToString())
            {
                //LamLe- Update luat moi neu sinh con 1-15 thi tinh 6 thang lien ke - Neu sinh con 16-cuối tháng tinh 6 thang bat dau tu thang sinh con.
                //Loai nghi sanh thi ap  dung ngay 16
                if (monthYear.Day > PeriodInsuranceDayCurrentMonthDefault)
                    monthYearIns = new DateTime(monthYear.Year
                                                , monthYear.Month
                                                , PeriodInsuranceDayCurrentMonthDefault);
            }

            //Kiem tra thoi gian dong bao hiem co lon hon 6 thang.
            DateTime monthSix = new DateTime(monthYearIns.AddMonths(-6).Year
                                            , monthYearIns.AddMonths(-6).Month
                                            , PeriodInsuranceDayCurrentMonthDefault);
            monthJoin = new DateTime(monthJoin.Year
                                     , monthJoin.Month
                                            , PeriodInsuranceDayCurrentMonthDefault);
            if (monthSix.Date.CompareTo(monthJoin.Date) < 0)
            {
                for (DateTime dx = monthJoin; dx <= monthYearIns; dx = new DateTime(dx.AddMonths(1).Year
                                                                           , dx.AddMonths(1).Month
                                                                           , PeriodInsuranceDayCurrentMonthDefault))
                {
                    month += 1;
                }
            }
            else
                month = 6;
            //lstSal = lstSal.Where(sal => sal.DateOfEffect > minMonthYear && ).ToList();
            lstSal = lstSal.Where(sal => sal.DateOfEffect <= monthYearIns).OrderByDescending(pit => pit.DateOfEffect).ToList();
            for (int i = 0; i < month; i++)
            {
                DateTime dateMonth = new DateTime(monthYearIns.AddMonths(-i).Year
                                            , monthYearIns.AddMonths(-i).Month
                                            , PeriodInsuranceDayCurrentMonthDefault);
                DateTime dateMaxSal = DateTime.MinValue;
                Sal_BasicSalary salMonth = new Sal_BasicSalary();
                foreach (Sal_BasicSalary sal in lstSal)
                {
                    if (sal.DateOfEffect > dateMaxSal && sal.DateOfEffect <= dateMonth)
                    {
                        dateMaxSal = sal.DateOfEffect;
                        salMonth = sal;
                    }
                }
                Double amountIns = salMonth.InsuranceAmount;
                Cat_Currency curIns = salMonth.Cat_Currency1;
                if (curIns != null && curIns.Code != CurrencyCode.VND.ToString())
                    amountIns = Sal_PayrollLib.ConvertExtractRateToVND(amountIns, curIns, listRateInsurance);

                if (amountIns > AmountMaxIns)
                {
                    _amount += AmountMaxIns;
                }
                else
                {
                    _amount += amountIns;
                }

            }
            return _amount / month;

        }
Ejemplo n.º 11
0
        private static WorkDay CreateWorkDay(Hre_Profile profile, List<Att_Workday> listInOutByWorkDate, Cat_OrgStructure orgLine,
            Cat_Shift shift, List<Cat_ShiftItem> listShiftItem, Att_Pregnancy pregnancyByWorkDay, Cat_GradeAttendance graCfgPro, string userLogin)
        {
            WorkDay result = null;

            listInOutByWorkDate = listInOutByWorkDate.Where(d => d.InTime1 != null
                && d.OutTime1 != null).OrderBy(d => d.WorkDate).ThenBy(d => d.InTime1).ToList();

            if (listInOutByWorkDate != null && listInOutByWorkDate.Count() > 0)
            {
                #region Khởi tạo

                result = new WorkDay();
                result.Cat_Shift = shift;
                result.WorkDuration = 0D;

                result.WorkDate = listInOutByWorkDate.Select(d => d.WorkDate).FirstOrDefault();//ngày làm việc
                DateTime timeShiftStart = result.WorkDate.Date.Add(shift.InTime.TimeOfDay);//thời gian bắt đầu của ca làm việc
                DateTime timeShiftEnd = timeShiftStart.AddHours(shift.CoOut);////thời gian kết thúc của ca làm việc (date + time)
                double totalTimeShift = timeShiftEnd.Subtract(timeShiftStart).TotalHours;

                //LamLe - 20121017 - Lay gio lam viec trong grade hay trong Shift
                double workingStandardHour = graCfgPro.GetWorkHouPerDay(result.WorkDate);
                //if (shift != null && graCfgPro != null && graCfgPro.WorkHoursType == GradeHoursType.E_SHIFT_HOURS.ToString())
                if (shift != null && graCfgPro != null)
                {
                    workingStandardHour = shift.WorkHours != null ? shift.WorkHours.Value : 0D;
                }

                listShiftItem = listShiftItem.Where(sh => sh.ShiftItemType == ShiftItemType.E_SHIFTBREAK.ToString()).OrderBy(p => p.CoFrom).ToList();
                Guid? lineID = orgLine != null ? orgLine.ID : profile.OrgStructureID;//LamLe - 20121030 - Xu ly truong hop co Line org trong Roster
                Cat_ShiftItem shiftItemFlex = listShiftItem.Where(p => p.OrgStructureID == lineID).FirstOrDefault();

                double realCoBreakStart = 0D;
                double realCoBreakEnd = 0D;

                //Vinhtran: Kiểm tra có giờ nghỉ giữa ca làm việc hay không?
                if (shift.ShiftBreakType == ShiftBreakType.E_FLEXIBLE.ToString() && totalTimeShift > workingStandardHour
                    && shiftItemFlex != null && shiftItemFlex.CoFrom > 0 && shiftItemFlex.CoTo > shiftItemFlex.CoFrom)
                {
                    if (!shift.IsBreakAsWork.HasValue || !shift.IsBreakAsWork.Value)
                    {
                        shift.udCoBreakStart = shiftItemFlex.CoFrom;
                        shift.udCoBreakEnd = shiftItemFlex.CoTo;
                    }

                    realCoBreakStart = shiftItemFlex.CoFrom;
                    realCoBreakEnd = shiftItemFlex.CoTo;
                }
                else if (shift.CoBreakIn > 0 && shift.CoBreakOut > shift.CoBreakIn)
                {
                    if (!shift.IsBreakAsWork.HasValue || !shift.IsBreakAsWork.Value)
                    {
                        shift.udCoBreakStart = shift.CoBreakIn;
                        shift.udCoBreakEnd = shift.CoBreakOut;
                    }

                    realCoBreakStart = shift.CoBreakIn;
                    realCoBreakEnd = shift.CoBreakOut;
                }

                if (realCoBreakEnd > realCoBreakStart)
                {
                    totalTimeShift -= realCoBreakEnd - realCoBreakStart;
                }

                //Thời gian bắt đầu và kết thúc nghỉ giữa ca - dùng cho tính toán
                DateTime timeShiftBreakIn = timeShiftStart.AddHours(shift.udCoBreakStart);
                DateTime timeShiftBreakOut = timeShiftStart.AddHours(shift.udCoBreakEnd);

                //Khoảng thời gian của nửa ca đầu
                DateTime firstHalfShiftStart = timeShiftStart;
                DateTime firstHalfShiftEnd = timeShiftEnd;

                //Khoảng thời gian của nửa ca sau
                DateTime lastHalfShiftStart = timeShiftStart;
                DateTime lastHalfShiftEnd = timeShiftEnd;

                if (shift.udCoBreakEnd > shift.udCoBreakStart
                    && shift.udCoBreakStart > 0)
                {
                    firstHalfShiftStart = timeShiftStart;
                    firstHalfShiftEnd = timeShiftBreakIn;

                    lastHalfShiftStart = timeShiftBreakOut;
                    lastHalfShiftEnd = timeShiftEnd;
                }

                if (timeShiftBreakIn > timeShiftStart && listInOutByWorkDate.Count() > 1)
                {
                    //Lần quẹt thẻ vào đầu tiên và lần quẹt thẻ ra cuối cùng của nửa ca đâu 
                    if (listInOutByWorkDate.Any(d => d.InTime1 < timeShiftBreakIn))
                    {
                        result.FirstInTime = listInOutByWorkDate.Where(d => d.InTime1 < timeShiftBreakIn).OrderBy(d => d.WorkDate).ThenBy(d => d.InTime1).Select(d => d.InTime1.Value).FirstOrDefault();
                        result.FirstOutTime = listInOutByWorkDate.Where(d => d.InTime1 < timeShiftBreakIn).OrderBy(d => d.WorkDate).ThenBy(d => d.OutTime1).Select(d => d.OutTime1.Value).LastOrDefault();
                    }
                    else
                    {
                        result.FirstInTime = listInOutByWorkDate.OrderBy(d => d.WorkDate).ThenBy(d => d.InTime1).Select(d => d.InTime1.Value).FirstOrDefault();
                        result.FirstOutTime = listInOutByWorkDate.OrderBy(d => d.WorkDate).ThenBy(d => d.OutTime1).Select(d => d.OutTime1.Value).FirstOrDefault();
                    }

                    //Lần quẹt thẻ vào đầu tiên và lần quẹt thẻ ra cuối cùng của nửa ca sau 
                    if (listInOutByWorkDate.Any(d => d.OutTime1 > timeShiftBreakOut))
                    {
                        result.LastInTime = listInOutByWorkDate.Where(d => d.OutTime1 > timeShiftBreakOut).OrderBy(d => d.WorkDate).ThenBy(d => d.InTime1).Select(d => d.InTime1.Value).FirstOrDefault();
                        result.LastOutTime = listInOutByWorkDate.Where(d => d.OutTime1 > timeShiftBreakOut).OrderBy(d => d.WorkDate).ThenBy(d => d.OutTime1).Select(d => d.OutTime1.Value).LastOrDefault();
                    }
                    else
                    {
                        result.LastInTime = listInOutByWorkDate.OrderBy(d => d.WorkDate).ThenBy(d => d.InTime1).Select(d => d.InTime1.Value).LastOrDefault();
                        result.LastOutTime = listInOutByWorkDate.OrderBy(d => d.WorkDate).ThenBy(d => d.OutTime1).Select(d => d.OutTime1.Value).LastOrDefault();
                    }
                }
                else
                {
                    //Lần quẹt thẻ vào đầu tiên và lần quẹt thẻ ra cuối cùng của nửa ca đâu 
                    result.FirstInTime = listInOutByWorkDate.OrderBy(d => d.WorkDate).ThenBy(d => d.InTime1).Select(d => d.InTime1.Value).FirstOrDefault();
                    result.FirstOutTime = listInOutByWorkDate.OrderBy(d => d.WorkDate).ThenBy(d => d.OutTime1).Select(d => d.OutTime1.Value).LastOrDefault();

                    //Lần quẹt thẻ vào đầu tiên và lần quẹt thẻ ra cuối cùng của nửa ca sau 
                    result.LastInTime = listInOutByWorkDate.OrderBy(d => d.WorkDate).ThenBy(d => d.InTime1).Select(d => d.InTime1.Value).FirstOrDefault();
                    result.LastOutTime = listInOutByWorkDate.OrderBy(d => d.WorkDate).ThenBy(d => d.OutTime1).Select(d => d.OutTime1.Value).LastOrDefault();
                }

                DateTime nightTimeStart = result.WorkDate.Date.AddHours(21);
                DateTime nightTimeEnd = result.WorkDate.Date.AddDays(1).AddHours(5);

                double nightDuration = 0D;
                double firstDuration = 0D;
                double lastDuration = 0D;

                if (shift.IsNightShift)
                {
                    if (shift.NightTimeStart == null || shift.NightTimeEnd == null)
                    {
                        string appConfigName = AppConfig.HRM_ATT_OT_.ToString();
                        double startHour = 21D;
                        double endHour = 5D;

                        List<object> lstParamSys = new List<object>();
                        lstParamSys.Add(appConfigName);
                        lstParamSys.Add(null);
                        lstParamSys.Add(null);
                        string status = string.Empty;
                        BaseService baseService = new BaseService();
                        var lstAppConfig = baseService.GetData<Sys_AllSetting>(lstParamSys, ConstantSql.hrm_sys_sp_get_AllSetting, userLogin, ref status);

                        Sys_AllSetting appConfig13 = lstAppConfig.Where(s => s.IsDelete == null && s.Name == AppConfig.HRM_ATT_OT_NIGHTSHIFTFROM.ToString()).FirstOrDefault();
                        Sys_AllSetting appConfig14 = lstAppConfig.Where(s => s.IsDelete == null && s.Name == AppConfig.HRM_ATT_OT_NIGHTSHIFTTO.ToString()).FirstOrDefault();
                        //Sys_AppConfig appConfig = EntityService.Instance.GetEntityList<Sys_AppConfig>(false,
                        //    EntityService.Instance.GuidMainContext, Guid.Empty, d => d.Info == appConfigName).FirstOrDefault();

                        if (lstAppConfig != null && appConfig13 != null && appConfig14 != null)
                        {
                            double.TryParse(appConfig13.Value1, out startHour);
                            double.TryParse(appConfig14.Value1, out endHour);
                        }

                        nightTimeStart = shift.NightTimeStart == null ? result.WorkDate.Date.AddHours(startHour) : result.WorkDate.Date.Add(shift.NightTimeStart.Value.TimeOfDay);
                        nightTimeEnd = shift.NightTimeEnd == null ? result.WorkDate.Date.AddHours(endHour) : result.WorkDate.Date.Add(shift.NightTimeEnd.Value.TimeOfDay);
                    }
                    else
                    {
                        nightTimeStart = result.WorkDate.Date.Add(shift.NightTimeStart.Value.TimeOfDay);
                        nightTimeEnd = result.WorkDate.Date.Add(shift.NightTimeEnd.Value.TimeOfDay);
                    }

                    nightTimeEnd = nightTimeStart > nightTimeEnd ? nightTimeEnd.AddDays(1) : nightTimeEnd;
                }

                #endregion

                foreach (Att_Workday objInOut in listInOutByWorkDate)
                {
                    if (objInOut.InTime1.HasValue && objInOut.OutTime1.HasValue)
                    {
                        #region Tính work duration

                        DateTime inTime = objInOut.InTime1.Value;
                        DateTime outTime = objInOut.OutTime1.Value;

                        firstDuration += GetIntersectAmountMinutes(inTime, outTime, firstHalfShiftStart, firstHalfShiftEnd);

                        if (timeShiftBreakIn > timeShiftStart)
                        {
                            //Nếu có giờ nghỉ giữa ca
                            lastDuration += GetIntersectAmountMinutes(inTime, outTime, lastHalfShiftStart, lastHalfShiftEnd);
                        }

                        #endregion

                        #region Tính night shift

                        if (shift.IsNightShift)
                        {
                            if (pregnancyByWorkDay != null)
                            {
                                if ((pregnancyByWorkDay.TypePregnancyEarly == PregnancyLeaveEarlyType.E_FIRST.ToString()
                                    || pregnancyByWorkDay.TypePregnancyEarly == PregnancyLeaveEarlyType.E_FIRST_OUT_BEARK.ToString())
                                    && Common.IsOverlap(inTime, outTime, nightTimeStart, nightTimeEnd))
                                {
                                    nightTimeStart = nightTimeStart.AddHours(1);
                                }
                                else if ((pregnancyByWorkDay.TypePregnancyEarly == PregnancyLeaveEarlyType.E_LAST.ToString()
                                    || pregnancyByWorkDay.TypePregnancyEarly == PregnancyLeaveEarlyType.E_LAST_IN_BEARK.ToString())
                                    && Common.IsOverlap(inTime, outTime, nightTimeStart, nightTimeEnd))
                                {
                                    nightTimeEnd = nightTimeEnd.AddHours(-1);
                                }
                            }

                            //Truong hop nghi giua ca nam trong khoang bat dau ca dem
                            if (nightTimeStart >= timeShiftBreakIn && nightTimeStart <= timeShiftBreakOut)
                            {
                                nightDuration += GetIntersectAmountMinutes(inTime, outTime, timeShiftBreakOut, nightTimeEnd);
                            }
                            else if (nightTimeEnd >= timeShiftBreakIn && nightTimeEnd <= timeShiftBreakOut)
                            {
                                nightDuration += GetIntersectAmountMinutes(inTime, outTime, nightTimeStart, timeShiftBreakIn);
                            }
                            else if (nightTimeEnd > timeShiftBreakOut && nightTimeStart < timeShiftBreakIn)
                            {
                                nightDuration += GetIntersectAmountMinutes(inTime, outTime, nightTimeStart, timeShiftBreakIn);
                                nightDuration += GetIntersectAmountMinutes(inTime, outTime, timeShiftBreakOut, nightTimeEnd);
                            }
                            else
                            {
                                nightDuration += GetIntersectAmountMinutes(inTime, outTime, nightTimeStart, nightTimeEnd);
                            }
                        }

                        #endregion
                    }
                }

                if (shift.ReduceNightShift != null && shift.ReduceNightShift >= 0)
                {
                    Int32 reduceNightMinutes = Convert.ToInt32(shift.ReduceNightShift.Value * 60);
                    nightDuration = nightDuration > reduceNightMinutes ? reduceNightMinutes : nightDuration;
                }

                nightDuration = nightDuration > 0 ? nightDuration / 60 : 0D;
                firstDuration = firstDuration > 0 ? firstDuration / 60 : 0D;
                lastDuration = lastDuration > 0 ? lastDuration / 60 : 0D;

                //Vinhtran: Tổng thời gian làm việc - tính theo giờ
                result.WorkDuration = firstDuration + lastDuration;
                result.NightShiftDuration = nightDuration;
                result.FirstDuration = firstDuration;
                result.LastDuration = lastDuration;

                if (result.WorkDuration > workingStandardHour)
                {
                    result.WorkDuration = workingStandardHour;
                }
                if (result.NightShiftDuration > workingStandardHour)
                {
                    result.NightShiftDuration = workingStandardHour;
                }

                if (shift.IsDoubleShift.Get_Boolean())
                {
                    //Vinh.Tran: Xử lý trường hợp ca ghép
                    totalTimeShift = shift.WorkHours.Get_Double();
                }

                //Vinhtran: Tổng thời gian bị đi trễ hoặc về sớm - tính theo giờ
                result.LateEarlyDuration = totalTimeShift - result.WorkDuration;

                #region Tính trễ sớm

                //Có đi trễ hoặc về sớm
                if (result.LateEarlyDuration > 0)
                {
                    if (timeShiftBreakIn > timeShiftStart)
                    {
                        if (result.FirstInTime > firstHalfShiftStart && result.FirstInTime < firstHalfShiftEnd)
                        {
                            //thời gian đi trễ nửa ca đầu
                            result.FirstLateDuration = result.FirstInTime.Value.Subtract(firstHalfShiftStart).TotalHours;
                        }

                        if (result.LastInTime > lastHalfShiftStart)
                        {
                            //thời gian đi trễ nửa ca sau
                            result.LastLateDuration = result.LastInTime.Value.Subtract(lastHalfShiftStart).TotalHours;
                        }

                        result.FirstEarlyDuration = firstHalfShiftEnd.Subtract(firstHalfShiftStart).TotalHours - firstDuration - result.FirstLateDuration;
                        result.LastEarlyDuration = lastHalfShiftEnd.Subtract(lastHalfShiftStart).TotalHours - lastDuration - result.LastLateDuration;

                        result.LateDuration = result.FirstLateDuration + result.LastLateDuration;
                        result.EarlyDuration = result.FirstEarlyDuration + result.LastEarlyDuration;
                    }
                    else
                    {
                        if (result.FirstInTime > timeShiftStart)
                        {
                            //thời gian đi trễ nửa ca đầu
                            result.LateDuration = result.FirstInTime.Value.Subtract(timeShiftStart).TotalHours;
                            result.FirstLateDuration = result.LateDuration;
                            result.LastLateDuration = 0;
                        }

                        result.EarlyDuration = timeShiftEnd.Subtract(timeShiftStart).TotalHours - result.WorkDuration - result.LateDuration;
                        result.FirstEarlyDuration = result.EarlyDuration;
                        result.LastEarlyDuration = 0;
                    }

                    if (pregnancyByWorkDay != null)
                    {
                        //Thời gian làm việc lớn nhất có thể xảy ra
                        double maxWorkDuration = totalTimeShift - result.LateEarlyDuration + 1;
                        maxWorkDuration += shift.IsDoubleShift.Get_Boolean() ? 1 : 0;//Ca ghép thì thêm 1 giờ
                        maxWorkDuration = maxWorkDuration > totalTimeShift ? totalTimeShift : maxWorkDuration;

                        if (pregnancyByWorkDay.TypePregnancyEarly == PregnancyLeaveEarlyType.E_FIRST.ToString())
                        {
                            //Chỉ được đi trễ 1 giờ đầu của nửa ca trước, không được về sớm trong nữa ca đầu.
                            result.WorkDuration += result.FirstLateDuration <= 1 ? result.FirstLateDuration : 1;
                            result.FirstLateDuration = result.FirstLateDuration <= 1 ? 0 : result.FirstLateDuration - 1;

                            if (shift.IsDoubleShift.Get_Boolean())
                            {
                                result.WorkDuration += result.LastLateDuration <= 1 ? result.LastLateDuration : 1;
                                result.LastLateDuration = result.LastLateDuration <= 1 ? 0 : result.LastLateDuration - 1;
                                result.LateDuration = result.LateDuration <= 2 ? 0 : result.LateDuration - 2;
                            }
                            else
                            {
                                result.LateDuration = result.LateDuration <= 1 ? 0 : result.LateDuration - 1;
                            }

                            result.WorkDuration = result.WorkDuration > maxWorkDuration ? maxWorkDuration : result.WorkDuration;
                        }
                        else if (pregnancyByWorkDay.TypePregnancyEarly == PregnancyLeaveEarlyType.E_FIRST_OUT_BEARK.ToString())
                        {
                            //Được đi trễ hoặc về sớm 1 giờ bất kỳ của nửa ca trước, nếu là ca ghép thì được 1 tiếng trễ sớm ở mỗi ca (tổng là 2 tiếng)
                            double firstLatetEarly = timeShiftBreakIn > timeShiftStart ? result.FirstLateDuration + result.FirstEarlyDuration : result.LateDuration + result.EarlyDuration;
                            double lastLatetEarly = (shift.IsDoubleShift.Get_Boolean() && timeShiftBreakIn > timeShiftStart) ? result.LastLateDuration + result.LastEarlyDuration : 0;
                            double totalLatetEarly = firstLatetEarly + lastLatetEarly;

                            if (shift.IsDoubleShift.Get_Boolean())
                            {
                                result.WorkDuration += totalLatetEarly <= 2 ? totalLatetEarly : 2;
                                result.LateDuration = result.LateDuration <= 2 ? 0 : result.LateDuration - 2;
                            }
                            else
                            {
                                result.WorkDuration += totalLatetEarly <= 1 ? totalLatetEarly : 1;
                                result.LateDuration = result.LateDuration <= 1 ? 0 : result.LateDuration - 1;
                            }

                            if (timeShiftBreakIn > timeShiftStart)
                            {
                                result.FirstLateDuration = result.FirstLateDuration <= 1 ? 0 : result.FirstLateDuration - 1;
                                result.FirstEarlyDuration = firstLatetEarly - result.FirstLateDuration;

                                if (shift.IsDoubleShift.Get_Boolean())
                                {
                                    result.LastLateDuration = result.LastLateDuration <= 1 ? 0 : result.LastLateDuration - 1;
                                    result.LastEarlyDuration = lastLatetEarly - result.LastLateDuration;
                                }
                            }

                            result.EarlyDuration = totalLatetEarly - result.LateDuration;
                        }
                        else if (pregnancyByWorkDay.TypePregnancyEarly == PregnancyLeaveEarlyType.E_LAST_IN_BEARK.ToString())
                        {
                            //Được đi trễ hoặc về sớm 1 giờ bất kỳ của nửa ca sau, nếu là ca ghép thì được 1 tiếng trễ sớm ở mỗi ca (tổng là 2 tiếng)
                            double lastLatetEarly = timeShiftBreakIn > timeShiftStart ? result.LastLateDuration + result.LastEarlyDuration : result.LateDuration + result.EarlyDuration;
                            double firstLatetEarly = (shift.IsDoubleShift.Get_Boolean() && timeShiftBreakIn > timeShiftStart) ? result.FirstLateDuration + result.FirstEarlyDuration : 0;
                            double totalLatetEarly = firstLatetEarly + lastLatetEarly;

                            if (shift.IsDoubleShift.Get_Boolean())
                            {
                                result.WorkDuration += totalLatetEarly <= 2 ? totalLatetEarly : 2;
                                result.LateDuration = result.LateDuration <= 2 ? 0 : result.LateDuration - 2;
                            }
                            else
                            {
                                result.WorkDuration += totalLatetEarly <= 1 ? totalLatetEarly : 1;
                                result.LateDuration = result.LateDuration <= 1 ? 0 : result.LateDuration - 1;
                            }

                            if (timeShiftBreakIn > timeShiftStart)
                            {
                                result.LastLateDuration = result.LastLateDuration <= 1 ? 0 : result.LastLateDuration - 1;
                                result.LastEarlyDuration = lastLatetEarly - result.LastLateDuration;

                                if (shift.IsDoubleShift.Get_Boolean())
                                {
                                    result.FirstLateDuration = result.FirstLateDuration <= 1 ? 0 : result.FirstLateDuration - 1;
                                    result.FirstEarlyDuration = firstLatetEarly - result.FirstLateDuration;
                                }
                            }

                            result.EarlyDuration = totalLatetEarly - result.LateDuration;
                        }
                        else if (pregnancyByWorkDay.TypePregnancyEarly == PregnancyLeaveEarlyType.E_LAST.ToString())
                        {
                            //Chỉ được về sớm 1 giờ cuối của nửa ca trước, không được đi trễ trong nữa ca sau.
                            if (timeShiftBreakIn > timeShiftStart)
                            {
                                result.WorkDuration += result.LastEarlyDuration <= 1 ? result.LastEarlyDuration : 1;
                                result.LastEarlyDuration = result.LastEarlyDuration <= 1 ? 0 : result.LastEarlyDuration - 1;

                                if (shift.IsDoubleShift.Get_Boolean())
                                {
                                    result.WorkDuration += result.FirstEarlyDuration <= 1 ? result.FirstEarlyDuration : 1;
                                    result.FirstEarlyDuration = result.FirstEarlyDuration <= 1 ? 0 : result.FirstEarlyDuration - 1;
                                }
                            }
                            else
                            {
                                if (shift.IsDoubleShift.Get_Boolean())
                                {
                                    result.WorkDuration += result.EarlyDuration <= 2 ? result.EarlyDuration : 2;
                                }
                                else
                                {
                                    result.WorkDuration += result.EarlyDuration <= 1 ? result.EarlyDuration : 1;
                                }
                            }

                            if (shift.IsDoubleShift.Get_Boolean())
                            {
                                result.EarlyDuration = result.EarlyDuration <= 2 ? 0 : result.EarlyDuration - 2;
                            }
                            else
                            {
                                result.EarlyDuration = result.EarlyDuration <= 1 ? 0 : result.EarlyDuration - 1;
                            }

                            result.WorkDuration = result.WorkDuration > maxWorkDuration ? maxWorkDuration : result.WorkDuration;
                        }
                    }
                }

                #endregion

                //Vinhtran: Tổng thời gian bị đi trễ hoặc về sớm - tính theo phút
                result.LateDuration = result.LateDuration > 0 ? result.LateDuration * 60 : 0D;
                result.EarlyDuration = result.EarlyDuration > 0 ? result.EarlyDuration * 60 : 0D;
                result.FirstLateDuration = result.FirstLateDuration > 0 ? result.FirstLateDuration * 60 : 0D;
                result.FirstEarlyDuration = result.FirstEarlyDuration > 0 ? result.FirstEarlyDuration * 60 : 0D;
                result.LastLateDuration = result.LastLateDuration > 0 ? result.LastLateDuration * 60 : 0D;
                result.LastEarlyDuration = result.LastEarlyDuration > 0 ? result.LastEarlyDuration * 60 : 0D;
                result.LateEarlyDuration = result.LateEarlyDuration > 0 ? result.LateEarlyDuration * 60 : 0D;

                //Vinhtran: Tổng thời gian (h) làm ca đêm lớn nhất có thể => làm tròn trễ sớm
                result.MaxNightDuration = nightTimeEnd.Subtract(nightTimeStart).TotalHours;

                //Thời gian bắt đầu và kết thúc nghỉ giữa ca - giá trị thực tế
                result.ShiftBreakInTime = timeShiftStart.AddHours(realCoBreakStart);
                result.ShiftBreakOutTime = timeShiftStart.AddHours(realCoBreakEnd);

                //Khoản thời gian làm việc của ca
                result.ShiftInTime = timeShiftStart;
                result.ShiftOutTime = timeShiftEnd;

                if (shift != null && shift.IsNotApplyWorkHoursReal != null && shift.IsNotApplyWorkHoursReal.Value == true)
                {
                    result.WorkDuration = workingStandardHour - Math.Abs(result.LateDuration / 60) - Math.Abs(result.EarlyDuration / 60);
                }
            }

            return result;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Lay table roster Key: Date, Value : Shift
        /// </summary>
        /// <param name="profile"></param>
        /// <param name="rosterCfgPro"></param>
        /// <param name="lstHistoryPro"></param>
        /// <param name="gradeCfg"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="lstRosterGroup">Ds RosterGroup</param>
        /// <param name="lstRosterTypeGroup">Ds Roster loai E_ROSTERGROUP</param>
        /// <returns></returns>
        public static Hashtable GetRosterTable(Hre_Profile profile
                                , List<Att_Roster> rosterCfgPro
                                , List<Hre_WorkHistory> lstHistoryPro
                                , Cat_GradeAttendance gradeCfg
                                , DateTime from, DateTime to, List<Att_RosterGroup> lstRosterGroup, List<Att_Roster> lstRosterTypeGroup)
        {

            rosterCfgPro = rosterCfgPro.Where(s => s.ProfileID == profile.ID).ToList();
            Hashtable res = new Hashtable();
            from = from.Date;
            to = to.Date;
            //LamLe : 20120809 - #0014556 - Chi lay nhung roster o trang thai Approved
            String statusApproved = RosterStatus.E_APPROVED.ToString();
            List<Att_Roster> rosterApproved = rosterCfgPro.Where(ros => ros.Status == statusApproved || String.IsNullOrEmpty(ros.Status)).ToList();
            List<Att_Roster> lstRosterTypeGroup_ByProfile = lstRosterTypeGroup.Where(m => m.ProfileID == profile.ID).ToList();


            //LamLe - 20120803 - Lay ca lam viec trong phong ban.
            if (lstHistoryPro != null && gradeCfg != null && gradeCfg.RosterType == GradeRosterType.E_ISROSTER_ORG.ToString())
            {
                res = GetRosterOrgTable(profile, lstHistoryPro, from, to);
            }
            if (rosterApproved != null) //LamLe - 20120803 - Lay ca lam viec dua vao roster
            {
                foreach (Att_Roster roster in rosterApproved)
                {
                    try
                    {
                        if (RosterType.E_DEFAULT.ToString() != roster.Type)
                            continue;

                        DateTime start = from;
                        if (roster.DateStart != null && roster.DateStart > start)
                            start = roster.DateStart;

                        DateTime end = to;
                        if (roster.DateEnd != null && roster.DateEnd < end)
                            end = roster.DateEnd;

                        for (DateTime idx = start; idx <= end; idx = idx.AddDays(1))
                        {
                            ArrayList arr = new ArrayList();
                            if (idx.DayOfWeek == DayOfWeek.Monday)
                                arr.Add(roster.Cat_Shift);

                            else if (idx.DayOfWeek == DayOfWeek.Tuesday)
                                arr.Add(roster.Cat_Shift1);

                            else if (idx.DayOfWeek == DayOfWeek.Wednesday)
                                arr.Add(roster.Cat_Shift2);

                            else if (idx.DayOfWeek == DayOfWeek.Thursday)
                                arr.Add(roster.Cat_Shift3);

                            else if (idx.DayOfWeek == DayOfWeek.Friday)
                                arr.Add(roster.Cat_Shift4);

                            else if (idx.DayOfWeek == DayOfWeek.Saturday)
                                arr.Add(roster.Cat_Shift5);

                            else if (idx.DayOfWeek == DayOfWeek.Sunday)
                                arr.Add(roster.Cat_Shift6);
                            if (!res.ContainsKey(idx))
                                res.Add(idx, arr);

                        }
                    }
                    catch (System.Exception e)
                    {

                    }
                }

                #region triet.mai Loai E_ROSTERGROUP loại Đăng ký tăng ca theo nhóm
                //Logic khá phức tạp 
                //1. Độ ưu tiên thì đứng sau Att_Roster (loại khác Vd: dateOff, ChangeShift)
                //2. tìm cái roster của từng ngày và kiêm tra cai tên của RosterGroupName >> Chạy qua bảng Att_RosterGroup để tìm Shift

                string E_ROSTERGROUP = RosterType.E_ROSTERGROUP.ToString();
                List<Att_Roster> lstRoster_Type_RosterGroup = lstRosterTypeGroup_ByProfile.Where(m => m.Type == E_ROSTERGROUP).OrderByDescending(m => m.DateStart).ToList();
                bool isContinue = true; //Dung de chay nguoc cac roster lay cai moi nhat va ko chay nua => tang toc;
                foreach (Att_Roster rosterGroup in lstRoster_Type_RosterGroup)
                {
                    if (isContinue == false)
                        continue;

                    if (rosterGroup.DateStart <= from)
                    {
                        isContinue = false;
                    }

                    DateTime start = from;
                    DateTime end = to;
                    RosterType type = (RosterType)Common.GetEnumValue(typeof(RosterType), rosterGroup.Type);
                    switch (type)
                    {
                        case RosterType.E_ROSTERGROUP:
                            for (DateTime idx = start; idx <= end; idx = idx.AddDays(1))
                            {
                                bool isExist = res.ContainsKey(idx);
                                ArrayList arr = new ArrayList();
                                if (isExist)
                                    res.Remove(idx);

                                if (string.IsNullOrEmpty(rosterGroup.RosterGroupName))
                                    continue;
                                Att_RosterGroup RosterGroup_Current = lstRosterGroup.Where(m => m.RosterGroupName == rosterGroup.RosterGroupName && m.DateStart <= idx && m.DateEnd >= idx).FirstOrDefault();
                                if (RosterGroup_Current == null)
                                    continue;

                                if (idx.DayOfWeek == DayOfWeek.Monday && RosterGroup_Current.Cat_Shift != null)
                                    arr.Add(RosterGroup_Current.Cat_Shift);

                                else if (idx.DayOfWeek == DayOfWeek.Tuesday && RosterGroup_Current.Cat_Shift1 != null)
                                    arr.Add(RosterGroup_Current.Cat_Shift1);

                                else if (idx.DayOfWeek == DayOfWeek.Wednesday && RosterGroup_Current.Cat_Shift2 != null)
                                    arr.Add(RosterGroup_Current.Cat_Shift2);

                                else if (idx.DayOfWeek == DayOfWeek.Thursday && RosterGroup_Current.Cat_Shift3 != null)
                                    arr.Add(RosterGroup_Current.Cat_Shift3);

                                else if (idx.DayOfWeek == DayOfWeek.Friday && RosterGroup_Current.Cat_Shift4 != null)
                                    arr.Add(RosterGroup_Current.Cat_Shift4);

                                else if (idx.DayOfWeek == DayOfWeek.Saturday && RosterGroup_Current.Cat_Shift5 != null)
                                    arr.Add(RosterGroup_Current.Cat_Shift5);

                                else if (idx.DayOfWeek == DayOfWeek.Sunday && RosterGroup_Current.Cat_Shift6 != null)
                                    arr.Add(RosterGroup_Current.Cat_Shift6);

                                if (!res.ContainsKey(idx))
                                    res.Add(idx, arr);
                            }
                            break;

                        default:
                            break;
                    }
                }
                #endregion



                //LamLe - 20121101 - Order theo loai de E_TIME_OFF uu tien sau cung
                rosterApproved = rosterApproved.OrderBy(rs => rs.Type).ToList();

                string E_TIME_OFF = RosterType.E_TIME_OFF.ToString();
                string E_CHANGE_SHIFT = RosterType.E_CHANGE_SHIFT.ToString();
                List<Att_Roster> lstRoster_Type_TimeOff_ChangeShift = rosterApproved.Where(m => m.Type == E_TIME_OFF || m.Type == E_CHANGE_SHIFT).ToList();
                foreach (Att_Roster roster in lstRoster_Type_TimeOff_ChangeShift)
                {
                    DateTime start = from;
                    if (roster.DateStart != null)
                        start = roster.DateStart;

                    DateTime end = to;
                    if (roster.DateEnd != null)
                        end = roster.DateEnd;

                    RosterType type = (RosterType)Common.GetEnumValue(typeof(RosterType), roster.Type);
                    switch (type)
                    {
                        case RosterType.E_TIME_OFF:
                            for (DateTime idx = start; idx <= end; idx = idx.AddDays(1))
                            {
                                if (res.ContainsKey(idx))
                                    res.Remove(idx);
                            }
                            break;

                        case RosterType.E_CHANGE_SHIFT:
                            for (DateTime idx = start; idx <= end; idx = idx.AddDays(1))
                            {
                                bool isExist = res.ContainsKey(idx);
                                ArrayList arr = new ArrayList();

                                if (isExist)
                                    res.Remove(idx);
                                arr.Add(roster.Cat_Shift);

                                res.Add(idx, arr);
                            }
                            break;


                        //case RosterType.E_UNUSUAL:
                        //    for (DateTime idx = start; idx <= end; idx = idx.AddDays(1))
                        //    {
                        //        bool isExist = res.ContainsKey(idx);
                        //        if (!isExist)
                        //            res.Add(idx, new ArrayList());

                        //        ((ArrayList)res[idx]).Add(roster.Cat_Shift);
                        //    }
                        //    break;
                        default:
                            break;
                    }
                }
            }
            return res;
        }
Ejemplo n.º 13
0
        /// <summary>      
        /// Tinh Thang tham gia bao hiem.
        /// </summary>
        /// <param name="rProfile"></param>
        /// <param name="MonthYear"></param>
        /// <returns></returns>
        public static DateTime GetMonthJoinInsurance(Hre_Profile pro, DateTime monthYear)
        {

            List<String> lstContractCodeSI = new List<String>();
            List<Sal_Grade> lstgrade = pro.Sal_Grade.Where(gr => gr.IsDelete == null || gr.IsDelete == false).ToList();
            List<Hre_Contract> lstContract = pro.Hre_Contract.Where(gr => gr.IsDelete == null || gr.IsDelete == false).ToList();

            if (pro.DateHire == null)
            {
                return DateTime.MinValue;
            }
            DateTime _dateHire = pro.DateHire.Value;
            if (_dateHire.Day > PeriodInsuranceDayCurrentMonthDefault)
                _dateHire = new DateTime(_dateHire.AddMonths(1).Year
                                        , _dateHire.AddMonths(1).Month
                                        , PeriodInsuranceDayCurrentMonthDefault);
            else
                _dateHire = new DateTime(_dateHire.Year
                                        , _dateHire.Month
                                        , PeriodInsuranceDayCurrentMonthDefault);

            DateTime monthJoinIns = new DateTime();
            if (pro.SocialInsDateReg.HasValue)
                monthJoinIns = pro.SocialInsDateReg.Value;
            else if (pro.DateEndProbation.HasValue)
                monthJoinIns = pro.DateEndProbation.Value;
            else
                monthJoinIns = _dateHire;

            for (DateTime _dx = _dateHire; _dx < monthYear;
                _dx = new DateTime(_dx.AddMonths(1).Year,
                                   _dx.AddMonths(1).Month,
                                   PeriodInsuranceDayCurrentMonthDefault)
                )
            {
                DateTime dateMaxGrade = DateTime.MinValue;
                Cat_GradePayroll gradeCfg = new Cat_GradePayroll();
                lstgrade = lstgrade.OrderBy(gra => gra.udMonthOfEffect).ToList();
                if (lstgrade.Count > 0)
                {
                    //Truong hop ngay hieu luc cua grade dau tien lon hon ngay vao lam
                    if (lstgrade[0].udMonthOfEffect.HasValue && lstgrade[0].udMonthOfEffect.Value > _dx)
                    {
                        //<RedundancyByResharper> //No Redundancy Trung.LE
                        dateMaxGrade = lstgrade[0].udMonthOfEffect.Value;
                        //</RedundancyByResharper>

                        gradeCfg = lstgrade[0].Cat_GradePayroll;
                    }
                    else
                    {
                        foreach (Sal_Grade gr in lstgrade)
                        {
                            if (gr.udMonthOfEffect > dateMaxGrade && gr.udMonthOfEffect <= _dx)
                            {
                                dateMaxGrade = gr.udMonthOfEffect.Value;
                                gradeCfg = gr.Cat_GradePayroll;
                            }
                        }
                    }
                }

                if (!String.IsNullOrEmpty(gradeCfg.SIContract))
                {
                    lstContractCodeSI.AddRange(gradeCfg.SIContract.Split(new char[1] { ',' }));
                    if (lstContract.Exists(ctr => ctr.DateStart <= _dx
                                      && (ctr.DateEnd == null || ctr.DateEnd > _dx)
                                      && lstContractCodeSI.Contains(ctr.Cat_ContractType.Code)))
                    {
                        monthJoinIns = _dx;
                        break;
                    }
                }
            }

            return monthJoinIns;

        }
Ejemplo n.º 14
0
        /// <summary>
        /// LamLe - 20120803 - Lay ca lam viec dua vao phong ban.
        /// </summary>
        /// <param name="profile"></param>
        /// <param name="lstHistory"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        public static Hashtable GetRosterOrgTable(Hre_Profile profile
                                , List<Hre_WorkHistory> lstHistory
                                , DateTime from, DateTime to)
        {
            Hashtable res = new Hashtable();
            for (DateTime idx = from; idx <= to; idx = idx.AddDays(1))
            {
                List<Hre_WorkHistory> listWorkdate = lstHistory.Where(wh => wh.DateEffective <= idx).OrderByDescending(wh => wh.DateEffective).ToList();
                Cat_OrgStructure org = null;
                if (listWorkdate != null && listWorkdate.Count > 0)
                {
                    Hre_WorkHistory whDate = listWorkdate[0];
                    org = whDate.Cat_OrgStructure;
                }
                else if (profile.Cat_OrgStructure != null)
                {
                    org = profile.Cat_OrgStructure;
                }
                if (org == null)
                    continue;

                ArrayList arr = new ArrayList();
                if (idx.DayOfWeek == DayOfWeek.Monday)
                    arr.Add(org.Cat_Shift);

                else if (idx.DayOfWeek == DayOfWeek.Tuesday)
                    arr.Add(org.Cat_Shift1);

                else if (idx.DayOfWeek == DayOfWeek.Wednesday)
                    arr.Add(org.Cat_Shift2);

                else if (idx.DayOfWeek == DayOfWeek.Thursday)
                    arr.Add(org.Cat_Shift3);

                else if (idx.DayOfWeek == DayOfWeek.Friday)
                    arr.Add(org.Cat_Shift4);

                else if (idx.DayOfWeek == DayOfWeek.Saturday)
                    arr.Add(org.Cat_Shift5);

                else if (idx.DayOfWeek == DayOfWeek.Sunday)
                    arr.Add(org.Cat_Shift6);

                if (!res.ContainsKey(idx))
                    res.Add(idx, arr);
            }
            return res;
        }
Ejemplo n.º 15
0
 public static List<Att_Roster> List(bool usingSecurity, Hre_Profile profile, DateTime from, DateTime to)
 {
     using (var context = new VnrHrmDataContext())
     {
         var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
         var repoAtt_Roster = new CustomBaseRepository<Att_Roster>(unitOfWork);
         //LamLe - 20120616 - task SONNGO chua assign - Sua lai dk giao ngay thang
         return repoAtt_Roster.FindBy(roster => roster.ProfileID == profile.ID
                           && ((roster.DateStart <= to && roster.DateEnd >= from))
                         ).OrderBy(roster => roster.DateCreate).ToList();
     }
 }
Ejemplo n.º 16
0
        public static Hashtable GetRosterTable(bool usingSecurity, Hre_Profile profile
                                                , DateTime from, DateTime to, List<Att_RosterGroup> lstRosterGroup, List<Att_Roster> lstRosterTypeGroup)
        {
            using (var contextRosterTable = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(contextRosterTable));
                var repoAtt_Grade = new CustomBaseRepository<Att_Grade>(unitOfWork);
                var repoHre_WorkHistory = new CustomBaseRepository<Hre_WorkHistory>(unitOfWork);

                Att_Grade grade = repoAtt_Grade
                    .FindBy(grd => grd.IsDelete == null && grd.ProfileID == profile.ID).FirstOrDefault();
                Cat_GradeAttendance gradeCfg = grade != null ? grade.Cat_GradeAttendance : null;
                List<Hre_WorkHistory> whProfile = repoHre_WorkHistory.FindBy(wh => wh.ProfileID == profile.ID).ToList();
                List<Att_Roster> rosterCfg = List(usingSecurity, profile, from.Date, to.Date);
                return GetRosterTable(profile, rosterCfg, whProfile, gradeCfg, from.Date, to.Date, lstRosterGroup, lstRosterTypeGroup);
            }
        }
Ejemplo n.º 17
0
        public List<Att_OvertimeEntity> LoadData(Att_OvertimeEntity overtime, string ProfileIds, bool ByShiftProfile,string UserLogin)
        {

            List<Att_OvertimeEntity> listOvertimeInsert = new List<Att_OvertimeEntity>();
            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repoCat_DayOff = new CustomBaseRepository<Cat_DayOff>(unitOfWork);
                var repoAtt_LeaveDay = new CustomBaseRepository<Att_LeaveDay>(unitOfWork);
                var repoAtt_Pregnancy = new CustomBaseRepository<Att_Pregnancy>(unitOfWork);

                List<Att_Pregnancy> _LstPregnancy = new List<Att_Pregnancy>();
                Att_OvertimeServices overtimeDAO = new Att_OvertimeServices();
                string status = string.Empty;

                string proStr = Common.DotNetToOracle(ProfileIds);
                var lstProfileDetails = GetData<Hre_ProfileEntity>(proStr, ConstantSql.hrm_hr_sp_get_ProfileByIds, UserLogin, ref status);
                List<Guid> listProfileId = lstProfileDetails.Select(s => s.ID).ToList();

                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 OTThanTwoHour = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_ISALLOWADDHOURWHENOTTHANTWOHOUR.ToString()).FirstOrDefault();
                var OTBreakTime = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_DONOTSPLITOTBREAKTIME.ToString()).FirstOrDefault();
                var inmaternityregime = config.Where(s => s.Name == AppConfig.HRM_ATT_OT_ALLOWREGISTEROTWHENINMATERNITYREGIME.ToString()).FirstOrDefault();


                List<Cat_DayOff> lstDayOff = repoCat_DayOff.FindBy(s => s.IsDelete == null).ToList();
                if (OTThanTwoHour.Value1 == bool.TrueString)
                    lstDayOff = lstDayOff.Where(dayoff => dayoff.Type == HolidayType.E_HOLIDAY_HLD.ToString()).ToList();

                bool isAllowCutOTBreakHour = false;
                if (OTBreakTime.Value1 == bool.TrueString)
                    isAllowCutOTBreakHour = true;

                Att_OvertimeEntity baseOT = null;

                //Trung.Le 20120621 #0014337 Nếu như CÓ THÊM đăng ký Leave loại nghỉ lễ (Mã: HLD) thì ngày đó tương đương với ngày nghỉ lễ
                string LeavedayTypeCode_HLD = LeavedayTypeCode.HLD.ToString();
                string E_HOLIDAY_HLD = HolidayType.E_HOLIDAY_HLD.ToString();
                DateTime DateFromOvertime = overtime.WorkDate.Date;
                DateTime DateEndOvertime = overtime.WorkDate.Add(TimeSpan.FromHours(overtime.RegisterHours)).Date;
                string E_APPROVED = LeaveDayStatus.E_APPROVED.ToString();
                List<Att_LeaveDay> lstLeaveDayHoliday = repoAtt_LeaveDay
                        .FindBy(att => att.IsDelete == null && DateEndOvertime >= att.DateStart && DateFromOvertime <= att.DateEnd
                            && att.Status == E_APPROVED && att.Cat_LeaveDayType.Code == LeavedayTypeCode_HLD
                            && listProfileId.Contains(att.ProfileID))
                        .ToList();


                if (overtime.ID == Guid.Empty)
                {
                    //baseOT = GetBaseDataOvertime(baseOT, overtime, profile);
                    string _pregnancyType = PregnancyType.E_LEAVE_EARLY.ToString();
                    _LstPregnancy = repoAtt_Pregnancy
                        .FindBy(prg => prg.Type == _pregnancyType && prg.DateEnd >= overtime.WorkDate.Date && prg.DateStart <= overtime.WorkDate)
                        .ToList();

                    Hre_Profile _hreProfile = new Hre_Profile();
                    foreach (var profile in lstProfileDetails)
                    {
                        overtime.ProfileID = profile.ID;
                        overtime.ProfileName = profile.ProfileName;
                        overtime.CodeEmp = profile.CodeEmp;

                        listOvertimeInsert.AddRange(AnalysisOvertime(overtime,
                        GetListDayOffPerProfile(lstLeaveDayHoliday, profile, lstDayOff, E_HOLIDAY_HLD) //lstDayOff
                        , _LstPregnancy, ByShiftProfile, isAllowCutOTBreakHour, UserLogin));
                    }


                }
                #region overtime.ID == Guid.Empty && strListId.Length > 1
                //if (overtime.ID == Guid.Empty && strListId.Length > 1)
                //{
                //    List<Hre_Profile> listAllProfile = EntityService.GetEntityList<Hre_Profile>(GuidContext, LoginUserID.Value, pf => listProfileId.Contains(pf.ID));
                //    foreach (Guid _pfID in listProfileId)
                //    {
                //        if (_pfID != pfid)
                //        {
                //            baseOT = GetBaseDataOvertime(baseOT, overtime, profile);

                //            List<Hre_Profile> _listPfTemp = listAllProfile.Where(pf => pf.ID == _pfID).ToList();
                //            if (_listPfTemp.Count != 1)
                //            {
                //                continue;
                //            }
                //            profile = _listPfTemp[0];
                //            baseOT.Hre_Profile = profile;
                //            listOvertimeInsert.AddRange(overtimeDAO.AnalysisOvertime(baseOT,
                //                GetListDayOffPerProfile(lstLeaveDayHoliday, profile, lstDayOff, E_HOLIDAY_HLD) //lstDayOff
                //                , _LstPregnancy, GuidContext, LoginUserID.Value, rdbByShiftProfile, isAllowCutOTBreakHour));
                //        }
                //    }
                //}
                #endregion
                #region tan.do danh dau nguoi huong che do thai san
                //_listbaseData = new List<BaseDataOvertime>();
                if (inmaternityregime.Value1 != bool.TrueString)
                {
                    DateTime time = overtime.WorkDate;
                    string type = PregnancyStatus.E_LEAVE_EARLY.ToString();
                    List<Guid> guids = listOvertimeInsert.Select(s => s.ProfileID).ToList();
                    var pregnancies = repoAtt_Pregnancy
                        .FindBy(s => s.IsDelete == null && s.DateStart <= time && time <= s.DateEnd && s.Type == type
                        && guids.Contains(s.ProfileID))
                        .ToList();
                    foreach (var baseDataOvertime in listOvertimeInsert)
                    {
                        foreach (var attPregnancy in pregnancies)
                        {
                            if (baseDataOvertime.ProfileID == attPregnancy.ProfileID)
                            {
                                //_listbaseData.Add(baseDataOvertime);
                            }
                        }
                    }
                }
                #endregion
                return listOvertimeInsert;
            }
        }
Ejemplo n.º 18
0
        private DataRow fillRowBasic(DataRow dr, DateTime monthYear, Hre_Profile profile, Ins_InsuranceRecord record, List<Ins_InsuranceRecord> lstRecordByProfile, List<Cat_DayOff> lstDayOff)
        {
            if (profile == null)
            {
                return dr;
            }
            Stt++;
            dr[Ins_C70aReportEntity.FieldNames.Stt] = Stt;
            dr[Ins_C70aReportEntity.FieldNames.CodeEmp] = profile.CodeEmp;
            dr[Ins_C70aReportEntity.FieldNames.ProfileName] = ConvertStringToNamePerson(profile.ProfileName);
            if (profile.DateOfBirth != null)
            {
                if (profile.Gender == EnumDropDown.Sexual.E_FEMALE.ToString())
                {
                    dr["FemaleBirthYear"] = profile.DateOfBirth.Value.Year;
                }
                else
                {
                    dr["MaleBirthYear"] = profile.DateOfBirth.Value.Year;
                }
            }
            dr["SocialInsNo"] = profile.SocialInsNo;
            if (record.DateStart != null)
            {
                dr["DateStart"] = record.DateStart.Value;
            }
            if (record.DateEnd != null)
            {
                dr["DateEnd"] = record.DateEnd.Value;
            }
            //if (record.DateStart != null && record.DateEnd != null)
            //{
            //    dr["SumStartEnd"] = (record.DateEnd.Value - record.DateStart.Value).TotalDays;
            //    totalLeaveInMonth += (record.DateEnd.Value - record.DateStart.Value).TotalDays;
            //}

            //DateTime beginYear = new DateTime(monthYear.Year-1,12,15); //bat dau tu ngay 15 theo bao hiem. Can phai hoi lai chi Oanh van de tren
            //lstDayOff = lstDayOff.Where(m=>m.DateOff > beginYear).ToList();
            //if (record.DateStart != null && record.DateEnd != null)
            //{
            //    List<Ins_InsuranceRecord> lstRecordLeaveInYear = lstRecordByProfile.Where(m => m.ProfileID == profile.ID && m.InsuranceType == record.InsuranceType
            //        && m.DateEnd != null && m.DateEnd.Value > beginYear
            //        && m.DateStart != null && m.DateStart.Value <= record.DateStart).ToList();
            //    dr["SumStartEndInYear"] = (record.DateEnd.Value - record.DateStart.Value).TotalDays + getNumDayLeaveInYear(lstRecordLeaveInYear, lstDayOff);
            //    totalLeaveInYear = (record.DateEnd.Value - record.DateStart.Value).TotalDays + getNumDayLeaveInYear(lstRecordLeaveInYear, lstDayOff);
            //}
            return dr;
        }
Ejemplo n.º 19
0
        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;
            }
        }
Ejemplo n.º 20
0
        public void AnalyseTotalLeaveDaysAndHours(Att_LeaveDay LeaveDay, Cat_LeaveDayType LeaveDayType, Hre_Profile profile, Cat_GradeAttendance gradeCfg, List<Att_Roster> lstRoster, List<Att_RosterGroup> lstRosterGroup, List<Hre_WorkHistory> listWorkHistory, List<Cat_DayOff> lstHoliday, List<Cat_Shift> lstShift)
        {
            if (LeaveDay.DurationType == null)
                return;
            #region data
            string LeaveDayTypeCode = string.Empty;
            if (LeaveDayType != null)
                LeaveDayTypeCode = LeaveDayType.Code;

            if (gradeCfg == null)
                return;
            DateTime dateFrom = LeaveDay.DateStart.Date;
            DateTime dateTo = LeaveDay.DateEnd;
            dateTo = dateTo.AddDays(1).AddMinutes(-1);
            string E_ROSTERGROUP = RosterType.E_ROSTERGROUP.ToString();
            List<Att_Roster> lstRosterByProfile = lstRoster.Where(m => m.ProfileID == profile.ID && m.DateStart <= dateTo && m.DateEnd >= dateFrom).ToList();
            List<Att_Roster> lstRosterByProfileTypeGroup = lstRosterByProfile.Where(m => m.Type == E_ROSTERGROUP).ToList();
            List<Hre_WorkHistory> listWorkHistoryByProfile = listWorkHistory.Where(m => m.ProfileID == profile.ID && m.DateEffective < dateTo).ToList();

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

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

            Dictionary<DateTime, Cat_Shift> listMonthShifts = Att_AttendanceLib.GetDailyShifts(profile.ID,
                dateFrom, dateTo, listRosterEntity, listRosterGroupEntity, lstShift);

            double leaveDays = 0;
            double leaveHours = 0;

            #endregion
            if (LeaveDay.DurationType != LeaveDayDurationType.E_FULLSHIFT.ToString())
            {
                DateTime dateLeave = LeaveDay.DateStart.Date;
                //Check co ca ko
                if (gradeCfg != null && Att_WorkDayHelper.IsWorkDay(dateLeave, gradeCfg, listMonthShifts, lstHoliday))
                {
                    if (listMonthShifts.ContainsKey(dateLeave) && listMonthShifts[dateLeave] != null && listMonthShifts[dateLeave].WorkHours != null && listMonthShifts[dateLeave].WorkHours != 0)
                    {
                        Cat_Shift Shift = listMonthShifts[dateLeave];
                        //Có ca thi lây giờ nghỉ giua ca để mà tính thời gian thực nghỉ
                        //Nếu như trừ thời gian nghỉ ra khỏi giờ nghi trưa mà lơn hơn workhour của ca thì lấy max la workhour của ca
                        DateTime ShiftBreakIn = dateLeave.Add(Shift.InTime.TimeOfDay).AddHours(Shift.CoBreakIn);
                        DateTime ShiftBreakOut = dateLeave.Add(Shift.InTime.TimeOfDay).AddHours(Shift.CoBreakOut);
                        if (LeaveDay.DateStart < ShiftBreakOut && LeaveDay.DateEnd > ShiftBreakIn)
                        {
                            //neu co long nhau
                            if (ShiftBreakIn > LeaveDay.DateStart)
                                leaveHours = (ShiftBreakIn - LeaveDay.DateStart).TotalHours;
                            if (LeaveDay.DateEnd > ShiftBreakOut)
                                leaveHours += (LeaveDay.DateEnd - ShiftBreakOut).TotalHours;

                            leaveDays = leaveHours / Shift.WorkHours ?? 8;
                        }
                        else
                        {
                            leaveHours = (LeaveDay.DateEnd - LeaveDay.DateStart).TotalHours;
                            leaveDays = leaveHours / Shift.WorkHours ?? 8;
                            //neu ko long nhau
                        }
                    }
                    else //Ko có ca làm việc
                    {
                        //Nếu ko có ca thì lấy giờ out trừ giờ in
                        leaveHours = (LeaveDay.DateEnd - LeaveDay.DateStart).TotalHours;
                        leaveDays = leaveHours / 8;
                    }
                }



            }
            else //Loại FullShift
            {
                if (LeaveDay.DurationType == null)
                {
                    LeaveDay.DurationType = LeaveDayDurationType.E_FULLSHIFT.ToString();
                }
                if (profile == null)
                    return;


                bool isSetFullLeaveDay = false;

                if (!string.IsNullOrEmpty(LeaveDayTypeCode) && (LeaveDayTypeCode == "SICK"
                                    || LeaveDayTypeCode == "PRG"
                                    || LeaveDayTypeCode == "SU"
                                    || LeaveDayTypeCode == "SD"
                                    || LeaveDayTypeCode == "D"
                                    || LeaveDayTypeCode == "DP"
                                    || LeaveDayTypeCode == "PSN"
                                    || LeaveDayTypeCode == "M"
                                    || LeaveDayTypeCode == "DSP"))
                {


                    for (DateTime idx = dateFrom; idx <= dateTo; idx = idx.AddDays(1))
                    {
                        if (!lstHoliday.Any(m => m.DateOff == idx))
                        {
                            leaveDays += 1;
                            Cat_Shift ShiftByDay = null;
                            if (listMonthShifts.ContainsKey(idx))
                            {
                                ShiftByDay = listMonthShifts[idx];
                            }
                            if (ShiftByDay != null)
                            {
                                leaveHours += ShiftByDay.WorkHours ?? 8;
                            }
                            else
                            {
                                leaveHours += 8;
                            }
                        }
                        isSetFullLeaveDay = true;
                    }
                }
                if (isSetFullLeaveDay == false)
                {

                    for (DateTime idx = dateFrom; idx <= dateTo; idx = idx.AddDays(1))
                    {
                        if (gradeCfg != null && Att_WorkDayHelper.IsWorkDay(idx, gradeCfg, listMonthShifts, lstHoliday))
                        {
                            leaveDays += 1;
                            Cat_Shift ShiftByDay = null;
                            if (listMonthShifts.ContainsKey(idx))
                            {
                                ShiftByDay = listMonthShifts[idx];
                            }
                            if (ShiftByDay != null)
                            {
                                leaveHours += ShiftByDay.WorkHours ?? 8;
                            }
                        }
                    }
                }
            }
            if (LeaveDay.LeaveDays == null || LeaveDay.LeaveDays != leaveDays)
            {
                LeaveDay.LeaveDays = leaveDays;
            }
            if (LeaveDay.LeaveHours == null || LeaveDay.LeaveHours != leaveHours)
            {
                LeaveDay.LeaveHours = leaveHours;
            }

        }
Ejemplo n.º 21
0
        public List<Sal_SalaryDepartmentItem> CalSalaryItemProfile(Sal_SalaryDepartment salDepartment, List<Att_AttendanceTableItem> lstAttItemPro, Hre_Profile pro,
                                         List<Sal_SalaryDepartmentItem> lstItemPro, DateTime dfrom, DateTime dto, DateTime monthYear)
        {
            List<Sal_SalaryDepartmentItem> lstItem = new List<Sal_SalaryDepartmentItem>();
            List<Sal_SalaryDepartmentItem> lstDepItemPro = lstItemPro.Where(p => p.ProfileID == pro.ID).ToList();
            Double ratePer = 0;

            //Lấy hệ số từ bảng Sal_SalaryDepartmentItem
            foreach (Sal_SalaryDepartmentItem rtDepItem in lstDepItemPro)
            {
                ratePer = rtDepItem.Rate != null ? rtDepItem.Rate : 0;
                Sal_SalaryDepartmentItem depItem = new Sal_SalaryDepartmentItem();
                //depItem.Sal_SalaryDepartment = salDepartment;
                depItem.SalaryDepartmentID = salDepartment.ID;
                depItem.DateFrom = dfrom;
                depItem.DateTo = dto;
                depItem.ProfileID = pro.ID;
                depItem.Rate = ratePer;

                for (DateTime idx = dfrom; idx <= dto; idx = idx.AddDays(1))
                {
                    //(3.Use general: Insert chi tiết --> Gần Finished)
                    depItem = SetItemSalDep(depItem, lstAttItemPro, idx);
                }
                lstItem.Add(depItem);

            }
            return lstItem;
        }
Ejemplo n.º 22
0
        private System.Data.DataTable FillRow(Hre_Profile Profile, Ins_InsuranceRecord record
          , System.Data.DataTable tblData, DateTime _from, DateTime _to, DateTime monthYear
          , List<Sal_BasicSalary> listBasicSalary, List<Ins_InsuranceRecord> list_Year, List<Cat_ExchangeRate> lstRateInsurance
          , string status, List<Cat_DayOff> lstDayOff, List<Guid> PositionIsWorkingHard, String GroupName, List<Cat_OrgStructure> lstOrgAll, List<Sys_AllSetting> lstAppConfig)
        {

            //List<Sys_AllSetting> lstAppConfig = EntityService.GetAllEntities<Sys_AllSetting>(EntityService.GuidMainContext, LoginUserID.Value);
            if (record.DayCount <= 0)
                return tblData;
            Guid proID = Profile.ID;
            //HRService hrser = new HRService();
            DataRow row = tblData.NewRow();
            row = fillRowBasic(row, monthYear, Profile, record, list_Year.Where(m => m.ProfileID == Profile.ID).ToList(), lstDayOff);
            DateTime _monthJoin = InsuranceServices.GetMonthJoinInsurance(Profile, monthYear);
            #region loai SICK
            if (status == InsuranceRecordType.E_SICK_SHORT.ToString() ||
                status == InsuranceRecordType.E_SICK_LONG.ToString() ||
                status == InsuranceRecordType.E_SICK_CHILD.ToString())
            {
                //Tính cột  thời gian đóng bảo hiểm xã hội
                if (record.DateStart != null)
                {


                    DateTime dateStartInsurance = new DateTime(record.DateStart.Value.AddMonths(-1).Year, record.DateStart.Value.AddMonths(-1).Month, InsuranceServices.PeriodInsuranceDayCurrentMonthDefault);
                    int month = 0;
                    if (Profile.UnEmpInsCountMonthOld != null)
                    {
                        month = Profile.UnEmpInsCountMonthOld ?? 0;
                    }
                    for (DateTime dateCheck = _monthJoin; dateCheck <= dateStartInsurance; dateCheck = dateCheck.AddMonths(1))
                    {
                        month++;
                    }
                    int year = month / 12;
                    month = month % 12;
                    string yearTemp = year.ToString();
                    yearTemp = yearTemp.Length == 1 ? "0" + yearTemp : yearTemp;
                    string monthTemp = month.ToString();
                    monthTemp = monthTemp.Length == 1 ? "0" + monthTemp : monthTemp;
                    row[Ins_C70aReportEntity.FieldNames.BeginSocialInsIssueDate] = yearTemp + "-" + monthTemp;
                }


                //Tình trạng của nhân viên 
                //Logic Tất cả các chức danh trừ nhân viên thì là tình trang "Điều kiện NN-ĐH"còn nhân viên thì là "Điều Kiện BT"
                if (status == InsuranceRecordType.E_SICK_CHILD.ToString()) // Nếu loại con óm thì không cần ghi
                {
                    row[Ins_C70aReportEntity.FieldNames.Notes] = string.Empty;
                    row[Ins_C70aReportEntity.FieldNames.Notes1] = record.DateSuckle != null ? string.Format("{0:dd/MM/yyyy}", record.DateSuckle.Value) : string.Empty;
                }
                else
                {
                    if (PositionIsWorkingHard.Contains(Profile.PositionID ?? Guid.Empty))
                    {
                        row[Ins_C70aReportEntity.FieldNames.Notes] = "Điều kiện NN-ĐH";
                    }
                    else
                    {
                        row[Ins_C70aReportEntity.FieldNames.Notes] = "Điều Kiện BT";
                    }
                }
            }
            #endregion
            #region loai Kham thai
            if (status == InsuranceRecordType.E_PREGNANCY_EXAMINE.ToString() ||
                status == InsuranceRecordType.E_PREGNANCY_LOST.ToString() ||
                status == InsuranceRecordType.E_PREGNANCY_SUCKLE.ToString() ||
                status == InsuranceRecordType.E_PREGNANCY_PREVENTION.ToString())
            {
                //Tính cột  thời gian đóng bảo hiểm xã hội
                if (record.DateStart != null)
                {

                    DateTime dateStartInsurance = new DateTime(record.DateStart.Value.AddMonths(-1).Year, record.DateStart.Value.AddMonths(-1).Month, InsuranceServices.PeriodInsuranceDayCurrentMonthDefault);
                    int month = 0;
                    for (DateTime dateCheck = _monthJoin; dateCheck <= dateStartInsurance; dateCheck = dateCheck.AddMonths(1))
                    {
                        month++;
                    }
                    month = month > 12 ? 12 : month;
                    string monthTemp = month.ToString();
                    monthTemp = monthTemp.Length == 1 ? "0" + monthTemp : monthTemp;
                    row[Ins_C70aReportEntity.FieldNames.BeginSocialInsIssueDate] = "0" + "-" + monthTemp;

                    if (status == InsuranceRecordType.E_PREGNANCY_LOST.ToString())
                    {
                        row[Ins_C70aReportEntity.FieldNames.Notes] = record.Comment;
                    }
                    if (status == InsuranceRecordType.E_PREGNANCY_SUCKLE.ToString())
                    {
                        //row["Notes"] = LanguageManager.GetString(record.TypeSuckle);
                        row[Ins_C70aReportEntity.FieldNames.Notes] = record.TypeSuckle;
                        row[Ins_C70aReportEntity.FieldNames.Notes1] = record.DateSuckle != null ? string.Format("{0:dd/MM/yyyy}", record.DateSuckle.Value) : string.Empty;
                    }
                }
            }
            #endregion
            #region loai Duong Suc
            if (status == InsuranceRecordType.E_RESTORATION_SICK.ToString() ||
                status == InsuranceRecordType.E_RESTORATION_TNLD.ToString() ||
                status == InsuranceRecordType.E_RESTORATION_PREGNANCY.ToString())
            {
                //Tính cột  thời gian đóng bảo hiểm xã hội
                //row["Notes"] = LanguageManager.GetString(record.TypeSuckle);
                row[Ins_C70aReportEntity.FieldNames.Notes] = record.TypeSuckle;
                row[Ins_C70aReportEntity.FieldNames.Notes1] = record.DateStartWorking != null ? string.Format("{0:dd/MM/yyyy}", record.DateStartWorking.Value) : string.Empty;
            }
            #endregion
            Double salaryIns = 0;
            Double moneyIns = 0;
            InsuranceServices.GetMoneyInsSalaryIns(record, ListMaxSalary, ListMinSalary, _monthJoin, listBasicSalary, lstRateInsurance, lstAppConfig, out moneyIns, out salaryIns, false);
            //Tien BHXH tra
            // Double roundMoney = Common.GetRoundMoney(moneyIns, 2);
            //totalMoney += roundMoney;
            row[Ins_C70aReportEntity.FieldNames.Money] = moneyIns;
            totalMoney += moneyIns;

            totalMoneyNotRound += moneyIns;
            // row["MoneyNotRound"] = moneyIns;

            //Luong tham gia BHXH
            totalSalaryInsurance += salaryIns;
            row[Ins_C70aReportEntity.FieldNames.SalaryInsurance] = salaryIns;

            if (status == InsuranceRecordType.E_LEAVE_AT_SAME_PLACE.ToString() ||
                status == InsuranceRecordType.E_LEAVE_AT_HOME.ToString() ||
                status == InsuranceRecordType.E_RESTORATION_TNLD.ToString() ||
                status == InsuranceRecordType.E_RESTORATION_PREGNANCY.ToString())//Nếu là phần dưỡng sưc thì thể hiện 25%
            {

                totalSalaryInsurance = 0.25;
                row[Ins_C70aReportEntity.FieldNames.SalaryInsurance] = 0.25;

                if (status == InsuranceRecordType.E_LEAVE_AT_SAME_PLACE.ToString())
                {
                    totalSalaryInsurance = 0.4;
                    row[Ins_C70aReportEntity.FieldNames.SalaryInsurance] = 0.4;
                }
            }




            //Lay nam nghi viec cua record de tinh luy ke. Neu nghi tu nam ngoai thi luy ke cac ngay nghi tu nam ngoai

            List<Ins_InsuranceRecord> lstInSursInYear = list_Year.Where(ir => ir.ProfileID == proID
                                                                        && ir.DateStart.Value.Year == record.DateStart.Value.Year
                                                                        && ir.DateEnd <= record.DateEnd
                                                                        && ir.InsuranceType == status).ToList();

            //Trường hợp con Ốm thì con nào phải đúng tuyến cho con đó.
            if (record.InsuranceType == InsuranceRecordType.E_SICK_CHILD.ToString())
            {
                lstInSursInYear = lstInSursInYear.Where(m => m.ChildSickID == record.ChildSickID).ToList();
            }

            Double leaveInYear = 0;
            foreach (Ins_InsuranceRecord it in lstInSursInYear)
            {
                leaveInYear += InsuranceServices.GetCountLeaveRecord(it);
            }
            totalLeaveInYear += leaveInYear;
            row[Ins_C70aReportEntity.FieldNames.LeaveInYear] = leaveInYear;
            Double leaveInMonth = InsuranceServices.GetCountLeaveRecord(record);
            totalLeaveInMonth += leaveInMonth;
            row[Ins_C70aReportEntity.FieldNames.LeaveInMonth] = leaveInMonth;
            if (record.DateStart != null)
            {
                row[Ins_C70aReportEntity.FieldNames.DateStart] = record.DateStart.Value;
            }
            if (record.DateEnd != null)
            {
                row[Ins_C70aReportEntity.FieldNames.DateEnd] = record.DateEnd.Value;
            }
            //row["Status"] = LanguageManager.GetString(status);
            //row["GroupName"] = LanguageManager.GetString(GroupName);
            row[Ins_C70aReportEntity.FieldNames.Status] = status;
            row[Ins_C70aReportEntity.FieldNames.GroupName] = GroupName;
            row[Ins_C70aReportEntity.FieldNames.CodeParentOrgLevel] = Hre_ProfileServices.GetCodeInListOrgParent(Profile.OrgStructureID ?? Guid.Empty, lstOrgAll, 1);
            tblData.Rows.Add(row);
            return tblData;
        }