feat: Sprint 3 — test editing with versioning
Backend:
- migration 003: add parent_id to tests table
- PUT /api/tests/{id}: edit in place if no attempts, create new version otherwise
- GET /api/tests: show only latest versions (no successor)
Frontend:
- TestForm: extracted reusable form component
- TestCreate: refactored to use TestForm
- TestEdit: full edit mode with pre-populated form, version redirect on new version
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,33 +1,11 @@
|
||||
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Checkbox,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Space,
|
||||
Switch,
|
||||
Typography,
|
||||
message,
|
||||
} from 'antd'
|
||||
import { message } from 'antd'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
|
||||
import { CreateTestDto, testsApi } from '../../api/tests'
|
||||
|
||||
const { Title } = Typography
|
||||
|
||||
// Начальные данные: 7 пустых вопросов с 3 вариантами ответов каждый
|
||||
const EMPTY_ANSWER = { text: '', is_correct: false }
|
||||
const EMPTY_QUESTION = {
|
||||
text: '',
|
||||
answers: [EMPTY_ANSWER, EMPTY_ANSWER, EMPTY_ANSWER],
|
||||
}
|
||||
const INITIAL_QUESTIONS = Array(7).fill(null).map(() => ({ ...EMPTY_QUESTION }))
|
||||
import TestForm, { TestFormValues } from '../../components/TestForm'
|
||||
|
||||
export default function TestCreate() {
|
||||
const [form] = Form.useForm()
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
@@ -44,15 +22,7 @@ export default function TestCreate() {
|
||||
},
|
||||
})
|
||||
|
||||
const onFinish = (values: {
|
||||
title: string
|
||||
description?: string
|
||||
passing_score: number
|
||||
has_timer: boolean
|
||||
time_limit?: number
|
||||
allow_navigation_back: boolean
|
||||
questions: { text: string; answers: { text: string; is_correct: boolean }[] }[]
|
||||
}) => {
|
||||
const onSubmit = (values: TestFormValues) => {
|
||||
createTest({
|
||||
title: values.title,
|
||||
description: values.description,
|
||||
@@ -64,218 +34,12 @@ export default function TestCreate() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 820, margin: '0 auto', padding: 24 }}>
|
||||
<Title level={2}>Создание теста</Title>
|
||||
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onFinish={onFinish}
|
||||
initialValues={{
|
||||
allow_navigation_back: true,
|
||||
has_timer: false,
|
||||
passing_score: 70,
|
||||
questions: INITIAL_QUESTIONS,
|
||||
}}
|
||||
>
|
||||
{/* ── Основные настройки ── */}
|
||||
<Card title="Основные настройки" style={{ marginBottom: 16 }}>
|
||||
<Form.Item
|
||||
name="title"
|
||||
label="Название теста"
|
||||
rules={[{ required: true, message: 'Введите название теста' }]}
|
||||
>
|
||||
<Input placeholder="Например: Пожарная безопасность 2026" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="description" label="Описание (необязательно)">
|
||||
<Input.TextArea rows={2} placeholder="Краткое описание теста" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="passing_score"
|
||||
label="Порог зачёта"
|
||||
rules={[{ required: true, message: 'Укажите порог' }]}
|
||||
>
|
||||
<InputNumber min={0} max={100} addonAfter="%" style={{ width: 140 }} />
|
||||
</Form.Item>
|
||||
|
||||
{/* Таймер: переключатель + поле минут */}
|
||||
<Form.Item label="Ограничение по времени">
|
||||
<Space align="center">
|
||||
<Form.Item name="has_timer" valuePropName="checked" noStyle>
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
noStyle
|
||||
shouldUpdate={(prev, cur) => prev.has_timer !== cur.has_timer}
|
||||
>
|
||||
{({ getFieldValue }) =>
|
||||
getFieldValue('has_timer') ? (
|
||||
<Form.Item
|
||||
name="time_limit"
|
||||
noStyle
|
||||
rules={[{ required: true, message: 'Укажите время' }]}
|
||||
>
|
||||
<InputNumber min={1} addonAfter="мин" style={{ width: 150 }} />
|
||||
</Form.Item>
|
||||
) : (
|
||||
<span style={{ color: '#999' }}>без ограничения</span>
|
||||
)
|
||||
}
|
||||
</Form.Item>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="allow_navigation_back"
|
||||
label="Разрешить возврат к предыдущему вопросу"
|
||||
valuePropName="checked"
|
||||
>
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Card>
|
||||
|
||||
{/* ── Вопросы ── */}
|
||||
<Form.List
|
||||
name="questions"
|
||||
rules={[
|
||||
{
|
||||
validator: async (_, questions) => {
|
||||
if (!questions || questions.length < 7) {
|
||||
return Promise.reject(new Error('Минимум 7 вопросов'))
|
||||
}
|
||||
},
|
||||
},
|
||||
]}
|
||||
>
|
||||
{(questionFields, { add: addQuestion, remove: removeQuestion }, { errors }) => (
|
||||
<>
|
||||
{questionFields.map(({ key, name: qName }, index) => (
|
||||
<Card
|
||||
key={key}
|
||||
title={`Вопрос ${index + 1}`}
|
||||
extra={
|
||||
questionFields.length > 7 ? (
|
||||
<MinusCircleOutlined
|
||||
style={{ color: '#ff4d4f', fontSize: 16 }}
|
||||
onClick={() => removeQuestion(qName)}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<Form.Item
|
||||
name={[qName, 'text']}
|
||||
rules={[{ required: true, message: 'Введите текст вопроса' }]}
|
||||
>
|
||||
<Input.TextArea rows={2} placeholder="Текст вопроса" />
|
||||
</Form.Item>
|
||||
|
||||
{/* ── Варианты ответов ── */}
|
||||
<Form.List
|
||||
name={[qName, 'answers']}
|
||||
rules={[
|
||||
{
|
||||
validator: async (_, answers) => {
|
||||
if (!answers || answers.length < 3) {
|
||||
return Promise.reject(new Error('Минимум 3 варианта ответа'))
|
||||
}
|
||||
if (!answers.some((a: { is_correct: boolean }) => a?.is_correct)) {
|
||||
return Promise.reject(
|
||||
new Error('Отметьте хотя бы один правильный ответ'),
|
||||
)
|
||||
}
|
||||
},
|
||||
},
|
||||
]}
|
||||
>
|
||||
{(
|
||||
answerFields,
|
||||
{ add: addAnswer, remove: removeAnswer },
|
||||
{ errors: answerErrors },
|
||||
) => (
|
||||
<>
|
||||
{answerFields.map(({ key: ak, name: aName }) => (
|
||||
<Space
|
||||
key={ak}
|
||||
style={{ display: 'flex', marginBottom: 8 }}
|
||||
align="start"
|
||||
>
|
||||
{/* Чекбокс «правильный» */}
|
||||
<Form.Item
|
||||
name={[aName, 'is_correct']}
|
||||
valuePropName="checked"
|
||||
initialValue={false}
|
||||
style={{ marginBottom: 0 }}
|
||||
>
|
||||
<Checkbox />
|
||||
</Form.Item>
|
||||
|
||||
{/* Текст ответа */}
|
||||
<Form.Item
|
||||
name={[aName, 'text']}
|
||||
rules={[{ required: true, message: 'Введите вариант ответа' }]}
|
||||
style={{ marginBottom: 0, flex: 1 }}
|
||||
>
|
||||
<Input placeholder="Вариант ответа" style={{ width: 440 }} />
|
||||
</Form.Item>
|
||||
|
||||
{answerFields.length > 3 && (
|
||||
<MinusCircleOutlined
|
||||
style={{ color: '#ff4d4f' }}
|
||||
onClick={() => removeAnswer(aName)}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
))}
|
||||
|
||||
<Form.ErrorList errors={answerErrors} />
|
||||
|
||||
<Button
|
||||
type="dashed"
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => addAnswer({ text: '', is_correct: false })}
|
||||
style={{ marginTop: 4 }}
|
||||
>
|
||||
Добавить вариант
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
<Form.ErrorList errors={errors} />
|
||||
|
||||
<Button
|
||||
type="dashed"
|
||||
block
|
||||
icon={<PlusOutlined />}
|
||||
style={{ marginBottom: 24 }}
|
||||
onClick={() =>
|
||||
addQuestion({
|
||||
text: '',
|
||||
answers: [EMPTY_ANSWER, EMPTY_ANSWER, EMPTY_ANSWER],
|
||||
})
|
||||
}
|
||||
>
|
||||
Добавить вопрос
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
|
||||
<Form.Item>
|
||||
<Space>
|
||||
<Button type="primary" htmlType="submit" loading={isPending}>
|
||||
Создать тест
|
||||
</Button>
|
||||
<Button onClick={() => navigate('/')}>Отмена</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</div>
|
||||
<TestForm
|
||||
heading="Создание теста"
|
||||
onSubmit={onSubmit}
|
||||
isPending={isPending}
|
||||
submitLabel="Создать тест"
|
||||
onCancel={() => navigate('/')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,29 +5,91 @@ import {
|
||||
EditOutlined,
|
||||
PlayCircleOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Alert, Button, Card, Descriptions, List, Space, Spin, Tag, Typography } from 'antd'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Alert, Button, Card, Descriptions, List, Space, Spin, Tag, Typography, message } from 'antd'
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
|
||||
import { Answer, testsApi } from '../../api/tests'
|
||||
import { Answer, CreateTestDto, testsApi } from '../../api/tests'
|
||||
import TestForm, { TestFormValues } from '../../components/TestForm'
|
||||
|
||||
const { Title, Text } = Typography
|
||||
|
||||
export default function TestEdit() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const [editMode, setEditMode] = useState(false)
|
||||
|
||||
const { data: test, isLoading } = useQuery({
|
||||
queryKey: ['tests', id],
|
||||
queryFn: () => testsApi.get(Number(id)).then((r) => r.data),
|
||||
})
|
||||
|
||||
const { mutate: updateTest, isPending } = useMutation({
|
||||
mutationFn: (data: CreateTestDto) => testsApi.update(Number(id), data).then((r) => r.data),
|
||||
onSuccess: (result) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tests'] })
|
||||
if (result.is_new_version) {
|
||||
message.success(`Создана новая версия теста (v${result.test.version})`)
|
||||
navigate(`/tests/${result.test.id}/edit`)
|
||||
} else {
|
||||
message.success('Тест обновлён')
|
||||
queryClient.invalidateQueries({ queryKey: ['tests', id] })
|
||||
setEditMode(false)
|
||||
}
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
const err = error as { response?: { data?: { detail?: string } } }
|
||||
message.error(err.response?.data?.detail || 'Ошибка при сохранении теста')
|
||||
},
|
||||
})
|
||||
|
||||
if (isLoading) {
|
||||
return <Spin size="large" style={{ display: 'block', margin: '48px auto' }} />
|
||||
}
|
||||
|
||||
if (!test) return null
|
||||
|
||||
// Режим редактирования — показываем форму с предзаполненными данными
|
||||
if (editMode) {
|
||||
const initialValues: TestFormValues = {
|
||||
title: test.title,
|
||||
description: test.description ?? undefined,
|
||||
passing_score: test.passing_score,
|
||||
has_timer: test.time_limit !== null,
|
||||
time_limit: test.time_limit ?? undefined,
|
||||
allow_navigation_back: test.allow_navigation_back,
|
||||
questions: test.questions.map((q) => ({
|
||||
text: q.text,
|
||||
answers: q.answers.map((a) => ({ text: a.text, is_correct: a.is_correct })),
|
||||
})),
|
||||
}
|
||||
|
||||
const onSubmit = (values: TestFormValues) => {
|
||||
updateTest({
|
||||
title: values.title,
|
||||
description: values.description,
|
||||
passing_score: values.passing_score,
|
||||
time_limit: values.has_timer ? values.time_limit : undefined,
|
||||
allow_navigation_back: values.allow_navigation_back ?? true,
|
||||
questions: values.questions,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<TestForm
|
||||
heading={`Редактирование теста — v${test.version}`}
|
||||
initialValues={initialValues}
|
||||
onSubmit={onSubmit}
|
||||
isPending={isPending}
|
||||
submitLabel="Сохранить"
|
||||
onCancel={() => setEditMode(false)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Режим просмотра (вид автора)
|
||||
return (
|
||||
<div style={{ maxWidth: 820, margin: '0 auto', padding: 24 }}>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||
@@ -37,8 +99,7 @@ export default function TestEdit() {
|
||||
<Space>
|
||||
<Button
|
||||
icon={<EditOutlined />}
|
||||
disabled
|
||||
title="Редактирование будет доступно в следующем спринте"
|
||||
onClick={() => setEditMode(true)}
|
||||
>
|
||||
Редактировать
|
||||
</Button>
|
||||
|
||||
Reference in New Issue
Block a user