private async Task <List <int> > CreateUserAnswersAndGetQuestionIdsSortedByStageAsync(int testId, int userId) { var questionIds = new List <int>(); int stagesCount = (await _questionManager.GetTestStagesByTestIdAsync(testId)).ToList().Count; for (int stage = 1; stage <= stagesCount; stage++) { int questionId = (await _questionManager.GetRandomQuestionInTestByStageAsync(testId, stage)).Id; List <DomainAnswer> answers = (await _answersManager.GetAnswersByQuestionIdAsync(questionId)).ToList(); foreach (DomainAnswer answer in answers) { var userAnswer = new DomainUserAnswer { isValid = false, Text = string.Empty, UserId = userId, AnswerId = answer.Id }; if (!await _answersManager.IsUserAnswerExistsAsync(userId, answer.Id)) { await _answersManager.CreateUserAnswerAsync(userAnswer); } } questionIds.Add(questionId); } return(questionIds); }
private async Task FinishTest(int userId, int testId) { if ((await _testManager.GetUserTestAsync(userId, testId)).Status == TestStatus.Finished) { return; } await _testManager.UpdateUserTestStatusAsync(userId, testId, TestStatus.Finished); List <DomainQuestion> questions = (await _questionManager.GetUserQuestionsByTestIdSortedByStageAsync(userId, testId)).ToList(); int points = 0; foreach (var question in questions) { if (question.QuestionType == QuestionTypes.Option) { var correctAnswerIds = (await _answersManager.GetAnswersByQuestionIdAsync(question.Id)) .Where(x => x.IsValid == true) .Select(x => x.Id) .ToHashSet(); var userSelectedAnswerIds = (await _answersManager.GetUserAnswersByQuestionIdAsync(userId, question.Id)) .Where(x => x.isValid == true) .Select(x => x.AnswerId) .ToHashSet(); if (correctAnswerIds.SetEquals(userSelectedAnswerIds)) { points += question.Points; } } else if (question.QuestionType == QuestionTypes.Text) { DomainAnswer answer = (await _answersManager.GetAnswersByQuestionIdAsync(question.Id)).Single(); DomainUserAnswer userAnswer = (await _answersManager.GetUserAnswersByQuestionIdAsync(userId, question.Id)) .Single(); if (answer.Text == userAnswer.Text) { points += question.Points; } } } await _testManager.UpdateUserTestPointsAsync(userId, testId, points); }