feat(admin): persist sessions and refresh via websocket

This commit is contained in:
nyan404 committed 2026-08-21 14:13:44 +03:00
1 parent 351ceeb990
commit 0c59d8cb15
5 files changed
+80 -9

No files matched your search

+10 -6
View File
@@ -138,7 +138,7 @@
const galleryImage = document.querySelector('#galleryImage');
const galleryCounter = document.querySelector('#galleryCounter');
let items = [], galleryPhotos = [], galleryIndex = 0, activeCategory = 'all';
let applications = [], activeApplicationStatus = 'pending', selectedApplicationId = null, activeAdminView = 'reports';
let applications = [], activeApplicationStatus = 'pending', selectedApplicationId = null, activeAdminView = 'reports', updatesSocket = null, updatesRetry = null;
function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; }
function kittenEntries(input) {
@@ -158,13 +158,16 @@
function categoryFor(item) { const input = item.input || {}; if (input.mode === 'inspection') return 'inspection'; if (input.mode === 'training') return 'training'; if (input.skill === 'ЛУ') return 'lu'; if (input.skill === 'ЗУ') return 'zu'; return 'other'; }
function filteredItems() { const cat = catFilter.value; const kitten = kittenFilter.value; return items.filter(item => { const input = item.input || {}; const person = personData(input); const kittens = kittenEntries(input); return (activeCategory === 'all' || categoryFor(item) === activeCategory) && (!cat || String(person.id) === cat) && (!kitten || kittens.some(entry => String(entry.id) === kitten)); }).sort((a, b) => { const av = textForSort(a, sort.value), bv = textForSort(b, sort.value); const result = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv), 'ru', {numeric: true, sensitivity: 'base'}); return direction.value === 'asc' ? result : -result; }); }
function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; }
function render() { rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} из ${items.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.created_at || '—'; return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE', headers: {'X-Admin-Password': password.value}}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); }
async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = new URLSearchParams({sort: 'escort_name', direction: 'asc', limit: '500'}); const response = await fetch(`/api/admin/calculations?${query}`, {headers: {'X-Admin-Password': password.value}}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }
function render() { rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} из ${items.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.created_at || '—'; return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE'}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); }
async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = new URLSearchParams({sort: 'escort_name', direction: 'asc', limit: '500'}); const response = await fetch(`/api/admin/calculations?${query}`); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }
const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'};
function applicationFields(item) { const a = item.application || {}; const fields = [['Тип', applicationLabels[a.type] || a.type], ['Персонаж', `${a.name || '—'}${a.character_id ? ` [${a.character_id}]` : ''}`], ['Источник', item.source === 'vk' ? 'VK-бот' : 'Веб-форма']]; if (a.vk_link) fields.push(['VK', a.vk_link]); if (a.type === 'flying_squirrel') { fields.push(['Практика ранее', a.practiced_before ? 'Да' : 'Нет']); if (a.practice_review_link) fields.push(['Комментарий практики', a.practice_review_link]); } if (a.type === 'feather_donation') fields.push(['Перья', (a.feathers || []).map(x => `${x.amount} ${x.color} — ${x.source}`).join('\n')]); if (a.type === 'curator') fields.push(['Подтверждение', 'Скриншот ЛУ с дробью']); return fields; }
function renderApplications() { const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications.filter(item => item.status === activeApplicationStatus); document.querySelector('#applicationCount').textContent = `${visible.length} ${activeApplicationStatus === 'pending' ? 'новых' : 'принятых'} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=async()=>{accept.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/accept`,{method:'PATCH',headers:{'X-Admin-Password':password.value}});const data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось принять заявку');await loadApplications()}catch(err){error.textContent=err.message;accept.disabled=false}};detail.append(accept)} }
async function loadApplications() { try { const response=await fetch('/api/admin/applications',{headers:{'X-Admin-Password':password.value}}), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
async function authenticate(event) { event.preventDefault(); error.textContent = ''; authButton.disabled = true; try { const response = await fetch('/api/admin/calculations?limit=1', {headers: {'X-Admin-Password': password.value}}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось войти'); authView.classList.add('hidden'); appView.classList.remove('hidden'); items = data.items || []; await load(); await loadApplications(); } catch (err) { const message = document.createElement('p'); message.textContent = err.message; message.className = 'error'; const old = authView.querySelector('.error'); if (old) old.remove(); authView.append(message); } finally { authButton.disabled = false; } }
function renderApplications() { const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications.filter(item => item.status === activeApplicationStatus); document.querySelector('#applicationCount').textContent = `${visible.length} ${activeApplicationStatus === 'pending' ? 'новых' : 'принятых'} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=async()=>{accept.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/accept`,{method:'PATCH'});const data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось принять заявку');await loadApplications()}catch(err){error.textContent=err.message;accept.disabled=false}};detail.append(accept)} }
async function loadApplications() { try { const response=await fetch('/api/admin/applications'), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
async function openAdmin() { authView.classList.add('hidden'); appView.classList.remove('hidden'); await load(); await loadApplications(); connectUpdates(); }
async function authenticate(event) { event.preventDefault(); error.textContent = ''; authButton.disabled = true; try { const response = await fetch('/api/admin/auth', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({password: password.value})}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось войти'); password.value = ''; await openAdmin(); } catch (err) { const message = document.createElement('p'); message.textContent = err.message; message.className = 'error'; const old = authView.querySelector('.error'); if (old) old.remove(); authView.append(message); } finally { authButton.disabled = false; } }
function connectUpdates() { if (updatesSocket && (updatesSocket.readyState === WebSocket.OPEN || updatesSocket.readyState === WebSocket.CONNECTING)) return; const scheme = location.protocol === 'https:' ? 'wss' : 'ws'; updatesSocket = new WebSocket(`${scheme}://${location.host}/api/admin/updates`); updatesSocket.onmessage = async event => { try { if (JSON.parse(event.data).type === 'refresh') { await load(); await loadApplications(); } } catch (_) {} }; updatesSocket.onclose = () => { updatesSocket = null; clearTimeout(updatesRetry); updatesRetry = setTimeout(connectUpdates, 5000); }; }
async function restoreAdminSession() { try { const response = await fetch('/api/admin/session'); const data = await response.json(); if (data.authenticated) await openAdmin(); } catch (_) {} }
function updateGallery() { const photo = galleryPhotos[galleryIndex]; galleryImage.src = photo.mirror_url || photo.url; galleryCounter.textContent = `${galleryIndex + 1} из ${galleryPhotos.length}`; }
function openGallery(photos, index) { galleryPhotos = photos.filter(photo => photo.mirror_url || photo.url); galleryIndex = Math.min(index, galleryPhotos.length - 1); updateGallery(); if (galleryDialog.showModal) galleryDialog.showModal(); else galleryDialog.setAttribute('open', ''); }
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
@@ -172,6 +175,7 @@
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', render); kittenFilter.addEventListener('change', render); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-selected', String(item === tab))); render(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); renderApplications(); }));
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
restoreAdminSession();
</script>
</body>
</html>