Пример #1
0
        public async Task <IOutput> Handle(AddCommentInput request, CancellationToken cancellationToken)
        {
            var currentUser = await _currentUserProvider.GetCurrentUser();

            if (currentUser is null)
            {
                return(ActionOutput.Error("Пользователь не найден"));
            }

            var lesson = await _context.Lessons.FirstOrDefaultAsync(
                x => x.Id == request.LessonId,
                cancellationToken : cancellationToken);

            if (lesson is null)
            {
                return(ActionOutput.Error("Урок не найден"));
            }

            var comment = new Entity.Comment(request.Text, currentUser, lesson);

            await _context.Comments.AddAsync(comment, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            return(ActionOutput.SuccessData(comment.Id));
        }
Пример #2
0
        public async Task <IOutput> Handle(ChangeRoleInput request, CancellationToken cancellationToken)
        {
            var currentUesrId = (await _currentUserProvider.GetCurrentUser()).Id;
            var user          = await _userManager.FindByIdAsync(request.UserId.ToString());

            if (user is null)
            {
                return(ActionOutput.Error("Пользователя не существует."));
            }

            if (user.Id == currentUesrId)
            {
                return(ActionOutput.Error("Нельзя менять себе роль"));
            }

            var newRole = request.NewRole;

            var userRoles = await _userManager.GetRolesAsync(user);

            var addResult = await _userManager.AddToRoleAsync(user, Enum.GetName(newRole));

            var removeResult = await _userManager.RemoveFromRolesAsync(user, userRoles);

            return(ActionOutput.Success);
        }
Пример #3
0
        public async Task <IActionResult> DispatchAsync <TRequest>(TRequest request) where TRequest : IUseCaseInput
        {
            using var services = _serviceProvider.CreateScope();

            var validator = services.ServiceProvider.GetService <IValidator <TRequest> >();

            if (validator is null)
            {
                throw new Exception("Validator wasn't found");
            }

            var validationResult = await validator.ValidateAsync(request, CancellationToken.None);

            if (!validationResult.IsValid)
            {
                var actionPresenter = services.ServiceProvider.GetService <IPresenter <ActionOutput> >();

                return(actionPresenter.Present(ActionOutput.Error(validationResult.Errors.First().ErrorMessage)));
            }

            var result = await _mediator.Send(request);

            var presenterType = typeof(IPresenter <>).MakeGenericType(result.GetType());
            var presenter     = services.ServiceProvider.GetService(presenterType);

            if (presenter is null)
            {
                throw new Exception("Presenter for this output was not found " + result.GetType().Name);
            }

            var method =
                presenter.GetType().GetMethod(nameof(IPresenter <IOutput> .Present), new [] { result.GetType() });

            return((IActionResult)method !.Invoke(presenter, new object[] { result }));
        }
Пример #4
0
        public async Task <IActionResult> AddPracticeOrder([FromForm] AddPracticeOrderInput request)
        {
            var currentUser = await _currentUserProvider.GetCurrentUser();

            if (currentUser is null)
            {
                return(Json(ActionOutput.Error("Пользователь не найден")));
            }
            request.UserId = currentUser.Id;
            return(await _dispatcher.DispatchAsync(request));
        }
        public async Task <IActionResult> GetProgressCurrent([FromQuery] ProgressesByIdInput request)
        {
            var currentUser = await _currentUserProvider.GetCurrentUser();

            if (currentUser is null)
            {
                return(Json(ActionOutput.Error("Пользователь не найден")));
            }

            request.SetUserId(currentUser.Id);

            return(await _dispatcher.DispatchAsync(request));
        }
Пример #6
0
        public async Task <IOutput> Handle(ChangePhotoInput request, CancellationToken cancellationToken)
        {
            var user = await _context.Users
                       .FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken : cancellationToken);

            if (user is null)
            {
                return(ActionOutput.Error("Пользователь не найден"));
            }

            using var unit = _context.CreateUnitOfWork();

            try
            {
                var oldFile = await _context.AppFiles
                              .FirstOrDefaultAsync(x => x.Id == user.UserPhotoId, cancellationToken : cancellationToken);

                user.UserPhoto = null;

                var deleteResult = await _fileUploader.DeleteFile(oldFile.Path);
            }
            catch (Exception e) {}

            var fileSaveResult = await _fileUploader.SaveFile(request.NewPhoto);

            if (fileSaveResult.Succeeded == false)
            {
                return(ActionOutput.Error("Что-то пошло не так"));
            }
            var filePath        = fileSaveResult.Data.OperatedFilePath;
            var filePathRelated = fileSaveResult.Data.OperatedFileRelatedPath;
            var fileEntity      = new AppFile(request.NewPhoto.FileName, filePath, filePathRelated)
            {
                UserId = user.Id
            };
            var items = await _context.AppFiles.Where(x => x.UserId == user.Id).ToListAsync(cancellationToken);

            _context.AppFiles.RemoveRange(items);

            await _context.SaveChangesAsync(cancellationToken);

            await _context.AppFiles.AddAsync(fileEntity, cancellationToken);

            user.Photo = filePathRelated;

            await _context.SaveChangesAsync(cancellationToken);

            await unit.Apply();

            return(ActionOutput.SuccessData(user.Photo));
        }
Пример #7
0
        public async Task <IOutput> Handle(GetSubjectInfoInput request, CancellationToken cancellationToken)
        {
            var subject = await _context.Subjects
                          .Include(x => x.Lessons)
                          .FirstOrDefaultAsync(x => x.Id == request.SubjectId || x.Name == request.SubjectName,
                                               cancellationToken: cancellationToken);

            if (subject is null)
            {
                return(ActionOutput.Error("Предмета не существует"));
            }

            return(ActionOutput.SuccessData(_mapper.Map <SubjectDeteiledView>(subject)));
        }
Пример #8
0
        public async Task <IOutput> Handle(AddCertificateInput request, CancellationToken cancellationToken)
        {
            var subject = await _context.Subjects
                          .Include(x => x.Lessons)
                          .FirstOrDefaultAsync(x => x.Id == request.SubjectId,
                                               cancellationToken: cancellationToken);

            if (subject is null)
            {
                return(ActionOutput.Error("Данного предмета не существует"));
            }

            var user = await _context.Users
                       .Include(x => x.UserProgresses)
                       .ThenInclude(x => x.Lesson)
                       .FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken: cancellationToken);

            if (user is null)
            {
                return(ActionOutput.Error("Пользователь не найден"));
            }

            /* has such certificate */
            var lastSertificate = await _context.SubjectSertificates
                                  .FirstOrDefaultAsync(
                x => x.OwnerId == request.UserId && x.SubjectId == request.SubjectId,
                cancellationToken : cancellationToken);

            if (lastSertificate != null)
            {
                return(ActionOutput.Error("Данный сертификат уже получен"));
            }

            /* count progresses to certificate */
            var doneLessonCount      = user.UserProgresses.Count(x => x.Lesson.SubjectId == subject.Id);
            var lessonForSertificate = subject.Lessons.Count;

            if (doneLessonCount != lessonForSertificate)
            {
                return(ActionOutput.Error("Пройдены не все уроки"));
            }

            var certificate = new SubjectSertificate(user, subject);

            _context.SubjectSertificates.Add(certificate);
            await _context.SaveChangesAsync(cancellationToken);

            return(ActionOutput.SuccessData(certificate.Id));
        }
Пример #9
0
        public async Task <IOutput> Handle(EditCommentInput request, CancellationToken cancellationToken)
        {
            var comment = await _context.Comments.FindAsync(request.CommentId);

            if (comment is null)
            {
                return(ActionOutput.Error("Комментария не существует"));
            }

            comment.Text = request.NewText;

            await _context.SaveChangesAsync(cancellationToken);

            return(ActionOutput.Success);
        }
Пример #10
0
        public async Task <IOutput> Handle(GetPracticeInfoInput request, CancellationToken cancellationToken)
        {
            var practice = await _context.PracticeOrders
                           .Include(x => x.Author)
                           .Include(x => x.Teacher)
                           .Include(x => x.Lesson)
                           .Include(x => x.PracticeContent)
                           .FirstOrDefaultAsync(x => x.Id == request.PracticeId, cancellationToken);

            if (practice is null)
            {
                return(ActionOutput.Error("Заявка на прохождение не нашлась"));
            }

            return(ActionOutput.SuccessData(_mapper.Map <Entity.PracticeOrder, GetPracticeInfoOutput>(practice)));
        }
Пример #11
0
        public async Task <IOutput> Handle(ChangeNickInput request, CancellationToken cancellationToken)
        {
            var currentUser = await _context.Users.FirstOrDefaultAsync(
                x => x.Id == request.UserId, cancellationToken : cancellationToken
                );

            if (currentUser is null)
            {
                return(ActionOutput.Error("User was not found"));
            }

            currentUser.Nick = request.NewNick;

            await _context.SaveChangesAsync(cancellationToken);

            return(ActionOutput.Success);
        }
Пример #12
0
        public async Task <IOutput> Handle(LessonGetOneInput request, CancellationToken cancellationToken)
        {
            Entity.Lesson lesson = await _context.Lessons
                                   .Include(x => x.Comments)
                                   .ThenInclude(x => x.Author)
                                   .Include(x => x.Subject)
                                   .FirstOrDefaultAsync(x => x.Id == request.LessonId,
                                                        cancellationToken: cancellationToken);

            if (lesson is null)
            {
                _logger.LogInformation("Lesson with id {id} wasn't found", request.LessonId);
                return(ActionOutput.Error("Урок не существует."));
            }

            return(ActionOutput.SuccessData(_mapper.Map <LessonDetailedView>(lesson)));
        }
Пример #13
0
        public async Task <IOutput> Handle(DeleteCommentInput request, CancellationToken cancellationToken)
        {
            var comment = await _context.Comments.FirstOrDefaultAsync(
                x => x.Id == request.CommentId,
                cancellationToken : cancellationToken);

            if (comment is null)
            {
                return(ActionOutput.Error("Комментария не существует."));
            }

            _context.Comments.Remove(comment);

            var affectedRecords = await _context.SaveChangesAsync(cancellationToken);

            return(ActionOutput.SuccessData(affectedRecords));
        }
Пример #14
0
        public async Task <IOutput> Handle(UserInfoInput request, CancellationToken cancellationToken)
        {
            var user = await _context.Users
                       .AsNoTracking()
                       .WithRoles()
                       .Include(x => x.SubjectSertificates)
                       .Include(x => x.UserProgresses)
                       .Include(x => x.PracticeOrders)
                       .FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken: cancellationToken);

            if (user is null)
            {
                return(ActionOutput.Error("Пользователь не был найден"));
            }

            return(ActionOutput.SuccessData(_mapper.Map <UserViewDetailed>(user)));
        }
Пример #15
0
        public async Task <IOutput> Handle(ChangePasswordInput request, CancellationToken cancellationToken)
        {
            var user = await _userManager.FindByIdAsync(request.UserId);

            if (user is null)
            {
                return(ActionOutput.Error("Пользователь не найден"));
            }

            var changeResult = await _userManager.ChangePasswordAsync(user, request.OldPassword, request.NewPassword);

            if (changeResult.Succeeded == false)
            {
                return(ActionOutput.Error(changeResult.Errors.FirstOrDefault().ToString()));
            }

            return(ActionOutput.Success);
        }
        public async Task <IOutput> Handle(ResolvePracticeInput request, CancellationToken cancellationToken)
        {
            var practice = await _context.PracticeOrders
                           .Include(x => x.Author)
                           .Include(x => x.Lesson)
                           .FirstOrDefaultAsync(x => x.Id == request.PracticeId, cancellationToken: cancellationToken);

            if (practice is null)
            {
                return(ActionOutput.Error("Заявка на прохождение не нашлась"));
            }

            if (practice.IsDone)
            {
                return(ActionOutput.Error("Решение уже принято"));
            }

            if (practice.AuthorId == request.TeacherId)
            {
                return(ActionOutput.Error("Нельзя принять практику у себя"));
            }

            practice.IsDone     = true;
            practice.IsResolved = true;
            practice.TeacherId  = request.TeacherId;

            _context.PracticeOrders.Update(practice);

            await _context.SaveChangesAsync(cancellationToken);

            var progress = new UserProgress(practice.Author, practice.Lesson);
            await _context.Progresses.AddAsync(progress, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            _mailClient.SendMail(practice.Author.Mail, message =>
            {
                message.Subject = $"Практический урок {practice.Lesson.Name} пройден.";
                message.Body    = _templateCreator.GetResolveLetter(practice.Lesson.Name);
            });

            return(ActionOutput.Success);
        }
Пример #17
0
        public async Task <IOutput> Handle(AddProgressInput request, CancellationToken cancellationToken)
        {
            var user = await _context.Users
                       .FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken : cancellationToken);

            if (user is null)
            {
                return(ActionOutput.Error("Пользователь не был найден"));
            }

            var lesson = await _context.Lessons.FindAsync(request.LessonId);

            if (lesson is null)
            {
                return(ActionOutput.Error("Урок не был найден"));
            }

            if (lesson.IsPractice)
            {
                return(ActionOutput.Error("Урок практический"));
            }

            var hasEqualProgress = await _context.Progresses
                                   .AnyAsync(x => x.UserId == user.Id && x.LessonId == lesson.Id,
                                             cancellationToken : cancellationToken);

            if (hasEqualProgress)
            {
                return(ActionOutput.Error("Данный урок уже засчитан"));
            }

            var progress = new UserProgress(user, lesson);

            await _context.Progresses.AddAsync(progress, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            var newUserProgresses =
                await _context.Progresses.Where(x => x.UserId == user.Id).ToListAsync(cancellationToken);

            return(ActionOutput.SuccessData(_mapper.Map <List <UserProgressView> >(newUserProgresses)));
        }
Пример #18
0
        public async Task <IOutput> Handle(GetOnePracticeInput request, CancellationToken cancellationToken)
        {
            var user = await _context.Users
                       .FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken : cancellationToken);

            if (user is null)
            {
                return(ActionOutput.Error("Пользователь не найден"));
            }

            var practices = await _context.PracticeOrders
                            .Include(x => x.Author)
                            .Include(x => x.Teacher)
                            .Where(x => x.Author.Id == user.Id && x.LessonId == request.LessonId)
                            .OrderByDescending(x => x.CreatedDate)
                            .ToListAsync(cancellationToken: cancellationToken);

            return(request.Last ?
                   ActionOutput.SuccessData(_mapper.Map <Entity.PracticeOrder, GetOnePracticeOutput>(practices.FirstOrDefault())) :
                   ActionOutput.SuccessData(_mapper.Map <List <Entity.PracticeOrder>, List <GetOnePracticeOutput> >(practices)));
        }
Пример #19
0
        public async Task <IOutput> Handle(SignInInput request, CancellationToken cancellationToken)
        {
            var user = await _context.Users
                       .Include(x => x.RolesEntities)
                       .ThenInclude(x => x.Role)
                       .FirstOrDefaultAsync(x => x.Mail == request.Mail, cancellationToken);

            if (user is null)
            {
                _logger.LogInformation("User {name} was not found", request.Mail);
                return(ActionOutput.Error("Пользователь не найден"));
            }

            if (user.IsBanned == true)
            {
                _logger.LogInformation("User {name} tried to enter with ban", request.Mail);
                return(ActionOutput.Error("Пользователь забанен."));
            }

            var signInResult = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);

            if (signInResult.Succeeded == false)
            {
                _logger.LogInformation("User {name} was not found", request.Mail);
                return(ActionOutput.Error("Пользователь не найден"));
            }

            _logger.LogInformation($"User {user} signed in");

            var identity = _dataProvider.GetIdentity(request.Mail);

            if (identity is null)
            {
                return(ActionOutput.Error("Пользователь не найден"));
            }

            return(ActionOutput.SuccessData(new { token = _dataProvider.GetJwtByIdentity(identity) }));
        }
Пример #20
0
        public async Task <IOutput> Handle(CheckInput request, CancellationToken cancellationToken)
        {
            var user = await _currentUserProvider.GetCurrentUser();

            if (user is null)
            {
                return(ActionOutput.Error("Вы не авторизованы"));
            }

            if (user.IsBanned == true)
            {
                _logger.LogInformation("User {name} tried to enter with ban", user.Mail);
                return(ActionOutput.Error("Пользователь забанен."));
            }

            var identity = _dataProvider.GetIdentity(user.Mail);

            if (identity is null)
            {
                return(ActionOutput.Error("Пользователь не найден"));
            }

            return(ActionOutput.SuccessData(new { token = _dataProvider.GetJwtByIdentity(identity) }));
        }
Пример #21
0
        public async Task <IOutput> Handle(SignUpInput request, CancellationToken cancellationToken)
        {
            var hasSameNick = await _context.Users
                              .AnyAsync(x => x.Nick == request.Nick, cancellationToken : cancellationToken);

            if (hasSameNick)
            {
                return(ActionOutput.Error("Пользователь с таким ником уже зарегистрирован"));
            }

            var user = new Entity.User(request.Mail)
            {
                Nick = request.Nick
            };
            var registerResult = await _userManager.CreateAsync(user);

            if (registerResult.Succeeded == false)
            {
                return(ActionOutput.Error("Такой пользователь уже есть"));
            }

            await _context.SaveChangesAsync(cancellationToken);

            using var unit = _context.CreateUnitOfWork();

            var userPhotoPath = _configuration.GetSection("Static:DefaultUserPhoto").Value;

            if (request.UserPhoto != null)
            {
                var fileSaveResult = await _fileUploader.SaveFile(request.UserPhoto);

                if (fileSaveResult.Succeeded == false)
                {
                    return(ActionOutput.Error("Что-то пошло не так"));
                }
                var filePath        = fileSaveResult.Data.OperatedFilePath;
                var filePathRelated = fileSaveResult.Data.OperatedFileRelatedPath;
                var fileEntity      = new AppFile(request.UserPhoto.FileName, filePath, filePathRelated)
                {
                    UserId = user.Id,
                };
                userPhotoPath = filePathRelated;
                _context.AppFiles.Add(fileEntity);
            }

            user.Photo = userPhotoPath;

            await _userManager.AddToRoleAsync(user, UserRoles.Participant.ToString());

            await _userManager.AddPasswordAsync(user, request.Password);

            _logger.LogInformation($"User {user} was registered");

            await _context.SaveChangesAsync(cancellationToken);

            await unit.Apply();

            var identity = _dataProvider.GetIdentity(request.Mail);

            if (identity is null)
            {
                return(ActionOutput.Error("Данные не верны"));
            }

            return(ActionOutput.SuccessData(new { token = _dataProvider.GetJwtByIdentity(identity) }));
        }
        public async Task <IOutput> Handle(AddPracticeOrderInput request, CancellationToken cancellationToken)
        {
            var author = await _context.Users
                         .Include(x => x.UserProgresses)
                         .ThenInclude(x => x.Lesson)
                         .FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken: cancellationToken);

            if (author is null)
            {
                return(ActionOutput.Error("Пользователь не был найден"));
            }

            var lesson = await _context.Lessons
                         .FirstOrDefaultAsync(x => x.Id == request.LessonId, cancellationToken : cancellationToken);

            if (lesson is null)
            {
                return(ActionOutput.Error("Урок не был найден"));
            }

            if (lesson.IsPractice == false)
            {
                return(ActionOutput.Error("Урок не практический"));
            }

            if (lesson.Index > 1)
            {
                var hasLastLesson = author.UserProgresses.Any(x => x.Lesson.Index == lesson.Index - 1);
                if (hasLastLesson == false)
                {
                    return(ActionOutput.Error("Прошлый урок не пройден"));
                }
            }

            /* check last order */
            var lastOrder = await _practiceOrderProvider.GetUserPracticeOrders(author.Id, lesson.Id);

            if (lastOrder.FirstOrDefault()?.IsDone == false)
            {
                return(ActionOutput.Error("Заявка уже оформлена"));
            }


            using var unit = _context.CreateUnitOfWork();

            var fileSaveResult = await _fileUploader.SaveFile(request.CodeFile);

            if (fileSaveResult.Succeeded == false)
            {
                return(ActionOutput.Error("Что-то пошло не так"));
            }

            var filePath        = fileSaveResult.Data.OperatedFilePath;
            var filePathRelated = fileSaveResult.Data.OperatedFileRelatedPath;
            var fileEntity      = new AppFile(request.CodeFile.FileName, filePath, filePathRelated);
            await _context.AppFiles.AddAsync(fileEntity, cancellationToken);

            var order = new Entity.PracticeOrder(author, lesson, fileEntity);
            await _context.PracticeOrders.AddAsync(order, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            await unit.Apply();

            return(ActionOutput.SuccessData(order.Id));
        }