feat(admin/gam): переработана форма начисления XP/монет
- select с полным списком пользователей + фильтр по имени (вместо typeahead) - пресеты XP (0/10/25/50/100/250) и монет (0/10/25/50) с подсветкой активного - пресеты причин (кнопки) + поле для своей причины - fix: xp/coins теперь Number(value) без || 0 — значение 0 не начисляется - форма сброса прогресса — тоже select из того же кэша пользователей Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,42 +1,93 @@
|
||||
'use strict';
|
||||
/* admin → gam (gamification) section: stats + top + recent XP + purchases + award XP */
|
||||
/* admin → gam (gamification) section: stats + top + recent XP + purchases + award XP/coins */
|
||||
(function () {
|
||||
'use strict';
|
||||
let inited = false;
|
||||
let _gamSearchTimer = null;
|
||||
let _gamAwarding = false;
|
||||
let _allUsers = []; // кэш пользователей для <select>-ов
|
||||
|
||||
const XP_REASONS = {
|
||||
'daily_activity': ['sun', '#F59E0B', 'Ежедневная активность'],
|
||||
'correct_answers':['check-circle', '#10B981', 'Правильные ответы'],
|
||||
'test_complete': ['file-text', '#06B6D4', 'Тест завершён'],
|
||||
'test_90+': ['zap', '#9B5DE5', 'Тест на 90%+'],
|
||||
'test_perfect': ['trophy', '#F59E0B', 'Идеальный тест (100%)'],
|
||||
'lab_experiment': ['atom', '#06D6A0', 'Лабораторный эксперимент'],
|
||||
'daily_goal': ['target', '#EF476F', 'Ежедневная цель выполнена'],
|
||||
'Admin award': ['crown', '#9B5DE5', 'Начисление администратором'],
|
||||
'daily_activity': ['sun', '#F59E0B', 'Ежедневная активность'],
|
||||
'correct_answers': ['check-circle', '#10B981', 'Правильные ответы'],
|
||||
'test_complete': ['file-text', '#06B6D4', 'Тест завершён'],
|
||||
'test_90+': ['zap', '#9B5DE5', 'Тест на 90%+'],
|
||||
'test_perfect': ['trophy', '#F59E0B', 'Идеальный тест (100%)'],
|
||||
'lab_experiment': ['atom', '#06D6A0', 'Лабораторный эксперимент'],
|
||||
'daily_goal': ['target', '#EF476F', 'Ежедневная цель выполнена'],
|
||||
'Admin award': ['crown', '#9B5DE5', 'Начисление администратором'],
|
||||
};
|
||||
|
||||
const PRESET_REASONS = [
|
||||
'Admin award',
|
||||
'За участие в мероприятии',
|
||||
'За активность на уроке',
|
||||
'Бонус за отличную работу',
|
||||
'Поощрение за серию',
|
||||
'Компенсация (техническая)',
|
||||
];
|
||||
|
||||
function fmtXPReason(reason) {
|
||||
if (!reason) return '—';
|
||||
const entry = XP_REASONS[reason];
|
||||
if (entry) {
|
||||
const [icon, color, label] = entry;
|
||||
return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:${color};display:inline-flex">${lsIcon(icon,14)}</span>${label}</span>`;
|
||||
return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:${color};display:inline-flex">${lsIcon(icon, 14)}</span>${label}</span>`;
|
||||
}
|
||||
if (reason.startsWith('achievement:')) {
|
||||
return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:#F59E0B;display:inline-flex">${lsIcon('award',14)}</span>Достижение: ${esc(reason.slice(12))}</span>`;
|
||||
return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:#F59E0B;display:inline-flex">${lsIcon('award', 14)}</span>Достижение: ${esc(reason.slice(12))}</span>`;
|
||||
}
|
||||
if (reason.startsWith('Испытание:')) {
|
||||
return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:#EF476F;display:inline-flex">${lsIcon('swords',14)}</span>${esc(reason)}</span>`;
|
||||
return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:#EF476F;display:inline-flex">${lsIcon('swords', 14)}</span>${esc(reason)}</span>`;
|
||||
}
|
||||
return esc(reason);
|
||||
}
|
||||
|
||||
/* ── Загрузить всех пользователей для select-ов ─────────────────────── */
|
||||
async function loadAllUsers() {
|
||||
if (_allUsers.length) return _allUsers;
|
||||
try {
|
||||
const r = await LS.adminGetUsers({ limit: 500 });
|
||||
_allUsers = (r.users || []).sort((a, b) => (a.name || '').localeCompare(b.name || '', 'ru'));
|
||||
} catch (e) { _allUsers = []; }
|
||||
return _allUsers;
|
||||
}
|
||||
|
||||
function buildUserOptions(selected) {
|
||||
const blank = `<option value="">— Выберите пользователя —</option>`;
|
||||
return blank + _allUsers.map(u => {
|
||||
const label = (u.name || u.email || 'ID:' + u.id) + (u.role !== 'student' ? ' (' + u.role + ')' : '');
|
||||
const sel = selected && selected == u.id ? ' selected' : '';
|
||||
return `<option value="${u.id}"${sel}>${esc(label)}</option>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function populateSelects() {
|
||||
for (const id of ['gam-award-uid', 'gam-reset-uid']) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.innerHTML = buildUserOptions(el.value);
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Быстрый фильтр select-а по вводу ───────────────────────────────── */
|
||||
function filterUserSelect(q, selectId) {
|
||||
const el = document.getElementById(selectId);
|
||||
if (!el) return;
|
||||
const ql = q.toLowerCase();
|
||||
for (const opt of el.options) {
|
||||
if (!opt.value) continue;
|
||||
opt.style.display = !ql || opt.textContent.toLowerCase().includes(ql) ? '' : 'none';
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Статистика ──────────────────────────────────────────────────────── */
|
||||
async function load() {
|
||||
const { fmtDate } = AdminCtx;
|
||||
try {
|
||||
const stats = await LS.adminGamStats();
|
||||
const [stats] = await Promise.all([
|
||||
LS.adminGamStats(),
|
||||
loadAllUsers(),
|
||||
]);
|
||||
|
||||
document.getElementById('gam-stats-grid').innerHTML = `
|
||||
<div class="stat-card" style="--stat-top:var(--violet)">
|
||||
<div class="stat-card-icon" style="background:rgba(155,93,229,0.1)"><i data-lucide="zap" class="stat-icon"></i></div>
|
||||
@@ -66,116 +117,123 @@
|
||||
|
||||
// Top-10
|
||||
const topBody = document.getElementById('gam-top-body');
|
||||
if (stats.topByXP?.length) {
|
||||
topBody.innerHTML = stats.topByXP.slice(0, 10).map((u, i) => `<tr>
|
||||
<td><strong>${i + 1}</strong></td>
|
||||
<td>${esc(u.name || u.email || 'ID:' + (u.id || u.user_id))}</td>
|
||||
<td><span style="color:var(--violet);font-weight:700">${u.xp}</span></td>
|
||||
<td>${u.level}</td>
|
||||
<td>${u.coins} <i data-lucide="coins" style="width:12px;height:12px;vertical-align:-2px;color:var(--amber, #FFB347)"></i></td>
|
||||
</tr>`).join('');
|
||||
} else {
|
||||
topBody.innerHTML = '<tr><td colspan="5" class="empty">Нет данных</td></tr>';
|
||||
}
|
||||
topBody.innerHTML = stats.topByXP?.length
|
||||
? stats.topByXP.slice(0, 10).map((u, i) => `<tr>
|
||||
<td><strong>${i + 1}</strong></td>
|
||||
<td>${esc(u.name || u.email || 'ID:' + (u.id || u.user_id))}</td>
|
||||
<td><span style="color:var(--violet);font-weight:700">${u.xp}</span></td>
|
||||
<td>${u.level}</td>
|
||||
<td>${u.coins} <i data-lucide="coins" style="width:12px;height:12px;vertical-align:-2px;color:var(--amber, #FFB347)"></i></td>
|
||||
</tr>`).join('')
|
||||
: '<tr><td colspan="5" class="empty">Нет данных</td></tr>';
|
||||
|
||||
// Recent XP
|
||||
// Recent XP log
|
||||
const logBody = document.getElementById('gam-log-body');
|
||||
if (stats.recentXP?.length) {
|
||||
logBody.innerHTML = stats.recentXP.slice(0, 20).map(e => `<tr>
|
||||
<td style="font-size:0.78rem;color:var(--text-3)">${fmtDate(e.created_at || e.date)}</td>
|
||||
<td>${esc(e.name || e.user_name || '—')}</td>
|
||||
<td><span style="color:var(--violet);font-weight:700">+${e.amount}</span></td>
|
||||
<td style="font-size:0.82rem;color:var(--text-2)">${fmtXPReason(e.reason)}</td>
|
||||
</tr>`).join('');
|
||||
} else {
|
||||
logBody.innerHTML = '<tr><td colspan="4" class="empty">Нет данных</td></tr>';
|
||||
}
|
||||
logBody.innerHTML = stats.recentXP?.length
|
||||
? stats.recentXP.slice(0, 20).map(e => `<tr>
|
||||
<td style="font-size:0.78rem;color:var(--text-3)">${fmtDate(e.created_at || e.date)}</td>
|
||||
<td>${esc(e.name || e.user_name || '—')}</td>
|
||||
<td><span style="color:var(--violet);font-weight:700">+${e.amount}</span></td>
|
||||
<td style="font-size:0.82rem;color:var(--text-2)">${fmtXPReason(e.reason)}</td>
|
||||
</tr>`).join('')
|
||||
: '<tr><td colspan="4" class="empty">Нет данных</td></tr>';
|
||||
|
||||
// Purchases
|
||||
const purchBody = document.getElementById('gam-purchases-body');
|
||||
if (stats.recentPurchases?.length) {
|
||||
purchBody.innerHTML = stats.recentPurchases.slice(0, 20).map(p => `<tr>
|
||||
<td style="font-size:0.78rem;color:var(--text-3)">${fmtDate(p.purchased_at)}</td>
|
||||
<td>${esc(p.user_name || '—')}</td>
|
||||
<td style="font-weight:600">${esc(p.item_name || '—')}</td>
|
||||
<td><span class="badge" style="font-size:0.7rem">${esc(p.type || '—')}</span></td>
|
||||
<td style="color:var(--amber,#FFB347);font-weight:700">${p.price} <i data-lucide="coins" style="width:12px;height:12px;vertical-align:-2px"></i></td>
|
||||
</tr>`).join('');
|
||||
} else {
|
||||
purchBody.innerHTML = '<tr><td colspan="5" class="empty">Нет покупок</td></tr>';
|
||||
}
|
||||
purchBody.innerHTML = stats.recentPurchases?.length
|
||||
? stats.recentPurchases.slice(0, 20).map(p => `<tr>
|
||||
<td style="font-size:0.78rem;color:var(--text-3)">${fmtDate(p.purchased_at)}</td>
|
||||
<td>${esc(p.user_name || '—')}</td>
|
||||
<td style="font-weight:600">${esc(p.item_name || '—')}</td>
|
||||
<td><span class="badge" style="font-size:0.7rem">${esc(p.type || '—')}</span></td>
|
||||
<td style="color:var(--amber,#FFB347);font-weight:700">${p.price} <i data-lucide="coins" style="width:12px;height:12px;vertical-align:-2px"></i></td>
|
||||
</tr>`).join('')
|
||||
: '<tr><td colspan="5" class="empty">Нет покупок</td></tr>';
|
||||
|
||||
populateSelects();
|
||||
if (window.lucide) lucide.createIcons();
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
document.getElementById('gam-stats-grid').innerHTML = `<div class="error">Ошибка: ${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function gamSearchUser(q, prefix) {
|
||||
clearTimeout(_gamSearchTimer);
|
||||
const box = document.getElementById(prefix + '-results');
|
||||
if (q.length < 2) { box.classList.remove('open'); return; }
|
||||
_gamSearchTimer = setTimeout(async () => {
|
||||
try {
|
||||
const r = await LS.adminGetUsers({ q, limit: 8 });
|
||||
const label = u => u.name || u.email;
|
||||
box.innerHTML = (r.users || []).map(u => `<div class="us-item" data-uid="${u.id}" data-name="${esc(label(u))}" data-prefix="${esc(prefix)}" onclick="gamPickUser(this)">
|
||||
<span>${esc(label(u))}</span><span class="us-role">${esc(u.role)}</span>
|
||||
</div>`).join('') || '<div class="us-item" style="color:var(--text-3)">Не найдено</div>';
|
||||
box.classList.add('open');
|
||||
} catch(e) { box.classList.remove('open'); }
|
||||
}, 300);
|
||||
/* ── Пресеты XP ──────────────────────────────────────────────────────── */
|
||||
function gamSetXP(val) {
|
||||
const inp = document.getElementById('gam-award-xp');
|
||||
if (!inp) return;
|
||||
inp.value = val;
|
||||
inp.readOnly = false;
|
||||
document.querySelectorAll('.gam-xp-preset').forEach(b => b.classList.toggle('active', b.dataset.xp == val));
|
||||
}
|
||||
|
||||
function gamPickUser(el) {
|
||||
const prefix = el.dataset.prefix;
|
||||
document.getElementById(prefix + '-uid').value = el.dataset.uid;
|
||||
document.getElementById(prefix + '-user').value = el.dataset.name || '';
|
||||
document.getElementById(prefix + '-results').classList.remove('open');
|
||||
function gamSetCoins(val) {
|
||||
const inp = document.getElementById('gam-award-coins');
|
||||
if (!inp) return;
|
||||
inp.value = val;
|
||||
document.querySelectorAll('.gam-coins-preset').forEach(b => b.classList.toggle('active', b.dataset.coins == val));
|
||||
}
|
||||
|
||||
function gamSetReason(val) {
|
||||
const inp = document.getElementById('gam-award-reason');
|
||||
if (inp) inp.value = val;
|
||||
}
|
||||
|
||||
/* ── Начислить XP/Монеты ─────────────────────────────────────────────── */
|
||||
async function gamAdminAward() {
|
||||
if (_gamAwarding) return;
|
||||
const userId = parseInt(document.getElementById('gam-award-uid').value);
|
||||
const xp = parseInt(document.getElementById('gam-award-xp').value) || 0;
|
||||
const coins = parseInt(document.getElementById('gam-award-coins').value) || 0;
|
||||
const reason = document.getElementById('gam-award-reason').value.trim();
|
||||
if (!userId) { LS.toast('Выберите пользователя', 'error'); return; }
|
||||
if (!xp && !coins) { LS.toast('Введите XP или монеты', 'error'); return; }
|
||||
const userId = parseInt(document.getElementById('gam-award-uid').value, 10);
|
||||
const xpRaw = document.getElementById('gam-award-xp').value;
|
||||
const coinsRaw = document.getElementById('gam-award-coins').value;
|
||||
const xp = xpRaw === '' ? 0 : Number(xpRaw);
|
||||
const coins = coinsRaw === '' ? 0 : Number(coinsRaw);
|
||||
const reason = document.getElementById('gam-award-reason').value.trim() || 'Admin award';
|
||||
|
||||
if (!userId) { LS.toast('Выберите пользователя', 'error'); return; }
|
||||
if (xp < 0 || coins < 0) { LS.toast('Значения не могут быть отрицательными', 'error'); return; }
|
||||
if (!xp && !coins) { LS.toast('Введите XP или монеты (больше 0)', 'error'); return; }
|
||||
|
||||
_gamAwarding = true;
|
||||
try {
|
||||
const r = await LS.adminGamAward({ userId, xp, coins, reason });
|
||||
LS.toast(`Начислено! XP: ${r.xp}, Уровень: ${r.level}, Монеты: ${r.coins}`, 'success');
|
||||
const userName = document.getElementById('gam-award-uid').selectedOptions?.[0]?.textContent || 'пользователю';
|
||||
LS.toast(`Начислено ${userName}: XP +${xp} Монеты +${coins} → Уровень ${r.level}`, 'success');
|
||||
// Reset form
|
||||
document.getElementById('gam-award-uid').value = '';
|
||||
document.getElementById('gam-award-user').value = '';
|
||||
document.getElementById('gam-award-xp').value = '0';
|
||||
document.getElementById('gam-award-coins').value = '0';
|
||||
document.getElementById('gam-award-reason').value = '';
|
||||
document.querySelectorAll('.gam-xp-preset,.gam-coins-preset').forEach(b => b.classList.remove('active'));
|
||||
inited = false;
|
||||
await load();
|
||||
inited = true;
|
||||
} catch(e) { LS.toast('Ошибка: ' + e.message, 'error'); }
|
||||
} catch (e) { LS.toast('Ошибка: ' + e.message, 'error'); }
|
||||
finally { _gamAwarding = false; }
|
||||
}
|
||||
|
||||
/* ── Сбросить прогресс ───────────────────────────────────────────────── */
|
||||
async function gamAdminReset() {
|
||||
const userId = parseInt(document.getElementById('gam-reset-uid').value);
|
||||
const userName = document.getElementById('gam-reset-user').value;
|
||||
const sel = document.getElementById('gam-reset-uid');
|
||||
const userId = parseInt(sel?.value, 10);
|
||||
const userName = sel?.selectedOptions?.[0]?.textContent || '';
|
||||
if (!userId) { LS.toast('Выберите пользователя', 'error'); return; }
|
||||
if (!await LS.confirm(`ВСЕ XP, монеты и достижения «${userName}» будут удалены безвозвратно.`, { title: 'Сбросить прогресс?', confirmText: 'Сбросить', danger: true })) return;
|
||||
if (!await LS.confirm(
|
||||
`ВСЕ XP, монеты и достижения пользователя «${userName}» будут удалены безвозвратно.`,
|
||||
{ title: 'Сбросить прогресс?', confirmText: 'Сбросить', danger: true }
|
||||
)) return;
|
||||
try {
|
||||
await LS.adminGamReset({ userId });
|
||||
LS.toast('Прогресс сброшен', 'success');
|
||||
document.getElementById('gam-reset-uid').value = '';
|
||||
document.getElementById('gam-reset-user').value = '';
|
||||
inited = false;
|
||||
await load();
|
||||
inited = true;
|
||||
} catch(e) { LS.toast('Ошибка: ' + e.message, 'error'); }
|
||||
LS.toast('Прогресс сброшен: ' + userName, 'success');
|
||||
sel.value = '';
|
||||
inited = false; await load(); inited = true;
|
||||
} catch (e) { LS.toast('Ошибка: ' + e.message, 'error'); }
|
||||
}
|
||||
|
||||
window.gamSearchUser = gamSearchUser;
|
||||
window.gamPickUser = gamPickUser;
|
||||
window.gamAdminAward = gamAdminAward;
|
||||
window.gamAdminReset = gamAdminReset;
|
||||
window.gamAdminAward = gamAdminAward;
|
||||
window.gamAdminReset = gamAdminReset;
|
||||
window.gamSetXP = gamSetXP;
|
||||
window.gamSetCoins = gamSetCoins;
|
||||
window.gamSetReason = gamSetReason;
|
||||
window.gamFilterUsers = filterUserSelect;
|
||||
|
||||
window.AdminSections = window.AdminSections || {};
|
||||
window.AdminSections.gam = {
|
||||
|
||||
Reference in New Issue
Block a user