Tabs in admin panel

This commit is contained in:
nyan404 committed 2026-08-17 01:00:39 +03:00
1 parent 7668618e6c
commit efaa358a0f
2 files changed
+16 -4

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@
- Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp. - Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp.
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred. - VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred.
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI. - `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI.
- The admin page uses a restrained light editorial table layout with a separate password gate, responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API. - The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API.
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported. - VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
- Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace. - Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace.
- The previously inspected `stage-zone-runner` at `10.3.1.236` is not the runner used by the current pipeline. Runner `#2` (`Ryzen-builder`) at `10.3.1.168` is a privileged Docker executor and supports the DinD service used by `.gitlab-ci.yml`. - The previously inspected `stage-zone-runner` at `10.3.1.236` is not the runner used by the current pipeline. Runner `#2` (`Ryzen-builder`) at `10.3.1.168` is a privileged Docker executor and supports the DinD service used by `.gitlab-ci.yml`.
+15 -3
View File
@@ -15,6 +15,10 @@
.intro { max-width: 520px; margin: 10px 0 0; line-height: 1.55; } .intro { max-width: 520px; margin: 10px 0 0; line-height: 1.55; }
.topbar { display: flex; align-items: end; justify-content: space-between; gap: 24px; padding-bottom: 28px; border-bottom: 1px solid var(--line); } .topbar { display: flex; align-items: end; justify-content: space-between; gap: 24px; padding-bottom: 28px; border-bottom: 1px solid var(--line); }
.record-count { color: var(--muted); font-size: .85rem; white-space: nowrap; } .record-count { color: var(--muted); font-size: .85rem; white-space: nowrap; }
.tabs { display: flex; flex-wrap: wrap; gap: 8px; padding: 22px 0 4px; border-bottom: 1px solid var(--line); }
.tab { min-height: 36px; padding: 7px 13px; border: 1px solid transparent; border-radius: 999px; background: transparent; color: var(--muted); font-size: .84rem; }
.tab:hover { border-color: #cfc8bf; background: #fffaf3; color: var(--ink); }
.tab[aria-selected="true"] { border-color: var(--ink); background: var(--ink); color: #fffdfa; }
.auth-view { width: min(480px, 100%); margin: 14vh auto 0; padding: 34px; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); box-shadow: 0 12px 35px #3b302414; } .auth-view { width: min(480px, 100%); margin: 14vh auto 0; padding: 34px; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); box-shadow: 0 12px 35px #3b302414; }
.auth-view p { margin: 0 0 24px; color: var(--muted); line-height: 1.55; } .auth-view p { margin: 0 0 24px; color: var(--muted); line-height: 1.55; }
.auth-form { display: flex; gap: 10px; } .auth-form { display: flex; gap: 10px; }
@@ -77,6 +81,13 @@
<div><h1>История отчётов</h1><p class="intro">Подтверждённые расчёты из VK-бота и веб-калькулятора.</p></div> <div><h1>История отчётов</h1><p class="intro">Подтверждённые расчёты из VK-бота и веб-калькулятора.</p></div>
<div class="record-count" id="recordCount">Записи не загружены</div> <div class="record-count" id="recordCount">Записи не загружены</div>
</header> </header>
<nav class="tabs" aria-label="Категория отчётов">
<button class="tab" type="button" data-category="all" aria-selected="true">Все</button>
<button class="tab" type="button" data-category="inspection" aria-selected="false">Осмотры</button>
<button class="tab" type="button" data-category="lu" aria-selected="false">Лазание (ЛУ)</button>
<button class="tab" type="button" data-category="zu" aria-selected="false">Зоркость (ЗУ)</button>
<button class="tab" type="button" data-category="training" aria-selected="false">ПУ / уроки</button>
</nav>
<section class="controls" aria-label="Фильтры истории"> <section class="controls" aria-label="Фильтры истории">
<label class="control-group">Сортировать по<select id="sort"><option value="cat">Коту</option><option value="kitten">Котёнку</option><option value="photo">Фото</option><option value="date">Дате</option><option value="message">Сообщению</option><option value="author">Автору</option><option value="id">ID</option></select></label> <label class="control-group">Сортировать по<select id="sort"><option value="cat">Коту</option><option value="kitten">Котёнку</option><option value="photo">Фото</option><option value="date">Дате</option><option value="message">Сообщению</option><option value="author">Автору</option><option value="id">ID</option></select></label>
<label class="control-group">Порядок<select id="direction"><option value="asc">По возрастанию</option><option value="desc" selected>По убыванию</option></select></label> <label class="control-group">Порядок<select id="direction"><option value="asc">По возрастанию</option><option value="desc" selected>По убыванию</option></select></label>
@@ -111,7 +122,7 @@
const galleryDialog = document.querySelector('#galleryDialog'); const galleryDialog = document.querySelector('#galleryDialog');
const galleryImage = document.querySelector('#galleryImage'); const galleryImage = document.querySelector('#galleryImage');
const galleryCounter = document.querySelector('#galleryCounter'); const galleryCounter = document.querySelector('#galleryCounter');
let items = [], galleryPhotos = [], galleryIndex = 0; let items = [], galleryPhotos = [], galleryIndex = 0, activeCategory = 'all';
function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; } function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; }
function kittenEntries(input) { function kittenEntries(input) {
@@ -128,7 +139,8 @@
if (gallery.childElementCount) node.append(gallery); else node.textContent = '—'; return node; if (gallery.childElementCount) node.append(gallery); else node.textContent = '—'; return node;
} }
function textForSort(item, field) { const input = item.input || {}; const person = personData(input); const kittens = kittenEntries(input); if (field === 'cat') return `${person.name} ${person.id}`.toLocaleLowerCase(); if (field === 'kitten') return kittens.map(item => `${item.name} ${item.id}`).join(',').toLocaleLowerCase(); if (field === 'photo') return (input.attachments || []).length; if (field === 'date') return item.created_at || ''; if (field === 'message') return item.message || ''; if (field === 'author') return String(item.actor_id || ''); return Number(item.id) || 0; } function textForSort(item, field) { const input = item.input || {}; const person = personData(input); const kittens = kittenEntries(input); if (field === 'cat') return `${person.name} ${person.id}`.toLocaleLowerCase(); if (field === 'kitten') return kittens.map(item => `${item.name} ${item.id}`).join(',').toLocaleLowerCase(); if (field === 'photo') return (input.attachments || []).length; if (field === 'date') return item.created_at || ''; if (field === 'message') return item.message || ''; if (field === 'author') return String(item.actor_id || ''); return Number(item.id) || 0; }
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 (!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 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 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); }); } 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; } } 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; } }
@@ -136,7 +148,7 @@
function updateGallery() { const photo = galleryPhotos[galleryIndex]; galleryImage.src = photo.mirror_url || photo.url; galleryCounter.textContent = `${galleryIndex + 1} из ${galleryPhotos.length}`; } 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 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'); } function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
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.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(); }); 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('.tab').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('.tab').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(); });
</script> </script>
</body> </body>
</html> </html>