public async Task <IActionResult> FinalizeChallenge(int id, [FromBody] CompleteChallengeModel completeChallengeModel)
        {
            var user = await _userService.GetOneByEmail(User.Identity.Name);

            var userChallenge = await _challengeService.GetUserChallengeById(user, id);

            await _challengeService.CompleteChallenge(completeChallengeModel, user, userChallenge);

            return(Ok(new { message = "Desafio finalizado com sucesso." }));
        }
Example #2
0
        public async Task CompleteChallenge(CompleteChallengeModel completeChallengeModel, User user, UserChallenge userChallenge)
        {
            completeChallengeModel.Validate();

            if (userChallenge == null)
            {
                throw new NotFoundException("Desafio não existente.");
            }

            if (userChallenge.Finished)
            {
                throw new BadRequestException("Esse desafio já foi finalizado.");
            }

            var challengesOfDay = await _context.UserChallenges
               .Include(x => x.User)
               .Include(x => x.Challenge)
               .Where(x => x.DayChallenge.Date == DateTime.Now.Date && user.Id == x.User.Id)
               .ToListAsync();

            if (userChallenge.Id != challengesOfDay.LastOrDefault().Id)
            {
                throw new BadRequestException("Esse desafio não é o atual.");
            }

            userChallenge.Completed = completeChallengeModel.Completed;
            userChallenge.Feedback = completeChallengeModel.Feedback;
            userChallenge.Finished = true;

            var countChallenges = await _context.UserChallenges
                .Include(x => x.User)
                .Include(x => x.Challenge)
                .CountAsync(x => x.DayChallenge.Date == DateTime.Now.Date && user.Id == x.User.Id);

            if (countChallenges < CHALLENGES_FOR_DAY)
            {
                var challenge = await GetNextChallenge();
                await _context.UserChallenges.AddAsync(new UserChallenge { User = user, Challenge = challenge, DayChallenge = DateTime.Now });
            }

            await _context.SaveChangesAsync();
        }