public IActionResult CreateWithGet(string date, string comment, string employeeId, string version, string topicId)
        {
            //Adding to LearningDays
            LearningDay learningDay = new LearningDay();

            learningDay.Date       = DateTime.Parse(date.Replace('-', '.'));
            learningDay.Comment    = comment;
            learningDay.EmployeeId = Int32.Parse(employeeId);
            learningDay.Version    = Int32.Parse(version);

            db.LearningDays.Add(learningDay);
            db.SaveChanges();

            //Adding to LearningDayTopics
            LearningDayTopic learningDayTopic = new LearningDayTopic();

            learningDayTopic.LearningDayId = learningDay.Id;
            learningDayTopic.TopicId       = Int32.Parse(topicId);
            learningDayTopic.Version       = Int32.Parse(version);

            db.LearningDayTopics.Add(learningDayTopic);
            db.SaveChanges();

            return(Json(Ok("Added")));
        }
예제 #2
0
        public bool canAddOrUpdateDay(LearningDay day)
        {
            int maxDays = 3;

            // If a day is edited and is moved to a new date in the same quarter, then this move should be permitted.
            if (day.LearningDayId > 0)
            {
                LearningDay oldDay       = getLearningDayById(day.LearningDayId);
                int         quarter      = (day.Date.Month - 1) / 3;
                DateTime    quarterStart = new DateTime(day.Date.Year, 1 + quarter * 3, 1),
                            quarterEnd   = new DateTime(day.Date.Year, 4 + quarter * 3, 1);
                if (day.Date >= quarterStart && day.Date < quarterEnd)
                {
                    maxDays++;
                }
            }
            else
            {
                // Do not allow adding if the date is taken by an other day.
                if (isDateTaken(day.Date, day.UserId))
                {
                    return(false);
                }
            }
            // Never allow creating a day at a date where a user has already got a learning day.


            return(getDaysInQuarterCount(day.Date, day.UserId) < maxDays);
        }
예제 #3
0
 // Checks if the date is taken by an other day.
 public bool isDateTaken(LearningDay day)
 {
     using (var context = new ApplicationDbContext())
     {
         return(context.learningDays.Where(x => x.UserId == day.UserId && x.Date == day.Date && x.LearningDayId != day.LearningDayId).Count() > 0);
     }
 }
예제 #4
0
 public FlatLearningDay(LearningDay learningDay)
 {
     Id          = learningDay.Id;
     TopicId     = learningDay.TopicId;
     DateFrom    = DateTime.SpecifyKind(learningDay.DateFrom, DateTimeKind.Utc);
     DateTo      = DateTime.SpecifyKind(learningDay.DateTo, DateTimeKind.Utc);
     Description = learningDay.Description;
     Title       = learningDay.Topic.Name;
     UserId      = learningDay.UserId;
 }
        public IActionResult GetLearningDayLearningDayLinks(int id)
        {
            LearningDay learningDay = db.LearningDays.Find(id);

            if (learningDay != null)
            {
                return(Json(learningDay.LearningDayLinks));
            }
            else
            {
                return(NotFound("GET: LearningDay with ID = " + id + " was not found."));
            }
        }
 public IActionResult UpdateLearningDay([FromBody] LearningDay learningDay)
 {
     if (learningDay != null)
     {
         db.LearningDays.Update(learningDay);
         db.SaveChanges();
         return(Json(Ok("LearningDay updated")));
     }
     else
     {
         return(NotFound("UPDATE: LearningDay was not found"));
     }
 }
 public IActionResult DeleteLearningDay(int id)
 {
     try
     {
         LearningDay learningDay = db.LearningDays.Find(id);
         db.LearningDays.Remove(learningDay);
         db.SaveChanges();
         return(Json(Ok("LearningDay deleted")));
     }
     catch (ArgumentNullException)
     {
         return(NotFound("DELETE: LearningDay with ID = " + id + " was not found."));
     }
 }
예제 #8
0
        public ActionResult EditLearningDay(int id)
        {
            var error = (string)TempData["UpdateLD"];

            if (!string.IsNullOrEmpty(error))
            {
                ModelState.AddModelError("", error);
                TempData.Remove("UpdateLD");
            }
            LearningDay editedDay = dayManager.getLearningDayById(id);
            EditLearningDayViewModel viewModel = new EditLearningDayViewModel();

            viewModel             = getData(viewModel);
            viewModel.LearningDay = editedDay;
            return(View("EditLearningDay", viewModel));
        }
        public LearningDayWithUser(LearningDay learningDay)
        {
            Id          = learningDay.Id;
            RowVersion  = learningDay.RowVersion;
            Description = learningDay.Description;
            DateFrom    = DateTime.SpecifyKind(learningDay.DateFrom, DateTimeKind.Utc);
            DateTo      = DateTime.SpecifyKind(learningDay.DateTo, DateTimeKind.Utc);

            UserId   = learningDay.User.Id;
            Name     = learningDay.User.Name;
            Surname  = learningDay.User.Surname;
            JobTitle = learningDay.User.JobTitle.Title;

            TopicId    = learningDay.Topic.Id;
            TopicTitle = learningDay.Topic.Name;
        }
예제 #10
0
        public bool createLearningDay(DateTime date, string Title, string Desc, string userId, List <Topic> chosenTopics = null, List <string> references = null)
        {
            using (var context = new ApplicationDbContext()) {
                using (var dbContextTransaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var user = context.Users.Where(x => x.Id == userId).First();
                        var LD   = new LearningDay();
                        LD.Date = date; LD.Description = Desc; LD.User = user; LD.Title = Title;
                        LD      = context.learningDays.Add(LD);
                        context.SaveChanges();
                        if (chosenTopics != null)
                        {
                            foreach (var topic in chosenTopics)
                            {
                                context.topicDay.Add(new TopicDay()
                                {
                                    Day = LD, Topic = context.topics.Where(x => x.TopicsId == topic.TopicsId).First()
                                });
                            }
                        }
                        if (references != null)
                        {
                            foreach (var reference in references)
                            {
                                context.lDayReferences.Add(new LDayReferences()
                                {
                                    learningDay = LD, ReferenceUrl = reference
                                });
                            }
                        }

                        context.SaveChanges();
                        dbContextTransaction.Commit();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
        }
예제 #11
0
 public void setReferences(LearningDay learningDay, List <string> references)
 {
     using (var context = new ApplicationDbContext())
     {
         if (references != null)
         {
             var newReferenceDays = new List <LDayReferences>();
             foreach (var reference in references)
             {
                 newReferenceDays.Add(new LDayReferences()
                 {
                     learningDay = learningDay, ReferenceUrl = reference
                 });
             }
             learningDay.References = newReferenceDays;
             UpdateChanges();
         }
     }
 }
예제 #12
0
 public void setTopics(LearningDay learningDay, List <Topic> newTopics)
 {
     using (var context = new ApplicationDbContext())
     {
         if (newTopics != null)
         {
             var NewTopicDays = new List <TopicDay>();
             foreach (var topic in newTopics)
             {
                 NewTopicDays.Add(new TopicDay()
                 {
                     Day = learningDay, Topic = topic
                 });
             }
             learningDay.Topics = NewTopicDays;
             UpdateChanges();
         }
     }
 }
예제 #13
0
        public ActionResult Schedule(ScheduleViewModel viewModel, string command)
        {
            // User needs to be authorized to create learning days.
            Authorized allowedActions = CheckAuthorized(viewModel.UserId);

            if ((!HasAuthorization(allowedActions, Authorized.Create)))
            {
                return(View("Error", new HandleErrorInfo(
                                new Exception("You may create/edit/remove learning days only for yourself."),
                                "Learning Controller",
                                "Schedule - Create learning day.")));
            }
            if (command == "Add")
            {
                try
                {
                    Debug.WriteLine("Adding a new learning day, date: {0}, title: {1}, description: {2}, topicId: {3}",
                                    viewModel.NewDayDate, viewModel.NewDayTitle, viewModel.NewDayDescription, viewModel.NewDayTopicId);
                    Debug.WriteLine("Target user: {0}", viewModel.UserId);
                    Debug.WriteLine("Days in quarter: {0}", dayManager.getDaysInQuarterCount(viewModel.NewDayDate, viewModel.UserId));
                    Topic topic = new Topic();
                    if (viewModel.NewDayDate.Date < DateTime.Today)
                    {
                        ModelState.AddModelError("", "Cannot add a day to past.");
                    }
                    else if (viewModel.NewDayTitle.IsNullOrWhiteSpace())
                    {
                        ModelState.AddModelError("", "Day title cannot be empty.");
                    }
                    else if (viewModel.CreateTopic && viewModel.NewDayTitle.IsNullOrWhiteSpace())
                    {
                        ModelState.AddModelError("", "Topic Title cannot be empty.");
                    }
                    else if (dayManager.getDaysInQuarterCount(viewModel.NewDayDate, viewModel.UserId) >= 3)
                    {
                        ModelState.AddModelError("", "Cannot add a day for, " + viewModel.NewDayDate + " - already have 3 learning days in the Quarter.");
                    }
                    else if (dayManager.isDateTaken(viewModel.NewDayDate, viewModel.UserId))
                    {
                        ModelState.AddModelError("", "Cannot add a day for, " + viewModel.NewDayDate + " - date already has a learning day.");
                    }

                    if (ModelState.IsValid)
                    {
                        if (viewModel.CreateTopic)
                        {
                            topic = topicManager.createTopic(viewModel.NewTopicTitle, viewModel.NewTopicDescription, viewModel.NewDayTopicId);
                        }
                        else
                        {
                            topic = topicManager.getTopicById(viewModel.NewDayTopicId);
                        }
                        dayManager.createLearningDay(viewModel.NewDayDate, viewModel.NewDayTitle, viewModel.NewDayDescription,
                                                     viewModel.UserId, new List <Topic>()
                        {
                            topic
                        });

                        return(RedirectToAction("Schedule"));
                    }
                    else
                    {
                        viewModel = getData(viewModel);
                        return(View(viewModel));
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("An error occurred while adding a new Learning day. LearningController ");
                    return(View(getData(viewModel)));
                }
            }
            else
            {
                LearningDay day = dayManager.getLearningDayById(int.Parse(viewModel.ViewedDayId));
                if (day == null)
                {
                    return(View(getData(viewModel)));
                }
                if (command == "Delete")
                {
                    if (day.Date.Date <= DateTime.Today.Date)
                    {
                        ModelState.AddModelError("", "Cannot delete a learning day that has started or is already over.");
                    }
                    else
                    {
                        dayManager.deleteLearningDay(day.LearningDayId, User.Identity.GetUserId());
                    }
                }
                else if (command == "Edit")
                {
                    if (day.Date.Date < DateTime.Today.Date)
                    {
                        ModelState.AddModelError("", "Cannot edit a learning day that is already over.");
                    }
                    else
                    {
                        return(EditLearningDay(day.LearningDayId));
                    }
                }
            }

            return(View(getData(viewModel)));
        }
예제 #14
0
        public ActionResult EditLearningDay(EditLearningDayViewModel viewModel, string command)
        {
            viewModel = getData(viewModel);
            Debug.WriteLine("Edit learning day, command: " + command);

            string currentUserId = User.Identity.GetUserId();

            if (viewModel.LearningDay.User.Id != currentUserId)
            {
                return(View("Error")); // Cannot edit someone elses learning day.
            }

            if ((command == "Add Topic" || command == "Add New Topic") && viewModel.LearningDay.Topics.Where(tp => !tp.Remove).Count() >= 4)
            {
                ModelState.AddModelError("", "Maximum number (4) of topics per day reached.");
                return(View(viewModel));
            }

            if (command == "Add Topic")
            {
                TopicDay topic = topicManager.createTopicDay(viewModel.AddTopicId,
                                                             viewModel.LearningDay.LearningDayId,
                                                             viewModel.LearningDay.UserId);
                topic.NewlyCreated = true;
                // Forcefully loading the lazy Topic, so that it can be displayed.
                topic.Topic = topicManager.getTopicById(topic.TopicId);
                if (topic.Topic.ParentTopicId == null)
                {
                    topic.Topic.parentTopic = null;
                }
                else
                {
                    topic.Topic.parentTopic = topicManager.getTopicById((int)topic.Topic.ParentTopicId);
                }


                var duplicateTopicDays = viewModel.LearningDay.Topics.Where(topicDay => topicDay.TopicId == viewModel.AddTopicId);
                if (duplicateTopicDays.Count() > 0)
                {
                    // If the topic was marked for removal and is being added again, then it should just be visible again.
                    if (duplicateTopicDays.First().Remove)
                    {
                        duplicateTopicDays.First().Remove = false;
                    }
                    else
                    {
                        ModelState.AddModelError("", "The learning day already has this topic.");
                    }
                    return(View(viewModel));
                }
                viewModel.LearningDay.Topics.Add(topic);
            }
            else if (command == "Add New Topic")
            {
                Topic    newTopic = topicManager.createTopic(viewModel.NewTopicTitle, viewModel.NewTopicDescription, viewModel.NewTopicParentId);
                TopicDay topicDay = topicManager.createTopicDay(newTopic.TopicsId, viewModel.LearningDay.LearningDayId, viewModel.LearningDay.UserId);
                topicDay.NewlyCreated = true;
                topicDay.Topic        = newTopic; // topicManager.getTopicById(newTopic.TopicsId);
                // Forcefully loading the lazy Topic, so that it can be displayed.
                if (newTopic.ParentTopicId != null)
                {
                    topicDay.Topic.parentTopic = topicManager.getTopicById((int)newTopic.ParentTopicId);
                }

                viewModel.LearningDay.Topics.Add(topicDay);
            }
            else if (command == "Add Reference")
            {
                LDayReferences reference = new LDayReferences()
                {
                    LearningDayId = viewModel.LearningDay.LearningDayId,
                    UserId        = viewModel.LearningDay.UserId
                };
                viewModel.LearningDay.References.Add(reference);
            }
            else if (command == "Remove Selected Topics" || command == "Remove Selected References")
            {// Do nothing, as the objects are marked for deletion and remain in learning day until saved.
            }
            else if (command == "Cancel/Refresh")
            {
                viewModel.LearningDay = dayManager.getLearningDayById(viewModel.LearningDay.LearningDayId);
            }
            else
            {
                LearningDay oldDay = dayManager.getLearningDayById(viewModel.LearningDay.LearningDayId);
                if (viewModel.LearningDay.Date <= DateTime.Today.Date && viewModel.LearningDay.Date != oldDay.Date)
                {
                    ModelState.AddModelError("", "Cannot change learning day date to past date or today.");
                    return(View(viewModel));
                }
                else if (!dayManager.canAddOrUpdateDay(viewModel.LearningDay))
                {
                    ModelState.AddModelError("", "Cannot change learning day date, maximum days (3) in target quarter reached.");
                    return(View(viewModel));
                }
                else if (dayManager.isDateTaken(viewModel.LearningDay))
                {
                    ModelState.AddModelError("", "Cannot change learning day date, date already taken by another day.");
                    return(View(viewModel));
                }
                else if (viewModel.LearningDay.Title.IsNullOrWhiteSpace())
                {
                    ModelState.AddModelError("", "Learning day title is required and may not be empty.");
                    return(View(viewModel));
                }
                else if (viewModel.LearningDay.Topics.All(topicDay => topicDay.Remove))
                {
                    ModelState.AddModelError("", "Learning day must have at least one topic assigned. Cannot delete all topics.");
                    viewModel.LearningDay.Topics.ForEach(topic => topic.Remove = false);
                    return(View(viewModel));
                }

                if (!dayManager.updateLearningDay(viewModel.LearningDay, viewModel.LearningDay.RowVersion))
                {
                    TempData["UpdateLD"] = "The day was already modified by another user. If this message persists, click 'Refresh'.";
                    //LearningDay newDay = dayManager.getLearningDayById(learningDay.LearningDayId);
                    return(RedirectToAction("EditLearningDay", new { id = viewModel.LearningDay.LearningDayId }));
                }
                return(RedirectToAction("Schedule", new { userId = viewModel.LearningDay.UserId }));
            }

            return(View(viewModel));
        }
        public IActionResult CreateLearningDay([FromBody] LearningDay learningDay)
        {
            Employee employee = db.Employees.Find(learningDay.EmployeeId);

            IList <LearningDay> learningDayExisting = db.LearningDays.FromSqlInterpolated(
                $@"
                select
                  lda.*
				from
				  learningDays lda
				where
				  lda.date = {learningDay.Date} and
				  lda.employeeId = {employee.Id}"                )
                                                      .ToList <LearningDay>();

            if (!learningDayExisting.IsNullOrEmpty())
            {
                return(Json(BadRequest("Learning day already exists!")));
            }

            if (!employee.Limits.IsNullOrEmpty())  // jei darbuotojas turi kazkokiu nustatytu apribojimu
            {
                var result = db.CheckBool.FromSqlInterpolated(
                    $@"
                    select
                      1 checkBool
                    from
                      limits lim
                    where
                      lim.employeeId = {employee.Id} and
                      {learningDay.Date} between convert(datetime, lim.startDate) and convert(datetime, lim.endDate)")
                             .ToList <CheckBool>();

                if (result.IsNullOrEmpty())
                {
                    return(Json(BadRequest("Learning day is not in allowed learning period of the employee!")));
                }

                if (!employee.LearningDays.IsNullOrEmpty())
                {
                    result = db.CheckBool.FromSqlInterpolated(
                        $@"
                        select
				          sum(che.checkBool) checkBool
				        from
					      (select
                            case
					          when count(lda.id) < lim.maxTotalLearningDays then
						        0
						      else
						        1
					        end checkBool
                          from
                            limits lim,
					        learningDays lda
                          where
                            lim.employeeId = {employee.Id} and
                            {learningDay.Date} between convert(datetime, lim.startDate) and convert(datetime, lim.endDate) and
					        lda.employeeId = lim.employeeId and
					        lda.date between convert(datetime, lim.startDate) and convert(datetime, lim.endDate)
					      group by
					        lim.id,
					        lim.maxTotalLearningDays) che"                    )
                             .ToList <CheckBool>();

                    if (result.First().checkBool != 0)
                    {
                        return(Json(BadRequest("Max learning days reached!")));
                    }

                    result = db.CheckBool.FromSqlInterpolated(
                        $@"
                        with groups(date, grp, maxDays) as (
                          select
                            lda.date,
                            dateadd(
	                          day,
	                          -dense_rank()
	                            over(
		                          order by
		                            lda.date), 
                              lda.date) grp,
	                          lim.maxConsecutiveLearningDays maxDays
                          from
                            learningDays lda,
	                        limits lim
                          where
                            lim.employeeId = {employee.Id}  and
	                        {learningDay.Date} between convert(datetime, lim.startDate) and convert(datetime, lim.endDate) and
	                        lda.employeeId = lim.employeeId and
	                        lda.date between convert(datetime, lim.startDate) and convert(datetime, lim.endDate)
                          group by
                            lda.date,
	                        lim.id,
	                        lim.maxConsecutiveLearningDays)
                        select
                          case
                            when count(date) = maxDays and
	                          (convert(datetime, min(date)) - 1 = {learningDay.Date} or
	                          convert(datetime, max(date)) + 1 = {learningDay.Date}) then
	                          0
	                        else 
	                          1
                          end checkBool
                        from
                          groups
                        group by
                          grp,
                          maxDays")
                             .ToList <CheckBool>();

                    if (result.First().checkBool == 0)
                    {
                        return(Json(BadRequest("Max consecutive learning days reached!")));
                    }
                }
            }

            if (learningDay != null)
            {
                db.LearningDays.Add(learningDay);
                db.SaveChanges();
                return(Json(Ok("LearningDay created")));
            }
            else
            {
                return(NotFound("CREATE: LearningDay was not found"));
            }
        }
예제 #16
0
 public bool updateLearningDay(LearningDay changedDay, byte[] RowState)
 {
     using (var context = new ApplicationDbContext())
     {
         // Don't update if the new day has no topics assigned. Learning days must have at least 1 topic.
         if (changedDay.Topics.Count == 0)
         {
             return(false);
         }
         try
         {
             var update = context.learningDays.Single(x => x.LearningDayId == changedDay.LearningDayId);
             update.Date        = changedDay.Date;
             update.Title       = changedDay.Title;
             update.Description = changedDay.Description;
             context.Entry(update).OriginalValues["RowVersion"] = RowState;
             foreach (var topic in changedDay.Topics)
             {
                 if (topic.Remove)
                 {
                     if (!topic.NewlyCreated)
                     {
                         TopicDay toRemove = context.topicDay.Single(x => x.TopicId == topic.TopicId &&
                                                                     x.LearningDayId == topic.LearningDayId &&
                                                                     x.UserId == topic.UserId);
                         context.topicDay.Remove(toRemove);
                     }
                 }
                 else
                 {
                     // A duplicate topic might be created if the virtual topic is not null.
                     topic.Topic = null;
                     context.topicDay.AddOrUpdate(topic);
                 }
             }
             foreach (var reference in changedDay.References)
             {
                 if (reference.Remove)
                 {
                     if (reference.ReferenceId > 0)
                     {
                         LDayReferences toRemove = context.lDayReferences.First(x => x.LearningDayId == reference.LearningDayId &&
                                                                                x.UserId == reference.UserId &&
                                                                                x.ReferenceUrl == reference.ReferenceUrl);
                         context.lDayReferences.Remove(toRemove);
                     }
                 }
                 else
                 {
                     context.lDayReferences.AddOrUpdate(reference);
                 }
             }
             context.learningDays.AddOrUpdate(update);
             context.SaveChanges();
             return(true);
         }
         catch (DbUpdateConcurrencyException ex)
         {
             return(false);
         }
         catch (DbUpdateException ex)
         {
             Exception tempEx = ex;
             // Exception may be nested. Might need to go deep for the exception message.
             while (tempEx.InnerException != null)
             {
                 tempEx = tempEx.InnerException;
             }
             Debug.WriteLine(tempEx.Message);
             return(false);
         }
     }
 }