Ejemplo n.º 1
0
 /// <summary>
 /// Обновляет денормализованную инфу о статусе в задачах
 /// </summary>
 public void UpdateStatus(ITasksStatus status)
 {
     _Context.ExecuteCommand(@"UPDATE Tasks SET TaskStatusName = {0}, TaskStatusPosition = {1} WHERE TaskStatusId = {2}",
                             status.Name,     // 0
                             status.Position, // 1
                             status.Id);      // 2
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Проверка лимитов по задачам
 /// </summary>
 static void CheckStatusLimits(ITasksStatus status, int?planingTime)
 {
     if (status.PlanningRequired && !planingTime.HasValue)
     {
         throw new PlanningTimeRequered(status);
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Основная функция обновления статуса
        /// Она проверяет все что нужно
        /// </summary>
        public ITask UpdateStatus(int taskId, int statusId, Limits limits)
        {
            ITask     task    = _Get(taskId);
            TimezTask oldTask = new TimezTask(task);

            if (task.TaskStatusId != statusId)
            {
                ITasksStatus newStatus = Utility.Statuses.Get(task.BoardId, statusId);

                CheckStatusLimits(newStatus, task.PlanningTime);
                CheckTaskLimits(newStatus, task.ExecutorUserId, limits, task);

                // Для обычных статусов только обновляем поля у задачи
                Repository.Tasks.UpdateStatus(task.Id, newStatus);

                // Обновляем у этой сущности, что б не запрашивать из бд
                task.TaskStatusId         = newStatus.Id;
                task.TaskStatusPosition   = newStatus.Position;
                task.StatusChangeDateTime = DateTime.Now;
                task.TaskStatusName       = newStatus.Name;

                OnUpdateStatus.Invoke(this, new UpdateEventArgs <ITask>(oldTask, task));
            }

            return(task);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Быстрое изменение статуса задачи
 /// Например, при перетаскивании в канбане
 /// </summary>
 public void UpdateStatus(int taskId, ITasksStatus newStatus)
 {
     _Context.ExecuteCommand(@"UPDATE Tasks SET StatusChangeDateTime = {0}, TaskStatusId = {1},  TaskStatusPosition = {2} WHERE Id = {3}",
                             DateTimeOffset.Now, // 0
                             newStatus.Id,       // 1
                             newStatus.Position, // 2
                             taskId);            // 3
 }
Ejemplo n.º 5
0
        private void _OnUpdate(ITasksStatus status, bool additionalUpdate)
        {
            if (additionalUpdate)
            {
                Repository.Tasks.UpdateStatus(status);
            }

            OnUpdate.Invoke(new EventArgs <ITasksStatus>(status));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Обновили статус задачи
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void TasksUtility_OnUpdateStatus(object sender, UpdateEventArgs <ITask> args)
        {
            ITask        newTask = args.NewData;
            ITasksStatus status  = Utility.Statuses.Get(newTask.BoardId, newTask.TaskStatusId);

            if (status != null)
            {
                TaskMessage(newTask, ReciveType.TaskStatusChanged, "В проекте \"{0}\" задаче <a href='{1}'>\"{2}\"</a> установлен статус \"" + status.Name + "\".");
            }
        }
Ejemplo n.º 7
0
 public TimezStatus(ITasksStatus status)
 {
     Id                  = status.Id;
     BoardId             = status.BoardId;
     IsBacklog           = status.IsBacklog;
     MaxTaskCountPerUser = status.MaxTaskCountPerUser;
     Name                = status.Name;
     NeedTimeCounting    = status.NeedTimeCounting;
     Position            = status.Position;
     PlanningRequired    = status.PlanningRequired;
     MaxPlanningTime     = status.MaxPlanningTime;
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Создание задачи
        /// </summary>
        /// <exception cref="PlanningTimeRequered"></exception>
        /// <exception cref="PlanningTimeIsExceeded"></exception>
        public ITask Create(string name, string desc, int executorId, int projectId, int colorId, int statusId, int boardId, int?planingTime = null, Limits checkLimits = Limits.NoLimits)
        {
            if (name.IsNullOrEmpty())
            {
                throw new ArgumentException("Name");
            }

            IBoardsColor color         = Utility.Boards.GetColor(boardId, colorId);
            IProject     project       = Utility.Projects.Get(boardId, projectId);
            IUser        executor      = Utility.Users.Get(executorId);
            ITasksStatus status        = Utility.Statuses.Get(boardId, statusId);
            int          creatorUserId = Utility.Authentication.UserId;

            // Передаем данные о создаваемой задаче, что бы проверить по ней ограничения
            CheckTaskLimits(status, executorId, checkLimits, new TimezTask
            {
                Name             = name,
                Description      = desc,
                ExecutorUserId   = executor.Id,
                ExecutorNick     = executor.Nick,
                ExecutorEmail    = executor.EMail,
                BoardId          = boardId,
                ColorHEX         = color.Color,
                ColorId          = color.Id,
                ColorName        = color.Name,
                ColorPosition    = color.Position,
                CreationDateTime = DateTimeOffset.Now,
                CreatorUserId    = creatorUserId,
                Id                   = 0,
                PlanningTime         = planingTime,
                ProjectId            = project.Id,
                ProjectName          = project.Name,
                StatusChangeDateTime = DateTimeOffset.Now,
                TaskStatusId         = status.Id,
                TaskStatusPosition   = status.Position
            });

            CheckStatusLimits(status, planingTime);

            //using (TransactionScope scope = new TransactionScope())
            {
                ITask task = Repository.Tasks.Create(name, desc, executor, project, color, status, planingTime, creatorUserId);

                OnCreate.Invoke(new EventArgs <ITask>(task));
                OnTaskAssigned.Invoke(new UpdateEventArgs <ITask>(null, task));

                //scope.Complete();

                return(task);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Создает статус и помещает ее перед беклогом
        /// </summary>
        public ITasksStatus Create(int boardId, string name, bool planningRequired, int?maxTaskCountPerUser, int?maxPlanningTime)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                ITasksStatus status = Repository.TasksStatuses.Create(
                    boardId, name,
                    false, planningRequired,
                    maxTaskCountPerUser, maxPlanningTime);

                OnCreate.Invoke(new EventArgs <ITasksStatus>(status));

                scope.Complete();
                return(status);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Достигнут ли предел количества задач в статусе для пользователя
        /// task = null - если задача новая
        /// </summary>
        void CheckTaskLimits(ITasksStatus status, int executorId, Limits toCheck, ITask task)
        {
            var filter = CreateFilter(status.BoardId);

            filter.ExecutorIds = new[] { executorId };
            filter.Statuses    = new[] { status.Id };
            var tasks = Get(filter);

            // Проверяем на лимит количества задач
            if ((toCheck & Limits.TaskCountLimitIsReached) == Limits.TaskCountLimitIsReached)
            {
                if (status.MaxTaskCountPerUser.HasValue && status.MaxTaskCountPerUser.Value > 0)
                {
                    // если количество задач больше лимита
                    if (status.MaxTaskCountPerUser.Value < tasks.Count)
                    {
                        OnTaskCountLimitIsReached(task, tasks.Count);
                        throw new TaskCountLimitIsReached(status.MaxTaskCountPerUser.Value);
                    }

                    // Проверять на равенство лимиту не нужно в попапе редактирования
                    if ((toCheck & Limits.PopupUpdating) != Limits.PopupUpdating && status.MaxTaskCountPerUser.Value == tasks.Count)
                    {
                        OnTaskCountLimitIsReached(task, tasks.Count);
                        throw new TaskCountLimitIsReached(status.MaxTaskCountPerUser.Value);
                    }
                }
            }

            // Проверяем суммарную планируемую длительность
            if ((toCheck & Limits.PlanningTimeIsExceeded) == Limits.PlanningTimeIsExceeded)
            {
                int timeSum = tasks.Sum(x => x.PlanningTime ?? 0) + task.PlanningTime ?? 0;
                if (status.MaxPlanningTime.HasValue && timeSum > status.MaxPlanningTime.Value)
                {
                    OnTaskPlanningTimeIsExceeded(task, status, timeSum);
                    throw new PlanningTimeIsExceeded(status.MaxPlanningTime.Value);
                }
            }
        }
Ejemplo n.º 11
0
        public ITasksStatus Delete(int statusId)
        {
            ITasksStatus status = Repository.TasksStatuses.Get(statusId);

            if (!status.IsBacklog)
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    Repository.TasksStatuses.Delete(status);

                    OnDelete.Invoke(new EventArgs <ITasksStatus>(status));

                    scope.Complete();
                }
            }
            else
            {
                throw new InvalidOperationException("Запрещено удалять Беклог");
            }

            return(status);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Случилось превышение допустимого времени
        /// </summary>
        /// <param name="task">изменяемая задача</param>
        /// <param name="status">желаемый статус, в котором произошло превышение лимитов</param>
        /// <param name="minutes">сколько уже времени запланировано</param>
        void Tasks_OnTaskPlanningTimeIsExceeded(ITask task, ITasksStatus status, int minutes)
        {
            EventType type = EventType.PlanningTimeIsExceeded;

            // Время гарантированно должно быть у стауса
            // ReSharper disable PossibleInvalidOperationException
            int time = status.MaxPlanningTime.Value;

            // ReSharper restore PossibleInvalidOperationException
            if (minutes > time + 12 * 60)
            {
                time += 12 * 60;
                type |= EventType.Error;
            }
            else if (minutes > time)
            {
                type |= EventType.Warning;
            }

            Add(Utility.Users.CurrentUser, task,
                EventType.PlanningTimeIsExceeded.GetAlias().Params(time), type);
        }
Ejemplo n.º 13
0
        public TasksStatusesUtility()
        {
            OnCreate += (s, e) =>
            {
                ITasksStatus status = e.Data;

                CacheClear(status.BoardId);
            };

            OnDelete += (s, e) =>
            {
                ITasksStatus status = e.Data;

                CacheClear(status.BoardId);
            };

            OnUpdate += (s, e) =>
            {
                ITasksStatus status = e.Data;

                CacheClear(status.BoardId);
            };
        }
Ejemplo n.º 14
0
        public ITask Create(string name, string desc, IUser user, IProject project, IBoardsColor color, ITasksStatus status, int?planingTime, int creatorUserId)
        {
            Task task = new Task
            {
                BoardId              = project.BoardId,
                ColorId              = color.Id,
                ColorHEX             = color.Color,
                ColorName            = color.Name,
                ColorPosition        = color.Position,
                CreationDateTime     = DateTimeOffset.Now,
                Description          = desc,
                ExecutorUserId       = user.Id,
                ExecutorEmail        = user.EMail,
                ExecutorNick         = user.Nick,
                Name                 = name,
                ProjectId            = project.Id,
                ProjectName          = project.Name,
                StatusChangeDateTime = DateTimeOffset.Now,
                TaskStatusId         = status.Id,
                TaskStatusPosition   = status.Position,
                TaskStatusName       = status.Name,
                PlanningTime         = planingTime,
                CreatorUserId        = creatorUserId
            };

            const string sql = @"
						INSERT INTO [dbo].[Tasks]
								   ([Name]
								   ,[Description]
								   ,[BoardId]
								   ,[CreatorUserId]
								   ,[CreationDateTime]
								   ,[StatusChangeDateTime]
								   ,[PlanningTime]
								   ,[ColorId]
								   ,[ColorHEX]
								   ,[ColorName]
								   ,[ColorPosition]
								   ,[ProjectId]
								   ,[ProjectName]
								   ,[ExecutorUserId]
								   ,[ExecutorNick]
								   ,[ExecutorEmail]
								   ,[TaskStatusId]
								   ,[TaskStatusPosition]
								   ,[TaskStatusName]
								   ,[IsDeleted])
							 VALUES
								   (@Name
								   ,@Description
								   ,@BoardId
								   ,@CreatorUserId
								   ,@CreationDateTime
								   ,@StatusChangeDateTime
								   ,@PlanningTime
								   ,@ColorId
								   ,@ColorHEX
								   ,@ColorName
								   ,@ColorPosition
								   ,@ProjectId
								   ,@ProjectName
								   ,@ExecutorUserId
								   ,@ExecutorNick
								   ,@ExecutorEmail
								   ,@TaskStatusId
								   ,@TaskStatusPosition
								   ,@TaskStatusName
								   ,@IsDeleted);
						SELECT CAST(@@IDENTITY AS INT)"                        ;

            using (DbCommand command = _Context.Connection.CreateCommand())
            {
                command.CommandText = sql;
                command.Parameters.Add(new SqlParameter("@Name", task.Name));
                command.Parameters.Add(new SqlParameter("@Description", task.Description));
                command.Parameters.Add(new SqlParameter("@BoardId", task.BoardId));
                command.Parameters.Add(new SqlParameter("@CreatorUserId", task.CreatorUserId));
                command.Parameters.Add(new SqlParameter("@CreationDateTime", task.CreationDateTime));
                command.Parameters.Add(new SqlParameter("@StatusChangeDateTime", task.StatusChangeDateTime));
                command.Parameters.Add(new SqlParameter("@PlanningTime", task.PlanningTime ?? (object)DBNull.Value));
                command.Parameters.Add(new SqlParameter("@ColorId", task.ColorId));
                command.Parameters.Add(new SqlParameter("@ColorHEX", task.ColorHEX));
                command.Parameters.Add(new SqlParameter("@ColorName", task.ColorName));
                command.Parameters.Add(new SqlParameter("@ColorPosition", task.ColorPosition));
                command.Parameters.Add(new SqlParameter("@ProjectId", task.ProjectId));
                command.Parameters.Add(new SqlParameter("@ProjectName", task.ProjectName));
                command.Parameters.Add(new SqlParameter("@ExecutorUserId", task.ExecutorUserId));
                command.Parameters.Add(new SqlParameter("@ExecutorNick", task.ExecutorNick));
                command.Parameters.Add(new SqlParameter("@ExecutorEmail", task.ExecutorEmail));
                command.Parameters.Add(new SqlParameter("@TaskStatusId", task.TaskStatusId));
                command.Parameters.Add(new SqlParameter("@TaskStatusPosition", task.TaskStatusPosition));
                command.Parameters.Add(new SqlParameter("@TaskStatusName", task.TaskStatusName));
                command.Parameters.Add(new SqlParameter("@IsDeleted", task.IsDeleted));
                _Context.Connection.Open();
                task.Id = (int)command.ExecuteScalar();
                _Context.Connection.Close();
            }

            //task.Id = _Context.ExecuteQuery<int>(sql
            //, task.Name
            //, task.Description
            //, task.BoardId
            //, task.CreatorUserId
            //, task.CreationDateTime
            //, task.StatusChangeDateTime
            //, task.PlanningTime ?? (object)DBNull.Value
            //, task.ColorId
            //, task.ColorHEX
            //, task.ColorName
            //, task.ColorPosition
            //, task.ProjectId
            //, task.ProjectName
            //, task.ExecutorUserId
            //, task.ExecutorNick
            //, task.ExecutorEmail
            //, task.TaskStatusId
            //, task.TaskStatusPosition
            //, task.TaskStatusName
            //, task.IsDeleted)
            //.First();

            return(task);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Обновлеяе основные параметры задачи
        /// Кроме статуса! Так как там сложная логика
        /// Обновление задачи, если задача была в кеше, то обновление происходит асинхронно
        /// Если в кеше задачи не было, то обновление синхронное и после задача добавляется в кеш
        /// </summary>
        public ITask Update(int boardId, int taskId, string name, string description, int userId, int projectId, int colorId, int?planingTime, Limits limits)
        {
            if (name.IsNullOrEmpty())
            {
                throw new ArgumentException("Name");
            }

            // TODO: Не вызывать апдейт, если ничиго не поменялось
            // TODO: Добавить колонку с временем обновления для поддержки версионности

            ITask     task    = _Get(taskId);
            TimezTask oldTask = new TimezTask(task);

            IProject     project  = Utility.Projects.Get(boardId, projectId);
            IBoardsColor color    = Utility.Boards.GetColor(project.BoardId, colorId);
            IUser        executor = Utility.Users.Get(userId);
            ITasksStatus status   = Utility.Statuses.Get(boardId, task.TaskStatusId);

            CheckTaskLimits(status, userId, limits, task);

            bool taskAssigned       = task.ExecutorUserId != executor.Id;
            bool colorChanged       = task.ColorId != color.Id;
            bool projectChanged     = task.ProjectId != project.Id;
            bool planingTimeChanged = task.PlanningTime != planingTime;

            task.Name           = name;
            task.Description    = description;
            task.ExecutorUserId = executor.Id;
            task.ExecutorEmail  = executor.EMail;
            task.ExecutorNick   = executor.Nick;
            task.ProjectId      = project.Id;
            task.ProjectName    = project.Name;
            task.ColorId        = color.Id;
            task.ColorHEX       = color.Color;
            task.ColorName      = color.Name;
            task.ColorPosition  = color.Position;
            task.PlanningTime   = planingTime;

            using (TransactionScope scope = new TransactionScope())
            {
                Repository.SubmitChanges();

                OnUpdate.Invoke(new UpdateEventArgs <ITask>(oldTask, task));

                if (taskAssigned)
                {
                    OnTaskAssigned.Invoke(new UpdateEventArgs <ITask>(oldTask, task));
                }

                if (colorChanged)
                {
                    OnUpdateColor.Invoke(new UpdateEventArgs <ITask>(oldTask, task));
                }

                if (projectChanged)
                {
                    OnUpdateProject.Invoke(new UpdateEventArgs <ITask>(oldTask, task));
                }

                if (planingTimeChanged)
                {
                    OnUpdatePlaningTime.Invoke(new UpdateEventArgs <ITask>(oldTask, task));
                }

                scope.Complete();
            }

            return(task);
        }
Ejemplo n.º 16
0
        internal override void Init()
        {
            #region

            // Следим за другими утилитами, что б поддерживать кеш задач в валидном состоянии
            Utility.Projects.OnDelete += ProjectsUtility_OnDelete;

            // Удаляем из кеша все задачи удаленного пользователя
            Utility.Boards.OnRemoveUserFromBoard += BoardsUtility_OnRemoveUserFromBoard;

            // Обновляем цвета у задач
            Utility.Boards.OnUpdateColor +=
                (s, e) =>
            {
                IBoardsColor color = e.Data;

                HashSet <ITask> cache = GetTasksCache(color.BoardId);
                if (cache != null)
                {
                    using (new UpdateLock(color.BoardId))
                    {
                        ITask[] tasks = cache
                                        .Where(x => x.ColorId == color.Id)
                                        .ToArray();

                        foreach (var item in tasks)
                        {
                            item.ColorHEX      = color.Color;
                            item.ColorPosition = color.Position;
                            item.ColorName     = color.Name;
                        }
                    }
                }
            };

            Utility.Boards.OnDeleteColor +=
                (s, e) =>
            {
                IBoardsColor color = e.Data;

                var key = GetAllTasksKey(color.BoardId);
                Cache.Clear(key);
            };
            #endregion

            #region Обновляем имена проектов в задачах
            Utility.Projects.OnUpdate.Add(
                (sender, e) =>
            {
                IProject project   = e.Data;
                TaskFilter filter  = CreateFilter(project.BoardId);
                filter.ProjectIds  = new[] { project.Id };
                List <ITask> tasks = Get(filter);
                tasks.ForEach(x => x.ProjectName = project.Name);
            });
            #endregion

            #region Обновляем имена статусов в задачах
            Utility.Statuses.OnUpdate.Add(
                (sender, e) =>
            {
                ITasksStatus status = e.Data;
                TaskFilter filter   = CreateFilter(status.BoardId);
                filter.Statuses     = new[] { status.Id };
                List <ITask> tasks  = Get(filter);
                tasks.ForEach(
                    x =>
                {
                    x.TaskStatusName     = status.Name;
                    x.TaskStatusPosition = status.Position;
                });
            });
            #endregion

            #region При удалении статуса чистим кеш доски
            Utility.Statuses.OnDelete.Add(
                (sender, e) =>
            {
                ITasksStatus status = e.Data;
                var key             = Cache.GetKeys(CacheKey.Status, status.Id);
                Cache.Clear(key);

                key = GetAllTasksKey(status.BoardId);
                Cache.Clear(key);
            });
            #endregion

            #region Обновление исполнителя

            Utility.Users.OnUpdate.Add(
                (sender, e) =>
            {
                IUser user = e.NewData;
                Repository.Tasks.UpdateExecutor(user);

                List <IBoard> boards = Utility.Boards.GetByUser(user.Id);
                foreach (var board in boards)
                {
                    var cache = GetTasksCache(board.Id);
                    if (cache != null)
                    {
                        using (new UpdateLock(board.Id))
                        {
                            foreach (ITask task in cache.Where(x => x.ExecutorUserId == user.Id))
                            {
                                task.ExecutorEmail = user.EMail;
                                task.ExecutorNick  = user.Nick;
                            }
                        }
                    }
                }
            });

            #endregion

            // TODO: протестить лики из-за подписок
        }
Ejemplo n.º 17
0
 public PlanningTimeRequered(ITasksStatus status)
     : base("В статусе \"" + status.Name + "\" обязательно требуется указывать планируемое время.")
 {
 }
Ejemplo n.º 18
0
        public void MainTest()
        {
            ViewResult            result;
            RedirectToRouteResult redirectToRouteResult;
            FormCollection        collection = new FormCollection();

            #region  егистрация/Атовризация

            IUser user0 = Registation(Email0);
            IUser user2 = Registation(Email2, out result, out redirectToRouteResult, null);
            IUser user1 = Registation(Email1, out result, out redirectToRouteResult, null);

            #endregion

            #region Создание доски
            BoardsController boardsController = Base.GetController <BoardsController>();
            collection.Clear();
            collection.Add("name", "test");
            collection.Add("description", "description");
            redirectToRouteResult = (RedirectToRouteResult)boardsController.Create(collection);
            int boardId = redirectToRouteResult.RouteValues["Id"].To <int>();
            var board   = boardsController.Utility.Boards.Get(boardId);
            Assert.IsNotNull(board);
            #endregion

            #region Проверяем статусы

            TasksStatusesController    tasksStatusesController = Base.GetController <TasksStatusesController>();
            PartialViewResult          resultBase = tasksStatusesController.List(boardId);
            IEnumerable <ITasksStatus> statuses   = (IEnumerable <ITasksStatus>)resultBase.Model;
            Assert.AreEqual(statuses.First().Name, "Беклог");

            tasksStatusesController = Base.GetController <TasksStatusesController>();
            resultBase = tasksStatusesController.Edit(boardId,
                                                      new TimezStatus
            {
                Name    = "test",
                BoardId = boardId
            });

            statuses = (IEnumerable <ITasksStatus>)resultBase.Model;
            Assert.AreEqual(statuses.ElementAt(statuses.Count() - 1).Name, "test");

            #endregion

            #region проверяем задачи

            var user            = boardsController.Utility.Users.Get(Email1);
            var boardStatusList = boardsController.Utility.Statuses.GetByBoard(board.Id);

            // получаем доску
            var boardData = (ViewResultBase)boardsController.Edit(boardId);
            Assert.IsInstanceOfType(boardData.Model, typeof(IBoard));
            ProjectsController     projectController = Base.GetController <ProjectsController>();
            IEnumerable <IProject> projs             = (IEnumerable <IProject>)projectController.List(boardId).Model;
            Assert.IsNotNull(projs);

            // получаем цвета доски
            var boardColor = (ViewResultBase)boardsController.EditColorList(boardId);
            Assert.IsInstanceOfType(boardColor.ViewData.Model, typeof(IEnumerable <IBoardsColor>));
            IEnumerable <IBoardsColor> boardColors = boardColor.ViewData.Model as IEnumerable <IBoardsColor>;

            // Создание задачи
            collection.Clear();
            collection["task-id"]          = null;
            collection["task-statusid"]    = boardStatusList[0].Id.ToString();
            collection["task-userid"]      = user.Id.ToString();
            collection["task-name"]        = "Тестовая задача";
            collection["task-description"] = "Описание тестовой задачи";

            collection["task-projectsid"] = projs.First().Id.ToString();
            collection["task-colorid"]    = boardColors.First().Id.ToString(CultureInfo.InvariantCulture);

            // проверяем создание
            KanbanController kanbanController = Base.GetController <KanbanController>();
            ViewResultBase   taskData         = (ViewResultBase)kanbanController.TaskPopup(boardId, null, collection);
            ITask            task             = CheckTask(taskData);
            Assert.IsTrue(task.CreatorUserId == kanbanController.Utility.Authentication.UserId);

            // архивирование
            collection["task-name"] = "Тестовая задача2";
            taskData = (ViewResultBase)kanbanController.TaskPopup(boardId, null, collection);
            ITask task2 = CheckTask(taskData);
            kanbanController.ToArchive(boardId, task2.Id);
            TasksController tasksController = Base.GetController <TasksController>();
            taskData = tasksController.Details(boardId, task2.Id, true);
            Assert.IsTrue((taskData.Model as ITask).Id == task2.Id);
            Assert.IsTrue((bool)taskData.ViewData["isArchive"]);

            // обновляем задачу
            collection.Clear();
            collection["task-id"] = task.Id.ToString();
            ITasksStatus planningStatus = boardStatusList.First(x => x.PlanningRequired);
            collection["task-statusid"]    = planningStatus.Id.ToString();
            collection["task-userid"]      = user.Id.ToString();
            collection["task-name"]        = "Тестовая задачаю. Обновление";
            collection["task-description"] = "Описание тестовой задачи. Обновление";
            collection["task-projectsid"]  = projs.First().Id.ToString();
            collection["task-colorid"]     = boardColors.ToList()[1].Id.ToString();
            kanbanController.Dispose();
            kanbanController = Base.GetController <KanbanController>();
            var json = (JsonResult)kanbanController.TaskPopup(boardId, task.Id, collection);
            Assert.IsTrue((json.Data as JsonMessage).Message == new PlanningTimeRequered(planningStatus).Message);


            // проверяем изменение цвета
            kanbanController = Base.GetController <KanbanController>();
            var color = kanbanController.SetColor(task.Id, boardColors.ToList()[0].Id, boardId);
            Assert.AreNotEqual(color, "");

            // проверям установку времени
            kanbanController = Base.GetController <KanbanController>();
            collection.Clear();
            collection["task-forsed-count"] = "true";
            collection["task-forsed-time"]  = "false";
#pragma warning disable 168
            JsonResult planningTime = (JsonResult)kanbanController.SetPlanningTime(boardId, task.Id, 180, task.TaskStatusId, collection);
#pragma warning restore 168

            // проверяем обновление статуса
            kanbanController = Base.GetController <KanbanController>();
            collection.Clear();
            collection["task-forsed-count"] = "true";
            collection["task-forsed-time"]  = "false";
            kanbanController.UpdateStatus(boardId, task.Id, boardStatusList[0].Id, collection);

            // проверяем исполнителя
            kanbanController = Base.GetController <KanbanController>();
            user             = kanbanController.Utility.Users.Get(Email2);
            kanbanController.SetExecutor(task.BoardId, task.Id, user.Id);

            // проверяем проект
            // сначала создадим проект
            projectController.Dispose();
            projectController = Base.GetController <ProjectsController>();
            collection.Clear();
            string projectName = "тестовый проект " + DateTime.Now.Ticks.ToString();
            collection["Name"] = projectName;
            var projectData = (ViewResultBase)projectController.Edit(boardId, null, collection);
            // проверяем создание проекта
            Assert.IsInstanceOfType(projectData.ViewData.Model, typeof(IEnumerable <IProject>));
            var projects = projectData.ViewData.Model as IEnumerable <IProject>;
            var project  = projects.SingleOrDefault(p => p.Name == projectName);
            Assert.IsNotNull(project);

            // изменяем проект
            kanbanController = Base.GetController <KanbanController>();
            kanbanController.SetProject(task.BoardId, task.Id, project.Id);

            // переназначение
            ParticipantController participantController = Base.GetController <ParticipantController>();
            collection.Clear();
            collection["participant-id"] = user1.Id.ToString();
            participantController.Tasks(boardId, user0.Id, collection);
            collection["participant-id"] = user2.Id.ToString();
            participantController.Tasks(boardId, user0.Id, collection);
            // удаление
            kanbanController = Base.GetController <KanbanController>();
            kanbanController.DeleteTask(task2.Id, task2.BoardId);
            kanbanController.DeleteTask(task.Id, task.BoardId);

            // проверяем удаление
            kanbanController = Base.GetController <KanbanController>();
            kanbanController.Index(boardId);
            kanbanController = Base.GetController <KanbanController>();
            collection.Clear();
            PartialViewResult kanban = kanbanController.Kanban(boardId, collection);
            Assert.IsInstanceOfType(kanban.ViewData["Tasks"], typeof(IEnumerable <ITask>));
            IEnumerable <ITask> boardTasks = kanban.ViewData["Tasks"] as IEnumerable <ITask>;
            ITask deletedTask = boardTasks.FirstOrDefault(t => t.Id == task.Id);
            Assert.IsNull(deletedTask);

            // Проверка попадания в журнал ошибок и предупреждений
            var logController = Base.GetController <LogController>();
            var logData       = (ViewResultBase)logController.Items(boardId, null);

            Assert.IsInstanceOfType(logData.ViewData.Model, typeof(IEnumerable <IEventHistory>));
            var logs        = logData.ViewData.Model as IEnumerable <IEventHistory>;
            var boardEvents = logs.Where(p => p.BoardId == boardId);
            Assert.AreNotEqual(boardEvents.Count(), 0);

            Assert.AreNotEqual(boardEvents.Count(e => (e.EventType & EventType.CreateTask) == EventType.CreateTask), 0);
            Assert.AreNotEqual(boardEvents.Count(e => (e.EventType & EventType.Delete) == EventType.Delete), 0);
            Assert.AreNotEqual(boardEvents.Count(e => (e.EventType & EventType.Update) == EventType.Update), 0);
            Assert.AreNotEqual(boardEvents.Count(e => (e.EventType & EventType.TaskColorChanged) == EventType.TaskColorChanged), 0);
            Assert.AreNotEqual(boardEvents.Count(e => (e.EventType & EventType.TaskAssigned) == EventType.TaskAssigned), 0);
            Assert.AreNotEqual(boardEvents.Count(e => (e.EventType & EventType.ProjectChanged) == EventType.ProjectChanged), 0);
            Assert.AreNotEqual(boardEvents.Count(e => (e.EventType & EventType.PlaningTimeChanged) == EventType.PlaningTimeChanged), 0);


            #endregion

            #region Удаление досок
            boardsController.Dispose();
            boardsController = Base.GetController <BoardsController>();
            PartialViewResult partialResult = boardsController.List(null);
            Assert.IsInstanceOfType(partialResult.Model, typeof(List <IBoard>));
            foreach (IBoard item in partialResult.Model as List <IBoard> )
            {
                boardsController = Base.GetController <BoardsController>();
                boardsController.Delete(item.Id);
                try
                {
                    board = boardsController.Utility.Boards.Get(item.Id);
                    Assert.IsNull(board);
                }
                catch (Exception ex)
                {
                    Assert.IsInstanceOfType(ex, typeof(AccessDeniedException));
                }
            }
            #endregion

            boardsController.Utility.Users.Delete(Email1);
            Assert.IsNull(boardsController.Utility.Users.Get(Email1));
        }
Ejemplo n.º 19
0
 public void Delete(ITasksStatus status)
 {
     _Context.TasksStatus.DeleteOnSubmit(status as TasksStatus);
     _Context.SubmitChanges();
 }