Skip to content

Commit 0ea7a3a

Browse files
committed
QAGDEV-723 - [FE] Прикрепления тестов к заданиям v4
1 parent 3800d22 commit 0ea7a3a

File tree

4 files changed

+106
-38
lines changed

4 files changed

+106
-38
lines changed

src/features/admin-panel/tests-admin/components/create-test-form.tsx

Lines changed: 47 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@ import {
2323
QuestionAnswer as QuestionIcon,
2424
} from "@mui/icons-material";
2525

26-
import { TestGroupDto } from "api/graphql/generated/graphql";
26+
import {
27+
TestGroupDto,
28+
useTestAnswerByQuestionLazyQuery,
29+
} from "api/graphql/generated/graphql";
2730

2831
import { QuestionForm } from "../types";
2932

@@ -51,33 +54,56 @@ const CreateTestForm: FC<CreateTestFormProps> = ({
5154
false
5255
);
5356

57+
const [getTestAnswers] = useTestAnswerByQuestionLazyQuery();
58+
5459
// Загружаем данные существующего теста для редактирования
5560
useEffect(() => {
5661
if (existingTest) {
5762
setTestName(existingTest.testName || "");
5863
setSuccessThreshold(existingTest.successThreshold || 70);
5964

60-
const loadedQuestions: QuestionForm[] =
61-
existingTest.testQuestions?.map((q, index) => ({
62-
id: q?.id || "",
63-
text: q?.text || "",
64-
answers: q?.testAnswers?.map((a) => ({
65-
id: a?.id || "",
66-
text: a?.text || "",
67-
correct: false, // В схеме нет поля correct для TestAnswerShortDto, будем получать отдельно
68-
})) || [
69-
{ text: "", correct: true },
70-
{ text: "", correct: false },
71-
],
72-
})) || [];
73-
74-
setQuestions(loadedQuestions);
75-
// Открываем первый вопрос по умолчанию
76-
if (loadedQuestions.length > 0) {
77-
setExpandedQuestion(`question-0`);
78-
}
65+
// Загружаем вопросы и ответы с правильностью
66+
const loadQuestionsWithAnswers = async () => {
67+
const loadedQuestions: QuestionForm[] = [];
68+
69+
for (const question of existingTest.testQuestions || []) {
70+
if (!question?.id) continue;
71+
72+
// Получаем полную информацию об ответах для каждого вопроса
73+
const { data: answersData } = await getTestAnswers({
74+
variables: { questionId: question.id },
75+
});
76+
77+
const answers =
78+
answersData?.testAnswerByQuestion?.map((a) => ({
79+
id: a?.id || "",
80+
text: a?.text || "",
81+
correct: a?.correct || false,
82+
})) || [];
83+
84+
loadedQuestions.push({
85+
id: question.id,
86+
text: question.text || "",
87+
answers:
88+
answers.length > 0
89+
? answers
90+
: [
91+
{ text: "", correct: true },
92+
{ text: "", correct: false },
93+
],
94+
});
95+
}
96+
97+
setQuestions(loadedQuestions);
98+
// Открываем первый вопрос по умолчанию
99+
if (loadedQuestions.length > 0) {
100+
setExpandedQuestion(`question-0`);
101+
}
102+
};
103+
104+
loadQuestionsWithAnswers();
79105
}
80-
}, [existingTest]);
106+
}, [existingTest, getTestAnswers]);
81107

82108
const addQuestion = () => {
83109
const newQuestionIndex = questions.length;

src/features/admin-panel/tests-admin/create-test-form.tsx

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import {
2626
useUpdateTestQuestionMutation,
2727
useUpdateTestAnswerMutation,
2828
TestGroupInput,
29-
TestQuestionInput,
29+
useTestAnswerByQuestionLazyQuery,
3030
} from "api/graphql/generated/graphql";
3131

3232
import { QuestionForm } from "./types";
@@ -56,6 +56,7 @@ const CreateTestForm: FC<CreateTestFormProps> = ({
5656
useUpdateTestGroupMutation();
5757
const [updateTestQuestion] = useUpdateTestQuestionMutation();
5858
const [updateTestAnswer] = useUpdateTestAnswerMutation();
59+
const [getTestAnswers] = useTestAnswerByQuestionLazyQuery();
5960

6061
// Загружаем данные существующего теста для редактирования
6162
useEffect(() => {
@@ -64,21 +65,38 @@ const CreateTestForm: FC<CreateTestFormProps> = ({
6465
setTestName(test.testName || "");
6566
setSuccessThreshold(test.successThreshold || 70);
6667

67-
const loadedQuestions: QuestionForm[] =
68-
test.testQuestions?.map((q) => ({
69-
id: q?.id || "",
70-
text: q?.text || "",
71-
answers:
72-
q?.testAnswers?.map((a) => ({
68+
// Загружаем вопросы и ответы с правильностью
69+
const loadQuestionsWithAnswers = async () => {
70+
const loadedQuestions: QuestionForm[] = [];
71+
72+
for (const question of test.testQuestions || []) {
73+
if (!question?.id) continue;
74+
75+
// Получаем полную информацию об ответах для каждого вопроса
76+
const { data: answersData } = await getTestAnswers({
77+
variables: { questionId: question.id },
78+
});
79+
80+
const answers =
81+
answersData?.testAnswerByQuestion?.map((a) => ({
7382
id: a?.id || "",
7483
text: a?.text || "",
75-
correct: false, // В схеме нет поля correct для TestAnswerShortDto
76-
})) || [],
77-
})) || [];
84+
correct: a?.correct || false,
85+
})) || [];
86+
87+
loadedQuestions.push({
88+
id: question.id,
89+
text: question.text || "",
90+
answers: answers.length > 0 ? answers : [],
91+
});
92+
}
93+
94+
setQuestions(loadedQuestions);
95+
};
7896

79-
setQuestions(loadedQuestions);
97+
loadQuestionsWithAnswers();
8098
}
81-
}, [existingTestData]);
99+
}, [existingTestData, getTestAnswers]);
82100

83101
const addQuestion = () => {
84102
setQuestions([
@@ -187,7 +205,7 @@ const CreateTestForm: FC<CreateTestFormProps> = ({
187205

188206
try {
189207
// Сначала сохраняем вопросы и ответы
190-
const savedQuestions: TestQuestionInput[] = [];
208+
const savedQuestions: { id: string }[] = [];
191209

192210
for (const question of questions) {
193211
// Сохраняем вопрос

src/features/test/containers/test-container.tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,16 @@ const TestContainer: FC<TestContainerProps> = ({
151151
}
152152
});
153153

154+
const scorePercentage = (correctAnswers / testQuestions.length) * 100;
155+
156+
console.log("🔍 Test Result Debug:", {
157+
correctAnswers,
158+
totalQuestions: testQuestions.length,
159+
scorePercentage: scorePercentage.toFixed(1) + "%",
160+
userAnswers: userAnswers.length,
161+
allLoadedAnswers: allLoadedAnswers.length,
162+
});
163+
154164
setScore(correctAnswers);
155165
setIsCompleted(true);
156166
};

src/features/test/views/test-view.tsx

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,17 @@ const TestView: FC<TestViewProps> = ({
8181

8282
const successThreshold = testData.successThreshold ?? 0;
8383
const progress = ((currentQuestionIndex + 1) / totalQuestions) * 100;
84-
const isPassed = score >= successThreshold;
84+
const scorePercentage = (score / totalQuestions) * 100;
85+
const isPassed = scorePercentage >= successThreshold;
86+
87+
// Отладочная информация
88+
console.log("🔍 TestView Debug:", {
89+
score,
90+
totalQuestions,
91+
successThreshold,
92+
scorePercentage: scorePercentage.toFixed(1) + "%",
93+
isPassed,
94+
});
8595

8696
if (isCompleted) {
8797
return (
@@ -94,15 +104,19 @@ const TestView: FC<TestViewProps> = ({
94104

95105
<Alert severity={isPassed ? "success" : "error"} sx={{ mb: 2 }}>
96106
{isPassed
97-
? `Поздравляем! Вы прошли тест с результатом ${score}/${totalQuestions}`
98-
: `Тест не пройден. Результат: ${score}/${totalQuestions}. Требуется: ${successThreshold}`}
107+
? `Поздравляем! Вы прошли тест с результатом ${scorePercentage.toFixed(
108+
0
109+
)}% (${score}/${totalQuestions})`
110+
: `Тест не пройден. Результат: ${scorePercentage.toFixed(
111+
0
112+
)}% (${score}/${totalQuestions}). Требуется: ${successThreshold}%`}
99113
</Alert>
100114

101115
<Typography variant="body1">
102116
Правильных ответов: {score} из {totalQuestions}
103117
</Typography>
104118
<Typography variant="body2" color="text.secondary">
105-
Проходной балл: {successThreshold}
119+
Проходной балл: {successThreshold}%
106120
</Typography>
107121

108122
{trainingId && lectureId && (

0 commit comments

Comments
 (0)