feat: Sprint 1 — infrastructure + test creation

Backend:
- FastAPI + SQLAlchemy 2.0 async + Alembic
- Models: Test, Question, Answer
- API: GET /api/tests, GET /api/tests/{id}, POST /api/tests
- Pydantic validation: min 7 questions, min 3 answers, ≥1 correct

Frontend:
- React 18 + TypeScript + Vite + Ant Design + TanStack Query
- Pages: TestList, TestCreate (nested Form.List), TestDetail

Infrastructure:
- Docker Compose: db (postgres:16), backend, frontend, nginx
- Nginx: /api/ → FastAPI, / → Vite dev server with HMR
- Alembic migration 001_init: tests, questions, answers tables
- entrypoint.sh: wait for db, migrate, start uvicorn

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Aleksey Razorvin
2026-03-21 12:05:04 +05:00
parent 054376bca7
commit 8b17c5d3c4
35 changed files with 1370 additions and 0 deletions
+281
View File
@@ -0,0 +1,281 @@
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 { 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 }))
export default function TestCreate() {
const [form] = Form.useForm()
const navigate = useNavigate()
const queryClient = useQueryClient()
const { mutate: createTest, isPending } = useMutation({
mutationFn: (data: CreateTestDto) => testsApi.create(data).then((r) => r.data),
onSuccess: (test) => {
queryClient.invalidateQueries({ queryKey: ['tests'] })
message.success('Тест успешно создан')
navigate(`/tests/${test.id}`)
},
onError: (error: unknown) => {
const err = error as { response?: { data?: { detail?: string } } }
message.error(err.response?.data?.detail || 'Ошибка при создании теста')
},
})
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 }[] }[]
}) => {
createTest({
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 (
<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>
)
}
+89
View File
@@ -0,0 +1,89 @@
import { ArrowLeftOutlined, CheckCircleTwoTone, CloseCircleTwoTone } from '@ant-design/icons'
import { useQuery } from '@tanstack/react-query'
import { Button, Card, Descriptions, List, Space, Spin, Tag, Typography } from 'antd'
import { useNavigate, useParams } from 'react-router-dom'
import { Answer, testsApi } from '../../api/tests'
const { Title, Text } = Typography
export default function TestDetail() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { data: test, isLoading } = useQuery({
queryKey: ['tests', id],
queryFn: () => testsApi.get(Number(id)).then((r) => r.data),
})
if (isLoading) {
return <Spin size="large" style={{ display: 'block', margin: '48px auto' }} />
}
if (!test) return null
return (
<div style={{ maxWidth: 820, margin: '0 auto', padding: 24 }}>
<Space style={{ marginBottom: 16 }}>
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/')}>
К списку тестов
</Button>
</Space>
<Title level={2}>{test.title}</Title>
{test.description && (
<Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
{test.description}
</Text>
)}
<Card style={{ marginBottom: 24 }}>
<Descriptions column={3}>
<Descriptions.Item label="Вопросов">{test.questions.length}</Descriptions.Item>
<Descriptions.Item label="Порог зачёта">{test.passing_score}%</Descriptions.Item>
<Descriptions.Item label="Таймер">
{test.time_limit ? `${test.time_limit} мин` : 'Без ограничений'}
</Descriptions.Item>
<Descriptions.Item label="Возврат к вопросу">
{test.allow_navigation_back ? (
<Tag color="green">Разрешён</Tag>
) : (
<Tag color="red">Запрещён</Tag>
)}
</Descriptions.Item>
<Descriptions.Item label="Версия">{test.version}</Descriptions.Item>
<Descriptions.Item label="Создан">
{new Date(test.created_at).toLocaleDateString('ru-RU')}
</Descriptions.Item>
</Descriptions>
</Card>
<Title level={3}>Вопросы ({test.questions.length})</Title>
{test.questions.map((question, index) => (
<Card key={question.id} style={{ marginBottom: 12 }}>
<Text strong>
{index + 1}. {question.text}
</Text>
<List
style={{ marginTop: 10 }}
dataSource={question.answers}
renderItem={(answer: Answer) => (
<List.Item style={{ padding: '4px 0' }}>
<Space>
{answer.is_correct ? (
<CheckCircleTwoTone twoToneColor="#52c41a" />
) : (
<CloseCircleTwoTone twoToneColor="#d9d9d9" />
)}
<Text>{answer.text}</Text>
</Space>
</List.Item>
)}
/>
</Card>
))}
</div>
)
}
+98
View File
@@ -0,0 +1,98 @@
import { PlusOutlined } from '@ant-design/icons'
import { useQuery } from '@tanstack/react-query'
import { Button, Space, Spin, Table, Tag, Typography } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { useNavigate } from 'react-router-dom'
import { TestListItem, testsApi } from '../../api/tests'
const { Title } = Typography
export default function TestList() {
const navigate = useNavigate()
const { data: tests = [], isLoading } = useQuery({
queryKey: ['tests'],
queryFn: () => testsApi.list().then((r) => r.data),
})
const columns: ColumnsType<TestListItem> = [
{
title: 'Название',
dataIndex: 'title',
key: 'title',
render: (text: string, record: TestListItem) => (
<a onClick={() => navigate(`/tests/${record.id}`)}>{text}</a>
),
},
{
title: 'Вопросов',
dataIndex: 'questions_count',
key: 'questions_count',
width: 100,
align: 'center',
},
{
title: 'Порог зачёта',
dataIndex: 'passing_score',
key: 'passing_score',
width: 130,
align: 'center',
render: (score: number) => `${score}%`,
},
{
title: 'Таймер',
dataIndex: 'time_limit',
key: 'time_limit',
width: 110,
align: 'center',
render: (limit: number | null) => (limit ? `${limit} мин` : '—'),
},
{
title: 'Создан',
dataIndex: 'created_at',
key: 'created_at',
width: 130,
render: (date: string) => new Date(date).toLocaleDateString('ru-RU'),
},
{
title: '',
key: 'actions',
width: 90,
render: (_: unknown, record: TestListItem) => (
<Button size="small" onClick={() => navigate(`/tests/${record.id}`)}>
Открыть
</Button>
),
},
]
if (isLoading) {
return <Spin size="large" style={{ display: 'block', margin: '48px auto' }} />
}
return (
<div style={{ maxWidth: 1000, margin: '0 auto', padding: 24 }}>
<Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: 16 }}>
<Title level={2} style={{ margin: 0 }}>
Тесты
</Title>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => navigate('/tests/create')}
>
Создать тест
</Button>
</Space>
<Table
dataSource={tests}
columns={columns}
rowKey="id"
locale={{ emptyText: 'Тестов пока нет. Создайте первый!' }}
pagination={{ pageSize: 20 }}
/>
</div>
)
}