From dae8489f93274f508360822ca2c7e19faa30f442 Mon Sep 17 00:00:00 2001 From: Grisha Lavrov Date: Fri, 4 Dec 2026 18:34:59 +0100 Subject: [PATCH] company page: progress by level and difficulty, filters and sort in URL, last interview, quick starts, Bit line - hero: segmented progress bar (passed / partial / failed / not started), clickable legend filters the table, passed per difficulty - quick starts: weak questions (failed first), up to 10 unpassed, or all when everything is passed; confirm before replacing an unfinished interview - last interview card from localStorage: continue from the first open question or open the results - table: status, category, sort filters (FilterBar drawer on mobile), state in URL, favorite star, AI score from the last interview - Bit comments the company progress once on open --- .../src/pages/CompanyQuestionsPage.test.tsx | 37 -- frontend/src/pages/CompanyQuestionsPage.tsx | 167 ------ .../CompanyQuestionsPage/CompanyHero.tsx | 313 ++++++++++++ .../CompanyQuestionsPage.test.tsx | 122 +++++ .../LastInterviewCard.tsx | 133 +++++ .../CompanyQuestionsPage/QuestionTable.tsx | 155 ++++++ .../CompanyQuestionsPage/companyView.test.ts | 152 ++++++ .../pages/CompanyQuestionsPage/companyView.ts | 254 +++++++++ .../src/pages/CompanyQuestionsPage/index.tsx | 482 ++++++++++++++++++ 9 files changed, 1611 insertions(+), 204 deletions(-) delete mode 100644 frontend/src/pages/CompanyQuestionsPage.test.tsx delete mode 100644 frontend/src/pages/CompanyQuestionsPage.tsx create mode 100644 frontend/src/pages/CompanyQuestionsPage/CompanyHero.tsx create mode 100644 frontend/src/pages/CompanyQuestionsPage/CompanyQuestionsPage.test.tsx create mode 100644 frontend/src/pages/CompanyQuestionsPage/LastInterviewCard.tsx create mode 100644 frontend/src/pages/CompanyQuestionsPage/QuestionTable.tsx create mode 100644 frontend/src/pages/CompanyQuestionsPage/companyView.test.ts create mode 100644 frontend/src/pages/CompanyQuestionsPage/companyView.ts create mode 100644 frontend/src/pages/CompanyQuestionsPage/index.tsx diff --git a/frontend/src/pages/CompanyQuestionsPage.test.tsx b/frontend/src/pages/CompanyQuestionsPage.test.tsx deleted file mode 100644 index c12612d..0000000 --- a/frontend/src/pages/CompanyQuestionsPage.test.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { http, HttpResponse } from 'msw'; -import { setupServer } from 'msw/node'; -import { screen } from '@testing-library/react'; -import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; -import { renderRoutes } from '../test/renderRoutes'; - -const BASE = 'http://localhost:8888/api/v1'; -const server = setupServer(); -beforeAll(() => server.listen()); -afterEach(() => server.resetHandlers()); -afterAll(() => server.close()); - -const user = { id: 'u1', email: 'a@b.c', first_name: 'A', last_name: 'B', is_admin: false, is_active: true }; -const q = (id: string, title: string) => ({ id, title, slug: id, difficulty: 'easy', category_id: 'c1', category: { id: 'c1', name: 'Python' } }); - -describe('CompanyQuestionsPage', () => { - it('loads company questions in one request and takes completion from /me/progress', async () => { - const urls: string[] = []; - server.use( - http.get(`${BASE}/auth/me`, () => HttpResponse.json(user)), - http.get(`${BASE}/me/progress`, () => HttpResponse.json({ completed_ids: ['a'], favorite_ids: [] })), - http.get(`${BASE}/companies/co1`, () => HttpResponse.json({ id: 'co1', name: 'Acme', slug: 'acme', description: 'd', is_active: true })), - http.get(`${BASE}/companies/co1/questions`, ({ request }) => { - urls.push(request.url); - return HttpResponse.json({ items: [q('a', 'Первый'), q('b', 'Второй')], total: 2 }); - }), - http.get(`${BASE}/*`, ({ request }) => { urls.push(request.url); return HttpResponse.json({ items: [], total: 0 }); }), - ); - renderRoutes('/companies/co1/questions'); - expect(await screen.findByText('Первый')).toBeInTheDocument(); - expect(await screen.findByText('1 из 2')).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Степень знания: Прошёл. Изменить' })).toBeInTheDocument(); - expect(urls.filter((u) => u.includes('is-completed'))).toEqual([]); - expect(urls.filter((u) => u.includes('limit=1000'))).toEqual([]); - expect(urls.filter((u) => u.includes('/companies/co1/questions'))).toHaveLength(1); - }); -}); diff --git a/frontend/src/pages/CompanyQuestionsPage.tsx b/frontend/src/pages/CompanyQuestionsPage.tsx deleted file mode 100644 index 678d800..0000000 --- a/frontend/src/pages/CompanyQuestionsPage.tsx +++ /dev/null @@ -1,167 +0,0 @@ -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; -import { Alert, Box, Button, Container, FormControl, IconButton, InputLabel, LinearProgress, MenuItem, Select, Skeleton, Stack, Typography } from '@mui/material'; -import { - PlayArrowRounded as PlayArrowIcon, - QuizOutlined as QuizIcon, - SearchOff as SearchOffIcon, - BusinessOutlined as BusinessIcon, - ChevronLeft, ChevronRight, -} from '@mui/icons-material'; -import { isAxiosError } from 'axios'; -import { Link as RouterLink, useNavigate, useParams } from 'react-router-dom'; -import { EmptyState, PageHeader, SearchInput } from '../components/ui'; -import { useCompany, useCompanyQuestions } from '../queries/companies'; -import { useProgress, useSetMastery } from '../queries/progress'; -import { MasteryIconButton } from '../components/ui/Mastery'; -import type { MasteryLevel } from '../types'; -import { useTokens, wideFrame } from '../theme/tokens'; -import { getDifficultyColors, getDifficultyLabel } from '../utils/difficulty'; -import type { Question } from '../types'; -import { CompanyLogo } from './CompaniesPage/CompanyLogo'; - -const NO_QUESTIONS: Question[] = []; - -export const CompanyQuestionsPage = () => { - const navigate = useNavigate(); - const { companyId } = useParams<{ companyId: string }>(); - const { c, mode } = useTokens(); - - const companyQuery = useCompany(companyId); - const questionsQuery = useCompanyQuestions(companyId); - const progress = useProgress(); - const setMastery = useSetMastery(); - const [pendingIds, setPendingIds] = useState>({}); - const [completionError, setCompletionError] = useState(false); - const [search, setSearch] = useState(''); - const [difficulty, setDifficulty] = useState(''); - const [page, setPage] = useState(1); - const listRef = useRef(null); - const [reservedListHeight, setReservedListHeight] = useState(0); - const [debouncedSearch, setDebouncedSearch] = useState(''); - - const isLoading = companyQuery.isPending || questionsQuery.isPending; - const loadError = companyQuery.isError || questionsQuery.isError; - const notFound = isAxiosError(companyQuery.error) && companyQuery.error.response?.status === 404; - const statusesError = progress.isError; - - useEffect(() => { - const timer = setTimeout(() => setDebouncedSearch(search), 300); - return () => clearTimeout(timer); - }, [search]); - - const company = companyQuery.data ?? null; - const questions = questionsQuery.data?.items ?? NO_QUESTIONS; - const completed = progress.completed; - - const filteredQuestions = useMemo(() => { - const query = debouncedSearch.trim().toLowerCase(); - return questions.filter((q) => (!query || q.title.toLowerCase().includes(query)) && (!difficulty || q.difficulty?.toLowerCase() === difficulty)); - }, [questions, debouncedSearch, difficulty]); - - const pageSize = 6; - const pageCount = Math.max(1, Math.ceil(filteredQuestions.length / pageSize)); - const visiblePage = Math.min(page, pageCount); - const start = (visiblePage - 1) * pageSize; - const visibleQuestions = filteredQuestions.slice(start, start + pageSize); - useLayoutEffect(() => { - if (!isLoading && filteredQuestions.length && listRef.current) { - const height = Math.ceil(listRef.current.scrollHeight); - setReservedListHeight(previous => Math.max(previous, height)); - } - }, [isLoading, visiblePage, filteredQuestions, reservedListHeight]); - - useEffect(() => { - const resetHeight = () => setReservedListHeight(0); - window.addEventListener('resize', resetHeight); - return () => window.removeEventListener('resize', resetHeight); - }, []); - - const categoryIds = new Set(questions.map(question => question.category_id).filter(Boolean)); - const commonCategory = categoryIds.size === 1 ? questions.find(question => question.category?.name)?.category?.name : undefined; - const completedCount = questions.filter((q) => completed.has(q.id)).length; - const completionPercent = questions.length > 0 ? Math.round((completedCount / questions.length) * 100) : 0; - - const handleStartInterview = () => { - navigate(`/companies/${companyId}/interview/setup`); - }; - - const handleSetLevel = async (questionId: string, level: MasteryLevel | null) => { - setPendingIds((prev) => ({ ...prev, [questionId]: true })); - try { - await setMastery.mutateAsync({ id: questionId, level }); - setCompletionError(false); - } catch (err) { - console.error('Failed to set mastery:', err); - setCompletionError(true); - } finally { - setPendingIds((prev) => { - const next = { ...prev }; - delete next[questionId]; - return next; - }); - } - }; - - if (isLoading && !loadError) { - return ( - - - - - - - ); - } - - if (loadError || !company) { - return ( - - - } - title={!notFound ? 'Не удалось загрузить компанию' : 'Компания не найдена'} - description={!notFound ? 'Обновите страницу или попробуйте позже.' : 'Возможно, она была удалена или ссылка устарела.'} - action={ - - } - /> - - ); - } - - return ( - - - {(statusesError || completionError) && Не удалось загрузить или сохранить статус прохождения. Обновите страницу и попробуйте снова.} - - - - {company.name}{company.description} - - - Прогресс{completedCount} из {questions.length} - - - - - Вопросы{commonCategory && {commonCategory}} - - {questions.length > 0 && :first-of-type': { flex: 1, maxWidth: 360, minWidth: 0 } }}> { setSearch(value); setPage(1); }} placeholder="Поиск по вопросам" />Сложность} - ВопросСложностьСтатус - - {questions.length === 0 ? } title="Нет доступных вопросов" description="Для этой компании вопросы пока не добавлены." /> : filteredQuestions.length === 0 ? } title="Вопросы не найдены" description="Попробуйте изменить запрос." /> : visibleQuestions.map((question) => { - const color = getDifficultyColors(question.difficulty, mode).fg; - return - {question.title}{!commonCategory && question.category?.name && {question.category.name}} - {getDifficultyLabel(question.difficulty)} - void handleSetLevel(question.id, next)} /> - ; - })} - - {questions.length > 0 && {filteredQuestions.length ? `${start + 1}–${Math.min(start + pageSize, filteredQuestions.length)} из ${filteredQuestions.length}` : '0 вопросов'} setPage(visiblePage - 1)}>= pageCount} onClick={() => setPage(visiblePage + 1)}>} - - - ); -}; diff --git a/frontend/src/pages/CompanyQuestionsPage/CompanyHero.tsx b/frontend/src/pages/CompanyQuestionsPage/CompanyHero.tsx new file mode 100644 index 0000000..d9c0613 --- /dev/null +++ b/frontend/src/pages/CompanyQuestionsPage/CompanyHero.tsx @@ -0,0 +1,313 @@ +import { Box, Button, ButtonBase, LinearProgress, Stack, Tooltip, Typography } from '@mui/material'; +import { + PlayArrowRounded as PlayArrowIcon, + ReplayRounded as ReplayIcon, + PlaylistPlayRounded as NewIcon, + ShuffleRounded as ShuffleIcon, +} from '@mui/icons-material'; +import { MasteryIcon } from '../../components/ui/Mastery'; +import { useMasteryColor } from '../../components/ui/masteryLevels'; +import { radius, useTokens } from '../../theme/tokens'; +import { getDifficultyColors } from '../../utils/difficulty'; +import type { Company } from '../../types'; +import { CompanyLogo } from '../CompaniesPage/CompanyLogo'; +import { STATUS_LABEL, type CompanyStatus, type LevelCounts } from './companyView'; + +const DIFFICULTY_PLURAL: Record = { + easy: 'Лёгкие', + medium: 'Средние', + hard: 'Сложные', +}; +const LEVELS = ['passed', 'partial', 'failed', 'new'] as const; + +interface CompanyHeroProps { + company: Company; + counts: LevelCounts; + byDifficulty: { difficulty: string; total: number; passed: number }[]; + /** Прогресс ещё не загружен или не загрузился: разбивку и быстрые старты не показываем. */ + progressReady: boolean; + status: CompanyStatus; + onStatus: (status: CompanyStatus) => void; + onStart: () => void; + onQuick: (kind: 'weak' | 'unpassed' | 'all') => void; + startDisabled: boolean; +} + +/** Шапка компании: описание, разбивка прогресса по уровням и сложности, старт собеседования. */ +export const CompanyHero = ({ + company, + counts, + byDifficulty, + progressReady, + status, + onStatus, + onStart, + onQuick, + startDisabled, +}: CompanyHeroProps) => { + const { c, mode } = useTokens(); + const color = useMasteryColor(); + const { total, passed, partial, failed } = counts; + const weak = partial + failed; + const unpassed = total - passed; + const percent = total ? Math.round((passed / total) * 100) : 0; + const levelColor = (level: (typeof LEVELS)[number]) => + level === 'new' ? c.textSubtle : color(level).fg; + + return ( + + + + + + + {company.name} + + {company.description && ( + + {company.description} + + )} + + + {progressReady && byDifficulty.length > 0 && ( + + {byDifficulty.map((d) => { + const fg = getDifficultyColors(d.difficulty, mode).fg; + const ratio = d.total ? d.passed / d.total : 0; + return ( + + + + {DIFFICULTY_PLURAL[d.difficulty]} + + + {d.passed}/{d.total} + + + + + + + ); + })} + + )} + + + + + + Прогресс + + + {passed} из {total} + {total > 0 && ( + + {' '} + · {percent}% + + )} + + + {progressReady && total > 0 ? ( + <> + + {(['passed', 'partial', 'failed'] as const).map((level) => + counts[level] ? ( + + ) : null, + )} + {counts.new > 0 && } + + + {LEVELS.map((level) => { + const active = status === level; + return ( + onStatus(active ? '' : level)} + sx={{ + justifyContent: 'space-between', + gap: 1, + px: 1, + py: 0.5, + borderRadius: `${radius.sm}px`, + border: `1px solid ${active ? c.accentBorder : 'transparent'}`, + bgcolor: active ? c.accentSoft : 'transparent', + color: c.text, + '&:hover': { bgcolor: c.surfaceHover }, + '&.Mui-disabled': { opacity: 0.5 }, + '&:focus-visible': { outline: `2px solid ${c.accent}` }, + }} + > + + + + {STATUS_LABEL[level]} + + + + {counts[level]} + + + ); + })} + + + ) : ( + + )} + + {progressReady && total > 0 && ( + + {weak > 0 && ( + + + + )} + {unpassed > 0 && unpassed !== weak && ( + + + + )} + {unpassed === 0 && ( + + + + )} + + )} + + + ); +}; diff --git a/frontend/src/pages/CompanyQuestionsPage/CompanyQuestionsPage.test.tsx b/frontend/src/pages/CompanyQuestionsPage/CompanyQuestionsPage.test.tsx new file mode 100644 index 0000000..eb8027d --- /dev/null +++ b/frontend/src/pages/CompanyQuestionsPage/CompanyQuestionsPage.test.tsx @@ -0,0 +1,122 @@ +import { http, HttpResponse } from 'msw'; +import { setupServer } from 'msw/node'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import { renderRoutes } from '../../test/renderRoutes'; + +const BASE = 'http://localhost:8888/api/v1'; +const server = setupServer(); +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +const user = { + id: 'u1', + email: 'a@b.c', + first_name: 'A', + last_name: 'B', + is_admin: false, + is_active: true, +}; +const q = (id: string, title: string, difficulty = 'easy') => ({ + id, + title, + slug: id, + difficulty, + category_id: 'c1', + category: { id: 'c1', name: 'Python' }, +}); + +describe('CompanyQuestionsPage', () => { + it('loads company questions in one request and takes completion from /me/progress', async () => { + const urls: string[] = []; + server.use( + http.get(`${BASE}/auth/me`, () => HttpResponse.json(user)), + http.get(`${BASE}/me/progress`, () => + HttpResponse.json({ completed_ids: ['a'], favorite_ids: [] }), + ), + http.get(`${BASE}/companies/co1`, () => + HttpResponse.json({ + id: 'co1', + name: 'Acme', + slug: 'acme', + description: 'd', + is_active: true, + }), + ), + http.get(`${BASE}/companies/co1/questions`, ({ request }) => { + urls.push(request.url); + return HttpResponse.json({ items: [q('a', 'Первый'), q('b', 'Второй')], total: 2 }); + }), + http.get(`${BASE}/*`, ({ request }) => { + urls.push(request.url); + return HttpResponse.json({ items: [], total: 0 }); + }), + ); + renderRoutes('/companies/co1/questions'); + expect(await screen.findByText('Первый')).toBeInTheDocument(); + expect(await screen.findByText('1 из 2')).toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'Степень знания: Прошёл. Изменить' }), + ).toBeInTheDocument(); + expect(urls.filter((u) => u.includes('is-completed'))).toEqual([]); + expect(urls.filter((u) => u.includes('limit=1000'))).toEqual([]); + expect(urls.filter((u) => u.includes('/companies/co1/questions'))).toHaveLength(1); + }); + + it('breaks progress down by level, filters from the legend and resumes the saved interview', async () => { + window.localStorage.setItem( + 'interview:v1:co1', + JSON.stringify({ + v: 1, + ids: ['b', 'c'], + startedAt: Date.now(), + options: { count: 2, order: 'random', difficulty: '', onlyNew: false }, + results: { b: { answer: 'x', review: { score: 4 } } }, + }), + ); + server.use( + http.get(`${BASE}/auth/me`, () => HttpResponse.json(user)), + http.get(`${BASE}/me/progress`, () => + HttpResponse.json({ + completed_ids: ['a'], + partial_ids: [], + failed_ids: ['b'], + favorite_ids: ['c'], + }), + ), + http.get(`${BASE}/companies/co1`, () => + HttpResponse.json({ + id: 'co1', + name: 'Acme', + slug: 'acme', + description: 'd', + is_active: true, + }), + ), + http.get(`${BASE}/companies/co1/questions`, () => + HttpResponse.json({ + items: [q('a', 'Первый'), q('b', 'Второй', 'hard'), q('c', 'Третий', 'hard')], + total: 3, + }), + ), + http.get(`${BASE}/*`, () => HttpResponse.json({ items: [], total: 0 })), + ); + const { router } = renderRoutes('/companies/co1/questions'); + expect(await screen.findByText('Незавершённое собеседование')).toBeInTheDocument(); + expect(screen.getByText('отвечено 1 из 2')).toBeInTheDocument(); + expect(screen.getByLabelText('Оценка 4 из 10')).toBeInTheDocument(); + expect(await screen.findByRole('button', { name: /Слабые · 1/ })).toBeInTheDocument(); + + fireEvent.click( + await screen.findByRole('button', { name: 'Не прошёл: 1. Показать только их' }), + ); + await waitFor(() => expect(screen.queryByText('Первый')).not.toBeInTheDocument()); + expect(screen.getByText('Второй')).toBeInTheDocument(); + expect(router.state.location.search).toBe('?status=failed'); + + fireEvent.click(screen.getByRole('button', { name: 'Продолжить' })); + await waitFor(() => expect(router.state.location.pathname).toBe('/companies/co1/interview/1')); + window.localStorage.clear(); + }); +}); diff --git a/frontend/src/pages/CompanyQuestionsPage/LastInterviewCard.tsx b/frontend/src/pages/CompanyQuestionsPage/LastInterviewCard.tsx new file mode 100644 index 0000000..d48c7df --- /dev/null +++ b/frontend/src/pages/CompanyQuestionsPage/LastInterviewCard.tsx @@ -0,0 +1,133 @@ +import { Box, Button, LinearProgress, Stack, Typography } from '@mui/material'; +import { + AssessmentOutlined as ResultsIcon, + PlayArrowRounded as PlayIcon, + HistoryRounded as HistoryIcon, +} from '@mui/icons-material'; +import { radius, useTokens } from '../../theme/tokens'; +import { plural } from '../../utils/difficulty'; +import type { LastInterview } from './companyView'; + +const dateFormat = new Intl.DateTimeFormat('ru-RU', { + day: 'numeric', + month: 'long', + hour: '2-digit', + minute: '2-digit', +}); +const Q: [string, string, string] = ['вопрос', 'вопроса', 'вопросов']; + +interface LastInterviewCardProps { + last: LastInterview; + onResume: () => void; + onResults: () => void; +} + +/** Последнее собеседование по компании из localStorage: продолжить незавершённое или открыть итоги. */ +export const LastInterviewCard = ({ last, onResume, onResults }: LastInterviewCardProps) => { + const { c } = useTokens(); + const unfinished = !last.finished; + const when = dateFormat.format(new Date(last.finishedAt ?? last.startedAt)); + const stats = [ + last.average !== null && `средний балл ${last.average.toFixed(1).replace('.', ',')}`, + last.strong > 0 && `сильных ${last.strong}`, + last.weak > 0 && `слабых ${last.weak}`, + ].filter(Boolean); + + return ( + + + + + + + + {unfinished ? 'Незавершённое собеседование' : 'Последнее собеседование'} + + {' '} + · {unfinished ? 'начато' : 'завершено'} {when} + + + {unfinished ? ( + + + + отвечено {last.answered} из {last.total} + + + ) : ( + + {last.total} {plural(last.total, Q)} + {stats.length > 0 && ` · ${stats.join(' · ')}`} + + )} + + + + {unfinished && ( + + )} + {last.answered > 0 && ( + + )} + + + ); +}; diff --git a/frontend/src/pages/CompanyQuestionsPage/QuestionTable.tsx b/frontend/src/pages/CompanyQuestionsPage/QuestionTable.tsx new file mode 100644 index 0000000..33b24ed --- /dev/null +++ b/frontend/src/pages/CompanyQuestionsPage/QuestionTable.tsx @@ -0,0 +1,155 @@ +import { Box, IconButton, Stack, Tooltip, Typography } from '@mui/material'; +import { Star, StarBorder } from '@mui/icons-material'; +import { Link as RouterLink } from 'react-router-dom'; +import { MasteryIconButton } from '../../components/ui/Mastery'; +import { ScoreBadge } from '../../components/interview/ScoreBadge'; +import { useTokens } from '../../theme/tokens'; +import { getDifficultyColors, getDifficultyLabel } from '../../utils/difficulty'; +import type { MasteryLevel, Question } from '../../types'; + +/** Колонки: вопрос | сложность | балл ИИ | избранное | статус. */ +const COLUMNS = 'minmax(0,1fr) 104px 56px 40px 52px'; + +export const QuestionTableHead = () => { + const { c } = useTokens(); + return ( + + Вопрос + Сложность + + Балл + + + + Статус + + + ); +}; + +interface QuestionRowProps { + question: Question; + showCategory: boolean; + level: MasteryLevel | null; + score: number | undefined; + favorite: boolean; + statusDisabled: boolean; + onLevel: (level: MasteryLevel | null) => void; + onFavorite: () => void; +} + +export const QuestionRow = ({ + question, + showCategory, + level, + score, + favorite, + statusDisabled, + onLevel, + onFavorite, +}: QuestionRowProps) => { + const { c, mode } = useTokens(); + const color = getDifficultyColors(question.difficulty, mode).fg; + return ( + + + + {question.title} + + {showCategory && question.category?.name && ( + + {question.category.name} + + )} + + + + {getDifficultyLabel(question.difficulty)} + + + {score !== undefined ? ( + + ) : ( + + — + + )} + + + + + {favorite ? : } + + + + + + + + ); +}; diff --git a/frontend/src/pages/CompanyQuestionsPage/companyView.test.ts b/frontend/src/pages/CompanyQuestionsPage/companyView.test.ts new file mode 100644 index 0000000..ec9719c --- /dev/null +++ b/frontend/src/pages/CompanyQuestionsPage/companyView.test.ts @@ -0,0 +1,152 @@ +import { describe, expect, it } from 'vitest'; +import { newSession, DEFAULT_OPTIONS } from '../../components/interview/session'; +import type { MasteryLevel, Question } from '../../types'; +import { + DEFAULT_STATE, + activeFilterCount, + applyPatch, + categoriesOf, + companyBitLine, + countByDifficulty, + countLevels, + filterAndSort, + lastInterviewOf, + parseState, + serializeState, +} from './companyView'; + +const q = ( + id: string, + title: string, + difficulty: Question['difficulty'], + category = 'c1', + name = 'Python', +) => + ({ + id, + title, + difficulty, + slug: id, + category_id: category, + category: { id: category, name }, + }) as unknown as Question; + +const questions = [ + q('a', 'Бета', 'medium'), + q('b', 'Альфа', 'easy'), + q('c', 'Гамма', 'hard', 'c2', 'SQL'), + q('d', 'Дельта', 'easy'), +]; +const levels: Record = { a: 'passed', b: 'partial', c: 'failed' }; +const levelOf = (id: string) => levels[id] ?? null; +const ctx = { levelOf, favorites: new Set(['d']) }; + +describe('url state', () => { + it('round-trips and drops defaults and garbage', () => { + const params = new URLSearchParams('status=failed&sort=weak&page=3&difficulty=bogus&utm=x'); + const state = parseState(params); + expect(state).toEqual({ ...DEFAULT_STATE, status: 'failed', sort: 'weak', page: 3 }); + expect(serializeState(state, params).toString()).toBe('utm=x&status=failed&sort=weak&page=3'); + expect(serializeState(DEFAULT_STATE).toString()).toBe(''); + }); + + it('resets the page on any change except paging', () => { + const state = { ...DEFAULT_STATE, page: 4 }; + expect(applyPatch(state, { status: 'new' }).page).toBe(1); + expect(applyPatch(state, { page: 2 }).page).toBe(2); + expect(activeFilterCount({ ...DEFAULT_STATE, q: 'x', sort: 'title', status: 'fav' })).toBe(2); + }); +}); + +describe('progress breakdown', () => { + it('counts levels and passed by difficulty', () => { + expect(countLevels(questions, levelOf)).toEqual({ + total: 4, + passed: 1, + partial: 1, + failed: 1, + new: 1, + }); + expect(countByDifficulty(questions, levelOf)).toEqual([ + { difficulty: 'easy', total: 2, passed: 0 }, + { difficulty: 'medium', total: 1, passed: 1 }, + { difficulty: 'hard', total: 1, passed: 0 }, + ]); + expect(categoriesOf(questions).map((c) => c.name)).toEqual(['Python', 'SQL']); + }); +}); + +describe('filterAndSort', () => { + const ids = (state: Partial) => + filterAndSort(questions, { ...DEFAULT_STATE, ...state }, ctx).map((x) => x.id); + + it('filters by status, favorites, category and search', () => { + expect(ids({ status: 'new' })).toEqual(['d']); + expect(ids({ status: 'partial' })).toEqual(['b']); + expect(ids({ status: 'fav' })).toEqual(['d']); + expect(ids({ category: 'c2' })).toEqual(['c']); + expect(ids({ q: 'ЛЬФ', difficulty: 'easy' })).toEqual(['b']); + }); + + it('sorts weak first, by difficulty and by title', () => { + expect(ids({ sort: 'weak' })).toEqual(['c', 'b', 'd', 'a']); + expect(ids({ sort: 'difficulty' })).toEqual(['b', 'd', 'a', 'c']); + expect(ids({ sort: 'title' })).toEqual(['b', 'a', 'c', 'd']); + expect(ids({})).toEqual(['a', 'b', 'c', 'd']); + }); +}); + +describe('lastInterviewOf', () => { + const known = new Set(['a', 'b', 'c']); + + it('summarizes an unfinished session and points to the first open question', () => { + const s = newSession(['gone', 'a', 'b', 'c'], DEFAULT_OPTIONS, 1000); + s.results = { + a: { answer: 'ответ', review: { score: 9 } as never }, + c: { answer: '', self: 'missed' }, + }; + const last = lastInterviewOf(s, known); + expect(last).toMatchObject({ + finished: false, + total: 3, + answered: 2, + average: 9, + resumeIndex: 1, + strong: 1, + }); + }); + + it('ignores missing sessions and sessions without known questions', () => { + expect(lastInterviewOf(null, known)).toBeNull(); + expect(lastInterviewOf(newSession(['x'], DEFAULT_OPTIONS), known)).toBeNull(); + }); +}); + +describe('companyBitLine', () => { + const counts = (passed: number, partial = 0, failed = 0, total = 5) => ({ + total, + passed, + partial, + failed, + new: total - passed - partial - failed, + }); + + it('picks the line by progress', () => { + expect(companyBitLine('AMD', counts(0, 0, 0, 0), null)).toBeNull(); + expect(companyBitLine('AMD', counts(0), null)?.key).toBe('company:start'); + expect(companyBitLine('AMD', counts(2), null)?.key).toBe('company:progress'); + expect(companyBitLine('AMD', counts(2, 1), null)?.key).toBe('company:weak'); + expect(companyBitLine('AMD', counts(5), null)?.tone).toBe('cheer'); + const paused = { + finished: false, + startedAt: 0, + total: 4, + answered: 1, + average: null, + strong: 0, + weak: 0, + resumeIndex: 1, + }; + expect(companyBitLine('AMD', counts(2, 1), paused)?.key).toBe('company:resume'); + }); +}); diff --git a/frontend/src/pages/CompanyQuestionsPage/companyView.ts b/frontend/src/pages/CompanyQuestionsPage/companyView.ts new file mode 100644 index 0000000..17ba4c6 --- /dev/null +++ b/frontend/src/pages/CompanyQuestionsPage/companyView.ts @@ -0,0 +1,254 @@ +import { isAnswered, summarize, type InterviewSession } from '../../components/interview/session'; +import { plural } from '../../utils/difficulty'; +import type { MasteryLevel, Question } from '../../types'; + +/** Статус в фильтре: new — без отметки, fav — в избранном, остальное — уровень знания. */ +export const STATUSES = ['new', 'passed', 'partial', 'failed', 'fav'] as const; +export type CompanyStatus = '' | (typeof STATUSES)[number]; +export const STATUS_LABEL: Record<(typeof STATUSES)[number], string> = { + new: 'Не начат', + passed: 'Прошёл', + partial: 'Частично', + failed: 'Не прошёл', + fav: 'В избранном', +}; + +/** '' — порядок с сервера, weak — сначала слабые, difficulty — от лёгких к сложным, title — по алфавиту. */ +export const SORTS = ['weak', 'difficulty', 'title'] as const; +export type CompanySort = '' | (typeof SORTS)[number]; +export const SORT_LABEL: Record<(typeof SORTS)[number] | '', string> = { + '': 'По умолчанию', + weak: 'Сначала слабые', + difficulty: 'По сложности', + title: 'По алфавиту', +}; + +const DIFFICULTIES = ['easy', 'medium', 'hard'] as const; +type Difficulty = (typeof DIFFICULTIES)[number]; + +export interface CompanyListState { + q: string; + difficulty: '' | Difficulty; + status: CompanyStatus; + category: string; + sort: CompanySort; + page: number; +} + +export const DEFAULT_STATE: CompanyListState = { + q: '', + difficulty: '', + status: '', + category: '', + sort: '', + page: 1, +}; +const KEYS = Object.keys(DEFAULT_STATE) as (keyof CompanyListState)[]; + +const oneOf = (values: readonly T[], raw: string | null): T | '' => + raw !== null && (values as readonly string[]).includes(raw) ? (raw as T) : ''; + +/** Мусор в одном параметре не ломает остальные: каждое поле читается отдельно. */ +export const parseState = (params: URLSearchParams): CompanyListState => { + const page = Number(params.get('page')); + return { + q: (params.get('q') ?? '').slice(0, 200), + difficulty: oneOf(DIFFICULTIES, params.get('difficulty')), + status: oneOf(STATUSES, params.get('status')), + category: (params.get('category') ?? '').slice(0, 100), + sort: oneOf(SORTS, params.get('sort')), + page: Number.isInteger(page) && page > 1 ? Math.min(page, 10_000) : 1, + }; +}; + +/** В URL — только отличия от значений по умолчанию; чужие параметры сохраняются. */ +export const serializeState = (state: CompanyListState, base = new URLSearchParams()) => { + const next = new URLSearchParams(base); + KEYS.forEach((k) => next.delete(k)); + if (state.q.trim()) next.set('q', state.q.trim()); + if (state.difficulty) next.set('difficulty', state.difficulty); + if (state.status) next.set('status', state.status); + if (state.category) next.set('category', state.category); + if (state.sort) next.set('sort', state.sort); + if (state.page > 1) next.set('page', String(state.page)); + return next; +}; + +/** Любое изменение, кроме страницы, возвращает на первую страницу. */ +export const applyPatch = ( + state: CompanyListState, + patch: Partial, +): CompanyListState => ({ + ...state, + ...patch, + page: 'page' in patch ? (patch.page ?? 1) : 1, +}); + +export const activeFilterCount = (s: CompanyListState) => + [s.difficulty, s.status, s.category, s.sort].filter(Boolean).length; + +type LevelOf = (id: string) => MasteryLevel | null; + +export interface LevelCounts { + total: number; + passed: number; + partial: number; + failed: number; + new: number; +} + +export const countLevels = (questions: Question[], levelOf: LevelOf): LevelCounts => { + const counts: LevelCounts = { total: questions.length, passed: 0, partial: 0, failed: 0, new: 0 }; + for (const q of questions) counts[levelOf(q.id) ?? 'new'] += 1; + return counts; +}; + +/** Пройдено из общего числа по каждой сложности (сложности без вопросов не показываются). */ +export const countByDifficulty = (questions: Question[], levelOf: LevelOf) => + DIFFICULTIES.map((difficulty) => { + const items = questions.filter((q) => q.difficulty?.toLowerCase() === difficulty); + return { + difficulty, + total: items.length, + passed: items.filter((q) => levelOf(q.id) === 'passed').length, + }; + }).filter((d) => d.total > 0); + +/** Разделы вопросов компании: фильтр по разделу показывается, только если их больше одного. */ +export const categoriesOf = (questions: Question[]) => { + const map = new Map(); + for (const q of questions) + if (q.category_id && q.category?.name) map.set(q.category_id, q.category.name); + return [...map] + .map(([id, name]) => ({ id, name })) + .sort((a, b) => a.name.localeCompare(b.name, 'ru')); +}; + +const WEAK_ORDER: Record = { + failed: 0, + partial: 1, + new: 2, + passed: 3, +}; +const DIFFICULTY_ORDER: Record = { easy: 0, medium: 1, hard: 2 }; + +export const filterAndSort = ( + questions: Question[], + state: CompanyListState, + { levelOf, favorites }: { levelOf: LevelOf; favorites: Set }, +) => { + const query = state.q.trim().toLowerCase(); + const items = questions.filter((q) => { + if (query && !q.title.toLowerCase().includes(query)) return false; + if (state.difficulty && q.difficulty?.toLowerCase() !== state.difficulty) return false; + if (state.category && q.category_id !== state.category) return false; + if (state.status === 'fav') return favorites.has(q.id); + if (state.status) return (levelOf(q.id) ?? 'new') === state.status; + return true; + }); + const by: Record, (a: Question, b: Question) => number> = { + weak: (a, b) => WEAK_ORDER[levelOf(a.id) ?? 'new'] - WEAK_ORDER[levelOf(b.id) ?? 'new'], + difficulty: (a, b) => + (DIFFICULTY_ORDER[a.difficulty] ?? 1) - (DIFFICULTY_ORDER[b.difficulty] ?? 1), + title: (a, b) => a.title.localeCompare(b.title, 'ru'), + }; + // sort стабилен: внутри группы сохраняется порядок с сервера + return state.sort ? [...items].sort(by[state.sort]) : items; +}; + +export interface LastInterview { + finished: boolean; + startedAt: number; + finishedAt?: number; + total: number; + answered: number; + /** Средний балл ИИ 0..10, если были оценки. */ + average: number | null; + strong: number; + weak: number; + /** Индекс первого неотвеченного вопроса — туда ведёт «Продолжить». */ + resumeIndex: number; +} + +/** + * Сводка сохранённого собеседования по компании. Вопросы, которых больше нет у компании, + * не учитываются — как и в самом собеседовании. + */ +export const lastInterviewOf = ( + session: InterviewSession | null, + questionIds: Set, +): LastInterview | null => { + if (!session) return null; + const ids = session.ids.filter((id) => questionIds.has(id)); + if (!ids.length) return null; + const summary = summarize({ ...session, ids }); + const firstOpen = ids.findIndex((id) => !isAnswered(session.results[id])); + return { + finished: Boolean(session.finishedAt), + startedAt: session.startedAt, + finishedAt: session.finishedAt, + total: ids.length, + answered: summary.answered, + average: summary.average, + strong: summary.strongIds.length, + weak: summary.weakIds.length, + resumeIndex: Math.max(0, firstOpen), + }; +}; + +const Q: [string, string, string] = ['вопрос', 'вопроса', 'вопросов']; + +/** Реплика Бита при открытии страницы: подсказывает следующий шаг по прогрессу компании. */ +export const companyBitLine = ( + company: string, + counts: LevelCounts, + last: LastInterview | null, +): { key: string; lines: string[]; tone: 'calm' | 'cheer' | 'focus' | 'fire' } | null => { + const { total, passed, partial, failed } = counts; + if (!total) return null; + const weak = partial + failed; + if (last && !last.finished && last.answered > 0) + return { + key: 'company:resume', + tone: 'focus', + lines: [ + `Собеседование в ${company} на паузе: ${last.answered} из ${last.total}. Продолжим с того же места?`, + `Собеседование на паузе: отвечено ${last.answered} из ${last.total}. Доведём до конца?`, + ], + }; + if (passed === total) + return { + key: 'company:done', + tone: 'cheer', + lines: [ + `Все ${total} ${plural(total, Q)} ${company} пройдены! Прогони их вразброс — проверим, что не забылось.`, + `Вопросы ${company} закрыты целиком. Можно браться за следующую компанию.`, + ], + }; + if (weak > 0) + return { + key: 'company:weak', + tone: 'fire', + lines: [ + `${weak} ${plural(weak, Q)} ${company} ${weak === 1 ? 'просел' : 'просели'}. Давай добьём — жми «Слабые».`, + `Пройдено ${passed} из ${total}, но ${weak} ${plural(weak, Q)} ещё шатаются. Начнём с них.`, + ], + }; + if (passed === 0) + return { + key: 'company:start', + tone: 'calm', + lines: [ + `У ${company} ${total} ${plural(total, Q)}. Начни с лёгких — разогреемся.`, + `${total} ${plural(total, Q)} от ${company}. Пробное собеседование — лучший способ понять, где пробелы.`, + ], + }; + return { + key: 'company:progress', + tone: 'focus', + lines: [ + `${passed} из ${total} уже в кармане. Осталось ${total - passed} — продолжим?`, + `Хороший темп: ${Math.round((passed / total) * 100)}% ${company} пройдено.`, + ], + }; +}; diff --git a/frontend/src/pages/CompanyQuestionsPage/index.tsx b/frontend/src/pages/CompanyQuestionsPage/index.tsx new file mode 100644 index 0000000..dfafe26 --- /dev/null +++ b/frontend/src/pages/CompanyQuestionsPage/index.tsx @@ -0,0 +1,482 @@ +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { + Alert, + Box, + Button, + Container, + FormControl, + IconButton, + InputLabel, + MenuItem, + Select, + Skeleton, + Stack, + Typography, +} from '@mui/material'; +import { + QuizOutlined as QuizIcon, + SearchOff as SearchOffIcon, + BusinessOutlined as BusinessIcon, + ChevronLeft, + ChevronRight, +} from '@mui/icons-material'; +import { isAxiosError } from 'axios'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { ConfirmDialog, EmptyState, FilterBar, PageHeader, SearchInput } from '../../components/ui'; +import { bitSay, pickLine } from '../../components/ui/bitVoice'; +import { + DEFAULT_OPTIONS, + buildPlan, + loadSession, + newSession, + saveSession, + scoreOf, + type InterviewOptions, +} from '../../components/interview/session'; +import { useCompany, useCompanyQuestions } from '../../queries/companies'; +import { useProgress, useSetMastery, useToggleFavorite } from '../../queries/progress'; +import type { MasteryLevel, Question } from '../../types'; +import { useTokens, wideFrame } from '../../theme/tokens'; +import { CompanyHero } from './CompanyHero'; +import { LastInterviewCard } from './LastInterviewCard'; +import { QuestionRow, QuestionTableHead } from './QuestionTable'; +import { + SORTS, + SORT_LABEL, + STATUSES, + STATUS_LABEL, + activeFilterCount, + applyPatch, + categoriesOf, + companyBitLine, + countByDifficulty, + countLevels, + filterAndSort, + lastInterviewOf, + parseState, + serializeState, + type CompanyListState, +} from './companyView'; + +const NO_QUESTIONS: Question[] = []; +const PAGE_SIZE = 10; + +type QuickStart = 'weak' | 'unpassed' | 'all'; + +export const CompanyQuestionsPage = () => { + const navigate = useNavigate(); + const { companyId } = useParams<{ companyId: string }>(); + const { c } = useTokens(); + const [params, setParams] = useSearchParams(); + const state = useMemo(() => parseState(params), [params]); + + const companyQuery = useCompany(companyId); + const questionsQuery = useCompanyQuestions(companyId); + const progress = useProgress(); + const setMastery = useSetMastery(); + const toggleFavorite = useToggleFavorite(); + const [pendingIds, setPendingIds] = useState>({}); + const [completionError, setCompletionError] = useState(false); + const [search, setSearch] = useState(state.q); + const [confirmQuick, setConfirmQuick] = useState(null); + const listRef = useRef(null); + const [reserved, setReserved] = useState({ key: '', height: 0 }); + // Сессия читается при входе на страницу: собеседование живёт на другом маршруте + const [session] = useState(() => loadSession(companyId)); + + const isLoading = companyQuery.isPending || questionsQuery.isPending; + const loadError = companyQuery.isError || questionsQuery.isError; + const notFound = isAxiosError(companyQuery.error) && companyQuery.error.response?.status === 404; + const statusesError = progress.isError; + const progressReady = progress.isSuccess; + + const update = (patch: Partial, replace = false) => + setParams((prev) => serializeState(applyPatch(parseState(prev), patch), prev), { replace }); + + useEffect(() => { + if (search.trim() === state.q.trim()) return; + const timer = setTimeout(() => update({ q: search }, true), 300); + return () => clearTimeout(timer); + // eslint-disable-next-line react-hooks/exhaustive-deps -- update пересоздаётся на каждый рендер + }, [search, state.q]); + + const company = companyQuery.data ?? null; + const questions = questionsQuery.data?.items ?? NO_QUESTIONS; + const { levelOf, favorites, completed } = progress; + + const counts = countLevels(questions, levelOf); + const byDifficulty = countByDifficulty(questions, levelOf); + const categories = useMemo(() => categoriesOf(questions), [questions]); + const commonCategory = categories.length === 1 ? categories[0].name : undefined; + const filtered = filterAndSort(questions, state, { levelOf, favorites }); + const questionIds = useMemo(() => new Set(questions.map((q) => q.id)), [questions]); + const last = useMemo(() => lastInterviewOf(session, questionIds), [session, questionIds]); + + const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE)); + const visiblePage = Math.min(state.page, pageCount); + const start = (visiblePage - 1) * PAGE_SIZE; + const visible = filtered.slice(start, start + PAGE_SIZE); + + // Высота списка не «прыгает» при листании: резервируем максимум увиденного для текущих фильтров + const filterKey = [state.q, state.status, state.difficulty, state.category, state.sort].join('|'); + useLayoutEffect(() => { + if (!isLoading && filtered.length && listRef.current) { + const height = Math.ceil(listRef.current.scrollHeight); + setReserved((prev) => + prev.key === filterKey && prev.height >= height + ? prev + : { + key: filterKey, + height: prev.key === filterKey ? Math.max(prev.height, height) : height, + }, + ); + } + }, [isLoading, visiblePage, filtered.length, filterKey]); + useEffect(() => { + const resetHeight = () => setReserved({ key: '', height: 0 }); + window.addEventListener('resize', resetHeight); + return () => window.removeEventListener('resize', resetHeight); + }, []); + + // Бит комментирует прогресс по компании один раз, когда всё загрузилось + const spokeRef = useRef(null); + useEffect(() => { + if (!company || !progressReady || isLoading || spokeRef.current === company.id) return; + spokeRef.current = company.id; + const line = companyBitLine(company.name, countLevels(questions, levelOf), last); + if (line) bitSay(pickLine(line.key, line.lines), line.tone); + }, [company, progressReady, isLoading, questions, levelOf, last]); + + const base = `/companies/${companyId}/interview`; + const unfinishedWithAnswers = Boolean(last && !last.finished && last.answered > 0); + + const quickPlan = (kind: QuickStart): { ids: string[]; options: InterviewOptions } => { + if (kind === 'weak') { + const weak = filterAndSort( + questions, + { ...state, q: '', difficulty: '', category: '', status: '', sort: 'weak' }, + { levelOf, favorites }, + ).filter((q) => { + const level = levelOf(q.id); + return level === 'failed' || level === 'partial'; + }); + return { + ids: weak.map((q) => q.id), + options: { ...DEFAULT_OPTIONS, count: 0, order: 'sequential', onlyNew: false }, + }; + } + const options: InterviewOptions = + kind === 'unpassed' + ? { ...DEFAULT_OPTIONS, count: 10, order: 'random', onlyNew: true } + : { ...DEFAULT_OPTIONS, count: 0, order: 'random', onlyNew: false }; + return { ids: buildPlan(questions, options, completed), options }; + }; + + const runQuick = (kind: QuickStart) => { + const { ids, options } = quickPlan(kind); + if (!ids.length) return; + saveSession(companyId, newSession(ids, options)); + navigate(`${base}/0`); + }; + + const requestQuick = (kind: QuickStart) => + unfinishedWithAnswers ? setConfirmQuick(kind) : runQuick(kind); + + const handleSetLevel = async (questionId: string, level: MasteryLevel | null) => { + setPendingIds((prev) => ({ ...prev, [questionId]: true })); + try { + await setMastery.mutateAsync({ id: questionId, level }); + setCompletionError(false); + } catch (err) { + console.error('Failed to set mastery:', err); + setCompletionError(true); + } finally { + setPendingIds((prev) => { + const next = { ...prev }; + delete next[questionId]; + return next; + }); + } + }; + + const resetFilters = () => { + setSearch(''); + setParams((prev) => + serializeState({ q: '', difficulty: '', status: '', category: '', sort: '', page: 1 }, prev), + ); + }; + + if (isLoading && !loadError) { + return ( + + + + + + + ); + } + + if (loadError || !company) { + return ( + + + } + title={!notFound ? 'Не удалось загрузить компанию' : 'Компания не найдена'} + description={ + !notFound + ? 'Обновите страницу или попробуйте позже.' + : 'Возможно, она была удалена или ссылка устарела.' + } + action={ + + } + /> + + ); + } + + const filterCount = activeFilterCount(state); + const selects = ( + <> + + Статус + + + + Сложность + + + {categories.length > 1 && ( + + Раздел + + + )} + + Сортировка + + + + ); + + return ( + + + {(statusesError || completionError) && ( + + Не удалось загрузить или сохранить статус прохождения. Обновите страницу и попробуйте + снова. + + )} + update({ status })} + onStart={() => navigate(`${base}/setup`)} + onQuick={requestQuick} + startDisabled={!questions.length || statusesError} + /> + {last && ( + navigate(`${base}/${last.resumeIndex}`)} + onResults={() => navigate(`${base}/results`)} + /> + )} + + + + Вопросы + + {commonCategory && ( + + {commonCategory} + + )} + + + {questions.length > 0 && ( + + + } + > + {selects} + + + )} + + PAGE_SIZE && reserved.key === filterKey ? reserved.height : 0, + }} + > + {questions.length === 0 ? ( + } + title="Нет доступных вопросов" + description="Для этой компании вопросы пока не добавлены." + /> + ) : filtered.length === 0 ? ( + + } + title={ + state.status === 'fav' && !state.q + ? 'В избранном пока пусто' + : 'Вопросы не найдены' + } + description={ + state.status === 'fav' && !state.q + ? 'Отмечайте вопросы звёздочкой, чтобы вернуться к ним позже.' + : 'Попробуйте изменить запрос или фильтры.' + } + action={ + + } + /> + + ) : ( + visible.map((question) => ( + void handleSetLevel(question.id, next)} + onFavorite={() => + toggleFavorite.mutate({ id: question.id, on: !favorites.has(question.id) }) + } + /> + )) + )} + + {questions.length > 0 && ( + + + {filtered.length + ? `${start + 1}–${Math.min(start + PAGE_SIZE, filtered.length)} из ${filtered.length}` + : '0 вопросов'} + {filtered.length !== questions.length && + filtered.length > 0 && + ` (всего ${questions.length})`} + + {pageCount > 1 && ( + + update({ page: visiblePage - 1 })} + > + + + = pageCount} + onClick={() => update({ page: visiblePage + 1 })} + > + + + + )} + + )} + + + setConfirmQuick(null)} + onConfirm={() => { + const kind = confirmQuick; + setConfirmQuick(null); + if (kind) runQuick(kind); + }} + /> + + ); +};