Files
cwshed-clone/web/admin.html
T

254 lines
49 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Беличья нора — админка</title>
<link rel="icon" href="/favicon.png" type="image/png" sizes="192x192">
<style>
:root { color-scheme: light; font-family: "Trebuchet MS", ui-sans-serif, sans-serif; background: #f4f1eb; color: #292725; --ink:#292725; --muted:#625d57; --line:#ded9d1; --paper:#fffdfa; --accent:#9a542e; --danger:#8e3630; --focus:#9a542e; }
* { box-sizing: border-box; }
body { margin: 0; background: #f4f1eb; color: var(--ink); }
main { width: min(1440px, calc(100% - 48px)); margin: 0 auto; padding: 42px 0 64px; }
h1 { margin: 0; font: 500 clamp(2rem, 4vw, 3.25rem)/1 Georgia, "Times New Roman", serif; letter-spacing: -.035em; }
h2 { margin: 0 0 8px; font: 500 2rem/1.1 Georgia, "Times New Roman", serif; }
.muted, .intro { color: var(--muted); }
.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); }
.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 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; }
.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; }
.schedule-time-control { align-content: start; }
.schedule-time-control .muted { font-size: .78rem; font-weight: 400; letter-spacing: 0; line-height: 1.35; text-transform: none; }
.vk-step { margin: 24px 0; padding: 22px; border: 1px solid var(--line); border-radius: 9px; background: var(--paper); }
.vk-step h3 { margin: 0 0 4px; font: 500 1.45rem/1.2 Georgia, "Times New Roman", serif; }
.vk-step > p { margin: 0 0 16px; color: var(--muted); line-height: 1.45; }
.vk-template-grid { display: grid; grid-template-columns: minmax(210px, .45fr) minmax(320px, 1fr); gap: 14px; align-items: start; }
.vk-template-grid textarea { min-height: 132px; width: 100%; resize: vertical; }
.vk-template-preview { min-height: 132px; margin: 0; padding: 12px; border: 1px solid var(--line); border-radius: 7px; background: #f8f5f0; color: var(--ink); white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; line-height: 1.5; }
.vk-template-actions { display: flex; flex-wrap: wrap; align-items: end; gap: 10px; margin-top: 12px; }
.vk-template-actions .control-group { min-width: 210px; }
.vk-template-actions .muted { font-size: .8rem; font-weight: 400; letter-spacing: 0; text-transform: none; }
.weekday-field { min-width: 260px; }
.weekday-field legend { padding: 0; color: var(--muted); font-size: .72rem; font-weight: 750; letter-spacing: .055em; text-transform: uppercase; }
.weekday-options { display: grid; grid-template-columns: repeat(7, minmax(30px, 1fr)); gap: 5px; }
.weekday-options label { display: grid; place-items: center; min-height: 42px; border: 1px solid #cbc5bc; border-radius: 7px; background: var(--paper); color: var(--ink); cursor: pointer; font-size: .82rem; font-weight: 700; letter-spacing: 0; text-transform: none; transition: background-color 160ms ease-out, border-color 160ms ease-out, color 160ms ease-out; }
.weekday-options label:has(input:checked) { border-color: var(--ink); background: var(--ink); color: #fffdfa; }
.weekday-options input { position: absolute; opacity: 0; pointer-events: none; }
.weekday-options label:focus-within { outline: 3px solid var(--focus); outline-offset: 2px; }
input, select, button { min-height: 42px; border-radius: 7px; font: inherit; }
input, select { border: 1px solid #cbc5bc; background: var(--paper); color: var(--ink); padding: 9px 12px; outline: none; }
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; }
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; }
button:disabled { cursor: wait; opacity: .55; }
.error { min-height: 22px; margin: 0 0 12px; color: var(--danger); font-size: .9rem; }
.hidden { display: none !important; }
.table-wrap { overflow: auto; border: 1px solid var(--line); border-radius: 9px; background: var(--paper); box-shadow: 0 12px 35px #3b302414; }
table { width: 100%; min-width: 1240px; border-collapse: separate; border-spacing: 0; }
th, td { padding: 15px 16px; text-align: left; vertical-align: top; border-bottom: 1px solid #ebe7e0; }
th { position: sticky; top: 0; z-index: 1; background: #f8f5f0; color: #69635d; font-size: .72rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; white-space: nowrap; }
tbody tr:last-child td { border-bottom: 0; }
tbody tr:hover td { background: #fff8ef; }
td { color: #3d3935; font-size: .91rem; line-height: 1.45; }
.id-cell { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
.person { min-width: 155px; }
.person strong { display: block; color: var(--ink); font-weight: 700; }
.person span { display: block; margin-top: 2px; color: var(--muted); font-size: .82rem; }
.mode { color: #8f4d26; font-size: .78rem; font-weight: 750; text-transform: uppercase; letter-spacing: .05em; }
.photos { display: flex; flex-wrap: wrap; gap: 5px; max-width: 300px; }
.photos button { width: 78px; height: 58px; min-height: 0; padding: 0; overflow: hidden; border: 0; border-radius: 5px; background: #e8e2d9; }
.photos img { display: block; width: 100%; height: 100%; object-fit: cover; }
.photos button:hover { outline: 2px solid var(--accent); outline-offset: 2px; }
.message { max-width: 460px; margin: 0; white-space: pre-wrap; color: #514b45; font: inherit; font-size: .84rem; line-height: 1.5; }
.delete { min-height: 34px; padding: 6px 10px; border-color: #d9b8b2; background: transparent; color: var(--danger); font-size: .82rem; }
.delete:hover { border-color: var(--danger); background: #fff1ef; color: var(--danger); }
.empty { padding: 44px 20px; text-align: center; color: var(--muted); }
.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; }
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; }
.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 (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>
</head>
<body>
<main>
<section id="authView" class="auth-view">
<h2>Админская панель</h2>
<p>Введите пароль администратора, чтобы открыть историю отчётов.</p>
<form id="authForm" class="auth-form">
<input id="password" type="password" autocomplete="current-password" placeholder="Пароль" required>
<button type="submit" id="authButton">Войти</button>
</form>
</section>
<section id="appView" class="hidden">
<header class="topbar">
<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>
</nav>
<section id="reportsView" class="admin-section">
<header class="topbar">
<div><h1>История отчётов</h1><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>
</nav>
<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="direction"><option value="asc">По возрастанию</option><option value="desc" selected>По убыванию</option></select></label>
<label class="control-group">Кот<select id="catFilter"><option value="">Все коты</option></select></label>
<label class="control-group">Котёнок<select id="kittenFilter"><option value="">Все котята</option></select></label>
<label class="control-group">Период<select id="reportPeriod"><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="reportDateFrom" type="date"></label>
<label class="control-group">По дату<input id="reportDateTo" type="date"></label>
<button id="load" type="button">Обновить</button>
<a id="reportsExport" class="export-link" href="/api/admin/calculations.xlsx">Скачать XLSX</a>
</section>
<p class="error" id="error" role="alert"></p>
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</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="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>
<section class="vk-step" aria-labelledby="vkScheduleStep"><h3 id="vkScheduleStep">2. Когда отправлять</h3><p>Выберите беседу и сохранённый шаблон, затем задайте одно или несколько времён. Новое расписание создаётся выключенным.</p><section class="controls" aria-label="Новое расписание"><label class="control-group">Беседа<select id="vkConversation"></select></label><label class="control-group">Шаблон<select id="vkTemplate"></select></label><label class="control-group schedule-time-control">Время отправки<input id="vkTimes" type="text" placeholder="09:00, 18:30" aria-describedby="vkTimesHelp"><span id="vkTimesHelp" class="muted">Одно или несколько времён через запятую</span></label><fieldset class="control-group weekday-field"><legend>Дни недели</legend><div class="weekday-options"><label><input type="checkbox" value="1" checked>Пн</label><label><input type="checkbox" value="2" checked>Вт</label><label><input type="checkbox" value="3" checked>Ср</label><label><input type="checkbox" value="4" checked>Чт</label><label><input type="checkbox" value="5" checked>Пт</label><label><input type="checkbox" value="6" checked>Сб</label><label><input type="checkbox" value="7" checked>Вс</label></div></fieldset><label class="control-group">Начало<input id="vkStartsOn" type="date"></label><label class="control-group">Окончание<input id="vkEndsOn" type="date"></label><button id="saveVkSchedule" type="button">Создать расписание</button></section></section>
<h3>Расписания</h3><div class="table-wrap"><table><thead><tr><th>ID</th><th>Шаблон</th><th>Беседа</th><th>Когда</th><th>Статус</th><th></th></tr></thead><tbody id="vkScheduleRows"><tr><td class="empty" colspan="6">Расписаний пока нет.</td></tr></tbody></table></div>
<p class="error" id="vkError" role="alert"></p><div class="table-wrap"><table><thead><tr><th>Беседа</th><th>Статус</th><th>Рассылка</th><th>Добавлена</th><th>Последняя отправка</th><th>Ошибка</th></tr></thead><tbody id="vkRows"><tr><td class="empty" colspan="6">Загрузка…</td></tr></tbody></table></div>
</section>
</section>
</main>
<dialog id="galleryDialog">
<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>
</dialog>
<script>
/* Admin UI helpers normalize stored applications, build filter options,
render report/application tables, and coordinate the photo gallery. */
const authView = document.querySelector('#authView');
const appView = document.querySelector('#appView');
const authForm = document.querySelector('#authForm');
const password = document.querySelector('#password');
const authButton = document.querySelector('#authButton');
const sort = document.querySelector('#sort');
const direction = document.querySelector('#direction');
const catFilter = document.querySelector('#catFilter');
const kittenFilter = document.querySelector('#kittenFilter');
const reportPeriod = document.querySelector('#reportPeriod'), reportDateFrom = document.querySelector('#reportDateFrom'), reportDateTo = document.querySelector('#reportDateTo');
const applicationPeriod = document.querySelector('#applicationPeriod'), applicationDateFrom = document.querySelector('#applicationDateFrom'), applicationDateTo = document.querySelector('#applicationDateTo');
const rows = document.querySelector('#rows');
const error = document.querySelector('#error');
const recordCount = document.querySelector('#recordCount');
const loadButton = document.querySelector('#load');
const galleryDialog = document.querySelector('#galleryDialog');
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', updatesSocket = null, updatesRetry = null;
async function loadVk() { const errorNode=document.querySelector('#vkError'); errorNode.textContent=''; try { const [convResponse, templateResponse, scheduleResponse]=await Promise.all([fetch('/api/admin/vk/conversations'),fetch('/api/admin/vk/templates'),fetch('/api/admin/vk/schedules')]); const convData=await convResponse.json(), templateData=await templateResponse.json(), scheduleData=await scheduleResponse.json(); if(!convResponse.ok||!templateResponse.ok||!scheduleResponse.ok) throw new Error('Не удалось загрузить настройки VK'); const conversations=convData.items||[], templates=templateData.items||[], schedules=scheduleData.items||[]; const conversationSelect=document.querySelector('#vkConversation'), templateSelect=document.querySelector('#vkTemplate'); conversationSelect.replaceChildren(); conversations.forEach(item=>conversationSelect.add(new Option(`${item.title||'Без названия'} · ${item.chat_id}`, item.peer_id))); templateSelect.replaceChildren(); templates.forEach(item=>templateSelect.add(new Option(`${item.name} · ${item.text.slice(0,50)}`, item.id))); const rowsNode=document.querySelector('#vkRows'); rowsNode.replaceChildren(); document.querySelector('#vkCount').textContent=`${conversations.length} бесед · ${schedules.length} расписаний`; conversations.forEach(item=>{const row=document.createElement('tr'); const name=document.createElement('td'); name.textContent=`${item.title||'Без названия'} · ${item.peer_id} / chat ${item.chat_id}`; const status=document.createElement('td'); status.textContent=item.status||'—'; const mailing=document.createElement('td'); mailing.textContent=item.mailing_enabled?'Есть активная рассылка':'Управляется расписаниями'; const added=document.createElement('td'); added.textContent=displayDate(item.added_at); const success=document.createElement('td'); success.textContent=displayDate(item.last_success_at); const lastError=document.createElement('td'); lastError.textContent=item.last_error||item.removal_reason||'—'; row.append(name,status,mailing,added,success,lastError); rowsNode.append(row); }); const scheduleRows=document.querySelector('#vkScheduleRows'); scheduleRows.replaceChildren(); schedules.forEach(item=>{const row=document.createElement('tr'); row.innerHTML=`<td>${item.id}</td><td>${templates.find(x=>x.id===item.template_id)?.name||item.template_id}</td><td>${item.peer_id}</td><td>${item.weekdays.join(', ')} · ${item.times.join(', ')}</td><td></td><td></td>`; const toggle=document.createElement('button'); toggle.type='button'; toggle.textContent=item.active?'Выключить':'Включить'; toggle.onclick=async()=>{toggle.disabled=true; await fetch(`/api/admin/vk/schedules/${item.id}`,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({active:!item.active})}); loadVk();}; row.children[4].append(toggle); const remove=document.createElement('button'); remove.type='button'; remove.className='delete'; remove.textContent='Удалить'; remove.onclick=async()=>{if(!window.confirm(`Удалить расписание №${item.id}?`))return; remove.disabled=true; const response=await fetch(`/api/admin/vk/schedules/${item.id}`,{method:'DELETE'}); if(!response.ok){const data=await response.json();errorNode.textContent=data.error||'Не удалось удалить расписание';remove.disabled=false;return;} loadVk();}; row.children[5].append(remove); scheduleRows.append(row); }); } catch(err) { errorNode.textContent=err.message; } }
async function updateVkTemplatePreview() { const selected=document.querySelector('#vkTemplate').selectedOptions[0]; if(!selected){document.querySelector('#vkTemplatePreview').textContent='Выберите сохранённый шаблон или напишите новый текст.';return;} try { const response=await fetch('/api/admin/vk/templates'), data=await response.json(), item=(data.items||[]).find(template=>String(template.id)===selected.value); document.querySelector('#vkTemplatePreview').textContent=item ? item.text : selected.textContent; } catch (_) { document.querySelector('#vkTemplatePreview').textContent=selected.textContent; } }
async function createVkTemplate() { const textValue=document.querySelector('#vkTemplateText').value.trim(), nameValue=document.querySelector('#vkTemplateName').value.trim() || 'Шаблон VK'; if(!textValue){document.querySelector('#vkError').textContent='Введите текст шаблона';return;} const response=await fetch('/api/admin/vk/templates',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:nameValue,text:textValue,active:true})}), data=await response.json(); if(!response.ok){document.querySelector('#vkError').textContent=data.error||'Не удалось создать шаблон';return;} document.querySelector('#vkTemplateText').value=''; document.querySelector('#vkTemplateName').value=''; updateVkTemplateCount(); await loadVk(); document.querySelector('#vkTemplate').value=String(data.id); updateVkTemplatePreview(); document.querySelector('#vkError').textContent='Шаблон сохранён и выбран для расписания.'; }
function updateVkTemplateCount() { document.querySelector('#vkTemplateCount').textContent=`${document.querySelector('#vkTemplateText').value.length} / 4096`; }
async function createVkSchedule() { const times=document.querySelector('#vkTimes').value.split(',').map(value=>value.trim()).filter(Boolean), weekdays=[...document.querySelectorAll('.weekday-options input:checked')].map(input=>Number(input.value)); const payload={peer_id:Number(document.querySelector('#vkConversation').value),template_id:Number(document.querySelector('#vkTemplate').value),times,weekdays,starts_on:document.querySelector('#vkStartsOn').value||null,ends_on:document.querySelector('#vkEndsOn').value||null,active:false}; const response=await fetch('/api/admin/vk/schedules',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); if(!response.ok){const data=await response.json();document.querySelector('#vkError').textContent=data.error||'Не удалось создать расписание';return;} document.querySelector('#vkTimes').value=''; loadVk(); }
// Extracts the primary person identity from a stored report payload.
function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; }
// Normalizes primary and additional kitten fields into one display list.
function kittenEntries(input) {
const entries = [];
if (input.kitten_name || input.kitten_id) entries.push({name: input.kitten_name || 'Котёнок', id: input.kitten_id || ''});
(input.extra_kittens || []).forEach(item => entries.push({name: item.name || item[0] || 'Котёнок', id: item.id || item[1] || ''}));
return entries;
}
// Renders a person identity cell with name and optional ID.
function personCell(person) { const node = document.createElement('td'); node.className = 'person'; const strong = document.createElement('strong'); strong.textContent = person.name || '—'; const small = document.createElement('span'); small.textContent = person.id ? `[${person.id}]` : 'ID не указан'; node.append(strong, small); return node; }
// Builds a thumbnail cell and connects images to the gallery viewer.
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); });
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.
function displayDate(value) { const text = String(value || ''); if (!text) return '—'; const normalized = text.includes('T') ? text : text.replace(' ', 'T'); const instant = new Date(/[zZ]|[+-]\d\d:\d\d$/.test(normalized) ? normalized : `${normalized}Z`); return Number.isNaN(instant.valueOf()) ? text : new Intl.DateTimeFormat('ru-RU', {timeZone: 'Europe/Moscow', dateStyle: 'short', timeStyle: 'medium'}).format(instant); }
// Produces the normalized value used by the selected table sort column.
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; }
// Maps an input payload to the report category used by tabs and filters.
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'; }
// Applies active category/person filters and returns sorted reports.
function queryFor(period, dateFrom, dateTo, extra = {}) { const query = new URLSearchParams({...extra, period: period.value}); if (dateFrom.value || dateTo.value) { query.set('date_from', dateFrom.value); query.set('date_to', dateTo.value); } return query; }
function syncReportsExport() { document.querySelector('#reportsExport').href = `/api/admin/calculations.xlsx?${queryFor(reportPeriod, reportDateFrom, reportDateTo, {category: activeCategory, cat: catFilter.value, kitten: kittenFilter.value})}`; }
function syncApplicationsExport() { document.querySelector('#applicationsExport').href = `/api/admin/applications.xlsx?${queryFor(applicationPeriod, applicationDateFrom, applicationDateTo, {status: activeApplicationStatus})}`; }
function filteredItems() { return items.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; }); }
// Rebuilds cat and kitten filter options from loaded records.
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; }
// Re-renders the report table, including empty and filtered states.
function render() { syncReportsExport(); rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.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 = displayDate(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 = queryFor(reportPeriod, reportDateFrom, reportDateTo, {sort: 'escort_name', direction: 'asc', limit: '500', category: activeCategory, cat: catFilter.value, kitten: kittenFilter.value}); 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; } }
// Loads report history from the admin API and refreshes filters/table.
const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'};
// 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)} }
// 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; } }
// 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.
async function restoreAdminSession() { try { const response = await fetch('/api/admin/session'); const data = await response.json(); if (data.authenticated) await openAdmin(); } catch (_) {} }
// 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', ''); }
// Closes the photo gallery dialog.
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
// 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(); }));
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);
document.querySelector('#vkTemplate').addEventListener('change', updateVkTemplatePreview); document.querySelector('#vkTemplateText').addEventListener('input', updateVkTemplateCount);
restoreAdminSession();
</script>
</body>
</html>