feat: student achievements (admin-managed types + per-student records, UI & backup)

This commit is contained in:
dev
2026-10-27 13:02:56 +03:00
parent 2bc96aaecc
commit 12034812ec
12 changed files with 1067 additions and 6 deletions
+161 -1
View File
@@ -1,6 +1,6 @@
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays'];
const NOTIFY_IDS = [];
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-bans'];
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', '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-bans'];
const SPAM_MAX = 10080;
const BAN_REASONS = {
'honeypot': 'Антиспам-поле',
@@ -1479,6 +1479,165 @@ window.addEventListener('beforeunload', e => {
}
});
let seAchTypes = [];
function seAchRowHtml(t) {
return `<div class="se-ach-row${t.is_active ? '' : ' is-off'}" data-id="${t.id}">
<span class="se-ach-drag" draggable="true" title="Перетащите, чтобы изменить порядок">⠿</span>
<button type="button" class="se-ach-on${t.is_active ? ' on' : ''}" data-ach-on title="${t.is_active ? 'Скрыть из выбора при добавлении' : 'Вернуть в выбор'}">${t.is_active ? 'Вкл' : 'Выкл'}</button>
<span class="se-ach-name">${esc(t.name)}</span>
<button type="button" class="se-ach-btn" data-ach-edit title="Переименовать"><i data-lucide="pencil"></i></button>
<button type="button" class="se-ach-btn danger" data-ach-del title="Удалить"><i data-lucide="trash-2"></i></button>
</div>`;
}
function seAchRender() {
const list = document.getElementById('seAchList');
if (!list) return;
list.innerHTML = seAchTypes.length ? seAchTypes.map(seAchRowHtml).join('') : '<div class="se-ach-empty">Типов пока нет — добавьте первый выше</div>';
renderIcons();
}
function seAchApi(url, body, method) {
return fetch(url, {
method: method || (body ? 'POST' : 'GET'),
headers: body ? { ...hdr(), 'Content-Type': 'application/json' } : hdr(),
body: body ? JSON.stringify(body) : undefined,
}).then(res => res.json().then(data => {
if (!res.ok) throw new Error(data.error || 'Ошибка');
return data;
}));
}
async function seAchLoad() {
try {
const data = await seAchApi(`${API}/api/achievement-types`);
seAchTypes = Array.isArray(data.items) ? data.items : [];
} catch {
seAchTypes = [];
}
seAchRender();
}
async function seAchPersistOrder(ids) {
const oldIds = seAchTypes.map(t => t.id);
if (oldIds.join() === ids.join()) { seAchRender(); return; }
try {
await seAchApi(`${API}/api/achievement-types/reorder`, { ids }, 'PUT');
seAchTypes.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
seAchRender();
} catch (err) {
showToast(err.message || 'Не удалось сохранить порядок', true);
await seAchLoad();
}
}
async function initAchievementTypes() {
if (!document.getElementById('seAchList')) return;
const box = document.getElementById('seAchList');
let seAchDragged = null;
box.addEventListener('dragstart', e => {
const row = e.target.closest('.se-ach-row');
if (!row) return;
seAchDragged = row;
e.dataTransfer.effectAllowed = 'move';
try { e.dataTransfer.setData('text/plain', row.dataset.id); } catch {}
});
box.addEventListener('dragover', e => {
if (!seAchDragged) return;
e.preventDefault();
const row = e.target.closest('.se-ach-row');
if (!row || row === seAchDragged) return;
const rect = row.getBoundingClientRect();
box.insertBefore(seAchDragged, e.clientY < rect.top + rect.height / 2 ? row : row.nextSibling);
});
box.addEventListener('drop', e => e.preventDefault());
box.addEventListener('dragend', () => {
if (!seAchDragged) return;
const ids = [...box.querySelectorAll('.se-ach-row')].map(r => Number(r.dataset.id));
seAchDragged = null;
seAchPersistOrder(ids);
});
box.addEventListener('click', async e => {
const row = e.target.closest('.se-ach-row');
if (!row) return;
const cur = seAchTypes.find(t => String(t.id) === String(row.dataset.id));
if (!cur) return;
const editBtn = e.target.closest('[data-ach-edit]');
if (editBtn) {
const nameEl = row.querySelector('.se-ach-name');
const input = document.createElement('input');
input.className = 'se-ach-name-input';
input.value = cur.name;
input.maxLength = 150;
nameEl.replaceWith(input);
input.focus();
input.select();
let done = false;
const finish = save => {
if (done) return;
done = true;
const val = input.value.trim();
if (!save || !val || val === cur.name) { seAchRender(); return; }
seAchApi(`${API}/api/achievement-types/${cur.id}`, { name: val, is_active: cur.is_active }, 'PUT')
.then(data => { cur.name = data.item.name; cur.is_active = data.item.is_active; showToast('Тип переименован'); seAchRender(); })
.catch(err => { showToast(err.message || 'Не удалось переименовать', true); seAchRender(); });
};
input.addEventListener('keydown', ev => {
if (ev.key === 'Enter') { ev.preventDefault(); finish(true); }
if (ev.key === 'Escape') { ev.preventDefault(); finish(false); }
});
input.addEventListener('blur', () => finish(true));
return;
}
const on = e.target.closest('[data-ach-on]');
if (on) {
try {
const data = await seAchApi(`${API}/api/achievement-types/${cur.id}`, { name: cur.name, is_active: !cur.is_active }, 'PUT');
Object.assign(cur, data.item);
seAchRender();
showToast(cur.is_active ? 'Тип снова доступен' : 'Тип скрыт из выбора');
} catch (err) {
showToast(err.message || 'Не удалось изменить тип', true);
}
return;
}
const del = e.target.closest('[data-ach-del]');
if (del) {
if (!confirm(`Удалить тип «${cur.name}»? Уже внесённые достижения сохранят его название`)) return;
try {
await seAchApi(`${API}/api/achievement-types/${cur.id}`, null, 'DELETE');
seAchTypes = seAchTypes.filter(t => t.id !== cur.id);
seAchRender();
showToast('Тип удалён');
} catch (err) {
showToast(err.message || 'Не удалось удалить тип', true);
}
}
});
document.getElementById('seAchAddBtn').addEventListener('click', async () => {
const input = document.getElementById('seAchNewName');
const name = input.value.trim();
if (!name) { showToast('Введите название типа', true); return; }
try {
const data = await seAchApi(`${API}/api/achievement-types`, { name });
seAchTypes.unshift(data.item);
input.value = '';
seAchRender();
showToast('Тип добавлен');
} catch (err) {
showToast(err.message || 'Не удалось добавить тип', true);
}
});
document.getElementById('seAchNewName').addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.preventDefault();
document.getElementById('seAchAddBtn').click();
}
});
await seAchLoad();
}
(async () => {
if (await requireAdminPage()) {
buildSidebar(document.body.dataset.page);
@@ -1493,6 +1652,7 @@ window.addEventListener('beforeunload', e => {
} catch {
if (authStatus) { authStatus.classList.remove('loaded'); authStatus.classList.add('err'); authStatus.textContent = 'Ошибка загрузки настроек'; }
}
initAchievementTypes();
loadBans();
}
})();