'use strict'; /* admin → gam (gamification) section: stats + top + recent XP + purchases + award XP */ (function () { 'use strict'; let inited = false; let _gamSearchTimer = null; let _gamAwarding = false; 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', 'Начисление администратором'], }; function fmtXPReason(reason) { if (!reason) return '—'; const entry = XP_REASONS[reason]; if (entry) { const [icon, color, label] = entry; return `${lsIcon(icon,14)}${label}`; } if (reason.startsWith('achievement:')) { return `${lsIcon('award',14)}Достижение: ${esc(reason.slice(12))}`; } if (reason.startsWith('Испытание:')) { return `${lsIcon('swords',14)}${esc(reason)}`; } return esc(reason); } async function load() { const { fmtDate } = AdminCtx; try { const stats = await LS.adminGamStats(); document.getElementById('gam-stats-grid').innerHTML = `
${stats.totalXP}
Суммарный XP
${stats.totalCoins}
Суммарные монеты
${(stats.avgLevel ?? 0).toFixed(1)}
Средний уровень
${stats.achievementCount}
Достижений выдано
${stats.totalPurchases || 0}
Покупок
`; // Top-10 const topBody = document.getElementById('gam-top-body'); if (stats.topByXP?.length) { topBody.innerHTML = stats.topByXP.slice(0, 10).map((u, i) => ` ${i + 1} ${esc(u.name || u.email || 'ID:' + (u.id || u.user_id))} ${u.xp} ${u.level} ${u.coins} `).join(''); } else { topBody.innerHTML = 'Нет данных'; } // Recent XP const logBody = document.getElementById('gam-log-body'); if (stats.recentXP?.length) { logBody.innerHTML = stats.recentXP.slice(0, 20).map(e => ` ${fmtDate(e.created_at || e.date)} ${esc(e.name || e.user_name || '—')} +${e.amount} ${fmtXPReason(e.reason)} `).join(''); } else { logBody.innerHTML = 'Нет данных'; } // Purchases const purchBody = document.getElementById('gam-purchases-body'); if (stats.recentPurchases?.length) { purchBody.innerHTML = stats.recentPurchases.slice(0, 20).map(p => ` ${fmtDate(p.purchased_at)} ${esc(p.user_name || '—')} ${esc(p.item_name || '—')} ${esc(p.type || '—')} ${p.price} `).join(''); } else { purchBody.innerHTML = 'Нет покупок'; } if (window.lucide) lucide.createIcons(); } catch(e) { document.getElementById('gam-stats-grid').innerHTML = `
Ошибка: ${esc(e.message)}
`; } } 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 }); box.innerHTML = (r.users || []).map(u => `
${esc(u.name || u.email)}${u.role}
`).join('') || '
Не найдено
'; box.classList.add('open'); } catch(e) { box.classList.remove('open'); } }, 300); } function gamPickUser(id, name, prefix) { document.getElementById(prefix + '-uid').value = id; document.getElementById(prefix + '-user').value = name; document.getElementById(prefix + '-results').classList.remove('open'); } 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; } _gamAwarding = true; try { const r = await LS.adminGamAward({ userId, xp, coins, reason }); LS.toast(`Начислено! XP: ${r.xp}, Уровень: ${r.level}, Монеты: ${r.coins}`, 'success'); document.getElementById('gam-award-uid').value = ''; document.getElementById('gam-award-user').value = ''; document.getElementById('gam-award-reason').value = ''; inited = false; await load(); inited = true; } 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; if (!userId) { LS.toast('Выберите пользователя', 'error'); 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'); } } window.gamSearchUser = gamSearchUser; window.gamPickUser = gamPickUser; window.gamAdminAward = gamAdminAward; window.gamAdminReset = gamAdminReset; window.AdminSections = window.AdminSections || {}; window.AdminSections.gam = { init: async () => { if (inited) return; inited = true; await load(); }, reload: load, }; })();