public async Task <JsonResult> GetAll([FromQuery] uint?id)
        {
            int taskId = this.ParseValue(id);

            // Проверяем существует ли задача
            var task = await _context.Worktasks.FirstOrDefaultAsync(x => x.Id == taskId)
                       .ConfigureAwait(false);

            if (task == null)
            {
                throw new Exception(TextResource.API_NotExistWorktaskId);
            }

            int projectId = task.ProjectId;
            int userId    = int.Parse(User.Identity.Name);

            // Проверяем доступ
            var linkedProject = await _context.GetLinkedAcceptedProject(projectId, userId)
                                .ConfigureAwait(false);

            if (linkedProject == null)
            {
                throw new Exception(TextResource.API_NoAccess);
            }

            // Собираем информацию по трекам
            var worktracks = await _context.Worktracks.Where(x => x.WorktaskId == taskId && !x.Running)
                             .OrderByDescending(x => x.StartedTime)
                             .Select(x => new WorktracksGetAllResponse
            {
                id          = x.Id,
                login       = x.User.Login,
                startedTime = x.StartedTime,
                stoppedTime = x.StoppedTime,
                totalTime   = (x.StoppedTime - x.StartedTime).ToString(@"hh\:mm\:ss")
            })
                             .ToListAsync()
                             .ConfigureAwait(false);

            if (worktracks.Count == 0)
            {
                return(new JsonResult(new List <WorktracksGetAllResponse>()));
            }

            return(new JsonResult(worktracks));
        }
        public async Task <JsonResult> GetUsers([FromQuery] uint?id)
        {
            int projectId = this.ParseValue(id);
            int userId    = int.Parse(User.Identity.Name);

            // Проверяем, что есть доступ
            var linkedProject = _dbContext.GetLinkedAcceptedProject(projectId, userId);

            if (linkedProject == null)
            {
                throw new Exception(TextResource.API_NoAccess);
            }

            var users = await _dbContext.LinkedProjects.Where(x => x.ProjectId == projectId)
                        .Select(x => new {
                Id    = x.UserId,
                login = x.User.Login,
                right = x.Role
            })
                        .ToListAsync()
                        .ConfigureAwait(false);

            return(new JsonResult(new ProjectGetUsersResponse
            {
                users = users
            }, _jsonOptions));
        }
Example #3
0
        public async Task <JsonResult> Get([FromQuery] uint?id)
        {
            int taskId = this.ParseValue(id);

            var worktask = await _context.Worktasks.FirstOrDefaultAsync(x => x.Id == taskId)
                           .ConfigureAwait(false);

            if (worktask == null)
            {
                throw new Exception(TextResource.API_NotExistWorktaskId);
            }

            int projectId = worktask.ProjectId;
            int userId    = int.Parse(User.Identity.Name);

            // Проверяем доступ
            var linkedProject = await _context.GetLinkedAcceptedProject(projectId, userId)
                                .ConfigureAwait(false);

            if (linkedProject == null)
            {
                throw new Exception(TextResource.API_NoAccess);
            }

            var task = new
            {
                worktask.Id,
                worktask.ProjectId,
                worktask.StateId,
                worktask.Title,
                worktask.Description,
                worktask.Duration,
                worktask.CreatedDate
            };

            return(new JsonResult(new WorktaskGetResponse
            {
                project = worktask.Project,
                worktask = task,
                isAdmin = linkedProject.RoleId
            }, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            }));
        }
Example #4
0
        public async Task <JsonResult> UpdateUser(UpdateUserModel model)
        {
            byte roleId    = byte.Parse(model.rightId);
            int  projectId = int.Parse(model.projectId);

            int userId = int.Parse(User.Identity.Name);

            // Проверка доступа
            var linkedProjectRequestUser = await _context.GetLinkedAcceptedProject(projectId, userId)
                                           .ConfigureAwait(false);

            if (linkedProjectRequestUser == null || linkedProjectRequestUser.RoleId == 1)
            {
                throw new Exception(TextResource.API_NoAccess);
            }

            // Проверка существования проекта
            var linkedProject = await _context.LinkedProjects.FirstOrDefaultAsync(x => x.User.Login == model.userLogin && x.ProjectId == projectId)
                                .ConfigureAwait(false);

            if (linkedProject == null)
            {
                throw new Exception(TextResource.API_NotExistLinkedProject);
            }

            linkedProject.RoleId = ( byte )roleId;

            await _context.SaveChangesAsync(true)
            .ConfigureAwait(false);

            // Обновляем значение в кэше
            await _context.GetLinkedAcceptedProject(linkedProject.ProjectId, linkedProject.UserId, true)
            .ConfigureAwait(false);

            return(new JsonResult(new RoleUpdateUserResponse
            {
                project = linkedProject.Project,
                roleId = roleId
            }, _jsonOptions));
        }
        public async Task <JsonResult> Update([FromBody] UpdateStateModel model)
        {
            var dbWorkTask = await _context.Worktasks.FirstOrDefaultAsync(x => x.Id == model.TaskId)
                             .ConfigureAwait(false);

            if (dbWorkTask == null)
            {
                throw new Exception(TextResource.API_NotExistWorktaskId);
            }

            var stateExist = await _context.States.AnyAsync(x => x.Id == model.StateId)
                             .ConfigureAwait(false);

            if (!stateExist)
            {
                throw new Exception(TextResource.API_NotExistStateId);
            }

            int projectId = dbWorkTask.ProjectId;
            int userId    = int.Parse(User.Identity.Name);

            var linkedProject = _context.GetLinkedAcceptedProject(projectId, userId);

            if (linkedProject == null)
            {
                throw new Exception(TextResource.API_NoAccess);
            }

            // Если на задачу кто-то тречит - заставить их прекратить
            var runningWorktracks = _context.Worktracks.Where(x => x.WorktaskId == dbWorkTask.Id && x.Running);

            if (model.StateId == 6 && runningWorktracks.Any())
            {
                var tracks = runningWorktracks.ToList();
                var users  = tracks.Select(x => x.UserId);

                foreach (var userName in users)
                {
                    await _hub.Value.Clients.Group(userName.ToString()).SendAsync("getActiveTracking", false, null, false, TextResource.API_TrackingTaskClosed)
                    .ConfigureAwait(false);
                }

                var now = DateTime.UtcNow;
                tracks.ForEach(x =>
                {
                    x.Running     = false;
                    x.StoppedTime = now;
                });

                _context.UpdateRange(tracks);
            }

            dbWorkTask.StateId = ( byte )model.StateId;

            _context.Update(dbWorkTask);

            await _context.SaveChangesAsync(true)
            .ConfigureAwait(false);

            return(new JsonResult(new OkResponse
            {
                message = "Вы успешно изменили состояние задачи"
            }));
        }
Example #6
0
        public async Task StartTracking(int?taskId)
        {
            var worktaskId = taskId.Value;

            var userName = Context.User.Identity.Name;
            int userId   = int.Parse(Context.User.Identity.Name);

            var anyActiveWorktrack = await _dbContext.Worktracks.AsNoTracking()
                                     .AnyAsync(x => x.User.Id == userId && x.Running)
                                     .ConfigureAwait(false);

            if (anyActiveWorktrack)
            {
                await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "У вас уже есть задача, которая отслеживается.")
                .ConfigureAwait(false);

                return;
            }

            var worktaskData = await _dbContext.Worktasks.AsNoTracking()
                               .Where(x => x.Id == worktaskId)
                               .Select(x => new { x.ProjectId, x.State })
                               .FirstOrDefaultAsync()
                               .ConfigureAwait(false);

            if (worktaskData == null)
            {
                await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "Не существует задачи с таким идентификатором")
                .ConfigureAwait(false);

                return;
            }

            var projectId = worktaskData.ProjectId;

            if (_dbContext.GetLinkedAcceptedProject(projectId, userId) == null)
            {
                await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "У вас недостаточно прав, чтобы отслеживать эту задачу.")
                .ConfigureAwait(false);

                return;
            }

            if (worktaskData.State.Id == 6)
            {
                await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "Данная задача уже закрыта")
                .ConfigureAwait(false);

                return;
            }

            var now       = DateTime.UtcNow;
            var worktrack = await _dbContext.AddAsync(new Worktrack
            {
                UserId      = userId,
                StartedTime = now,
                StoppedTime = now,
                WorktaskId  = worktaskId,
                Running     = true
            })
                            .ConfigureAwait(false);

            await _dbContext.SaveChangesAsync()
            .ConfigureAwait(false);

            var group = Clients.Group(userName);

            await group.SendAsync("getActiveTracking", true, worktrack.Entity, true, string.Empty)
            .ConfigureAwait(false);
        }