Тесты и опросы: генерация ИИ, критерии оценки, версия 2.0
- ИИ-генерация черновиков тестов (lib/quiz-ai.js, quiz-ai-jobs, quiz-ai.selftest.js) - Критерии оценки (quiz_grade_scales/quiz_grade_ranges, lib/quiz-grades.js, public/js/grade-scales.js) - Версия 2.0 формата бэкапа, добавление таблиц тестов в BACKUP_TABLES - Обновление AGENTS.md под новый функционал тестов/опросов
This commit is contained in:
@@ -449,23 +449,26 @@ 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` (только для `survey`).
|
||||
- **Два вида:** `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`.
|
||||
- **У ассета ровно один владелец:** `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` — только для теста.
|
||||
- **Мин. длина ответа:** `quiz_questions.min_length` (0..2000) действует только для `line`/`text` и только при `required = true` — в конструкторе поле появляется после включения «Обязательный». Сервер проверяет длину в `performSubmit` (после `textValue`, то есть по обрезанной строке) и отвечает `400` с текстом «минимум N символов»; клиент блокирует отправку с той же подсказкой. Для `number`/`date` и при `required = false` значение принудительно обнуляется.
|
||||
- **Ответы после завершения:** два независимых флага — `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`).
|
||||
- **Варианты в строку:** `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`).
|
||||
- **Анонимные опросы:** только `kind = 'survey' AND allow_anonymous AND is_published AND deleted_at IS NULL`. Публичная страница `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`). `allow_anonymous` принудительно сбрасывается для `test` (`normalizeMeta`).
|
||||
- **Права:** админ — всё; тьютор создаёт/правит только свои, проходит любые опубликованные. Мутации и `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`.
|
||||
- **Состояние попытки:** `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:** рендерится `public/js/md.js` (`WhatIDoMD.render`) на странице прохождения, в анонимном опросе и в предпросмотре конструктора; описания вопросов/вариантов остаются обычным текстом.
|
||||
- **Soft-delete:** `deleted_at`/`purge_at` по `trashPurgeDays()`, своя корзина в списке (`?deleted=1`, не-admin только свои), физическая чистка — `purgeQuizzes()` из `purgeScheduledDeletions()`; возвращает пути всех ассетов и обложки, вызывающий делает `safeUnlink`. В общий `GET /api/trash` тесты не входят.
|
||||
- **Sweep/бэкап:** `quiz_assets.path` и `quizzes.cover_path` обязаны быть в `sweepOrphanedUploads()` **и** `BROKEN_IMAGE_SOURCES`; все 6 таблиц входят в `BACKUP_TABLES`/`BACKUP_SEQUENCE_TABLES`, нормализуются в `normalizeRestoreData` (числа клампятся `quizInt`, пути — `optUploadPath`, `accepted_answers` дедуплицируются, `anon_token` при восстановлении обнуляется) и восстанавливаются после `users` с проверкой FK; проверки — в `backup.selftest.js` и `quiz.selftest.js`.
|
||||
- **UI:** внутренние страницы (`quizzes.html` — список с корзиной и бейджем «Анонимный», `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`.
|
||||
- **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` и переоткрывается с перезагрузкой списка — фоновые вкладки освобождают слот соединения.
|
||||
|
||||
### 4. API Patterns
|
||||
- **Middleware**: `requireAuth` — читает `X-Auth-Token`, 401 без валидной активной сессии. `requireAdmin` — самодостаточный (внутри вызывает `requireAuth`, если `req.user` ещё нет), 403 при `role !== 'admin'`. `optionalAuth` — для публичных страниц с персонализацией
|
||||
@@ -697,11 +700,15 @@ guards against.
|
||||
| `public/calendar.html` | Календарь: 4 вида (день/неделя/месяц/повестка), мини-календарь, источники, модалка события (page-local CSS) |
|
||||
| `public/js/calendar.js` | Календарь: сетка CSS Grid, drag-to-create, раскладка пересечений, CRUD, localStorage (`calView`/`calAnchor`/`calSources`) |
|
||||
| `lib/quizzes.js` | Тесты и опросы: таблицы `quizzes*`, CRUD, привязка медиа, подсчёт баллов, попытки, статистика, purge и уборка непривязанных ассетов |
|
||||
| `lib/quiz-grades.js` | Критерии оценки: таблицы `quiz_grade_scales`/`quiz_grade_ranges`, CRUD диапазонов, подбор оценки по баллам, список картинок для выбора |
|
||||
| `public/js/grade-scales.js` | Модалка «Критерии оценки» на странице тестов: список шкал, редактор диапазонов, выбор/загрузка картинки |
|
||||
| `public/quizzes.html` / `public/js/quizzes.js` | Список тестов и опросов: фильтры, корзина, карточки, SSE `quizzes_changed` |
|
||||
| `public/quiz-edit.html` / `public/js/quiz-edit.js` | Конструктор: вопросы/варианты, веса и правильные ответы, медиа, обложка, `Ctrl+S` |
|
||||
| `public/quiz.html` / `public/js/quiz.js` | Прохождение: продолжение попытки, таймер, результаты, свои попытки, статистика автора |
|
||||
| `public/quiz-public.html` / `public/js/quiz-public.js` | Анонимный опрос без входа: токен попытки, медиа через публичный роут, Markdown-описание |
|
||||
| `quiz.selftest.js` | Юнит-проверки подсчёта баллов (включая текстовые `exact`/`contains`) и нормализации ответов |
|
||||
| `lib/quiz-ai.js` | ИИ-генерация тестов: системный промпт, разбор JSON от модели (`extractJson`/`normalizeDraft`) и создание черновика через `createQuiz` + `saveQuiz` |
|
||||
| `quiz-ai.selftest.js` | Юнит-проверки разбора ответа модели: markdown-обёртка, алиасы типов, варианты, правильные ответы и ошибки формата |
|
||||
| `lib/sidebar.js` | Дефолтные пункты сайдбара (`DEFAULT_ITEMS`), таблица `sidebar_items` |
|
||||
| `face-id/app.py` | Face-ID сервис: детект лиц и эмбеддинги (insightface / ArcFace), `/health`, `/detect`, `/compare` |
|
||||
| `public/js/feedback.js` | Логика обратной связи: список, модалка, выбор short_messages, ИИ-очередь |
|
||||
|
||||
+28
-2
@@ -25,6 +25,7 @@ const BACKUP_TABLES = [
|
||||
'short_messages', 'feedbacks', 'feedback_versions', 'bookmarks', 'student_face_refs', 'photo_faces',
|
||||
'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', 'sidebar_items', 'digests', 'digest_images', 'farewell_messages', 'calendar_events', 'calendar_action_log',
|
||||
'quizzes', 'quiz_questions', 'quiz_options', 'quiz_assets', 'quiz_attempts', 'quiz_attempt_answers',
|
||||
'quiz_grade_scales', 'quiz_grade_ranges',
|
||||
];
|
||||
const BACKUP_SEQUENCE_TABLES = [
|
||||
'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos',
|
||||
@@ -33,6 +34,7 @@ const BACKUP_SEQUENCE_TABLES = [
|
||||
'chat_attachments', 'short_messages', 'feedbacks', 'bookmarks', 'student_face_refs', 'photo_faces',
|
||||
'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', 'sidebar_items', 'digests', 'digest_images', 'farewell_messages', 'calendar_events', 'calendar_action_log',
|
||||
'quizzes', 'quiz_questions', 'quiz_options', 'quiz_assets', 'quiz_attempts', 'quiz_attempt_answers',
|
||||
'quiz_grade_scales', 'quiz_grade_ranges',
|
||||
];
|
||||
|
||||
function isSupportedBackupVersion(data) {
|
||||
@@ -860,6 +862,27 @@ function normalizeRestoreData(data) {
|
||||
if (!Number.isFinite(n)) return def;
|
||||
return Math.min(hi, Math.max(lo, Math.trunc(n)));
|
||||
};
|
||||
const quizScore = v => Math.min(100000, Math.max(0, Math.round((Number(v) || 0) * 100) / 100));
|
||||
const gradeScales = (data.quiz_grade_scales || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
name: optText(x.name, 200) || '',
|
||||
description: optText(x.description, 2000) || null,
|
||||
sort_order: optInt(x.sort_order, -100000, 100000) ?? 0,
|
||||
created_by: x.created_by == null ? null : reqInt(x.created_by),
|
||||
created_at: optTs(x.created_at),
|
||||
updated_at: optTs(x.updated_at),
|
||||
})).filter(x => x.id > 0);
|
||||
const restoredScaleIds = new Set(gradeScales.map(x => x.id));
|
||||
const gradeRanges = (data.quiz_grade_ranges || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
scale_id: reqInt(x.scale_id),
|
||||
min_score: quizScore(x.min_score),
|
||||
max_score: quizScore(x.max_score),
|
||||
label: optText(x.label, 200) || '',
|
||||
image_path: optUploadPath(x.image_path, 300) || null,
|
||||
created_at: optTs(x.created_at),
|
||||
updated_at: optTs(x.updated_at),
|
||||
})).filter(x => x.id > 0 && restoredScaleIds.has(x.scale_id) && x.label);
|
||||
const quizzes = (data.quizzes || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
title: optText(x.title, 200) || '',
|
||||
@@ -869,11 +892,13 @@ function normalizeRestoreData(data) {
|
||||
shuffle_questions: x.shuffle_questions === true,
|
||||
shuffle_options: x.shuffle_options === true,
|
||||
show_results: x.show_results !== false,
|
||||
show_answers: x.show_answers !== false,
|
||||
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),
|
||||
pass_percent: quizInt(x.pass_percent, 0, 100, 60),
|
||||
cover_path: optUploadPath(x.cover_path, 300) || null,
|
||||
allow_anonymous: x.allow_anonymous === true && (quizKinds.includes(x.kind) ? x.kind : 'test') === 'survey',
|
||||
allow_anonymous: x.allow_anonymous === true,
|
||||
author_id: x.author_id == null ? null : reqInt(x.author_id),
|
||||
created_at: optTs(x.created_at),
|
||||
updated_at: optTs(x.updated_at),
|
||||
@@ -947,6 +972,7 @@ function normalizeRestoreData(data) {
|
||||
percent: Math.min(100, quizWeight(x.percent)),
|
||||
passed: x.passed == null ? null : x.passed === true,
|
||||
anon_token: null,
|
||||
guest_name: optText(x.guest_name, 120) || null,
|
||||
started_at: optTs(x.started_at),
|
||||
finished_at: optTs(x.finished_at),
|
||||
})).filter(x => x.quiz_id);
|
||||
@@ -962,7 +988,7 @@ function normalizeRestoreData(data) {
|
||||
score: quizWeight(x.score),
|
||||
max_score: quizWeight(x.max_score),
|
||||
})).filter(x => x.attempt_id);
|
||||
return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, farewell_messages, bookmarks, calendar_events: calendarEvents, calendar_action_log: calendarActionLog, achievement_types: achievementTypes, student_achievements: studentAchievements, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages, doc_files: docFiles, sidebar_items: sidebarItems, digests, digest_images: digestImages, quizzes, quiz_questions: quizQuestions, quiz_options: quizOptions, quiz_assets: quizAssets, quiz_attempts: quizAttempts, quiz_attempt_answers: quizAttemptAnswers };
|
||||
return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, farewell_messages, bookmarks, calendar_events: calendarEvents, calendar_action_log: calendarActionLog, achievement_types: achievementTypes, student_achievements: studentAchievements, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages, doc_files: docFiles, sidebar_items: sidebarItems, digests, digest_images: digestImages, quiz_grade_scales: gradeScales, quiz_grade_ranges: gradeRanges, quizzes, quiz_questions: quizQuestions, quiz_options: quizOptions, quiz_assets: quizAssets, quiz_attempts: quizAttempts, quiz_attempt_answers: quizAttemptAnswers };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
+22
-3
@@ -324,13 +324,24 @@ ok('quizzes входят в бэкап и sequences',
|
||||
BACKUP_TABLES.includes('quizzes') && BACKUP_TABLES.includes('quiz_questions') &&
|
||||
BACKUP_TABLES.includes('quiz_options') && BACKUP_TABLES.includes('quiz_assets') &&
|
||||
BACKUP_TABLES.includes('quiz_attempts') && BACKUP_TABLES.includes('quiz_attempt_answers') &&
|
||||
BACKUP_SEQUENCE_TABLES.includes('quizzes') && BACKUP_SEQUENCE_TABLES.includes('quiz_attempt_answers'));
|
||||
BACKUP_TABLES.includes('quiz_grade_scales') && BACKUP_TABLES.includes('quiz_grade_ranges') &&
|
||||
BACKUP_SEQUENCE_TABLES.includes('quizzes') && BACKUP_SEQUENCE_TABLES.includes('quiz_attempt_answers') &&
|
||||
BACKUP_SEQUENCE_TABLES.includes('quiz_grade_scales') && BACKUP_SEQUENCE_TABLES.includes('quiz_grade_ranges'));
|
||||
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: 3, kind: 'test', title: 'Тест 2', allow_anonymous: true },
|
||||
{ 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: 0, name: 'Битая', sort_order: 0 },
|
||||
],
|
||||
quiz_grade_ranges: [
|
||||
{ id: 7, scale_id: 5, min_score: 0, max_score: 5, label: 'Плохо', image_path: '/uploads/range.png' },
|
||||
{ id: 8, scale_id: 99, min_score: 0, max_score: 1, label: 'Сирота' },
|
||||
{ id: 9, scale_id: 5, min_score: 6, max_score: 15, label: '' },
|
||||
],
|
||||
quiz_questions: [
|
||||
{ id: 1, quiz_id: 1, kind: 'multiple', text: 'Вопрос', weight: 2, partial_credit: true },
|
||||
@@ -357,7 +368,15 @@ ok('quizzes нормализуются: тип/порог/попытки/пут
|
||||
quizRestore.quizzes[0].deleted_at === '2026-11-24T07:00:00.000Z' &&
|
||||
quizRestore.quizzes[1].kind === 'survey' &&
|
||||
quizRestore.quizzes[1].allow_anonymous === true &&
|
||||
quizRestore.quizzes[2].allow_anonymous === false &&
|
||||
quizRestore.quizzes[2].allow_anonymous === true &&
|
||||
quizRestore.quizzes[2].show_answers === false &&
|
||||
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].created_by === 1 &&
|
||||
quizRestore.quiz_grade_ranges.length === 1 &&
|
||||
quizRestore.quiz_grade_ranges[0].scale_id === 5 &&
|
||||
quizRestore.quiz_grade_ranges[0].image_path === '/uploads/range.png' &&
|
||||
quizRestore.quiz_questions.length === 5 &&
|
||||
quizRestore.quiz_questions[1].kind === 'single' &&
|
||||
quizRestore.quiz_questions[2].text_match === 'contains' &&
|
||||
|
||||
+49
@@ -532,6 +532,8 @@ INSERT INTO settings (key, value) VALUES ('lesson_ai_enabled', 'true')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
INSERT INTO settings (key, value) VALUES ('quiz_ai_enabled', 'true')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
INSERT INTO settings (key, value) VALUES ('lesson_ai_prompt', 'Ты — редактор сообщений тьютора детской IT-школы.
|
||||
|
||||
Переработай исходный текст занятия так, чтобы он звучал естественно и грамотно, как будто его написал живой тьютор родителю, а не нейросеть.
|
||||
@@ -911,6 +913,29 @@ CREATE TABLE IF NOT EXISTS calendar_action_log (
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_action_log_created ON calendar_action_log(id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_action_log_user ON calendar_action_log(user_id, id DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS quiz_grade_scales (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
created_by INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
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,
|
||||
min_score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
max_score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
label VARCHAR(200) NOT NULL DEFAULT '',
|
||||
image_path TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_grade_ranges_scale ON quiz_grade_ranges(scale_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS quizzes (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title VARCHAR(200) NOT NULL DEFAULT '',
|
||||
@@ -920,11 +945,13 @@ CREATE TABLE IF NOT EXISTS quizzes (
|
||||
shuffle_questions BOOLEAN NOT NULL DEFAULT false,
|
||||
shuffle_options BOOLEAN NOT NULL DEFAULT false,
|
||||
show_results BOOLEAN NOT NULL DEFAULT true,
|
||||
show_answers BOOLEAN NOT NULL DEFAULT true,
|
||||
max_attempts INT,
|
||||
time_limit_min INT NOT NULL DEFAULT 0,
|
||||
pass_percent INT NOT NULL DEFAULT 60,
|
||||
cover_path TEXT,
|
||||
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
|
||||
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(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -989,6 +1016,7 @@ CREATE TABLE IF NOT EXISTS quiz_attempts (
|
||||
percent NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
passed BOOLEAN,
|
||||
anon_token TEXT,
|
||||
guest_name TEXT,
|
||||
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
finished_at TIMESTAMPTZ
|
||||
);
|
||||
@@ -1019,3 +1047,24 @@ CREATE INDEX IF NOT EXISTS idx_quiz_attempts_quiz ON quiz_attempts(quiz_id, star
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_attempts_user ON quiz_attempts(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_attempt ON quiz_attempt_answers(attempt_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_question ON quiz_attempt_answers(question_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS quiz_ai_jobs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
prompt TEXT NOT NULL,
|
||||
kind VARCHAR(16) NOT NULL DEFAULT 'test',
|
||||
question_count INT NOT NULL DEFAULT 10,
|
||||
difficulty VARCHAR(16) NOT NULL DEFAULT 'medium',
|
||||
profile TEXT NOT NULL DEFAULT '',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'pending',
|
||||
attempts INT NOT NULL DEFAULT 0,
|
||||
quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL,
|
||||
questions INT,
|
||||
model TEXT,
|
||||
error TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
finished_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_status ON quiz_ai_jobs(status, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_user ON quiz_ai_jobs(user_id, status);
|
||||
|
||||
@@ -238,6 +238,7 @@ ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ;
|
||||
CREATE INDEX IF NOT EXISTS idx_user_notes_pending ON user_notes(ai_status, id) WHERE ai_status = 'pending';
|
||||
CREATE INDEX IF NOT EXISTS idx_user_notes_deleted ON user_notes(deleted_at);
|
||||
INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING;
|
||||
INSERT INTO settings (key, value) VALUES ('quiz_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bookmarks (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -1201,6 +1202,29 @@ CREATE TABLE IF NOT EXISTS calendar_action_log (
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_action_log_created ON calendar_action_log(id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_action_log_user ON calendar_action_log(user_id, id DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS quiz_grade_scales (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
created_by INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
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,
|
||||
min_score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
max_score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
label VARCHAR(200) NOT NULL DEFAULT '',
|
||||
image_path TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_grade_ranges_scale ON quiz_grade_ranges(scale_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS quizzes (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title VARCHAR(200) NOT NULL DEFAULT '',
|
||||
@@ -1210,11 +1234,13 @@ CREATE TABLE IF NOT EXISTS quizzes (
|
||||
shuffle_questions BOOLEAN NOT NULL DEFAULT false,
|
||||
shuffle_options BOOLEAN NOT NULL DEFAULT false,
|
||||
show_results BOOLEAN NOT NULL DEFAULT true,
|
||||
show_answers BOOLEAN NOT NULL DEFAULT true,
|
||||
max_attempts INT,
|
||||
time_limit_min INT NOT NULL DEFAULT 0,
|
||||
pass_percent INT NOT NULL DEFAULT 60,
|
||||
cover_path TEXT,
|
||||
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
|
||||
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(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -1297,11 +1323,14 @@ CREATE TABLE IF NOT EXISTS quiz_attempt_answers (
|
||||
);
|
||||
|
||||
ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS allow_anonymous BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS show_answers BOOLEAN NOT NULL DEFAULT true;
|
||||
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 '{}';
|
||||
ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS min_length INT NOT NULL DEFAULT 0;
|
||||
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;
|
||||
|
||||
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);
|
||||
@@ -1317,6 +1346,34 @@ CREATE INDEX IF NOT EXISTS idx_quiz_attempts_user ON quiz_attempts(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_attempt ON quiz_attempt_answers(attempt_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_question ON quiz_attempt_answers(question_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS quiz_ai_jobs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
prompt TEXT NOT NULL,
|
||||
kind VARCHAR(16) NOT NULL DEFAULT 'test',
|
||||
question_count INT NOT NULL DEFAULT 10,
|
||||
difficulty VARCHAR(16) NOT NULL DEFAULT 'medium',
|
||||
profile TEXT NOT NULL DEFAULT '',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'pending',
|
||||
attempts INT NOT NULL DEFAULT 0,
|
||||
quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL,
|
||||
questions INT,
|
||||
model TEXT,
|
||||
error TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
finished_at TIMESTAMPTZ
|
||||
);
|
||||
ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS attempts INT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS profile TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL;
|
||||
ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS questions INT;
|
||||
ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS model TEXT;
|
||||
ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS error TEXT;
|
||||
ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS finished_at TIMESTAMPTZ;
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_status ON quiz_ai_jobs(status, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_user ON quiz_ai_jobs(user_id, status);
|
||||
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'quiz_assets_one_owner' AND conrelid = 'quiz_assets'::regclass) THEN
|
||||
ALTER TABLE quiz_assets ADD CONSTRAINT quiz_assets_one_owner CHECK (num_nonnulls(quiz_id, question_id, option_id) <= 1) NOT VALID;
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
'use strict';
|
||||
|
||||
const JOB_STATUSES = new Set(['pending', 'processing', 'done', 'error']);
|
||||
const PRUNE_DAYS = 7;
|
||||
const HISTORY_DEFAULT_LIMIT = 20;
|
||||
const HISTORY_MAX_LIMIT = 100;
|
||||
|
||||
function publicJob(row) {
|
||||
if (!row) return null;
|
||||
return {
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
status: JOB_STATUSES.has(row.status) ? row.status : 'pending',
|
||||
kind: row.kind,
|
||||
count: row.question_count,
|
||||
questions: row.questions == null ? null : Number(row.questions),
|
||||
model: row.model || null,
|
||||
quiz_id: row.quiz_id == null ? null : Number(row.quiz_id),
|
||||
error: row.error || null,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
finished_at: row.finished_at,
|
||||
};
|
||||
}
|
||||
|
||||
function historyJob(row) {
|
||||
const job = publicJob(row);
|
||||
if (!job) return null;
|
||||
job.user_name = row.user_name || null;
|
||||
job.user_username = row.user_username || null;
|
||||
job.prompt = row.prompt || '';
|
||||
job.difficulty = row.difficulty || 'medium';
|
||||
job.profile = row.profile || '';
|
||||
job.attempts = Number(row.attempts) || 0;
|
||||
return job;
|
||||
}
|
||||
|
||||
async function listQuizAiJobs(pool, user, options = {}) {
|
||||
const limit = Math.max(1, Math.min(HISTORY_MAX_LIMIT, parseInt(options.limit, 10) || HISTORY_DEFAULT_LIMIT));
|
||||
const offset = Math.max(0, parseInt(options.offset, 10) || 0);
|
||||
const own = user.role !== 'admin';
|
||||
const where = own ? 'WHERE j.user_id = $1' : '';
|
||||
const params = own ? [user.id] : [];
|
||||
params.push(limit, offset);
|
||||
const { rows } = await pool.query(
|
||||
`SELECT j.*, u.name AS user_name, u.username AS user_username
|
||||
FROM quiz_ai_jobs j
|
||||
LEFT JOIN users u ON u.id = j.user_id
|
||||
${where}
|
||||
ORDER BY j.id DESC
|
||||
LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
||||
params
|
||||
);
|
||||
const { rows: countRows } = await pool.query(
|
||||
`SELECT count(*)::int AS total FROM quiz_ai_jobs j ${where}`,
|
||||
own ? [user.id] : []
|
||||
);
|
||||
return { items: rows.map(historyJob), total: countRows[0] ? countRows[0].total : 0 };
|
||||
}
|
||||
|
||||
async function ensureQuizAiJobsTable(pool) {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_ai_jobs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
prompt TEXT NOT NULL,
|
||||
kind VARCHAR(16) NOT NULL DEFAULT 'test',
|
||||
question_count INT NOT NULL DEFAULT 10,
|
||||
difficulty VARCHAR(16) NOT NULL DEFAULT 'medium',
|
||||
profile TEXT NOT NULL DEFAULT '',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'pending',
|
||||
attempts INT NOT NULL DEFAULT 0,
|
||||
quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL,
|
||||
questions INT,
|
||||
model TEXT,
|
||||
error TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
finished_at TIMESTAMPTZ
|
||||
)`);
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS attempts INT NOT NULL DEFAULT 0');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS profile TEXT NOT NULL DEFAULT \'\'');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS questions INT');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS model TEXT');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS error TEXT');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS finished_at TIMESTAMPTZ');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_status ON quiz_ai_jobs(status, id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_user ON quiz_ai_jobs(user_id, status)');
|
||||
}
|
||||
|
||||
async function createQuizAiJob(pool, user, request) {
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO quiz_ai_jobs (user_id, prompt, kind, question_count, difficulty, profile)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING *`,
|
||||
[user.id, request.prompt, request.kind, request.count, request.difficulty, request.profile]
|
||||
);
|
||||
return publicJob(rows[0]);
|
||||
}
|
||||
|
||||
async function findActiveQuizAiJob(pool, userId) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT * FROM quiz_ai_jobs
|
||||
WHERE user_id = $1 AND status IN ('pending', 'processing')
|
||||
ORDER BY id DESC LIMIT 1`,
|
||||
[userId]
|
||||
);
|
||||
return rows.length ? publicJob(rows[0]) : null;
|
||||
}
|
||||
|
||||
async function getQuizAiJob(pool, id, user) {
|
||||
const { rows } = await pool.query('SELECT * FROM quiz_ai_jobs WHERE id = $1', [id]);
|
||||
if (!rows.length) return null;
|
||||
const row = rows[0];
|
||||
if (user.role !== 'admin' && Number(row.user_id) !== Number(user.id)) return null;
|
||||
return publicJob(row);
|
||||
}
|
||||
|
||||
async function claimQuizAiJob(pool) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const { rows } = await client.query(
|
||||
`SELECT id, user_id, prompt, kind, question_count, difficulty, profile
|
||||
FROM quiz_ai_jobs
|
||||
WHERE status = 'pending'
|
||||
ORDER BY id ASC LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED`
|
||||
);
|
||||
if (!rows.length) {
|
||||
await client.query('COMMIT');
|
||||
return null;
|
||||
}
|
||||
await client.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'processing', attempts = attempts + 1, updated_at = now()
|
||||
WHERE id = $1`,
|
||||
[rows[0].id]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return rows[0];
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function finishQuizAiJob(pool, id, result) {
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'done', quiz_id = $2, questions = $3, model = $4,
|
||||
error = NULL, updated_at = now(), finished_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[id, result.quiz.id, result.questions, result.model]
|
||||
);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function failQuizAiJob(pool, id, message) {
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'error', error = $2, updated_at = now(), finished_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[id, String(message || '').slice(0, 500)]
|
||||
);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function resetStaleQuizAiJobs(pool) {
|
||||
await pool.query(`UPDATE quiz_ai_jobs SET status = 'pending', updated_at = now() WHERE status = 'processing'`);
|
||||
}
|
||||
|
||||
async function pruneQuizAiJobs(pool, days = PRUNE_DAYS) {
|
||||
const keep = Math.max(1, parseInt(days, 10) || PRUNE_DAYS);
|
||||
await pool.query(
|
||||
`DELETE FROM quiz_ai_jobs
|
||||
WHERE status IN ('done', 'error')
|
||||
AND updated_at < now() - ($1::int * interval '1 day')`,
|
||||
[keep]
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ensureQuizAiJobsTable,
|
||||
createQuizAiJob,
|
||||
findActiveQuizAiJob,
|
||||
getQuizAiJob,
|
||||
listQuizAiJobs,
|
||||
claimQuizAiJob,
|
||||
finishQuizAiJob,
|
||||
failQuizAiJob,
|
||||
resetStaleQuizAiJobs,
|
||||
pruneQuizAiJobs,
|
||||
};
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
createQuiz,
|
||||
saveQuiz,
|
||||
httpError,
|
||||
QUIZ_QUESTIONS_MAX,
|
||||
QUIZ_OPTIONS_MAX,
|
||||
QUIZ_TITLE_MAX,
|
||||
QUIZ_DESCRIPTION_MAX,
|
||||
QUIZ_TEXT_MAX,
|
||||
QUIZ_DESC_MAX,
|
||||
QUIZ_ANSWER_MAX,
|
||||
QUIZ_ACCEPTED_MAX,
|
||||
QUIZ_ACCEPTED_LEN,
|
||||
} = require('./quizzes');
|
||||
|
||||
const QUIZ_AI_PROMPT_MAX = 4000;
|
||||
const QUIZ_AI_QUESTIONS_DEFAULT = 10;
|
||||
const QUIZ_AI_QUESTIONS_MAX = 40;
|
||||
const QUIZ_AI_TIMEOUT_MS = 300000;
|
||||
const QUIZ_AI_DIFFICULTIES = new Set(['easy', 'medium', 'hard']);
|
||||
const QUIZ_AI_DIFFICULTY_LABELS = { easy: 'лёгкая', medium: 'средняя', hard: 'сложная' };
|
||||
|
||||
const QUIZ_AI_SYSTEM_PROMPT = [
|
||||
'Ты — методист образовательного центра и составляешь проверочные тесты и опросы по описанию пользователя.',
|
||||
'Верни ТОЛЬКО валидный JSON без markdown-разметки, без пояснений и без текста до или после него.',
|
||||
'Схема ответа:',
|
||||
'{"title":"string","description":"string","questions":[{"text":"string","kind":"single","description":"string","options":[{"text":"string","is_correct":true}],"accepted_answers":["string"]}]}',
|
||||
'Правила:',
|
||||
'- kind — один из: single (один верный вариант), multiple (несколько верных), select (выпадающий список), line (короткий свободный ответ), text (развёрнутый свободный ответ), number (число), date (дата).',
|
||||
'- Для single, multiple и select обязательно от 2 до 25 вариантов в options; у single и select ровно один вариант с is_correct = true; у multiple минимум один.',
|
||||
'- Для line, text, number и date options не нужны; в тесте можно указать accepted_answers — список допустимых ответов для автопроверки.',
|
||||
'- Не добавляй description в вопросах и вариантах, если пользователь прямо об этом не просил.',
|
||||
'- Формулируй вопросы и варианты кратко — до 120 символов, без вступлений и пояснений.',
|
||||
'- Все тексты на русском языке, без нумерации вида «1.», без LaTeX и без служебных пометок.',
|
||||
'- Не выдумывай факты, которых нет в описании; раскрывай тему по существу и формулируй вопросы однозначно.',
|
||||
].join('\n');
|
||||
|
||||
const KIND_ALIASES = {
|
||||
single: 'single',
|
||||
single_choice: 'single',
|
||||
singlechoice: 'single',
|
||||
radio: 'single',
|
||||
one: 'single',
|
||||
one_answer: 'single',
|
||||
multiple: 'multiple',
|
||||
multiple_choice: 'multiple',
|
||||
multiplechoice: 'multiple',
|
||||
checkbox: 'multiple',
|
||||
checkboxes: 'multiple',
|
||||
multi: 'multiple',
|
||||
select: 'select',
|
||||
dropdown: 'select',
|
||||
line: 'line',
|
||||
input: 'line',
|
||||
short: 'line',
|
||||
short_text: 'line',
|
||||
short_answer: 'line',
|
||||
text: 'text',
|
||||
long: 'text',
|
||||
long_text: 'text',
|
||||
textarea: 'text',
|
||||
free: 'text',
|
||||
number: 'number',
|
||||
numeric: 'number',
|
||||
int: 'number',
|
||||
integer: 'number',
|
||||
date: 'date',
|
||||
};
|
||||
|
||||
const FREE_KINDS = new Set(['line', 'text', 'number', 'date']);
|
||||
|
||||
function strOf(value, max) {
|
||||
if (value == null) return '';
|
||||
const text = String(value).replace(/\s+/g, ' ').trim();
|
||||
return text.length > max ? text.slice(0, max) : text;
|
||||
}
|
||||
|
||||
function blockOf(value, max) {
|
||||
if (value == null) return '';
|
||||
const text = String(value).replace(/\r\n/g, '\n').trim();
|
||||
return text.length > max ? text.slice(0, max) : text;
|
||||
}
|
||||
|
||||
function stripNumbering(text) {
|
||||
return String(text || '').replace(/^\s*\d+[.)]\s+/, '');
|
||||
}
|
||||
|
||||
function normKind(value) {
|
||||
const key = String(value || '').trim().toLowerCase().replace(/[\s-]+/g, '_');
|
||||
return KIND_ALIASES[key] || 'single';
|
||||
}
|
||||
|
||||
function clampCount(value) {
|
||||
const n = parseInt(value, 10);
|
||||
if (!Number.isFinite(n)) return QUIZ_AI_QUESTIONS_DEFAULT;
|
||||
return Math.max(1, Math.min(QUIZ_AI_QUESTIONS_MAX, n));
|
||||
}
|
||||
|
||||
function quizAiMaxTokens(count) {
|
||||
return Math.min(4096, Math.max(1024, count * 320 + 512));
|
||||
}
|
||||
|
||||
function quizAiUserPrompt({ prompt, kind, count, difficulty }) {
|
||||
const lines = [
|
||||
`Тема и требования пользователя: ${prompt}`,
|
||||
`Формат: ${kind === 'survey' ? 'опрос без правильных ответов' : 'тест с правильными ответами'}.`,
|
||||
`Количество вопросов: ${count}.`,
|
||||
`Сложность: ${QUIZ_AI_DIFFICULTY_LABELS[difficulty] || QUIZ_AI_DIFFICULTY_LABELS.medium}.`,
|
||||
];
|
||||
if (kind === 'survey') lines.push('В вопросах с вариантами не указывай is_correct — просто перечисли варианты.');
|
||||
else lines.push('Отметь правильные ответы is_correct = true и укажи accepted_answers там, где ответ вводится текстом.');
|
||||
lines.push('Ответ — только JSON по схеме, без пояснений.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function stringField(text, key) {
|
||||
const re = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`);
|
||||
const m = re.exec(text);
|
||||
if (!m) return '';
|
||||
try {
|
||||
return JSON.parse('"' + m[1] + '"');
|
||||
} catch (e) {
|
||||
return m[1];
|
||||
}
|
||||
}
|
||||
|
||||
function salvageQuestions(text) {
|
||||
const qKey = text.indexOf('"questions"');
|
||||
const arrStart = qKey === -1 ? text.indexOf('[') : text.indexOf('[', qKey);
|
||||
if (arrStart === -1) return null;
|
||||
const objects = [];
|
||||
let depth = 0;
|
||||
let objStart = -1;
|
||||
let inString = false;
|
||||
let escaped = false;
|
||||
for (let i = arrStart + 1; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inString) {
|
||||
if (escaped) escaped = false;
|
||||
else if (ch === '\\') escaped = true;
|
||||
else if (ch === '"') inString = false;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
inString = true;
|
||||
continue;
|
||||
}
|
||||
if (ch === '{') {
|
||||
if (depth === 0) objStart = i;
|
||||
depth++;
|
||||
} else if (ch === '}') {
|
||||
depth--;
|
||||
if (depth === 0 && objStart !== -1) {
|
||||
try {
|
||||
objects.push(JSON.parse(text.slice(objStart, i + 1)));
|
||||
} catch (e) {
|
||||
void e;
|
||||
}
|
||||
objStart = -1;
|
||||
}
|
||||
} else if (ch === ']' && depth === 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!objects.length) return null;
|
||||
return {
|
||||
title: stringField(text, 'title'),
|
||||
description: stringField(text, 'description'),
|
||||
questions: objects,
|
||||
};
|
||||
}
|
||||
|
||||
function extractJson(raw) {
|
||||
let text = String(raw || '').trim();
|
||||
text = text.replace(/^```[a-z]*\s*/i, '').replace(/\s*```$/i, '').trim();
|
||||
if (!text) throw httpError(502, 'Модель вернула пустой ответ');
|
||||
const objStart = text.indexOf('{');
|
||||
const arrStart = text.indexOf('[');
|
||||
const start = arrStart !== -1 && (objStart === -1 || arrStart < objStart) ? arrStart : objStart;
|
||||
if (start === -1) throw httpError(502, 'Модель вернула ответ без JSON');
|
||||
const close = text[start] === '{' ? '}' : ']';
|
||||
const end = text.lastIndexOf(close);
|
||||
if (end > start) {
|
||||
try {
|
||||
return JSON.parse(text.slice(start, end + 1));
|
||||
} catch (e) {
|
||||
void e;
|
||||
}
|
||||
}
|
||||
const salvaged = salvageQuestions(text);
|
||||
if (salvaged) return salvaged;
|
||||
throw httpError(502, 'Модель вернула повреждённый JSON');
|
||||
}
|
||||
|
||||
function normOptions(raw) {
|
||||
const list = raw.options ?? raw.answers ?? raw.variants ?? raw.choices ?? raw.items;
|
||||
if (!Array.isArray(list)) return [];
|
||||
const seen = new Set();
|
||||
const options = [];
|
||||
for (const item of list) {
|
||||
const source = typeof item === 'string' ? { text: item } : item;
|
||||
if (!source || typeof source !== 'object') continue;
|
||||
const text = stripNumbering(strOf(source.text ?? source.title ?? source.value ?? source.label, QUIZ_TEXT_MAX));
|
||||
if (!text) continue;
|
||||
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' });
|
||||
if (options.length >= QUIZ_OPTIONS_MAX) break;
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function normAccepted(raw) {
|
||||
const list = raw.accepted_answers ?? raw.acceptedAnswers ?? raw.correct_answers ?? raw.answers;
|
||||
if (!Array.isArray(list)) return [];
|
||||
const seen = new Set();
|
||||
const accepted = [];
|
||||
for (const item of list) {
|
||||
const text = strOf(typeof item === 'object' && item ? item.text : item, QUIZ_ACCEPTED_LEN);
|
||||
if (!text) continue;
|
||||
const key = text.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
accepted.push(text);
|
||||
if (accepted.length >= QUIZ_ACCEPTED_MAX) break;
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
|
||||
function normQuestion(raw, quizKind) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const text = stripNumbering(blockOf(raw.text ?? raw.question ?? raw.title ?? raw.prompt, QUIZ_TEXT_MAX));
|
||||
if (!text) return null;
|
||||
const kind = normKind(raw.kind ?? raw.type ?? raw.question_type);
|
||||
const free = FREE_KINDS.has(kind);
|
||||
const question = {
|
||||
kind,
|
||||
text,
|
||||
description: blockOf(raw.description ?? raw.note, QUIZ_DESC_MAX) || null,
|
||||
weight: 1,
|
||||
partial_credit: false,
|
||||
required: true,
|
||||
min_length: 0,
|
||||
options_inline: false,
|
||||
text_match: 'exact',
|
||||
accepted_answers: [],
|
||||
asset_ids: [],
|
||||
options: [],
|
||||
};
|
||||
if (free) {
|
||||
if (quizKind === 'test') question.accepted_answers = normAccepted(raw);
|
||||
return question;
|
||||
}
|
||||
const options = normOptions(raw);
|
||||
if (options.length < 2) return null;
|
||||
if (quizKind === 'test') {
|
||||
const correct = options.filter(o => o.is_correct);
|
||||
if (kind === 'multiple') {
|
||||
if (!correct.length) options[0].is_correct = true;
|
||||
} else {
|
||||
const keep = correct[0] || options[0];
|
||||
options.forEach(o => { o.is_correct = o === keep; });
|
||||
}
|
||||
} else {
|
||||
options.forEach(o => { o.is_correct = false; });
|
||||
}
|
||||
question.options = options;
|
||||
return question;
|
||||
}
|
||||
|
||||
function normalizeDraft(raw, { kind, count, fallbackTitle }) {
|
||||
let body = raw;
|
||||
if (Array.isArray(body)) body = { questions: body };
|
||||
if (body && typeof body === 'object' && !Array.isArray(body.questions)) {
|
||||
const nested = body.quiz || body.test || body.survey || body.data;
|
||||
if (nested && typeof nested === 'object' && !Array.isArray(nested)) body = nested;
|
||||
}
|
||||
if (!body || typeof body !== 'object') throw httpError(502, 'Модель вернула неожиданный формат ответа');
|
||||
const list = Array.isArray(body.questions)
|
||||
? body.questions
|
||||
: Array.isArray(body.items)
|
||||
? body.items
|
||||
: Array.isArray(body.quiz)
|
||||
? body.quiz
|
||||
: [];
|
||||
const limit = Math.min(count, QUIZ_QUESTIONS_MAX);
|
||||
const questions = [];
|
||||
for (const item of list) {
|
||||
const question = normQuestion(item, kind);
|
||||
if (!question) continue;
|
||||
questions.push(question);
|
||||
if (questions.length >= limit) break;
|
||||
}
|
||||
if (!questions.length) throw httpError(502, 'Модель не вернула ни одного корректного вопроса');
|
||||
return {
|
||||
title: strOf(body.title ?? body.name, QUIZ_TITLE_MAX) || fallbackTitle,
|
||||
description: blockOf(body.description ?? body.summary, QUIZ_DESCRIPTION_MAX),
|
||||
questions,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuizAiRequest(body = {}) {
|
||||
const prompt = String(body.prompt ?? '').trim();
|
||||
if (!prompt) throw httpError(400, 'Опишите тему теста');
|
||||
if (prompt.length > QUIZ_AI_PROMPT_MAX) {
|
||||
throw httpError(400, `Описание не может быть длиннее ${QUIZ_AI_PROMPT_MAX} символов`);
|
||||
}
|
||||
const kind = body.kind === 'survey' ? 'survey' : 'test';
|
||||
const count = clampCount(body.count);
|
||||
const difficulty = QUIZ_AI_DIFFICULTIES.has(String(body.difficulty)) ? String(body.difficulty) : 'medium';
|
||||
const rawProfile = body.profile ?? body.model;
|
||||
const profile = rawProfile == null ? '' : String(rawProfile);
|
||||
return { prompt, kind, count, difficulty, profile };
|
||||
}
|
||||
|
||||
async function generateQuizDraft(pool, user, body, deps) {
|
||||
const request = normalizeQuizAiRequest(body);
|
||||
const { prompt, kind, count, difficulty, profile: profileId } = request;
|
||||
const profile = await deps.resolveProfile(profileId, user.id);
|
||||
if (profileId && profileId !== 'native' && !profile) throw httpError(400, 'Профиль ИИ не найден');
|
||||
let answer;
|
||||
try {
|
||||
answer = await deps.complete(
|
||||
QUIZ_AI_SYSTEM_PROMPT,
|
||||
quizAiUserPrompt({ prompt, kind, count, difficulty }),
|
||||
quizAiMaxTokens(count),
|
||||
profile,
|
||||
QUIZ_AI_TIMEOUT_MS
|
||||
);
|
||||
} catch (e) {
|
||||
if (e && e.name === 'AbortError') {
|
||||
throw httpError(504, `Модель не ответила за ${Math.round(QUIZ_AI_TIMEOUT_MS / 1000)} с — попробуйте меньше вопросов или другую модель`);
|
||||
}
|
||||
throw httpError(502, 'Сервис ИИ недоступен: ' + (e && e.message ? e.message : 'ошибка запроса'));
|
||||
}
|
||||
const fallbackTitle = kind === 'survey'
|
||||
? `Опрос: ${prompt.slice(0, 120)}`
|
||||
: `Тест: ${prompt.slice(0, 120)}`;
|
||||
const draft = normalizeDraft(extractJson(answer), { kind, count, fallbackTitle });
|
||||
const created = await createQuiz(pool, user, { kind, title: draft.title });
|
||||
const id = created.quiz.id;
|
||||
let saved;
|
||||
try {
|
||||
saved = await saveQuiz(pool, id, user, {
|
||||
kind,
|
||||
title: draft.title,
|
||||
description: draft.description || null,
|
||||
is_published: false,
|
||||
show_results: true,
|
||||
questions: draft.questions,
|
||||
});
|
||||
} catch (e) {
|
||||
await pool.query('DELETE FROM quizzes WHERE id = $1', [id]).catch(() => {});
|
||||
if (e && e.status) throw httpError(502, 'Модель вернула вопросы, которые не прошли проверку: ' + e.message);
|
||||
throw e;
|
||||
}
|
||||
return {
|
||||
quiz: { id, title: saved.quiz.title, kind: saved.quiz.kind },
|
||||
questions: draft.questions.length,
|
||||
model: profile ? profile.model : 'native',
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
QUIZ_AI_PROMPT_MAX,
|
||||
QUIZ_AI_QUESTIONS_DEFAULT,
|
||||
QUIZ_AI_QUESTIONS_MAX,
|
||||
QUIZ_AI_TIMEOUT_MS,
|
||||
QUIZ_AI_SYSTEM_PROMPT,
|
||||
quizAiMaxTokens,
|
||||
quizAiUserPrompt,
|
||||
extractJson,
|
||||
normalizeDraft,
|
||||
normalizeQuizAiRequest,
|
||||
generateQuizDraft,
|
||||
};
|
||||
@@ -0,0 +1,294 @@
|
||||
const GRADE_NAME_MAX = 200;
|
||||
const GRADE_DESC_MAX = 2000;
|
||||
const GRADE_LABEL_MAX = 200;
|
||||
const GRADE_RANGES_MAX = 30;
|
||||
const GRADE_SCORE_MAX = 100000;
|
||||
const GRADE_IMAGES_LIMIT = 300;
|
||||
|
||||
function gradeError(status, message) {
|
||||
const e = new Error(message);
|
||||
e.status = status;
|
||||
return e;
|
||||
}
|
||||
|
||||
function gradeText(v, max, label, required) {
|
||||
if (v === undefined || v === null) {
|
||||
if (required) throw gradeError(400, `${label}: обязательное поле`);
|
||||
return '';
|
||||
}
|
||||
if (typeof v !== 'string') throw gradeError(400, `${label}: неверный текст`);
|
||||
const s = v.trim();
|
||||
if (required && !s) throw gradeError(400, `${label}: обязательное поле`);
|
||||
if (s.length > max) throw gradeError(400, `${label}: максимум ${max} символов`);
|
||||
return s;
|
||||
}
|
||||
|
||||
function gradeScore(v, label) {
|
||||
if (v === undefined || v === null || v === '') throw gradeError(400, `${label}: обязательное поле`);
|
||||
const n = Number(v);
|
||||
if (!Number.isFinite(n) || n < 0 || n > GRADE_SCORE_MAX) throw gradeError(400, `Неверное значение: ${label}`);
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
function gradeImagePath(v, label) {
|
||||
if (v === undefined || v === null || v === '') return null;
|
||||
if (typeof v !== 'string' || !/^\/uploads\/[\w,.()-]+$/.test(v)) throw gradeError(400, `${label}: неверный путь к картинке`);
|
||||
return v;
|
||||
}
|
||||
|
||||
function normalizeRanges(list) {
|
||||
if (!Array.isArray(list)) return [];
|
||||
if (list.length > GRADE_RANGES_MAX) throw gradeError(400, `Диапазонов не больше ${GRADE_RANGES_MAX}`);
|
||||
return list.map((raw, i) => {
|
||||
const label = `Диапазон ${i + 1}`;
|
||||
if (!raw || typeof raw !== 'object') throw gradeError(400, `${label}: неверные данные`);
|
||||
const min = gradeScore(raw.min_score, `${label}: мин. балл`);
|
||||
const max = gradeScore(raw.max_score, `${label}: макс. балл`);
|
||||
if (max < min) throw gradeError(400, `${label}: макс. балл меньше минимального`);
|
||||
return {
|
||||
min_score: min,
|
||||
max_score: max,
|
||||
label: gradeText(raw.label, GRADE_LABEL_MAX, `${label}: результат`, true),
|
||||
image_path: gradeImagePath(raw.image_path, label),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeScale(body) {
|
||||
const name = gradeText(body.name, GRADE_NAME_MAX, 'Название', true);
|
||||
const description = gradeText(body.description, GRADE_DESC_MAX, 'Описание', false) || null;
|
||||
const rawSort = body.sort_order;
|
||||
const sortOrder = rawSort === undefined || rawSort === null || rawSort === '' ? 0 : Number(rawSort);
|
||||
if (!Number.isFinite(sortOrder) || sortOrder < -100000 || sortOrder > 100000) {
|
||||
throw gradeError(400, 'Неверное значение: порядок сортировки');
|
||||
}
|
||||
const ranges = normalizeRanges(body.ranges);
|
||||
if (!ranges.length) throw gradeError(400, 'Добавьте хотя бы один диапазон баллов');
|
||||
return { name, description, sort_order: Math.trunc(sortOrder), ranges };
|
||||
}
|
||||
|
||||
function rangeToJson(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
min_score: Number(row.min_score),
|
||||
max_score: Number(row.max_score),
|
||||
label: row.label,
|
||||
image_path: row.image_path || null,
|
||||
};
|
||||
}
|
||||
|
||||
function scaleToJson(row, ranges) {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
description: row.description || null,
|
||||
sort_order: row.sort_order,
|
||||
created_by: row.created_by,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
ranges: ranges || [],
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureQuizGradeTables(pool) {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_grade_scales (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
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(`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,
|
||||
min_score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
max_score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
label VARCHAR(200) NOT NULL DEFAULT '',
|
||||
image_path TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`);
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_grade_ranges_scale ON quiz_grade_ranges(scale_id)');
|
||||
}
|
||||
|
||||
async function listGradeScales(pool) {
|
||||
const { rows: scales } = await pool.query(
|
||||
'SELECT * FROM quiz_grade_scales ORDER BY sort_order ASC, id ASC'
|
||||
);
|
||||
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'
|
||||
);
|
||||
const map = new Map();
|
||||
for (const r of ranges) {
|
||||
if (!map.has(r.scale_id)) map.set(r.scale_id, []);
|
||||
map.get(r.scale_id).push(rangeToJson(r));
|
||||
}
|
||||
return scales.map(s => scaleToJson(s, map.get(s.id) || []));
|
||||
}
|
||||
|
||||
async function getGradeScale(pool, id) {
|
||||
const { rows } = await pool.query('SELECT * FROM quiz_grade_scales WHERE id = $1', [id]);
|
||||
if (!rows.length) throw gradeError(404, 'Критерий оценки не найден');
|
||||
const { rows: ranges } = await pool.query(
|
||||
'SELECT * FROM quiz_grade_ranges WHERE scale_id = $1 ORDER BY min_score ASC, id ASC',
|
||||
[id]
|
||||
);
|
||||
return scaleToJson(rows[0], ranges.map(rangeToJson));
|
||||
}
|
||||
|
||||
async function assertUniqueName(client, name, excludeId) {
|
||||
const { rows } = await client.query(
|
||||
'SELECT id FROM quiz_grade_scales WHERE lower(name) = lower($1) AND id <> $2 LIMIT 1',
|
||||
[name, excludeId || 0]
|
||||
);
|
||||
if (rows.length) throw gradeError(400, 'Критерий с таким названием уже есть');
|
||||
}
|
||||
|
||||
async function insertRanges(client, scaleId, ranges) {
|
||||
for (const r of ranges) {
|
||||
await client.query(
|
||||
`INSERT INTO quiz_grade_ranges (scale_id, min_score, max_score, label, image_path)
|
||||
VALUES ($1,$2,$3,$4,$5)`,
|
||||
[scaleId, r.min_score, r.max_score, r.label, r.image_path]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function unusedImages(client, candidates) {
|
||||
const list = [...new Set((candidates || []).filter(Boolean))];
|
||||
if (!list.length) return [];
|
||||
const { rows } = await client.query(
|
||||
'SELECT DISTINCT image_path FROM quiz_grade_ranges WHERE image_path = ANY($1::text[])',
|
||||
[list]
|
||||
);
|
||||
const used = new Set(rows.map(r => r.image_path));
|
||||
return list.filter(p => !used.has(p));
|
||||
}
|
||||
|
||||
async function createGradeScale(pool, user, body = {}) {
|
||||
const data = normalizeScale(body);
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await assertUniqueName(client, data.name, 0);
|
||||
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]
|
||||
);
|
||||
await insertRanges(client, rows[0].id, data.ranges);
|
||||
await client.query('COMMIT');
|
||||
return { item: await getGradeScale(pool, rows[0].id) };
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function updateGradeScale(pool, id, 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 { 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]
|
||||
);
|
||||
await client.query('DELETE FROM quiz_grade_ranges WHERE scale_id = $1', [id]);
|
||||
await insertRanges(client, id, data.ranges);
|
||||
removed = await unusedImages(client, oldRanges.map(r => r.image_path));
|
||||
await client.query('COMMIT');
|
||||
return { item: await getGradeScale(pool, id), removed };
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteGradeScale(pool, id) {
|
||||
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, 'Критерий оценки не найден');
|
||||
const { rows: oldRanges } = await client.query(
|
||||
'SELECT image_path FROM quiz_grade_ranges WHERE scale_id = $1',
|
||||
[id]
|
||||
);
|
||||
await client.query('DELETE FROM quiz_grade_scales WHERE id = $1', [id]);
|
||||
const removed = await unusedImages(client, oldRanges.map(r => r.image_path));
|
||||
await client.query('COMMIT');
|
||||
return { removed };
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
function gradeForScore(ranges, score) {
|
||||
const value = Number(score);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
for (const r of ranges || []) {
|
||||
const min = Number(r.min_score);
|
||||
const max = Number(r.max_score);
|
||||
if (value >= min && value <= max) {
|
||||
return {
|
||||
label: r.label,
|
||||
image_path: r.image_path || null,
|
||||
min_score: min,
|
||||
max_score: max,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function listGradeImages(pool, limit) {
|
||||
const max = Math.min(Math.max(Number(limit) || GRADE_IMAGES_LIMIT, 1), GRADE_IMAGES_LIMIT);
|
||||
const { rows } = await pool.query(
|
||||
`SELECT path FROM (
|
||||
SELECT path FROM doc_images
|
||||
UNION SELECT photo_path AS path FROM bookmarks WHERE photo_path IS NOT NULL
|
||||
UNION SELECT photo_path AS path FROM student_photos
|
||||
UNION SELECT photo_path AS path FROM group_photos
|
||||
UNION SELECT photo_path AS path FROM entry_photos
|
||||
UNION SELECT path FROM quiz_assets WHERE path ~* '\\.(jpe?g|png|gif|webp|bmp|avif|heic|heif|jfif|ico)$'
|
||||
UNION SELECT image_path AS path FROM quiz_grade_ranges WHERE image_path IS NOT NULL
|
||||
) t
|
||||
WHERE path LIKE '/uploads/%'
|
||||
ORDER BY path DESC
|
||||
LIMIT $1`,
|
||||
[max]
|
||||
);
|
||||
return rows.map(r => r.path);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
GRADE_NAME_MAX,
|
||||
GRADE_LABEL_MAX,
|
||||
GRADE_RANGES_MAX,
|
||||
ensureQuizGradeTables,
|
||||
listGradeScales,
|
||||
getGradeScale,
|
||||
createGradeScale,
|
||||
updateGradeScale,
|
||||
deleteGradeScale,
|
||||
gradeForScore,
|
||||
listGradeImages,
|
||||
};
|
||||
+84
-26
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const { ensureQuizGradeTables, gradeForScore } = require('./quiz-grades');
|
||||
|
||||
const QUIZ_KINDS = new Set(['test', 'survey']);
|
||||
const QUESTION_KINDS = new Set(['single', 'multiple', 'select', 'line', 'text', 'number', 'date']);
|
||||
@@ -145,6 +146,7 @@ function normalizeIdList(list, max) {
|
||||
}
|
||||
|
||||
async function ensureQuizTables(pool) {
|
||||
await ensureQuizGradeTables(pool);
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quizzes (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title VARCHAR(200) NOT NULL DEFAULT '',
|
||||
@@ -154,11 +156,13 @@ async function ensureQuizTables(pool) {
|
||||
shuffle_questions BOOLEAN NOT NULL DEFAULT false,
|
||||
shuffle_options BOOLEAN NOT NULL DEFAULT false,
|
||||
show_results BOOLEAN NOT NULL DEFAULT true,
|
||||
show_answers BOOLEAN NOT NULL DEFAULT true,
|
||||
max_attempts INT,
|
||||
time_limit_min INT NOT NULL DEFAULT 0,
|
||||
pass_percent INT NOT NULL DEFAULT 60,
|
||||
cover_path TEXT,
|
||||
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
|
||||
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(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -169,11 +173,13 @@ async function ensureQuizTables(pool) {
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS shuffle_questions BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS shuffle_options BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS show_results BOOLEAN NOT NULL DEFAULT true');
|
||||
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 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 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');
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_questions (
|
||||
@@ -250,10 +256,12 @@ async function ensureQuizTables(pool) {
|
||||
percent NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
passed BOOLEAN,
|
||||
anon_token TEXT,
|
||||
guest_name TEXT,
|
||||
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
finished_at TIMESTAMPTZ
|
||||
)`);
|
||||
await pool.query('ALTER TABLE quiz_attempts ADD COLUMN IF NOT EXISTS anon_token TEXT');
|
||||
await pool.query('ALTER TABLE quiz_attempts ADD COLUMN IF NOT EXISTS guest_name TEXT');
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_attempt_answers (
|
||||
id SERIAL PRIMARY KEY,
|
||||
attempt_id INT NOT NULL REFERENCES quiz_attempts(id) ON DELETE CASCADE,
|
||||
@@ -404,11 +412,13 @@ function quizMeta(row) {
|
||||
shuffle_questions: row.shuffle_questions === true,
|
||||
shuffle_options: row.shuffle_options === true,
|
||||
show_results: row.show_results !== false,
|
||||
show_answers: row.show_answers !== false,
|
||||
max_attempts: row.max_attempts,
|
||||
time_limit_min: row.time_limit_min,
|
||||
pass_percent: row.pass_percent,
|
||||
cover_path: row.cover_path,
|
||||
allow_anonymous: row.allow_anonymous === true,
|
||||
grade_scale_id: row.grade_scale_id == null ? null : Number(row.grade_scale_id),
|
||||
author_id: row.author_id,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
@@ -535,6 +545,7 @@ function normalizeMeta(body, current) {
|
||||
const passPercent = intValue(body.pass_percent, 0, 100, 'порог сдачи');
|
||||
const timeLimit = intValue(body.time_limit_min, 0, QUIZ_TIME_LIMIT_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;
|
||||
if (body.cover_path !== undefined) {
|
||||
const raw = body.cover_path;
|
||||
@@ -550,7 +561,11 @@ function normalizeMeta(body, current) {
|
||||
shuffle_questions: asBool(body.shuffle_questions, current.shuffle_questions === true),
|
||||
shuffle_options: asBool(body.shuffle_options, current.shuffle_options === true),
|
||||
show_results: asBool(body.show_results, current.show_results !== false),
|
||||
allow_anonymous: kind === 'survey' && asBool(body.allow_anonymous, current.allow_anonymous === true),
|
||||
show_answers: asBool(body.show_answers, current.show_answers !== false),
|
||||
allow_anonymous: asBool(body.allow_anonymous, current.allow_anonymous === true),
|
||||
grade_scale_id: kind === 'survey'
|
||||
? null
|
||||
: (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,
|
||||
pass_percent: passPercent == null ? current.pass_percent : passPercent,
|
||||
@@ -708,6 +723,10 @@ 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, 'Критерий оценки не найден');
|
||||
}
|
||||
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 quizAssetIds = normalizeIdList(body.asset_ids, QUIZ_ASSETS_MAX);
|
||||
@@ -718,11 +737,12 @@ async function saveQuiz(pool, id, user, body = {}) {
|
||||
await client.query(
|
||||
`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, updated_at = now()
|
||||
pass_percent = $11, cover_path = $12, allow_anonymous = $13, show_answers = $14,
|
||||
grade_scale_id = $15, 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.pass_percent, meta.cover_path, meta.allow_anonymous, meta.show_answers, meta.grade_scale_id]
|
||||
);
|
||||
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));
|
||||
@@ -1061,16 +1081,34 @@ async function performSubmit(pool, row, attempt, body = {}) {
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
const show = row.show_results !== false;
|
||||
const showAnswers = show && row.show_answers !== false;
|
||||
let grade = null;
|
||||
if (row.kind === 'test' && row.grade_scale_id != null) {
|
||||
const { rows: ranges } = await pool.query(
|
||||
'SELECT min_score, max_score, label, image_path FROM quiz_grade_ranges WHERE scale_id = $1 ORDER BY min_score ASC, id ASC',
|
||||
[row.grade_scale_id]
|
||||
);
|
||||
grade = gradeForScore(ranges, totalScore);
|
||||
}
|
||||
const saved = upd.rows[0];
|
||||
return {
|
||||
attempt: {
|
||||
...saved,
|
||||
guest_name: attempt.guest_name || null,
|
||||
score: Number(saved.score),
|
||||
max_score: Number(saved.max_score),
|
||||
percent: Number(saved.percent),
|
||||
},
|
||||
result: show ? { score: totalScore, max_score: totalMax, percent, passed, questions: results } : null,
|
||||
revealed: show,
|
||||
result: show ? {
|
||||
score: totalScore,
|
||||
max_score: totalMax,
|
||||
percent,
|
||||
passed,
|
||||
grade,
|
||||
answers_hidden: !showAnswers,
|
||||
questions: showAnswers ? results : [],
|
||||
} : null,
|
||||
revealed: showAnswers,
|
||||
};
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
@@ -1091,17 +1129,23 @@ async function submitAttempt(pool, quizId, attemptId, user, body = {}) {
|
||||
return performSubmit(pool, row, attempt, body);
|
||||
}
|
||||
|
||||
async function findAnonymousSurvey(pool, quizId) {
|
||||
function guestNameValue(raw) {
|
||||
if (typeof raw !== 'string') return null;
|
||||
const value = raw.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 120);
|
||||
return value || null;
|
||||
}
|
||||
|
||||
async function findPublicQuiz(pool, quizId) {
|
||||
const row = await findQuizRow(pool, quizId);
|
||||
if (!row) throw httpError(404, 'Опрос не найден');
|
||||
if (row.kind !== 'survey' || row.allow_anonymous !== true || row.is_published !== true) {
|
||||
throw httpError(404, 'Опрос не найден');
|
||||
if (!row) throw httpError(404, 'Тест не найден');
|
||||
if (row.allow_anonymous !== true || row.is_published !== true) {
|
||||
throw httpError(404, 'Тест не найден');
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
async function getPublicSurvey(pool, quizId) {
|
||||
const row = await findAnonymousSurvey(pool, quizId);
|
||||
async function getPublicQuiz(pool, quizId) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
const structure = stripAnswers(await loadQuizStructure(pool, quizId));
|
||||
const meta = quizMeta(row);
|
||||
delete meta.author_id;
|
||||
@@ -1114,16 +1158,17 @@ async function getPublicSurvey(pool, quizId) {
|
||||
};
|
||||
}
|
||||
|
||||
async function startAnonymousAttempt(pool, quizId) {
|
||||
await findAnonymousSurvey(pool, quizId);
|
||||
async function startPublicAttempt(pool, quizId, opts = {}) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
const guestName = row.kind === 'test' ? guestNameValue(opts.name) : null;
|
||||
const token = crypto.randomBytes(QUIZ_ANON_TOKEN_BYTES).toString('hex');
|
||||
const { rows } = await pool.query(
|
||||
'INSERT INTO quiz_attempts (quiz_id, user_id, anon_token) VALUES ($1, NULL, $2) RETURNING id, started_at',
|
||||
[quizId, token]
|
||||
'INSERT INTO quiz_attempts (quiz_id, user_id, anon_token, guest_name) VALUES ($1, NULL, $2, $3) RETURNING id, started_at',
|
||||
[quizId, token, guestName]
|
||||
);
|
||||
return {
|
||||
attempt: { id: rows[0].id, started_at: rows[0].started_at, anon_token: token },
|
||||
quiz: await getPublicSurvey(pool, quizId),
|
||||
attempt: { id: rows[0].id, started_at: rows[0].started_at, anon_token: token, guest_name: guestName },
|
||||
quiz: await getPublicQuiz(pool, quizId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1134,8 +1179,8 @@ function anonTokenMatches(expected, given) {
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
async function submitAnonymousAttempt(pool, quizId, attemptId, token, body = {}) {
|
||||
const row = await findAnonymousSurvey(pool, quizId);
|
||||
async function submitPublicAttempt(pool, quizId, attemptId, token, body = {}) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
const { rows } = await pool.query('SELECT * FROM quiz_attempts WHERE id = $1 AND quiz_id = $2', [attemptId, quizId]);
|
||||
if (!rows.length) throw httpError(404, 'Попытка не найдена');
|
||||
const attempt = rows[0];
|
||||
@@ -1159,8 +1204,9 @@ async function listAttempts(pool, quizId, user, params = {}) {
|
||||
where += ` AND a.user_id = $${args.length}`;
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`SELECT a.id, a.user_id, a.status, a.score, a.max_score, a.percent, a.passed, a.started_at, a.finished_at,
|
||||
CASE WHEN a.user_id IS NULL THEN 'Аноним' ELSE u.name END AS user_name, a.anon_token IS NOT NULL AS anonymous
|
||||
`SELECT a.id, a.user_id, a.guest_name, a.status, a.score, a.max_score, a.percent, a.passed, a.started_at, a.finished_at,
|
||||
CASE WHEN a.user_id IS NULL THEN COALESCE(NULLIF(a.guest_name, ''), 'Аноним') ELSE u.name END AS user_name,
|
||||
(a.user_id IS NULL AND COALESCE(a.guest_name, '') = '') AS anonymous
|
||||
FROM quiz_attempts a LEFT JOIN users u ON u.id = a.user_id
|
||||
WHERE ${where}
|
||||
ORDER BY a.finished_at DESC NULLS LAST, a.id DESC
|
||||
@@ -1184,7 +1230,7 @@ async function getAttempt(pool, quizId, attemptId, user) {
|
||||
if (!row) throw httpError(404, 'Тест не найден');
|
||||
const editable = canEditQuiz(row, user);
|
||||
const { rows } = await pool.query(
|
||||
`SELECT a.*, CASE WHEN a.user_id IS NULL THEN 'Аноним' ELSE u.name END AS user_name
|
||||
`SELECT a.*, CASE WHEN a.user_id IS NULL THEN COALESCE(NULLIF(a.guest_name, ''), 'Аноним') ELSE u.name END AS user_name
|
||||
FROM quiz_attempts a LEFT JOIN users u ON u.id = a.user_id
|
||||
WHERE a.id = $1 AND a.quiz_id = $2`,
|
||||
[attemptId, quizId]
|
||||
@@ -1198,7 +1244,15 @@ async function getAttempt(pool, quizId, attemptId, user) {
|
||||
[attemptId]
|
||||
);
|
||||
const structure = await loadQuizStructure(pool, quizId);
|
||||
const revealed = editable || row.show_results !== false;
|
||||
const revealed = editable || (row.show_results !== false && row.show_answers !== false);
|
||||
let grade = null;
|
||||
if (row.kind === 'test' && row.grade_scale_id != null) {
|
||||
const { rows: ranges } = await pool.query(
|
||||
'SELECT min_score, max_score, label, image_path FROM quiz_grade_ranges WHERE scale_id = $1 ORDER BY min_score ASC, id ASC',
|
||||
[row.grade_scale_id]
|
||||
);
|
||||
grade = gradeForScore(ranges, attempt.score);
|
||||
}
|
||||
const qmap = new Map(structure.questions.map(q => [q.id, q]));
|
||||
return {
|
||||
attempt: {
|
||||
@@ -1224,6 +1278,7 @@ async function getAttempt(pool, quizId, attemptId, user) {
|
||||
};
|
||||
}),
|
||||
revealed,
|
||||
grade,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1321,8 +1376,11 @@ module.exports = {
|
||||
QUIZ_TITLE_MAX,
|
||||
QUIZ_DESCRIPTION_MAX,
|
||||
QUIZ_TEXT_MAX,
|
||||
QUIZ_DESC_MAX,
|
||||
QUIZ_ANSWER_MAX,
|
||||
QUIZ_CAPTION_MAX,
|
||||
QUIZ_ACCEPTED_MAX,
|
||||
QUIZ_ACCEPTED_LEN,
|
||||
QUIZ_QUESTIONS_MAX,
|
||||
QUIZ_OPTIONS_MAX,
|
||||
QUIZ_ASSETS_MAX,
|
||||
@@ -1348,9 +1406,9 @@ module.exports = {
|
||||
startAttempt,
|
||||
restartAttempt,
|
||||
submitAttempt,
|
||||
getPublicSurvey,
|
||||
startAnonymousAttempt,
|
||||
submitAnonymousAttempt,
|
||||
getPublicQuiz,
|
||||
startPublicAttempt,
|
||||
submitPublicAttempt,
|
||||
normalizeAnswerText,
|
||||
normalizeNumberValue,
|
||||
normalizeDateValue,
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
(function () {
|
||||
const state = { items: [], draft: null, imageTarget: -1 };
|
||||
|
||||
function el(id) {
|
||||
return document.getElementById(id);
|
||||
}
|
||||
|
||||
function a(s) {
|
||||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function openModal(id) {
|
||||
const node = el(id);
|
||||
if (node) node.classList.add('open');
|
||||
}
|
||||
|
||||
function closeModal(id) {
|
||||
const node = el(id);
|
||||
if (node) node.classList.remove('open');
|
||||
}
|
||||
|
||||
function showList() {
|
||||
el('qsEditorView').hidden = true;
|
||||
el('qsListView').hidden = false;
|
||||
}
|
||||
|
||||
function showEditor() {
|
||||
el('qsListView').hidden = true;
|
||||
el('qsEditorView').hidden = false;
|
||||
}
|
||||
|
||||
async function fetchScales() {
|
||||
const res = await fetch(API + '/api/grade-scales', { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить критерии');
|
||||
state.items = Array.isArray(data.items) ? data.items : [];
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
const list = el('qsList');
|
||||
if (!state.items.length) {
|
||||
list.innerHTML = '<div class="qs-empty">Критериев пока нет. Создайте первый — например «Шкала на 15 баллов».</div>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = state.items.map(s => {
|
||||
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('');
|
||||
return `<div class="qs-item">
|
||||
<div class="qs-item-head">
|
||||
<div class="qs-item-main">
|
||||
<div class="qs-item-name">${esc(s.name || '')}</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>
|
||||
</div>
|
||||
<div class="qs-item-ranges">${ranges || '<span class="qs-range-chip">нет диапазонов</span>'}</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function blankDraft() {
|
||||
return {
|
||||
id: null,
|
||||
name: '',
|
||||
description: '',
|
||||
sort_order: 0,
|
||||
ranges: [{ min_score: 0, max_score: '', label: '', image_path: null }],
|
||||
};
|
||||
}
|
||||
|
||||
function renderRanges() {
|
||||
const d = state.draft;
|
||||
el('qsRanges').innerHTML = d.ranges.map((r, i) => `<div class="qs-range" data-ri="${i}">
|
||||
<input type="number" min="0" step="0.01" class="settings-input qs-min" data-field="min_score" value="${a(r.min_score)}" placeholder="Мин. балл">
|
||||
<input type="number" min="0" step="0.01" class="settings-input qs-max" data-field="max_score" value="${a(r.max_score)}" placeholder="Макс. балл">
|
||||
<input class="settings-input qs-label" data-field="label" maxlength="200" value="${a(r.label)}" placeholder="Результат, напр. Отлично">
|
||||
<div class="qs-range-img">
|
||||
${r.image_path ? `<img src="${a(thumbSrc(r.image_path))}" alt="">` : '<span class="qs-noimg">нет</span>'}
|
||||
<button type="button" class="btn-link" data-qs-img="${i}">${r.image_path ? 'Заменить' : 'Картинка'}</button>
|
||||
${r.image_path ? `<button type="button" class="btn-link danger" data-qs-imgdel="${i}">Убрать</button>` : ''}
|
||||
</div>
|
||||
<button type="button" class="btn-link danger" data-qs-rmrange="${i}" title="Удалить диапазон">✕</button>
|
||||
</div>`).join('');
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
function renderEditor() {
|
||||
const d = state.draft;
|
||||
el('qsName').value = d.name;
|
||||
el('qsDesc').value = d.description;
|
||||
el('qsSort').value = d.sort_order;
|
||||
el('qsEditorTitle').textContent = d.id ? 'Изменить критерий' : 'Новый критерий оценки';
|
||||
renderRanges();
|
||||
}
|
||||
|
||||
function startCreate() {
|
||||
state.draft = blankDraft();
|
||||
renderEditor();
|
||||
showEditor();
|
||||
}
|
||||
|
||||
function startEdit(id) {
|
||||
const s = state.items.find(x => Number(x.id) === Number(id));
|
||||
if (!s) return;
|
||||
state.draft = {
|
||||
id: s.id,
|
||||
name: s.name || '',
|
||||
description: s.description || '',
|
||||
sort_order: Number(s.sort_order) || 0,
|
||||
ranges: (s.ranges || []).map(r => ({
|
||||
min_score: Number(r.min_score),
|
||||
max_score: Number(r.max_score),
|
||||
label: r.label || '',
|
||||
image_path: r.image_path || null,
|
||||
})),
|
||||
};
|
||||
if (!state.draft.ranges.length) state.draft.ranges.push({ min_score: 0, max_score: '', label: '', image_path: null });
|
||||
renderEditor();
|
||||
showEditor();
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const d = state.draft;
|
||||
if (!d) return;
|
||||
const name = el('qsName').value.trim();
|
||||
if (!name) return showToast('Укажите название критерия', true);
|
||||
if (!d.ranges.length) return showToast('Добавьте хотя бы один диапазон', true);
|
||||
const ranges = [];
|
||||
for (const r of d.ranges) {
|
||||
const min = Number(r.min_score);
|
||||
const max = Number(r.max_score);
|
||||
const label = String(r.label || '').trim();
|
||||
if (!label) return showToast('У каждого диапазона должен быть результат', true);
|
||||
if (r.max_score === '' || !Number.isFinite(min) || !Number.isFinite(max)) return showToast('Укажите минимальный и максимальный балл', true);
|
||||
if (max < min) return showToast('Максимальный балл меньше минимального', true);
|
||||
ranges.push({ min_score: min, max_score: max, label, image_path: r.image_path || null });
|
||||
}
|
||||
const payload = {
|
||||
name,
|
||||
description: el('qsDesc').value.trim(),
|
||||
sort_order: Number(el('qsSort').value) || 0,
|
||||
ranges,
|
||||
};
|
||||
const btn = el('qsSaveBtn');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await fetch(API + '/api/grade-scales' + (d.id ? '/' + d.id : ''), {
|
||||
method: d.id ? 'PUT' : 'POST',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось сохранить критерий');
|
||||
await fetchScales();
|
||||
renderList();
|
||||
showList();
|
||||
showToast('Критерий сохранён');
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(id) {
|
||||
const item = state.items.find(x => Number(x.id) === Number(id));
|
||||
if (!item) return;
|
||||
if (!confirm(`Удалить критерий «${item.name}»? Тесты, где он выбран, останутся без градации.`)) return;
|
||||
try {
|
||||
const res = await fetch(API + '/api/grade-scales/' + id, { method: 'DELETE', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось удалить критерий');
|
||||
await fetchScales();
|
||||
renderList();
|
||||
showToast('Критерий удалён');
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function openImagePicker(index) {
|
||||
state.imageTarget = Number(index);
|
||||
openModal('qsImageModal');
|
||||
el('qsImgGrid').innerHTML = '<div class="qs-empty">Загрузка…</div>';
|
||||
try {
|
||||
const res = await fetch(API + '/api/grade-scales/images', { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить картинки');
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
el('qsImgGrid').innerHTML = items.length
|
||||
? items.map(p => `<button type="button" class="qs-img-cell" data-qs-pickimg="${a(p)}"><img src="${a(thumbSrc(p))}" alt=""></button>`).join('')
|
||||
: '<div class="qs-empty">Картинок пока нет — загрузите первую.</div>';
|
||||
} catch (e) {
|
||||
el('qsImgGrid').innerHTML = `<div class="qs-empty">${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadScales() {
|
||||
el('qsList').innerHTML = '<div class="qs-empty">Загрузка…</div>';
|
||||
try {
|
||||
await fetchScales();
|
||||
renderList();
|
||||
} catch (e) {
|
||||
el('qsList').innerHTML = `<div class="qs-empty">${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function bind() {
|
||||
const btn = el('quizScalesBtn');
|
||||
if (!btn) return;
|
||||
btn.addEventListener('click', () => {
|
||||
showList();
|
||||
openModal('quizScalesModal');
|
||||
loadScales();
|
||||
});
|
||||
el('qsCloseBtn').addEventListener('click', () => closeModal('quizScalesModal'));
|
||||
el('qsNewBtn').addEventListener('click', startCreate);
|
||||
el('qsCancelBtn').addEventListener('click', showList);
|
||||
el('qsSaveBtn').addEventListener('click', save);
|
||||
el('qsAddRange').addEventListener('click', () => {
|
||||
state.draft.ranges.push({ min_score: 0, max_score: '', label: '', image_path: null });
|
||||
renderRanges();
|
||||
});
|
||||
el('qsList').addEventListener('click', e => {
|
||||
const edit = e.target.closest('[data-qs-edit]');
|
||||
if (edit) { startEdit(edit.dataset.qsEdit); return; }
|
||||
const del = e.target.closest('[data-qs-del]');
|
||||
if (del) { remove(del.dataset.qsDel); return; }
|
||||
});
|
||||
el('qsRanges').addEventListener('input', e => {
|
||||
const input = e.target.closest('[data-field]');
|
||||
if (!input) return;
|
||||
const row = input.closest('[data-ri]');
|
||||
if (!row) return;
|
||||
const i = Number(row.dataset.ri);
|
||||
if (!state.draft || !state.draft.ranges[i]) return;
|
||||
state.draft.ranges[i][input.dataset.field] = input.value;
|
||||
});
|
||||
el('qsRanges').addEventListener('click', e => {
|
||||
const img = e.target.closest('[data-qs-img]');
|
||||
if (img) { openImagePicker(img.dataset.qsImg); return; }
|
||||
const delImg = e.target.closest('[data-qs-imgdel]');
|
||||
if (delImg) {
|
||||
state.draft.ranges[Number(delImg.dataset.qsImgdel)].image_path = null;
|
||||
renderRanges();
|
||||
return;
|
||||
}
|
||||
const rm = e.target.closest('[data-qs-rmrange]');
|
||||
if (rm) {
|
||||
state.draft.ranges.splice(Number(rm.dataset.qsRmrange), 1);
|
||||
renderRanges();
|
||||
}
|
||||
});
|
||||
el('qsImgGrid').addEventListener('click', e => {
|
||||
const cell = e.target.closest('[data-qs-pickimg]');
|
||||
if (!cell) return;
|
||||
const target = state.draft && state.draft.ranges[state.imageTarget];
|
||||
if (target) target.image_path = cell.dataset.qsPickimg;
|
||||
closeModal('qsImageModal');
|
||||
renderRanges();
|
||||
});
|
||||
el('qsImgCancel').addEventListener('click', () => closeModal('qsImageModal'));
|
||||
el('qsImgFile').addEventListener('change', async e => {
|
||||
const file = e.target.files && e.target.files[0];
|
||||
e.target.value = '';
|
||||
if (!file) return;
|
||||
const fd = new FormData();
|
||||
fd.append('photo', file);
|
||||
try {
|
||||
const res = await fetch(API + '/api/grade-scales/upload', { method: 'POST', headers: hdr(), body: fd });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить картинку');
|
||||
const target = state.draft && state.draft.ranges[state.imageTarget];
|
||||
if (target) target.image_path = data.path;
|
||||
closeModal('qsImageModal');
|
||||
renderRanges();
|
||||
} catch (err) {
|
||||
showToast(err.message, true);
|
||||
}
|
||||
});
|
||||
el('quizScalesModal').addEventListener('click', e => {
|
||||
if (e.target.id === 'quizScalesModal') closeModal('quizScalesModal');
|
||||
});
|
||||
el('qsImageModal').addEventListener('click', e => {
|
||||
if (e.target.id === 'qsImageModal') closeModal('qsImageModal');
|
||||
});
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key !== 'Escape') return;
|
||||
if (el('qsImageModal').classList.contains('open')) {
|
||||
closeModal('qsImageModal');
|
||||
return;
|
||||
}
|
||||
if (el('quizScalesModal').classList.contains('open')) closeModal('quizScalesModal');
|
||||
});
|
||||
}
|
||||
|
||||
bind();
|
||||
})();
|
||||
+61
-9
@@ -1,6 +1,6 @@
|
||||
(function () {
|
||||
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
|
||||
const state = { quiz: null, assets: [], questions: [] };
|
||||
const state = { quiz: null, assets: [], questions: [], gradeScales: [] };
|
||||
let dirty = false;
|
||||
let saving = false;
|
||||
let dragState = null;
|
||||
@@ -68,6 +68,8 @@
|
||||
shuffle_questions: quiz.shuffle_questions === true,
|
||||
shuffle_options: quiz.shuffle_options === true,
|
||||
show_results: quiz.show_results !== false,
|
||||
show_answers: quiz.show_answers !== false,
|
||||
grade_scale_id: quiz.grade_scale_id == null ? '' : quiz.grade_scale_id,
|
||||
allow_anonymous: quiz.allow_anonymous === true,
|
||||
max_attempts: quiz.max_attempts == null ? '' : quiz.max_attempts,
|
||||
time_limit_min: quiz.time_limit_min || 0,
|
||||
@@ -109,6 +111,8 @@
|
||||
shuffle_questions: q.shuffle_questions,
|
||||
shuffle_options: q.shuffle_options,
|
||||
show_results: q.show_results,
|
||||
show_answers: q.show_answers,
|
||||
grade_scale_id: q.grade_scale_id === '' ? null : q.grade_scale_id,
|
||||
allow_anonymous: q.allow_anonymous,
|
||||
max_attempts: q.max_attempts === '' ? null : q.max_attempts,
|
||||
time_limit_min: q.time_limit_min === '' ? 0 : q.time_limit_min,
|
||||
@@ -301,18 +305,23 @@
|
||||
function renderAnon() {
|
||||
const wrap = document.getElementById('qeAnonWrap');
|
||||
if (!wrap) return;
|
||||
const isSurvey = state.quiz.kind === 'survey';
|
||||
wrap.hidden = !isSurvey;
|
||||
if (!isSurvey) return;
|
||||
wrap.hidden = false;
|
||||
const isTest = state.quiz.kind === 'test';
|
||||
document.getElementById('qeAnonymous').checked = state.quiz.allow_anonymous;
|
||||
const link = document.getElementById('qeAnonLink');
|
||||
const hint = document.getElementById('qeAnonPublishHint');
|
||||
const desc = document.getElementById('qeAnonDesc');
|
||||
if (desc) {
|
||||
desc.textContent = isTest
|
||||
? 'По ссылке можно пройти тест без входа в систему. Перед началом ученик может указать имя; если оставить пустым, результат будет анонимным.'
|
||||
: 'По ссылке можно пройти опрос без входа в систему. Ответы сохраняются без имени.';
|
||||
}
|
||||
const ready = state.quiz.allow_anonymous && state.quiz.is_published;
|
||||
const visible = ready && !dirty;
|
||||
link.hidden = !visible;
|
||||
let text = '';
|
||||
if (state.quiz.allow_anonymous && !state.quiz.is_published) text = 'Опубликуйте опрос, чтобы ссылка заработала.';
|
||||
else if (ready && dirty) text = 'Сохраните опрос, чтобы ссылка заработала.';
|
||||
if (state.quiz.allow_anonymous && !state.quiz.is_published) text = 'Опубликуйте, чтобы ссылка заработала.';
|
||||
else if (ready && dirty) text = 'Сохраните изменения, чтобы ссылка заработала.';
|
||||
hint.hidden = !text;
|
||||
hint.textContent = text;
|
||||
if (visible) {
|
||||
@@ -322,6 +331,33 @@
|
||||
}
|
||||
}
|
||||
|
||||
function renderGradeSelect() {
|
||||
const sel = document.getElementById('qeGradeScale');
|
||||
if (!sel) return;
|
||||
const current = state.quiz.grade_scale_id === '' || state.quiz.grade_scale_id == null
|
||||
? ''
|
||||
: String(state.quiz.grade_scale_id);
|
||||
let known = current === '';
|
||||
const opts = ['<option value="">Без градации</option>'];
|
||||
for (const s of state.gradeScales) {
|
||||
if (String(s.id) === current) known = true;
|
||||
opts.push(`<option value="${s.id}">${at(s.name)}</option>`);
|
||||
}
|
||||
if (!known) opts.push(`<option value="${at(current)}">Критерий не найден</option>`);
|
||||
sel.innerHTML = opts.join('');
|
||||
sel.value = current;
|
||||
}
|
||||
|
||||
async function loadGradeScales() {
|
||||
try {
|
||||
const res = await fetch(API + '/api/grade-scales', { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
state.gradeScales = res.ok && Array.isArray(data.items) ? data.items : [];
|
||||
} catch (e) {
|
||||
state.gradeScales = [];
|
||||
}
|
||||
}
|
||||
|
||||
function renderSide() {
|
||||
const q = state.quiz;
|
||||
document.getElementById('qeName').value = q.title;
|
||||
@@ -333,15 +369,26 @@
|
||||
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('qeShowAnswersWrap').hidden = q.kind !== 'test';
|
||||
document.getElementById('qeGradeWrap').hidden = q.kind !== 'test';
|
||||
renderGradeSelect();
|
||||
document.querySelectorAll('#qeKindSeg .qe-seg-btn').forEach(b => {
|
||||
b.classList.toggle('on', b.dataset.kind === q.kind);
|
||||
});
|
||||
document.getElementById('qePassWrap').hidden = q.kind !== 'test';
|
||||
document.getElementById('qeBarTitle').textContent = q.title || 'Без названия';
|
||||
document.getElementById('qePreviewBtn').href = 'quiz.html?id=' + q.id;
|
||||
const previewBtn = document.getElementById('qePreviewBtn');
|
||||
if (previewBtn) previewBtn.href = 'quiz.html?id=' + q.id;
|
||||
renderCover();
|
||||
renderQuizAssets();
|
||||
renderAnon();
|
||||
if (location.hash === '#public') {
|
||||
const wrap = document.getElementById('qeAnonWrap');
|
||||
if (wrap) wrap.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||
const url = document.getElementById('qeAnonUrl');
|
||||
if (url && !document.getElementById('qeAnonLink').hidden) url.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
@@ -740,13 +787,14 @@
|
||||
state.quiz.time_limit_min = e.target.value === '' ? 0 : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
['qePublished', 'qeShuffleQ', 'qeShuffleO', 'qeShowResults', 'qeAnonymous'].forEach(id => {
|
||||
['qePublished', 'qeShuffleQ', 'qeShuffleO', 'qeShowResults', 'qeShowAnswers', 'qeAnonymous'].forEach(id => {
|
||||
document.getElementById(id).addEventListener('change', e => {
|
||||
const map = {
|
||||
qePublished: 'is_published',
|
||||
qeShuffleQ: 'shuffle_questions',
|
||||
qeShuffleO: 'shuffle_options',
|
||||
qeShowResults: 'show_results',
|
||||
qeShowAnswers: 'show_answers',
|
||||
qeAnonymous: 'allow_anonymous',
|
||||
};
|
||||
state.quiz[map[id]] = e.target.checked;
|
||||
@@ -754,12 +802,15 @@
|
||||
if (id === 'qePublished' || id === 'qeAnonymous') renderAnon();
|
||||
});
|
||||
});
|
||||
document.getElementById('qeGradeScale').addEventListener('change', e => {
|
||||
state.quiz.grade_scale_id = e.target.value === '' ? '' : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
document.getElementById('qeKindSeg').addEventListener('click', e => {
|
||||
const btn = e.target.closest('[data-kind]');
|
||||
if (!btn) return;
|
||||
if (state.quiz.kind === btn.dataset.kind) return;
|
||||
state.quiz.kind = btn.dataset.kind;
|
||||
if (state.quiz.kind !== 'survey') state.quiz.allow_anonymous = false;
|
||||
markDirty();
|
||||
renderSide();
|
||||
renderQuestions();
|
||||
@@ -832,6 +883,7 @@
|
||||
if (!(await checkAuth())) return;
|
||||
buildSidebar(document.body.dataset.page);
|
||||
bind();
|
||||
await loadGradeScales();
|
||||
await load();
|
||||
}
|
||||
|
||||
|
||||
+59
-16
@@ -122,15 +122,16 @@
|
||||
|
||||
function introHtml() {
|
||||
const q = state.quiz;
|
||||
const isTest = q.kind === 'test';
|
||||
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 || 'Опрос')}</div>
|
||||
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span>${q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : ''}</div>
|
||||
<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>
|
||||
${q.description ? `<div class="qp-desc">${renderMd(q.description)}</div>` : ''}
|
||||
${assetsHtml(state.quizAssets)}
|
||||
<div class="qp-actions">
|
||||
<button type="button" class="btn-primary" data-act="start">Начать</button>
|
||||
<span class="qp-hint">Ответы сохраняются без имени и входа в систему.</span>
|
||||
<span class="qp-hint">${isTest ? 'Вход в систему не нужен.' : 'Ответы сохраняются без имени и входа в систему.'}</span>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -206,10 +207,18 @@
|
||||
const btn = document.querySelector('[data-act="start"]');
|
||||
if (btn) btn.disabled = true;
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts', { method: 'POST' });
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось начать');
|
||||
state.attempt = { id: data.attempt.id, started_at: data.attempt.started_at, anon_token: data.attempt.anon_token };
|
||||
state.attempt = {
|
||||
id: data.attempt.id,
|
||||
started_at: data.attempt.started_at,
|
||||
anon_token: data.attempt.anon_token,
|
||||
};
|
||||
if (data.quiz) {
|
||||
state.quiz = data.quiz.quiz || state.quiz;
|
||||
state.questions = data.quiz.questions || state.questions;
|
||||
@@ -223,6 +232,44 @@
|
||||
}
|
||||
}
|
||||
|
||||
function renderDone(data) {
|
||||
const isTest = state.quiz && state.quiz.kind === 'test';
|
||||
const result = data && data.result ? data.result : null;
|
||||
const score = result ? `${result.score} / ${result.max_score} (${result.percent}%)` : '';
|
||||
const passText = result && result.passed === true ? 'Тест сдан' : (result && result.passed === false ? 'Тест не сдан' : '');
|
||||
const grade = result && result.grade ? result.grade : null;
|
||||
const gradeHtml = grade
|
||||
? `<div class="qp-grade">${grade.image_path ? `<img src="${at(thumb(grade.image_path))}" data-img="${at(API + grade.image_path)}" alt="">` : ''}<div class="qp-grade-label">${esc2(grade.label || '')}</div></div>`
|
||||
: '';
|
||||
const hiddenAnswers = !!(result && result.answers_hidden);
|
||||
const details = result && Array.isArray(result.questions) && result.questions.length
|
||||
? `<div class="qp-result">${result.questions.map(q => {
|
||||
const ok = q.is_correct === true;
|
||||
const bad = q.is_correct === false;
|
||||
return `<div class="qp-result-item ${ok ? 'ok' : (bad ? 'bad' : '')}">
|
||||
<div class="qp-result-q">${esc2(q.text || '')}</div>
|
||||
<div class="qp-result-a">${ok ? 'Верно' : (bad ? 'Неверно' : 'Ответ сохранён')}${q.max_score ? ` · ${q.score} / ${q.max_score}` : ''}</div>
|
||||
</div>`;
|
||||
}).join('')}</div>`
|
||||
: '';
|
||||
let hint = 'Ответы сохранены.';
|
||||
if (isTest) {
|
||||
if (!result) hint = 'Ответы сохранены. Подробный результат автор скрыл.';
|
||||
else if (hiddenAnswers) hint = 'Ответы сохранены. Автор скрыл разбор ответов.';
|
||||
}
|
||||
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>
|
||||
${isTest && score ? `<p style="margin-top:8px;font-size:1rem"><b>${esc2(score)}</b>${passText ? ` · ${esc2(passText)}` : ''}</p>` : ''}
|
||||
${gradeHtml}
|
||||
<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>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
async function submit(auto) {
|
||||
if (!state.attempt) return;
|
||||
if (!auto) {
|
||||
@@ -260,14 +307,7 @@
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
|
||||
stopTimer();
|
||||
state.done = true;
|
||||
document.getElementById('qpBody').innerHTML = `<div class="qp-card qp-done">
|
||||
<div class="qp-done-ic">✓</div>
|
||||
<div class="qp-title">Спасибо!</div>
|
||||
<p class="qp-hint" style="margin-top:8px">Ответы сохранены.</p>
|
||||
<div class="qp-actions" style="justify-content:center">
|
||||
<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>
|
||||
</div>
|
||||
</div>`;
|
||||
renderDone(data);
|
||||
} catch (e) {
|
||||
toast(e.message, true);
|
||||
if (btn) btn.disabled = false;
|
||||
@@ -332,18 +372,21 @@
|
||||
|
||||
async function init() {
|
||||
if (!Number.isInteger(quizId) || quizId < 1) {
|
||||
document.getElementById('qpBody').innerHTML = '<div class="qp-error">Неверная ссылка на опрос</div>';
|
||||
document.getElementById('qpBody').innerHTML = '<div class="qp-error">Неверная ссылка</div>';
|
||||
return;
|
||||
}
|
||||
bind();
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Опрос не найден');
|
||||
if (!res.ok) throw new Error(data.error || 'Тест не найден');
|
||||
state.quiz = data.quiz;
|
||||
state.questions = data.questions || [];
|
||||
state.quizAssets = data.quiz_assets || [];
|
||||
document.title = (state.quiz.title || 'Опрос') + ' — опрос';
|
||||
const kindLabel = state.quiz.kind === 'survey' ? 'Опрос' : 'Тест';
|
||||
document.title = (state.quiz.title || kindLabel) + ' — ' + kindLabel.toLowerCase();
|
||||
const brand = document.getElementById('qpBrand');
|
||||
if (brand) brand.textContent = kindLabel;
|
||||
render();
|
||||
} catch (e) {
|
||||
document.getElementById('qpBody').innerHTML = `<div class="qp-error">${esc2(e.message)}</div>`;
|
||||
|
||||
+19
-4
@@ -86,7 +86,7 @@
|
||||
`<span class="qz-badge${q.is_published ? ' on' : ''}">${q.is_published ? 'Опубликован' : 'Черновик'}</span>`,
|
||||
state.quiz.can_edit ? '<span class="qz-badge on">Редактирование доступно</span>' : '',
|
||||
`</div>`,
|
||||
q.description ? `<div class="qz-desc">${renderMd(q.description)}</div>` : '',
|
||||
q.description ? `<div class="qz-desc qz-q">${renderMd(q.description)}</div>` : '',
|
||||
`</div>`,
|
||||
`</div>`,
|
||||
];
|
||||
@@ -240,21 +240,35 @@
|
||||
state.timer = null;
|
||||
}
|
||||
|
||||
function gradeBlock(grade) {
|
||||
if (!grade) return '';
|
||||
const img = grade.image_path
|
||||
? `<img src="${at(thumbSrc(grade.image_path))}" alt="" style="width:52px;height:52px;object-fit:cover;border-radius:10px">`
|
||||
: '';
|
||||
return `<div style="margin-top:10px;display:flex;align-items:center;gap:10px">
|
||||
${img}
|
||||
<div><div style="font-size:.76rem;color:var(--muted);text-transform:uppercase;letter-spacing:.04em">Оценка</div>
|
||||
<div style="font-weight:700;font-size:1.05rem">${esc(grade.label || '')}</div></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderResult() {
|
||||
const body = document.getElementById('qzBody');
|
||||
const attempt = state.attempt;
|
||||
if (!attempt) return;
|
||||
const pct = Number(attempt.percent || 0);
|
||||
const grade = state.result && state.result.grade ? state.result.grade : null;
|
||||
const head = `<div class="qz-panel">
|
||||
<div class="qz-sub">${kindLabel(state.quiz.kind)} · ${fmtDateTime(attempt.finished_at || attempt.started_at)}</div>
|
||||
${state.quiz.kind === 'test'
|
||||
? `<div class="qz-score">${Number(attempt.score || 0).toFixed(2)} <small>из ${Number(attempt.max_score || 0).toFixed(2)} · ${pct.toFixed(1)}%</small></div>
|
||||
<div class="qz-bar ${attempt.passed ? 'ok' : ''}" style="margin-top:10px"><span style="width:${Math.max(0, Math.min(100, pct))}%"></span></div>
|
||||
<div class="qz-badges"><span class="qz-badge ${attempt.passed ? 'on' : 'warn'}">${attempt.passed ? 'Сдано' : 'Не сдано'}</span></div>`
|
||||
<div class="qz-badges"><span class="qz-badge ${attempt.passed ? 'on' : 'warn'}">${attempt.passed ? 'Сдано' : 'Не сдано'}</span></div>
|
||||
${gradeBlock(grade)}`
|
||||
: '<div class="qz-hint" style="margin-top:6px">Ответы сохранены. Опрос не оценивается.</div>'}
|
||||
</div>`;
|
||||
let details = '';
|
||||
if (state.result && Array.isArray(state.result.questions)) {
|
||||
if (state.result && Array.isArray(state.result.questions) && state.result.questions.length) {
|
||||
details = state.result.questions.map((r, i) => {
|
||||
const mark = r.is_correct === null ? '' : r.is_correct
|
||||
? '<span class="qz-check ok">верно</span>'
|
||||
@@ -291,7 +305,8 @@
|
||||
<div class="qz-sub">${esc(a.user_name || '')} · ${fmtDateTime(a.finished_at || a.started_at)}</div>
|
||||
${state.quiz.kind === 'test'
|
||||
? `<div class="qz-score">${Number(a.score).toFixed(2)} <small>из ${Number(a.max_score).toFixed(2)} · ${pct.toFixed(1)}%</small></div>
|
||||
<div class="qz-bar ${a.passed ? 'ok' : ''}" style="margin-top:10px"><span style="width:${Math.max(0, Math.min(100, pct))}%"></span></div>`
|
||||
<div class="qz-bar ${a.passed ? 'ok' : ''}" style="margin-top:10px"><span style="width:${Math.max(0, Math.min(100, pct))}%"></span></div>
|
||||
${gradeBlock(data.grade)}`
|
||||
: '<div class="qz-hint" style="margin-top:6px">Опрос не оценивается.</div>'}
|
||||
</div>`;
|
||||
const rows = (data.answers || []).map((row, i) => {
|
||||
|
||||
+553
-42
@@ -1,8 +1,19 @@
|
||||
(function () {
|
||||
let items = [];
|
||||
let loading = false;
|
||||
let loaded = false;
|
||||
let deletedMode = false;
|
||||
let loadSeq = 0;
|
||||
let loadAbort = null;
|
||||
let aiEnabled = false;
|
||||
let aiBusy = false;
|
||||
let aiModelsCache = null;
|
||||
let aiJob = null;
|
||||
let aiPoll = null;
|
||||
const AI_HISTORY_LIMIT = 20;
|
||||
const LOAD_TIMEOUT_MS = 15000;
|
||||
const aiHistory = { offset: 0, total: 0, items: [], error: '', loading: false, poll: null };
|
||||
let liveSource = null;
|
||||
let liveDebounce = null;
|
||||
|
||||
function attr(s) {
|
||||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||||
@@ -12,11 +23,19 @@
|
||||
return {
|
||||
search: document.getElementById('quizSearch').value.trim(),
|
||||
kind: document.getElementById('quizKindFilter').value,
|
||||
mine: document.getElementById('quizMineOnly').checked ? '1' : '',
|
||||
deleted: document.getElementById('quizDeletedOnly').checked ? '1' : '',
|
||||
};
|
||||
}
|
||||
|
||||
function mineOnly() {
|
||||
return !!document.getElementById('quizMineOnly').checked;
|
||||
}
|
||||
|
||||
function visibleItems() {
|
||||
if (!mineOnly() || !currentUser) return items;
|
||||
return items.filter(q => Number(q.author_id) === Number(currentUser.id));
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return kind === 'survey' ? 'Опрос' : 'Тест';
|
||||
}
|
||||
@@ -27,7 +46,7 @@
|
||||
: '<span class="quiz-cover-ic"><i data-lucide="clipboard-list"></i></span>';
|
||||
const flags = [];
|
||||
flags.push(`<span class="quiz-flag${q.is_published ? ' on' : ''}">${q.is_published ? 'Опубликован' : 'Черновик'}</span>`);
|
||||
if (q.allow_anonymous) flags.push('<span class="quiz-flag on">Анонимный</span>');
|
||||
if (q.allow_anonymous) flags.push('<span class="quiz-flag on">Ссылка</span>');
|
||||
if (q.deleted_at) flags.push('<span class="quiz-flag del">Удалён</span>');
|
||||
const attempts = q.kind === 'test'
|
||||
? `Попыток: <b>${q.attempt_count}</b>${q.my_attempt_count ? ` · моих: <b>${q.my_attempt_count}</b>` : ''}`
|
||||
@@ -41,6 +60,7 @@
|
||||
} else {
|
||||
if (q.can_take) actions.push(`<a class="btn-link" href="quiz.html?id=${q.id}">Пройти</a>`);
|
||||
if (q.can_edit) actions.push(`<a class="btn-link" href="quiz-edit.html?id=${q.id}">Изменить</a>`);
|
||||
if (q.can_edit && q.allow_anonymous && q.is_published) actions.push(`<button type="button" class="btn-link" data-copy-link="${q.id}">Ссылку</button>`);
|
||||
if (q.can_edit) actions.push(`<button type="button" class="btn-link" data-stats="${q.id}">Статистика</button>`);
|
||||
if (q.can_edit) actions.push(`<button type="button" class="btn-link danger" data-del="${q.id}">Удалить</button>`);
|
||||
}
|
||||
@@ -66,58 +86,95 @@
|
||||
function render() {
|
||||
const list = document.getElementById('quizList');
|
||||
const empty = document.getElementById('quizEmpty');
|
||||
if (loading) {
|
||||
if (!loaded) {
|
||||
list.innerHTML = '';
|
||||
empty.hidden = true;
|
||||
return;
|
||||
}
|
||||
if (!items.length) {
|
||||
list.innerHTML = '';
|
||||
empty.hidden = false;
|
||||
empty.className = 'quiz-empty';
|
||||
empty.textContent = deletedMode ? 'В корзине нет тестов и опросов' : 'Тестов и опросов пока нет';
|
||||
const shown = visibleItems();
|
||||
if (!shown.length) {
|
||||
renderPlaceholder(deletedMode
|
||||
? 'В корзине нет тестов и опросов'
|
||||
: (mineOnly() ? 'У вас пока нет своих тестов и опросов' : 'Тестов и опросов пока нет'));
|
||||
return;
|
||||
}
|
||||
empty.hidden = true;
|
||||
list.innerHTML = items.map(cardHtml).join('');
|
||||
list.innerHTML = shown.map(cardHtml).join('');
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const seq = ++loadSeq;
|
||||
loading = true;
|
||||
render();
|
||||
const f = filters();
|
||||
deletedMode = !!f.deleted;
|
||||
const params = new URLSearchParams();
|
||||
if (f.search) params.set('search', f.search);
|
||||
if (f.kind) params.set('kind', f.kind);
|
||||
if (f.mine) params.set('mine', f.mine);
|
||||
if (f.deleted) params.set('deleted', f.deleted);
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes?' + params.toString(), { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (seq !== loadSeq) return;
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить тесты');
|
||||
items = Array.isArray(data.items) ? data.items : [];
|
||||
} catch (e) {
|
||||
if (seq !== loadSeq) return;
|
||||
items = [];
|
||||
loading = false;
|
||||
function renderPlaceholder(text) {
|
||||
const list = document.getElementById('quizList');
|
||||
const empty = document.getElementById('quizEmpty');
|
||||
list.innerHTML = '';
|
||||
empty.hidden = false;
|
||||
empty.className = 'quiz-empty';
|
||||
empty.textContent = text;
|
||||
}
|
||||
|
||||
function renderLoadError(message) {
|
||||
const list = document.getElementById('quizList');
|
||||
const empty = document.getElementById('quizEmpty');
|
||||
list.innerHTML = '';
|
||||
empty.hidden = false;
|
||||
empty.className = 'quiz-error';
|
||||
empty.innerHTML = `${esc(e.message)}<div style="margin-top:10px"><button type="button" class="btn-primary ghost" id="quizRetry">Повторить</button></div>`;
|
||||
document.getElementById('quizRetry').addEventListener('click', () => {
|
||||
empty.className = 'quiz-empty';
|
||||
load();
|
||||
});
|
||||
empty.innerHTML = `${esc(message)}<div style="margin-top:10px"><button type="button" class="btn-primary ghost" id="quizRetry">Повторить</button></div>`;
|
||||
document.getElementById('quizRetry').addEventListener('click', () => load());
|
||||
}
|
||||
|
||||
function setBusy(busy) {
|
||||
const bar = document.getElementById('quizBusy');
|
||||
if (bar) bar.classList.toggle('on', busy);
|
||||
const list = document.getElementById('quizList');
|
||||
if (list) list.classList.toggle('quiz-busy', busy);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const seq = ++loadSeq;
|
||||
const f = filters();
|
||||
const nextDeleted = !!f.deleted;
|
||||
const params = new URLSearchParams();
|
||||
if (f.search) params.set('search', f.search);
|
||||
if (f.kind) params.set('kind', f.kind);
|
||||
if (f.deleted) params.set('deleted', f.deleted);
|
||||
if (loadAbort) loadAbort.abort();
|
||||
const controller = new AbortController();
|
||||
loadAbort = controller;
|
||||
let expired = false;
|
||||
const timer = setTimeout(() => {
|
||||
expired = true;
|
||||
controller.abort();
|
||||
}, LOAD_TIMEOUT_MS);
|
||||
setBusy(true);
|
||||
let failure = null;
|
||||
let nextItems = [];
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes?' + params.toString(), { headers: hdr(), signal: controller.signal });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (seq !== loadSeq) return;
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить тесты');
|
||||
nextItems = Array.isArray(data.items) ? data.items : [];
|
||||
aiEnabled = data.ai_enabled !== false;
|
||||
syncAiButton();
|
||||
} catch (e) {
|
||||
if (seq !== loadSeq) return;
|
||||
if (e && e.name === 'AbortError' && !expired) return;
|
||||
failure = expired
|
||||
? new Error('Сервер не ответил вовремя. Закройте лишние вкладки приложения и нажмите «Повторить».')
|
||||
: e;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (loadAbort === controller) loadAbort = null;
|
||||
if (seq === loadSeq) setBusy(false);
|
||||
}
|
||||
loaded = true;
|
||||
deletedMode = nextDeleted;
|
||||
if (failure) {
|
||||
items = [];
|
||||
renderLoadError(failure.message);
|
||||
return;
|
||||
}
|
||||
if (seq !== loadSeq) return;
|
||||
loading = false;
|
||||
items = nextItems;
|
||||
render();
|
||||
}
|
||||
|
||||
@@ -136,6 +193,381 @@
|
||||
}
|
||||
}
|
||||
|
||||
function syncAiButton() {
|
||||
const btn = document.getElementById('quizAiBtn');
|
||||
if (btn) btn.style.display = aiEnabled ? '' : 'none';
|
||||
}
|
||||
|
||||
function setAiStatus(text, kind) {
|
||||
const el = document.getElementById('quizAiStatus');
|
||||
el.textContent = text;
|
||||
el.className = 'quiz-ai-status' + (kind ? ' ' + kind : '');
|
||||
}
|
||||
|
||||
function setAiBusy(busy) {
|
||||
aiBusy = !!busy;
|
||||
const runBtn = document.getElementById('quizAiRun');
|
||||
if (runBtn) runBtn.disabled = aiBusy;
|
||||
}
|
||||
|
||||
function stopAiPoll() {
|
||||
if (aiPoll) {
|
||||
clearInterval(aiPoll);
|
||||
aiPoll = null;
|
||||
}
|
||||
}
|
||||
|
||||
function syncAiResult(job) {
|
||||
const box = document.getElementById('quizAiResult');
|
||||
const text = document.getElementById('quizAiResultText');
|
||||
const edit = document.getElementById('quizAiOpenEdit');
|
||||
const pub = document.getElementById('quizAiOpenPublic');
|
||||
if (!box || !text) return;
|
||||
if (job && job.status === 'done' && job.quiz_id) {
|
||||
const editUrl = 'quiz-edit.html?id=' + job.quiz_id;
|
||||
box.hidden = false;
|
||||
text.textContent = `Готово: создан тест #${job.quiz_id}, вопросов: ${job.questions || 0}.`;
|
||||
if (edit) edit.href = editUrl;
|
||||
if (pub) pub.href = editUrl + '#public';
|
||||
renderIcons();
|
||||
} else {
|
||||
box.hidden = true;
|
||||
if (text) text.textContent = '';
|
||||
if (edit) edit.removeAttribute('href');
|
||||
if (pub) pub.removeAttribute('href');
|
||||
}
|
||||
}
|
||||
|
||||
function applyAiJob(job) {
|
||||
aiJob = job || null;
|
||||
if (!job) {
|
||||
setAiBusy(false);
|
||||
syncAiResult(null);
|
||||
return;
|
||||
}
|
||||
if (job.status === 'pending' || job.status === 'processing') {
|
||||
setAiBusy(true);
|
||||
syncAiResult(null);
|
||||
setAiStatus(job.status === 'pending'
|
||||
? 'Задание в очереди… страницу можно закрыть, результат появится в списке.'
|
||||
: 'ИИ генерирует вопросы… страницу можно закрыть, результат появится в списке.', 'busy');
|
||||
return;
|
||||
}
|
||||
setAiBusy(false);
|
||||
stopAiPoll();
|
||||
if (job.status === 'done') {
|
||||
syncAiResult(job);
|
||||
setAiStatus('Генерация завершена. Тест создан как черновик.');
|
||||
load();
|
||||
} else {
|
||||
syncAiResult(null);
|
||||
setAiStatus('Ошибка: ' + (job.error || 'Не удалось сгенерировать тест'), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAiJob() {
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/ai-jobs/active', { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return;
|
||||
if (data.job) applyAiJob(data.job);
|
||||
else if (aiBusy) applyAiJob(null);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
function startAiPoll() {
|
||||
stopAiPoll();
|
||||
aiPoll = setInterval(refreshAiJob, 3000);
|
||||
}
|
||||
|
||||
function aiStatusLabel(status) {
|
||||
if (status === 'pending') return 'В очереди';
|
||||
if (status === 'processing') return 'В работе';
|
||||
if (status === 'done') return 'Готово';
|
||||
if (status === 'error') return 'Ошибка';
|
||||
return status || '—';
|
||||
}
|
||||
|
||||
function aiDifficultyLabel(value) {
|
||||
if (value === 'easy') return 'лёгкая';
|
||||
if (value === 'hard') return 'сложная';
|
||||
return 'средняя';
|
||||
}
|
||||
|
||||
function aiHistoryMeta(job) {
|
||||
const parts = [];
|
||||
parts.push(`#${job.id}`);
|
||||
parts.push(kindLabel(job.kind));
|
||||
parts.push(`вопросов: <b>${job.questions != null ? job.questions : job.count}</b>`);
|
||||
parts.push(`сложность: ${aiDifficultyLabel(job.difficulty)}`);
|
||||
if (job.attempts > 1) parts.push(`попыток: <b>${job.attempts}</b>`);
|
||||
if (job.model) parts.push(`модель: <b>${esc(job.model)}</b>`);
|
||||
else if (job.profile && job.profile !== 'native') parts.push(`профиль: <b>${esc(job.profile)}</b>`);
|
||||
else parts.push('модель: <b>нативная</b>');
|
||||
if (currentUser && currentUser.role === 'admin') {
|
||||
const who = job.user_name || job.user_username;
|
||||
if (who) parts.push(`автор: <b>${esc(who)}</b>`);
|
||||
}
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
function aiHistoryRow(job) {
|
||||
const prompt = String(job.prompt || '').trim();
|
||||
const created = job.created_at ? fmtDateTime(job.created_at) : '';
|
||||
const finished = job.finished_at ? ' → ' + fmtDateTime(job.finished_at) : '';
|
||||
const link = job.quiz_id
|
||||
? `<a class="btn-link quiz-ai-job-link" href="quiz-edit.html?id=${job.quiz_id}">Открыть тест #${job.quiz_id}</a>`
|
||||
: '';
|
||||
return `<div class="quiz-ai-job">
|
||||
<div class="quiz-ai-job-head">
|
||||
<span class="quiz-ai-job-status ${attr(job.status)}" data-job-status="${job.id}">${aiStatusLabel(job.status)}</span>
|
||||
<span class="quiz-ai-job-meta">${created}${finished}</span>
|
||||
</div>
|
||||
<div class="quiz-ai-job-prompt" title="${attr(prompt.slice(0, 300))}">${prompt ? esc(prompt) : '<span style="color:var(--muted)">Без описания</span>'}</div>
|
||||
<div class="quiz-ai-job-meta">${aiHistoryMeta(job)}</div>
|
||||
${job.error ? `<div class="quiz-ai-job-error">${esc(job.error)}</div>` : ''}
|
||||
${link}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderAiHistory() {
|
||||
const list = document.getElementById('quizAiHistoryList');
|
||||
if (!list) return;
|
||||
if (aiHistory.loading && !aiHistory.items.length) {
|
||||
list.innerHTML = '<div class="quiz-ai-history-empty">Загрузка…</div>';
|
||||
} else if (aiHistory.error && !aiHistory.items.length) {
|
||||
list.innerHTML = `<div class="quiz-ai-history-empty">${esc(aiHistory.error)}</div>`;
|
||||
} else if (!aiHistory.items.length) {
|
||||
list.innerHTML = '<div class="quiz-ai-history-empty">Заданий пока нет. Сгенерируйте тест — оно появится здесь.</div>';
|
||||
} else {
|
||||
list.innerHTML = aiHistory.items.map(aiHistoryRow).join('');
|
||||
}
|
||||
const from = aiHistory.total ? aiHistory.offset + 1 : 0;
|
||||
const to = Math.min(aiHistory.offset + AI_HISTORY_LIMIT, aiHistory.total);
|
||||
document.getElementById('quizAiHistoryPage').textContent = `${from}–${to} из ${aiHistory.total}`;
|
||||
document.getElementById('quizAiHistoryPrev').disabled = aiHistory.loading || aiHistory.offset <= 0;
|
||||
document.getElementById('quizAiHistoryNext').disabled = aiHistory.loading || aiHistory.offset + AI_HISTORY_LIMIT >= aiHistory.total;
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
async function fetchAiHistory() {
|
||||
const res = await fetch(API + '/api/quizzes/ai-jobs?limit=' + AI_HISTORY_LIMIT + '&offset=' + aiHistory.offset, { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить историю');
|
||||
return {
|
||||
items: Array.isArray(data.items) ? data.items : [],
|
||||
total: Number(data.total) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadAiHistory() {
|
||||
aiHistory.loading = true;
|
||||
renderAiHistory();
|
||||
try {
|
||||
const data = await fetchAiHistory();
|
||||
aiHistory.items = data.items;
|
||||
aiHistory.total = data.total;
|
||||
aiHistory.error = '';
|
||||
} catch (e) {
|
||||
aiHistory.error = e.message;
|
||||
} finally {
|
||||
aiHistory.loading = false;
|
||||
renderAiHistory();
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAiHistory() {
|
||||
if (!document.getElementById('quizAiHistoryModal').classList.contains('open')) return;
|
||||
if (aiHistory.loading) return;
|
||||
try {
|
||||
const data = await fetchAiHistory();
|
||||
const sameSet = data.items.length === aiHistory.items.length
|
||||
&& data.items.every((job, i) => aiHistory.items[i] && aiHistory.items[i].id === job.id);
|
||||
const totalChanged = data.total !== aiHistory.total;
|
||||
const finalChanged = data.items.some(job => {
|
||||
const prev = aiHistory.items.find(item => item.id === job.id);
|
||||
return prev && prev.status !== job.status && job.status !== 'pending' && job.status !== 'processing';
|
||||
});
|
||||
aiHistory.items = data.items;
|
||||
aiHistory.total = data.total;
|
||||
aiHistory.error = '';
|
||||
if (!sameSet || totalChanged || finalChanged) {
|
||||
renderAiHistory();
|
||||
return;
|
||||
}
|
||||
data.items.forEach(job => {
|
||||
const badge = document.querySelector('[data-job-status="' + job.id + '"]');
|
||||
if (!badge) return;
|
||||
badge.textContent = aiStatusLabel(job.status);
|
||||
badge.className = 'quiz-ai-job-status ' + job.status;
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
function openQuizAiHistory() {
|
||||
aiHistory.offset = 0;
|
||||
aiHistory.items = [];
|
||||
aiHistory.total = 0;
|
||||
aiHistory.error = '';
|
||||
document.getElementById('quizAiHistoryModal').classList.add('open');
|
||||
renderIcons();
|
||||
loadAiHistory();
|
||||
if (aiHistory.poll) clearInterval(aiHistory.poll);
|
||||
aiHistory.poll = setInterval(refreshAiHistory, 3000);
|
||||
}
|
||||
|
||||
function closeQuizAiHistory() {
|
||||
document.getElementById('quizAiHistoryModal').classList.remove('open');
|
||||
if (aiHistory.poll) {
|
||||
clearInterval(aiHistory.poll);
|
||||
aiHistory.poll = null;
|
||||
}
|
||||
}
|
||||
|
||||
function aiHistoryPage(delta) {
|
||||
const next = aiHistory.offset + delta * AI_HISTORY_LIMIT;
|
||||
if (next < 0 || next >= aiHistory.total) return;
|
||||
aiHistory.offset = next;
|
||||
document.getElementById('quizAiHistoryList').scrollTop = 0;
|
||||
loadAiHistory();
|
||||
}
|
||||
|
||||
function aiNativeOption(label) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = 'native';
|
||||
opt.textContent = label;
|
||||
return opt;
|
||||
}
|
||||
|
||||
function aiOptgroup(label, list) {
|
||||
const group = document.createElement('optgroup');
|
||||
group.label = label;
|
||||
list.forEach(m => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = m.id;
|
||||
opt.textContent = [m.name, m.model].filter(Boolean).join(' — ');
|
||||
group.appendChild(opt);
|
||||
});
|
||||
return group;
|
||||
}
|
||||
|
||||
async function loadAiModels() {
|
||||
const [mineRes, optRes] = await Promise.allSettled([
|
||||
fetch(API + '/api/user-settings', { headers: hdr() }),
|
||||
fetch(API + '/api/ai/profiles/options', { headers: hdr() }),
|
||||
]);
|
||||
const result = { native: 'Нативная', active: 'native', profiles: [], personal: [], loaded: 0 };
|
||||
if (optRes.status === 'fulfilled' && optRes.value.ok) {
|
||||
const d = await optRes.value.json().catch(() => ({}));
|
||||
result.loaded++;
|
||||
if (d.native && d.native.model) result.native = 'Нативная — ' + d.native.model;
|
||||
result.active = d.active || 'native';
|
||||
if (Array.isArray(d.profiles)) result.profiles = d.profiles;
|
||||
}
|
||||
if (mineRes.status === 'fulfilled' && mineRes.value.ok) {
|
||||
const d = await mineRes.value.json().catch(() => ({}));
|
||||
let arr = [];
|
||||
try {
|
||||
arr = JSON.parse((d.settings && d.settings.feedback_models) || '[]');
|
||||
} catch (e) {
|
||||
arr = [];
|
||||
}
|
||||
result.loaded++;
|
||||
if (Array.isArray(arr)) result.personal = arr.filter(m => m && m.id);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function fillAiModels(models) {
|
||||
const sel = document.getElementById('quizAiModel');
|
||||
const keep = sel.value;
|
||||
sel.innerHTML = '';
|
||||
sel.appendChild(aiNativeOption(models.native));
|
||||
if (models.personal.length) sel.appendChild(aiOptgroup('Мои модели', models.personal));
|
||||
if (models.profiles.length) sel.appendChild(aiOptgroup('Системные', models.profiles));
|
||||
const wanted = keep || models.active;
|
||||
sel.value = [...sel.options].some(o => o.value === wanted) ? wanted : 'native';
|
||||
}
|
||||
|
||||
async function openQuizAi() {
|
||||
if (!aiEnabled) {
|
||||
showToast('ИИ-генерация отключена в настройках', true);
|
||||
return;
|
||||
}
|
||||
document.getElementById('quizAiPrompt').value = '';
|
||||
document.getElementById('quizAiPromptCount').textContent = '0';
|
||||
document.getElementById('quizAiCount').value = '10';
|
||||
document.getElementById('quizAiKind').value = 'test';
|
||||
document.getElementById('quizAiDifficulty').value = 'medium';
|
||||
const sel = document.getElementById('quizAiModel');
|
||||
sel.innerHTML = '<option value="native">Нативная</option>';
|
||||
if (aiModelsCache) fillAiModels(aiModelsCache);
|
||||
syncAiResult(aiJob && aiJob.status === 'done' ? aiJob : null);
|
||||
if (!aiBusy) setAiStatus('Готово к генерации');
|
||||
document.getElementById('quizAiModal').classList.add('open');
|
||||
renderIcons();
|
||||
document.getElementById('quizAiPrompt').focus();
|
||||
try {
|
||||
const models = await loadAiModels();
|
||||
aiModelsCache = models;
|
||||
fillAiModels(models);
|
||||
if (!models.loaded && !aiBusy) setAiStatus('Модели не загрузились — доступна нативная', 'error');
|
||||
else if (!models.personal.length && !models.profiles.length && !aiBusy) {
|
||||
setAiStatus('Доступна только нативная модель: добавьте свою в профиле, вкладка «ИИ и модели»');
|
||||
}
|
||||
} catch (e) {
|
||||
if (!aiBusy) setAiStatus('Не удалось загрузить список моделей — доступна нативная', 'error');
|
||||
}
|
||||
refreshAiJob();
|
||||
}
|
||||
|
||||
function closeQuizAi() {
|
||||
document.getElementById('quizAiModal').classList.remove('open');
|
||||
}
|
||||
|
||||
async function runQuizAi() {
|
||||
if (aiBusy) return;
|
||||
const promptText = document.getElementById('quizAiPrompt').value.trim();
|
||||
if (!promptText) {
|
||||
showToast('Опишите тему теста');
|
||||
document.getElementById('quizAiPrompt').focus();
|
||||
return;
|
||||
}
|
||||
const count = Math.max(1, Math.min(40, parseInt(document.getElementById('quizAiCount').value, 10) || 10));
|
||||
document.getElementById('quizAiCount').value = String(count);
|
||||
setAiBusy(true);
|
||||
syncAiResult(null);
|
||||
setAiStatus('Отправляем задание в очередь…', 'busy');
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/ai-generate', {
|
||||
method: 'POST',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify({
|
||||
prompt: promptText,
|
||||
kind: document.getElementById('quizAiKind').value === 'survey' ? 'survey' : 'test',
|
||||
count,
|
||||
difficulty: document.getElementById('quizAiDifficulty').value,
|
||||
profile: document.getElementById('quizAiModel').value || 'native',
|
||||
}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.status === 409 && data.job) {
|
||||
applyAiJob(data.job);
|
||||
startAiPoll();
|
||||
showToast('Генерация уже идёт');
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось запустить генерацию');
|
||||
applyAiJob(data.job);
|
||||
startAiPoll();
|
||||
showToast('Генерация запущена');
|
||||
} catch (e) {
|
||||
setAiBusy(false);
|
||||
setAiStatus('Ошибка: ' + e.message, 'error');
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeQuiz(id) {
|
||||
if (!confirm('Удалить тест? Он попадёт в корзину и будет удалён окончательно по истечении срока.')) return;
|
||||
try {
|
||||
@@ -177,12 +609,43 @@
|
||||
function bind() {
|
||||
document.getElementById('quizNewTestBtn').addEventListener('click', () => createQuiz('test'));
|
||||
document.getElementById('quizNewSurveyBtn').addEventListener('click', () => createQuiz('survey'));
|
||||
document.getElementById('quizAiBtn').addEventListener('click', openQuizAi);
|
||||
document.getElementById('quizAiCancel').addEventListener('click', closeQuizAi);
|
||||
document.getElementById('quizAiRun').addEventListener('click', runQuizAi);
|
||||
document.getElementById('quizAiModal').addEventListener('click', e => {
|
||||
if (e.target.id === 'quizAiModal') closeQuizAi();
|
||||
});
|
||||
document.getElementById('quizAiPrompt').addEventListener('input', e => {
|
||||
document.getElementById('quizAiPromptCount').textContent = String(e.target.value.length);
|
||||
});
|
||||
document.getElementById('quizAiHistoryBtn').addEventListener('click', openQuizAiHistory);
|
||||
document.getElementById('quizAiHistoryClose').addEventListener('click', closeQuizAiHistory);
|
||||
document.getElementById('quizAiHistoryPrev').addEventListener('click', () => aiHistoryPage(-1));
|
||||
document.getElementById('quizAiHistoryNext').addEventListener('click', () => aiHistoryPage(1));
|
||||
document.getElementById('quizAiHistoryRefresh').addEventListener('click', loadAiHistory);
|
||||
document.getElementById('quizAiHistoryModal').addEventListener('click', e => {
|
||||
if (e.target.id === 'quizAiHistoryModal') closeQuizAiHistory();
|
||||
});
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key !== 'Escape') return;
|
||||
if (document.getElementById('quizAiHistoryModal').classList.contains('open')) {
|
||||
closeQuizAiHistory();
|
||||
return;
|
||||
}
|
||||
if (document.getElementById('quizAiModal').classList.contains('open')) closeQuizAi();
|
||||
});
|
||||
document.getElementById('quizSearch').addEventListener('input', () => {
|
||||
clearTimeout(bind.t);
|
||||
bind.t = setTimeout(load, 300);
|
||||
});
|
||||
document.getElementById('quizKindFilter').addEventListener('change', load);
|
||||
document.getElementById('quizMineOnly').addEventListener('change', load);
|
||||
document.getElementById('quizMineOnly').addEventListener('change', () => {
|
||||
if (!loaded) {
|
||||
load();
|
||||
return;
|
||||
}
|
||||
render();
|
||||
});
|
||||
document.getElementById('quizDeletedOnly').addEventListener('change', load);
|
||||
|
||||
document.addEventListener('click', e => {
|
||||
@@ -192,6 +655,17 @@
|
||||
if (restore) { e.preventDefault(); restoreQuiz(restore.dataset.restore); return; }
|
||||
const perm = e.target.closest('[data-perm]');
|
||||
if (perm) { e.preventDefault(); purgeQuiz(perm.dataset.perm); return; }
|
||||
const copyLink = e.target.closest('[data-copy-link]');
|
||||
if (copyLink) {
|
||||
e.preventDefault();
|
||||
const url = location.origin + '/quiz-public.html?id=' + copyLink.dataset.copyLink;
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
navigator.clipboard.writeText(url).then(() => showToast('Ссылка скопирована'), () => showToast('Не удалось скопировать ссылку', true));
|
||||
} else {
|
||||
showToast(url);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const stats = e.target.closest('[data-stats]');
|
||||
if (stats) { e.preventDefault(); location.href = 'quiz.html?id=' + stats.dataset.stats + '&tab=stats'; return; }
|
||||
if (e.target.closest('a')) return;
|
||||
@@ -201,21 +675,58 @@
|
||||
}
|
||||
|
||||
function connectLive() {
|
||||
let t = null;
|
||||
if (liveSource) return;
|
||||
const es = new EventSource(API + '/api/events?token=' + encodeURIComponent(token || ''));
|
||||
liveSource = es;
|
||||
es.addEventListener('quizzes_changed', () => {
|
||||
clearTimeout(t);
|
||||
t = setTimeout(load, 400);
|
||||
clearTimeout(liveDebounce);
|
||||
liveDebounce = setTimeout(load, 400);
|
||||
});
|
||||
es.addEventListener('quiz_ai_status', e => {
|
||||
let payload = null;
|
||||
try { payload = JSON.parse(e.data); } catch (err) { return; }
|
||||
const job = payload && payload.job ? payload.job : null;
|
||||
if (!job) return;
|
||||
if (currentUser && Number(job.user_id) !== Number(currentUser.id)) return;
|
||||
applyAiJob(job);
|
||||
if (job.status === 'pending' || job.status === 'processing') startAiPoll();
|
||||
if (document.getElementById('quizAiHistoryModal').classList.contains('open')) refreshAiHistory();
|
||||
});
|
||||
}
|
||||
|
||||
function disconnectLive() {
|
||||
if (liveDebounce) {
|
||||
clearTimeout(liveDebounce);
|
||||
liveDebounce = null;
|
||||
}
|
||||
if (!liveSource) return;
|
||||
liveSource.close();
|
||||
liveSource = null;
|
||||
}
|
||||
|
||||
function bindVisibility() {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) {
|
||||
disconnectLive();
|
||||
return;
|
||||
}
|
||||
connectLive();
|
||||
load();
|
||||
});
|
||||
}
|
||||
|
||||
async function init() {
|
||||
if (!(await checkAuth())) return;
|
||||
buildSidebar(document.body.dataset.page);
|
||||
const scalesBtn = document.getElementById('quizScalesBtn');
|
||||
if (scalesBtn) scalesBtn.hidden = !(currentUser && currentUser.role === 'admin');
|
||||
bind();
|
||||
bindVisibility();
|
||||
renderIcons();
|
||||
await load();
|
||||
connectLive();
|
||||
await refreshAiJob();
|
||||
if (aiJob && (aiJob.status === 'pending' || aiJob.status === 'processing')) startAiPoll();
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'calWeekStart', 'calDayStart', 'calDayEnd', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays', 'imgbbUrl', 'imgbbKey', 'facesBrokenScanEnabled', 'facesBrokenScanInterval'];
|
||||
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'calWeekStart', 'calDayStart', 'calDayEnd', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'quizAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays', 'imgbbUrl', 'imgbbKey', 'facesBrokenScanEnabled', 'facesBrokenScanInterval'];
|
||||
const NOTIFY_IDS = [];
|
||||
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-calendar', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-achievements', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-external-services', 'sec-bans', 'sec-face-broken'];
|
||||
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-calendar', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-quiz-ai', 'sec-achievements', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-external-services', 'sec-bans', 'sec-face-broken'];
|
||||
const SPAM_MAX = 10080;
|
||||
const BAN_REASONS = {
|
||||
'honeypot': 'Антиспам-поле',
|
||||
@@ -312,6 +312,7 @@ async function loadSettings() {
|
||||
document.getElementById('lessonAiEnabled').checked = s.lesson_ai_enabled !== 'false';
|
||||
document.getElementById('lessonAiPrompt').value = s.lesson_ai_prompt || '';
|
||||
document.getElementById('notesAiEnabled').checked = s.notes_ai_enabled !== 'false';
|
||||
document.getElementById('quizAiEnabled').checked = s.quiz_ai_enabled !== 'false';
|
||||
const fe = document.getElementById('faceIdEnabled');
|
||||
const fsu = document.getElementById('faceScanOnUpload');
|
||||
const fth = document.getElementById('faceIdThreshold');
|
||||
@@ -956,6 +957,7 @@ async function saveSettings() {
|
||||
lesson_ai_enabled: document.getElementById('lessonAiEnabled').checked ? 'true' : 'false',
|
||||
lesson_ai_prompt: document.getElementById('lessonAiPrompt').value.trim(),
|
||||
notes_ai_enabled: document.getElementById('notesAiEnabled').checked ? 'true' : 'false',
|
||||
quiz_ai_enabled: document.getElementById('quizAiEnabled').checked ? 'true' : 'false',
|
||||
face_id_enabled: (document.getElementById('faceIdEnabled') || {}).checked ? 'true' : 'false',
|
||||
face_scan_on_upload: (document.getElementById('faceScanOnUpload') || {}).checked ? 'true' : 'false',
|
||||
face_id_threshold: String((document.getElementById('faceIdThreshold') || {}).value || '0.6').trim(),
|
||||
|
||||
+16
-7
@@ -33,7 +33,7 @@
|
||||
.qe-opt-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.qe-opt-row .qe-opt-text { flex: 1; min-width: 160px; }
|
||||
.qe-weight { display: inline-flex; align-items: center; gap: 6px; font-size: .78rem; font-weight: 600; color: var(--muted); white-space: nowrap; }
|
||||
.qe-weight input { width: 78px; padding: 6px 8px; font-size: .82rem; }
|
||||
.qe-weight input.settings-input { width: 78px; padding: 6px 8px; font-size: .82rem; }
|
||||
.qe-correct { padding: 3px 8px; gap: 8px; background: transparent; border-color: transparent; }
|
||||
.qe-correct:hover { background: var(--card); border-color: var(--border); }
|
||||
.qe-correct .toggle-track { width: 34px; height: 20px; }
|
||||
@@ -42,7 +42,7 @@
|
||||
.qe-mini { font-size: .74rem; }
|
||||
.qe-assets { display: flex; flex-wrap: wrap; gap: 8px; margin: 8px 0; }
|
||||
.qe-asset { position: relative; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; background: var(--card); max-width: 220px; }
|
||||
.qe-asset img { display: block; width: 120px; height: 80px; object-fit: cover; cursor: zoom-in; }
|
||||
.qe-asset img { display: block; width: 100%; height: 80px; object-fit: cover; cursor: zoom-in; }
|
||||
.qe-asset audio { display: block; width: 220px; height: 36px; }
|
||||
.qe-asset video { display: block; width: 220px; max-height: 140px; background: #000; }
|
||||
.qe-asset .qe-asset-file { display: flex; align-items: center; gap: 6px; padding: 8px 10px; font-size: .76rem; max-width: 220px; overflow-wrap: anywhere; }
|
||||
@@ -138,17 +138,26 @@
|
||||
<div class="settings-field">
|
||||
<label class="toggle"><input type="checkbox" id="qeShowResults"><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Показывать результат</small></span></label>
|
||||
</div>
|
||||
<div id="qeAnonWrap" hidden>
|
||||
<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 class="settings-field" id="qeShowAnswersWrap">
|
||||
<label class="toggle"><input type="checkbox" id="qeShowAnswers"><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Показывать ответы</small></span></label>
|
||||
<div class="qe-hint">Разбор ответов после завершения. Выключите, чтобы показывать только балл и оценку.</div>
|
||||
</div>
|
||||
<div class="qe-hint">Опрос можно пройти по ссылке без входа в систему. Ответы сохраняются без имени.</div>
|
||||
<div class="settings-field" id="qeGradeWrap">
|
||||
<label for="qeGradeScale">Критерий оценки</label>
|
||||
<select id="qeGradeScale" class="settings-input"></select>
|
||||
<div class="qe-hint">Подпись по набранным баллам. Создаётся в «Критерии оценки» на странице тестов.</div>
|
||||
</div>
|
||||
<div id="qeAnonWrap">
|
||||
<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="qe-hint" id="qeAnonDesc">По ссылке можно пройти без входа в систему.</div>
|
||||
<div class="qe-anon-link" id="qeAnonLink" hidden>
|
||||
<input class="settings-input" id="qeAnonUrl" readonly>
|
||||
<button type="button" class="btn-link" data-act="copy-anon">Копировать</button>
|
||||
<a class="btn-link" id="qeAnonOpen" target="_blank" rel="noopener noreferrer">Открыть</a>
|
||||
</div>
|
||||
<div class="qe-hint" id="qeAnonPublishHint" hidden>Опубликуйте опрос, чтобы ссылка заработала.</div>
|
||||
<div class="qe-hint" id="qeAnonPublishHint" hidden>Опубликуйте, чтобы ссылка заработала.</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
+10
-1
@@ -44,6 +44,15 @@
|
||||
.qp-error { text-align: center; color: #b91c1c; padding: 28px 16px; font-size: .9rem; border: 1px dashed rgba(220,38,38,.4); border-radius: var(--radius); }
|
||||
.qp-done { text-align: center; padding: 12px 0 4px; }
|
||||
.qp-done .qp-done-ic { font-size: 2.4rem; line-height: 1; margin-bottom: 8px; }
|
||||
.qp-grade { margin-top: 12px; display: flex; align-items: center; justify-content: center; gap: 10px; }
|
||||
.qp-grade img { width: 56px; height: 56px; object-fit: cover; border-radius: 12px; border: 1px solid var(--border); }
|
||||
.qp-grade-label { font-weight: 700; font-size: 1.1rem; }
|
||||
.qp-result { margin-top: 14px; display: grid; gap: 10px; }
|
||||
.qp-result-item { text-align: left; border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; background: var(--bg); }
|
||||
.qp-result-item.ok { border-color: rgba(34,197,94,.35); }
|
||||
.qp-result-item.bad { border-color: rgba(239,68,68,.35); }
|
||||
.qp-result-q { font-size: .84rem; font-weight: 600; margin-bottom: 4px; }
|
||||
.qp-result-a { font-size: .78rem; color: var(--muted); }
|
||||
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.75); display: none; align-items: center; justify-content: center; z-index: 200; padding: 20px; }
|
||||
.modal-overlay.open { display: flex; }
|
||||
.modal-overlay img { max-width: 92vw; max-height: 88vh; border-radius: 10px; }
|
||||
@@ -52,7 +61,7 @@
|
||||
<body>
|
||||
<div class="qp-wrap">
|
||||
<div class="qp-top">
|
||||
<span class="qp-brand">Анонимный опрос</span>
|
||||
<span class="qp-brand" id="qpBrand">Тест</span>
|
||||
<button type="button" class="btn-link" data-theme-toggle>Тема</button>
|
||||
</div>
|
||||
<div id="qpBody"></div>
|
||||
|
||||
@@ -35,8 +35,60 @@
|
||||
.quiz-toolbar .settings-field { margin: 0; min-width: 140px; }
|
||||
.quiz-toolbar .settings-field > label { font-size: .78rem; font-weight: 600; color: var(--muted); }
|
||||
.quiz-toolbar .settings-input { padding: 8px 10px; font-size: .86rem; }
|
||||
.quiz-busy-bar { display: flex; align-items: center; gap: 8px; min-height: 16px; margin-top: 12px; font-size: .8rem; color: var(--muted); visibility: hidden; }
|
||||
.quiz-busy-bar.on { visibility: visible; }
|
||||
.quiz-busy-bar::before { content: ''; width: 12px; height: 12px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: quiz-spin .7s linear infinite; }
|
||||
@keyframes quiz-spin { to { transform: rotate(360deg); } }
|
||||
.quiz-list.quiz-busy { opacity: .55; transition: opacity .15s; }
|
||||
.quiz-empty { text-align: center; color: var(--muted); padding: 40px 16px; font-size: .9rem; border: 1px dashed var(--border); border-radius: var(--radius); margin-top: 16px; }
|
||||
.quiz-error { text-align: center; color: #b91c1c; padding: 28px 16px; font-size: .9rem; border: 1px dashed rgba(220,38,38,.4); border-radius: var(--radius); margin-top: 16px; }
|
||||
.quiz-ai-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
|
||||
@media (max-width: 620px) { .quiz-ai-row { grid-template-columns: 1fr; } }
|
||||
.quiz-ai-status { font-size: .8rem; color: var(--muted); padding: 8px 10px; border: 1px dashed var(--border); border-radius: var(--radius); }
|
||||
.quiz-ai-status.error { color: #b91c1c; border-color: rgba(220,38,38,.35); }
|
||||
.quiz-ai-status.busy { color: var(--accent); border-color: rgba(37,99,235,.35); }
|
||||
.quiz-ai-result { margin-top: 10px; padding: 12px; border: 1px solid rgba(var(--accent-rgb, 37,99,235), .25); border-radius: var(--radius); background: rgba(var(--accent-rgb, 37,99,235), .04); }
|
||||
.quiz-ai-result-text { font-size: .84rem; margin-bottom: 10px; }
|
||||
.quiz-ai-result-actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.quiz-ai-result-actions .btn-primary { text-decoration: none; }
|
||||
#quizAiPrompt { resize: vertical; }
|
||||
.quiz-ai-history { display: flex; flex-direction: column; gap: 10px; max-height: 58vh; overflow-y: auto; padding-right: 2px; }
|
||||
.quiz-ai-history-empty { text-align: center; color: var(--muted); font-size: .85rem; padding: 22px 12px; border: 1px dashed var(--border); border-radius: var(--radius); }
|
||||
.quiz-ai-job { border: 1px solid var(--border); border-radius: var(--radius); padding: 10px 12px; display: flex; flex-direction: column; gap: 6px; background: var(--bg); }
|
||||
.quiz-ai-job-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.quiz-ai-job-status { font-size: .7rem; font-weight: 700; padding: 2px 9px; border-radius: 999px; border: 1px solid var(--border); color: var(--muted); }
|
||||
.quiz-ai-job-status.pending { color: #b45309; border-color: rgba(180,83,9,.3); background: rgba(180,83,9,.08); }
|
||||
.quiz-ai-job-status.processing { color: var(--accent); border-color: rgba(37,99,235,.3); background: rgba(37,99,235,.08); }
|
||||
.quiz-ai-job-status.done { color: #15803d; border-color: rgba(21,128,61,.28); background: rgba(21,128,61,.08); }
|
||||
.quiz-ai-job-status.error { color: #b91c1c; border-color: rgba(220,38,38,.25); background: rgba(220,38,38,.08); }
|
||||
.quiz-ai-job-meta { font-size: .74rem; color: var(--muted); display: flex; flex-wrap: wrap; gap: 4px 12px; }
|
||||
.quiz-ai-job-meta b { color: var(--text); font-weight: 600; }
|
||||
.quiz-ai-job-prompt { font-size: .82rem; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
|
||||
.quiz-ai-job-error { font-size: .78rem; color: #b91c1c; overflow-wrap: anywhere; }
|
||||
.quiz-ai-job-link { align-self: flex-start; font-size: .78rem; }
|
||||
.quiz-ai-pager { display: flex; align-items: center; gap: 10px; justify-content: flex-end; flex-wrap: wrap; }
|
||||
.quiz-ai-pager span { font-size: .78rem; color: var(--muted); }
|
||||
.quiz-ai-pager .btn-primary { padding: 6px 12px; font-size: .8rem; }
|
||||
.quiz-ai-pager .btn-primary:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.qs-list { display: flex; flex-direction: column; gap: 10px; max-height: 56vh; overflow-y: auto; padding-right: 2px; }
|
||||
.qs-empty { text-align: center; color: var(--muted); font-size: .85rem; padding: 22px 12px; border: 1px dashed var(--border); border-radius: var(--radius); }
|
||||
.qs-item { border: 1px solid var(--border); border-radius: var(--radius); padding: 10px 12px; background: var(--bg); display: flex; flex-direction: column; gap: 8px; }
|
||||
.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-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; }
|
||||
.qs-range-chip { font-size: .74rem; padding: 2px 8px; border: 1px solid var(--border); border-radius: 999px; color: var(--muted); }
|
||||
.qs-range { display: grid; grid-template-columns: 110px 110px minmax(160px, 1fr) auto 28px; gap: 8px; align-items: center; margin-bottom: 8px; }
|
||||
.qs-range .settings-input { padding: 8px 10px; }
|
||||
.qs-range-img { display: flex; align-items: center; gap: 6px; }
|
||||
.qs-range-img img { width: 34px; height: 34px; object-fit: cover; border-radius: 8px; border: 1px solid var(--border); }
|
||||
.qs-noimg { font-size: .74rem; color: var(--muted); }
|
||||
.qs-img-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 8px; max-height: 56vh; overflow-y: auto; }
|
||||
.qs-img-cell { padding: 0; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; background: var(--bg); cursor: pointer; aspect-ratio: 1 / 1; }
|
||||
.qs-img-cell img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
@media (max-width: 760px) { .qs-range { grid-template-columns: 1fr 1fr; } }
|
||||
</style>
|
||||
</head>
|
||||
<body data-page="quizzes">
|
||||
@@ -46,6 +98,9 @@
|
||||
<div class="page-head">
|
||||
<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="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>
|
||||
</div>
|
||||
@@ -81,17 +136,142 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="quiz-busy-bar" id="quizBusy" aria-live="polite">Обновляем список…</div>
|
||||
<div id="quizList" class="quiz-list"></div>
|
||||
<div id="quizEmpty" class="quiz-empty" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="imgModal"><img id="imgModalSrc" alt=""></div>
|
||||
|
||||
<div class="modal-overlay" id="quizAiModal">
|
||||
<div class="edit-modal" style="max-width:620px">
|
||||
<h3><i data-lucide="sparkles" style="width:18px;height:18px;vertical-align:-3px"></i> Генерация теста ИИ</h3>
|
||||
<div class="page-sub" style="margin-bottom:8px">Опишите тему — модель соберёт вопросы в фоне. Страницу можно закрыть: когда тест будет готов, он появится в списке черновиком, и отсюда можно будет открыть конструктор или ссылку для учеников.</div>
|
||||
<div class="settings-field">
|
||||
<label for="quizAiPrompt">Тема и требования <span class="req">*</span></label>
|
||||
<textarea id="quizAiPrompt" class="settings-input" rows="5" placeholder="Например: тест по основам Photoshop для детей 12–14 лет — слои, маски, форматы файлов, 10 вопросов" maxlength="4000"></textarea>
|
||||
<span class="field-note"><span id="quizAiPromptCount">0</span> / 4000</span>
|
||||
</div>
|
||||
<div class="quiz-ai-row">
|
||||
<div class="settings-field">
|
||||
<label for="quizAiKind">Тип</label>
|
||||
<select id="quizAiKind" class="settings-input">
|
||||
<option value="test">Тест с ответами</option>
|
||||
<option value="survey">Опрос</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="quizAiCount">Вопросов</label>
|
||||
<input type="number" id="quizAiCount" class="settings-input" min="1" max="40" step="1" value="10">
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="quizAiDifficulty">Сложность</label>
|
||||
<select id="quizAiDifficulty" class="settings-input">
|
||||
<option value="easy">Лёгкая</option>
|
||||
<option value="medium" selected>Средняя</option>
|
||||
<option value="hard">Сложная</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="quizAiModel">Модель</label>
|
||||
<select id="quizAiModel" class="settings-input"></select>
|
||||
<span class="field-note">Свои модели добавляются в профиле, вкладка «ИИ и модели»</span>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<div id="quizAiStatus" class="quiz-ai-status">Готово к генерации</div>
|
||||
<div id="quizAiResult" class="quiz-ai-result" hidden>
|
||||
<div id="quizAiResultText" class="quiz-ai-result-text"></div>
|
||||
<div class="quiz-ai-result-actions">
|
||||
<a id="quizAiOpenEdit" class="btn-primary ghost btn-sm" href="#">Открыть конструктор</a>
|
||||
<a id="quizAiOpenPublic" class="btn-primary btn-sm" href="#">Ссылка для учеников</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-foot" style="justify-content:flex-end;gap:8px;margin-top:12px">
|
||||
<button type="button" class="btn-primary ghost" id="quizAiCancel">Отмена</button>
|
||||
<button type="button" class="btn-primary" id="quizAiRun"><i data-lucide="sparkles" style="width:15px;height:15px;vertical-align:-3px"></i> Сгенерировать</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="quizAiHistoryModal">
|
||||
<div class="edit-modal" style="max-width:860px">
|
||||
<h3><i data-lucide="history" style="width:18px;height:18px;vertical-align:-3px"></i> История генерации тестов</h3>
|
||||
<div class="page-sub" style="margin-bottom:8px">Задания модели и их статусы. Пока окно открыто, список обновляется автоматически: очередь, работа, готовый результат или ошибка.</div>
|
||||
<div id="quizAiHistoryList" class="quiz-ai-history" aria-live="polite"></div>
|
||||
<div class="quiz-ai-pager">
|
||||
<button type="button" class="btn-primary ghost" id="quizAiHistoryPrev">Назад</button>
|
||||
<span id="quizAiHistoryPage"></span>
|
||||
<button type="button" class="btn-primary ghost" id="quizAiHistoryNext">Вперёд</button>
|
||||
<button type="button" class="btn-primary ghost" id="quizAiHistoryRefresh" title="Обновить"><i data-lucide="refresh-cw"></i></button>
|
||||
</div>
|
||||
<div class="card-foot" style="justify-content:flex-end;gap:8px;margin-top:0">
|
||||
<button type="button" class="btn-primary ghost" id="quizAiHistoryClose">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="quizScalesModal">
|
||||
<div class="edit-modal" style="max-width:940px">
|
||||
<h3><i data-lucide="award" style="width:18px;height:18px;vertical-align:-3px"></i> Критерии оценки</h3>
|
||||
<div class="page-sub" style="margin-bottom:10px">Шкалы результатов по набранным баллам. Выберите нужную в настройках теста — после завершения ученик увидит подпись и картинку диапазона, в который попал его балл.</div>
|
||||
<div id="qsListView">
|
||||
<div class="qs-list" id="qsList"></div>
|
||||
<div class="card-foot" style="justify-content:space-between;gap:8px;margin-top:12px">
|
||||
<button type="button" class="btn-primary" id="qsNewBtn"><i data-lucide="plus"></i> Новый критерий</button>
|
||||
<button type="button" class="btn-primary ghost" id="qsCloseBtn">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="qsEditorView" hidden>
|
||||
<h4 id="qsEditorTitle" style="margin:0 0 10px">Новый критерий оценки</h4>
|
||||
<div class="settings-field">
|
||||
<label for="qsName">Название *</label>
|
||||
<input id="qsName" class="settings-input" maxlength="200" placeholder="Например: Шкала на 15 баллов">
|
||||
<div class="page-sub" style="font-size:.76rem">Краткое название критерия для выбора в настройках теста.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="qsDesc">Описание</label>
|
||||
<textarea id="qsDesc" class="settings-input" rows="2" maxlength="2000"></textarea>
|
||||
</div>
|
||||
<div class="settings-field" style="max-width:200px">
|
||||
<label for="qsSort">Порядок сортировки</label>
|
||||
<input id="qsSort" type="number" class="settings-input" value="0">
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Диапазоны баллов</label>
|
||||
<div class="page-sub" style="font-size:.76rem;margin-bottom:6px">Минимальный и максимальный балл включительно. Порядок строк не важен — при показе результата берётся диапазон, в который попал набранный балл.</div>
|
||||
<div id="qsRanges"></div>
|
||||
<button type="button" class="btn-link" id="qsAddRange">+ Добавить диапазон</button>
|
||||
</div>
|
||||
<div class="card-foot" style="justify-content:flex-end;gap:8px;margin-top:12px">
|
||||
<button type="button" class="btn-primary ghost" id="qsCancelBtn">Назад</button>
|
||||
<button type="button" class="btn-primary" id="qsSaveBtn">Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="qsImageModal">
|
||||
<div class="edit-modal" style="max-width:760px">
|
||||
<h3>Картинка диапазона</h3>
|
||||
<div class="page-sub" style="margin-bottom:10px">Выберите из уже загруженных картинок или загрузите новую.</div>
|
||||
<div class="qs-img-grid" id="qsImgGrid"></div>
|
||||
<div class="card-foot" style="justify-content:space-between;gap:8px;margin-top:12px">
|
||||
<label class="btn-primary ghost" for="qsImgFile">Загрузить картинку</label>
|
||||
<input type="file" id="qsImgFile" accept="image/*" hidden>
|
||||
<button type="button" class="btn-primary ghost" id="qsImgCancel">Отмена</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
<script src="vendor/lucide.min.js"></script>
|
||||
<script src="js/datetime.js"></script>
|
||||
<script src="admin.js"></script>
|
||||
<script src="js/quizzes.js"></script>
|
||||
<script src="js/grade-scales.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -72,6 +72,7 @@
|
||||
<a href="#sec-faces" data-nav="sec-faces"><i data-lucide="scan-face"></i> Библиотека лиц</a>
|
||||
<a href="#sec-achievements" data-nav="sec-achievements"><i data-lucide="trophy"></i> Достижения</a>
|
||||
<a href="#sec-notes-ai" data-nav="sec-notes-ai"><i data-lucide="sticky-note"></i> Заголовки заметок</a>
|
||||
<a href="#sec-quiz-ai" data-nav="sec-quiz-ai"><i data-lucide="clipboard-list"></i> Генерация тестов</a>
|
||||
<a href="#sec-tls" data-nav="sec-tls"><i data-lucide="key-round"></i> Сертификат</a>
|
||||
<a href="#sec-backup" data-nav="sec-backup"><i data-lucide="database"></i> Бэкапы</a>
|
||||
<a href="#sec-trash" data-nav="sec-trash"><i data-lucide="trash-2"></i> Корзина</a>
|
||||
@@ -413,6 +414,19 @@
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="settings-card" id="sec-quiz-ai">
|
||||
<div class="card-head">
|
||||
<div class="ic"><i data-lucide="clipboard-list"></i></div>
|
||||
<h3>Генерация тестов ИИ</h3>
|
||||
</div>
|
||||
<p class="hint">Кнопка «Сгенерировать ИИ» на странице «Тесты и опросы»: пользователь описывает тему, модель собирает вопросы и открывает конструктор с черновиком. Каждый пользователь выбирает свою модель — нативную, системную или добавленную в профиле.</p>
|
||||
<label class="toggle">
|
||||
<input type="checkbox" id="quizAiEnabled">
|
||||
<span class="toggle-track"><span class="toggle-thumb"></span></span>
|
||||
<span class="toggle-text"><b>Разрешить генерацию тестов ИИ</b><small>Выключение скрывает кнопку и блокирует эндпоинт</small></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="card-head">
|
||||
<div class="ic"><i data-lucide="boxes"></i></div>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
|
||||
const { extractJson, normalizeDraft, quizAiUserPrompt, quizAiMaxTokens } = require('./lib/quiz-ai');
|
||||
|
||||
let failed = 0;
|
||||
function ok(label, cond, extra) {
|
||||
console.log(`${cond ? 'PASS' : 'FAIL'} ${label}${extra !== undefined && !cond ? ' -> ' + JSON.stringify(extra) : ''}`);
|
||||
if (!cond) failed++;
|
||||
}
|
||||
|
||||
function status(fn) {
|
||||
try {
|
||||
fn();
|
||||
return 0;
|
||||
} catch (e) {
|
||||
return e && e.status ? e.status : -1;
|
||||
}
|
||||
}
|
||||
|
||||
const fenced = extractJson('```json\n{"title":"T","questions":[{"text":"Q","kind":"single","options":[{"text":"A","is_correct":true},{"text":"B"}]}]}\n```');
|
||||
ok('extractJson: снимает markdown-обёртку', fenced.title === 'T' && fenced.questions.length === 1);
|
||||
|
||||
const chatty = extractJson('Вот тест: {"questions":[]} — готово');
|
||||
ok('extractJson: вырезает JSON из текста', Array.isArray(chatty.questions));
|
||||
|
||||
const arrayDraft = normalizeDraft([{ text: 'Q1', kind: 'single', options: ['1) A', 'B'] }], { kind: 'test', count: 5, fallbackTitle: 'Черновик' });
|
||||
ok('normalizeDraft: голый массив вопросов', arrayDraft.questions.length === 1 && arrayDraft.title === 'Черновик');
|
||||
ok('normalizeDraft: строковые варианты превращаются в объекты', arrayDraft.questions[0].options[0].text === 'A');
|
||||
ok('normalizeDraft: снимает нумерацию из текста', arrayDraft.questions[0].text === 'Q1');
|
||||
|
||||
const single = normalizeDraft({
|
||||
title: 'Фотошоп',
|
||||
questions: [{ text: 'Что такое слой?', kind: 'single_choice', options: ['Слой', 'Маска', 'Фильтр'] }],
|
||||
}, { kind: 'test', count: 10, fallbackTitle: 'X' });
|
||||
ok('normalizeDraft: алиас типа вопроса', single.questions[0].kind === 'single');
|
||||
ok('normalizeDraft: один верный вариант назначается сам',
|
||||
single.questions[0].options.filter(o => o.is_correct).length === 1);
|
||||
|
||||
const multi = normalizeDraft({
|
||||
questions: [{ text: 'Выберите форматы', kind: 'multiple', options: [{ text: 'PSD' }, { text: 'PNG' }, { text: 'DOC' }] }],
|
||||
}, { kind: 'test', count: 10, fallbackTitle: 'X' });
|
||||
ok('normalizeDraft: multiple получает минимум один верный',
|
||||
multi.questions[0].options.filter(o => o.is_correct).length >= 1);
|
||||
|
||||
const survey = normalizeDraft({
|
||||
questions: [{ text: 'Как вам занятие?', kind: 'single', options: [{ text: 'Хорошо', is_correct: true }, { text: 'Плохо', is_correct: true }] }],
|
||||
}, { kind: 'survey', count: 10, fallbackTitle: 'X' });
|
||||
ok('normalizeDraft: у опроса нет правильных ответов',
|
||||
survey.questions[0].options.every(o => o.is_correct === false));
|
||||
|
||||
const free = normalizeDraft({
|
||||
questions: [{ text: 'Назовите формат', kind: 'line', accepted_answers: ['PSD', 'psd', ' TIFF '] }],
|
||||
}, { kind: 'test', count: 10, fallbackTitle: 'X' });
|
||||
ok('normalizeDraft: свободный ответ получает accepted_answers', free.questions[0].accepted_answers.length === 2, free.questions[0]);
|
||||
|
||||
const noisy = normalizeDraft({
|
||||
questions: [
|
||||
{ kind: 'single', options: ['A', 'B'] },
|
||||
{ text: 'Пропуск', kind: 'single', options: ['A'] },
|
||||
{ text: 'Один вариант', kind: 'single', options: ['A', 'A'] },
|
||||
{ text: 'Нормальный', kind: 'single', options: ['A', 'B'] },
|
||||
],
|
||||
}, { kind: 'test', count: 10, fallbackTitle: 'X' });
|
||||
ok('normalizeDraft: битые вопросы отбрасываются', noisy.questions.length === 1 && noisy.questions[0].text === 'Нормальный', noisy.questions);
|
||||
|
||||
const capped = normalizeDraft({
|
||||
questions: Array.from({ length: 50 }, (_, i) => ({ text: 'Q' + i, kind: 'single', options: ['A', 'B'] })),
|
||||
}, { kind: 'test', count: 3, fallbackTitle: 'X' });
|
||||
ok('normalizeDraft: соблюдает запрошенное число вопросов', capped.questions.length === 3);
|
||||
|
||||
const nested = normalizeDraft({
|
||||
quiz: { title: 'Вложенный', questions: [{ text: 'Q', kind: 'single', options: [{ text: 'A', is_correct: 'true' }, { text: 'B' }] }] },
|
||||
}, { kind: 'test', count: 5, fallbackTitle: 'X' });
|
||||
ok('normalizeDraft: разворачивает объект quiz', nested.title === 'Вложенный' && nested.questions.length === 1, nested);
|
||||
ok('normalizeDraft: строка "true" считается верным ответом', nested.questions[0].options[0].is_correct === true);
|
||||
|
||||
const truncated = '{"title":"Обрезанный","questions":[' +
|
||||
'{"text":"Q1","kind":"single","options":[{"text":"A","is_correct":true},{"text":"B"}]},' +
|
||||
'{"text":"Q2","kind":"single","options":[{"text":"A","is_correct":true},{"text":"B"}]},' +
|
||||
'{"text":"Q3","kind":"sin';
|
||||
const salvaged = extractJson(truncated);
|
||||
ok('extractJson: спасает полные вопросы из обрезанного ответа',
|
||||
salvaged.title === 'Обрезанный' && salvaged.questions.length === 2, salvaged.questions);
|
||||
|
||||
ok('normalizeDraft: битый JSON — 502', status(() => extractJson('не json вовсе')) === 502);
|
||||
ok('normalizeDraft: пустой ответ — 502', status(() => extractJson('')) === 502);
|
||||
ok('normalizeDraft: нет вопросов — 502',
|
||||
status(() => normalizeDraft({ title: 'X', questions: [] }, { kind: 'test', count: 5, fallbackTitle: 'Y' })) === 502);
|
||||
ok('normalizeDraft: не объект — 502',
|
||||
status(() => normalizeDraft('строка', { kind: 'test', count: 5, fallbackTitle: 'Y' })) === 502);
|
||||
|
||||
ok('quizAiUserPrompt: тест просит правильные ответы',
|
||||
quizAiUserPrompt({ prompt: 'Тема', kind: 'test', count: 5, difficulty: 'hard' }).includes('правильные ответы'));
|
||||
ok('quizAiUserPrompt: опрос не просит is_correct',
|
||||
quizAiUserPrompt({ prompt: 'Тема', kind: 'survey', count: 5, difficulty: 'easy' }).includes('не указывай is_correct'));
|
||||
ok('quizAiMaxTokens: растёт с числом вопросов', quizAiMaxTokens(20) > quizAiMaxTokens(5));
|
||||
|
||||
if (failed) {
|
||||
console.error(`\n${failed} проверок не прошло`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('\nВсе проверки ИИ-генерации тестов прошли');
|
||||
@@ -6,7 +6,7 @@ const { ipKeyGenerator } = require('express-rate-limit');
|
||||
const helmet = require('helmet');
|
||||
const bcrypt = require('bcrypt');
|
||||
const heicConvert = require('heic-convert');
|
||||
const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker, createDigestPublisher, createFarewellWorker } = require('./worker');
|
||||
const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker, createQuizAiWorker, createDigestPublisher, createFarewellWorker } = require('./worker');
|
||||
const { createZipWriter, renderStudentReport } = require('./student-report');
|
||||
|
||||
const { createStorage, mimeFor } = require('./storage');
|
||||
@@ -69,6 +69,13 @@ const { groupOwnedBy } = require('./lib/groups');
|
||||
const { ensureProjectFileSizeColumn, backfillProjectFileSizes } = require('./lib/file-sizes');
|
||||
const { resolveImgbbEndpoint, friendlyApiError } = require('./lib/feedback-imgbb');
|
||||
const { ensureFarewellTable, createFarewell, listFarewells, listFarewellTemplates, findFarewell, setFarewellStatus, updateFarewellText, setFarewellSent, farewellForUser, deleteFarewell, restoreFarewell, deleteFarewellPermanent, FAREWELL_AI_DEFAULT_PROMPT } = require('./lib/farewell');
|
||||
const {
|
||||
listGradeScales,
|
||||
createGradeScale,
|
||||
updateGradeScale,
|
||||
deleteGradeScale,
|
||||
listGradeImages,
|
||||
} = require('./lib/quiz-grades');
|
||||
const {
|
||||
QUIZ_MEDIA_EXT,
|
||||
mediaKind: quizMediaKind,
|
||||
@@ -88,15 +95,23 @@ const {
|
||||
startAttempt: startQuizAttempt,
|
||||
restartAttempt: restartQuizAttempt,
|
||||
submitAttempt: submitQuizAttempt,
|
||||
getPublicSurvey,
|
||||
startAnonymousAttempt,
|
||||
submitAnonymousAttempt,
|
||||
getPublicQuiz,
|
||||
startPublicAttempt,
|
||||
submitPublicAttempt,
|
||||
listAttempts: listQuizAttempts,
|
||||
getAttempt: getQuizAttempt,
|
||||
quizStats,
|
||||
purgeQuizzes,
|
||||
cleanupQuizAssets,
|
||||
} = require('./lib/quizzes');
|
||||
const { generateQuizDraft, normalizeQuizAiRequest } = require('./lib/quiz-ai');
|
||||
const {
|
||||
ensureQuizAiJobsTable,
|
||||
createQuizAiJob,
|
||||
findActiveQuizAiJob,
|
||||
getQuizAiJob,
|
||||
listQuizAiJobs,
|
||||
} = require('./lib/quiz-ai-jobs');
|
||||
const { aiHttpErrorFromResponse, aiHttpErrorText, aiHttpErrorDetail } = require('./lib/ai-errors');
|
||||
const { findBrokenFaceRefs, scanAllBrokenFaceRefs, cleanupAllBrokenFaceRefs, deleteFaceRef } = require('./lib/photo-cleanup');
|
||||
const {
|
||||
@@ -278,6 +293,7 @@ const FEEDBACK_WAKE_CHANNEL = 'whatido:wake:feedback';
|
||||
const NOTE_AI_WAKE_CHANNEL = 'whatido:wake:note-ai';
|
||||
const FAREWELL_WAKE_CHANNEL = 'whatido:wake:farewell';
|
||||
const FACE_SCAN_WAKE_CHANNEL = 'whatido:wake:face-scan';
|
||||
const QUIZ_AI_WAKE_CHANNEL = 'whatido:wake:quiz-ai';
|
||||
|
||||
function createWorkerBus(channel) {
|
||||
return {
|
||||
@@ -292,9 +308,11 @@ function createWorkerBus(channel) {
|
||||
|
||||
const sseClients = new Set();
|
||||
|
||||
function writeFrame(event, data) {
|
||||
function writeFrame(event, data, onlyUserId) {
|
||||
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
||||
const uid = onlyUserId == null ? null : Number(onlyUserId);
|
||||
for (const client of sseClients) {
|
||||
if (uid != null && Number(client._sseUserId) !== uid) continue;
|
||||
try { client.write(frame); } catch (e) { sseClients.delete(client); }
|
||||
}
|
||||
}
|
||||
@@ -333,6 +351,13 @@ function dispatchEvent(payload) {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (payload && payload.type === 'quiz_ai_status') {
|
||||
writeFrame('quiz_ai_status', {
|
||||
job: payload.job,
|
||||
ts: Date.now(),
|
||||
}, payload.job && payload.job.user_id);
|
||||
return;
|
||||
}
|
||||
if (payload && (payload.type === 'entries_changed' || payload.type === 'lessons_changed' || payload.type === 'shorts_changed' || payload.type === 'notes_changed' || payload.type === 'quizzes_changed')) {
|
||||
writeFrame(payload.type, { ts: Date.now() });
|
||||
return;
|
||||
@@ -377,6 +402,11 @@ function broadcastQuizzesChanged() {
|
||||
.catch(err => console.error('Publish failed:', err.message));
|
||||
}
|
||||
|
||||
function broadcastQuizAiStatus(job) {
|
||||
cache.publish(EVENTS_CHANNEL, { type: 'quiz_ai_status', job })
|
||||
.catch(err => console.error('Publish failed:', err.message));
|
||||
}
|
||||
|
||||
function broadcastAiStatus(payload) {
|
||||
cache.publish(EVENTS_CHANNEL, { type: 'ai_status', ...payload })
|
||||
.catch(err => console.error('Publish failed:', err.message));
|
||||
@@ -389,9 +419,10 @@ cache.on(EVENTS_CHANNEL, message => {
|
||||
});
|
||||
|
||||
app.get('/api/events', async (req, res) => {
|
||||
let user = null;
|
||||
try {
|
||||
const token = req.headers['x-auth-token'] || req.query.token;
|
||||
const user = await loadUserByToken(token);
|
||||
user = await loadUserByToken(token);
|
||||
if (!user || !user.is_active) return res.status(401).end();
|
||||
} catch (e) {
|
||||
return res.status(500).end();
|
||||
@@ -403,6 +434,7 @@ app.get('/api/events', async (req, res) => {
|
||||
'X-Accel-Buffering': 'no'
|
||||
});
|
||||
res.write(':ok\n\n');
|
||||
res._sseUserId = user.id;
|
||||
sseClients.add(res);
|
||||
const ping = setInterval(() => {
|
||||
try { res.write(':ping\n\n'); } catch (e) { clearInterval(ping); sseClients.delete(res); }
|
||||
@@ -1885,7 +1917,7 @@ async function removeEntryFiles(entryId) {
|
||||
async function sweepOrphanedUploads() {
|
||||
const dir = UPLOADS_DIR;
|
||||
try { fs.mkdirSync(dir, { recursive: true }); } catch {}
|
||||
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: userAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }, { rows: docFiles }, { rows: digestImages }, { rows: digestPreviews }, { rows: quizAssets }, { rows: quizCovers }] = await Promise.all([
|
||||
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: userAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }, { rows: docFiles }, { rows: digestImages }, { rows: digestPreviews }, { rows: quizAssets }, { rows: quizCovers }, { rows: gradeImages }] = await Promise.all([
|
||||
pool.query('SELECT photo_path AS p FROM entries WHERE photo_path IS NOT NULL'),
|
||||
pool.query('SELECT path AS p FROM project_files'),
|
||||
pool.query('SELECT photo_path AS p FROM group_photos'),
|
||||
@@ -1909,9 +1941,10 @@ async function sweepOrphanedUploads() {
|
||||
pool.query('SELECT preview_path AS p FROM digests WHERE preview_path IS NOT NULL'),
|
||||
pool.query('SELECT path AS p FROM quiz_assets'),
|
||||
pool.query('SELECT cover_path AS p FROM quizzes WHERE cover_path IS NOT NULL'),
|
||||
pool.query('SELECT image_path AS p FROM quiz_grade_ranges WHERE image_path IS NOT NULL'),
|
||||
]);
|
||||
const refs = new Set();
|
||||
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...userAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos, ...docFiles, ...digestImages, ...digestPreviews, ...quizAssets, ...quizCovers].forEach(r => {
|
||||
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...userAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos, ...docFiles, ...digestImages, ...digestPreviews, ...quizAssets, ...quizCovers, ...gradeImages].forEach(r => {
|
||||
const key = storage.keyFromPath(r.p);
|
||||
if (key) refs.add(key);
|
||||
});
|
||||
@@ -1954,6 +1987,7 @@ const BROKEN_IMAGE_SOURCES = [
|
||||
{ key: 'digests.preview_path', table: 'digests', column: 'preview_path', idColumn: 'id', kind: 'column', label: 'Обложка дайджеста' },
|
||||
{ key: 'quiz_assets.path', table: 'quiz_assets', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл теста' },
|
||||
{ key: 'quizzes.cover_path', table: 'quizzes', column: 'cover_path', idColumn: 'id', kind: 'column', label: 'Обложка теста' },
|
||||
{ key: 'quiz_grade_ranges.image_path', table: 'quiz_grade_ranges', column: 'image_path', idColumn: 'id', kind: 'row', label: 'Картинка критерия оценки' },
|
||||
{ key: 'project_files.path', table: 'project_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл проекта' },
|
||||
{ key: 'chat_attachments.path', table: 'chat_attachments', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение чата' },
|
||||
{ key: 'photo_jobs.before_path', table: 'photo_jobs', column: 'before_path', idColumn: 'id', kind: 'column', label: 'Фото до обработки' },
|
||||
@@ -3021,6 +3055,7 @@ async function ensureUsersAndFirstAdmin() {
|
||||
await ensureCalendarEventsTable(pool);
|
||||
await ensureFarewellTable(pool);
|
||||
await ensureQuizTables(pool);
|
||||
await ensureQuizAiJobsTable(pool);
|
||||
await ensureFirstAdmin();
|
||||
}
|
||||
|
||||
@@ -6895,6 +6930,9 @@ app.put('/api/settings', requireAdmin, async (req, res) => {
|
||||
if (key === 'notes_ai_enabled' && !['true', 'false'].includes(String(value))) {
|
||||
return res.status(400).json({ error: 'notes_ai_enabled должен быть true или false' });
|
||||
}
|
||||
if (key === 'quiz_ai_enabled' && !['true', 'false'].includes(String(value))) {
|
||||
return res.status(400).json({ error: 'quiz_ai_enabled должен быть true или false' });
|
||||
}
|
||||
if (key === 'feedback_imgbb_url' && String(value).trim() !== '') {
|
||||
try {
|
||||
const u = new URL(String(value));
|
||||
@@ -7287,6 +7325,7 @@ let noteAiWorker = null;
|
||||
let faceScanWorker = null;
|
||||
let digestPublisher = null;
|
||||
let farewellWorker = null;
|
||||
let quizAiWorker = null;
|
||||
|
||||
function wakeFarewellWorker() {
|
||||
if (farewellWorker) farewellWorker.notify();
|
||||
@@ -7308,6 +7347,73 @@ function wakeNoteAiWorker() {
|
||||
if (noteAiWorker) noteAiWorker.notify();
|
||||
}
|
||||
|
||||
function wakeQuizAiWorker() {
|
||||
if (quizAiWorker) quizAiWorker.notify();
|
||||
}
|
||||
|
||||
async function runQuizAiJob(job) {
|
||||
if (String(await getSetting('quiz_ai_enabled', 'true')) === 'false') {
|
||||
throw new Error('ИИ-генерация тестов отключена в настройках');
|
||||
}
|
||||
return generateQuizDraft(pool, { id: job.user_id, role: 'tutor' }, {
|
||||
prompt: job.prompt,
|
||||
kind: job.kind,
|
||||
count: job.question_count,
|
||||
difficulty: job.difficulty,
|
||||
profile: job.profile,
|
||||
}, {
|
||||
complete: aiComplete,
|
||||
resolveProfile: resolveUserAiProfile,
|
||||
});
|
||||
}
|
||||
|
||||
async function onQuizAiDone({ row, result, status, error }) {
|
||||
try {
|
||||
if (status === 'done') {
|
||||
if (logAudit) {
|
||||
await logAudit(null, 'quiz.ai.generate', {
|
||||
id: result.quiz.id,
|
||||
job_id: row.id,
|
||||
kind: result.quiz.kind,
|
||||
title: result.quiz.title,
|
||||
questions: result.questions,
|
||||
model: result.model,
|
||||
prompt: String(row.prompt || '').slice(0, 500),
|
||||
});
|
||||
}
|
||||
broadcastQuizzesChanged();
|
||||
broadcastQuizAiStatus({
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
status: 'done',
|
||||
quiz_id: result.quiz.id,
|
||||
questions: result.questions,
|
||||
model: result.model,
|
||||
error: null,
|
||||
});
|
||||
} else {
|
||||
if (logAudit) {
|
||||
await logAudit(null, 'quiz.ai.error', {
|
||||
id: row.id,
|
||||
error: String(error || '').slice(0, 500),
|
||||
prompt: String(row.prompt || '').slice(0, 500),
|
||||
});
|
||||
}
|
||||
broadcastQuizAiStatus({
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
status: 'error',
|
||||
quiz_id: null,
|
||||
questions: null,
|
||||
model: null,
|
||||
error: error || null,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Quiz AI onDone error:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function onNoteAiDone({ row, status, title, error }) {
|
||||
try {
|
||||
broadcastNotesChanged();
|
||||
@@ -7445,7 +7551,7 @@ async function probeAiModel(model) {
|
||||
}
|
||||
}
|
||||
|
||||
async function aiComplete(systemPrompt, userText, maxTokensOverride, profileOverride) {
|
||||
async function aiComplete(systemPrompt, userText, maxTokensOverride, profileOverride, timeoutMs) {
|
||||
const profile = profileOverride || await getActiveAiProfile();
|
||||
let url = `${AI_URL.replace(/\/+$/, '')}/v1/chat/completions`;
|
||||
let model = AI_MODEL;
|
||||
@@ -7461,7 +7567,8 @@ async function aiComplete(systemPrompt, userText, maxTokensOverride, profileOver
|
||||
}
|
||||
if (maxTokensOverride) maxTokens = Math.max(maxTokens, maxTokensOverride);
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), AI_CALL_TIMEOUT_MS);
|
||||
const limitMs = Math.max(5000, Number(timeoutMs) || AI_CALL_TIMEOUT_MS);
|
||||
const timer = setTimeout(() => controller.abort(), limitMs);
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
@@ -7617,7 +7724,7 @@ function backupUploadGuard(req, res, next) {
|
||||
async function buildBackupArchive() {
|
||||
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
||||
try {
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, si, atr, sar, dg, dgi, fm, ce, cal, qz, qq, qo, qa, qat, qaa] = await Promise.all([
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, si, atr, sar, dg, dgi, fm, ce, cal, qgs, qgr, qz, qq, qo, qa, qat, qaa] = await Promise.all([
|
||||
pool.query('SELECT * FROM groups ORDER BY id'),
|
||||
pool.query('SELECT * FROM students ORDER BY id'),
|
||||
pool.query('SELECT * FROM entries ORDER BY id'),
|
||||
@@ -7661,6 +7768,8 @@ async function buildBackupArchive() {
|
||||
pool.query('SELECT * FROM farewell_messages ORDER BY id'),
|
||||
pool.query('SELECT * FROM calendar_events ORDER BY id'),
|
||||
pool.query('SELECT * FROM calendar_action_log ORDER BY id'),
|
||||
pool.query('SELECT * FROM quiz_grade_scales ORDER BY id'),
|
||||
pool.query('SELECT * FROM quiz_grade_ranges ORDER BY id'),
|
||||
pool.query('SELECT * FROM quizzes ORDER BY id'),
|
||||
pool.query('SELECT * FROM quiz_questions ORDER BY id'),
|
||||
pool.query('SELECT * FROM quiz_options ORDER BY id'),
|
||||
@@ -7691,6 +7800,7 @@ async function buildBackupArchive() {
|
||||
digests: dg.rowCount, digest_images: dgi.rowCount, farewell_messages: fm.rowCount,
|
||||
calendar_events: ce.rowCount,
|
||||
calendar_action_log: cal.rowCount,
|
||||
quiz_grade_scales: qgs.rowCount, quiz_grade_ranges: qgr.rowCount,
|
||||
quizzes: qz.rowCount, quiz_questions: qq.rowCount, quiz_options: qo.rowCount,
|
||||
quiz_assets: qa.rowCount, quiz_attempts: qat.rowCount, quiz_attempt_answers: qaa.rowCount,
|
||||
},
|
||||
@@ -7701,6 +7811,7 @@ async function buildBackupArchive() {
|
||||
digests: dg.rows, digest_images: dgi.rows, farewell_messages: fm.rows,
|
||||
calendar_events: ce.rows,
|
||||
calendar_action_log: cal.rows,
|
||||
quiz_grade_scales: qgs.rows, quiz_grade_ranges: qgr.rows,
|
||||
quizzes: qz.rows, quiz_questions: qq.rows, quiz_options: qo.rows,
|
||||
quiz_assets: qa.rows, quiz_attempts: qat.rows, quiz_attempt_answers: qaa.rows,
|
||||
};
|
||||
@@ -7994,6 +8105,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
await client.query('DELETE FROM quiz_options');
|
||||
await client.query('DELETE FROM quiz_questions');
|
||||
await client.query('DELETE FROM quizzes');
|
||||
await client.query('DELETE FROM quiz_grade_ranges');
|
||||
await client.query('DELETE FROM quiz_grade_scales');
|
||||
await client.query('DELETE FROM users');
|
||||
await client.query('DELETE FROM branches');
|
||||
for (const x of ndata.branches) {
|
||||
@@ -8101,14 +8214,29 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
[x.id, x.digest_id, x.path, x.name || '', x.size || 0, x.created_at || null]
|
||||
);
|
||||
}
|
||||
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]
|
||||
);
|
||||
}
|
||||
const restoredScaleIds = new Set((ndata.quiz_grade_scales || []).map(x => x.id));
|
||||
for (const x of (ndata.quiz_grade_ranges || [])) {
|
||||
if (!restoredScaleIds.has(x.scale_id)) continue;
|
||||
await client.query(
|
||||
'INSERT INTO quiz_grade_ranges (id, scale_id, min_score, max_score, label, image_path, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)',
|
||||
[x.id, x.scale_id, x.min_score, x.max_score, x.label, x.image_path, x.created_at || null, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
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) 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)',
|
||||
'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))',
|
||||
[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.deleted_at || null, x.purge_at || null,
|
||||
x.show_answers !== false, x.grade_scale_id]
|
||||
);
|
||||
}
|
||||
const restoredQuizIds = new Set((ndata.quizzes || []).map(x => x.id));
|
||||
@@ -8151,9 +8279,9 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
for (const x of (ndata.quiz_attempts || [])) {
|
||||
if (!restoredQuizIds.has(x.quiz_id)) continue;
|
||||
const ins = await client.query(
|
||||
'INSERT INTO quiz_attempts (id, quiz_id, user_id, status, score, max_score, percent, passed, started_at, finished_at) VALUES ($1,$2,(SELECT id FROM users WHERE id = $3),$4,$5,$6,$7,$8,$9,$10) RETURNING id',
|
||||
'INSERT INTO quiz_attempts (id, quiz_id, user_id, status, score, max_score, percent, passed, guest_name, started_at, finished_at) VALUES ($1,$2,(SELECT id FROM users WHERE id = $3),$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id',
|
||||
[x.id, x.quiz_id, x.user_id, x.status, x.score, x.max_score, x.percent, x.passed,
|
||||
x.started_at || null, x.finished_at || null]
|
||||
x.guest_name || null, x.started_at || null, x.finished_at || null]
|
||||
);
|
||||
if (ins.rowCount) restoredAttemptIds.add(x.id);
|
||||
}
|
||||
@@ -15360,6 +15488,74 @@ 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) });
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось загрузить критерии оценки', 'grade scales list');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/grade-scales/images', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
res.json({ items: await listGradeImages(pool) });
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось загрузить картинки', 'grade scale images');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/grade-scales/upload', requireAdmin, (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 });
|
||||
if (err.message === 'Only images') return res.status(400).json({ error: 'Допустимы только изображения' });
|
||||
if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла' });
|
||||
return res.status(400).json({ error: 'Недопустимый файл' });
|
||||
}
|
||||
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
||||
try {
|
||||
await convertPhoto(req.file);
|
||||
res.json({ path: `/uploads/${req.file.filename}` });
|
||||
} catch (e) {
|
||||
removeUpload(req.file);
|
||||
quizError(res, e, 'Не удалось загрузить картинку', 'grade scale image upload');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/grade-scales', requireAdmin, 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 });
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось создать критерий оценки', 'grade scale create');
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/grade-scales/:id', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const result = await updateGradeScale(pool, reqInt(req.params.id), 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);
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось сохранить критерий оценки', 'grade scale update');
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/grade-scales/:id', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const id = reqInt(req.params.id);
|
||||
const result = await deleteGradeScale(pool, id);
|
||||
unlinkMedia(result.removed);
|
||||
await logAudit(req, 'grade_scale.delete', { id });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось удалить критерий оценки', 'grade scale delete');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/quizzes', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const items = await listQuizzes(pool, req.user, {
|
||||
@@ -15370,7 +15566,7 @@ app.get('/api/quizzes', requireAuth, async (req, res) => {
|
||||
limit: req.query.limit,
|
||||
offset: req.query.offset,
|
||||
});
|
||||
res.json(items);
|
||||
res.json({ ...items, ai_enabled: String(await getSetting('quiz_ai_enabled', 'true')) !== 'false' });
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось загрузить тесты', 'quizzes list');
|
||||
}
|
||||
@@ -15387,6 +15583,61 @@ app.post('/api/quizzes', requireAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/quizzes/ai-generate', requireAuth, aiLimiter, async (req, res) => {
|
||||
try {
|
||||
if (String(await getSetting('quiz_ai_enabled', 'true')) === 'false') {
|
||||
return res.status(403).json({ error: 'ИИ-генерация тестов отключена в настройках' });
|
||||
}
|
||||
const request = normalizeQuizAiRequest(req.body || {});
|
||||
if (request.profile && request.profile !== 'native') {
|
||||
const profile = await resolveUserAiProfile(request.profile, req.user.id);
|
||||
if (!profile) return res.status(400).json({ error: 'Профиль ИИ не найден' });
|
||||
}
|
||||
const active = await findActiveQuizAiJob(pool, req.user.id);
|
||||
if (active) return res.status(409).json({ error: 'Генерация уже идёт', job: active });
|
||||
const job = await createQuizAiJob(pool, req.user, request);
|
||||
await logAudit(req, 'quiz.ai.enqueue', {
|
||||
id: job.id,
|
||||
kind: job.kind,
|
||||
count: job.count,
|
||||
prompt: String(request.prompt).slice(0, 500),
|
||||
});
|
||||
wakeQuizAiWorker();
|
||||
res.status(202).json({ job });
|
||||
} catch (e) {
|
||||
if (!e || !e.status || e.status >= 500) console.error('quiz ai enqueue:', e && e.message ? e.message : e);
|
||||
quizError(res, e, 'Не удалось запустить генерацию', 'quiz ai enqueue');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/quizzes/ai-jobs/active', requireAuth, async (req, res) => {
|
||||
try {
|
||||
res.json({ job: await findActiveQuizAiJob(pool, req.user.id) });
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось получить статус генерации', 'quiz ai active');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/quizzes/ai-jobs', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const limit = optInt(req.query.limit, 1, 100) ?? 20;
|
||||
const offset = optInt(req.query.offset, 0) ?? 0;
|
||||
res.json(await listQuizAiJobs(pool, req.user, { limit, offset }));
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось получить историю генерации', 'quiz ai history');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/quizzes/ai-jobs/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const job = await getQuizAiJob(pool, reqInt(req.params.id), req.user);
|
||||
if (!job) return res.status(404).json({ error: 'Задание не найдено' });
|
||||
res.json({ job });
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось получить статус генерации', 'quiz ai job');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/quizzes/assets', requireAuth, (req, res) => {
|
||||
quizMediaUpload.single('file')(req, res, async err => {
|
||||
if (err) {
|
||||
@@ -15595,15 +15846,15 @@ app.get('/api/quizzes/:id/stats', requireAuth, async (req, res) => {
|
||||
|
||||
app.get('/api/public-quizzes/:id', apiLimiter, async (req, res) => {
|
||||
try {
|
||||
res.json(await getPublicSurvey(pool, reqInt(req.params.id)));
|
||||
res.json(await getPublicQuiz(pool, reqInt(req.params.id)));
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Опрос не найден', 'public quiz get');
|
||||
quizError(res, e, 'Тест не найден', 'public quiz get');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/public-quizzes/:id/attempts', apiLimiter, async (req, res) => {
|
||||
try {
|
||||
res.json(await startAnonymousAttempt(pool, reqInt(req.params.id)));
|
||||
res.json(await startPublicAttempt(pool, reqInt(req.params.id), { name: req.body?.name }));
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось начать прохождение', 'public quiz attempt start');
|
||||
}
|
||||
@@ -15612,14 +15863,19 @@ app.post('/api/public-quizzes/:id/attempts', apiLimiter, async (req, res) => {
|
||||
app.put('/api/public-quizzes/:id/attempts/:attemptId', apiLimiter, async (req, res) => {
|
||||
try {
|
||||
const token = typeof req.body?.token === 'string' ? req.body.token : '';
|
||||
const result = await submitAnonymousAttempt(
|
||||
const result = await submitPublicAttempt(
|
||||
pool,
|
||||
reqInt(req.params.id),
|
||||
reqInt(req.params.attemptId),
|
||||
token,
|
||||
req.body || {}
|
||||
);
|
||||
res.json({ attempt: result.attempt, anonymous: true });
|
||||
res.json({
|
||||
attempt: result.attempt,
|
||||
result: result.result,
|
||||
revealed: result.revealed,
|
||||
anonymous: !result.attempt.guest_name,
|
||||
});
|
||||
} catch (e) {
|
||||
quizError(res, e, 'Не удалось отправить ответы', 'public quiz attempt submit');
|
||||
}
|
||||
@@ -15637,7 +15893,7 @@ app.get('/api/public-quizzes/files/:name', fileLimiter, async (req, res) => {
|
||||
LEFT JOIN quiz_questions oq ON oq.id = qo.question_id
|
||||
JOIN quizzes q ON q.id = COALESCE(a.quiz_id, qq.quiz_id, oq.quiz_id)
|
||||
WHERE a.path = $1
|
||||
AND q.kind = 'survey' AND q.allow_anonymous = true
|
||||
AND q.allow_anonymous = true
|
||||
AND q.is_published = true AND q.deleted_at IS NULL
|
||||
LIMIT 1`,
|
||||
[`/uploads/${name}`]
|
||||
@@ -16478,6 +16734,14 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab
|
||||
});
|
||||
noteAiWorker.start();
|
||||
console.log('Note title AI worker started');
|
||||
quizAiWorker = createQuizAiWorker({
|
||||
pool,
|
||||
generate: runQuizAiJob,
|
||||
onDone: onQuizAiDone,
|
||||
bus: createWorkerBus(QUIZ_AI_WAKE_CHANNEL),
|
||||
});
|
||||
quizAiWorker.start();
|
||||
console.log('Quiz AI worker started');
|
||||
faceScanWorker = createFaceScanWorker({
|
||||
pool,
|
||||
getSetting,
|
||||
|
||||
@@ -2375,6 +2375,170 @@ function createFaceScanWorker({ pool, getSetting, logAudit, bus, scan, onDone })
|
||||
return { start, stop, notify, getInfo };
|
||||
}
|
||||
|
||||
function createQuizAiWorker({ pool, generate, onDone, bus }) {
|
||||
let started = false;
|
||||
let stopped = false;
|
||||
let idleMs = IDLE_MIN_MS;
|
||||
let wake = null;
|
||||
let processing = false;
|
||||
let currentId = null;
|
||||
let startedAt = null;
|
||||
let sincePrune = 0;
|
||||
const stats = { generated: 0, errors: 0, last_at: null, last_error: null };
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
const t = setTimeout(() => { wake = null; resolve(); }, ms);
|
||||
wake = () => { clearTimeout(t); wake = null; resolve(); };
|
||||
});
|
||||
}
|
||||
|
||||
function wakeLocal() {
|
||||
if (wake) wake();
|
||||
}
|
||||
|
||||
function notify() {
|
||||
wakeLocal();
|
||||
if (bus) bus.publish();
|
||||
}
|
||||
|
||||
if (bus) bus.subscribe(wakeLocal);
|
||||
|
||||
async function claimNext() {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const { rows } = await client.query(
|
||||
`SELECT id, user_id, prompt, kind, question_count, difficulty, profile
|
||||
FROM quiz_ai_jobs
|
||||
WHERE status = 'pending'
|
||||
ORDER BY id ASC LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED`
|
||||
);
|
||||
if (!rows.length) {
|
||||
await client.query('COMMIT');
|
||||
return null;
|
||||
}
|
||||
await client.query(
|
||||
`UPDATE quiz_ai_jobs SET status = 'processing', attempts = attempts + 1, updated_at = now() WHERE id = $1`,
|
||||
[rows[0].id]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return rows[0];
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function processOne(row) {
|
||||
try {
|
||||
const result = await generate(row);
|
||||
const saved = await pool.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'done', quiz_id = $2, questions = $3, model = $4, error = NULL,
|
||||
updated_at = now(), finished_at = now()
|
||||
WHERE id = $1 RETURNING *`,
|
||||
[row.id, result.quiz.id, result.questions, result.model]
|
||||
);
|
||||
stats.generated++;
|
||||
stats.last_at = new Date().toISOString();
|
||||
if (onDone && saved.rows.length) {
|
||||
await onDone({ row: saved.rows[0], result, status: 'done' })
|
||||
.catch(e => console.error('Quiz AI onDone error:', e.message));
|
||||
}
|
||||
} catch (e) {
|
||||
const message = String(e && e.message ? e.message : e).slice(0, 500);
|
||||
const saved = await pool.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'error', error = $2, updated_at = now(), finished_at = now()
|
||||
WHERE id = $1 RETURNING *`,
|
||||
[row.id, message]
|
||||
).catch(() => null);
|
||||
stats.errors++;
|
||||
stats.last_error = message;
|
||||
stats.last_at = new Date().toISOString();
|
||||
if (onDone) {
|
||||
await onDone({ row: saved && saved.rows.length ? saved.rows[0] : row, status: 'error', error: message })
|
||||
.catch(err => console.error('Quiz AI onDone error:', err.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loop() {
|
||||
while (!stopped) {
|
||||
let row = null;
|
||||
try {
|
||||
row = await claimNext();
|
||||
} catch (e) {
|
||||
console.error('Quiz AI claim error:', e.message);
|
||||
await sleep(IDLE_MAX_MS);
|
||||
continue;
|
||||
}
|
||||
if (!row) {
|
||||
await sleep(idleMs);
|
||||
idleMs = Math.min(idleMs * 2, IDLE_MAX_MS);
|
||||
continue;
|
||||
}
|
||||
idleMs = IDLE_MIN_MS;
|
||||
processing = true;
|
||||
currentId = row.id;
|
||||
try {
|
||||
await processOne(row);
|
||||
} catch (e) {
|
||||
console.error('Quiz AI process error:', e.message);
|
||||
} finally {
|
||||
processing = false;
|
||||
currentId = null;
|
||||
}
|
||||
sincePrune++;
|
||||
if (sincePrune >= 25) {
|
||||
sincePrune = 0;
|
||||
pool.query(`DELETE FROM quiz_ai_jobs WHERE status IN ('done', 'error') AND updated_at < now() - interval '7 days'`)
|
||||
.catch(e => console.error('Quiz AI prune error:', e.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resetStale() {
|
||||
return pool.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'error', error = 'Генерация прервана перезапуском сервера',
|
||||
updated_at = now(), finished_at = now()
|
||||
WHERE status = 'processing'`
|
||||
);
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (started) return;
|
||||
started = true;
|
||||
startedAt = Date.now();
|
||||
resetStale()
|
||||
.catch(e => console.error('Quiz AI reset error:', e.message))
|
||||
.finally(() => { loop().catch(e => console.error('Quiz AI loop error:', e.message)); });
|
||||
}
|
||||
|
||||
function stop() {
|
||||
stopped = true;
|
||||
notify();
|
||||
}
|
||||
|
||||
function getInfo() {
|
||||
return {
|
||||
started_at: startedAt ? new Date(startedAt).toISOString() : null,
|
||||
uptime_ms: startedAt ? Date.now() - startedAt : 0,
|
||||
processing,
|
||||
current_id: currentId,
|
||||
config: { idle_min_ms: IDLE_MIN_MS, idle_max_ms: IDLE_MAX_MS },
|
||||
...stats,
|
||||
};
|
||||
}
|
||||
|
||||
return { start, stop, notify, getInfo };
|
||||
}
|
||||
|
||||
const DIGEST_PUBLISH_INTERVAL_MS = Math.max(10000, parseInt(process.env.DIGEST_PUBLISH_INTERVAL_MS || '60000', 10) || 60000);
|
||||
|
||||
function createDigestPublisher({ pool, onDone }) {
|
||||
@@ -2412,4 +2576,4 @@ function createDigestPublisher({ pool, onDone }) {
|
||||
return { start, stop, notify };
|
||||
}
|
||||
|
||||
module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker, createDigestPublisher, createFarewellWorker, lessonTopicPosition };
|
||||
module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker, createQuizAiWorker, createDigestPublisher, createFarewellWorker, lessonTopicPosition };
|
||||
|
||||
Reference in New Issue
Block a user