fix: improve calculator accessibility and async result handling

This commit is contained in:
nyan404 committed 2026-11-14 01:34:20 +03:00
1 parent ea2f0fbe05
commit bb21a767d7
9 files changed
+473 -105

No files matched your search

+32 -27
View File
@@ -21,11 +21,14 @@
.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; }
.tab[aria-pressed="true"] { text-decoration:underline; text-underline-offset:4px; 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 p { margin: 0 0 24px; color: var(--muted); line-height: 1.55; }
.auth-form { display: flex; gap: 10px; }
.auth-form input { flex: 1; min-width: 0; }
.auth-form input { width:100%; min-width:0; }
.password-field { display:grid; gap:6px; flex:1; min-width:0; }
.auth-form { align-items:end; }
.auth-view h1 { font-size:2rem; margin-bottom:8px; }
.controls { display: flex; flex-wrap: wrap; align-items: end; gap: 12px; padding: 20px 0; }
.control-group { display: grid; gap: 6px; color: var(--muted); font-size: .72rem; font-weight: 750; letter-spacing: .055em; text-transform: uppercase; }
.control-group input, .control-group select { align-self: start; }
@@ -52,7 +55,7 @@
input { min-width: 245px; }
input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px #b86f3b22; }
button { border: 1px solid var(--ink); padding: 9px 16px; background: var(--ink); color: #fffdfa; cursor: pointer; font-weight: 650; transition: background-color 160ms ease-out, border-color 160ms ease-out, color 160ms ease-out; }
button:focus-visible, a:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; }
input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible, a:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; }
button:hover { background: #45413d; }
.export-link { display: inline-flex; min-height: 42px; align-items: center; justify-content: center; padding: 9px 16px; border: 1px solid var(--accent); border-radius: 7px; color: var(--accent); font-weight: 650; text-decoration: none; }
.export-link:hover { background: #fff4ea; }
@@ -90,15 +93,17 @@
.admin-section { padding-top: 28px; }
.applications { padding-top: 4px; }
.application-layout { display: grid; grid-template-columns: minmax(260px, .8fr) minmax(380px, 1.2fr); border: 1px solid var(--line); border-radius: 9px; overflow: hidden; background: var(--paper); }
.application-list { border-right: 1px solid var(--line); }.application-item { display: block; width: 100%; min-height: 76px; padding: 15px 16px; border: 0; border-bottom: 1px solid #ebe7e0; border-radius: 0; background: transparent; color: var(--ink); text-align: left; }.application-item:last-child { border-bottom: 0; }.application-item[aria-selected="true"] { background: #f0f7ee; }.application-item strong,.application-item span { display:block; }.application-item span { margin-top:4px; color:var(--muted); font-size:.82rem; }.application-detail { min-height: 360px; padding: 25px; }.application-detail dl { display:grid; grid-template-columns: 150px 1fr; gap:12px 16px; margin:22px 0; }.application-detail dt { color:var(--muted); font-size:.8rem; font-weight:750; text-transform:uppercase; letter-spacing:.05em; }.application-detail dd { margin:0; white-space:pre-wrap; }.application-detail .photos { max-width:none; margin:0 0 18px; }.application-detail .photos button { width:120px; height:90px; }.application-actions { display:flex; flex-wrap:wrap; gap:10px; margin-top:18px; }.accept { border-color:#247036; background:#247036; }.accept:hover { background:#185627; }.reject { border-color:#a23d35; background:transparent; color:#8e3630; }.reject:hover { background:#fff1ef; }
.application-list { border-right: 1px solid var(--line); }.application-item { display: block; width: 100%; min-height: 76px; padding: 15px 16px; border: 0; border-bottom: 1px solid #ebe7e0; border-radius: 0; background: transparent; color: var(--ink); text-align: left; }.application-item:last-child { border-bottom: 0; }.application-item[aria-pressed="true"] { text-decoration:underline; text-underline-offset:4px; background: #f0f7ee; }.application-item strong,.application-item span { display:block; }.application-item span { margin-top:4px; color:var(--muted); font-size:.82rem; }.application-detail { min-height: 360px; padding: 25px; }.application-detail dl { display:grid; grid-template-columns: 150px 1fr; gap:12px 16px; margin:22px 0; }.application-detail dt { color:var(--muted); font-size:.8rem; font-weight:750; text-transform:uppercase; letter-spacing:.05em; }.application-detail dd { margin:0; white-space:pre-wrap; }.application-detail .photos { max-width:none; margin:0 0 18px; }.application-detail .photos button { width:120px; height:90px; }.application-actions { display:flex; flex-wrap:wrap; gap:10px; margin-top:18px; }.accept { border-color:#247036; background:#247036; }.accept:hover { background:#185627; }.reject { border-color:#a23d35; background:transparent; color:#8e3630; }.reject:hover { background:#fff1ef; }
dialog { width: min(900px, calc(100% - 32px)); padding: 0; border: 1px solid #5a524b; border-radius: 10px; background: #24211f; color: #fffdfa; box-shadow: 0 24px 80px #211b18aa; }
dialog::backdrop { background: #211b1877; }
dialog:modal { overscroll-behavior:contain; }
dialog::backdrop { background: #211b1877; overflow:hidden; overscroll-behavior:contain; }
.gallery { display: grid; grid-template-columns: 52px 1fr 52px; align-items: center; gap: 12px; padding: 16px; }
.gallery img { display: block; width: 100%; max-height: 72vh; object-fit: contain; }
.gallery button { width: 44px; min-height: 44px; padding: 0; border-color: #665d56; background: #3a3430; font-size: 1.25rem; }
.gallery button:hover { background: #514840; }
.gallery-footer { display: flex; justify-content: space-between; align-items: center; padding: 0 18px 16px; color: #c8bfb8; font-size: .85rem; }
.gallery-footer button { min-height: 34px; padding: 5px 10px; }
@media (pointer: coarse) { .tab, .delete, .gallery-footer button, .weekday-options label { min-height:48px; } }
@media (max-width: 720px) { main { width: calc(100% - 28px); padding-top: 28px; } .topbar { display: block; } .record-count { display: block; margin-top: 18px; } .controls { display: grid; grid-template-columns: 1fr 1fr; } .control-group:first-child, .controls > button, .controls > .export-link { grid-column: 1 / -1; } input { min-width: 0; width: 100%; } .auth-form { display: grid; } .application-layout { grid-template-columns:1fr; }.application-list { border-right:0; border-bottom:1px solid var(--line); }.application-detail dl { grid-template-columns:1fr; gap:4px; }.application-detail dd { margin-bottom:14px; } .weekday-field { grid-column: 1 / -1; min-width: 0; } .weekday-options { gap: 4px; } }
</style>
<link rel="stylesheet" href="/api/weather/effect.css">
@@ -108,10 +113,10 @@
<div class="leaf-field" aria-hidden="true"><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span></div>
<main>
<section id="authView" class="auth-view">
<h2>Админская панель</h2>
<h1>Админская панель</h1>
<p>Введите пароль администратора, чтобы открыть историю отчётов.</p>
<form id="authForm" class="auth-form">
<input id="password" type="password" autocomplete="current-password" placeholder="Пароль" required>
<label for="password" class="password-field">Пароль<input id="password" type="password" autocomplete="current-password" name="password" required></label>
<button type="submit" id="authButton">Войти</button>
</form>
</section>
@@ -121,21 +126,21 @@
<div><h1>Админская панель</h1><p class="intro">Расчёты и заявки из бота VK и с сайта.</p></div>
</header>
<nav class="tabs" aria-label="Раздел админской панели">
<button class="admin-tab tab" type="button" data-admin-view="reports" aria-selected="true">Отчёты</button>
<button class="admin-tab tab" type="button" data-admin-view="applications" aria-selected="false">Заявки</button>
<button class="admin-tab tab" type="button" data-admin-view="vk" aria-selected="false">Беседы VK</button>
<button class="admin-tab tab" type="button" data-admin-view="reports" aria-pressed="true">Отчёты</button>
<button class="admin-tab tab" type="button" data-admin-view="applications" aria-pressed="false">Заявки</button>
<button class="admin-tab tab" type="button" data-admin-view="vk" aria-pressed="false">Беседы VK</button>
</nav>
<section id="reportsView" class="admin-section">
<header class="topbar">
<div><h1>История отчётов</h1><p class="intro">Подтверждённые расчёты из VK-бота и веб-калькулятора.</p></div>
<div><h2>История отчётов</h2><p class="intro">Подтверждённые расчёты из VK-бота и веб-калькулятора.</p></div>
<div class="record-count" id="recordCount">Записи не загружены</div>
</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>
<button class="tab" type="button" data-category="all" aria-pressed="true">Все</button>
<button class="tab" type="button" data-category="inspection" aria-pressed="false">Осмотры</button>
<button class="tab" type="button" data-category="lu" aria-pressed="false">Лазание (ЛУ)</button>
<button class="tab" type="button" data-category="zu" aria-pressed="false">Зоркость (ЗУ)</button>
<button class="tab" type="button" data-category="training" aria-pressed="false">ПУ / уроки</button>
</nav>
<section class="controls" aria-label="Фильтры истории">
<label class="control-group">Сортировать по<select id="sort"><option value="date" selected>Дате</option><option value="cat">Коту</option><option value="kitten">Котёнку</option><option value="photo">Фото</option><option value="message">Сообщению</option><option value="author">Автору</option><option value="id">ID</option></select></label>
@@ -151,7 +156,7 @@
<p class="error" id="error" role="alert"></p>
<div class="table-wrap"><table><thead><tr><th>Внесено</th><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Баллы</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="10">Загрузка истории…</td></tr></tbody></table></div>
</section>
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые заявки из бота VK и с сайта.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-selected="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые заявки из бота VK и с сайта.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-pressed="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-pressed="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-pressed="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
<header class="topbar"><div><h2 id="vkTitle">Беседы VK</h2><p class="intro">Беседы и расписания сообщений. Время указано по Москве. Каждое расписание включается отдельно.</p></div><div class="record-count" id="vkCount">Не загружено</div></header>
<section class="vk-step" aria-labelledby="vkTemplateStep"><h3 id="vkTemplateStep">1. Шаблон сообщения</h3><p>Сначала сохраните текст сообщения. Переносы строк сохранятся.</p><div class="vk-template-grid"><label class="control-group">Текст сообщения<textarea id="vkTemplateText" maxlength="4096" placeholder="Например: напоминание об еженедельном отчёте"></textarea><span id="vkTemplateCount" class="muted">0 / 4096</span></label><div><div class="control-group">Предпросмотр</div><pre id="vkTemplatePreview" class="vk-template-preview">Выберите сохранённый шаблон или напишите новый текст.</pre></div></div><div class="vk-template-actions"><label class="control-group">Название шаблона<input id="vkTemplateName" maxlength="100" placeholder="Например, Понедельник"></label><button id="saveVkTemplate" type="button">Сохранить шаблон</button><button id="loadVk" type="button">Обновить данные</button></div></section>
@@ -162,9 +167,9 @@
</section>
</main>
<dialog id="galleryDialog">
<dialog id="galleryDialog" aria-label="Скриншоты отчёта">
<div class="gallery"><button id="prevPhoto" type="button" aria-label="Предыдущее фото">←</button><img id="galleryImage" alt="Фото отчёта"><button id="nextPhoto" type="button" aria-label="Следующее фото">→</button></div>
<div class="gallery-footer"><span id="galleryCounter"></span><button id="closeGallery" type="button">Закрыть</button></div>
<div class="gallery-footer"><span id="galleryCounter" role="status"></span><button id="closeGallery" type="button">Закрыть</button></div>
</dialog>
<script>
@@ -211,7 +216,7 @@
function photoCell(attachments) {
const node = document.createElement('td'); const gallery = document.createElement('div'); gallery.className = 'photos';
const validPhotos = (attachments || []).filter(photo => photo.mirror_url || photo.url);
validPhotos.forEach((photo, index) => { const url = photo.mirror_url || photo.url; const button = document.createElement('button'); button.type = 'button'; button.title = 'Открыть фото'; const image = document.createElement('img'); image.src = url; image.alt = 'Фото отчёта'; image.loading = 'lazy'; button.append(image); button.addEventListener('click', () => openGallery(validPhotos, index)); gallery.append(button); });
validPhotos.forEach((photo, index) => { const url = photo.mirror_url || photo.url; const button = document.createElement('button'); button.type = 'button'; button.setAttribute('aria-label', `Открыть фото ${index + 1}`); const image = document.createElement('img'); image.src = url; image.alt = 'Фото отчёта'; image.loading = 'lazy'; button.append(image); button.addEventListener('click', () => openGallery(validPhotos, index)); gallery.append(button); });
if (gallery.childElementCount) node.append(gallery); else node.textContent = '—'; return node;
}
// Formats stored ISO timestamps for the Russian admin table without shifting their clock time.
@@ -236,13 +241,13 @@
// Extracts display fields from one application for the detail panel.
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; }
// Renders pending or accepted applications and their actions.
function renderApplications() { syncApplicationsExport(); const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications; document.querySelector('#applicationCount').textContent = `${visible.length} заявок`; 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 actions=document.createElement('div');actions.className='application-actions';const review=async(action,button)=>{button.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/${action}`,{method:'PATCH'}),data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось изменить статус заявки');await loadApplications()}catch(err){error.textContent=err.message;button.disabled=false}};const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=()=>review('accept',accept);const reject=document.createElement('button');reject.className='reject';reject.type='button';reject.textContent='Отклонить';reject.onclick=()=>review('reject',reject);actions.append(accept,reject);detail.append(actions)} }
function renderApplications() { syncApplicationsExport(); const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications; document.querySelector('#applicationCount').textContent = `${visible.length} заявок`; 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-pressed', 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 actions=document.createElement('div');actions.className='application-actions';const review=async(action,button)=>{button.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/${action}`,{method:'PATCH'}),data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось изменить статус заявки');await loadApplications()}catch(err){error.textContent=err.message;button.disabled=false}};const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=()=>review('accept',accept);const reject=document.createElement('button');reject.className='reject';reject.type='button';reject.textContent='Отклонить';reject.onclick=()=>review('reject',reject);actions.append(accept,reject);detail.append(actions)} }
// Loads applications from the admin API and renders the selected status.
async function loadApplications() { try { const response=await fetch(`/api/admin/applications?${queryFor(applicationPeriod, applicationDateFrom, applicationDateTo, {status: activeApplicationStatus})}`), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
// Opens the authenticated admin view and starts both data loaders.
async function openAdmin() { authView.classList.add('hidden'); appView.classList.remove('hidden'); await load(); await loadApplications(); connectUpdates(); }
// Authenticates the administrator and transitions to the admin view.
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; } }
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(); message.setAttribute('role', 'alert'); authView.append(message); } finally { authButton.disabled = false; } }
// Maintains the live update WebSocket and reconnects after disconnects.
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); }; }
// Restores an existing admin session when the page is reopened.
@@ -250,13 +255,13 @@
// Updates the current gallery image and counter.
function updateGallery() { const photo = galleryPhotos[galleryIndex]; galleryImage.src = photo.mirror_url || photo.url; galleryCounter.textContent = `${galleryIndex + 1} из ${galleryPhotos.length}`; }
// Opens the photo gallery at the requested image index.
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(); galleryDialog.showModal(); }
// Closes the photo gallery dialog.
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
function closeGallery() { galleryDialog.close(); }
// Switches between report and application admin views.
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelector('#vkView').classList.toggle('hidden', view !== 'vk'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); if(view==='vk')loadVk(); }
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', load); kittenFilter.addEventListener('change', load); [reportPeriod, reportDateFrom, reportDateTo].forEach(control => control.addEventListener('change', load)); 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))); load(); })); 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.querySelector('#loadApplications').addEventListener('click', loadApplications); [applicationPeriod, applicationDateFrom, applicationDateTo].forEach(control => control.addEventListener('change', loadApplications)); 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))); loadApplications(); }));
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelector('#vkView').classList.toggle('hidden', view !== 'vk'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-pressed', String(tab.dataset.adminView === view))); if(view==='vk')loadVk(); }
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', load); kittenFilter.addEventListener('change', load); [reportPeriod, reportDateFrom, reportDateTo].forEach(control => control.addEventListener('change', load)); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-pressed', String(item === tab))); load(); })); 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 === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
document.querySelector('#loadApplications').addEventListener('click', loadApplications); [applicationPeriod, applicationDateFrom, applicationDateTo].forEach(control => control.addEventListener('change', loadApplications)); document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-pressed', String(item === tab))); loadApplications(); }));
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
document.querySelector('#loadVk').addEventListener('click', loadVk); document.querySelector('#saveVkTemplate').addEventListener('click', createVkTemplate);
document.querySelector('#saveVkSchedule').addEventListener('click', createVkSchedule);