Polish Russian website and VK bot copy for CatWar players

This commit is contained in:
nyan404 committed 2026-10-18 19:09:48 +03:00
1 parent 3ebab303a5
commit 955f47ccd6
11 files changed
+105 -100

No files matched your search

+8 -8
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Беличья нора — админка</title>
<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: #f5efe3; color: #2d2924; --ink:#2d2924; --muted:#675c50; --line:#ded3c2; --paper:#fffdf7; --accent:#b56824; --gold:#d89a28; --danger:#8e3630; --focus:#a9541d; }
@@ -124,7 +124,7 @@
<section id="appView" class="hidden">
<header class="topbar">
<div><h1>Админская панель</h1><p class="intro">Расчёты и обращения из VK-бота и веб-формы.</p></div>
<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>
@@ -157,11 +157,11 @@
<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-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>
<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">Укажите время через запятую, например 09:00, 18:30</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>
@@ -235,12 +235,12 @@
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 pointsCell(item) { const cell = document.createElement('td'); cell.className = 'points-cell'; const result = item.result || {}; if (item.mode !== 'inspection' || result.points === undefined) { cell.textContent = '—'; return cell; } const details = document.createElement('div'); details.className = 'points-details'; const grouped = new Map(); (result.resource_points || []).forEach(resource => { const name = resource.name || resource[0] || 'Ресурс'; const amount = Number(resource.amount ?? resource[1] ?? 0); const points = Number(resource.points ?? resource[2] ?? 0); const key = name.trim().replace(/\s+/g, ' ').toLocaleLowerCase('ru-RU'); const current = grouped.get(key) || {name, amount: 0, points: 0}; current.amount += amount; current.points += points; grouped.set(key, current); }); const resourceTotal = [...grouped.values()].reduce((sum, resource) => sum + resource.points, 0); const resourceHeader = document.createElement('strong'); resourceHeader.textContent = `Итого по ресурсам: ${resourceTotal}`; details.append(resourceHeader); grouped.forEach(resource => { const perItem = resource.amount ? resource.points / resource.amount : 0; const line = document.createElement('span'); line.textContent = `${resource.name} ×${resource.amount}: ${resource.points} (${perItem}Б)`; details.append(line); }); if (result.inspection_points !== undefined) { const base = document.createElement('span'); base.textContent = `Баллы осмотра: ${result.inspection_points}`; details.append(base); } const total = document.createElement('strong'); total.textContent = `Всего: ${result.points}`; details.append(total); cell.append(details); return cell; }
// 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 = 9; 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; })(), pointsCell(item)); 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); }); }
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 = 9; 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; })(), pointsCell(item)); 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: 'created_at', direction: 'desc', 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; }
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.
+3 -3
View File
@@ -21,16 +21,16 @@
</head>
<body><main>
<nav class="topnav"><a class="brand" href="/belki">Беличья нора</a><a href="/belki">Калькулятор отчётов</a></nav>
<section id="app"><h1>Новая заявка</h1><p class="intro">Заполните форму — администратор получит структурированную заявку для рассмотрения. Не нужно готовить форумную отпись.</p>
<section id="app"><h1>Новая заявка</h1><p class="intro">Заполните форму, и администратор получит заявку. Готовить форумную отпись не нужно.</p>
<div class="types" role="radiogroup" aria-label="Тип заявки">
<button class="type active" type="button" data-type="feather_donation">Пожертвовать перо отряду</button><button class="type" type="button" data-type="kitten">Хочу стать бельчонком</button><button class="type" type="button" data-type="flying_squirrel">Хочу стать белкой-летягой</button><button class="type" type="button" data-type="curator">Хочу стать куратором</button>
</div>
<form id="form" class="panel"><div class="grid">
<label>Имя персонажа<input name="name" required></label><label>ID персонажа<input name="character_id" type="number" min="1" required></label>
<label>Имя кота<input name="name" required></label><label>ID кота<input name="character_id" type="number" min="1" required></label>
<label id="vkField" class="wide">Ссылка на страницу VK <span class="hint">(необязательно)</span><input name="vk_link" type="text" inputmode="url" placeholder="vk.com/id… или vk.ru/id…"></label>
<section id="kittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Перетащите изображение сюда или выберите файл</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="curatorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="flyingFields" class="wide hidden"><label>Сдавали практику ранее?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="practiceLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/... или https://vk.com/... "></label></section>
<section id="flyingFields" class="wide hidden"><label>Уже сдавали практику?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="practiceLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/... или https://vk.com/... "></label></section>
<section id="featherFields" class="wide"><h2>Перья для казны</h2><p class="hint">Укажите цвет, количество и откуда получены перья.</p><div id="feathers"></div><button id="addFeather" class="secondary" type="button">Добавить перо</button></section>
</div><p id="error" class="error" role="alert"></p><div class="actions"><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden"></div>
</section>
+28 -28
View File
@@ -103,7 +103,7 @@
<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>
<h1>Генератор отчётов и калькулятор</h1>
<p class="muted">Отчёты и заявки — в одном месте.</p>
<p class="muted">Здесь можно подготовить отчёт, посчитать баллы и подать заявку.</p>
<nav class="tabs section-tabs" role="tablist" aria-label="Раздел Беличьей норы">
<button class="active" id="reportsTab" type="button" role="tab" aria-selected="true" aria-controls="reportsSection" data-section="reports">Отчёты</button>
@@ -113,7 +113,7 @@
</nav>
<section id="reportsSection" role="tabpanel" aria-labelledby="reportsTab">
<p class="muted">Один заход — один отчёт. Скриншот нужен только для осмотра; прикрепите его перед формированием сообщения.</p>
<p class="muted">На каждый заход нужен отдельный отчёт. Для осмотра прикрепите скриншот перед подготовкой сообщения. Для других отчётов он не нужен.</p>
<div class="tabs" role="tablist" aria-label="Вид отчёта">
<button class="active" data-mode="coaching">Прокачка ЛУ/ЗУ</button>
<button data-mode="training">Тренировка</button>
@@ -125,7 +125,7 @@
<section class="panel">
<div class="bulk">
<strong>Быстрый ввод</strong>
<p class="muted">Вставьте данные одной строкой — символы <code>|</code> не нужны. Мы распознаем заполненные поля и подскажем, что ещё указать.</p>
<p class="muted">Вставьте данные одной строкой без разделителей <code>|</code>. Калькулятор заполнит поля и подскажет, чего не хватает.</p>
<textarea id="bulkText" placeholder="15 августа, 11:00–11:20, Дикая Вишня 1604614, Серолап 1617140"></textarea>
<button type="button" id="inspectBulk">Распознать данные</button>
<p class="muted bulk-status" id="bulkStatus"></p>
@@ -161,9 +161,9 @@
</div>
<div id="inspection" class="grid mode hidden">
<label>Имя персонажа<input name="character_name"></label>
<label>ID персонажа<input name="character_id" type="number" min="1"></label>
<div class="wide identity-tools"><button type="button" id="resolveIdentity">Найти связку имени и ID</button><span class="muted" id="identityStatus"></span></div>
<label>Имя кота<input name="character_name"></label>
<label>ID кота<input name="character_id" type="number" min="1"></label>
<div class="wide identity-tools"><button type="button" id="resolveIdentity">Найти имя или ID</button><span class="muted" id="identityStatus"></span></div>
<label>Место<select name="place"><option>дупло</option><option>расщелина</option></select></label>
<label>Количество осмотров<input name="inspections" type="number" min="0" value="0"></label>
<label class="wide">Ресурсы, по одному на строку: +количество название<br>
@@ -172,7 +172,7 @@
</div>
<div id="goal" class="grid mode hidden">
<p class="wide muted">Посчитайте прогресс без заполнения отчёта: укажите текущие и целевые баллы, а также длительность одного захода.</p>
<p class="wide muted">Чтобы узнать, сколько осталось до цели, укажите текущие и нужные баллы, а также длительность захода. Заполнять отчёт не нужно.</p>
<label>Текущие баллы<input name="current_points" type="number" min="0" step="0.01" value="0"></label>
<label>Целевые баллы<input name="target_points" type="number" min="0" step="0.01" value="25"></label>
<label>Минут в одном заходе<input name="minutes_per_session" type="number" min="1" value="20"></label>
@@ -182,7 +182,7 @@
</div>
<div id="points" class="grid mode hidden">
<p class="wide muted">Выберите занятие и его условия — без данных отчёта. Калькулятор покажет начисленные баллы.</p>
<p class="wide muted">Выберите занятие и укажите его условия, чтобы посчитать баллы. Заполнять отчёт не нужно.</p>
<label>Занятие<select name="activity" id="pointsActivity"><option value="coaching">Прокачка ЛУ/ЗУ</option><option value="training">Тренировка</option><option value="inspection">Осмотр</option></select></label>
<div id="pointsCoaching" class="wide grid">
<label>Навык<select name="skill"><option>ЛУ</option><option>ЗУ</option></select></label>
@@ -204,21 +204,21 @@
<div id="profileSection" class="panel hidden" style="margin-top: 16px;">
<strong>Ваш профиль</strong>
<div class="grid">
<label>Имя персонажа<input id="profileName"></label>
<label>ID персонажа<input id="profileId" type="number" min="1"></label>
<label>Имя кота<input id="profileName"></label>
<label>ID кота<input id="profileId" type="number" min="1"></label>
</div>
<div class="actions">
<button type="button" id="saveProfileBtn">Сохранить профиль</button>
<button type="button" id="clearProfileBtn" class="muted" style="background:transparent;border-color:#bdb6ad;">Очистить</button>
</div>
<p class="muted">Профиль будет автоматически подставляться в поля при создании отчётов.</p>
<p class="muted">Имя и ID из профиля будут подставляться в новые отчёты.</p>
</div>
<dialog id="confirmDialog">
<h3 style="margin-top:0">Подтверждение</h3>
<div id="confirmPreview" style="white-space:pre-wrap;background:#f8f5f0;padding:12px;border-radius:8px;border:1px solid #ded9d1;max-height:40vh;overflow-y:auto;margin-bottom:12px;"></div>
<div style="display:flex;gap:10px;">
<button type="button" id="confirmYes" class="primary">Да, сформировать</button>
<button type="button" id="confirmYes" class="primary">Да, подготовить</button>
<button type="button" id="confirmNo">Отмена</button>
</div>
</dialog>
@@ -245,7 +245,7 @@
<section id="applicationsSection" class="hidden" role="tabpanel" aria-labelledby="applicationsTab">
<div id="applicationWorkspace">
<h2>Новая заявка</h2>
<p class="muted application-intro">Заполните форму — администратор получит структурированную заявку для рассмотрения. Форумную отпись готовить не нужно.</p>
<p class="muted application-intro">Заполните форму, и администратор получит заявку. Готовить форумную отпись не нужно.</p>
<div class="application-types" role="group" aria-label="Тип заявки">
<button class="application-type" type="button" aria-pressed="true" data-application-type="feather_donation">Пожертвовать перо отряду</button>
<button class="application-type" type="button" aria-pressed="false" data-application-type="kitten">Хочу стать бельчонком</button>
@@ -254,13 +254,13 @@
</div>
<form id="applicationForm" class="panel">
<div class="grid">
<label>Имя персонажа<input name="name" required></label>
<label>ID персонажа<input name="character_id" type="number" min="1" inputmode="numeric" required></label>
<label>Имя кота<input name="name" required></label>
<label>ID кота<input name="character_id" type="number" min="1" inputmode="numeric" required></label>
<label id="applicationVkField" class="wide hidden">Ссылка на страницу VK <span class="muted">(необязательно)</span><input name="vk_link" type="text" inputmode="url" placeholder="vk.com/id… или vk.ru/id…"></label>
<section id="applicationKittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Выберите или перетащите изображение</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="applicationCuratorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="applicationFlyingFields" class="wide hidden"><label>Сдавали практику ранее?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="applicationPracticeLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/… или https://vk.com/…"></label></section>
<section id="applicationFeatherFields" class="wide"><h2>Перья для казны</h2><p class="muted">Укажите количество, цвет и источник добычи.</p><div id="applicationFeathers"></div><button id="applicationAddFeather" type="button">Добавить перо</button></section>
<section id="applicationFlyingFields" class="wide hidden"><label>Уже сдавали практику?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="applicationPracticeLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/… или https://vk.com/…"></label></section>
<section id="applicationFeatherFields" class="wide"><h2>Перья для казны</h2><p class="muted">Укажите количество и цвет перьев, а также откуда они получены.</p><div id="applicationFeathers"></div><button id="applicationAddFeather" type="button">Добавить перо</button></section>
</div>
<p id="applicationError" class="error" role="alert"></p>
<div class="actions"><button class="primary" id="applicationSubmit" type="submit">Отправить заявку</button></div>
@@ -271,7 +271,7 @@
<section id="identitySection" class="hidden" role="tabpanel" aria-labelledby="identityTab">
<div id="identityWorkspace">
<h2>Изменить имя кота</h2>
<p class="muted">Укажите ID из существующей связки, проверьте текущее имя и сохраните новое.</p>
<p class="muted">Введите ID кота, чьё имя уже сохранено. Проверьте текущее имя и укажите новое.</p>
<form id="renameIdentityForm" class="panel">
<div class="grid">
<label>ID кота<input id="renameIdentityId" name="character_id" type="number" min="1" inputmode="numeric" required></label>
@@ -292,9 +292,9 @@
</main>
<dialog id="identityDialog">
<p id="identityDialogText"></p>
<label id="identityMissingLabel">Недостающее значение<input id="identityMissingValue"></label>
<p class="muted">Связка будет использована только для текущего расчёта.</p>
<button type="button" id="saveIdentity">Добавить связку</button>
<label id="identityMissingLabel">Имя или ID, которого не хватает<input id="identityMissingValue"></label>
<p class="muted">Эти имя и ID будут использованы только в текущем расчёте.</p>
<button type="button" id="saveIdentity">Добавить имя и ID</button>
<button type="button" id="closeIdentityDialog">Понятно</button>
</dialog>
<script>
@@ -427,14 +427,14 @@
const characterId = document.querySelector('#inspection [name="character_id"]').value.trim();
const response = await fetch('/api/resolve-identity', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name, character_id: characterId}) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Не удалось проверить связку');
if (!response.ok) throw new Error(data.error || 'Не удалось найти имя или ID');
if (data.status === 'found') {
setField('inspection', 'character_name', data.name);
setField('inspection', 'character_id', data.character_id);
identityStatus.textContent = 'Связка найдена и подставлена.';
identityStatus.textContent = 'Имя и ID найдены, поля заполнены.';
} else {
identityDialogText.textContent = data.message;
const missing = name ? 'ID персонажа' : 'Имя персонажа';
const missing = name ? 'ID кота' : 'Имя кота';
identityMissingLabel.firstChild.textContent = `Введите ${missing}`;
identityMissingValue.value = '';
identityMissingValue.type = name ? 'number' : 'text';
@@ -448,12 +448,12 @@
const idField = document.querySelector('#inspection [name="character_id"]');
const name = nameField.value.trim() || (identityMissingValue.type === 'text' ? identityMissingValue.value.trim() : '');
const characterId = idField.value.trim() || (identityMissingValue.type === 'number' ? identityMissingValue.value.trim() : '');
if (!name || !characterId) { identityDialogText.textContent = 'Нужно указать и имя, и ID персонажа.'; return; }
if (!name || !characterId) { identityDialogText.textContent = 'Нужно указать и имя, и ID кота.'; return; }
const response = await fetch('/api/resolve-identity', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name, character_id: characterId, remember: true}) });
const data = await response.json();
if (!response.ok) { identityDialogText.textContent = data.error || 'Не удалось сохранить связку'; return; }
if (!response.ok) { identityDialogText.textContent = data.error || 'Не удалось сохранить имя и ID'; return; }
setField('inspection', 'character_name', data.name); setField('inspection', 'character_id', data.character_id);
identityDialog.close(); identityStatus.textContent = 'Связка добавлена в текущий процесс.';
identityDialog.close(); identityStatus.textContent = 'Имя и ID добавлены в текущий расчёт.';
});
document.querySelector('#closeIdentityDialog').addEventListener('click', () => identityDialog.close());
// Serializes the active calculator form into the API payload shape.
@@ -670,7 +670,7 @@
try {
const response = await fetch('/api/resolve-identity', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({character_id: characterId})});
const data = await response.json();
if (!response.ok || data.status !== 'found') throw new Error(data.error || data.message || 'Связка с таким ID не найдена.');
if (!response.ok || data.status !== 'found') throw new Error(data.error || data.message || 'Для этого ID нет сохранённого имени.');
renameIdentityCurrentName.value = data.name;
renameIdentityId.value = data.character_id;
renameIdentityLookupStatus.textContent = `Текущее имя: «${data.name}».`;
+2 -2
View File
@@ -69,8 +69,8 @@
<body>
<div class="content">
<h1>Привет! 🐱</h1>
<p>Здесь хранятся необходимые файлы для работы скриптов CatWar.</p>
<p>👀 Глазами тут смотреть нечего, но если интересуют исходники - добро пожаловать!</p>
<p>Здесь хранятся файлы для работы скриптов CatWar.</p>
<p>👀 Хотите посмотреть исходники? Ссылка ниже.</p>
<div class="links">
<p><i class="fas fa-code emoji"></i><a href="https://git.nyan404.ru/nyan404/cwshed-clone" target="_blank">Исходный код проекта</a></p>