Example #1
0
 public async Task <LeaveApplicationViewModel> DetailsLeaveApp(int id)
 {
     try
     {
         var detailsLeaveapp = new LeaveApplicationViewModel();
         if (_context != null)
         {
             detailsLeaveapp = await(from l in _context.LeaveApplication
                                     where l.Id == id
                                     select new LeaveApplicationViewModel
             {
                 Id                 = l.Id,
                 EmployeeId         = l.EmployeeId,
                 ManagerId          = l.ManagerId,
                 Status1            = l.Status == 1 ? "Waiting" : l.Status == 2 ? "Accept" : l.Status == 3 ? "Not Apcept" : "",
                 StartDate          = l.StartDate.ToString("ddd dd/MM/yyyy"),
                 EndDate            = l.EndDate.HasValue ? l.EndDate.Value.ToString("ddd dd/MM/yyyy") : " ",
                 DaysLeaveRemaining = l.DaysLeaveRemaining,
                 NumberOfAbsent     = l.NumberOfAbsent,
                 CommentDate        = l.CommentDate.ToString("ddd dd/MM/yyyy"),
                 FeedbackDate       = l.FeedbackDate.HasValue ? l.FeedbackDate.Value.ToString("ddd dd/MM/yyyy") : " ",
                 Comment            = l.Comment,
                 Feedback           = l.Feedback
             }).FirstOrDefaultAsync();
         }
         return(detailsLeaveapp);
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #2
0
        public ActionResult AnnualLeaveApplication(LeaveApplicationViewModel leaveApplicationViewModel)
        {
            LeaveApplication leaveApplication = null;

            if (!ModelState.IsValid)
            {
                return(View(leaveApplicationViewModel));
            }

            try
            {
                LeaveApplicationFactory leaveApplicationFactory = new LeaveApplicationFactory(_context);
                string userId = HttpContext.User.Identity.GetUserId();
                leaveApplication = leaveApplicationFactory.Create(userId, leaveApplicationViewModel.StartDateTime, leaveApplicationViewModel.EndDateTime, leaveApplicationViewModel.Description, leaveApplicationViewModel.ApproverEmail, leaveApplicationViewModel.Comment, LeaveType.AnnualLeave);
                _leaveApplicationService.CreateLeaveApplication(leaveApplication);
                return(RedirectToAction("MyAnnualLeave"));
            }
            catch (InvalidOperationException invalidException)
            {
                ModelState.AddModelError("", invalidException.Message);
            }catch (Exception e)
            {
                _logger.Error("Failed to create a new Annual Leave application", e);
                ModelState.AddModelError("", e.Message);
            }
            return(View(leaveApplicationViewModel));
        }
        // GET: LeaveApplication/CreateLeaveForm
        public ActionResult CreateLeaveList(DateTime start, DateTime end, _leaveType leaveType)
        {
            // Try to fetch Leaveapplication from DB if it exists
            LeaveApplicationViewModel applicationVM  = new LeaveApplicationViewModel();
            List <TimeRecord>         newTimeRecords = new List <TimeRecord>();

            ViewBag.LeaveType = LeaveApplication.GetLeaveTypeItems();

            for (int i = 0; i <= (end - start).Days; i++)
            {
                // Fetch each timerecord in DB if it exists
                DateTime currentDate   = start.AddDays(i);
                var      newTimeRecord = new TimeRecord(currentDate.Date);
                newTimeRecord.SetAttendence(null, null, 0);
                newTimeRecord.UserID    = User.Identity.Name;
                newTimeRecord.LeaveType = leaveType;
                newTimeRecord.LeaveTime = (leaveType == 0) ? 0 : 7.5;
                PayPeriod.SetPublicHoliday(newTimeRecord);
                if (!newTimeRecord.IsHoliday)
                {
                    newTimeRecords.Add(newTimeRecord);
                }
            }
            applicationVM.TimeRecords = newTimeRecords;

            if (applicationVM.TimeRecords.Count == 0)
            {
                return(Content("No working days were found."));
            }

            return(PartialView(@"~/Views/LeaveApplication/_LeaveList.cshtml", applicationVM));
        }
        // GET: LeaveApplications/Details/5
        public async Task <IActionResult> Details(Guid?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            LeaveApplication leaveApplication = await _context.LeaveApplications
                                                .Include(l => l.Applicant)
                                                .Include(l => l.SignedFile)
                                                .FirstOrDefaultAsync(m => m.Id == id);

            if (leaveApplication == null)
            {
                return(NotFound());
            }

            //Get View Model for creating XML from model
            var config = new MapperConfiguration(cfg => {
                cfg.CreateMap <LeaveApplication, LeaveApplicationViewModel>();
            });
            IMapper iMapper = config.CreateMapper();
            LeaveApplicationViewModel leaveApplicationView = iMapper.Map <LeaveApplication, LeaveApplicationViewModel>(leaveApplication);
            XmlDocument xmlDocument = Adapter.SerializeToXml <LeaveApplicationViewModel>(leaveApplicationView);

            ViewData["xml"] = xmlDocument.OuterXml;
            ViewData["Id"]  = id;
            return(View(leaveApplication));
        }
Example #5
0
        public ActionResult AnnualLeaveApplication()
        {
            LeaveApplicationViewModel leaveApplicationViewModel = new LeaveApplicationViewModel();

            leaveApplicationViewModel.ApproverEmail = User.Identity.GetUserManagerEmail();
            leaveApplicationViewModel.StartDateTime = DateTime.Now;
            leaveApplicationViewModel.EndDateTime   = DateTime.Now;
            return(View(leaveApplicationViewModel));
        }
Example #6
0
        public ActionResult LeaveDetailAdmin(int id)
        {
            LeaveApplicationViewModel lavm = _leaveServices.LeaveDetailAdmin(id);
            LeaveApplicationRecommendDetailViewModel lardVM = new LeaveApplicationRecommendDetailViewModel();

            lardVM.LeaveDetail  = lavm;
            lardVM.LeaveApplier = _employeeServices.GetEmployeeDetails(lavm.LeaveEmpCode);
            return(View(lardVM));
        }
        public ActionResult ApplicationOutput(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            LeaveApplicationViewModel applicationVM = new LeaveApplicationViewModel();
            LeaveApplication          application   = contextDb.LeaveApplications.Find(id);

            if (application != null)
            {
                applicationVM.LeaveApplication = application;
                applicationVM.TimeRecords      = application.GetTimeRecords();
                // Get leave balance
                List <LeaveBalance> LeaveBalances = new List <LeaveBalance>();
                if (application.OriginalBalances != null)
                {
                    ViewBag.OriginalBalances = application.OriginalBalances.Split('/');
                }
                else
                {
                    ViewBag.OriginalBalances = new string[] { "", "", "" }
                };

                if (application.CloseBalances != null)
                {
                    ViewBag.CloseBalances = application.CloseBalances.Split('/');
                }
                else
                {
                    ViewBag.CloseBalances = new string[] { "", "", "" }
                };

                // Get manager name
                ViewBag.ManagerName = contextDb.ADUsers.Find(application.ApprovedBy).UserName ?? string.Empty;

                // Get pay period and format it
                int    payPeriod1 = PayPeriod.GetPeriodNum(application.StartTime);
                int    payPeriod2 = PayPeriod.GetPeriodNum(application.EndTime);
                string period     = "Pay Period " + payPeriod1;
                if (payPeriod1 != payPeriod2)
                {
                    period += " - " + payPeriod2;
                }
                ViewBag.PayPeriod = period;

                return(View(applicationVM));
            }
            else
            {
                return(HttpNotFound("Cannot find the application in database. Please contact our IT support."));
            }
        }
Example #8
0
        public ActionResult RefuseAnnualLeaveApplication(LeaveApplicationViewModel leaveApplicationViewModel, string leaveApplicationId)
        {
            LeaveApplication leaveApplication = _context.LeaveApplications.Find(new Guid(leaveApplicationId));

            leaveApplication.Comment = leaveApplicationViewModel.Comment;
            string currentUserId = HttpContext.User.Identity.GetUserId();
            User   approver      = _context.Users.Find(currentUserId);

            _leaveApplicationService.RefuseLeaveApplication(leaveApplication, approver);

            return(RedirectToAction("MyApprovingAnnualLeave"));
        }
        public int Create([FromBody] LeaveApplicationViewModel leaveVM)
        {
            var leave = new Leave
            {
                EmployeeId      = leaveVM.EmployeeId,
                LeaveCategoryId = leaveVM.LeaveCategoryId,
                FromDate        = leaveVM.FromDate,
                ToDate          = leaveVM.ToDate,
                Reason          = leaveVM.Reason
            };

            return(_unitOfWork.Leave.AddLeave(leave));
        }
Example #10
0
        public int NotificationLeaveRequestRecommend(LeaveApplicationViewModel Lat)
        {
            EmployeeDetailsViewModel user     = _employeeService.GetEmployeeDetails(Lat.LeaveEmpCode);
            EmployeeDetailsViewModel recomend = _employeeService.GetEmployeeDetails(Convert.ToInt32(Lat.LeaveRecommenderEmpcode));
            EmployeeDetailsViewModel approver = _employeeService.GetEmployeeDetails(Convert.ToInt32(Lat.LeaveApproverEmpcode));

            if (Lat.RecommendStatus == 2)
            {
                #region NotificationUser
                NotificationsDTOs ntd = new NotificationsDTOs();
                ntd.NotificationDate         = DateTime.Now;
                ntd.NotificationReceiverId   = Convert.ToInt32(Lat.LeaveEmpCode);
                ntd.NotificationSubject      = "Recommender approve your Leave Request";
                ntd.NotificationMessage      = "Your " + Lat.LeaveTypeName + " requested on " + Lat.LeaveAppliedDate.ToString("yyyy,MMM dd") + " is Recommended by " + recomend.Name;
                ntd.NotificationReceiverType = "E";
                ntd.NotificationDetailURL    = "/user/leave/detail/" + Lat.LeaveId;
                ntd.NotificationReadDate     = null;
                _notifications.InsertNotification(ntd);
                #endregion

                #region Notificationapprover
                NotificationsDTOs ntf = new NotificationsDTOs();
                ntf.NotificationDate         = DateTime.Now;
                ntf.NotificationReceiverId   = approver.Code;
                ntf.NotificationSubject      = "Leave  Requested to approve";
                ntf.NotificationMessage      = user.Name + " Slected you as Approver as this leave request is already been recommened by " + recomend.Name + ".Please confirm the request ";
                ntf.NotificationReceiverType = "E";
                ntf.NotificationDetailURL    = "/user/leaveapplication/approve/" + Lat.LeaveId;
                ntf.NotificationReadDate     = null;
                _notifications.InsertNotification(ntf);
                #endregion
            }
            else
            if (Lat.RecommendStatus == 3)
            {
                #region NotificationUser
                NotificationsDTOs ntd = new NotificationsDTOs();
                ntd.NotificationDate         = DateTime.Now;
                ntd.NotificationReceiverId   = Convert.ToInt32(user.Code);
                ntd.NotificationSubject      = Lat.LeaveTypeName + " request rejected by " + recomend.Name;
                ntd.NotificationMessage      = "Sorry!! Your " + Lat.LeaveTypeName + " applied on " + Lat.LeaveAppliedDate.ToString("yyyy,MMM dd") + " is rejected by " + recomend.Name;
                ntd.NotificationReceiverType = "E";
                ntd.NotificationDetailURL    = "/user/leave/detail/" + Lat.LeaveId;
                ntd.NotificationReadDate     = null;
                _notifications.InsertNotification(ntd);
                #endregion
            }

            return(0);
        }
        // GET: LeaveApplication/_Leave
        public ActionResult Leave()
        {
            LeaveApplicationViewModel applicationVM = new LeaveApplicationViewModel();
            List <LeaveBalance>       LeaveBalances = new List <LeaveBalance>();

            //get manager droplist
            ViewBag.Manager   = Manager.GetManagerItems();
            ViewBag.LeaveType = LeaveApplication.GetLeaveTypeItems();
            for (int i = 1; i < 4; i++)
            {
                var availableLeave = contextDb.LeaveBalances.Find(User.Identity.Name, (_leaveType)i);
                LeaveBalances.Add(availableLeave == null ? new LeaveBalance() : availableLeave);
            }
            applicationVM.LeaveBalances = LeaveBalances;

            return(PartialView(@"~/Views/LeaveApplication/_Leave.cshtml", applicationVM));
        }
Example #12
0
        /// <summary>
        ///     Create a tab page for user to fill and submit a HR application.
        /// </summary>
        /// <returns>A partial view with details of an application.</returns>
        public ActionResult Leave()
        {
            LeaveApplicationViewModel model         = new LeaveApplicationViewModel();
            List <LeaveBalance>       LeaveBalances = new List <LeaveBalance>();

            //get manager dropdown list
            ViewBag.Manager = UserRoleSetting.GetManagerItems();

            for (int i = 0; i < 3; i++)
            {
                var availableLeave = contextDb.LeaveBalances.Find(User.Identity.Name, (_leaveType)i);
                LeaveBalances.Add(availableLeave == null ? new LeaveBalance() : availableLeave);
            }
            model.LeaveBalances = LeaveBalances;

            return(PartialView("_Leave", model));
        }
Example #13
0
        public ActionResult RefuseAnnualLeaveApplicationForm(string leaveApplicationId)
        {
            var leaveApplication = _context.LeaveApplications.Where(l => l.Id.ToString() == leaveApplicationId).FirstOrDefault();
            LeaveApplicationViewModel leaveApplicationViewModel = new LeaveApplicationViewModel()
            {
                Id            = leaveApplication.Id.ToString(),
                StartDateTime = leaveApplication.StartDate,
                EndDateTime   = leaveApplication.EndDate,
                TotalDays     = leaveApplication.TotalDays,
                ApproverEmail = leaveApplication.Approver.Email,
                Description   = leaveApplication.Discription,
                Comment       = leaveApplication.Comment,
                TaskState     = leaveApplication.TaskState,
                LeaveType     = leaveApplication.LeaveType,
                InitiatorId   = leaveApplication.Initiator.Id
            };

            return(PartialView(leaveApplicationViewModel));
        }
Example #14
0
        /// <summary>
        ///     Create a list of <see cref="TimeRecord"/> for the applicant to edit details
        ///     on each day of an HR application.
        /// </summary>
        /// <param name="start">The start day of the HR application</param>
        /// <param name="end">The end day of the HR application</param>
        /// <param name="leaveType">The main leave type of the application. It is also the default
        ///     leave type of each <see cref="TimeRecord"/> in the period.</param>
        /// <returns>A partial view with a list of <see cref="TimeRecord"/> to edit leave details.</returns>
        public ActionResult CreateLeaveList(DateTime start, DateTime end, _leaveType leaveType)
        {
            // Create new Leaveapplication
            LeaveApplicationViewModel model          = new LeaveApplicationViewModel();
            List <TimeRecord>         newTimeRecords = new List <TimeRecord>();
            //get leave type for holidays
            IEnumerable <SelectListItem> items = new List <SelectListItem>()
            {
                new SelectListItem
                {
                    Text     = "Flexi Hours (earned)",
                    Value    = _leaveType.flexiHours.ToString(),
                    Selected = true
                },
                new SelectListItem
                {
                    Text  = "Additional Hours",
                    Value = _leaveType.additionalHours.ToString()
                }
            };

            ViewBag.HolidayLeaveTypeItems = items;

            for (int i = 0; i <= (end - start).Days; i++)
            {
                // Create new timerecords
                DateTime currentDate   = start.AddDays(i);
                var      newTimeRecord = new TimeRecord(currentDate.Date);
                PayPeriod.SetPublicHoliday(newTimeRecord);

                newTimeRecord.LeaveTime = (newTimeRecord.IsHoliday) ? 0 : 7.60;
                newTimeRecord.SetAttendence(null, null, 0);
                newTimeRecord.UserID    = User.Identity.Name;
                newTimeRecord.LeaveType = leaveType;
                newTimeRecords.Add(newTimeRecord);
            }
            model.TimeRecords = newTimeRecords;

            return(PartialView("_LeaveList", model));
        }
Example #15
0
        public ActionResult ModifyAnnualLeave(LeaveApplicationViewModel leaveApplicationViewModel, string leaveApplicationId)
        {
            if (!ModelState.IsValid)
            {
                return(View(leaveApplicationViewModel));
            }

            try
            {
                LeaveApplication leaveApplication = _context.LeaveApplications.Find(new Guid(leaveApplicationId));
                leaveApplication.StartDate   = leaveApplicationViewModel.StartDateTime;
                leaveApplication.EndDate     = leaveApplicationViewModel.EndDateTime;
                leaveApplication.Discription = leaveApplicationViewModel.Description;
                leaveApplication.Comment     = leaveApplicationViewModel.Comment;
                User user = _context.Users.Find(HttpContext.User.Identity.GetUserId());
                if (!LeaveApplicationHelper.CanApprove(user, leaveApplicationViewModel.ApproverEmail))
                {
                    throw new InvalidOperationException("请填写正确的审批人邮箱地址");
                }
                User approver = _context.Users.Where(u => u.Email == leaveApplicationViewModel.ApproverEmail).FirstOrDefault();
                leaveApplication.Approver  = approver;
                leaveApplication.TotalDays = LeaveApplicationHelper.CaculateTotalDays(leaveApplicationViewModel.StartDateTime, leaveApplicationViewModel.EndDateTime, _context);
                leaveApplication.TaskState = TaskState.Applying;
                _leaveApplicationService.ModifyLeaveApplication(leaveApplication);
                return(RedirectToAction("MyAnnualLeave"));
            }
            catch (InvalidOperationException invalidException)
            {
                ModelState.AddModelError("", invalidException.Message);
            }
            catch (Exception e)
            {
                _logger.Error("Failed to create a new Annual Leave application", e);
                ModelState.AddModelError("", e.Message);
            }
            return(View(leaveApplicationViewModel));
        }
        public async Task <ActionResult> Leave(LeaveApplicationViewModel applicationVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    double[] takenLeaves = new double[3];
                    foreach (var l in applicationVM.TimeRecords)
                    {
                        int index = (int)l.LeaveType - 1;
                        takenLeaves[index] += l.LeaveTime;
                    }

                    // Transfer attachments to ViewModel
                    if (applicationVM.Attachments.Count > 0)
                    {
                        List <LeaveAttachment> files = new List <LeaveAttachment>();
                        foreach (var file in applicationVM.Attachments)
                        {
                            if (file.ContentLength > 0)
                            {
                                var attachment = new LeaveAttachment
                                {
                                    FileName    = System.IO.Path.GetFileName(file.FileName),
                                    ContentType = file.ContentType
                                };
                                using (var reader = new System.IO.BinaryReader(file.InputStream))
                                {
                                    attachment.Content = reader.ReadBytes(file.ContentLength);
                                }
                                files.Add(attachment);
                            }
                        }
                        applicationVM.LeaveApplication.Attachments = files;
                    }

                    // Try to fetch Leaveapplication from DB if it exists
                    applicationVM.LeaveApplication.UserID = User.Identity.Name;
                    var application = (from a in contextDb.LeaveApplications
                                       where DbFunctions.TruncateTime(a.StartTime) == applicationVM.LeaveApplication.StartTime.Date &&
                                       DbFunctions.TruncateTime(a.EndTime) == applicationVM.LeaveApplication.EndTime.Date &&
                                       a.UserID == applicationVM.LeaveApplication.UserID
                                       select a).FirstOrDefault();

                    foreach (var r in applicationVM.TimeRecords)
                    {
                        // Configure time record if it's not a full day off
                        if (r.LeaveTime != 7.5)
                        {
                            r.SetAttendence(9, 17 - r.LeaveTime, 0.5);
                        }

                        // Sum up total leave time
                        applicationVM.LeaveApplication.TotalTime += r.LeaveTime;

                        // Try to fetch TimeRecord from DB if it exists
                        var timeRecord = (from a in contextDb.TimeRecords
                                          where DbFunctions.TruncateTime(a.RecordDate) == r.RecordDate.Date &&
                                          a.UserID == r.UserID
                                          select a).FirstOrDefault();

                        // Update TimeRecord if exists, Add if not
                        if (timeRecord == null)
                        {
                            contextDb.TimeRecords.Add(r);
                        }
                        else
                        {
                            int index = (int)timeRecord.LeaveType - 1;
                            takenLeaves[index]  -= timeRecord.LeaveTime;
                            timeRecord.LeaveTime = r.LeaveTime;
                            timeRecord.LeaveType = r.LeaveType;
                            contextDb.Entry(timeRecord).State = EntityState.Modified;
                        }
                        contextDb.SaveChanges();
                    }

                    // Update LeaveApplication if exists, add if not
                    if (application == null)
                    {
                        applicationVM.LeaveApplication.status = _status.submited;
                        contextDb.LeaveApplications.Add(applicationVM.LeaveApplication);
                    }
                    else
                    {
                        application.status    = _status.modified;
                        application.leaveType = applicationVM.LeaveApplication.leaveType;
                        application.ManagerID = applicationVM.LeaveApplication.ManagerID;
                        application.Comment   = applicationVM.LeaveApplication.Comment;
                        application.TotalTime = applicationVM.LeaveApplication.TotalTime;
                        contextDb.Entry(application).State = EntityState.Modified;
                    }
                    contextDb.SaveChanges();

                    // Update user leaves data in Db after submitting if it's leave application
                    if (applicationVM.LeaveApplication.leaveType != _leaveType.none)
                    {
                        for (int i = 1; i < 4; i++)
                        {
                            var LeaveBalance = contextDb.LeaveBalances.Find(User.Identity.Name, (_leaveType)i);
                            if (LeaveBalance == null)
                            {
                                LeaveBalance                      = new LeaveBalance();
                                LeaveBalance.LeaveType            = (_leaveType)i;
                                LeaveBalance.UserID               = User.Identity.Name;
                                LeaveBalance.AvailableLeaveHours -= takenLeaves[i - 1];
                                contextDb.LeaveBalances.Add(LeaveBalance);
                            }
                            else
                            {
                                LeaveBalance.AvailableLeaveHours   -= takenLeaves[i - 1];
                                contextDb.Entry(LeaveBalance).State = EntityState.Modified;
                            }
                            contextDb.SaveChanges();
                        }
                    }

                    // Send an email to manager
                    var applicationModel = (from a in contextDb.LeaveApplications
                                            where DbFunctions.TruncateTime(a.StartTime) == applicationVM.LeaveApplication.StartTime.Date &&
                                            DbFunctions.TruncateTime(a.EndTime) == applicationVM.LeaveApplication.EndTime.Date &&
                                            a.UserID == applicationVM.LeaveApplication.UserID
                                            select a).FirstOrDefault();

                    if (applicationModel != null)
                    {
                        Task.Run(() => EmailSetting.SendEmail(applicationModel.ManagerID, string.Empty, "LeaveApplication", applicationModel.id.ToString()));
                    }
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
            }
            return(RedirectToAction("Index"));
        }
Example #17
0
        public async Task <ActionResult> Leave(LeaveApplicationViewModel applicationVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // Initialise variables
                    double[] appliedLeaveTimes = new double[3];
                    string   originalBalances  = String.Empty;

                    // Record Submitted Time
                    applicationVM.LeaveApplication.SubmittedTime = DateTime.Now;

                    // Calculate applied leave times and group by leavetype
                    foreach (var l in applicationVM.TimeRecords)
                    {
                        // Compassionate pay will take Sick leave balance
                        if (l.LeaveType == _leaveType.compassionatePay)
                        {
                            appliedLeaveTimes[(int)_leaveType.sick] += l.LeaveTime;
                        }
                        // Subtract balance for Sick Leave, Flexi Leave, and Annual Leave
                        else if ((int)l.LeaveType < 3)
                        {
                            appliedLeaveTimes[(int)l.LeaveType] += l.LeaveTime;
                        }
                        // Flexi hours will increase Flexi leave balance
                        else if (l.LeaveType == _leaveType.flexiHours)
                        {
                            appliedLeaveTimes[(int)_leaveType.flexi] -= l.LeaveTime;
                        }
                    }

                    // Update TimeRecords in Db
                    foreach (var r in applicationVM.TimeRecords)
                    {
                        // Configure attendance of a TimeRecord
                        if (r.LeaveType == _leaveType.flexiHours ||
                            r.LeaveType == _leaveType.additionalHours)
                        {
                            if (r.LeaveTime < 14.5)
                            {
                                r.SetAttendence(9, 9.5 + r.LeaveTime, 0.5);
                            }
                            else
                            {
                                r.SetAttendence(12 - r.LeaveTime / 2.0, 12 + r.LeaveTime / 2.0, 0);
                            }
                        }
                        else
                        {
                            if (r.LeaveTime <= 7.6)
                            {
                                r.SetAttendence(9, 17 - r.LeaveTime, 0.5);
                            }
                        }

                        // Sum up total leave time
                        applicationVM.LeaveApplication.TotalLeaveTime += r.LeaveTime;

                        // Try to fetch TimeRecord from Db if it exists
                        var timeRecord = (from a in contextDb.TimeRecords
                                          where DbFunctions.TruncateTime(a.RecordDate) == r.RecordDate.Date &&
                                          a.UserID == r.UserID
                                          select a).FirstOrDefault();

                        // Update TimeRecord if exists, add if not
                        if (timeRecord == null)
                        {
                            contextDb.TimeRecords.Add(r);
                        }
                        else
                        {
                            // Record the difference of applied leave time and the balance in Db
                            if (timeRecord.LeaveType != null)
                            {
                                // Compassionate pay will take Sick leaves balance
                                if (timeRecord.LeaveType == _leaveType.compassionatePay)
                                {
                                    appliedLeaveTimes[(int)_leaveType.sick] -= timeRecord.LeaveTime;
                                }
                                // Flexi hours will increase Flexi leave balance
                                else if (timeRecord.LeaveType == _leaveType.flexiHours)
                                {
                                    appliedLeaveTimes[(int)_leaveType.flexi] += timeRecord.LeaveTime;
                                }
                                // Subtract balance for Sick Leave, Flexi Leave, and Annual Leave
                                else if ((int)timeRecord.LeaveType < 3)
                                {
                                    appliedLeaveTimes[(int)timeRecord.LeaveType] -= timeRecord.LeaveTime;
                                }
                            }

                            timeRecord.LeaveTime = r.LeaveTime;
                            timeRecord.LeaveType = r.LeaveType;
                            contextDb.Entry(timeRecord).State = EntityState.Modified;
                        }
                    }

                    // Transfer attachments to ViewModel
                    if (applicationVM.Attachments.Count != 0)
                    {
                        List <LeaveAttachment> files = new List <LeaveAttachment>();
                        foreach (var file in applicationVM.Attachments)
                        {
                            if (file != null && file.ContentLength > 0)
                            {
                                var attachment = new LeaveAttachment
                                {
                                    FileName    = System.IO.Path.GetFileName(file.FileName),
                                    ContentType = file.ContentType
                                };
                                using (var reader = new System.IO.BinaryReader(file.InputStream))
                                {
                                    attachment.Content = reader.ReadBytes(file.ContentLength);
                                }
                                files.Add(attachment);
                            }
                        }
                        applicationVM.LeaveApplication.Attachments = files;
                    }

                    // Update user leaves balance in Db after submitting
                    for (int i = 0; i < 3; i++)
                    {
                        var LeaveBalance = contextDb.LeaveBalances.Find(User.Identity.Name, (_leaveType)i);
                        if (LeaveBalance == null)
                        {
                            originalBalances += "0.00";
                            LeaveBalance      = new LeaveBalance()
                            {
                                LeaveType           = (_leaveType)i,
                                UserID              = User.Identity.Name,
                                AvailableLeaveHours = 0
                            };
                            contextDb.LeaveBalances.Add(LeaveBalance);
                        }
                        else
                        {
                            originalBalances += string.Format("{0:0.00}", LeaveBalance.AvailableLeaveHours);
                            LeaveBalance.AvailableLeaveHours   -= appliedLeaveTimes[i];
                            contextDb.Entry(LeaveBalance).State = EntityState.Modified;
                        }
                        if (i != 2)
                        {
                            originalBalances += "/";
                        }
                        //contextDb.SaveChanges();
                    }

                    // Try to fetch Leaveapplication from DB if it exists
                    applicationVM.LeaveApplication.UserID = User.Identity.Name;
                    var application = (from a in contextDb.LeaveApplications
                                       where DbFunctions.TruncateTime(a.StartTime) == applicationVM.LeaveApplication.StartTime.Date &&
                                       DbFunctions.TruncateTime(a.EndTime) == applicationVM.LeaveApplication.EndTime.Date &&
                                       a.UserID == applicationVM.LeaveApplication.UserID
                                       select a).FirstOrDefault();

                    // Update LeaveApplication if exists, add if not
                    if (application == null)
                    {
                        applicationVM.LeaveApplication.status           = _status.submited;
                        applicationVM.LeaveApplication.UserName         = contextDb.ADUsers.Find(User.Identity.Name).UserName;
                        applicationVM.LeaveApplication.OriginalBalances = originalBalances;
                        contextDb.LeaveApplications.Add(applicationVM.LeaveApplication);
                    }
                    else
                    {
                        application.status                 = _status.modified;
                        application.leaveType              = applicationVM.LeaveApplication.leaveType;
                        application.ManagerIDs             = applicationVM.LeaveApplication.ManagerIDs;
                        application.Comment                = applicationVM.LeaveApplication.Comment;
                        application.ApprovedBy             = null;
                        application.ApprovedTime           = null;
                        application.TotalLeaveTime         = applicationVM.LeaveApplication.TotalLeaveTime;
                        contextDb.Entry(application).State = EntityState.Modified;
                    }
                    contextDb.SaveChanges();

                    // Send an email to manager
                    var applicationModel = (from a in contextDb.LeaveApplications
                                            where DbFunctions.TruncateTime(a.StartTime) == applicationVM.LeaveApplication.StartTime.Date &&
                                            DbFunctions.TruncateTime(a.EndTime) == applicationVM.LeaveApplication.EndTime.Date &&
                                            a.UserID == applicationVM.LeaveApplication.UserID
                                            select a).FirstOrDefault();

                    if (applicationModel != null)
                    {
                        foreach (var mangerId in applicationModel._managerIDs)
                        {
                            await Task.Run(() => EmailSetting.SendEmail(mangerId, string.Empty, "LeaveApplication", applicationModel.id.ToString()));
                        }
                    }

                    return(RedirectToAction("PostRequest", new { status = postRequestStatus.success }));
                }
                //TempData["ErrorModel"] = ModelState.Values;
                return(RedirectToAction("PostRequest", new { status = postRequestStatus.fail }));
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            catch (Exception e)
            {
                throw e;
            }
            return(RedirectToAction("PostRequest", new { status = postRequestStatus.fail }));
        }
Example #18
0
        /// <summary>
        ///     Create a page for a user to view details of a submitted application.
        /// </summary>
        /// <param name="id">The identifier of the <see cref="LeaveApplication"/>.</param>
        /// <returns>A view with details of an application.</returns>
        // GET: LeaveApplication/ApplicationDetail
        public ActionResult ApplicationDetail(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            LeaveApplicationViewModel model = new LeaveApplicationViewModel();

            // Get the appliction from DB
            var application = contextDb.LeaveApplications
                              .Include(a => a.Attachments)
                              .SingleOrDefault(a => a.id == id);

            if (application == null)
            {
                return(HttpNotFound("The application you request does not exist in our database. Please contact our IT support."));
            }
            else
            {
                model.LeaveApplication = application;
                model.TimeRecords      = application.GetTimeRecords();
                model.LeaveApplication = application;

                // Get manager names for dropdown list
                List <string> managerNames = new List <string>();
                foreach (var managerId in application._managerIDs)
                {
                    managerNames.Add(contextDb.ADUsers.Find(managerId).UserName);
                }
                ViewBag.Managers = managerNames;

                if (application.ApprovedTime != null)
                {
                    // Get leave balance
                    List <LeaveBalance> LeaveBalances = new List <LeaveBalance>();
                    if (application.OriginalBalances != null)
                    {
                        ViewBag.OriginalBalances = application.OriginalBalances.Split('/');
                    }
                    else
                    {
                        ViewBag.OriginalBalances = new string[] { "", "", "" }
                    };

                    if (application.CloseBalances != null)
                    {
                        ViewBag.CloseBalances = application.CloseBalances.Split('/');
                    }
                    else
                    {
                        ViewBag.CloseBalances = new string[] { "", "", "" }
                    };

                    // Get the manager who signed, if it is singed
                    if (application.ApprovedBy != null)
                    {
                        ViewBag.SignedManager = contextDb.ADUsers.Find(application.ApprovedBy).UserName;
                    }
                    else
                    {
                        ViewBag.SignedManager = string.Empty;
                    }
                }
                return(View(model));
            }
        }
Example #19
0
        public int NoftificationLeaveRequestApprove(LeaveApplicationViewModel lat)
        {
            EmployeeDetailsViewModel user     = _employeeService.GetEmployeeDetails(lat.LeaveEmpCode);
            EmployeeDetailsViewModel recomend = _employeeService.GetEmployeeDetails(Convert.ToInt32(lat.LeaveRecommenderEmpcode));
            EmployeeDetailsViewModel approver = _employeeService.GetEmployeeDetails(Convert.ToInt32(lat.LeaveApproverEmpcode));


            if (lat.LeaveStatus == 2)
            {
                #region NotificationUser
                NotificationsDTOs ntd = new NotificationsDTOs();
                ntd.NotificationDate         = DateTime.Now;
                ntd.NotificationReceiverId   = Convert.ToInt32(user.Code);
                ntd.NotificationSubject      = lat.LeaveTypeName + " Request has been approved";
                ntd.NotificationMessage      = lat.LeaveTypeName + " requested on " + lat.LeaveAppliedDate.ToString("yyyy,MM dd") + " is Approved by " + approver.Name;
                ntd.NotificationReceiverType = "E";
                ntd.NotificationDetailURL    = "/user/leave/detail/" + lat.LeaveId;
                ntd.NotificationReadDate     = null;
                _notifications.InsertNotification(ntd);
                #endregion
                #region Notificationrecommender
                NotificationsDTOs ntf = new NotificationsDTOs();
                ntf.NotificationDate         = DateTime.Now;
                ntf.NotificationReceiverId   = recomend.Code;
                ntf.NotificationSubject      = "Recommended Leave request has been approved ";
                ntf.NotificationMessage      = lat.LeaveTypeName + " requested by" + user.Name + " on " + lat.LeaveAppliedDate.ToString("yyyy-MMM-dd") + " is aproved by" + approver.Name;
                ntf.NotificationReceiverType = "E";
                ntf.NotificationDetailURL    = "/user/leaveapplication/recommend/" + lat.LeaveId;
                ntf.NotificationReadDate     = null;
                _notifications.InsertNotification(ntf);
                #endregion
            }
            else
            if (lat.LeaveStatus == 3)
            {
                #region NotificationUser
                NotificationsDTOs ntd = new NotificationsDTOs();
                ntd.NotificationDate         = DateTime.Now;
                ntd.NotificationReceiverId   = Convert.ToInt32(user.Code);
                ntd.NotificationSubject      = "Approver reject your " + lat.LeaveTypeName + "  request";
                ntd.NotificationMessage      = lat.LeaveTypeName + " requested on " + lat.LeaveAppliedDate.ToString("yyyy,MM dd") + " is Rejected by " + approver.Name;
                ntd.NotificationReceiverType = "E";
                ntd.NotificationDetailURL    = "/user/leave/detail/" + lat.LeaveId;
                ntd.NotificationReadDate     = null;
                _notifications.InsertNotification(ntd);
                #endregion
                #region Notificationrecommender
                NotificationsDTOs ntf = new NotificationsDTOs();
                ntf.NotificationDate         = DateTime.Now;
                ntf.NotificationReceiverId   = recomend.Code;
                ntf.NotificationSubject      = "Recommended Leave request has been Rejected ";
                ntf.NotificationMessage      = lat.LeaveTypeName + "  Request of " + user.Name + " requested on " + lat.LeaveAppliedDate.ToString("yyyy,MM dd") + "  is rejected by" + approver.Name;
                ntf.NotificationReceiverType = "E";
                ntf.NotificationDetailURL    = "/user/leave/detail/" + lat.LeaveId;
                ntf.NotificationReadDate     = null;
                _notifications.InsertNotification(ntf);
                #endregion
            }


            return(0);
        }