Тесты и опросы: критерии оценки, génération ИИ, улучшения конструктора и прохождения
- lib/quizzes.js: система criterial-оценки (quiz_grade_scales/quiz_grade_ranges), подсчёт баллов, попытки, anon-опросы, системные поля, доступ по коду - lib/quiz-grades.js: CRUD критериев оценки, диапазоны, картинки - lib/quiz-ai.js: генерация черновика теста через ИИ - server.js: роуты тестов, критериев, медиа-ассетов, попыток - db/init.sql + db/migration.sql: таблицы quizzes*, валидация и индексы - public/: конструктор, прохождение, публичная страница, список, критерии оценки - quiz.selftest.js, quiz-ai.selftest.js: юнит-проверки
This commit is contained in:
@@ -449,26 +449,29 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
|
||||
|
||||
### 3t. Тесты и опросы (`lib/quizzes.js`, `server.js`, `public/quizzes.html`, `public/quiz-edit.html`, `public/quiz.html`)
|
||||
|
||||
- **Два вида:** `quizzes.kind` = `test` (правильные ответы, балл, `pass_percent`) и `survey` (оценки нет, собирается статистика). Типы вопросов (`quiz_questions.kind`): `single` (радиокнопки), `multiple` (флажки), `select` (выпадающий список), `line` (строка), `text` (многострочный текст), `number` (число), `date` (дата). У варианта `is_correct` + `weight NUMERIC(6,2)`, у вопроса `weight` + `partial_credit` + `min_length` (минимальная длина обязательного ответа для `line`/`text`) + `options_inline` (варианты ответов в одну строку) + `text_match`/`accepted_answers` (автопроверка свободных ответов), у теста-опроса — `allow_anonymous` (публичная ссылка доступна и тестам, и опросам).
|
||||
- **Таблицы:** `quizzes`, `quiz_questions`, `quiz_options`, `quiz_assets`, `quiz_attempts`, `quiz_attempt_answers`. Схема — `db/init.sql`, `db/migration.sql` и `ensureQuizTables(pool)` (вызывается из `ensureUsersAndFirstAdmin()`); CHECK `quiz_assets_one_owner` (`num_nonnulls(quiz_id, question_id, option_id) <= 1`) добавляется guarded `DO`-блоком в обоих SQL и в модуле. Расширения (`allow_anonymous`, `text_match`, `accepted_answers`, `anon_token`, `min_length`, `options_inline`) есть и в `CREATE TABLE`, и в идемпотентных `ALTER ... ADD COLUMN IF NOT EXISTS` в `db/migration.sql`.
|
||||
- **Два вида:** `quizzes.kind` = `test` (правильные ответы, балл, `pass_percent`) и `survey` (оценки нет, собирается статистика). Типы вопросов (`quiz_questions.kind`): `single` (радиокнопки), `multiple` (флажки), `select` (выпадающий список), `line` (строка), `text` (многострочный текст), `number` (число), `date` (дата), а также системные `student` / `group` / `branch` / `module` — ученик, группа, филиал и тема модуля с поиском по названию (см. ниже). У варианта `is_correct` + `weight NUMERIC(6,2)`, у вопроса `weight` + `partial_credit` + `min_length` (минимальная длина обязательного ответа для `line`/`text`) + `options_inline` (варианты ответов в одну строку) + `text_match`/`accepted_answers` (автопроверка свободных ответов), у теста-опроса — `allow_anonymous` (публичная ссылка доступна и тестам, и опросам) и `access_code` (код перед прохождением по ссылке).
|
||||
- **Интервал повтора:** `quizzes.retry_cooldown_min INT NOT NULL DEFAULT 0` — через сколько минут можно пройти тест/опрос повторно. Ограничение **клиентское и на браузер**: `public/js/quiz.js` / `public/js/quiz-public.js` пишут метку в `localStorage` (`whatido_quiz_retry_<quiz_id>`) после успешной отправки и до истечения срока прячут кнопку «Начать»/«Пройти ещё раз», показывая обратный отсчёт (по образцу отправки записи в `public/js/index.js`). Ключ общий для внутренней и публичной страницы (один origin), поэтому прохождение по ссылке и в интерфейсе блокируются одинаково; сервер попытки не ограничивает — смена браузера или очистка `localStorage` снимает паузу. `0` — без ограничения, максимум `QUIZ_RETRY_COOLDOWN_MAX` = 10080 (7 дней). Поле `#qeRetry` («Повтор, мин») в блоке «Основное» редактора.
|
||||
- **Таблицы:** `quizzes`, `quiz_questions`, `quiz_options`, `quiz_assets`, `quiz_attempts`, `quiz_attempt_answers`. Схема — `db/init.sql`, `db/migration.sql` и `ensureQuizTables(pool)` (вызывается из `ensureUsersAndFirstAdmin()`); CHECK `quiz_assets_one_owner` (`num_nonnulls(quiz_id, question_id, option_id) <= 1`) добавляется guarded `DO`-блоком в обоих SQL и в модуле. Расширения (`allow_anonymous`, `access_code`, `text_match`, `accepted_answers`, `anon_token`, `min_length`, `options_inline`, `answer_id` у ответов) есть и в `CREATE TABLE`, и в идемпотентных `ALTER ... ADD COLUMN IF NOT EXISTS` в `db/migration.sql`.
|
||||
- **У ассета ровно один владелец:** `quiz_id` (материал теста), `question_id` или `option_id`. `bindAssets()` при привязке к вопросу/варианту обнуляет `quiz_id`, поэтому нельзя «поделить» один файл между тестом и вопросом — второй владелец перезапишет первый.
|
||||
- **Медиа до сохранения структуры:** `POST /api/quizzes/assets` кладёт файл в `quiz_assets` без владельца (`created_by` = загрузивший) и возвращает `id`; структура ссылается на `asset_ids`, привязка — при `PUT /api/quizzes/:id`. Брошенные ассеты чистит `cleanupQuizAssets(pool, 24)` (интервал 6 ч в `server.js`), файлы удаляются через `safeUnlink`.
|
||||
- **Файлы:** свой `multer` `quizMediaUpload` с белым списком `QUIZ_MEDIA_EXT` (а не «не заблокировано»), `limits.fileSize = MAX_FILE_UPLOAD_BYTES`, запись в `uploads/` + общий хук `storage.persist`. Картинки — через `/uploads/<name>`/`thumbSrc()`; аудио/видео/документы — `GET /api/quizzes/files/:name`: авторизация по `X-Auth-Token` **или** `?token=` (нужно для `<audio>/<video>`), `?play=1` + Range для медиа, иначе attachment. Для анонимного опроса — `GET /api/public-quizzes/files/:name`, который через JOIN проверяет, что файл принадлежит ассету опубликованного анонимного опроса (`quiz_assets` → `quiz_id`/`question_id`/`option_id` → `quizzes`).
|
||||
- **Scoring:** `scoreQuestion()`/`scoreTextAnswer()` в `lib/quizzes.js`. `single`/`select` — ровно один верный; `multiple` без `partial_credit` — точное совпадение набора; с `partial_credit` — `sum(верные) − sum(неверные)`, клампится в `0..sum(верные)`; балл × `question.weight`. Свободные ответы (`line`/`text`/`number`/`date`): пустой `accepted_answers` → `0/0` и `is_correct = null` (ручная проверка), иначе `max_score = question.weight`; `line`/`text` нормализуются `normalizeAnswerText` (нижний регистр, `ё → е`, пробелы, хвостовая пунктуация) и сравниваются по `text_match` (`exact`/`contains`), `number` — как числа (`normalizeNumberValue`: запятая/пробелы), `date` — как даты (`normalizeDateValue`: `ГГГГ-ММ-ДД` или `ДД.ММ.ГГГГ`). `percent` и `passed` — только для теста.
|
||||
- **Scoring:** `scoreQuestion()`/`scoreTextAnswer()` в `lib/quizzes.js`. `single`/`select` — ровно один верный; `multiple` без `partial_credit` — точное совпадение набора; с `partial_credit` — `Σ(вес верных) − Σ(вес неверных)`, клампится в `0..Σ(вес верных)`. **Баллы выборочного вопроса считаются по весам вариантов, без множителя `question.weight`**: `max_score = Σ весов верных вариантов`, `score` — сумма весов выбранных верных (минус неверные при частичном зачёте). `question.weight` — баллы только свободных ответов, где вариантов нет. Оба веса по умолчанию 0 (`weight NUMERIC(6,2) NOT NULL DEFAULT 0`), автор проставляет баллы явно; у нового `multiple` `partial_credit` включён по умолчанию. Свободные ответы (`line`/`text`/`number`/`date`): пустой `accepted_answers` → `0/0` и `is_correct = null` (ручная проверка), иначе `max_score = question.weight`; `line`/`text` нормализуются `normalizeAnswerText` (нижний регистр, `ё → е`, пробелы, хвостовая пунктуация) и сравниваются по `text_match` (`exact`/`contains`), `number` — как числа (`normalizeNumberValue`: запятая/пробелы), `date` — как даты (`normalizeDateValue`: `ГГГГ-ММ-ДД` или `ДД.ММ.ГГГГ`). `percent` и `passed` — только для теста. Системные поля (`student`/`group`/`branch`) оцениваются как свободный ответ без `accepted_answers` — `0/0` и `is_correct = null` (ручная проверка); их текст (название) лежит в `text_answer`, а id выбранной записи — в `quiz_attempt_answers.answer_id` и `answer_snapshot.answer_id`.
|
||||
- **Мин. длина ответа:** `quiz_questions.min_length` (0..2000) действует только для `line`/`text` и только при `required = true` — в конструкторе поле появляется после включения «Обязательный». Сервер проверяет длину в `performSubmit` (после `textValue`, то есть по обрезанной строке) и отвечает `400` с текстом «минимум N символов»; клиент блокирует отправку с той же подсказкой. Для `number`/`date` и при `required = false` значение принудительно обнуляется.
|
||||
- **Обязательные вопросы:** `quiz_questions.required` (`NOT NULL DEFAULT true`) — единственный признак обязательности и действует для **всех** типов вопросов. `performSubmit` отклоняет отправку с `400` «Вопрос «…»: ответ обязателен», если `required !== false`, а ответ пуст: нет `option_ids` у `single`/`multiple`/`select`, пустой `text` и нет `answer_id` у свободных и системных (`line`/`text`/`number`/`date`/`student`/`group`/`branch`). Обе страницы (`public/js/quiz.js`, `public/js/quiz-public.js`) блокируют отправку, показывают номер вопроса и прокручивают к нему; `confirm`-предупреждение удалено. Исключение — автоотправка по истечении таймера: клиент шлёт `time_up: true`, и в этом режиме `performSubmit` пропускает проверки `required` и `min_length`, иначе истёкшая попытка навсегда зависла бы в `in_progress`. `time_up` — не граница безопасности: обход `required` даёт только нулевой балл.
|
||||
- **Ответы после завершения:** два независимых флага — `quizzes.show_results` (показывать результат вообще: балл, процент, оценку) и `quizzes.show_answers` (показывать разбор ответов). В конструкторе это тумблеры «Показывать результат» (`#qeShowResults`) и «Показывать ответы» (`#qeShowAnswers`, виден только у теста). `performSubmit` при `show_results = false` возвращает `result: null`, а при `show_answers = false` — результат только с баллом и оценкой, `questions: []` и `answers_hidden: true`, `revealed: false`. Автор и админ разбор видят всегда: в `getAttempt` `revealed = editable || (show_results && show_answers)`. Фронт при скрытом разборе пишет «Автор скрыл разбор ответов» (`public/js/quiz.js`, `public/js/quiz-public.js`).
|
||||
- **Критерии оценки (grade scales):** таблицы `quiz_grade_scales` (`name`, `description`, `sort_order`, `created_by`) и `quiz_grade_ranges` (`scale_id` FK CASCADE, `min_score`/`max_score` NUMERIC(8,2) включительно, `label`, `image_path`). У теста — `quizzes.grade_scale_id` (`ON DELETE SET NULL`), у опроса всегда `NULL` (`normalizeMeta`). CRUD в `lib/quiz-grades.js`: `GET /api/grade-scales` (`requireAuth`, список с диапазонами), `POST`/`PUT /api/grade-scales/:id`/`DELETE`, `POST /api/grade-scales/upload` и `GET /api/grade-scales/images` — под `requireAdmin`; аудит `grade_scale.create/update/delete`. Валидация (`normalizeScale`/`normalizeRanges`): 1..30 диапазонов, `max >= min`, подпись обязательна, имя уникально без учёта регистра, картинка — `/uploads/<name>`. Оценка считается по **набранным баллам** (`gradeForScore(ranges, score)` — первый диапазон, куда попал `score`; диапазоны сортируются по `min_score`, порядок строк в форме не важен) и возвращается в `result.grade` (`performSubmit`) и `grade` (`getAttempt`). UI — кнопка «Критерии оценки» на `public/quizzes.html` (видна только админу) → модалка `#quizScalesModal`: список шкал, редактор диапазонов (мин/макс/подпись) и картинка из уже загруженных (`listGradeImages` — UNION по doc/фото/ассетам) или загрузка новой (`public/js/grade-scales.js`). В конструкторе — селект «Критерий оценки» (`#qeGradeScale`) только у теста; оценка выводится на экране результата (`quiz.js`, `quiz-public.js`).
|
||||
- **Критерии оценки (grade scales):** таблицы `quiz_grade_scales` (`name`, `description`, `sort_order`, `is_shared`, `created_by`) и `quiz_grade_ranges` (`scale_id` FK CASCADE, `min_score`/`max_score` NUMERIC(8,2) включительно, `label`, `image_path`). У теста — `quizzes.grade_scale_id` (`ON DELETE SET NULL`), у опроса всегда `NULL` (`normalizeMeta`). CRUD в `lib/quiz-grades.js`: **все роуты под `requireAuth`** — `GET /api/grade-scales`, `POST`/`PUT /api/grade-scales/:id`/`DELETE`, `POST /api/grade-scales/upload`, `GET /api/grade-scales/images`. Создавать может любой пользователь; править и удалять — только автор шкалы или админ (`loadScaleForWrite` → 403 «Изменять можно только свои критерии оценки»); админ видит все шкалы. Видимость списка: админ — все, остальные — свои плюс шкалы админа с `is_shared = TRUE` («Доступна всем»). Флаг `is_shared` переключает только админ: в `createGradeScale`/`updateGradeScale` у не-админа он принудительно сбрасывается/сохраняется как был, поэтому «общей» шкала становится только по решению админа. Аудит `grade_scale.create/update/delete`. Валидация (`normalizeScale`/`normalizeRanges`): 1..30 диапазонов, `max >= min`, подпись обязательна, имя уникально без учёта регистра **в рамках автора** (`assertUniqueName` сравнивает `created_by` через `IS NOT DISTINCT FROM`), картинка — `/uploads/<name>`. `saveQuiz` проверяет доступность выбранной шкалы через `gradeScaleAccessible` (своя или общая админская), иначе 400 «Критерий оценки не найден» — иначе тьютор мог бы привязать чужую приватную шкалу. Оценка считается по **набранным баллам** (`gradeForScore(ranges, score)` — первый диапазон, куда попал `score`; диапазоны сортируются по `min_score`, порядок строк в форме не важен) и возвращается в `result.grade` (`performSubmit`) и `grade` (`getAttempt`). UI — кнопка «Критерии оценки» на `public/quizzes.html` (видна всем) → модалка `#quizScalesModal`: список шкал с бейджем «Доступна всем», кнопки «Изменить»/«Удалить» только у своих/админских (`canManage` в `public/js/grade-scales.js`), галочка `#qsPublic` в редакторе видна только админу, редактор диапазонов (мин/макс/подпись) и картинка из уже загруженных (`listGradeImages` — UNION по doc/фото/ассетам) или загрузка новой. В конструкторе — селект «Критерий оценки» (`#qeGradeScale`) только у теста; оценка выводится на экране результата (`quiz.js`, `quiz-public.js`).
|
||||
- **Варианты в строку:** `quiz_questions.options_inline` (для `single`/`multiple`) — в конструкторе тумблер «Ответы в строку», на страницах прохождения варианты рендерятся в `.qz-opts.inline` (flex-wrap), по умолчанию — колонкой. На `select` не влияет.
|
||||
- **Права:** админ — всё; тьютор создаёт/правит только свои, проходит любые опубликованные. Мутации и `GET /stats` чужого теста — 403, чтение неопубликованного чужого — 404. Правильные ответы, веса и принимаемые ответы вырезаются (`stripAnswers`) для всех, кто не автор/админ; `min_length` и `options_inline` остаются (они нужны для рендера формы); при `show_results = false` разбор скрыт и в `GET .../attempts/:attemptId` (`revealed: false`). Критерии оценки (`/api/grade-scales*`) читает любой авторизованный (нужно для селекта в конструкторе), создаёт/правит/удаляет только админ.
|
||||
- **Права:** админ — всё; тьютор создаёт/правит только свои, проходит любые опубликованные. Мутации и `GET /stats` чужого теста — 403, чтение неопубликованного чужого — 404. Правильные ответы, веса и принимаемые ответы вырезаются (`stripAnswers`) для всех, кто не автор/админ; `min_length` и `options_inline` остаются (они нужны для рендера формы); при `show_results = false` разбор скрыт и в `GET .../attempts/:attemptId` (`revealed: false`). Критерии оценки (`/api/grade-scales*`) читает и создаёт любой авторизованный; правит/удаляет только автор шкалы или админ, а «Доступна всем» (общие шкалы админа) переключает только админ.
|
||||
- **Анонимные прохождения:** `allow_anonymous = true AND is_published AND deleted_at IS NULL` — и для `kind = 'test'`, и для `survey` (`normalizeMeta` не сбрасывает флаг у тестов). Публичная страница `public/quiz-public.html`, роуты `/api/public-quizzes/:id`, `/attempts`, `/attempts/:attemptId` (под `apiLimiter`) и `/files/:name` (под `fileLimiter`). Попытка — `user_id = NULL` + случайный `anon_token` (`crypto.randomBytes`), отправка требует совпадения токена (`crypto.timingSafeEqual`); в статистике/списке автор видит «Аноним» (`anonymous: true`). **Поле имени на публичной странице не выводится** (раньше это был `#qpName` на тестах): если автору нужно имя, он добавляет в конструкторе вопрос `line`/`text`. Серверный параметр `name` в `startPublicAttempt` и колонка `quiz_attempts.guest_name` сохранены для совместимости и уже сохранённых попыток; новые попытки с публичной страницы приходят без `guest_name`.
|
||||
- **Системные поля и код доступа:** `student`/`group`/`branch`/`module` — типы вопросов (`SYSTEM_FIELD_KINDS` в `lib/quizzes.js`), при прохождении это поле с подсказками по названию, а не полный список. Ответ хранится как название в `text_answer` + id в `quiz_attempt_answers.answer_id` (и `answer_snapshot.answer_id`), автооценки нет. Авторизованным подсказки даёт `GET /api/quizzes/system-options?field=&q=` (`requireAuth`, `quizLookupLimiter`, филиалы через `branchScope`), публичной ссылке — `GET /api/public-quizzes/:id/options?field=&q=&code=` (тот же `quizLookupLimiter`, только при совпадении `quizzes.access_code`, иначе 403). `module` ищет по справочнику `modules` (`is_active = true`), поэтому фильтр по филиалам к нему не применяется — темы модулей глобальные. `quizzes.access_code` (≤64, plain text) задаётся в конструкторе (`#qeAccessCode`); если в тесте есть системные поля и включён `allow_anonymous`, `saveQuiz` требует код (400), `POST /api/public-quizzes/:id/attempts` принимает `{ code }` и при неверном отвечает 403. `GET /api/public-quizzes/:id` отдаёт `requires_code` и `has_system_fields`, сам код не раскрывает; `getQuiz` возвращает `access_code` только автору/админу. Поиск — `ILIKE` с экранированием `%`/`_`, `LIMIT 20`; по ссылке подсказки ограничены филиалами автора (если автор — админ, видны все). UI: подсказки в `public/js/quiz.js` и `public/js/quiz-public.js` (debounce 250 мс, `.qz-suggest-wrap`/`.qz-suggest` в `admin.css`), в конструкторе — четыре системных пункта в списке типов и поле кода в блоке «Доступ по ссылке».
|
||||
- **Состояние попытки:** `POST /attempts` **продолжает** незавершённую попытку пользователя (`resumed: true`), а не создаёт новую; перезапуск — `POST /attempts/restart` (удаляет `in_progress` и создаёт новую). `in_progress` старше 2 суток чистит `cleanupQuizAssets`. Снимок вопроса/вариантов (`quiz_attempt_answers.question_text`, `answer_snapshot`) сохраняется, чтобы изменения структуры не ломали историю.
|
||||
- **Медиа-подписи:** `quiz_assets.caption` правится в конструкторе (поле под файлом) и сохраняется сразу через `PUT /api/quizzes/assets/:id`; подпись показывается под файлом на странице прохождения и в анонимном опросе.
|
||||
- **ИИ-генерация (опционально):** кнопка «Сгенерировать ИИ» на `public/quizzes.html` открывает `#quizAiModal` (промпт, тип, число вопросов, сложность, модель). `public/js/quizzes.js` собирает список моделей так же, как `public/js/shorts.js`: `GET /api/ai/profiles/options` + `feedback_models` из `GET /api/user-settings`. В списке `#quizAiModel` у всех ролей: «Нативная», optgroup «Мои модели» и optgroup «Системные» (эндпоинт `options` и резолв профилей доступны любому авторизованному). Список кэшируется в памяти страницы, поэтому повторное открытие модалки не показывает пустой селект; если оба запроса упали — статус честно пишет, что доступна только нативная, вместо молчаливого пустого списка. `POST /api/quizzes/ai-generate` (`requireAuth, aiLimiter`) вызывает `generateQuizDraft(...)` из `lib/quiz-ai.js`: профиль резолвит `resolveUserAiProfile` (личные модели → системные → native), запрос идёт через `aiComplete`. `extractJson` снимает markdown-обёртку, `normalizeDraft` приводит алиасы типов (`single_choice` и т.п.), строковые варианты и `is_correct`, гарантирует 2+ варианта и ровно один верный у `single`/`select` (первый, если модель забыла), у опроса обнуляет `is_correct`, собирает `accepted_answers`. Черновик создаётся `createQuiz` + `saveQuiz` (`is_published = false`) и открывается в `quiz-edit.html?id=`. Генерация идёт с таймаутом `QUIZ_AI_TIMEOUT_MS` (300 с) — он передаётся пятым аргументом `aiComplete(..., timeoutMs)`, по истечении модель отдаёт 504 с понятным текстом (обычный `AI_CALL_TIMEOUT_MS` = 120 с для 10 вопросов не хватает). Битый JSON/пустой ответ — 502, непрошедшая валидация — удаление пустого теста и 502. Пока идёт генерация, статус в модалке тикает секундами, а «Отмена»/Escape/клик по оверлею прерывают запрос (`AbortController`). Выключатель `quiz_ai_enabled` (сид в `db/init.sql` + `db/migration.sql`, валидация в `PUT /api/settings`, карточка `sec-quiz-ai` на `settings.html`) скрывает кнопку (`ai_enabled` в ответе `GET /api/quizzes`) и блокирует эндпоинт (403). Аудит `quiz.ai.generate`, затем `broadcastQuizzesChanged()`. Юнит-проверки — `node quiz-ai.selftest.js`.
|
||||
- **SSE:** отдельного канала нет — `broadcastQuizzesChanged()` публикует `{ type: 'quizzes_changed' }` в `EVENTS_CHANNEL`, ветка уже есть в `dispatchEvent`; слушает только список (`public/js/quizzes.js`). Redis-кэша у тестов нет.
|
||||
- **Описание — Markdown:** `quizzes.description` рендерится `public/js/md.js` (`WhatIDoMD.render`) на странице прохождения, в анонимном опросе и в предпросмотре конструктора; описания вопросов рендерятся так же, описания вариантов — через `WhatIDoMD.inline`. В карточке списка (`public/js/quizzes.js`) Markdown превращается в плоский текст (`mdPlain`), чтобы в двухстрочном превью не было разметки. ИИ-генерация просит модель заполнять `description` теста и пояснения к вопросам в Markdown (сам JSON — без markdown-обёртки).
|
||||
- **Soft-delete:** `deleted_at`/`purge_at` по `trashPurgeDays()`, своя корзина в списке (`?deleted=1`, не-admin только свои), физическая чистка — `purgeQuizzes()` из `purgeScheduledDeletions()`; возвращает пути всех ассетов и обложки, вызывающий делает `safeUnlink`. В общий `GET /api/trash` тесты не входят.
|
||||
- **Sweep/бэкап:** `quiz_assets.path`, `quizzes.cover_path` и `quiz_grade_ranges.image_path` обязаны быть в `sweepOrphanedUploads()` **и** `BROKEN_IMAGE_SOURCES`; все 8 таблиц (`quizzes`, `quiz_questions`, `quiz_options`, `quiz_assets`, `quiz_attempts`, `quiz_attempt_answers`, `quiz_grade_scales`, `quiz_grade_ranges`) входят в `BACKUP_TABLES`/`BACKUP_SEQUENCE_TABLES`, нормализуются в `normalizeRestoreData` (числа клампятся `quizInt`/`quizScore`, пути — `optUploadPath`, `accepted_answers` дедуплицируются, `show_answers`/`grade_scale_id` сохраняются, диапазоны без существующей шкалы отбрасываются, `anon_token` при восстановлении обнуляется) и восстанавливаются после `users`; шкалы и диапазоны — **до** `quizzes` (FK `grade_scale_id`), проверки — в `backup.selftest.js` и `quiz.selftest.js`.
|
||||
- **UI:** внутренние страницы (`quizzes.html` — список с корзиной и бейджем «Анонимный», кнопка «Критерии оценки» для админа (`public/js/grade-scales.js`), `quiz-edit.html` — конструктор с drag&drop `⠿`, Markdown-предпросмотром, анонимной ссылкой, принимаемыми ответами, мин. длиной ответа, тумблером «Ответы в строку», «Показывать ответы», селектом критерия оценки и подписями медиа, `quiz.html` — прохождение с продолжением попытки/«Начать заново», результаты и статистика) и публичная `quiz-public.html` (анонимный опрос без `admin.js`). Пункт сайдбара `quizzes` («Тесты и опросы», `clipboard-list`) — в `lib/sidebar.js` и `fallbackBase` в `public/admin.js`, `data-page="quizzes"`. Даты — только через `js/datetime.js`. Список (`public/js/quizzes.js`) не очищается на время запроса: старые карточки остаются с классом `.quiz-busy` и полоской `#quizBusy`, а предыдущий запрос отменяется `AbortController` с таймаутом `LOAD_TIMEOUT_MS` (15 с): по истечении индикатор гаснет и показывается ошибка с кнопкой «Повторить», зависнуть навсегда он не может (причина таких зависаний — исчерпание 6 слотов HTTP/1.1 постоянными SSE при многих открытых вкладках). Тумблер «Только мои» не делает запрос: он фильтрует уже загруженный список по `author_id` (`visibleItems()`), это тот же набор, что отдаёт сервер по `?mine=1`. Живое SSE страницы (`/api/events`) закрывается при `document.hidden` и переоткрывается с перезагрузкой списка — фоновые вкладки освобождают слот соединения.
|
||||
- **Sweep/бэкап:** `quiz_assets.path`, `quizzes.cover_path` и `quiz_grade_ranges.image_path` обязаны быть в `sweepOrphanedUploads()` **и** `BROKEN_IMAGE_SOURCES`; все 8 таблиц (`quizzes`, `quiz_questions`, `quiz_options`, `quiz_assets`, `quiz_attempts`, `quiz_attempt_answers`, `quiz_grade_scales`, `quiz_grade_ranges`) входят в `BACKUP_TABLES`/`BACKUP_SEQUENCE_TABLES`, нормализуются в `normalizeRestoreData` (числа клампятся `quizInt`/`quizScore`, пути — `optUploadPath`, `accepted_answers` дедуплицируются, `show_answers`/`grade_scale_id`/`is_shared` сохраняются, диапазоны без существующей шкалы отбрасываются, `anon_token` при восстановлении обнуляется, `access_code` и `answer_id` проходят в restore) и восстанавливаются после `users`; шкалы и диапазоны — **до** `quizzes` (FK `grade_scale_id`), проверки — в `backup.selftest.js` и `quiz.selftest.js`.
|
||||
- **UI:** внутренние страницы (`quizzes.html` — список с корзиной и бейджем «Анонимный», кнопка «Критерии оценки» для всех авторизованных (`public/js/grade-scales.js`), `quiz-edit.html` — конструктор с drag&drop `⠿`, Markdown-предпросмотром, анонимной ссылкой, принимаемыми ответами, мин. длиной ответа, тумблером «Ответы в строку», «Показывать ответы», селектом критерия оценки и подписями медиа; в карточке вопроса — живой бейдж «Макс. баллов» (сумма весов верных вариантов, для свободных ответов — вес вопроса), в шапке — «Всего баллов» (`updatePoints()` пересчитывает при вводе весов, смене верных вариантов и добавлении/удалении; поле веса вопроса показывается только у свободных ответов), `quiz.html` — прохождение с продолжением попытки/«Начать заново», результаты и статистика) и публичная `quiz-public.html` (анонимный опрос без `admin.js`). Пункт сайдбара `quizzes` («Тесты и опросы», `clipboard-list`) — в `lib/sidebar.js` и `fallbackBase` в `public/admin.js`, `data-page="quizzes"`. Даты — только через `js/datetime.js`. Список (`public/js/quizzes.js`) не очищается на время запроса: старые карточки остаются с классом `.quiz-busy` и полоской `#quizBusy`, а предыдущий запрос отменяется `AbortController` с таймаутом `LOAD_TIMEOUT_MS` (15 с): по истечении индикатор гаснет и показывается ошибка с кнопкой «Повторить», зависнуть навсегда он не может (причина таких зависаний — исчерпание 6 слотов HTTP/1.1 постоянными SSE при многих открытых вкладках). Тумблер «Только мои» не делает запрос: он фильтрует уже загруженный список по `author_id` (`visibleItems()`), это тот же набор, что отдаёт сервер по `?mine=1`. Живое SSE страницы (`/api/events`) закрывается при `document.hidden` и переоткрывается с перезагрузкой списка — фоновые вкладки освобождают слот соединения.
|
||||
|
||||
### 4. API Patterns
|
||||
- **Middleware**: `requireAuth` — читает `X-Auth-Token`, 401 без валидной активной сессии. `requireAdmin` — самодостаточный (внутри вызывает `requireAuth`, если `req.user` ещё нет), 403 при `role !== 'admin'`. `optionalAuth` — для публичных страниц с персонализацией
|
||||
|
||||
+5
-1
@@ -853,7 +853,7 @@ function normalizeRestoreData(data) {
|
||||
updated_at: optTs(x.updated_at),
|
||||
})).filter(x => x.source_id && x.photo_path);
|
||||
const quizKinds = ['test', 'survey'];
|
||||
const quizQuestionKinds = ['single', 'multiple', 'select', 'line', 'text', 'number', 'date'];
|
||||
const quizQuestionKinds = ['single', 'multiple', 'select', 'line', 'text', 'number', 'date', 'student', 'group', 'branch'];
|
||||
const quizWeight = v => Math.min(100, Math.max(0, Math.round((Number(v) || 0) * 100) / 100));
|
||||
const quizAssetKinds = ['image', 'audio', 'video', 'file'];
|
||||
const quizInt = (v, lo, hi, def = null) => {
|
||||
@@ -868,6 +868,7 @@ function normalizeRestoreData(data) {
|
||||
name: optText(x.name, 200) || '',
|
||||
description: optText(x.description, 2000) || null,
|
||||
sort_order: optInt(x.sort_order, -100000, 100000) ?? 0,
|
||||
is_shared: x.is_shared === true,
|
||||
created_by: x.created_by == null ? null : reqInt(x.created_by),
|
||||
created_at: optTs(x.created_at),
|
||||
updated_at: optTs(x.updated_at),
|
||||
@@ -896,9 +897,11 @@ function normalizeRestoreData(data) {
|
||||
grade_scale_id: x.grade_scale_id == null ? null : reqInt(x.grade_scale_id),
|
||||
max_attempts: quizInt(x.max_attempts, 1, 1000),
|
||||
time_limit_min: quizInt(x.time_limit_min, 0, 1440, 0),
|
||||
retry_cooldown_min: quizInt(x.retry_cooldown_min, 0, 10080, 0),
|
||||
pass_percent: quizInt(x.pass_percent, 0, 100, 60),
|
||||
cover_path: optUploadPath(x.cover_path, 300) || null,
|
||||
allow_anonymous: x.allow_anonymous === true,
|
||||
access_code: optText(x.access_code, 64) || null,
|
||||
author_id: x.author_id == null ? null : reqInt(x.author_id),
|
||||
created_at: optTs(x.created_at),
|
||||
updated_at: optTs(x.updated_at),
|
||||
@@ -984,6 +987,7 @@ function normalizeRestoreData(data) {
|
||||
option_ids: Array.isArray(x.option_ids) ? x.option_ids.map(Number).filter(n => Number.isInteger(n) && n > 0).slice(0, 25) : [],
|
||||
answer_snapshot: x.answer_snapshot && typeof x.answer_snapshot === 'object' && !Array.isArray(x.answer_snapshot) ? x.answer_snapshot : {},
|
||||
text_answer: optText(x.text_answer, 2000) || null,
|
||||
answer_id: x.answer_id == null ? null : quizInt(x.answer_id, 1, 1000000000),
|
||||
is_correct: x.is_correct == null ? null : x.is_correct === true,
|
||||
score: quizWeight(x.score),
|
||||
max_score: quizWeight(x.max_score),
|
||||
|
||||
+6
-3
@@ -330,12 +330,12 @@ ok('quizzes входят в бэкап и sequences',
|
||||
const quizRestore = normalizeRestoreData({
|
||||
...base,
|
||||
quizzes: [
|
||||
{ id: 1, title: 'Тест', kind: 'test', pass_percent: 150, max_attempts: 0, time_limit_min: -5, cover_path: '/uploads/cover.jpg', deleted_at: '2026-11-24T07:00:00.000Z', purge_at: '2026-12-24T07:00:00.000Z' },
|
||||
{ id: 2, kind: 'survey', title: 'Опрос', allow_anonymous: true },
|
||||
{ id: 1, title: 'Тест', kind: 'test', pass_percent: 150, max_attempts: 0, time_limit_min: -5, retry_cooldown_min: 45, cover_path: '/uploads/cover.jpg', deleted_at: '2026-11-24T07:00:00.000Z', purge_at: '2026-12-24T07:00:00.000Z' },
|
||||
{ id: 2, kind: 'survey', title: 'Опрос', allow_anonymous: true, retry_cooldown_min: -5 },
|
||||
{ id: 3, kind: 'test', title: 'Тест 2', allow_anonymous: true, show_answers: false, grade_scale_id: 5 },
|
||||
],
|
||||
quiz_grade_scales: [
|
||||
{ id: 5, name: 'Шкала на 15 баллов', description: 'Описание', sort_order: 3, created_by: 1 },
|
||||
{ id: 5, name: 'Шкала на 15 баллов', description: 'Описание', sort_order: 3, is_shared: true, created_by: 1 },
|
||||
{ id: 0, name: 'Битая', sort_order: 0 },
|
||||
],
|
||||
quiz_grade_ranges: [
|
||||
@@ -365,6 +365,8 @@ ok('quizzes нормализуются: тип/порог/попытки/пут
|
||||
quizRestore.quizzes[0].pass_percent === 100 &&
|
||||
quizRestore.quizzes[0].max_attempts === 1 &&
|
||||
quizRestore.quizzes[0].time_limit_min === 0 &&
|
||||
quizRestore.quizzes[0].retry_cooldown_min === 45 &&
|
||||
quizRestore.quizzes[1].retry_cooldown_min === 0 &&
|
||||
quizRestore.quizzes[0].deleted_at === '2026-11-24T07:00:00.000Z' &&
|
||||
quizRestore.quizzes[1].kind === 'survey' &&
|
||||
quizRestore.quizzes[1].allow_anonymous === true &&
|
||||
@@ -373,6 +375,7 @@ ok('quizzes нормализуются: тип/порог/попытки/пут
|
||||
quizRestore.quizzes[2].grade_scale_id === 5 &&
|
||||
quizRestore.quiz_grade_scales.length === 1 &&
|
||||
quizRestore.quiz_grade_scales[0].sort_order === 3 &&
|
||||
quizRestore.quiz_grade_scales[0].is_shared === true &&
|
||||
quizRestore.quiz_grade_scales[0].created_by === 1 &&
|
||||
quizRestore.quiz_grade_ranges.length === 1 &&
|
||||
quizRestore.quiz_grade_ranges[0].scale_id === 5 &&
|
||||
|
||||
+6
-2
@@ -918,6 +918,7 @@ CREATE TABLE IF NOT EXISTS quiz_grade_scales (
|
||||
name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
is_shared BOOLEAN NOT NULL DEFAULT false,
|
||||
created_by INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
@@ -948,9 +949,11 @@ CREATE TABLE IF NOT EXISTS quizzes (
|
||||
show_answers BOOLEAN NOT NULL DEFAULT true,
|
||||
max_attempts INT,
|
||||
time_limit_min INT NOT NULL DEFAULT 0,
|
||||
retry_cooldown_min INT NOT NULL DEFAULT 0,
|
||||
pass_percent INT NOT NULL DEFAULT 60,
|
||||
cover_path TEXT,
|
||||
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
|
||||
access_code VARCHAR(64),
|
||||
grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL,
|
||||
author_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -966,7 +969,7 @@ CREATE TABLE IF NOT EXISTS quiz_questions (
|
||||
kind VARCHAR(16) NOT NULL DEFAULT 'single',
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
partial_credit BOOLEAN NOT NULL DEFAULT false,
|
||||
required BOOLEAN NOT NULL DEFAULT true,
|
||||
min_length INT NOT NULL DEFAULT 0,
|
||||
@@ -984,7 +987,7 @@ CREATE TABLE IF NOT EXISTS quiz_options (
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
is_correct BOOLEAN NOT NULL DEFAULT false,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -1029,6 +1032,7 @@ CREATE TABLE IF NOT EXISTS quiz_attempt_answers (
|
||||
option_ids INT[] NOT NULL DEFAULT '{}',
|
||||
answer_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
text_answer TEXT,
|
||||
answer_id INT,
|
||||
is_correct BOOLEAN,
|
||||
score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
max_score NUMERIC(8,2) NOT NULL DEFAULT 0
|
||||
|
||||
+12
-2
@@ -1207,6 +1207,7 @@ CREATE TABLE IF NOT EXISTS quiz_grade_scales (
|
||||
name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
is_shared BOOLEAN NOT NULL DEFAULT false,
|
||||
created_by INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
@@ -1237,9 +1238,11 @@ CREATE TABLE IF NOT EXISTS quizzes (
|
||||
show_answers BOOLEAN NOT NULL DEFAULT true,
|
||||
max_attempts INT,
|
||||
time_limit_min INT NOT NULL DEFAULT 0,
|
||||
retry_cooldown_min INT NOT NULL DEFAULT 0,
|
||||
pass_percent INT NOT NULL DEFAULT 60,
|
||||
cover_path TEXT,
|
||||
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
|
||||
access_code VARCHAR(64),
|
||||
grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL,
|
||||
author_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -1255,7 +1258,7 @@ CREATE TABLE IF NOT EXISTS quiz_questions (
|
||||
kind VARCHAR(16) NOT NULL DEFAULT 'single',
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
partial_credit BOOLEAN NOT NULL DEFAULT false,
|
||||
required BOOLEAN NOT NULL DEFAULT true,
|
||||
min_length INT NOT NULL DEFAULT 0,
|
||||
@@ -1273,7 +1276,7 @@ CREATE TABLE IF NOT EXISTS quiz_options (
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
is_correct BOOLEAN NOT NULL DEFAULT false,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -1317,13 +1320,19 @@ CREATE TABLE IF NOT EXISTS quiz_attempt_answers (
|
||||
option_ids INT[] NOT NULL DEFAULT '{}',
|
||||
answer_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
text_answer TEXT,
|
||||
answer_id INT,
|
||||
is_correct BOOLEAN,
|
||||
score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
max_score NUMERIC(8,2) NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
ALTER TABLE quiz_grade_scales ADD COLUMN IF NOT EXISTS is_shared BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE quiz_questions ALTER COLUMN weight SET DEFAULT 0;
|
||||
ALTER TABLE quiz_options ALTER COLUMN weight SET DEFAULT 0;
|
||||
ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS allow_anonymous BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS access_code VARCHAR(64);
|
||||
ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS show_answers BOOLEAN NOT NULL DEFAULT true;
|
||||
ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS retry_cooldown_min INT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL;
|
||||
ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS text_match VARCHAR(16) NOT NULL DEFAULT 'exact';
|
||||
ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS accepted_answers TEXT[] NOT NULL DEFAULT '{}';
|
||||
@@ -1331,6 +1340,7 @@ ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS min_length INT NOT NULL DEFA
|
||||
ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS options_inline BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE quiz_attempts ADD COLUMN IF NOT EXISTS anon_token TEXT;
|
||||
ALTER TABLE quiz_attempts ADD COLUMN IF NOT EXISTS guest_name TEXT;
|
||||
ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS answer_id INT;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_quizzes_author ON quizzes(author_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_quizzes_kind ON quizzes(kind, is_published);
|
||||
|
||||
+18
-17
@@ -3,8 +3,6 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const storage = require('../storage');
|
||||
|
||||
const UPLOADS_DIR = path.join(__dirname, '..', 'uploads');
|
||||
const THUMBS_DIR = path.join(UPLOADS_DIR, '.thumbs');
|
||||
|
||||
@@ -18,20 +16,24 @@ function thumbUnlinkFor(key) {
|
||||
try { if (fs.existsSync(tp)) fs.unlinkSync(tp); } catch {}
|
||||
}
|
||||
|
||||
function safeUnlink(relPath) {
|
||||
const key = storage.keyFromPath(relPath);
|
||||
if (!key) return;
|
||||
storage.unlinkLocalOnly(key);
|
||||
if (!storage.isRemote()) return;
|
||||
storage.del(key).catch(err => console.error('Upload delete failed:', key, err.message));
|
||||
}
|
||||
|
||||
function unlinkMedia(list) {
|
||||
for (const p of list || []) {
|
||||
if (!p) continue;
|
||||
safeUnlink(p);
|
||||
thumbUnlinkFor(p);
|
||||
function createFileTools(storage) {
|
||||
function safeUnlink(relPath) {
|
||||
const key = storage.keyFromPath(relPath);
|
||||
if (!key) return;
|
||||
storage.unlinkLocalOnly(key);
|
||||
if (!storage.isRemote()) return;
|
||||
storage.del(key).catch(err => console.error('Upload delete failed:', key, err.message));
|
||||
}
|
||||
|
||||
function unlinkMedia(list) {
|
||||
for (const p of list || []) {
|
||||
if (!p) continue;
|
||||
safeUnlink(p);
|
||||
thumbUnlinkFor(p);
|
||||
}
|
||||
}
|
||||
|
||||
return { safeUnlink, unlinkMedia };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
@@ -39,6 +41,5 @@ module.exports = {
|
||||
THUMBS_DIR,
|
||||
thumbFileFor,
|
||||
thumbUnlinkFor,
|
||||
safeUnlink,
|
||||
unlinkMedia,
|
||||
createFileTools,
|
||||
};
|
||||
|
||||
+1
-1
@@ -209,7 +209,7 @@ function normOptions(raw) {
|
||||
const key = text.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
options.push({ text, is_correct: source.is_correct === true || source.is_correct === 'true' || source.correct === true || source.correct === 'true' });
|
||||
options.push({ text, is_correct: source.is_correct === true || source.is_correct === 'true' || source.correct === true || source.correct === 'true', weight: 1 });
|
||||
if (options.length >= QUIZ_OPTIONS_MAX) break;
|
||||
}
|
||||
return options;
|
||||
|
||||
+61
-18
@@ -83,6 +83,7 @@ function scaleToJson(row, ranges) {
|
||||
name: row.name,
|
||||
description: row.description || null,
|
||||
sort_order: row.sort_order,
|
||||
is_shared: row.is_shared === true,
|
||||
created_by: row.created_by,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
@@ -96,10 +97,12 @@ async function ensureQuizGradeTables(pool) {
|
||||
name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
is_shared BOOLEAN NOT NULL DEFAULT false,
|
||||
created_by INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`);
|
||||
await pool.query('ALTER TABLE quiz_grade_scales ADD COLUMN IF NOT EXISTS is_shared BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_grade_ranges (
|
||||
id SERIAL PRIMARY KEY,
|
||||
scale_id INT NOT NULL REFERENCES quiz_grade_scales(id) ON DELETE CASCADE,
|
||||
@@ -113,13 +116,21 @@ async function ensureQuizGradeTables(pool) {
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_grade_ranges_scale ON quiz_grade_ranges(scale_id)');
|
||||
}
|
||||
|
||||
async function listGradeScales(pool) {
|
||||
async function listGradeScales(pool, user) {
|
||||
const isAdmin = user && user.role === 'admin';
|
||||
const where = isAdmin
|
||||
? ''
|
||||
: ` WHERE (s.created_by = $1 OR (s.is_shared = TRUE AND EXISTS (
|
||||
SELECT 1 FROM users u WHERE u.id = s.created_by AND u.role = 'admin')))`;
|
||||
const params = isAdmin ? [] : [user ? user.id : 0];
|
||||
const { rows: scales } = await pool.query(
|
||||
'SELECT * FROM quiz_grade_scales ORDER BY sort_order ASC, id ASC'
|
||||
`SELECT s.* FROM quiz_grade_scales s${where} ORDER BY s.sort_order ASC, s.id ASC`,
|
||||
params
|
||||
);
|
||||
if (!scales.length) return [];
|
||||
const { rows: ranges } = await pool.query(
|
||||
'SELECT * FROM quiz_grade_ranges ORDER BY scale_id ASC, min_score ASC, id ASC'
|
||||
'SELECT * FROM quiz_grade_ranges WHERE scale_id = ANY($1::int[]) ORDER BY scale_id ASC, min_score ASC, id ASC',
|
||||
[scales.map(s => s.id)]
|
||||
);
|
||||
const map = new Map();
|
||||
for (const r of ranges) {
|
||||
@@ -139,14 +150,43 @@ async function getGradeScale(pool, id) {
|
||||
return scaleToJson(rows[0], ranges.map(rangeToJson));
|
||||
}
|
||||
|
||||
async function assertUniqueName(client, name, excludeId) {
|
||||
async function assertUniqueName(client, name, excludeId, ownerId) {
|
||||
const { rows } = await client.query(
|
||||
'SELECT id FROM quiz_grade_scales WHERE lower(name) = lower($1) AND id <> $2 LIMIT 1',
|
||||
[name, excludeId || 0]
|
||||
'SELECT id FROM quiz_grade_scales WHERE lower(name) = lower($1) AND id <> $2 AND created_by IS NOT DISTINCT FROM $3 LIMIT 1',
|
||||
[name, excludeId || 0, ownerId == null ? null : ownerId]
|
||||
);
|
||||
if (rows.length) throw gradeError(400, 'Критерий с таким названием уже есть');
|
||||
}
|
||||
|
||||
async function loadScaleForWrite(client, id, user) {
|
||||
const { rows } = await client.query(
|
||||
`SELECT s.id, s.created_by, s.is_shared, u.role AS owner_role
|
||||
FROM quiz_grade_scales s LEFT JOIN users u ON u.id = s.created_by
|
||||
WHERE s.id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (!rows.length) throw gradeError(404, 'Критерий оценки не найден');
|
||||
const row = rows[0];
|
||||
const isAdmin = user && user.role === 'admin';
|
||||
const isOwner = user && row.created_by != null && Number(row.created_by) === Number(user.id);
|
||||
if (!isAdmin && !isOwner) throw gradeError(403, 'Изменять можно только свои критерии оценки');
|
||||
return row;
|
||||
}
|
||||
|
||||
async function gradeScaleAccessible(pool, id, user) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT s.created_by, s.is_shared, u.role AS owner_role
|
||||
FROM quiz_grade_scales s LEFT JOIN users u ON u.id = s.created_by
|
||||
WHERE s.id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (!rows.length) return false;
|
||||
if (user && user.role === 'admin') return true;
|
||||
const row = rows[0];
|
||||
if (user && row.created_by != null && Number(row.created_by) === Number(user.id)) return true;
|
||||
return row.is_shared === true && row.owner_role === 'admin';
|
||||
}
|
||||
|
||||
async function insertRanges(client, scaleId, ranges) {
|
||||
for (const r of ranges) {
|
||||
await client.query(
|
||||
@@ -170,13 +210,14 @@ async function unusedImages(client, candidates) {
|
||||
|
||||
async function createGradeScale(pool, user, body = {}) {
|
||||
const data = normalizeScale(body);
|
||||
const isShared = user.role === 'admin' && body.is_shared === true;
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await assertUniqueName(client, data.name, 0);
|
||||
await assertUniqueName(client, data.name, 0, user.id);
|
||||
const { rows } = await client.query(
|
||||
'INSERT INTO quiz_grade_scales (name, description, sort_order, created_by) VALUES ($1,$2,$3,$4) RETURNING *',
|
||||
[data.name, data.description, data.sort_order, user.id]
|
||||
'INSERT INTO quiz_grade_scales (name, description, sort_order, is_shared, created_by) VALUES ($1,$2,$3,$4,$5) RETURNING *',
|
||||
[data.name, data.description, data.sort_order, isShared, user.id]
|
||||
);
|
||||
await insertRanges(client, rows[0].id, data.ranges);
|
||||
await client.query('COMMIT');
|
||||
@@ -189,22 +230,24 @@ async function createGradeScale(pool, user, body = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
async function updateGradeScale(pool, id, body = {}) {
|
||||
async function updateGradeScale(pool, id, user, body = {}) {
|
||||
const data = normalizeScale(body);
|
||||
const client = await pool.connect();
|
||||
let removed = [];
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const { rows: existing } = await client.query('SELECT id FROM quiz_grade_scales WHERE id = $1', [id]);
|
||||
if (!existing.length) throw gradeError(404, 'Критерий оценки не найден');
|
||||
await assertUniqueName(client, data.name, id);
|
||||
const existing = await loadScaleForWrite(client, id, user);
|
||||
await assertUniqueName(client, data.name, id, existing.created_by);
|
||||
const isShared = user.role === 'admin'
|
||||
? (body.is_shared === undefined ? existing.is_shared === true : body.is_shared === true)
|
||||
: existing.is_shared === true;
|
||||
const { rows: oldRanges } = await client.query(
|
||||
'SELECT image_path FROM quiz_grade_ranges WHERE scale_id = $1',
|
||||
[id]
|
||||
);
|
||||
await client.query(
|
||||
'UPDATE quiz_grade_scales SET name = $2, description = $3, sort_order = $4, updated_at = now() WHERE id = $1',
|
||||
[id, data.name, data.description, data.sort_order]
|
||||
'UPDATE quiz_grade_scales SET name = $2, description = $3, sort_order = $4, is_shared = $5, updated_at = now() WHERE id = $1',
|
||||
[id, data.name, data.description, data.sort_order, isShared]
|
||||
);
|
||||
await client.query('DELETE FROM quiz_grade_ranges WHERE scale_id = $1', [id]);
|
||||
await insertRanges(client, id, data.ranges);
|
||||
@@ -219,12 +262,11 @@ async function updateGradeScale(pool, id, body = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteGradeScale(pool, id) {
|
||||
async function deleteGradeScale(pool, id, user) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const { rows: existing } = await client.query('SELECT id FROM quiz_grade_scales WHERE id = $1', [id]);
|
||||
if (!existing.length) throw gradeError(404, 'Критерий оценки не найден');
|
||||
await loadScaleForWrite(client, id, user);
|
||||
const { rows: oldRanges } = await client.query(
|
||||
'SELECT image_path FROM quiz_grade_ranges WHERE scale_id = $1',
|
||||
[id]
|
||||
@@ -289,6 +331,7 @@ module.exports = {
|
||||
createGradeScale,
|
||||
updateGradeScale,
|
||||
deleteGradeScale,
|
||||
gradeScaleAccessible,
|
||||
gradeForScore,
|
||||
listGradeImages,
|
||||
};
|
||||
|
||||
+167
-31
@@ -1,12 +1,15 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const { ensureQuizGradeTables, gradeForScore } = require('./quiz-grades');
|
||||
const { ensureQuizGradeTables, gradeForScore, gradeScaleAccessible } = require('./quiz-grades');
|
||||
|
||||
const QUIZ_KINDS = new Set(['test', 'survey']);
|
||||
const QUESTION_KINDS = new Set(['single', 'multiple', 'select', 'line', 'text', 'number', 'date']);
|
||||
const QUESTION_KINDS = new Set(['single', 'multiple', 'select', 'line', 'text', 'number', 'date', 'student', 'group', 'branch', 'module']);
|
||||
const OPTION_KINDS = new Set(['single', 'multiple', 'select']);
|
||||
const FREE_KINDS = new Set(['line', 'text', 'number', 'date']);
|
||||
const SYSTEM_FIELD_KINDS = new Set(['student', 'group', 'branch', 'module']);
|
||||
const SYSTEM_FIELD_LABELS = { student: 'Ученик', group: 'Группа', branch: 'Филиал', module: 'Тема модуля' };
|
||||
const QUIZ_ACCESS_CODE_MAX = 64;
|
||||
const QUIZ_TITLE_MAX = 200;
|
||||
const QUIZ_DESCRIPTION_MAX = 20000;
|
||||
const QUIZ_TEXT_MAX = 5000;
|
||||
@@ -19,6 +22,7 @@ const QUIZ_ASSETS_MAX = 10;
|
||||
const QUIZ_WEIGHT_MAX = 100;
|
||||
const QUIZ_MAX_ATTEMPTS_MAX = 1000;
|
||||
const QUIZ_TIME_LIMIT_MAX = 1440;
|
||||
const QUIZ_RETRY_COOLDOWN_MAX = 10080;
|
||||
const QUIZ_ATTEMPT_ANSWERS_MAX = 500;
|
||||
const QUIZ_ACCEPTED_MAX = 50;
|
||||
const QUIZ_ACCEPTED_LEN = 200;
|
||||
@@ -94,6 +98,32 @@ function normalizeQuestionKind(v) {
|
||||
return QUESTION_KINDS.has(v) ? v : 'single';
|
||||
}
|
||||
|
||||
function isFreeKind(kind) {
|
||||
return FREE_KINDS.has(kind) || SYSTEM_FIELD_KINDS.has(kind);
|
||||
}
|
||||
|
||||
function accessCodeValue(raw) {
|
||||
if (raw == null) return null;
|
||||
const value = String(raw).replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
if (!value) return null;
|
||||
if (value.length > QUIZ_ACCESS_CODE_MAX) {
|
||||
throw httpError(400, `Код доступа: максимум ${QUIZ_ACCESS_CODE_MAX} символов`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function accessCodeMatches(expected, given) {
|
||||
if (!expected) return true;
|
||||
const a = crypto.createHash('sha256').update(String(expected), 'utf8').digest();
|
||||
const b = crypto.createHash('sha256').update(String(given == null ? '' : given), 'utf8').digest();
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
function normalizeAnswerId(value) {
|
||||
const n = Number(value);
|
||||
return Number.isInteger(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
function normalizeAnswerText(v) {
|
||||
return String(v == null ? '' : v)
|
||||
.toLowerCase()
|
||||
@@ -159,9 +189,11 @@ async function ensureQuizTables(pool) {
|
||||
show_answers BOOLEAN NOT NULL DEFAULT true,
|
||||
max_attempts INT,
|
||||
time_limit_min INT NOT NULL DEFAULT 0,
|
||||
retry_cooldown_min INT NOT NULL DEFAULT 0,
|
||||
pass_percent INT NOT NULL DEFAULT 60,
|
||||
cover_path TEXT,
|
||||
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
|
||||
access_code VARCHAR(64),
|
||||
grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL,
|
||||
author_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -176,9 +208,11 @@ async function ensureQuizTables(pool) {
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS show_answers BOOLEAN NOT NULL DEFAULT true');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS max_attempts INT');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS time_limit_min INT NOT NULL DEFAULT 0');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS retry_cooldown_min INT NOT NULL DEFAULT 0');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS pass_percent INT NOT NULL DEFAULT 60');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS cover_path TEXT');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS allow_anonymous BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS access_code VARCHAR(64)');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ');
|
||||
@@ -189,7 +223,7 @@ async function ensureQuizTables(pool) {
|
||||
kind VARCHAR(16) NOT NULL DEFAULT 'single',
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
partial_credit BOOLEAN NOT NULL DEFAULT false,
|
||||
required BOOLEAN NOT NULL DEFAULT true,
|
||||
min_length INT NOT NULL DEFAULT 0,
|
||||
@@ -201,7 +235,8 @@ async function ensureQuizTables(pool) {
|
||||
)`);
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS kind VARCHAR(16) NOT NULL DEFAULT \'single\'');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS description TEXT');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS weight NUMERIC(6,2) NOT NULL DEFAULT 1');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS weight NUMERIC(6,2) NOT NULL DEFAULT 0');
|
||||
await pool.query('ALTER TABLE quiz_questions ALTER COLUMN weight SET DEFAULT 0');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS partial_credit BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS required BOOLEAN NOT NULL DEFAULT true');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS text_match VARCHAR(16) NOT NULL DEFAULT \'exact\'');
|
||||
@@ -215,13 +250,14 @@ async function ensureQuizTables(pool) {
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
is_correct BOOLEAN NOT NULL DEFAULT false,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
|
||||
weight NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`);
|
||||
await pool.query('ALTER TABLE quiz_options ADD COLUMN IF NOT EXISTS description TEXT');
|
||||
await pool.query('ALTER TABLE quiz_options ADD COLUMN IF NOT EXISTS is_correct BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quiz_options ADD COLUMN IF NOT EXISTS weight NUMERIC(6,2) NOT NULL DEFAULT 1');
|
||||
await pool.query('ALTER TABLE quiz_options ADD COLUMN IF NOT EXISTS weight NUMERIC(6,2) NOT NULL DEFAULT 0');
|
||||
await pool.query('ALTER TABLE quiz_options ALTER COLUMN weight SET DEFAULT 0');
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_assets (
|
||||
id SERIAL PRIMARY KEY,
|
||||
quiz_id INT REFERENCES quizzes(id) ON DELETE CASCADE,
|
||||
@@ -270,12 +306,14 @@ async function ensureQuizTables(pool) {
|
||||
option_ids INT[] NOT NULL DEFAULT '{}',
|
||||
answer_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
text_answer TEXT,
|
||||
answer_id INT,
|
||||
is_correct BOOLEAN,
|
||||
score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
max_score NUMERIC(8,2) NOT NULL DEFAULT 0
|
||||
)`);
|
||||
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS question_text TEXT NOT NULL DEFAULT \'\'');
|
||||
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS answer_snapshot JSONB NOT NULL DEFAULT \'{}\'::jsonb');
|
||||
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS answer_id INT');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_author ON quizzes(author_id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_kind ON quizzes(kind, is_published)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_purge ON quizzes(purge_at) WHERE purge_at IS NOT NULL');
|
||||
@@ -415,9 +453,11 @@ function quizMeta(row) {
|
||||
show_answers: row.show_answers !== false,
|
||||
max_attempts: row.max_attempts,
|
||||
time_limit_min: row.time_limit_min,
|
||||
retry_cooldown_min: Number(row.retry_cooldown_min) || 0,
|
||||
pass_percent: row.pass_percent,
|
||||
cover_path: row.cover_path,
|
||||
allow_anonymous: row.allow_anonymous === true,
|
||||
requires_code: !!(row.access_code && String(row.access_code).trim()),
|
||||
grade_scale_id: row.grade_scale_id == null ? null : Number(row.grade_scale_id),
|
||||
author_id: row.author_id,
|
||||
created_at: row.created_at,
|
||||
@@ -522,7 +562,11 @@ async function getQuiz(pool, id, user, opts = {}) {
|
||||
authorName = u.rows[0]?.name || null;
|
||||
}
|
||||
return {
|
||||
quiz: { ...quizMeta(row), author_name: authorName },
|
||||
quiz: {
|
||||
...quizMeta(row),
|
||||
author_name: authorName,
|
||||
access_code: editable ? (row.access_code || '') : null,
|
||||
},
|
||||
quiz_assets: structure.quiz_assets,
|
||||
questions: structure.questions,
|
||||
my_attempts: att.rows.map(r => ({
|
||||
@@ -544,6 +588,7 @@ function normalizeMeta(body, current) {
|
||||
const description = textValue(body.description, QUIZ_DESCRIPTION_MAX, 'Описание', false);
|
||||
const passPercent = intValue(body.pass_percent, 0, 100, 'порог сдачи');
|
||||
const timeLimit = intValue(body.time_limit_min, 0, QUIZ_TIME_LIMIT_MAX, 'лимит времени');
|
||||
const retryCooldown = intValue(body.retry_cooldown_min, 0, QUIZ_RETRY_COOLDOWN_MAX, 'интервал повтора');
|
||||
const maxAttempts = intValue(body.max_attempts, 1, QUIZ_MAX_ATTEMPTS_MAX, 'число попыток');
|
||||
const gradeScaleId = intValue(body.grade_scale_id, 1, 1000000000, 'критерий оценки');
|
||||
let coverPath = current.cover_path;
|
||||
@@ -553,6 +598,9 @@ function normalizeMeta(body, current) {
|
||||
else if (typeof raw === 'string' && /^\/uploads\/[\w,.()-]+$/.test(raw)) coverPath = raw;
|
||||
else throw httpError(400, 'Неверный путь к обложке');
|
||||
}
|
||||
const accessCode = body.access_code === undefined
|
||||
? (current.access_code == null ? null : accessCodeValue(current.access_code))
|
||||
: accessCodeValue(body.access_code);
|
||||
return {
|
||||
kind,
|
||||
title,
|
||||
@@ -568,8 +616,10 @@ function normalizeMeta(body, current) {
|
||||
: (body.grade_scale_id === undefined ? (current.grade_scale_id == null ? null : Number(current.grade_scale_id)) : gradeScaleId),
|
||||
max_attempts: maxAttempts,
|
||||
time_limit_min: timeLimit == null ? current.time_limit_min : timeLimit,
|
||||
retry_cooldown_min: retryCooldown == null ? (Number(current.retry_cooldown_min) || 0) : retryCooldown,
|
||||
pass_percent: passPercent == null ? current.pass_percent : passPercent,
|
||||
cover_path: coverPath,
|
||||
access_code: accessCode,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -578,16 +628,17 @@ function validateQuestion(q, quizKind, index) {
|
||||
const kind = normalizeQuestionKind(q.kind);
|
||||
const text = textValue(q.text, QUIZ_TEXT_MAX, `${label}: текст`, true);
|
||||
const description = textValue(q.description, QUIZ_DESC_MAX, `${label}: описание`, false);
|
||||
const weight = quizKind === 'test' ? numWeight(q.weight, 1) : 1;
|
||||
const weight = quizKind === 'test' ? numWeight(q.weight, 0) : 1;
|
||||
const required = asBool(q.required, true);
|
||||
const free = FREE_KINDS.has(kind);
|
||||
const free = isFreeKind(kind);
|
||||
const plainFree = FREE_KINDS.has(kind);
|
||||
const minLength = required && (kind === 'line' || kind === 'text')
|
||||
? (intValue(q.min_length, 0, QUIZ_ANSWER_MAX, 'минимальная длина ответа') ?? 0)
|
||||
: 0;
|
||||
const optionsInline = !free && asBool(q.options_inline, false);
|
||||
const partialCredit = quizKind === 'test' && kind === 'multiple' && asBool(q.partial_credit, false);
|
||||
const textMatch = free ? normalizeTextMatch(q.text_match) : 'exact';
|
||||
const acceptedAnswers = free && quizKind === 'test'
|
||||
const textMatch = plainFree ? normalizeTextMatch(q.text_match) : 'exact';
|
||||
const acceptedAnswers = plainFree && quizKind === 'test'
|
||||
? normalizeAcceptedAnswers(q.accepted_answers)
|
||||
: [];
|
||||
const rawOptions = free || !Array.isArray(q.options) ? [] : q.options.slice(0, QUIZ_OPTIONS_MAX);
|
||||
@@ -601,7 +652,7 @@ function validateQuestion(q, quizKind, index) {
|
||||
text: textValue(o.text, QUIZ_TEXT_MAX, `${olabel}: текст`, true),
|
||||
description: textValue(o.description, QUIZ_DESC_MAX, `${olabel}: описание`, false) || null,
|
||||
is_correct: quizKind === 'test' ? asBool(o.is_correct, false) : false,
|
||||
weight: quizKind === 'test' ? numWeight(o.weight, 1) : 1,
|
||||
weight: quizKind === 'test' ? numWeight(o.weight, 0) : 1,
|
||||
asset_ids: normalizeIdList(o.asset_ids, QUIZ_ASSETS_MAX),
|
||||
};
|
||||
});
|
||||
@@ -689,7 +740,7 @@ async function saveQuestionOptions(client, quizId, user, questionId, q, removedP
|
||||
const { rows: existing } = await client.query('SELECT id FROM quiz_options WHERE question_id = $1', [questionId]);
|
||||
const existingIds = new Set(existing.map(r => r.id));
|
||||
const kept = [];
|
||||
const options = FREE_KINDS.has(q.kind) ? [] : q.options;
|
||||
const options = isFreeKind(q.kind) ? [] : q.options;
|
||||
for (let i = 0; i < options.length; i++) {
|
||||
const o = options[i];
|
||||
let oid = o.id && existingIds.has(o.id) ? o.id : null;
|
||||
@@ -723,12 +774,15 @@ async function saveQuiz(pool, id, user, body = {}) {
|
||||
if (!row) throw httpError(404, 'Тест не найден');
|
||||
if (!canEditQuiz(row, user)) throw httpError(403, 'Изменять тест может только автор или администратор');
|
||||
const meta = normalizeMeta(body, row);
|
||||
if (meta.grade_scale_id != null) {
|
||||
const { rows: scaleRows } = await pool.query('SELECT id FROM quiz_grade_scales WHERE id = $1', [meta.grade_scale_id]);
|
||||
if (!scaleRows.length) throw httpError(400, 'Критерий оценки не найден');
|
||||
if (meta.grade_scale_id != null && !(await gradeScaleAccessible(pool, meta.grade_scale_id, user))) {
|
||||
throw httpError(400, 'Критерий оценки не найден');
|
||||
}
|
||||
const rawQuestions = Array.isArray(body.questions) ? body.questions.slice(0, QUIZ_QUESTIONS_MAX) : [];
|
||||
const questions = rawQuestions.map((q, i) => validateQuestion(q, meta.kind, i));
|
||||
const hasSystemFields = questions.some(q => SYSTEM_FIELD_KINDS.has(q.kind));
|
||||
if (meta.allow_anonymous && hasSystemFields && !meta.access_code) {
|
||||
throw httpError(400, 'Для теста с системными полями задайте код доступа — его вводят перед прохождением по ссылке');
|
||||
}
|
||||
const quizAssetIds = normalizeIdList(body.asset_ids, QUIZ_ASSETS_MAX);
|
||||
const removedPaths = [];
|
||||
const client = await pool.connect();
|
||||
@@ -738,11 +792,12 @@ async function saveQuiz(pool, id, user, body = {}) {
|
||||
`UPDATE quizzes SET title = $2, description = $3, kind = $4, is_published = $5, shuffle_questions = $6,
|
||||
shuffle_options = $7, show_results = $8, max_attempts = $9, time_limit_min = $10,
|
||||
pass_percent = $11, cover_path = $12, allow_anonymous = $13, show_answers = $14,
|
||||
grade_scale_id = $15, updated_at = now()
|
||||
grade_scale_id = $15, access_code = $16, retry_cooldown_min = $17, updated_at = now()
|
||||
WHERE id = $1`,
|
||||
[id, meta.title, meta.description, meta.kind, meta.is_published, meta.shuffle_questions,
|
||||
meta.shuffle_options, meta.show_results, meta.max_attempts, meta.time_limit_min,
|
||||
meta.pass_percent, meta.cover_path, meta.allow_anonymous, meta.show_answers, meta.grade_scale_id]
|
||||
meta.pass_percent, meta.cover_path, meta.allow_anonymous, meta.show_answers, meta.grade_scale_id,
|
||||
meta.access_code, meta.retry_cooldown_min]
|
||||
);
|
||||
const { rows: existingQ } = await client.query('SELECT id FROM quiz_questions WHERE quiz_id = $1', [id]);
|
||||
const existingQIds = new Set(existingQ.map(r => r.id));
|
||||
@@ -911,7 +966,7 @@ async function deleteAsset(pool, id, user) {
|
||||
function scoreTextAnswer(question, textAnswer) {
|
||||
const accepted = Array.isArray(question.accepted_answers) ? question.accepted_answers : [];
|
||||
if (!accepted.length) return { score: 0, max_score: 0, is_correct: null };
|
||||
const qWeight = Number(question.weight == null ? 1 : question.weight);
|
||||
const qWeight = Number(question.weight == null ? 0 : question.weight);
|
||||
const maxScore = round2(qWeight);
|
||||
let ok = false;
|
||||
if (question.kind === 'number') {
|
||||
@@ -937,17 +992,16 @@ function scoreTextAnswer(question, textAnswer) {
|
||||
|
||||
function scoreQuestion(question, selectedIds, textAnswer) {
|
||||
const options = Array.isArray(question.options) ? question.options : [];
|
||||
if (FREE_KINDS.has(question.kind)) return scoreTextAnswer(question, textAnswer);
|
||||
if (isFreeKind(question.kind)) return scoreTextAnswer(question, textAnswer);
|
||||
const selected = new Set((selectedIds || []).map(Number).filter(Number.isInteger));
|
||||
const kind = question.kind;
|
||||
const correct = options.filter(o => o.is_correct);
|
||||
const maxRaw = correct.reduce((s, o) => s + Number(o.weight || 0), 0);
|
||||
const qWeight = Number(question.weight == null ? 1 : question.weight);
|
||||
const maxScore = round2(maxRaw * qWeight);
|
||||
const maxScore = round2(maxRaw);
|
||||
if (kind === 'single' || kind === 'select') {
|
||||
const chosen = options.filter(o => selected.has(Number(o.id)));
|
||||
const ok = chosen.length === 1 && chosen[0].is_correct === true;
|
||||
return { score: ok ? round2(Number(chosen[0].weight || 0) * qWeight) : 0, max_score: maxScore, is_correct: ok };
|
||||
return { score: ok ? round2(Number(chosen[0].weight || 0)) : 0, max_score: maxScore, is_correct: ok };
|
||||
}
|
||||
const exact = correct.length === selected.size && correct.every(o => selected.has(Number(o.id)));
|
||||
if (!question.partial_credit) {
|
||||
@@ -957,7 +1011,7 @@ function scoreQuestion(question, selectedIds, textAnswer) {
|
||||
let raw = 0;
|
||||
for (const o of chosen) raw += (o.is_correct ? 1 : -1) * Number(o.weight || 0);
|
||||
raw = Math.max(0, Math.min(raw, maxRaw));
|
||||
return { score: round2(raw * qWeight), max_score: maxScore, is_correct: exact };
|
||||
return { score: round2(raw), max_score: maxScore, is_correct: exact };
|
||||
}
|
||||
|
||||
async function startAttempt(pool, quizId, user) {
|
||||
@@ -1011,6 +1065,7 @@ async function performSubmit(pool, row, attempt, body = {}) {
|
||||
const quizId = Number(row.id);
|
||||
const attemptId = Number(attempt.id);
|
||||
const structure = await loadQuizStructure(pool, quizId);
|
||||
const skipRequired = body.time_up === true;
|
||||
const answers = Array.isArray(body.answers) ? body.answers.slice(0, QUIZ_ATTEMPT_ANSWERS_MAX) : [];
|
||||
const byQuestion = new Map();
|
||||
for (const a of answers) {
|
||||
@@ -1026,13 +1081,18 @@ async function performSubmit(pool, row, attempt, body = {}) {
|
||||
await client.query('BEGIN');
|
||||
for (const q of structure.questions) {
|
||||
const a = byQuestion.get(q.id) || {};
|
||||
const free = FREE_KINDS.has(q.kind);
|
||||
const free = isFreeKind(q.kind);
|
||||
const optionIds = free ? [] : normalizeIdList(a.option_ids, QUIZ_OPTIONS_MAX);
|
||||
const textAnswer = free
|
||||
? textValue(a.text, QUIZ_ANSWER_MAX, 'Ответ', false)
|
||||
: '';
|
||||
if (free && q.required !== false && q.min_length > 0 && textAnswer.length < q.min_length) {
|
||||
throw httpError(400, `Вопрос «${q.text}»: минимум ${q.min_length} символов`);
|
||||
const answerId = SYSTEM_FIELD_KINDS.has(q.kind) ? normalizeAnswerId(a.answer_id) : null;
|
||||
if (!skipRequired && q.required !== false) {
|
||||
const answered = free ? (textAnswer !== '' || answerId != null) : optionIds.length > 0;
|
||||
if (!answered) throw httpError(400, `Вопрос «${q.text}»: ответ обязателен`);
|
||||
if (free && q.min_length > 0 && textAnswer.length < q.min_length) {
|
||||
throw httpError(400, `Вопрос «${q.text}»: минимум ${q.min_length} символов`);
|
||||
}
|
||||
}
|
||||
const res = row.kind === 'survey'
|
||||
? { score: 0, max_score: 0, is_correct: null }
|
||||
@@ -1054,11 +1114,15 @@ async function performSubmit(pool, row, attempt, body = {}) {
|
||||
accepted_answers: q.accepted_answers,
|
||||
selected: optionIds,
|
||||
};
|
||||
if (SYSTEM_FIELD_KINDS.has(q.kind)) {
|
||||
snapshot.field = q.kind;
|
||||
snapshot.answer_id = answerId;
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO quiz_attempt_answers (attempt_id, question_id, question_text, option_ids, answer_snapshot, text_answer, is_correct, score, max_score)
|
||||
VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7,$8,$9)`,
|
||||
`INSERT INTO quiz_attempt_answers (attempt_id, question_id, question_text, option_ids, answer_snapshot, text_answer, answer_id, is_correct, score, max_score)
|
||||
VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7,$8,$9,$10)`,
|
||||
[attemptId, q.id, q.text, optionIds, JSON.stringify(snapshot), textAnswer || null,
|
||||
res.is_correct, res.score, res.max_score]
|
||||
answerId, res.is_correct, res.score, res.max_score]
|
||||
);
|
||||
results.push({
|
||||
question_id: q.id,
|
||||
@@ -1152,7 +1216,10 @@ async function getPublicQuiz(pool, quizId) {
|
||||
delete meta.deleted_at;
|
||||
delete meta.purge_at;
|
||||
return {
|
||||
quiz: meta,
|
||||
quiz: {
|
||||
...meta,
|
||||
has_system_fields: structure.questions.some(q => SYSTEM_FIELD_KINDS.has(q.kind)),
|
||||
},
|
||||
quiz_assets: structure.quiz_assets,
|
||||
questions: structure.questions,
|
||||
};
|
||||
@@ -1160,6 +1227,7 @@ async function getPublicQuiz(pool, quizId) {
|
||||
|
||||
async function startPublicAttempt(pool, quizId, opts = {}) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
if (!accessCodeMatches(row.access_code, opts.code)) throw httpError(403, 'Неверный код доступа');
|
||||
const guestName = row.kind === 'test' ? guestNameValue(opts.name) : null;
|
||||
const token = crypto.randomBytes(QUIZ_ANON_TOKEN_BYTES).toString('hex');
|
||||
const { rows } = await pool.query(
|
||||
@@ -1190,6 +1258,69 @@ async function submitPublicAttempt(pool, quizId, attemptId, token, body = {}) {
|
||||
return performSubmit(pool, row, attempt, body);
|
||||
}
|
||||
|
||||
async function lookupSystemOptions(pool, field, query, branchIds = null) {
|
||||
if (!SYSTEM_FIELD_KINDS.has(field)) throw httpError(400, 'Неизвестное системное поле');
|
||||
const term = String(query == null ? '' : query).trim().slice(0, 80);
|
||||
const like = '%' + term.replace(/[\\%_]/g, ch => '\\' + ch) + '%';
|
||||
const params = [like];
|
||||
let branch = '';
|
||||
if (Array.isArray(branchIds) && (field === 'student' || field === 'group' || field === 'branch')) {
|
||||
params.push(branchIds.length ? branchIds : [0]);
|
||||
const column = field === 'branch' ? 'b.id' : 'g.branch_id';
|
||||
branch = ` AND ${column} = ANY($2::int[])`;
|
||||
}
|
||||
let sql;
|
||||
if (field === 'student') {
|
||||
sql = `SELECT s.id, s.name, g.name AS sub
|
||||
FROM students s
|
||||
LEFT JOIN groups g ON g.id = s.group_id
|
||||
WHERE s.deleted_at IS NULL AND s.name ILIKE $1${branch}
|
||||
ORDER BY s.name ASC
|
||||
LIMIT 20`;
|
||||
} else if (field === 'group') {
|
||||
sql = `SELECT g.id, g.name, b.name AS sub
|
||||
FROM groups g
|
||||
LEFT JOIN branches b ON b.id = g.branch_id
|
||||
WHERE g.deleted_at IS NULL AND g.hidden = false AND g.name ILIKE $1${branch}
|
||||
ORDER BY g.name ASC
|
||||
LIMIT 20`;
|
||||
} else if (field === 'branch') {
|
||||
sql = `SELECT b.id, b.name, NULL AS sub
|
||||
FROM branches b
|
||||
WHERE b.name ILIKE $1${branch}
|
||||
ORDER BY b.name ASC
|
||||
LIMIT 20`;
|
||||
} else {
|
||||
sql = `SELECT m.id, m.name, NULL AS sub
|
||||
FROM modules m
|
||||
WHERE m.is_active = true AND m.name ILIKE $1
|
||||
ORDER BY m.name ASC
|
||||
LIMIT 20`;
|
||||
}
|
||||
const { rows } = await pool.query(sql, params);
|
||||
return { items: rows.map(r => ({ id: r.id, name: r.name, sub: r.sub || null })) };
|
||||
}
|
||||
|
||||
async function lookupPublicQuizOptions(pool, quizId, opts = {}) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
if (!row.access_code) throw httpError(403, 'Подсказки недоступны: автор не задал код доступа');
|
||||
if (!accessCodeMatches(row.access_code, opts.code)) throw httpError(403, 'Неверный код доступа');
|
||||
let branchIds = null;
|
||||
if (row.author_id != null) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT u.role, ub.branch_id
|
||||
FROM users u
|
||||
LEFT JOIN user_branches ub ON ub.user_id = u.id
|
||||
WHERE u.id = $1`,
|
||||
[row.author_id]
|
||||
);
|
||||
if (rows.length && rows[0].role !== 'admin') {
|
||||
branchIds = rows.map(r => r.branch_id).filter(id => id != null);
|
||||
}
|
||||
}
|
||||
return lookupSystemOptions(pool, opts.field, opts.query, branchIds);
|
||||
}
|
||||
|
||||
async function listAttempts(pool, quizId, user, params = {}) {
|
||||
const row = await findQuizRow(pool, quizId);
|
||||
if (!row) throw httpError(404, 'Тест не найден');
|
||||
@@ -1373,6 +1504,9 @@ module.exports = {
|
||||
QUESTION_KINDS,
|
||||
OPTION_KINDS,
|
||||
FREE_KINDS,
|
||||
SYSTEM_FIELD_KINDS,
|
||||
SYSTEM_FIELD_LABELS,
|
||||
QUIZ_ACCESS_CODE_MAX,
|
||||
QUIZ_TITLE_MAX,
|
||||
QUIZ_DESCRIPTION_MAX,
|
||||
QUIZ_TEXT_MAX,
|
||||
@@ -1409,6 +1543,8 @@ module.exports = {
|
||||
getPublicQuiz,
|
||||
startPublicAttempt,
|
||||
submitPublicAttempt,
|
||||
lookupSystemOptions,
|
||||
lookupPublicQuizOptions,
|
||||
normalizeAnswerText,
|
||||
normalizeNumberValue,
|
||||
normalizeDateValue,
|
||||
|
||||
@@ -1511,3 +1511,12 @@ body.report-card-open .report-fields{display:flex}
|
||||
.qz-desc blockquote, .qz-q-desc blockquote, .qp-desc blockquote { margin: 6px 0; padding-left: 10px; border-left: 3px solid var(--border); }
|
||||
.qz-desc table, .qz-q-desc table, .qp-desc table { border-collapse: collapse; margin: 6px 0; }
|
||||
.qz-desc th, .qz-desc td, .qz-q-desc th, .qz-q-desc td, .qp-desc th, .qp-desc td { border: 1px solid var(--border); padding: 4px 8px; }
|
||||
|
||||
/* --- Системные поля в тестах: подсказки --- */
|
||||
.qz-suggest-wrap { position: relative; }
|
||||
.qz-suggest { position: absolute; z-index: 30; left: 0; right: 0; top: calc(100% + 4px); background: var(--card); border: 1px solid var(--border); border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,.14); max-height: 240px; overflow-y: auto; padding: 4px; }
|
||||
.qz-sug-item { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; width: 100%; text-align: left; background: none; border: 0; color: var(--text); padding: 7px 9px; border-radius: 7px; cursor: pointer; font-size: .88rem; font-family: inherit; }
|
||||
.qz-sug-item:hover, .qz-sug-item:focus { background: var(--bg); }
|
||||
.qz-sug-item span { overflow-wrap: anywhere; }
|
||||
.qz-sug-item small { color: var(--muted); font-size: .75rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.qz-sug-empty { padding: 8px 10px; font-size: .8rem; color: var(--muted); }
|
||||
|
||||
@@ -9,6 +9,16 @@
|
||||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function canManage(s) {
|
||||
if (!s || typeof currentUser === 'undefined' || !currentUser) return false;
|
||||
if (currentUser.role === 'admin') return true;
|
||||
return s.created_by != null && Number(s.created_by) === Number(currentUser.id);
|
||||
}
|
||||
|
||||
function isAdmin() {
|
||||
return typeof currentUser !== 'undefined' && !!currentUser && currentUser.role === 'admin';
|
||||
}
|
||||
|
||||
function openModal(id) {
|
||||
const node = el(id);
|
||||
if (node) node.classList.add('open');
|
||||
@@ -46,16 +56,19 @@
|
||||
const ranges = (s.ranges || []).map(r =>
|
||||
`<span class="qs-range-chip">${esc(String(r.min_score))}–${esc(String(r.max_score))}: ${esc(r.label || '')}</span>`
|
||||
).join('');
|
||||
const acts = canManage(s)
|
||||
? `<div class="qs-item-acts">
|
||||
<button type="button" class="btn-link" data-qs-edit="${s.id}">Изменить</button>
|
||||
<button type="button" class="btn-link danger" data-qs-del="${s.id}">Удалить</button>
|
||||
</div>`
|
||||
: '';
|
||||
return `<div class="qs-item">
|
||||
<div class="qs-item-head">
|
||||
<div class="qs-item-main">
|
||||
<div class="qs-item-name">${esc(s.name || '')}</div>
|
||||
<div class="qs-item-name">${esc(s.name || '')}${s.is_shared ? ' <span class="qs-tag">Доступна всем</span>' : ''}</div>
|
||||
${s.description ? `<div class="qs-item-desc">${esc(s.description)}</div>` : ''}
|
||||
</div>
|
||||
<div class="qs-item-acts">
|
||||
<button type="button" class="btn-link" data-qs-edit="${s.id}">Изменить</button>
|
||||
<button type="button" class="btn-link danger" data-qs-del="${s.id}">Удалить</button>
|
||||
</div>
|
||||
${acts}
|
||||
</div>
|
||||
<div class="qs-item-ranges">${ranges || '<span class="qs-range-chip">нет диапазонов</span>'}</div>
|
||||
</div>`;
|
||||
@@ -68,6 +81,7 @@
|
||||
name: '',
|
||||
description: '',
|
||||
sort_order: 0,
|
||||
is_shared: false,
|
||||
ranges: [{ min_score: 0, max_score: '', label: '', image_path: null }],
|
||||
};
|
||||
}
|
||||
@@ -93,6 +107,8 @@
|
||||
el('qsName').value = d.name;
|
||||
el('qsDesc').value = d.description;
|
||||
el('qsSort').value = d.sort_order;
|
||||
el('qsPublicField').hidden = !isAdmin();
|
||||
el('qsPublic').checked = isAdmin() && d.is_shared === true;
|
||||
el('qsEditorTitle').textContent = d.id ? 'Изменить критерий' : 'Новый критерий оценки';
|
||||
renderRanges();
|
||||
}
|
||||
@@ -111,6 +127,7 @@
|
||||
name: s.name || '',
|
||||
description: s.description || '',
|
||||
sort_order: Number(s.sort_order) || 0,
|
||||
is_shared: s.is_shared === true,
|
||||
ranges: (s.ranges || []).map(r => ({
|
||||
min_score: Number(r.min_score),
|
||||
max_score: Number(r.max_score),
|
||||
@@ -143,6 +160,7 @@
|
||||
name,
|
||||
description: el('qsDesc').value.trim(),
|
||||
sort_order: Number(el('qsSort').value) || 0,
|
||||
is_shared: el('qsPublic').checked === true,
|
||||
ranges,
|
||||
};
|
||||
const btn = el('qsSaveBtn');
|
||||
|
||||
+71
-14
@@ -5,13 +5,18 @@
|
||||
let saving = false;
|
||||
let dragState = null;
|
||||
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
const SYSTEM_KINDS = ['student', 'group', 'branch', 'module'];
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS];
|
||||
const OPTION_KINDS = ['single', 'multiple', 'select'];
|
||||
|
||||
function isFree(kind) {
|
||||
return FREE_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function isSystemKind(kind) {
|
||||
return SYSTEM_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function isOptionKind(kind) {
|
||||
return OPTION_KINDS.includes(kind);
|
||||
}
|
||||
@@ -24,6 +29,35 @@
|
||||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function round2(n) {
|
||||
return Math.round((Number(n) || 0) * 100) / 100;
|
||||
}
|
||||
|
||||
function isPlainFree(kind) {
|
||||
return kind === 'line' || kind === 'text' || kind === 'number' || kind === 'date';
|
||||
}
|
||||
|
||||
function questionPoints(q) {
|
||||
if (!state.quiz || state.quiz.kind !== 'test') return 0;
|
||||
if (isSystemKind(q.kind)) return 0;
|
||||
if (isFree(q.kind)) return round2(Math.max(0, Number(q.weight) || 0));
|
||||
return round2((q.options || []).reduce((sum, o) => sum + (o.is_correct ? Math.max(0, Number(o.weight) || 0) : 0), 0));
|
||||
}
|
||||
|
||||
function updatePoints() {
|
||||
const isTest = !!(state.quiz && state.quiz.kind === 'test');
|
||||
const totalEl = document.getElementById('qeTotalPoints');
|
||||
if (totalEl) {
|
||||
totalEl.hidden = !isTest;
|
||||
if (isTest) totalEl.textContent = 'Всего баллов: ' + round2(state.questions.reduce((sum, q) => sum + questionPoints(q), 0));
|
||||
}
|
||||
document.querySelectorAll('[data-qpoints]').forEach(node => {
|
||||
const q = state.questions[Number(node.dataset.qpoints)];
|
||||
if (!q) return;
|
||||
node.textContent = 'Макс. баллов: ' + round2(questionPoints(q));
|
||||
});
|
||||
}
|
||||
|
||||
function assetName(a) {
|
||||
return String(a.path || '').split('/').pop();
|
||||
}
|
||||
@@ -71,8 +105,10 @@
|
||||
show_answers: quiz.show_answers !== false,
|
||||
grade_scale_id: quiz.grade_scale_id == null ? '' : quiz.grade_scale_id,
|
||||
allow_anonymous: quiz.allow_anonymous === true,
|
||||
access_code: quiz.access_code || '',
|
||||
max_attempts: quiz.max_attempts == null ? '' : quiz.max_attempts,
|
||||
time_limit_min: quiz.time_limit_min || 0,
|
||||
retry_cooldown_min: Number(quiz.retry_cooldown_min) || 0,
|
||||
pass_percent: quiz.pass_percent == null ? 60 : quiz.pass_percent,
|
||||
cover_path: quiz.cover_path || null,
|
||||
};
|
||||
@@ -82,7 +118,7 @@
|
||||
kind: normalizeKind(q.kind),
|
||||
text: q.text || '',
|
||||
description: q.description || '',
|
||||
weight: q.weight == null ? 1 : Number(q.weight),
|
||||
weight: q.weight == null ? 0 : Number(q.weight),
|
||||
partial_credit: q.partial_credit === true,
|
||||
required: q.required !== false,
|
||||
min_length: Number(q.min_length) || 0,
|
||||
@@ -95,7 +131,7 @@
|
||||
text: o.text || '',
|
||||
description: o.description || '',
|
||||
is_correct: o.is_correct === true,
|
||||
weight: o.weight == null ? 1 : Number(o.weight),
|
||||
weight: o.weight == null ? 0 : Number(o.weight),
|
||||
assets: Array.isArray(o.assets) ? o.assets.slice() : [],
|
||||
})),
|
||||
}));
|
||||
@@ -114,8 +150,10 @@
|
||||
show_answers: q.show_answers,
|
||||
grade_scale_id: q.grade_scale_id === '' ? null : q.grade_scale_id,
|
||||
allow_anonymous: q.allow_anonymous,
|
||||
access_code: q.access_code || '',
|
||||
max_attempts: q.max_attempts === '' ? null : q.max_attempts,
|
||||
time_limit_min: q.time_limit_min === '' ? 0 : q.time_limit_min,
|
||||
retry_cooldown_min: q.retry_cooldown_min === '' ? 0 : q.retry_cooldown_min,
|
||||
pass_percent: q.pass_percent === '' ? 60 : q.pass_percent,
|
||||
cover_path: q.cover_path,
|
||||
asset_ids: state.assets.map(a => a.id),
|
||||
@@ -175,7 +213,7 @@
|
||||
<span class="toggle-track"><span class="toggle-thumb"></span></span>
|
||||
<span class="toggle-text"><small>Верный</small></span>
|
||||
</label>
|
||||
<label class="qe-weight" title="Вес ответа"><span>вес</span>
|
||||
<label class="qe-weight" title="Баллы за вариант"><span>балл</span>
|
||||
<input type="number" class="settings-input qe-opt-weight" data-oi="${oi}" data-field="weight" min="0" max="100" step="0.5" value="${at(o.weight)}">
|
||||
</label>` : ''}
|
||||
<button type="button" class="icon-btn" data-act="del-option" data-oi="${oi}" title="Удалить вариант"><i data-lucide="trash-2"></i></button>
|
||||
@@ -189,7 +227,7 @@
|
||||
}
|
||||
|
||||
function acceptedHtml(q, qi, isTest) {
|
||||
if (!isFree(q.kind) || !isTest) return '';
|
||||
if (!isFree(q.kind) || !isTest || isSystemKind(q.kind)) return '';
|
||||
const hints = {
|
||||
line: 'Ответ вводится одной строкой. Регистр, «ё» и лишние пробелы не важны.',
|
||||
text: 'Ответ вводится многострочным текстом. Регистр, «ё» и лишние пробелы не важны.',
|
||||
@@ -212,7 +250,7 @@
|
||||
<span></span>
|
||||
<textarea id="qeAccepted${qi}" class="settings-input" rows="2" data-qi="${qi}" data-field="accepted_raw" placeholder="${placeholder}" maxlength="4000">${esc((q.accepted_answers || []).join('\n'))}</textarea>
|
||||
${matchSelect}
|
||||
<span class="qe-hint">${hints[q.kind] || ''} Балл за вопрос: вес вопроса.</span>
|
||||
<span class="qe-hint">${hints[q.kind] || ''} Балл за вопрос задаётся полем «балл» у вопроса.</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -227,6 +265,10 @@
|
||||
['text', 'Многострочный текст'],
|
||||
['number', 'Число'],
|
||||
['date', 'Дата'],
|
||||
['student', 'Ученик — поиск по имени'],
|
||||
['group', 'Группа — поиск по названию'],
|
||||
['branch', 'Филиал — поиск по названию'],
|
||||
['module', 'Тема модуля — поиск по названию'],
|
||||
].map(([value, label]) => `<option value="${value}"${q.kind === value ? ' selected' : ''}>${label}</option>`).join('');
|
||||
const options = isOptionKind(q.kind) ? `
|
||||
<div data-options="${qi}">${q.options.map((o, oi) => optionHtml(o, qi, oi, isTest)).join('')}</div>
|
||||
@@ -236,7 +278,8 @@
|
||||
<span class="qe-drag" draggable="true" title="Перетащить вопрос">⠿</span>
|
||||
<span class="qe-q-num">${qi + 1}</span>
|
||||
<select class="settings-input" data-role="qkind" data-qi="${qi}">${kindOptions}</select>
|
||||
${isTest ? `<label class="qe-weight" title="Вес вопроса"><span>вес</span><input type="number" class="settings-input qe-q-weight" style="max-width:90px" data-qi="${qi}" data-field="weight" min="0" max="100" step="0.5" value="${at(q.weight)}"></label>` : ''}
|
||||
${isTest && isPlainFree(q.kind) ? `<label class="qe-weight" title="Баллы за вопрос"><span>балл</span><input type="number" class="settings-input qe-q-weight" style="max-width:90px" data-qi="${qi}" data-field="weight" min="0" max="100" step="0.5" value="${at(q.weight)}"></label>` : ''}
|
||||
${isTest && !isSystemKind(q.kind) ? `<span class="qe-points" data-qpoints="${qi}">Макс. баллов: ${round2(questionPoints(q))}</span>` : ''}
|
||||
<span class="spacer"></span>
|
||||
<button type="button" class="icon-btn" data-act="up" data-qi="${qi}" title="Выше"><i data-lucide="arrow-up"></i></button>
|
||||
<button type="button" class="icon-btn" data-act="down" data-qi="${qi}" title="Ниже"><i data-lucide="arrow-down"></i></button>
|
||||
@@ -275,10 +318,12 @@
|
||||
const wrap = document.getElementById('qeQuestions');
|
||||
if (!state.questions.length) {
|
||||
wrap.innerHTML = '<div class="qe-panel"><p class="qe-hint" style="margin:0">Вопросов пока нет. Добавьте первый вопрос.</p></div>';
|
||||
updatePoints();
|
||||
return;
|
||||
}
|
||||
wrap.innerHTML = state.questions.map(questionHtml).join('');
|
||||
renderIcons();
|
||||
updatePoints();
|
||||
}
|
||||
|
||||
function renderQuizAssets() {
|
||||
@@ -365,11 +410,13 @@
|
||||
document.getElementById('qePass').value = q.pass_percent;
|
||||
document.getElementById('qeAttempts').value = q.max_attempts;
|
||||
document.getElementById('qeTime').value = q.time_limit_min;
|
||||
document.getElementById('qeRetry').value = q.retry_cooldown_min;
|
||||
document.getElementById('qePublished').checked = q.is_published;
|
||||
document.getElementById('qeShuffleQ').checked = q.shuffle_questions;
|
||||
document.getElementById('qeShuffleO').checked = q.shuffle_options;
|
||||
document.getElementById('qeShowResults').checked = q.show_results;
|
||||
document.getElementById('qeShowAnswers').checked = q.show_answers;
|
||||
document.getElementById('qeAccessCode').value = q.access_code || '';
|
||||
document.getElementById('qeShowAnswersWrap').hidden = q.kind !== 'test';
|
||||
document.getElementById('qeGradeWrap').hidden = q.kind !== 'test';
|
||||
renderGradeSelect();
|
||||
@@ -574,8 +621,8 @@
|
||||
q.options = [];
|
||||
} else if (q.options.length < 2) {
|
||||
q.options = [
|
||||
{ id: null, text: '', description: '', is_correct: q.kind !== 'multiple', weight: 1, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: q.kind !== 'multiple', weight: 0, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] },
|
||||
];
|
||||
}
|
||||
markDirty();
|
||||
@@ -602,6 +649,7 @@
|
||||
opt[field] = el.value;
|
||||
}
|
||||
markDirty();
|
||||
updatePoints();
|
||||
return;
|
||||
}
|
||||
if (el.dataset.qi !== undefined) {
|
||||
@@ -622,6 +670,7 @@
|
||||
q.text_match = el.value === 'contains' ? 'contains' : 'exact';
|
||||
} else q[field] = el.value;
|
||||
markDirty();
|
||||
updatePoints();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -703,7 +752,7 @@
|
||||
const act = btn.dataset.act;
|
||||
if (act === 'add-option') {
|
||||
const qi = Number(btn.dataset.qi);
|
||||
state.questions[qi].options.push({ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] });
|
||||
state.questions[qi].options.push({ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] });
|
||||
markDirty();
|
||||
renderAll();
|
||||
return;
|
||||
@@ -787,6 +836,14 @@
|
||||
state.quiz.time_limit_min = e.target.value === '' ? 0 : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
document.getElementById('qeRetry').addEventListener('input', e => {
|
||||
state.quiz.retry_cooldown_min = e.target.value === '' ? 0 : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
document.getElementById('qeAccessCode').addEventListener('input', e => {
|
||||
state.quiz.access_code = e.target.value;
|
||||
markDirty();
|
||||
});
|
||||
['qePublished', 'qeShuffleQ', 'qeShuffleO', 'qeShowResults', 'qeShowAnswers', 'qeAnonymous'].forEach(id => {
|
||||
document.getElementById(id).addEventListener('change', e => {
|
||||
const map = {
|
||||
@@ -821,8 +878,8 @@
|
||||
kind: 'single',
|
||||
text: '',
|
||||
description: '',
|
||||
weight: 1,
|
||||
partial_credit: false,
|
||||
weight: 0,
|
||||
partial_credit: true,
|
||||
required: true,
|
||||
min_length: 0,
|
||||
options_inline: false,
|
||||
@@ -830,8 +887,8 @@
|
||||
accepted_answers: [],
|
||||
assets: [],
|
||||
options: [
|
||||
{ id: null, text: '', description: '', is_correct: true, weight: 1, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: true, weight: 0, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] },
|
||||
],
|
||||
});
|
||||
markDirty();
|
||||
|
||||
+168
-16
@@ -1,7 +1,9 @@
|
||||
(function () {
|
||||
const API = location.origin;
|
||||
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
const SYSTEM_KINDS = ['student', 'group', 'branch', 'module'];
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS];
|
||||
const SYSTEM_LABELS = { student: 'ученика', group: 'группы', branch: 'филиала', module: 'темы модуля' };
|
||||
const state = {
|
||||
quiz: null,
|
||||
questions: [],
|
||||
@@ -9,9 +11,14 @@
|
||||
attempt: null,
|
||||
selection: new Map(),
|
||||
texts: new Map(),
|
||||
systemIds: new Map(),
|
||||
sugTimers: new Map(),
|
||||
code: '',
|
||||
timer: null,
|
||||
done: false,
|
||||
};
|
||||
const RETRY_KEY = 'whatido_quiz_retry_' + (Number.isInteger(quizId) ? quizId : '');
|
||||
let retryTimer = null;
|
||||
|
||||
function esc2(v) {
|
||||
return String(v == null ? '' : v)
|
||||
@@ -60,6 +67,54 @@
|
||||
toast.t = setTimeout(() => { el.className = 'toast'; }, 3200);
|
||||
}
|
||||
|
||||
function retryUntil() {
|
||||
const min = Number(state.quiz && state.quiz.retry_cooldown_min) || 0;
|
||||
if (min <= 0) return 0;
|
||||
let raw = null;
|
||||
try { raw = localStorage.getItem(RETRY_KEY); } catch (e) { raw = null; }
|
||||
const at = parseInt(raw, 10);
|
||||
if (!Number.isFinite(at)) return 0;
|
||||
const until = at + min * 60000;
|
||||
if (Date.now() >= until) {
|
||||
try { localStorage.removeItem(RETRY_KEY); } catch (e) { /* ignore */ }
|
||||
return 0;
|
||||
}
|
||||
return until;
|
||||
}
|
||||
|
||||
function markRetry() {
|
||||
if (!(Number(state.quiz && state.quiz.retry_cooldown_min) > 0)) return;
|
||||
try { localStorage.setItem(RETRY_KEY, String(Date.now())); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
function retryLeftText(until) {
|
||||
const left = Math.max(0, until - Date.now());
|
||||
const min = Math.floor(left / 60000);
|
||||
const sec = Math.floor((left % 60000) / 1000);
|
||||
return `Повторно пройти можно через ${min} мин ${sec} сек`;
|
||||
}
|
||||
|
||||
function stopRetryTimer() {
|
||||
if (retryTimer) clearInterval(retryTimer);
|
||||
retryTimer = null;
|
||||
}
|
||||
|
||||
function startRetryTimer(until) {
|
||||
stopRetryTimer();
|
||||
const tick = () => {
|
||||
const el = document.getElementById('qpRetryTimer');
|
||||
if (!el) { stopRetryTimer(); return; }
|
||||
if (Date.now() >= until) {
|
||||
stopRetryTimer();
|
||||
render();
|
||||
return;
|
||||
}
|
||||
el.textContent = retryLeftText(until);
|
||||
};
|
||||
tick();
|
||||
retryTimer = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
function assetsHtml(list) {
|
||||
if (!Array.isArray(list) || !list.length) return '';
|
||||
const cards = list.map(a => {
|
||||
@@ -82,7 +137,23 @@
|
||||
return FREE_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function isSystemKind(kind) {
|
||||
return SYSTEM_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function systemAnswerHtml(q) {
|
||||
const value = state.texts.get(q.id) || '';
|
||||
const picked = state.systemIds.get(q.id) || '';
|
||||
const label = SYSTEM_LABELS[q.kind] || 'названия';
|
||||
return `<div class="qz-suggest-wrap">
|
||||
<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" data-qsys="${q.kind}" placeholder="Начните вводить название ${label}" autocomplete="off" maxlength="200" value="${esc2(value)}">
|
||||
<input type="hidden" data-qsysid="${q.id}" value="${picked}">
|
||||
<div class="qz-suggest" data-sug="${q.id}" hidden></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function freeAnswerHtml(q) {
|
||||
if (isSystemKind(q.kind)) return systemAnswerHtml(q);
|
||||
const value = state.texts.get(q.id) || '';
|
||||
const hint = q.required !== false && q.min_length > 0
|
||||
? `<div class="qp-hint" style="margin-top:4px">Минимум ${q.min_length} символов</div>`
|
||||
@@ -99,6 +170,34 @@
|
||||
return `<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000" value="${esc2(value)}">${hint}`;
|
||||
}
|
||||
|
||||
async function systemLookup(qid, kind, term) {
|
||||
const box = document.querySelector('[data-sug="' + qid + '"]');
|
||||
if (!box) return;
|
||||
const text = String(term || '').trim();
|
||||
if (!text) {
|
||||
box.hidden = true;
|
||||
box.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const url = API + '/api/public-quizzes/' + quizId + '/options?field=' + encodeURIComponent(kind)
|
||||
+ '&q=' + encodeURIComponent(text) + '&code=' + encodeURIComponent(state.code || '');
|
||||
const res = await fetch(url);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
box.hidden = true;
|
||||
return;
|
||||
}
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
box.innerHTML = items.length
|
||||
? items.map(it => `<button type="button" class="qz-sug-item" data-sug-q="${qid}" data-sug-id="${it.id}" data-sug-name="${esc2(it.name)}"><span>${esc2(it.name)}</span>${it.sub ? `<small>${esc2(it.sub)}</small>` : ''}</button>`).join('')
|
||||
: '<div class="qz-sug-empty">Ничего не найдено</div>';
|
||||
box.hidden = false;
|
||||
} catch (e) {
|
||||
box.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
function questionHtml(q, index) {
|
||||
const chosen = state.selection.get(q.id) || new Set();
|
||||
let body;
|
||||
@@ -130,16 +229,23 @@
|
||||
function introHtml() {
|
||||
const q = state.quiz;
|
||||
const isTest = q.kind === 'test';
|
||||
const until = retryUntil();
|
||||
return `<div class="qp-card">
|
||||
${q.cover_path ? `<img class="qp-cover" src="${at(thumb(q.cover_path))}" data-img="${at(API + q.cover_path)}" alt="Обложка">` : ''}
|
||||
<div class="qp-title">${esc2(q.title || (isTest ? 'Тест' : 'Опрос'))}</div>
|
||||
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span>${q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : ''}${isTest ? `<span>${q.show_results === false ? 'Результат виден автору' : 'Результат после отправки'}</span>` : ''}</div>
|
||||
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span>${q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : ''}${q.retry_cooldown_min ? `<span>Повтор: через ${q.retry_cooldown_min} мин</span>` : ''}${isTest ? `<span>${q.show_results === false ? 'Результат виден автору' : 'Результат после отправки'}</span>` : ''}</div>
|
||||
${q.description ? `<div class="qp-desc">${renderMd(q.description)}</div>` : ''}
|
||||
${assetsHtml(state.quizAssets)}
|
||||
${q.requires_code ? `<div class="settings-field" style="margin-top:14px">
|
||||
<label for="qpAccessCode">Код доступа</label>
|
||||
<input class="settings-input" id="qpAccessCode" maxlength="64" autocomplete="off" placeholder="Введите код">
|
||||
<div class="qp-hint">Код выдает тьютор.</div>
|
||||
</div>` : ''}
|
||||
<div class="qp-actions">
|
||||
<button type="button" class="btn-primary" data-act="start">Начать</button>
|
||||
<span class="qp-hint">${isTest ? 'Вход в систему не нужен.' : 'Ответы сохраняются без имени и входа в систему.'}</span>
|
||||
${until ? '' : '<button type="button" class="btn-primary" data-act="start">Начать</button>'}
|
||||
<span class="qp-hint">${until ? `Вы уже прошли ${isTest ? 'этот тест' : 'этот опрос'} в этом браузере.` : (isTest ? 'Вход в систему не нужен.' : 'Ответы сохраняются без имени и входа в систему.')}</span>
|
||||
</div>
|
||||
${until ? `<div class="qp-hint" id="qpRetryTimer" style="margin-top:8px">${esc2(retryLeftText(until))}</div>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -163,11 +269,16 @@
|
||||
if (!state.quiz) return;
|
||||
body.innerHTML = state.attempt ? renderQuestions() : introHtml();
|
||||
if (state.attempt) {
|
||||
stopRetryTimer();
|
||||
updateProgress();
|
||||
const deadline = state.quiz.time_limit_min > 0
|
||||
? new Date(state.attempt.started_at).getTime() + state.quiz.time_limit_min * 60000
|
||||
: 0;
|
||||
startTimer(deadline);
|
||||
} else {
|
||||
const until = retryUntil();
|
||||
if (until) startRetryTimer(until);
|
||||
else stopRetryTimer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,16 +322,21 @@
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const until = retryUntil();
|
||||
if (until) { toast(retryLeftText(until), true); return; }
|
||||
const btn = document.querySelector('[data-act="start"]');
|
||||
if (btn) btn.disabled = true;
|
||||
const codeInput = document.getElementById('qpAccessCode');
|
||||
const code = codeInput ? codeInput.value.trim() : '';
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
body: JSON.stringify({ code }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось начать');
|
||||
state.code = code;
|
||||
state.attempt = {
|
||||
id: data.attempt.id,
|
||||
started_at: data.attempt.started_at,
|
||||
@@ -264,6 +380,7 @@
|
||||
if (!result) hint = 'Ответы сохранены. Подробный результат автор скрыл.';
|
||||
else if (hiddenAnswers) hint = 'Ответы сохранены. Автор скрыл разбор ответов.';
|
||||
}
|
||||
const until = retryUntil();
|
||||
document.getElementById('qpBody').innerHTML = `<div class="qp-card qp-done">
|
||||
<div class="qp-done-ic">${isTest && result && result.passed === false ? '•' : '✓'}</div>
|
||||
<div class="qp-title">${isTest ? 'Тест завершён' : 'Спасибо!'}</div>
|
||||
@@ -272,7 +389,9 @@
|
||||
<p class="qp-hint" style="margin-top:8px">${esc2(hint)}</p>
|
||||
${details}
|
||||
<div class="qp-actions" style="justify-content:center">
|
||||
<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>
|
||||
${until
|
||||
? `<span class="qp-hint">${esc2(retryLeftText(until))}</span>`
|
||||
: '<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>'}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -280,6 +399,19 @@
|
||||
async function submit(auto) {
|
||||
if (!state.attempt) return;
|
||||
if (!auto) {
|
||||
for (let i = 0; i < state.questions.length; i++) {
|
||||
const q = state.questions[i];
|
||||
if (q.required === false) continue;
|
||||
const answered = isFree(q.kind)
|
||||
? !!String(state.texts.get(q.id) || '').trim()
|
||||
: !!(state.selection.get(q.id) || new Set()).size;
|
||||
if (!answered) {
|
||||
toast(`Вопрос ${i + 1}: ответ обязателен`, true);
|
||||
const qEl = document.querySelectorAll('.qz-q')[i];
|
||||
if (qEl) qEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < state.questions.length; i++) {
|
||||
const q = state.questions[i];
|
||||
if (!isFree(q.kind) || q.required === false || !(q.min_length > 0)) continue;
|
||||
@@ -289,13 +421,6 @@
|
||||
return;
|
||||
}
|
||||
}
|
||||
const missing = state.questions.filter(q => {
|
||||
if (q.required === false) return false;
|
||||
return isFree(q.kind)
|
||||
? !String(state.texts.get(q.id) || '').trim()
|
||||
: !(state.selection.get(q.id) || new Set()).size;
|
||||
}).length;
|
||||
if (missing && !confirm(`Без ответа осталось вопросов: ${missing}. Отправить?`)) return;
|
||||
}
|
||||
const btn = document.querySelector('[data-act="submit"]');
|
||||
if (btn) btn.disabled = true;
|
||||
@@ -303,17 +428,19 @@
|
||||
question_id: q.id,
|
||||
option_ids: isFree(q.kind) ? [] : [...(state.selection.get(q.id) || new Set())],
|
||||
text: isFree(q.kind) ? (state.texts.get(q.id) || '') : '',
|
||||
answer_id: isSystemKind(q.kind) ? (state.systemIds.get(q.id) || null) : null,
|
||||
}));
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts/' + state.attempt.id, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: state.attempt.anon_token, answers }),
|
||||
body: JSON.stringify({ token: state.attempt.anon_token, answers, time_up: auto === true }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
|
||||
stopTimer();
|
||||
state.done = true;
|
||||
markRetry();
|
||||
renderDone(data);
|
||||
} catch (e) {
|
||||
toast(e.message, true);
|
||||
@@ -345,12 +472,37 @@
|
||||
}
|
||||
});
|
||||
document.addEventListener('input', e => {
|
||||
if (e.target.dataset.qtext) {
|
||||
state.texts.set(Number(e.target.dataset.qtext), e.target.value);
|
||||
const el = e.target;
|
||||
if (el.dataset.qtext) {
|
||||
const qid = Number(el.dataset.qtext);
|
||||
state.texts.set(qid, el.value);
|
||||
updateProgress();
|
||||
if (el.dataset.qsys) {
|
||||
state.systemIds.delete(qid);
|
||||
const kind = el.dataset.qsys;
|
||||
clearTimeout(state.sugTimers.get(qid));
|
||||
state.sugTimers.set(qid, setTimeout(() => systemLookup(qid, kind, el.value), 250));
|
||||
}
|
||||
}
|
||||
});
|
||||
document.addEventListener('click', e => {
|
||||
const sug = e.target.closest('[data-sug-id]');
|
||||
if (sug) {
|
||||
e.preventDefault();
|
||||
const qid = Number(sug.dataset.sugQ);
|
||||
const name = sug.dataset.sugName || '';
|
||||
state.systemIds.set(qid, Number(sug.dataset.sugId));
|
||||
state.texts.set(qid, name);
|
||||
const input = document.querySelector('[data-qsys][data-qtext="' + qid + '"]');
|
||||
if (input) input.value = name;
|
||||
const box = document.querySelector('[data-sug="' + qid + '"]');
|
||||
if (box) { box.hidden = true; box.innerHTML = ''; }
|
||||
updateProgress();
|
||||
return;
|
||||
}
|
||||
if (!e.target.closest('.qz-suggest-wrap')) {
|
||||
document.querySelectorAll('.qz-suggest').forEach(box => { box.hidden = true; });
|
||||
}
|
||||
const act = e.target.closest('[data-act]');
|
||||
if (act) {
|
||||
if (act.dataset.act === 'start') { e.preventDefault(); start(); return; }
|
||||
|
||||
+164
-11
@@ -1,5 +1,7 @@
|
||||
(function () {
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
const SYSTEM_KINDS = ['student', 'group', 'branch', 'module'];
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS];
|
||||
const SYSTEM_LABELS = { student: 'ученика', group: 'группы', branch: 'филиала', module: 'темы модуля' };
|
||||
const params = new URLSearchParams(location.search);
|
||||
const quizId = parseInt(params.get('id'), 10);
|
||||
const state = {
|
||||
@@ -9,7 +11,10 @@
|
||||
attempt: null,
|
||||
selection: new Map(),
|
||||
texts: new Map(),
|
||||
systemIds: new Map(),
|
||||
sugTimers: new Map(),
|
||||
timer: null,
|
||||
retryTimer: null,
|
||||
result: null,
|
||||
revealed: false,
|
||||
tab: params.get('tab') === 'stats' ? 'stats' : params.get('tab') === 'attempts' ? 'attempts' : 'take',
|
||||
@@ -54,6 +59,58 @@
|
||||
return arr;
|
||||
}
|
||||
|
||||
function retryKey() {
|
||||
return 'whatido_quiz_retry_' + quizId;
|
||||
}
|
||||
|
||||
function retryUntil() {
|
||||
const min = Number(state.quiz && state.quiz.retry_cooldown_min) || 0;
|
||||
if (min <= 0) return 0;
|
||||
let raw = null;
|
||||
try { raw = localStorage.getItem(retryKey()); } catch (e) { raw = null; }
|
||||
const at = parseInt(raw, 10);
|
||||
if (!Number.isFinite(at)) return 0;
|
||||
const until = at + min * 60000;
|
||||
if (Date.now() >= until) {
|
||||
try { localStorage.removeItem(retryKey()); } catch (e) { /* ignore */ }
|
||||
return 0;
|
||||
}
|
||||
return until;
|
||||
}
|
||||
|
||||
function markRetry() {
|
||||
if (!(Number(state.quiz && state.quiz.retry_cooldown_min) > 0)) return;
|
||||
try { localStorage.setItem(retryKey(), String(Date.now())); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
function retryLeftText(until) {
|
||||
const left = Math.max(0, until - Date.now());
|
||||
const min = Math.floor(left / 60000);
|
||||
const sec = Math.floor((left % 60000) / 1000);
|
||||
return `Повторно пройти можно через ${min} мин ${sec} сек`;
|
||||
}
|
||||
|
||||
function stopRetryTimer() {
|
||||
if (state.retryTimer) clearInterval(state.retryTimer);
|
||||
state.retryTimer = null;
|
||||
}
|
||||
|
||||
function startRetryTimer(until) {
|
||||
stopRetryTimer();
|
||||
const tick = () => {
|
||||
const el = document.getElementById('qzRetryTimer');
|
||||
if (!el) { stopRetryTimer(); return; }
|
||||
if (Date.now() >= until) {
|
||||
stopRetryTimer();
|
||||
renderTab();
|
||||
return;
|
||||
}
|
||||
el.textContent = retryLeftText(until);
|
||||
};
|
||||
tick();
|
||||
state.retryTimer = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return kind === 'survey' ? 'Опрос' : 'Тест';
|
||||
}
|
||||
@@ -87,6 +144,7 @@
|
||||
q.author_name ? `<span>Автор: ${esc(q.author_name)}</span>` : '',
|
||||
q.max_attempts != null ? `<span>Попыток: ${q.max_attempts}</span>` : '',
|
||||
q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : '',
|
||||
q.retry_cooldown_min ? `<span>Повтор: через ${q.retry_cooldown_min} мин</span>` : '',
|
||||
q.kind === 'test' ? `<span>Порог: ${q.pass_percent}%</span>` : '',
|
||||
`</div>`,
|
||||
`<div class="qz-badges">`,
|
||||
@@ -123,6 +181,13 @@
|
||||
if (!q.is_published) {
|
||||
return '<div class="qz-panel"><p class="qz-hint" style="margin:0">Тест не опубликован. Пройти его может только автор после публикации.</p></div>';
|
||||
}
|
||||
const until = retryUntil();
|
||||
if (until) {
|
||||
return `<div class="qz-panel">
|
||||
<p class="qz-hint" style="margin:0 0 6px">Вы уже прошли ${q.kind === 'survey' ? 'этот опрос' : 'этот тест'} в этом браузере.</p>
|
||||
<p class="qz-hint" id="qzRetryTimer" style="margin:0">${retryLeftText(until)}</p>
|
||||
</div>`;
|
||||
}
|
||||
return `<div class="qz-panel">
|
||||
<div class="qz-sub" style="margin:0 0 10px">
|
||||
${q.kind === 'test' ? 'После отправки ответов будет показан результат.' : 'Ответы сохранятся без оценки.'}
|
||||
@@ -136,7 +201,23 @@
|
||||
return FREE_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function isSystemKind(kind) {
|
||||
return SYSTEM_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function systemAnswerHtml(q) {
|
||||
const value = state.texts.get(q.id) || '';
|
||||
const picked = state.systemIds.get(q.id) || '';
|
||||
const label = SYSTEM_LABELS[q.kind] || 'названия';
|
||||
return `<div class="qz-suggest-wrap">
|
||||
<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" data-qsys="${q.kind}" placeholder="Начните вводить название ${label}" autocomplete="off" maxlength="200" value="${esc(value)}">
|
||||
<input type="hidden" data-qsysid="${q.id}" value="${picked}">
|
||||
<div class="qz-suggest" data-sug="${q.id}" hidden></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function freeAnswerHtml(q) {
|
||||
if (isSystemKind(q.kind)) return systemAnswerHtml(q);
|
||||
const value = state.texts.get(q.id) || '';
|
||||
const hint = q.required !== false && q.min_length > 0
|
||||
? `<div class="qz-hint" style="margin-top:4px">Минимум ${q.min_length} символов</div>`
|
||||
@@ -153,6 +234,32 @@
|
||||
return `<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000" value="${esc(value)}">${hint}`;
|
||||
}
|
||||
|
||||
async function systemLookup(qid, kind, term) {
|
||||
const box = document.querySelector('[data-sug="' + qid + '"]');
|
||||
if (!box) return;
|
||||
const text = String(term || '').trim();
|
||||
if (!text) {
|
||||
box.hidden = true;
|
||||
box.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/system-options?field=' + encodeURIComponent(kind) + '&q=' + encodeURIComponent(text), { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
box.hidden = true;
|
||||
return;
|
||||
}
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
box.innerHTML = items.length
|
||||
? items.map(it => `<button type="button" class="qz-sug-item" data-sug-q="${qid}" data-sug-id="${it.id}" data-sug-name="${at(it.name)}"><span>${esc(it.name)}</span>${it.sub ? `<small>${esc(it.sub)}</small>` : ''}</button>`).join('')
|
||||
: '<div class="qz-sug-empty">Ничего не найдено</div>';
|
||||
box.hidden = false;
|
||||
} catch (e) {
|
||||
box.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
function questionTakeHtml(q, index) {
|
||||
const opts = q.options || [];
|
||||
const chosen = state.selection.get(q.id) || new Set();
|
||||
@@ -189,8 +296,12 @@
|
||||
if (!state.attempt) {
|
||||
body.innerHTML = takeIntroHtml();
|
||||
renderIcons();
|
||||
const until = retryUntil();
|
||||
if (until) startRetryTimer(until);
|
||||
else stopRetryTimer();
|
||||
return;
|
||||
}
|
||||
stopRetryTimer();
|
||||
const list = state.questions.map(questionTakeHtml).join('');
|
||||
const deadline = state.quiz.time_limit_min > 0
|
||||
? new Date(state.attempt.started_at).getTime() + state.quiz.time_limit_min * 60000
|
||||
@@ -323,7 +434,7 @@
|
||||
? q.options.map(o => {
|
||||
const okClass = data.revealed ? (o.is_correct ? ' ok' : selected.has(Number(o.id)) ? ' bad' : '') : (selected.has(Number(o.id)) ? ' ok' : '');
|
||||
const tag = data.revealed && o.is_correct ? ' ✓' : '';
|
||||
return `<div class="qz-opt${okClass}"><span class="qz-opt-text">${esc(o.text)}${tag}</span>${data.revealed && o.weight ? `<span class="qz-opt-weight">вес ${o.weight}</span>` : ''}</div>`;
|
||||
return `<div class="qz-opt${okClass}"><span class="qz-opt-text">${esc(o.text)}${tag}</span>${data.revealed && o.weight ? `<span class="qz-opt-weight">балл ${o.weight}</span>` : ''}</div>`;
|
||||
}).join('')
|
||||
: '';
|
||||
return `<section class="qz-q">
|
||||
@@ -420,6 +531,8 @@
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const until = retryUntil();
|
||||
if (until) { showToast(retryLeftText(until), true); return; }
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts', { method: 'POST', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
@@ -431,6 +544,8 @@
|
||||
}
|
||||
state.selection = new Map();
|
||||
state.texts = new Map();
|
||||
state.systemIds = new Map();
|
||||
state.sugTimers = new Map();
|
||||
state.result = null;
|
||||
state.attemptDetail = null;
|
||||
renderTake();
|
||||
@@ -442,6 +557,19 @@
|
||||
async function submit(auto) {
|
||||
if (!state.attempt) return;
|
||||
if (!auto) {
|
||||
for (let i = 0; i < state.questions.length; i++) {
|
||||
const q = state.questions[i];
|
||||
if (q.required === false) continue;
|
||||
const answered = isFree(q.kind)
|
||||
? !!String(state.texts.get(q.id) || '').trim()
|
||||
: !!(state.selection.get(q.id) || new Set()).size;
|
||||
if (!answered) {
|
||||
showToast(`Вопрос ${i + 1}: ответ обязателен`, true);
|
||||
const qEl = document.querySelectorAll('#qzQuestions .qz-q')[i];
|
||||
if (qEl) qEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < state.questions.length; i++) {
|
||||
const q = state.questions[i];
|
||||
if (!isFree(q.kind) || q.required === false || !(q.min_length > 0)) continue;
|
||||
@@ -451,13 +579,6 @@
|
||||
return;
|
||||
}
|
||||
}
|
||||
const missing = state.questions.filter(q => {
|
||||
if (q.required === false) return false;
|
||||
return isFree(q.kind)
|
||||
? !String(state.texts.get(q.id) || '').trim()
|
||||
: !(state.selection.get(q.id) || new Set()).size;
|
||||
}).length;
|
||||
if (missing && !confirm(`Без ответа осталось вопросов: ${missing}. Отправить?`)) return;
|
||||
}
|
||||
const btn = document.querySelector('[data-act="submit"]');
|
||||
if (btn) btn.disabled = true;
|
||||
@@ -465,12 +586,13 @@
|
||||
question_id: q.id,
|
||||
option_ids: isFree(q.kind) ? [] : [...(state.selection.get(q.id) || new Set())],
|
||||
text: isFree(q.kind) ? (state.texts.get(q.id) || '') : '',
|
||||
answer_id: isSystemKind(q.kind) ? (state.systemIds.get(q.id) || null) : null,
|
||||
}));
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/' + state.attempt.id, {
|
||||
method: 'PUT',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify({ answers }),
|
||||
body: JSON.stringify({ answers, time_up: auto === true }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
|
||||
@@ -479,6 +601,7 @@
|
||||
state.result = data.result;
|
||||
state.revealed = data.revealed;
|
||||
state.tab = 'take';
|
||||
markRetry();
|
||||
renderTab();
|
||||
await loadQuiz(true);
|
||||
showToast(data.revealed ? 'Ответы отправлены' : 'Ответы сохранены');
|
||||
@@ -489,6 +612,8 @@
|
||||
}
|
||||
|
||||
async function restart() {
|
||||
const until = retryUntil();
|
||||
if (until) { showToast(retryLeftText(until), true); return; }
|
||||
if (!confirm('Начать попытку заново? Текущие ответы не сохранятся.')) return;
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/restart', {
|
||||
@@ -503,6 +628,8 @@
|
||||
state.attemptDetail = null;
|
||||
state.selection = new Map();
|
||||
state.texts = new Map();
|
||||
state.systemIds = new Map();
|
||||
state.sugTimers = new Map();
|
||||
renderTake();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
@@ -548,11 +675,35 @@
|
||||
document.addEventListener('input', e => {
|
||||
const el = e.target;
|
||||
if (el.dataset.qtext) {
|
||||
state.texts.set(Number(el.dataset.qtext), el.value);
|
||||
const qid = Number(el.dataset.qtext);
|
||||
state.texts.set(qid, el.value);
|
||||
updateProgress();
|
||||
if (el.dataset.qsys) {
|
||||
state.systemIds.delete(qid);
|
||||
const kind = el.dataset.qsys;
|
||||
clearTimeout(state.sugTimers.get(qid));
|
||||
state.sugTimers.set(qid, setTimeout(() => systemLookup(qid, kind, el.value), 250));
|
||||
}
|
||||
}
|
||||
});
|
||||
document.addEventListener('click', e => {
|
||||
const sug = e.target.closest('[data-sug-id]');
|
||||
if (sug) {
|
||||
e.preventDefault();
|
||||
const qid = Number(sug.dataset.sugQ);
|
||||
const name = sug.dataset.sugName || '';
|
||||
state.systemIds.set(qid, Number(sug.dataset.sugId));
|
||||
state.texts.set(qid, name);
|
||||
const input = document.querySelector('[data-qsys][data-qtext="' + qid + '"]');
|
||||
if (input) input.value = name;
|
||||
const box = document.querySelector('[data-sug="' + qid + '"]');
|
||||
if (box) { box.hidden = true; box.innerHTML = ''; }
|
||||
updateProgress();
|
||||
return;
|
||||
}
|
||||
if (!e.target.closest('.qz-suggest-wrap')) {
|
||||
document.querySelectorAll('.qz-suggest').forEach(box => { box.hidden = true; });
|
||||
}
|
||||
const tabBtn = e.target.closest('[data-act="tab"]');
|
||||
if (tabBtn) {
|
||||
e.preventDefault();
|
||||
@@ -606,6 +757,8 @@
|
||||
state.revealed = false;
|
||||
state.selection = new Map();
|
||||
state.texts = new Map();
|
||||
state.systemIds = new Map();
|
||||
state.sugTimers = new Map();
|
||||
} else {
|
||||
state.attempt = prevAttempt;
|
||||
state.result = prevResult;
|
||||
|
||||
@@ -728,7 +728,7 @@
|
||||
if (!(await checkAuth())) return;
|
||||
buildSidebar(document.body.dataset.page);
|
||||
const scalesBtn = document.getElementById('quizScalesBtn');
|
||||
if (scalesBtn) scalesBtn.hidden = !(currentUser && currentUser.role === 'admin');
|
||||
if (scalesBtn) scalesBtn.hidden = false;
|
||||
bind();
|
||||
bindVisibility();
|
||||
renderIcons();
|
||||
|
||||
@@ -69,6 +69,8 @@
|
||||
.qe-anon-link .btn-link { white-space: nowrap; }
|
||||
.qe-min-len { display: inline-flex; align-items: center; gap: 6px; font-size: .78rem; font-weight: 600; color: var(--muted); }
|
||||
.qe-min-len input { width: 80px; padding: 5px 8px; font-size: .82rem; }
|
||||
.qe-points { font-size: .74rem; font-weight: 600; color: var(--muted); white-space: nowrap; padding: 3px 8px; border: 1px solid var(--border); border-radius: 999px; }
|
||||
.qe-total { font-size: .82rem; font-weight: 700; color: var(--accent); white-space: nowrap; }
|
||||
</style>
|
||||
</head>
|
||||
<body data-page="quizzes">
|
||||
@@ -78,6 +80,7 @@
|
||||
<div class="qe-bar">
|
||||
<a class="btn-link" href="quizzes.html">← К списку</a>
|
||||
<div class="qe-bar-title" id="qeBarTitle">Тест</div>
|
||||
<span class="qe-total" id="qeTotalPoints" hidden>Всего баллов: 0</span>
|
||||
<span class="qe-dirty" id="qeDirty" hidden>не сохранено</span>
|
||||
<div class="qe-bar-actions">
|
||||
<a class="btn-primary ghost" id="qePreviewBtn" href="#" target="_blank" rel="noopener noreferrer">Открыть</a>
|
||||
@@ -125,7 +128,12 @@
|
||||
<label for="qeTime">Время, мин</label>
|
||||
<input id="qeTime" type="number" min="0" max="1440" class="settings-input" placeholder="0">
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="qeRetry">Повтор, мин</label>
|
||||
<input id="qeRetry" type="number" min="0" max="10080" class="settings-input" placeholder="0">
|
||||
</div>
|
||||
</div>
|
||||
<div class="qe-hint">Через сколько минут можно пройти повторно в этом браузере. 0 — без ограничения.</div>
|
||||
<div class="settings-field" style="margin-top:10px">
|
||||
<label class="toggle"><input type="checkbox" id="qePublished"><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Опубликован</small></span></label>
|
||||
</div>
|
||||
@@ -151,6 +159,11 @@
|
||||
<div class="settings-field">
|
||||
<label class="toggle"><input type="checkbox" id="qeAnonymous"><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Доступ по ссылке</small></span></label>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="qeAccessCode">Код доступа</label>
|
||||
<input class="settings-input" id="qeAccessCode" maxlength="64" placeholder="Например, 2026" autocomplete="off">
|
||||
<div class="qe-hint">Для тестов с системными полями («Ученик», «Группа», «Филиал», «Тема модуля») код обязателен: ученик вводит его перед началом по ссылке.</div>
|
||||
</div>
|
||||
<div class="qe-hint" id="qeAnonDesc">По ссылке можно пройти без входа в систему.</div>
|
||||
<div class="qe-anon-link" id="qeAnonLink" hidden>
|
||||
<input class="settings-input" id="qeAnonUrl" readonly>
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
.qp-top { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 18px; }
|
||||
.qp-brand { font-size: .82rem; color: var(--muted); }
|
||||
.qp-card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px 22px; }
|
||||
.qp-cover { width: 100%; max-height: 220px; object-fit: cover; border-radius: 10px; display: block; margin-bottom: 14px; }
|
||||
.qp-cover { width: 100%; object-fit: cover; border-radius: 10px; display: block; margin-bottom: 14px; }
|
||||
.qp-title { font-size: 1.35rem; font-weight: 700; line-height: 1.3; }
|
||||
.qp-sub { color: var(--muted); font-size: .84rem; margin-top: 6px; display: flex; flex-wrap: wrap; gap: 6px 14px; }
|
||||
.qp-desc { margin-top: 12px; font-size: .92rem; line-height: 1.65; overflow-wrap: anywhere; }
|
||||
|
||||
+9
-2
@@ -13,7 +13,7 @@
|
||||
@media (max-width: 760px) { .quiz-list { grid-template-columns: 1fr; } }
|
||||
.quiz-card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); display: flex; flex-direction: column; overflow: hidden; transition: box-shadow .15s, transform .15s; }
|
||||
.quiz-card:hover { box-shadow: 0 8px 22px rgba(0,0,0,.08); }
|
||||
.quiz-cover { height: 120px; background: linear-gradient(135deg, rgba(37,99,235,.14), rgba(37,99,235,.04)); display: flex; align-items: center; justify-content: center; overflow: hidden; position: relative; }
|
||||
.quiz-cover { height: 220px; background: linear-gradient(135deg, rgba(37,99,235,.14), rgba(37,99,235,.04)); display: flex; align-items: center; justify-content: center; overflow: hidden; position: relative; }
|
||||
.quiz-cover img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.quiz-cover .quiz-cover-ic { color: var(--accent); opacity: .7; }
|
||||
.quiz-cover .quiz-cover-ic svg { width: 34px; height: 34px; }
|
||||
@@ -76,6 +76,7 @@
|
||||
.qs-item-head { display: flex; align-items: flex-start; gap: 10px; }
|
||||
.qs-item-main { flex: 1; min-width: 0; }
|
||||
.qs-item-name { font-weight: 700; }
|
||||
.qs-tag { font-size: .68rem; font-weight: 600; padding: 1px 7px; border-radius: 999px; background: var(--accent-soft, rgba(99,102,241,.14)); color: var(--accent, #6366f1); vertical-align: 1px; }
|
||||
.qs-item-desc { font-size: .8rem; color: var(--muted); }
|
||||
.qs-item-acts { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.qs-item-ranges { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
@@ -99,7 +100,7 @@
|
||||
<h2>Тесты и опросы</h2>
|
||||
<p class="page-sub">Проверочные тесты с правильными ответами и опросы без оценки</p>
|
||||
<button type="button" class="btn-primary ghost" id="quizAiHistoryBtn" title="История и статусы генерации тестов"><i data-lucide="history"></i> История ИИ</button>
|
||||
<button type="button" class="btn-primary ghost" id="quizScalesBtn" hidden title="Шкалы оценок по набранным баллам"><i data-lucide="award"></i> Критерии оценки</button>
|
||||
<button type="button" class="btn-primary ghost" id="quizScalesBtn" title="Шкалы оценок по набранным баллам"><i data-lucide="award"></i> Критерии оценки</button>
|
||||
<button type="button" class="btn-primary ghost" id="quizAiBtn" style="display:none"><i data-lucide="sparkles"></i> Сгенерировать ИИ</button>
|
||||
<button type="button" class="btn-primary ghost" id="quizNewSurveyBtn"><i data-lucide="clipboard-list"></i> Новый опрос</button>
|
||||
<button type="button" class="btn-primary" id="quizNewTestBtn"><i data-lucide="plus"></i> Новый тест</button>
|
||||
@@ -239,6 +240,12 @@
|
||||
<label for="qsSort">Порядок сортировки</label>
|
||||
<input id="qsSort" type="number" class="settings-input" value="0">
|
||||
</div>
|
||||
<div class="settings-field" id="qsPublicField" hidden>
|
||||
<label for="qsPublic" style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="qsPublic"> Доступна всем пользователям
|
||||
</label>
|
||||
<div class="page-sub" style="font-size:.76rem">Общий критерий видят все пользователи и могут выбрать его в своих тестах.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Диапазоны баллов</label>
|
||||
<div class="page-sub" style="font-size:.76rem;margin-bottom:6px">Минимальный и максимальный балл включительно. Порядок строк не важен — при показе результата берётся диапазон, в который попал набранный балл.</div>
|
||||
|
||||
+23
-3
@@ -29,8 +29,8 @@ const single = {
|
||||
{ id: 3, text: 'C', is_correct: false, weight: 1 },
|
||||
],
|
||||
};
|
||||
ok('single: верный ответ даёт вес варианта × вес вопроса',
|
||||
scoreQuestion(single, [1]).score === 3 && scoreQuestion(single, [1]).max_score === 3,
|
||||
ok('single: верный ответ даёт баллы варианта (без множителя веса вопроса)',
|
||||
scoreQuestion(single, [1]).score === 2 && scoreQuestion(single, [1]).max_score === 2,
|
||||
scoreQuestion(single, [1]));
|
||||
ok('single: неверный ответ — 0',
|
||||
scoreQuestion(single, [3]).score === 0 && scoreQuestion(single, [3]).is_correct === false);
|
||||
@@ -39,7 +39,7 @@ ok('single: два выбранных — неверно',
|
||||
|
||||
const multiple = { kind: 'multiple', weight: 2, partial_credit: false, options: opts };
|
||||
ok('multiple: точное совпадение даёт максимум',
|
||||
scoreQuestion(multiple, [1, 2]).score === 6 && scoreQuestion(multiple, [1, 2]).max_score === 6);
|
||||
scoreQuestion(multiple, [1, 2]).score === 3 && scoreQuestion(multiple, [1, 2]).max_score === 3);
|
||||
ok('multiple: неполный набор — 0',
|
||||
scoreQuestion(multiple, [1]).score === 0);
|
||||
ok('multiple: лишний вариант — 0',
|
||||
@@ -53,6 +53,17 @@ ok('partial: только верные — сумма весов',
|
||||
ok('partial: не уходит ниже нуля',
|
||||
scoreQuestion(partial, [3]).score === 0);
|
||||
|
||||
const fiveCorrect = {
|
||||
kind: 'multiple',
|
||||
weight: 0,
|
||||
partial_credit: true,
|
||||
options: [1, 2, 3, 4, 5].map(id => ({ id, text: String(id), is_correct: true, weight: 2 })),
|
||||
};
|
||||
ok('partial: 5 вариантов по 2 балла, выбраны 3 верных — 6 из 10',
|
||||
scoreQuestion(fiveCorrect, [1, 2, 3]).score === 6 &&
|
||||
scoreQuestion(fiveCorrect, [1, 2, 3]).max_score === 10,
|
||||
scoreQuestion(fiveCorrect, [1, 2, 3]));
|
||||
|
||||
const textExact = { kind: 'text', weight: 2, text_match: 'exact', accepted_answers: ['Четыре', '4'] };
|
||||
ok('text exact: регистр, «ё» и пробелы не важны',
|
||||
scoreQuestion(textExact, [], ' ЧЕТЫРЕ ').score === 2 &&
|
||||
@@ -84,6 +95,15 @@ ok('QUESTION_KINDS содержит строку, список, число и д
|
||||
['single', 'multiple', 'select', 'line', 'text', 'number', 'date'].every(k => QUESTION_KINDS.has(k)),
|
||||
[...QUESTION_KINDS]);
|
||||
|
||||
ok('QUESTION_KINDS содержит системные поля',
|
||||
['student', 'group', 'branch', 'module'].every(k => QUESTION_KINDS.has(k)),
|
||||
[...QUESTION_KINDS]);
|
||||
|
||||
const systemScore = scoreQuestion({ kind: 'student', weight: 2, options: [] }, [], 'Иван Иванов');
|
||||
ok('системное поле не оценивается автоматически (0/0, ручная проверка)',
|
||||
systemScore.score === 0 && systemScore.max_score === 0 && systemScore.is_correct === null,
|
||||
systemScore);
|
||||
|
||||
const selectQ = {
|
||||
kind: 'select',
|
||||
weight: 1,
|
||||
|
||||
@@ -98,6 +98,8 @@ const {
|
||||
getPublicQuiz,
|
||||
startPublicAttempt,
|
||||
submitPublicAttempt,
|
||||
lookupSystemOptions,
|
||||
lookupPublicQuizOptions,
|
||||
listAttempts: listQuizAttempts,
|
||||
getAttempt: getQuizAttempt,
|
||||
quizStats,
|
||||
@@ -933,6 +935,15 @@ const fileLimiter = rateLimit({
|
||||
message: { error: 'Слишком много запросов. Попробуйте позже.' },
|
||||
});
|
||||
|
||||
const quizLookupLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
max: Math.max(1, parseInt(process.env.FILE_LIMIT_MAX || '1200', 10) || 1200),
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
store: cache.rateLimitStore('quiz-lookup', 15 * 60 * 1000),
|
||||
message: { error: 'Слишком много запросов. Попробуйте позже.' },
|
||||
});
|
||||
|
||||
const ADMIN_USERNAME = (process.env.ADMIN_USERNAME || 'admin').toLowerCase().trim();
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
|
||||
if (!ADMIN_PASSWORD) {
|
||||
@@ -976,7 +987,8 @@ app.use((req, res, next) => {
|
||||
});
|
||||
next();
|
||||
});
|
||||
const { THUMBS_DIR, thumbFileFor, thumbUnlinkFor, safeUnlink, unlinkMedia } = require('./lib/files');
|
||||
const { THUMBS_DIR, thumbFileFor, thumbUnlinkFor, createFileTools } = require('./lib/files');
|
||||
const { safeUnlink, unlinkMedia } = createFileTools(storage);
|
||||
const ORIGINALS_DIR = path.join(UPLOADS_DIR, '.originals');
|
||||
const THUMB_WIDTH = 480;
|
||||
let sharp = null;
|
||||
@@ -8216,8 +8228,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
}
|
||||
for (const x of (ndata.quiz_grade_scales || [])) {
|
||||
await client.query(
|
||||
'INSERT INTO quiz_grade_scales (id, name, description, sort_order, created_by, created_at, updated_at) VALUES ($1,$2,$3,$4,(SELECT id FROM users WHERE id = $5),$6,$7)',
|
||||
[x.id, x.name, x.description, x.sort_order, x.created_by, x.created_at || null, x.updated_at || null]
|
||||
'INSERT INTO quiz_grade_scales (id, name, description, sort_order, is_shared, created_by, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,(SELECT id FROM users WHERE id = $6),$7,$8)',
|
||||
[x.id, x.name, x.description, x.sort_order, x.is_shared === true, x.created_by, x.created_at || null, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
const restoredScaleIds = new Set((ndata.quiz_grade_scales || []).map(x => x.id));
|
||||
@@ -8230,13 +8242,13 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
}
|
||||
for (const x of (ndata.quizzes || [])) {
|
||||
await client.query(
|
||||
'INSERT INTO quizzes (id, title, description, kind, is_published, shuffle_questions, shuffle_options, show_results, max_attempts, time_limit_min, pass_percent, cover_path, allow_anonymous, author_id, created_at, updated_at, deleted_at, purge_at, show_answers, grade_scale_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,(SELECT id FROM users WHERE id = $14),$15,$16,$17,$18,$19,(SELECT id FROM quiz_grade_scales WHERE id = $20))',
|
||||
'INSERT INTO quizzes (id, title, description, kind, is_published, shuffle_questions, shuffle_options, show_results, max_attempts, time_limit_min, pass_percent, cover_path, allow_anonymous, author_id, created_at, updated_at, deleted_at, purge_at, show_answers, grade_scale_id, access_code, retry_cooldown_min) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,(SELECT id FROM users WHERE id = $14),$15,$16,$17,$18,$19,(SELECT id FROM quiz_grade_scales WHERE id = $20),$21,$22)',
|
||||
[x.id, x.title, x.description, x.kind, x.is_published === true, x.shuffle_questions === true,
|
||||
x.shuffle_options === true, x.show_results !== false, x.max_attempts, x.time_limit_min,
|
||||
x.pass_percent, x.cover_path, x.allow_anonymous === true, x.author_id,
|
||||
x.created_at || null, x.updated_at || null,
|
||||
x.deleted_at || null, x.purge_at || null,
|
||||
x.show_answers !== false, x.grade_scale_id]
|
||||
x.show_answers !== false, x.grade_scale_id, x.access_code || null, x.retry_cooldown_min || 0]
|
||||
);
|
||||
}
|
||||
const restoredQuizIds = new Set((ndata.quizzes || []).map(x => x.id));
|
||||
@@ -8289,9 +8301,9 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
if (!restoredAttemptIds.has(x.attempt_id)) continue;
|
||||
const questionOk = x.question_id != null && restoredQuestionIds.has(x.question_id);
|
||||
await client.query(
|
||||
'INSERT INTO quiz_attempt_answers (id, attempt_id, question_id, question_text, option_ids, answer_snapshot, text_answer, is_correct, score, max_score) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7,$8,$9,$10)',
|
||||
'INSERT INTO quiz_attempt_answers (id, attempt_id, question_id, question_text, option_ids, answer_snapshot, text_answer, answer_id, is_correct, score, max_score) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7,$8,$9,$10,$11)',
|
||||
[x.id, x.attempt_id, questionOk ? x.question_id : null, x.question_text, x.option_ids,
|
||||
JSON.stringify(x.answer_snapshot || {}), x.text_answer, x.is_correct, x.score, x.max_score]
|
||||
JSON.stringify(x.answer_snapshot || {}), x.text_answer, x.answer_id || null, x.is_correct, x.score, x.max_score]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.user_branches) {
|
||||
@@ -15490,13 +15502,13 @@ app.get('/api/quizzes/files/:name', fileLimiter, async (req, res) => {
|
||||
|
||||
app.get('/api/grade-scales', requireAuth, async (req, res) => {
|
||||
try {
|
||||
res.json({ items: await listGradeScales(pool) });
|
||||
res.json({ items: await listGradeScales(pool, req.user) });
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось загрузить критерии оценки', 'grade scales list');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/grade-scales/images', requireAdmin, async (req, res) => {
|
||||
app.get('/api/grade-scales/images', requireAuth, async (req, res) => {
|
||||
try {
|
||||
res.json({ items: await listGradeImages(pool) });
|
||||
} catch (e) {
|
||||
@@ -15504,7 +15516,7 @@ app.get('/api/grade-scales/images', requireAdmin, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/grade-scales/upload', requireAdmin, (req, res) => {
|
||||
app.post('/api/grade-scales/upload', requireAuth, (req, res) => {
|
||||
upload.single('photo')(req, res, async err => {
|
||||
if (err) {
|
||||
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
|
||||
@@ -15523,7 +15535,7 @@ app.post('/api/grade-scales/upload', requireAdmin, (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/grade-scales', requireAdmin, async (req, res) => {
|
||||
app.post('/api/grade-scales', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const result = await createGradeScale(pool, req.user, req.body || {});
|
||||
await logAudit(req, 'grade_scale.create', { id: result.item.id, name: result.item.name, ranges: result.item.ranges.length });
|
||||
@@ -15533,9 +15545,9 @@ app.post('/api/grade-scales', requireAdmin, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/grade-scales/:id', requireAdmin, async (req, res) => {
|
||||
app.put('/api/grade-scales/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const result = await updateGradeScale(pool, reqInt(req.params.id), req.body || {});
|
||||
const result = await updateGradeScale(pool, reqInt(req.params.id), req.user, req.body || {});
|
||||
unlinkMedia(result.removed);
|
||||
await logAudit(req, 'grade_scale.update', { id: result.item.id, name: result.item.name, ranges: result.item.ranges.length });
|
||||
res.json(result);
|
||||
@@ -15544,10 +15556,10 @@ app.put('/api/grade-scales/:id', requireAdmin, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/grade-scales/:id', requireAdmin, async (req, res) => {
|
||||
app.delete('/api/grade-scales/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = reqInt(req.params.id);
|
||||
const result = await deleteGradeScale(pool, id);
|
||||
const result = await deleteGradeScale(pool, id, req.user);
|
||||
unlinkMedia(result.removed);
|
||||
await logAudit(req, 'grade_scale.delete', { id });
|
||||
res.json({ ok: true });
|
||||
@@ -15681,6 +15693,16 @@ app.delete('/api/quizzes/assets/:id', requireAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/quizzes/system-options', requireAuth, quizLookupLimiter, async (req, res) => {
|
||||
try {
|
||||
const scope = branchScope(req.user);
|
||||
const result = await lookupSystemOptions(pool, req.query.field, req.query.q, scope.ids);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось загрузить подсказки', 'quiz system options');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/quizzes/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const data = await getQuiz(pool, reqInt(req.params.id), req.user);
|
||||
@@ -15854,7 +15876,10 @@ app.get('/api/public-quizzes/:id', apiLimiter, async (req, res) => {
|
||||
|
||||
app.post('/api/public-quizzes/:id/attempts', apiLimiter, async (req, res) => {
|
||||
try {
|
||||
res.json(await startPublicAttempt(pool, reqInt(req.params.id), { name: req.body?.name }));
|
||||
res.json(await startPublicAttempt(pool, reqInt(req.params.id), {
|
||||
name: req.body?.name,
|
||||
code: typeof req.body?.code === 'string' ? req.body.code : '',
|
||||
}));
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось начать прохождение', 'public quiz attempt start');
|
||||
}
|
||||
@@ -15881,6 +15906,19 @@ app.put('/api/public-quizzes/:id/attempts/:attemptId', apiLimiter, async (req, r
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/public-quizzes/:id/options', quizLookupLimiter, async (req, res) => {
|
||||
try {
|
||||
const result = await lookupPublicQuizOptions(pool, reqInt(req.params.id), {
|
||||
field: req.query.field,
|
||||
query: req.query.q,
|
||||
code: req.query.code,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось загрузить подсказки', 'public quiz options');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/public-quizzes/files/:name', fileLimiter, async (req, res) => {
|
||||
const name = req.params.name;
|
||||
if (!/^[\w,.()-]+$/.test(name)) return res.status(400).end();
|
||||
|
||||
Reference in New Issue
Block a user