feat(quizzes): публичные ссылки по токену и флаг no_shuffle
- quizzes.public_token (VARCHAR 32, уникальный индекс) вместо числового id в публичных роутах /api/public-quizzes/:token - бэкилл токенов для существующих строк в db/migration.sql + ensureQuizTables - quiz_questions.no_shuffle — вопрос исключён из перемешивания - POST /api/quizzes/:id/public-token/rotate — сброс утёкшей ссылки (автор/админ) - restore: no_shuffle в INSERT quiz_questions, backup.selftest обновлён - документация AGENTS.md + handoff
This commit is contained in:
+27
-3
@@ -124,6 +124,7 @@
|
||||
required: q.required !== false,
|
||||
min_length: Number(q.min_length) || 0,
|
||||
options_inline: q.options_inline === true,
|
||||
no_shuffle: q.no_shuffle === true,
|
||||
text_match: q.text_match === 'contains' ? 'contains' : 'exact',
|
||||
accepted_answers: Array.isArray(q.accepted_answers) ? q.accepted_answers.slice() : [],
|
||||
assets: Array.isArray(q.assets) ? q.assets.slice() : [],
|
||||
@@ -169,6 +170,7 @@
|
||||
required: qq.required,
|
||||
min_length: qq.min_length,
|
||||
options_inline: qq.options_inline,
|
||||
no_shuffle: qq.no_shuffle,
|
||||
text_match: qq.text_match,
|
||||
accepted_answers: qq.accepted_answers,
|
||||
asset_ids: qq.assets.map(a => a.id),
|
||||
@@ -298,6 +300,7 @@
|
||||
${isTest && q.kind === 'multiple' ? `<label class="toggle" style="padding:2px 6px"><input type="checkbox" data-qi="${qi}" data-field="partial_credit"${q.partial_credit ? ' checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Частичный зачёт</small></span></label>` : ''}
|
||||
${isOptionKind(q.kind) && q.kind !== 'select' ? `<label class="toggle" style="padding:2px 6px"><input type="checkbox" data-qi="${qi}" data-field="options_inline"${q.options_inline ? ' checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Ответы в строку</small></span></label>` : ''}
|
||||
<label class="toggle" style="padding:2px 6px"><input type="checkbox" data-qi="${qi}" data-field="required"${q.required ? ' checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Обязательный</small></span></label>
|
||||
<label class="toggle" style="padding:2px 6px" title="Вопрос останется в начале списка и не будет перемешиваться"><input type="checkbox" data-qi="${qi}" data-field="no_shuffle"${q.no_shuffle ? ' checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Не перемешивать</small></span></label>
|
||||
${q.required && (q.kind === 'line' || q.kind === 'text') ? `<label class="qe-min-len">Мин. длина <input type="number" class="settings-input" data-qi="${qi}" data-field="min_length" min="0" max="2000" value="${at(q.min_length || 0)}"></label>` : ''}
|
||||
</div>
|
||||
<div class="qe-assets" data-assets="${owner}">${assetsHtml(q.assets, owner)}</div>
|
||||
@@ -363,7 +366,7 @@
|
||||
? 'По ссылке можно пройти тест без входа в систему. Перед началом ученик может указать имя; если оставить пустым, результат будет анонимным.'
|
||||
: 'По ссылке можно пройти опрос без входа в систему. Ответы сохраняются без имени.';
|
||||
}
|
||||
const ready = state.quiz.allow_anonymous && state.quiz.is_published;
|
||||
const ready = state.quiz.allow_anonymous && state.quiz.is_published && !!state.quiz.public_token;
|
||||
const visible = ready && !dirty;
|
||||
link.hidden = !visible;
|
||||
let text = '';
|
||||
@@ -372,12 +375,28 @@
|
||||
hint.hidden = !text;
|
||||
hint.textContent = text;
|
||||
if (visible) {
|
||||
const url = location.origin + '/quiz-public.html?id=' + state.quiz.id;
|
||||
const url = location.origin + '/quiz-public.html?t=' + encodeURIComponent(state.quiz.public_token);
|
||||
document.getElementById('qeAnonUrl').value = url;
|
||||
document.getElementById('qeAnonOpen').href = url;
|
||||
}
|
||||
}
|
||||
|
||||
async function rotatePublicLink() {
|
||||
if (!confirm('Обновить ссылку? Старая ссылка перестанет работать.')) return;
|
||||
const res = await fetch(API + '/api/quizzes/' + state.quiz.id + '/public-token/rotate', {
|
||||
method: 'POST',
|
||||
headers: hdr(),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
showToast(data.error || 'Не удалось обновить ссылку', true);
|
||||
return;
|
||||
}
|
||||
state.quiz.public_token = data.public_token;
|
||||
renderAnon();
|
||||
showToast('Ссылка обновлена');
|
||||
}
|
||||
|
||||
function renderGradeSelect() {
|
||||
const sel = document.getElementById('qeGradeScale');
|
||||
if (!sel) return;
|
||||
@@ -660,7 +679,7 @@
|
||||
const q = state.questions[qi];
|
||||
if (field === 'weight') q.weight = el.value === '' ? 0 : Number(el.value);
|
||||
else if (field === 'min_length') q.min_length = el.value === '' ? 0 : Math.max(0, Math.min(2000, Math.round(Number(el.value) || 0)));
|
||||
else if (field === 'partial_credit' || field === 'required' || field === 'options_inline') {
|
||||
else if (field === 'partial_credit' || field === 'required' || field === 'options_inline' || field === 'no_shuffle') {
|
||||
q[field] = el.checked;
|
||||
if (field === 'required' && (q.kind === 'line' || q.kind === 'text')) {
|
||||
markDirty();
|
||||
@@ -798,6 +817,10 @@
|
||||
deleteCover();
|
||||
return;
|
||||
}
|
||||
if (act === 'rotate-anon') {
|
||||
rotatePublicLink();
|
||||
return;
|
||||
}
|
||||
if (act === 'copy-anon') {
|
||||
const input = document.getElementById('qeAnonUrl');
|
||||
input.select();
|
||||
@@ -887,6 +910,7 @@
|
||||
required: true,
|
||||
min_length: 0,
|
||||
options_inline: false,
|
||||
no_shuffle: false,
|
||||
text_match: 'exact',
|
||||
accepted_answers: [],
|
||||
assets: [],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
(function () {
|
||||
const API = location.origin;
|
||||
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
|
||||
const quizToken = (new URLSearchParams(location.search).get('t') || '').trim();
|
||||
const SYSTEM_KINDS = ['student', 'group', 'branch', 'module'];
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS];
|
||||
const SYSTEM_LABELS = { student: 'ученика', group: 'группы', branch: 'филиала', module: 'темы модуля' };
|
||||
@@ -17,7 +17,7 @@
|
||||
timer: null,
|
||||
done: false,
|
||||
};
|
||||
const RETRY_KEY = 'whatido_quiz_retry_' + (Number.isInteger(quizId) ? quizId : '');
|
||||
const RETRY_KEY = 'whatido_quiz_retry_' + quizToken;
|
||||
let retryTimer = null;
|
||||
|
||||
function esc2(v) {
|
||||
@@ -70,7 +70,11 @@
|
||||
function prepareQuestions(list) {
|
||||
const quiz = state.quiz || {};
|
||||
let items = Array.isArray(list) ? list.slice() : [];
|
||||
if (quiz.shuffle_questions) items = shuffleList(items);
|
||||
if (quiz.shuffle_questions) {
|
||||
const pinned = items.filter(q => q.no_shuffle);
|
||||
const rest = items.filter(q => !q.no_shuffle);
|
||||
items = pinned.concat(shuffleList(rest));
|
||||
}
|
||||
if (quiz.shuffle_options) {
|
||||
items = items.map(q => ({ ...q, options: shuffleList(q.options || []) }));
|
||||
}
|
||||
@@ -199,7 +203,7 @@
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const url = API + '/api/public-quizzes/' + quizId + '/options?field=' + encodeURIComponent(kind)
|
||||
const url = API + '/api/public-quizzes/' + encodeURIComponent(quizToken) + '/options?field=' + encodeURIComponent(kind)
|
||||
+ '&q=' + encodeURIComponent(text) + '&code=' + encodeURIComponent(state.code || '');
|
||||
const res = await fetch(url);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
@@ -348,7 +352,7 @@
|
||||
const codeInput = document.getElementById('qpAccessCode');
|
||||
const code = codeInput ? codeInput.value.trim() : '';
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts', {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + encodeURIComponent(quizToken) + '/attempts', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code }),
|
||||
@@ -451,7 +455,7 @@
|
||||
answer_id: isSystemKind(q.kind) ? (state.systemIds.get(q.id) || null) : null,
|
||||
}));
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts/' + state.attempt.id, {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + encodeURIComponent(quizToken) + '/attempts/' + state.attempt.id, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: state.attempt.anon_token, answers, time_up: auto === true }),
|
||||
@@ -550,13 +554,13 @@
|
||||
}
|
||||
|
||||
async function init() {
|
||||
if (!Number.isInteger(quizId) || quizId < 1) {
|
||||
if (!/^[a-f0-9]{32}$/i.test(quizToken)) {
|
||||
document.getElementById('qpBody').innerHTML = '<div class="qp-error">Неверная ссылка</div>';
|
||||
return;
|
||||
}
|
||||
bind();
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId);
|
||||
const res = await fetch(API + '/api/public-quizzes/' + encodeURIComponent(quizToken));
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Тест не найден');
|
||||
state.quiz = data.quiz;
|
||||
|
||||
+5
-1
@@ -825,7 +825,11 @@
|
||||
state.quiz.my_attempts = data.my_attempts || [];
|
||||
state.quizAssets = data.quiz_assets || [];
|
||||
state.questions = (data.questions || []).map(q => ({ ...q }));
|
||||
if (state.quiz.shuffle_questions && !prevAttempt) state.questions = shuffle(state.questions);
|
||||
if (state.quiz.shuffle_questions && !prevAttempt) {
|
||||
const pinned = state.questions.filter(q => q.no_shuffle);
|
||||
const rest = state.questions.filter(q => !q.no_shuffle);
|
||||
state.questions = pinned.concat(shuffle(rest));
|
||||
}
|
||||
if (state.quiz.shuffle_options) {
|
||||
state.questions = state.questions.map(q => ({ ...q, options: shuffle(q.options || []) }));
|
||||
}
|
||||
|
||||
@@ -70,7 +70,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 && q.allow_anonymous && q.is_published && q.public_token) actions.push(`<button type="button" class="btn-link" data-copy-link="${q.public_token}">Ссылку</button>`);
|
||||
if (q.stats_available) 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>`);
|
||||
}
|
||||
@@ -668,7 +668,7 @@
|
||||
const copyLink = e.target.closest('[data-copy-link]');
|
||||
if (copyLink) {
|
||||
e.preventDefault();
|
||||
const url = location.origin + '/quiz-public.html?id=' + copyLink.dataset.copyLink;
|
||||
const url = location.origin + '/quiz-public.html?t=' + encodeURIComponent(copyLink.dataset.copyLink);
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
navigator.clipboard.writeText(url).then(() => showToast('Ссылка скопирована'), () => showToast('Не удалось скопировать ссылку', true));
|
||||
} else {
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
.qe-asset-cap:focus { outline: 1px solid var(--accent); }
|
||||
.qe-accepted { margin-top: 8px; display: grid; gap: 6px; grid-template-columns: minmax(0,1fr) 150px; align-items: center; }
|
||||
.qe-accepted textarea { grid-column: 1 / -1; }
|
||||
.qe-anon-link { display: flex; gap: 6px; align-items: center; margin-top: 8px; }
|
||||
.qe-anon-link { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 8px; }
|
||||
.qe-anon-link input { flex: 1; min-width: 0; }
|
||||
.qe-anon-link .btn-link { white-space: nowrap; }
|
||||
.qe-min-len { display: inline-flex; align-items: center; gap: 6px; font-size: .78rem; font-weight: 600; color: var(--muted); }
|
||||
@@ -172,6 +172,7 @@
|
||||
<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>
|
||||
<button type="button" class="btn-link danger" data-act="rotate-anon">Обновить ссылку</button>
|
||||
<a class="btn-link" id="qeAnonOpen" target="_blank" rel="noopener noreferrer">Открыть</a>
|
||||
</div>
|
||||
<div class="qe-hint" id="qeAnonPublishHint" hidden>Опубликуйте, чтобы ссылка заработала.</div>
|
||||
|
||||
Reference in New Issue
Block a user