Example #1
0
        public HttpResponseMessage SendPasswordResetEmail([FromBody] UserDetail UserDetail)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.ExpectationFailed);

            Models.Security.User user = null;
            using (EverestPortalContext context = new EverestPortalContext())
            {
                user = context.Users.Where(x => x.UserName == UserDetail.UserName && x.IsActive == true)
                       .FirstOrDefault();
            }

            if (user != null && user.Email != "" && user.IsPasswordVerified && Request.Headers.Contains("Origin"))
            {
                AuthController authController = new AuthController();
                string         callBackUrl    = Request.Headers.GetValues("Origin").FirstOrDefault() + "/#/?resettoken=" + HttpUtility.UrlEncode(authController.GenerateHashedResetToken(user.UserID));
                string         emailBody      = CreatePasswordResetEmailBody(user, callBackUrl);
                authController.SendEmail(user.Email, "Everest: Password reset", emailBody);
                response = Request.CreateResponse(HttpStatusCode.OK, new { isSuccess = true, message = "An email has been sent to " + user.Email + " successfully." });
            }
            else if (user != null && !user.IsPasswordVerified)
            {
                response = Request.CreateResponse(HttpStatusCode.OK, new { isSuccess = false, message = "Your password link has not yet been verified. Please contact support." });
            }
            else
            {
                response = Request.CreateResponse(HttpStatusCode.OK, new { isSuccess = false, message = "User inactive or email address invalid." });
            }
            return(response);
        }
Example #2
0
        public static List <Alert> GenerateAlerts(Models.Security.User user)
        {
            User   = user;
            alerts = checkForDaysThatAreNotUpdated();

            return(alerts);
        }
Example #3
0
        public static IList <Models.Security.User> UserList(Models.Security.User filter = null)
        {
            var urlApi  = ConfigurationManager.AppSettings["Api_Rede"];
            var request = new Models.Security.User();

            urlApi = @"http://localhost:49344/api/";

            if (filter != null)
            {
                request = filter;
            }

            string reqString    = JsonConvert.SerializeObject(request);
            var    retApiString = CallWebApi.CallWebApiGet(null, urlApi + "/usuarios/");
            var    retApi       = retApiString.Result;
            var    ret          = new List <Models.Security.User>();

            List <Dictionary <string, string> > date = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(retApi);

            foreach (Dictionary <string, string> lst in date)
            {
                var register = new Models.Security.User();
                foreach (KeyValuePair <string, string> item in lst)
                {
                    if (register != null)
                    {
                        if (!string.IsNullOrEmpty(item.Key))
                        {
                            if (item.Value != null)
                            {
                                register.UsuarioId = item.Key.ToLower().Trim() ==
                                                     "usuarioid" ? int.Parse(item.Value) : register.UsuarioId;
                                register.Nome          = item.Key.ToLower().Trim() == "nome" ? item.Value : register.Nome;
                                register.Apelido       = item.Key.ToLower().Trim() == "apelido" ? item.Value : register.Apelido;
                                register.Email         = item.Key.ToLower().Trim() == "email" ? item.Value : register.Email;
                                register.Login         = item.Key.ToLower().Trim() == "login" ? item.Value : register.Login;
                                register.Senha         = item.Key.ToLower().Trim() == "senha" ? item.Value : register.Senha;
                                register.UsuarioTipoId =
                                    item.Key.ToLower().Trim() == "usuariotipoId" ? int.Parse(item.Value) : register.UsuarioTipoId;
                                register.CadastroDataHora
                                    = item.Key.ToLower().Trim() == "cadastrodatahora" ? DateTime.Parse(item.Value) : register.CadastroDataHora;
                                register.CadastroUsuarioId
                                    = item.Key.ToLower().Trim() == "cadastrousuarioid" ? int.Parse(item.Value) : register.CadastroUsuarioId;
                                register.AtualizacaoDataHora
                                    = item.Key.ToLower().Trim() == "atualizacaodatahora" ? DateTime.Parse(item.Value) : register.AtualizacaoDataHora;
                                register.AtualizacaoUsuarioId =
                                    item.Key.ToLower().Trim() == "atualizacaousuarioid" ? int.Parse(item.Value) : register.AtualizacaoUsuarioId;
                            }
                        }
                    }
                }
                ret.Add(register);
            }

            return(ret);
        }
Example #4
0
        public DayRecord(List <DBContext.Main_Data> records, Models.Security.User user)
        {
            if (records.Count == 0 || records == null)
            {
                throw new ArgumentNullException("The argument cannot be null, or have 0 records");
            }

            this.records = records;
            this.user    = user;
        }
        //public ActionResult CheckIn(Models.Portal.Action data)
        //{
        //    //Get the date in UTC Format;
        //    DateTime CurrentTime = DateTime.UtcNow;
        //    DateTime PreviousTime = DateTime.UtcNow.AddDays(-1);

        //    //get user from the sessiopn
        //    Models.Security.User user = GetUserFromSession();
        //    if (user != null)
        //    {
        //        //IF the user didnt select any status and any project then we create a record in login table and another one in main data with Available as default
        //        //check if the user has  clock out already
        //        var clockedOut = db.User_Login_Logout.Where(x => x.UserId == user.ID && x.LoginTime.Value > PreviousTime && x.LogoutTime != null).OrderByDescending(x => x.LogoutTime).FirstOrDefault();
        //        if (clockedOut != null)
        //            return Json(new { result = false, message = "Already Clocked Out for today!" }, JsonRequestBehavior.AllowGet);

        //        //check if the user has  clock In already
        //        var clockedIn = db.User_Login_Logout.Where(x => x.UserId == user.ID && x.LoginTime.Value > PreviousTime && x.LogoutTime == null).OrderByDescending(x => x.LogoutTime).FirstOrDefault();
        //        if (clockedOut != null)
        //            return Json(new { result = false, message = "Already Clocked In for today!" }, JsonRequestBehavior.AllowGet);

        //        //Create a login object
        //        DBContext.User_Login_Logout login = new DBContext.User_Login_Logout
        //        {
        //            UserId = user.ID,
        //            Date = CurrentTime,
        //            LoginTime = CurrentTime,
        //        };
        //        db.User_Login_Logout.Add(login);


        //        //create a main data record with projectID as 0 and Status as Available as default!;
        //        DBContext.Main_Data mainData = new DBContext.Main_Data
        //        {
        //            userID = user.ID,
        //            CurrentDate = CurrentTime,
        //            Status_Start_Time = CurrentTime,
        //            ProjectID = 0,
        //            Current_Status = "Available",
        //            Comments = data.Comment

        //        };


        //        if (data.ProjectId >= 0)
        //            mainData.ProjectID = data.ProjectId;

        //        if (data.Type != "0")
        //            mainData.Current_Status = data.Type;


        //        //if(data.Type != "0" && data.ProjectId ==0)
        //        //    return Json(new { result = false, message = "Need to select a project!" }, JsonRequestBehavior.AllowGet);

        //        try
        //        {
        //            db.Main_Data.Add(mainData);
        //            db.SaveChanges();

        //            return Json(new { result = true, message = "Clocked In!" , location = Url.Action("Overview", "Portal")}, JsonRequestBehavior.AllowGet);
        //        }
        //        catch (Exception ex)
        //        {
        //            //Log the exception

        //            return Json(new { result = false, message = "Something happen! Please try again!" }, JsonRequestBehavior.AllowGet);
        //        }


        //    }
        //    else
        //    {
        //        return RedirectToAction("Index", "Home");
        //    }


        //}

        //public ActionResult UpdateStatus(Models.Portal.Action data)
        //{
        //    //Get the date in UTC Format;
        //    DateTime CurrentTime = DateTime.UtcNow;
        //    DateTime PreviousTime = DateTime.UtcNow.AddDays(-1);

        //    Models.Security.User user = GetUserFromSession();
        //    if (user != null)
        //    {
        //        if (data.Type == "0")
        //            return Json(new { result = false, message = "Please select a status!" }, JsonRequestBehavior.AllowGet);

        //        if(data.ProjectId == 0)
        //            return Json(new { result = false, message = "Please select a Project!" }, JsonRequestBehavior.AllowGet);



        //        //check if the user has clock in and if not clock out for today
        //        var clockedOut = db.User_Login_Logout.Where(x => x.UserId == user.ID && x.LoginTime.Value > PreviousTime && x.LogoutTime != null).OrderByDescending(x => x.LoginTime).FirstOrDefault();
        //        if (clockedOut != null)
        //            return Json(new { result = false, message = "Already Clocked, cannot change status!" }, JsonRequestBehavior.AllowGet);


        //        var clockedIn = db.User_Login_Logout.Where(x => x.UserId == user.ID && x.LoginTime.Value > PreviousTime && x.LogoutTime == null).OrderByDescending(x => x.LoginTime).FirstOrDefault();
        //        if (clockedIn == null)
        //            return Json(new { result = false, message = "Please Clock In First!" }, JsonRequestBehavior.AllowGet);


        //        //get the last records and set the EndStatus to now
        //        var addFinishTimelst = db.Main_Data.Where(x => x.userID == user.ID && x.Status_End_Time == null).OrderByDescending(x => x.Status_Start_Time).FirstOrDefault();
        //        if(addFinishTimelst != null)
        //        {
        //            try
        //            {
        //                addFinishTimelst.Status_End_Time = CurrentTime;
        //                db.SaveChanges();
        //            }
        //            catch (Exception ex)
        //            {

        //                //Log the exception

        //                return Json(new { result = false, message = "Something happen! Please try again!" }, JsonRequestBehavior.AllowGet);
        //            }

        //        }



        //        //create a main data record with projectID as 0 and Status as Available as default!;
        //        DBContext.Main_Data mainData = new DBContext.Main_Data
        //        {
        //            userID = user.ID,
        //            CurrentDate = CurrentTime,
        //            Status_Start_Time = CurrentTime,
        //            ProjectID = data.ProjectId,
        //            Current_Status = data.Type,
        //            Comments = Utilities.Helper.StripDangerousCharacters(data.Comment)

        //        };

        //        try
        //        {
        //            db.Main_Data.Add(mainData);
        //            db.SaveChanges();
        //            return Json(new { result = true, message = "Status Updated!", newobj = mainData }, JsonRequestBehavior.AllowGet);
        //        }
        //        catch (Exception ex)
        //        {
        //            //Log the exception

        //            return Json(new { result = false, message = "Something happen! Please try again!" }, JsonRequestBehavior.AllowGet);
        //        }


        //    }
        //    else
        //    {
        //        return RedirectToAction("Index", "Home");
        //    }


        //}

        //public ActionResult ClockOut()
        //{

        //    DateTime CurrentTime = DateTime.UtcNow;
        //    DateTime PreviousTime = DateTime.UtcNow.AddDays(-1);

        //    Models.Security.User user = GetUserFromSession();
        //    if (user != null)
        //    {
        //        //get the last Login Record
        //        var checkRecord = db.User_Login_Logout.Where(x => x.UserId == user.ID && x.LoginTime > PreviousTime && x.LogoutTime != null).OrderByDescending(x => x.LogoutTime).FirstOrDefault();
        //        if(checkRecord != null){
        //            return Json(new { result = false, message = "Already Clock Out Today!" }, JsonRequestBehavior.AllowGet);
        //        }

        //        var loginRecord = db.User_Login_Logout.Where(x => x.UserId == user.ID && x.LoginTime > PreviousTime && x.LogoutTime == null).OrderByDescending(x => x.LoginTime).FirstOrDefault();
        //        if(loginRecord != null)
        //        {
        //            loginRecord.LogoutTime = CurrentTime;
        //        }
        //        else
        //        {
        //            return Json(new { result = false, message = "You didn't Clock In for today!" }, JsonRequestBehavior.AllowGet);
        //        }

        //        //get the last records and set the EndStatus to now
        //        var addFinishTimelst = db.Main_Data.Where(x => x.userID == user.ID && x.Status_End_Time == null).OrderByDescending(x => x.Status_Start_Time).FirstOrDefault();
        //        if (addFinishTimelst != null)
        //        {
        //            addFinishTimelst.Status_End_Time = CurrentTime;

        //        }


        //        try
        //        {
        //            db.SaveChanges();
        //            //return Json(new { result = true, message = "Clock Out Successfully!" }, JsonRequestBehavior.AllowGet);
        //            return Json(new { result = true, message = "Clocked Out!", location = Url.Action("Overview", "Portal") }, JsonRequestBehavior.AllowGet);
        //        }
        //        catch (Exception ex)
        //        {
        //            //Log the exception

        //            return Json(new { result = false, message = "Something happen! Please try again!" }, JsonRequestBehavior.AllowGet);
        //        }

        //    }
        //    else
        //    {
        //        return RedirectToAction("Index", "Home");
        //    }
        //}


        #region Partial Requests

        //public ActionResult OvertimeRequest(Models.Portal.Partial_Request.OvertimeRequest req)
        //{
        //    //when a request is send
        //    //1. add a notification to the liveNotification table where we inform the manager that a new overtime request has been sent for appoval if the request is set for ManaualApprove
        //    //2. if the request is set for AutoApprove, then we just inform the manager that someone has requested for Overtime.

        //    //get ther user details from session
        //    var user = GetUserFromSession();
        //    if (user == null)
        //        return RedirectToAction("Overview");

        //    //add the current user as the User who made the request.
        //    req.AddUser(user);

        //    //Perform some checkes about the notification.
        //    //1. The request cannot be in the past;
        //    //2. The Request cannot be during shift time, so need to check for the starting time of the shift, then calculate the end time.
        //    //3. End time of the request cannot be higher then 4 hours per day. Maybe in here we can add some seetings on how much time an overtime can have.
        //    //4. Check for the duration to be higher then 0 minutes
        //    //5. check for the project, to be different then 0
        //    //6. check for the start time to be higher then 0
        //    DateTime currentTime = DateTime.UtcNow;

        //    //check for the start and end time
        //    if(DateTime.Compare(req.RequestDate, req.RequestDate.Add(req.Duration)) > 0)
        //    {
        //        return Json(new { result = false, message = "Start time cannot be later then End Time!" }, JsonRequestBehavior.AllowGet);
        //    }
        //    //check duration
        //    if(req.Duration.Ticks == 0)
        //    {
        //        return Json(new { result = false, message = "Duration need to be higher then 0!" }, JsonRequestBehavior.AllowGet);
        //    }
        //    if (req.StartTime.Ticks == 0)
        //    {
        //        return Json(new { result = false, message = "Start Time need to be higher then 0!" }, JsonRequestBehavior.AllowGet);
        //    }
        //    if (req.ProjectId == 0)
        //    {
        //        return Json(new { result = false, message = "Need to select a project!" }, JsonRequestBehavior.AllowGet);
        //    }
        //    //if the user didnt select a date, we cab take the date from the time, as it is basically the same!
        //    //Technically in the view we should check for this situation and not allow a empty date field
        //    if (req.RequestDate.Ticks == 0)
        //        req.RequestDate = req.StartTime;



        //    //Check if there is another request raised for the specific period and tell the user that cannot raise a new one.
        //    //if the request is already approve, need to contact the manager to request it
        //    //if the request is not approved you can cancel it, and then request a new one



        //    //check for the start time
        //    if (DateTime.Compare(req.RequestDate.Date, currentTime.Date) < 0)
        //    {
        //        return Json(new { result = false, message = "Cannot add Overtime for a past day!" }, JsonRequestBehavior.AllowGet);
        //    }
        //    else if(DateTime.Compare(req.RequestDate.Date, currentTime.Date) == 0)//current day
        //    {
        //        //check for the shift time.
        //        var shiftStart = db.User_Login_Logout.Where(x => x.UserId == user.ID && x.LoginTime.Value.Year == currentTime.Year && x.LoginTime.Value.Month == currentTime.Month && x.LoginTime.Value.Day == currentTime.Day).FirstOrDefault();
        //        if(shiftStart != null)
        //        {
        //            var userSettings = db.User_Settings.Find(user.ID);
        //            if(userSettings != null)
        //            {
        //                var supposeEnd = shiftStart.LoginTime.Value.Add(userSettings.ShiftTime.Value);
        //                if (DateTime.Compare(req.StartTime, supposeEnd) < 0)
        //                {
        //                    return Json(new { result = false, message = "Cannot request Overtime during shift period!" }, JsonRequestBehavior.AllowGet);
        //                }
        //            }
        //            else
        //            {
        //                return Json(new { result = false, message = "There has been an error. Contact the Administrator!" }, JsonRequestBehavior.AllowGet);
        //            }

        //        }
        //    }
        //    //in the future
        //    else
        //    {

        //    }

        //    //Get the Approve status from the compnay settings
        //    var companySettings = db.Companies_Assigned_Items.Where(x => x.Company_ID == user.Company).FirstOrDefault();
        //    if(companySettings == null)
        //    {
        //        //log the error
        //        //send error to the Dev team
        //        return Json(new { result = false, message = "There has been an error when processing your request!" }, JsonRequestBehavior.AllowGet);
        //    }

        //    List<string> AutoApproveLst = Utilities.Helper.convertStringtoList(companySettings.AutoApprove, ';');
        //    List<string> ManualApprove = Utilities.Helper.convertStringtoList(companySettings.ManualApprove, ';');

        //    if (AutoApproveLst.Contains(req.Type)) //if the request type is set to manual
        //    {
        //        //send notif tot the manager saying that the request has been autoApprove
        //        //autoApprove the request
        //        //since the request is set to autoApprove we can update directly the mai_data table with the request.
        //        //Add also a record into the partial Time Request table with the status of approved!
        //        try
        //        {
        //            //Add record into the partial Time Requests
        //            req.Status ="Approved";
        //            req.Approver = "System";
        //            req.AddRequest();

        //            //Add record into the main data
        //            var mainRecord = new Models.Portal.Action(req);
        //            mainRecord.AddRecord();

        //            //Create the notitication and send it to the Manager.
        //            string title = req.Type + " request!";
        //            string message = user.FirstName + " " + user.LastName + " has submited an " + req.Type + " request for the date of " + req.RequestDate.ToString("dd-MM-yyyy") + " with the starting time at " + req.StartTime.ToString("HH:mm") +
        //            " and a total duration of " + req.Duration + ". This request is Auto Approved due to System settings. If you still want to cancell this request you can access the Request page and search the request.";
        //            Hubs.LiveNotification.InsertNotification(user.ManagerID, DateTime.Now, title, message, user.ID, "Info");

        //            var notifCommTracker = new Models.Notification.Notification_Comm(req.getNotificationId(), DateTime.UtcNow, req.Comments, req.User.ID);
        //            notifCommTracker.AddNewRecord(notifCommTracker);

        //            //send email to the user who created the request.
        //        }
        //        catch (Exception ex)
        //        {

        //            //log the error
        //            return Json(new { result = false, message = "There has been an error when processing your request!" }, JsonRequestBehavior.AllowGet);
        //        }

        //    }
        //    else if (ManualApprove.Contains(req.Type)) //if the request type is set to auto
        //    {
        //        try
        //        {
        //            //Add record into the PartialTime_request db
        //            req.Status = "Pending";
        //            req.Approver = user.ManagerID;
        //            req.AddRequest();



        //            //send notification to the manager that there is a pending request
        //            string title = req.Type + " request pending for Approval!";

        //            string message = user.FirstName + " " + user.LastName + " has submited an " + req.Type + " request for the date of " + req.RequestDate.ToString("dd-MM-yyyy") + " with the starting time at " + req.StartTime.ToString("HH:mm") +
        //                    " and a total duration of " + req.Duration + ". The Request is waiting your feetback.";

        //            Hubs.LiveNotification.InsertNotification(user.ManagerID, DateTime.Now, title, message, user.ID, "Approve");

        //            var notifCommTracker = new Models.Notification.Notification_Comm(req.getNotificationId(), DateTime.UtcNow, req.Comments, req.User.ID);
        //            notifCommTracker.AddNewRecord(notifCommTracker);

        //            //send email to the manager with the user in CC
        //        }
        //        catch (Exception ex)
        //        {

        //            //log the error
        //            return Json(new { result = false, message = "There has been an error when processing your request!" }, JsonRequestBehavior.AllowGet);
        //        }

        //    }
        //    else
        //    {
        //        //log the error
        //        //send error to the Dev team
        //        return Json(new { result = false, message = "There has been an error when processing your request!" }, JsonRequestBehavior.AllowGet);
        //    }

        //    return Json(new { result = true, message = "Request has been submited!" }, JsonRequestBehavior.AllowGet);
        //}

        #endregion

        //public ActionResult ApproveRequest(string id, string comment = null)
        //{

        //    if (String.IsNullOrEmpty(id))
        //    {
        //        return Json(new { result = true, message = "There is a problem with the request. Contact Support Team!" }, JsonRequestBehavior.AllowGet);
        //    }

        //    var request = new Models.Portal.Partial_Request.OvertimeRequest(id);
        //    request.ApproveRequest();

        //    //add record into live notification



        //    return Json(new { result = true, message = "Request has been approved!" }, JsonRequestBehavior.AllowGet);
        //}

        //public ActionResult DeclineReqeust(string id)
        //{

        //    if (String.IsNullOrEmpty(id))
        //    {
        //        return Json(new { result = true, message = "There is a problem with the request. Contact Support Team!" }, JsonRequestBehavior.AllowGet);
        //    }

        //    var request = new Models.Portal.Partial_Request.OvertimeRequest(id);
        //    request.ApproveRequest();

        //    //add record into live notification



        //    return Json(new { result = true, message = "Request has been approved!" }, JsonRequestBehavior.AllowGet);
        //}

        #region SignalR


        public JsonResult GeLiveNotification()
        {
            Models.Security.User user = GetUserFromSession();

            List <Hubs.LiveNotification> notif = new List <Hubs.LiveNotification>();
            var liveNotif = new Hubs.LiveNotification(user.ID);

            notif = liveNotif.GetOpenNotificationByID();

            return(Json(notif, JsonRequestBehavior.AllowGet));
        }
Example #6
0
 public int InsertRecordIntoDb(Models.Security.User user)
 {
     if (user != null)
     {
         return(InsertRecord(GenerateDbRecord(user)));
     }
     else
     {
         throw new ArgumentNullException("User argument is null!");
     }
 }
Example #7
0
        public static Dictionary <string, string> getColorCoding(Models.Security.User user)
        {
            Dictionary <string, string> colorList = new Dictionary <string, string>();

            List <DBContext.Params> colorsDb = db.Params.Where(x => x.Identifier == "ColorCoding" & x.Active == true).Distinct().ToList();

            foreach (var item in colorsDb)
            {
                colorList.Add(item.Param1, item.Param2);
            }



            return(colorList);
        }
Example #8
0
        /// <summary>
        /// Cria um novo usuário.
        /// </summary>
        /// <param name="model">Modelo dos usuários</param>
        /// <returns></returns>
        public static UserViewModel UserCreate(UserViewModel model)
        {
            var           urlApi  = ConfigurationManager.AppSettings["Api_Rede"];
            var           request = new Models.Security.User();
            UserViewModel ret     = new UserViewModel();

            try
            {
                urlApi = @"http://localhost:49344//api";

                if (model != null)
                {
                    if (model.User != null)
                    {
                        request = model.User;
                    }
                }

                if (request != null)
                {
                    if (request.CadastroDataHora == null || request.CadastroDataHora <= DateTime.Now)
                    {
                        request.CadastroDataHora = DateTime.Now;
                    }
                    if (request.CadastroUsuarioId == 0)
                    {
                        request.CadastroUsuarioId = 1;
                    }
                }

                string reqString    = JsonConvert.SerializeObject(request);
                var    retApiString = CallWebApi.CallWebApiPost(reqString, urlApi + "/usuarios/post");

                ret.Message       = "Processado com sucesso!";
                ret               = ConvertJsonStringToUser(retApiString);
                ret.Success       = true;
                ret.PersistFields = false;
            }
            catch (Exception ex)
            {
                ret.Success       = false;
                ret.PersistFields = true;
                ret.Message       = ex.Message.ToString();
            }

            return(ret);
        }
Example #9
0
 private DBContext.Main_Data GenerateDbRecord(Models.Security.User user)
 {
     return(new DBContext.Main_Data
     {
         User_ID = user.ID,
         CurrentDate = this.currentDate,
         Status_Start_Time = startDate,
         Status_End_Time = endDate,
         Status = status,
         Project_ID = projectId,
         Project_Name = projectName,
         Title = title,
         Description = description,
         Tags = tagsforDb,
         TagsColors = tagsColorforDb
     });
 }
Example #10
0
        private string CreatePasswordResetEmailBody(Models.Security.User user, string callBackUrl)
        {
            StringBuilder emailBody = new StringBuilder();

            emailBody.Append(@"<div>");
            TextInfo textInfo         = new CultureInfo("en-US", false).TextInfo;
            string   userNameForEmail = "User";

            if (user.FirstName != "" && user.LastName != "")
            {
                userNameForEmail = textInfo.ToTitleCase(user.FirstName) + " " + textInfo.ToTitleCase(user.LastName);
            }
            emailBody.Append(@"Please do not reply to this system generated e-mail.<br/><br/>");
            emailBody.Append(@"Dear "); emailBody.Append(userNameForEmail); emailBody.Append(@", <br /><br />");
            emailBody.Append(@"Please reset your password by clicking here: <a href=" + callBackUrl + ">link</a>");
            emailBody.Append(@"<br/><br/>Thank you,<br/><br/>IQVIA<br/></div>");
            return(emailBody.ToString());
        }
Example #11
0
 public void LogOut()
 {
     IsLogedOut = true;
     IsLogedIn  = false;
     User       = null;
 }
Example #12
0
        public ActionResult MyTimeSheet()
        {
            Models.Security.User      user      = (Models.Security.User)Session["User"];
            Models.Security.AuthState userState = (Models.Security.AuthState)Session["AuthState"];

            if (user == null || userState == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var worklogsDb = db.Main_Data.Where(x => x.User_ID == user.ID).OrderByDescending(x => x.Status_Start_Time).Take(100);

            List <Models.Portal.WorkRecord> workLogs = new List <Models.Portal.WorkRecord>();

            foreach (var worklog in worklogsDb)
            {
                var newWorkLog = new Models.Portal.WorkRecord(worklog);
                workLogs.Add(newWorkLog);
            }
            //Get today date in UTC Format
            DateTime todayDate = DateTime.UtcNow.Date;

            //Get the public holidays
            var publicHolidaysDb = db.Public_Holidays.Where(x => x.Holiday_country == user.Country && x.Holiday_date >= todayDate.Date).ToList();
            List <Models.Portal.PublicHoliday> publicHolidays = new List <Models.Portal.PublicHoliday>();

            DateTime[] publicHolidaysAsArray = new DateTime[publicHolidaysDb.Count];
            int        counter = 0;

            foreach (var holiday in publicHolidaysDb)
            {
                publicHolidaysAsArray[counter] = holiday.Holiday_date.Value.Date;
                publicHolidays.Add(new Models.Portal.PublicHoliday(holiday));
                counter++;
            }


            List <DBContext.Leave>            thisYearleaves = db.Leaves.Where(x => x.StartDate.Value.Year == todayDate.Year && x.UserId == user.ID && x.EndDate.Value.Year == todayDate.Year).ToList();
            List <Models.Portal.Leave.ILeave> leaves         = new List <Models.Portal.Leave.ILeave>();

            foreach (var leave in thisYearleaves)
            {
                var newleave = new Models.Portal.Leave.Leave(leave, publicHolidaysAsArray);
                leaves.Add(newleave);
            }


            //Get the requested leaves
            List <DBContext.Leave_Requests> requestedLeavesDb = db.Leave_Requests.Where(x => x.Requestor == user.ID && x.RequestStartDate.Value >= todayDate.Date).ToList();

            foreach (var leave in requestedLeavesDb)
            {
                var newLeave = new Models.Portal.Leave.LeaveRequest(leave, publicHolidaysAsArray);
                leaves.Add(newLeave);
            }

            //Get the requested leaves
            List <DBContext.Leaves_Saved_Not_Submited> savedLeavesDb = db.Leaves_Saved_Not_Submited.Where(x => x.UserID == user.ID && x.StartDate.Value >= todayDate.Date).ToList();

            foreach (var leave in savedLeavesDb)
            {
                var newLeave = new Models.Portal.Leave.SavedLeave(leave, publicHolidaysAsArray);
                leaves.Add(newLeave);
            }



            //get a list of projects that the user is assign to
            var projectsDb = db.User_Assigned_Projects.Where(x => x.UserID == user.ID).ToList();
            List <Models.Portal.Project> projectsAssignedToUser = new List <Models.Portal.Project>();

            //add one item as default All projects with the value 0
            projectsAssignedToUser.Add(new Models.Portal.Project(0, "All projects", user.ID));

            foreach (var project in projectsDb)
            {
                projectsAssignedToUser.Add(
                    new Models.Portal.Project(project)
                    );
            }



            //Implement Dependency injection
            //Mostlikly is not needed
            var cb = new ContainerBuilder();

            //cb.RegisterType<List<Models.Portal.WorkRecord>>();
            //cb.RegisterType<List<Models.Portal.Leave.ILeave>>();

            cb.RegisterInstance(workLogs).As <List <Models.Portal.WorkRecord> >();
            cb.RegisterInstance(leaves).As <List <Models.Portal.Leave.ILeave> >();
            cb.RegisterInstance(projectsAssignedToUser).As <List <Models.Portal.Project> >();

            cb.RegisterType <Models.Activity.MyActivity>();

            var builder    = cb.Build();
            var myActivity = builder.Resolve <Models.Activity.MyActivity>();


            //Models.Activity.MyActivity myActivity = new Models.Activity.MyActivity();
            //myActivity.workLogs = workLogs;
            //myActivity.leaves = leaves;

            //Add values to session for further use when the user change the number of records to show
            SetMyStatSession(myActivity);
            Session.Timeout = 120;

            return(View(myActivity));
        }
Example #13
0
 public AuthState(User user, string timezone)
 {
     User     = user;
     TimeZone = timezone;
     GetUserSettings();
 }
Example #14
0
        public JsonResult AddTask(FormCollection formCollection)
        {
            Dictionary <string, string> erroredItems = new Dictionary <string, string>();
            bool errored = false;

            Models.Portal.WorkRecord record         = new Models.Portal.WorkRecord();
            Models.Portal.WorkRecord insertedRecord = null;
            Models.Security.User     user           = GetUserFromSession();


            //get the records fromt the session
            var myActivityFromSession = getMyActivityFromSession();
            var records = myActivityFromSession.workLogs;

            //get data from the formCollection
            var recordDateFm  = formCollection["currentDate"]; //2022/02/09
            var startTimeFm   = formCollection["startDate"];   //20:00
            var endTimeFm     = formCollection["endDate"];     //21:00
            var statusFm      = formCollection["status"];
            var projectIdFm   = formCollection["projectId"];
            var descriptionFm = formCollection["description"];
            var titleFm       = formCollection["title"];
            var tagsFm        = formCollection["tags"];
            var tagsColorFm   = formCollection["tagsColors"];

            DateTime recordDate = DateTime.UtcNow;
            DateTime startTime  = DateTime.UtcNow;
            DateTime endTime    = DateTime.UtcNow;
            string   tags       = null;
            string   tagsColor  = null;


            //validate Form Data
            //Validate recordDateFm
            if (!String.IsNullOrEmpty(recordDateFm))
            {
                string[]    dateFormats = new[] { "yyyy/MM/dd", "yyyy-MM-dd" };
                CultureInfo provider    = new CultureInfo("en-US");
                var         success     = DateTime.TryParseExact(recordDateFm, dateFormats, provider, DateTimeStyles.AssumeUniversal, out recordDate);
                if (!success)
                {
                    errored = true;
                    erroredItems.Add("currentDate", "Task Date is not valid!");
                }
            }
            else
            {
                errored = true;
                erroredItems.Add("currentDate", "Task Date is not valid!");
            }

            //validate startTimeFm
            if (!String.IsNullOrEmpty(startTimeFm))
            {
                string[]    dateFormats = new[] { "HH:mm", "HH:mm:ss" };
                CultureInfo provider    = new CultureInfo("en-US");
                try
                {
                    var tempStartTime = DateTime.ParseExact(startTimeFm, "HH:mm", CultureInfo.InvariantCulture);
                    startTime = (recordDate.Date + tempStartTime.TimeOfDay).ToUniversalTime();
                }
                catch (Exception ex)
                {
                    errored = true;
                    erroredItems.Add("startDate", "Start Time is not valid!");
                }
            }
            else
            {
                errored = true;
                erroredItems.Add("startDate", "Start Time is not valid!");
            }

            //validate endTimeFm
            if (!String.IsNullOrEmpty(endTimeFm))
            {
                string[]    dateFormats = new[] { "HH:mm", "HH:mm:ss" };
                CultureInfo provider    = new CultureInfo("en-US");
                try
                {
                    var tempEndTime = DateTime.ParseExact(endTimeFm, "HH:mm", CultureInfo.InvariantCulture);
                    endTime = (recordDate.Date + tempEndTime.TimeOfDay).ToUniversalTime();
                }
                catch (Exception ex)
                {
                    errored = true;
                    erroredItems.Add("endDate", "End Time is not valid!");
                }
            }
            else
            {
                errored = true;
                erroredItems.Add("endDate", "End Time is not valid!");
            }

            //Validate Status
            if (String.IsNullOrEmpty(statusFm))
            {
                errored = true;
                erroredItems.Add("status", "Task Status is not valid!");
            }
            //Validate project Id
            if (String.IsNullOrEmpty(projectIdFm))
            {
                errored = true;
                erroredItems.Add("projectId", "Selected Project is not valid!");
            }
            //Validate Description
            if (String.IsNullOrEmpty(descriptionFm))
            {
                errored = true;
                erroredItems.Add("description", "Please add a short description!");
            }
            //Validate Title
            if (String.IsNullOrEmpty(titleFm))
            {
                errored = true;
                erroredItems.Add("title", "Please add a title to the task!");
            }

            if (!string.IsNullOrEmpty(tagsFm))
            {
                tags = tagsFm.Replace(',', ' ');
            }
            if (!string.IsNullOrEmpty(tagsColorFm))
            {
                tagsColor = tagsColorFm.Replace("),", ");").Replace("0.1)", "1)").Replace(" ", "");
            }


            record = new Models.Portal.WorkRecord(recordDate, startTime, endTime, statusFm, Int32.Parse(projectIdFm), titleFm, descriptionFm, tags, tagsColor);
            int position = 1;
            Dictionary <string, string> validationErrors = CheckTaskForPotentialIssues(record, user);

            if (!errored)
            {
                if (validationErrors.Count > 0)
                {
                    foreach (var error in validationErrors)
                    {
                        erroredItems.Add(error.Key, error.Value);
                    }
                    return(Json(new { status = "failed", errors = erroredItems }, JsonRequestBehavior.AllowGet));
                }

                try
                {
                    //here we get the ID of the new record inserted, in  order to get the record from the database
                    //we need to do this because we need the date in UTC format
                    //and cannot figure a way to do it without extracting the new record from the database
                    //apperently when you return the JSOn with a datetime that is createad in the controller it gets the date in pc timezone, and we need it in UTC Time.
                    int id = record.InsertRecordIntoDb(user);
                    insertedRecord = new Models.Portal.WorkRecord(db.Main_Data.Find(id));

                    //checking the position of the new task so that we can place correctly in the view.
                    foreach (var item in records)
                    {
                        if (item.startDate < insertedRecord.startDate)
                        {
                            records.Insert(position - 1, insertedRecord);
                            myActivityFromSession.workLogs = records;
                            SetMyStatSession(myActivityFromSession);
                            break;
                        }


                        position++;
                    }
                }
                catch (Exception ex)
                {
                    //log exception
                    erroredItems.Add("Insert", "There is an issue with the data. Try again or contact Administrator!");
                    return(Json(new { status = "failed", errors = erroredItems }, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                return(Json(new { status = "failed", errors = erroredItems }, JsonRequestBehavior.AllowGet));
            }



            return(Json(new { status = "success", recordAdded = insertedRecord, position = position }, JsonRequestBehavior.AllowGet));
        }
Example #15
0
        private Dictionary <string, string> CheckTaskForPotentialIssues(Models.Portal.WorkRecord task, Models.Security.User user)
        {
            Dictionary <string, string> issues = new Dictionary <string, string>();

            DBContext.DBModel db = new DBContext.DBModel();

            if (user == null)
            {
                user = GetUserFromSession();
            }



            if (task == null)
            {
                issues.Add("Missing Data", "The Task was not submited successfully");
            }
            else
            {
                //Check that the start time should not be  grater then the end time
                if (task.startDate > task.endDate)
                {
                    issues.Add("Invalid Time", "Start time cannot be higher then end time!");
                }

                //Check if it is Sunday or Saturday
                if (task.currentDate.DayOfWeek == DayOfWeek.Saturday || task.currentDate.DayOfWeek == DayOfWeek.Sunday)
                {
                    issues.Add("Wrong Day", "Cannot add task on: " + task.currentDate.DayOfWeek);
                }

                //check if it is bank holiday
                var isBankHoliday = db.Public_Holidays.Where(x => x.Holiday_date == task.currentDate.Date).FirstOrDefault();
                if (isBankHoliday != null)
                {
                    issues.Add("Bank Holiday", "On: " + task.currentDate.ToString("dd/MM/yyyy") + " is Public Holyday: " + isBankHoliday.Holiday_name);
                }
                //check if it is on leave already
                var leaves = db.Leaves.Where(x => x.StartDate <= task.currentDate.Date && x.EndDate >= task.currentDate.Date).FirstOrDefault();
                if (leaves != null)
                {
                    issues.Add("Leave", "Cannot add Task on Leave Day!");
                }

                var requestedLeaves = db.Leave_Requests.Where(x => x.RequestStartDate <= task.currentDate.Date && x.RequestEndDate >= task.currentDate.Date).FirstOrDefault();
                if (requestedLeaves != null)
                {
                    issues.Add("Requested Leave", "Leave requested for the day!");
                }


                //get a list of records for the task day.
                var taskDate        = task.currentDate.Date;
                var existingRecords = db.Main_Data.Where(x => x.CurrentDate.Day == taskDate.Day && x.CurrentDate.Month == taskDate.Month && x.CurrentDate.Year == taskDate.Year && x.User_ID == user.ID).ToList();

                var overlapingRecord = existingRecords.Where(x => x.Status_Start_Time <= task.startDate && x.Status_End_Time >= task.startDate).FirstOrDefault();
                if (overlapingRecord != null)
                {
                    issues.Add("Wrong Start Time", "Interval already existing with Title: " + overlapingRecord.Title);
                }

                overlapingRecord = db.Main_Data.Where(x => x.Status_Start_Time <= task.endDate && x.Status_Start_Time >= task.startDate).FirstOrDefault();
                if (overlapingRecord != null)
                {
                    issues.Add("Wrong End Time", "Interval already existing with Title: " + overlapingRecord.Title);
                }
            }


            return(issues);
        }
        public JsonResult ChangePeriodForChart(int periodType)
        {
            if (periodType == 0)
            {
                return(Json(new { reuslt = new Dictionary <int, double>() }, JsonRequestBehavior.AllowGet));
            }

            Models.Security.User      user      = (Models.Security.User)Session["User"];
            Models.Security.AuthState userState = (Models.Security.AuthState)Session["AuthState"];

            if (user == null || userState == null)
            {
                //passs the redirect to the view, in order to send the user back to the login page.
                //further will have to build a way whwere we log out the user if it doesnot do anything on the page.
                //build a solution to keep the user logged in if he actually using the website. like always reseting the timmer for the session variable
                return(Json(new { result = false, redirectUrl = Url.Action("Index", "Home"), isRedirect = true }, JsonRequestBehavior.AllowGet));
            }


            int defaultDays = 0;

            switch (periodType)
            {
            case 1:
                defaultDays = -7;
                break;

            case 2:
                defaultDays = -14;
                break;

            case 3:
                defaultDays = -30;
                break;

            default:
                defaultDays = 0;
                break;
            }

            DateTime todayDate      = DateTime.UtcNow;
            DateTime sevenDaysBackT = todayDate.AddDays(defaultDays);
            DateTime svn            = new DateTime(sevenDaysBackT.Year, sevenDaysBackT.Month, sevenDaysBackT.Day, 0, 0, 0);
            DateTime yesterdayDate  = new DateTime(todayDate.AddDays(-1).Year, todayDate.AddDays(-1).Month, todayDate.AddDays(-1).Day, 23, 59, 59);

            try
            {
                //Get the list of records for the past default Days.
                List <DBContext.Main_Data>      records     = db.Main_Data.Where(x => x.Status_Start_Time >= svn && x.Status_End_Time <= yesterdayDate && x.User_ID == user.ID).ToList();
                List <Models.Portal.WorkRecord> workRecords = new List <Models.Portal.WorkRecord>();
                foreach (var record in records)
                {
                    var newWorkRecord = new Models.Portal.WorkRecord(record);
                    workRecords.Add(newWorkRecord);
                }

                var dailyTotalHours = Models.Portal.TimeSheet.CalculateTotalHoursForPeriod(workRecords, defaultDays, todayDate);

                return(Json(new { result = true, data = dailyTotalHours.ToList() }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(new { result = false, message = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #17
0
 private void SetUserSession(Models.Security.User user, Models.Security.AuthState userState)
 {
     Session["User"]        = user;
     Session["DisplayName"] = user.FirstName;
     Session["AuthState"]   = userState;
 }
Example #18
0
        public ActionResult UserLogin(Models.Security.LoginModel vm)
        {
            bool isMailvalid = false;

            if (vm != null)
            {
                if (vm.loginID == null || vm.loginID.Length < 1 || vm.loginPassword == null || vm.loginPassword.Length < 1)
                {
                    ErrorManagement.LoginError loginError = ErrorManagement.LoginError.CreateModel("EmailIssue", true, "The Login Credential are not correct!");
                    TempData["loginError"] = loginError;
                    return(RedirectToAction("index", "Home"));
                }
                //since the user can connect using the email address and the id, we need to validate first if the email address is correct
                //if it is, then we search based on the email addreess, if not, we try to search based on the id, if the id is not valid also, then we failed and return tu user
                //validate the Email Address by using the MailAddress class from .Net Framework.
                //if the email Address received from the view is accurate, then it will create a instance of the MailAddress class. If not will fail
                //MailAddress mailAddress = new MailAddress(vm.loginID);
                //isMailvalid = (mailAddress.Address == vm.loginID);
                if (vm.loginID.Contains("@"))
                {
                    isMailvalid = true;
                }
                ;

                if (isMailvalid)
                {
                    if (ModelState.IsValid)
                    {
                        //try to get the details from the database
                        DBContext.User user = dbmodel.Users.Where(x => x.EmailAddress == vm.loginID && x.Password == vm.loginPassword).FirstOrDefault();
                        if (user != null)
                        {
                            //Get the settings for the useer
                            // Models.Security.UserSettings userSettings = new Models.Security.UserSettings(dbmodel.User_Settings.Where(x => x.ID == user.ID).FirstOrDefault());
                            Models.Security.User      userModel = Models.Security.User.CreateUser(user);
                            Models.Security.AuthState userState = new Models.Security.AuthState(userModel, vm.timezone);
                            userState.LogIn();
                            SetUserSession(userModel, userState);

                            return(RedirectToAction("Overview", "Portal"));
                        }
                        else
                        {
                            //Create Error Model
                            ErrorManagement.LoginError loginError = ErrorManagement.LoginError.CreateModel("EmailIssue", true, "The Login Credential are not correct!");
                            TempData["loginError"] = loginError;
                            return(RedirectToAction("index", "Home"));
                        }
                    }
                    //if the model is not valid, return back to user
                    else
                    {
                        ErrorManagement.LoginError loginError = ErrorManagement.LoginError.CreateModel("EmailIssue", true, "The Login Credential are not correct!");
                        TempData["loginError"] = loginError;
                        return(RedirectToAction("index", "Home"));
                    }
                }
                else //get user by the ID since the email failed.
                {
                    DBContext.User user = dbmodel.Users.Where(x => x.ID == vm.loginID && x.Password == vm.loginPassword).FirstOrDefault();
                    if (user != null)
                    {
                        //Get the settings for the useer
                        //Models.Security.UserSettings userSettings = new Models.Security.UserSettings(dbmodel.User_Settings.Where(x => x.ID == user.ID).FirstOrDefault());
                        Models.Security.User      userModel = Models.Security.User.CreateUser(user);
                        Models.Security.AuthState userState = new Models.Security.AuthState(userModel, vm.timezone);
                        userState.LogIn();

                        SetUserSession(userModel, userState);

                        return(RedirectToAction("Overview", "Portal"));
                    }
                    else
                    {
                        ErrorManagement.LoginError loginError = ErrorManagement.LoginError.CreateModel("IDIssue", true, "The Login Credential are not correct!");
                        TempData["loginError"] = loginError;
                        return(RedirectToAction("index", "Home"));
                    }
                }
            }
            else
            {
                ErrorManagement.LoginError loginError = ErrorManagement.LoginError.CreateModel("Datasend", true, "The Login Credential are not correct!");
                TempData["loginError"] = loginError;
                return(RedirectToAction("Error"));
            }
        }
        // GET: Portal
        public ActionResult Overview()
        {
            //Get the user from the session
            Models.Security.User      user      = (Models.Security.User)Session["User"];
            Models.Security.AuthState userState = (Models.Security.AuthState)Session["AuthState"];

            if (user == null || userState == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            const int defaultDays    = -7;
            DateTime  todayDate      = DateTime.UtcNow;
            DateTime  sevenDaysBackT = todayDate.AddDays(defaultDays);
            DateTime  svn            = new DateTime(sevenDaysBackT.Year, sevenDaysBackT.Month, sevenDaysBackT.Day, 0, 0, 0);
            DateTime  yesterdayDate  = new DateTime(todayDate.AddDays(-1).Year, todayDate.AddDays(-1).Month, todayDate.AddDays(-1).Day, 23, 59, 59);

            //Get the list of records for the past default Days.
            List <DBContext.Main_Data>      records     = db.Main_Data.Where(x => x.Status_Start_Time >= svn && x.Status_End_Time <= yesterdayDate && x.User_ID == user.ID).ToList();
            List <Models.Portal.WorkRecord> workRecords = new List <Models.Portal.WorkRecord>();

            foreach (var record in records)
            {
                var newWorkRecord = new Models.Portal.WorkRecord(record);
                workRecords.Add(newWorkRecord);
            }

            var dailyTotalHours = Models.Portal.TimeSheet.CalculateTotalHoursForPeriod(workRecords, defaultDays, todayDate);

            //Get the stats for today;

            var todayRecords = db.Main_Data.Where(x => x.CurrentDate.Day == todayDate.Day && x.CurrentDate.Month == todayDate.Month && x.CurrentDate.Year == todayDate.Year && x.User_ID == user.ID).ToList();
            List <Models.Portal.WorkRecord> todayRecordsModel = new List <Models.Portal.WorkRecord>();

            foreach (var record in todayRecords)
            {
                var newWorkRecord = new Models.Portal.WorkRecord(record);
                todayRecordsModel.Add(newWorkRecord);
            }

            var userSettings = new Models.Security.UserSettings();


            //get top five public holidays
            var publicHolidaysDb = db.Public_Holidays.Where(x => x.Holiday_country == user.Country && x.Holiday_date >= todayDate.Date).Take(5).ToList();
            List <Models.Portal.PublicHoliday> publicHolidays = new List <Models.Portal.PublicHoliday>();

            DateTime[] publicHolidaysAsArray = new DateTime[publicHolidaysDb.Count];
            int        counter = 0;

            foreach (var holiday in publicHolidaysDb)
            {
                publicHolidaysAsArray[counter] = holiday.Holiday_date.Value.Date;
                publicHolidays.Add(new Models.Portal.PublicHoliday(holiday));
                counter++;
            }


            //calculate work time for the current month;
            int currentMonth = todayDate.Month;

            var monthlyRecords = db.Main_Data.Where(x => x.CurrentDate.Day >= 1 && x.CurrentDate.Month == currentMonth && x.CurrentDate.Year == todayDate.Year && x.CurrentDate.Day <= 31 && x.User_ID == user.ID).ToList();
            var recordsModel   = new List <Models.Portal.WorkRecord>();

            foreach (var record in monthlyRecords)
            {
                var newWorkRecord = new Models.Portal.WorkRecord(record);
                recordsModel.Add(newWorkRecord);
            }


            //Get the leaves status
            List <DBContext.Leave>            thisYearleaves = db.Leaves.Where(x => x.StartDate.Value >= todayDate.Date && x.UserId == user.ID).ToList();
            List <Models.Portal.Leave.ILeave> leaves         = new List <Models.Portal.Leave.ILeave>();

            foreach (var leave in thisYearleaves)
            {
                var newleave = new Models.Portal.Leave.Leave(leave, publicHolidaysAsArray);
                leaves.Add(newleave);
            }


            //get user leaves status(entitled, accrued, carried over)
            List <DBContext.User_Leaves_Status>  userLeavesStatusDb = db.User_Leaves_Status.Where(x => x.UserId == user.ID).ToList();
            List <Models.Portal.UserLeaveStatus> userLeaveStatus    = new List <Models.Portal.UserLeaveStatus>();

            foreach (var item in userLeavesStatusDb)
            {
                var newLeave = new Models.Portal.UserLeaveStatus(item);
                userLeaveStatus.Add(newLeave);
            }

            //Set User Stats and calculate the data
            var userStats = new Models.Portal.UserStatus(userSettings, todayRecordsModel, leaves, userLeaveStatus);

            userStats.totalWorkedHoursPerMonth = userStats.CalculateWorkTimeForGivenList(recordsModel);
            userStats.CalculateStats();



            //Get user Alerts!
            List <DBContext.Alert> alerts = db.Alerts.Where(x => x.UserID == user.ID || (x.ManagerId == user.ManagerID && x.IsForEveryone == true)).ToList();

            //Filter the list;
            alerts = alerts.Where(x => (x.StartDate == null || x.EndDate == null) || x.EndDate.Value.Date > todayDate.Date).ToList();


            List <Models.Portal.Alert> alertList = new List <Models.Portal.Alert>();

            foreach (var alert in alerts)
            {
                var newAlert = new Models.Portal.Alert(alert);
                alertList.Add(newAlert);
            }

            //Generate AutoAlerts and add them to the list of the already existing one
            var autoAlerts = Models.Portal.AutoGeneratedAlerts.GenerateAlerts(user);

            alertList.AddRange(autoAlerts);



            //Get the requested leaves
            List <DBContext.Leave_Requests> requestedLeavesDb = db.Leave_Requests.Where(x => x.Requestor == user.ID && x.RequestStartDate.Value >= todayDate.Date).ToList();

            foreach (var leave in requestedLeavesDb)
            {
                var newLeave = new Models.Portal.Leave.LeaveRequest(leave, publicHolidaysAsArray);
                leaves.Add(newLeave);
            }

            //Get the requested leaves
            List <DBContext.Leaves_Saved_Not_Submited> savedLeavesDb = db.Leaves_Saved_Not_Submited.Where(x => x.UserID == user.ID && x.StartDate.Value >= todayDate.Date).ToList();

            foreach (var leave in savedLeavesDb)
            {
                var newLeave = new Models.Portal.Leave.SavedLeave(leave, publicHolidaysAsArray);
                leaves.Add(newLeave);
            }



            leaves = leaves.OrderBy(x => x.start).Take(5).ToList();
            var dashboard = new Models.Portal.Dashboard(user, dailyTotalHours, userStats, leaves, alertList, publicHolidays);


            return(View(dashboard));
        }