public IActionResult AddNewScore([FromBody] NewScoreData data)
 {
     try
     {
         var userData = jwtService.ParseData(this.User);
         questionService.AddNewScore(data, userData.UserId);
         return(Ok());
     }
     catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }
Exemple #2
0
        public void AddNewScore(NewScoreData data, int userId)
        {
            var score      = data.Score;
            var questionId = data.QuestionId;

            if (score < 1 || score > 10)
            {
                throw new ServiceException("Score must be between 1 and 10!");
            }

            var user = context.Users.SingleOrDefault(x => x.Id == userId);

            if (user == null)
            {
                throw new ServiceException("User not found!");
            }

            var question = context.PersonalQuestionPackages.SingleOrDefault(x => x.Id == questionId);

            if (question == null)
            {
                throw new ServiceException("Question not found!");
            }

            var parentSheetUserId = context.QuestionSheets.SingleOrDefault(x => x.Id == question.QuestionSheetId)?.UserId;

            if (parentSheetUserId == null)
            {
                throw new ServiceException("Parent Sheet Not Found!");
            }

            if (parentSheetUserId != user.Id)
            {
                throw new ServiceException("Question does not beling to you!");
            }

            var scoresString = question.LatestScores;

            if (scoresString == null || scoresString.Split(",", StringSplitOptions.RemoveEmptyEntries).Length == 0)
            {
                question.LatestScores = score.ToString();
                question.AnswerRate   = score;
            }
            else
            {
                var scores = scoresString.Split(",", StringSplitOptions.RemoveEmptyEntries).ToList();

                if (scores.Count >= numberOfStoredScores)
                {
                    scores.RemoveAt(0);
                }
                scores.Add(score.ToString());
                question.LatestScores = string.Join(",", scores);

                question.AnswerRate = CalculateWaightedAvarage(scores.ToArray());
            }

            question.TimesBeingAnswered++;

            context.SaveChanges();
        }