Files
cwshed-clone/web/calculator.html
T

470 lines
35 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; --ink:#292725; --muted:#625d57; --paper:#fffdfa; --ground:#f4f1eb; --line:#ded9d1; --accent:#9a542e; --focus:#9a542e; --error:#8e3630; }
* { box-sizing: border-box; } body { margin: 0; background: var(--ground); color: var(--ink); }
main { width: min(1060px, calc(100% - 32px)); margin: 48px auto 72px; }
h1 { margin: 0 0 6px; font: 500 clamp(2.25rem, 5vw, 4rem)/1 Georgia, "Times New Roman", serif; letter-spacing: -.045em; }
h2 { font: 500 1.55rem/1.15 Georgia, "Times New Roman", serif; } .muted { color: var(--muted); line-height: 1.55; }
.tabs { display: flex; gap: 8px; flex-wrap: wrap; margin: 24px 0 16px; }
.section-tabs { margin-top: 32px; border-bottom: 1px solid var(--line); padding-bottom: 16px; }
.section-tabs button { border-color: transparent; background: transparent; }
button, select, input, textarea { font: inherit; }
button { min-height:44px; cursor: pointer; border: 1px solid #bdb6ad; border-radius: 7px; padding: 9px 14px; background: var(--paper); color: var(--ink); transition: background-color 160ms ease-out, border-color 160ms ease-out, color 160ms ease-out; }
button:hover { border-color:var(--accent); background:#fff8ef; } button:focus-visible, a:focus-visible { outline:3px solid var(--focus); outline-offset:3px; }
button.active, button.primary { background: var(--ink); color: #fffdfa; border-color: var(--ink); } button.active:hover, button.primary:hover { background:#45413d; }
.panel { background: var(--paper); border: 1px solid var(--line); border-radius: 10px; padding: 28px; box-shadow:0 10px 28px #3b30220d; }
.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
label { display: grid; gap: 6px; color: #403b36; font-weight:700; }
input, select, textarea { min-height:44px; width: 100%; border: 1px solid #c8c1b8; border-radius: 7px; padding: 9px 12px; background: #fff; color: var(--ink); } input:focus,select:focus,textarea:focus { outline:3px solid #9a542e2b; border-color:var(--accent); }
textarea { min-height: 210px; resize: vertical; }
.wide { grid-column: 1 / -1; }
.actions { display: flex; gap: 10px; margin-top: 18px; }
.quick-actions { display: flex; gap: 6px; margin-top: 4px; flex-wrap: wrap; }
.quick-actions button { padding: 4px 10px; font-size: 0.85em; border-width: 1px; }
.bulk { margin-bottom: 28px; padding-bottom: 24px; border-bottom: 1px solid var(--line); }
.bulk textarea { min-height: 100px; margin: 8px 0; }
.bulk-status { white-space: pre-wrap; }
.identity-tools { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.extra-kittens { display: grid; gap: 8px; }
.extra-kitten { display: grid; grid-template-columns: 1fr 140px 180px auto; gap: 8px; align-items: end; }
.status-help { margin: -4px 0 0; font-size: .85rem; }
@media (max-width: 700px) { .extra-kitten { grid-template-columns: 1fr; } }
dialog { max-width: min(520px, calc(100% - 32px)); background: var(--paper); color: var(--ink); border: 1px solid #5a524b; border-radius: 10px; padding: 24px; box-shadow:0 24px 80px #211b1855; }
dialog::backdrop { background: #211b1866; }
.result { margin-top: 20px; }
.hidden { display: none; }
.error { color: var(--error); font-weight:700; white-space: pre-wrap; }
.auth-panel { max-width: 460px; margin: 12vh auto; }
.auth-panel form { display: grid; gap: 12px; }
.application-intro { max-width: 68ch; margin: 0 0 24px; }
.application-types { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin: 20px 0; }
.application-type { min-height: 68px; text-align: left; font-weight: 700; }
.application-type[aria-pressed="true"] { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); background: #fff8ef; }
.upload { display: grid; justify-items: center; gap: 8px; min-height: 132px; padding: 20px; text-align: center; border: 1px dashed #b9afa4; border-radius: 7px; background: #fffaf4; color: var(--muted); cursor: pointer; }
.upload strong { color: var(--ink); } .upload input { display: none; }
.files { margin: 10px 0 0; padding-left: 18px; color: var(--muted); }
.feather { display: grid; grid-template-columns: 110px 1fr 1.3fr auto; gap: 9px; align-items: end; margin-bottom: 9px; }
.remove { color: var(--error); border-color: #d9aaa5; }
.success { margin-top: 20px; padding: 16px; border-left: 4px solid #527739; background: #f3f8ed; color: #304a22; border-radius: 7px; }
@media (prefers-reduced-motion: reduce) { *,*::before,*::after { transition-duration:.01ms!important; } }
@media (max-width: 700px) { main { margin:28px auto 48px; } .panel{padding:20px}.grid,.application-types,.feather { grid-template-columns: 1fr; } .wide { grid-column: auto; }.actions{flex-direction:column}.actions button{width:100%;} }
</style>
</head>
<body>
<main>
<h1>Беличья нора — калькулятор отчётов</h1>
<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>
<button id="applicationsTab" type="button" role="tab" aria-selected="false" aria-controls="applicationsSection" data-section="applications">Заявки</button>
</nav>
<section id="reportsSection" role="tabpanel" aria-labelledby="reportsTab">
<p class="muted">Один заход — один отчёт. Скриншоты к готовому отчёту нужно приложить вручную.</p>
<div class="tabs" role="tablist" aria-label="Вид отчёта">
<button class="active" data-mode="coaching">Прокачка ЛУ/ЗУ</button>
<button data-mode="training">Тренировка</button>
<button data-mode="inspection">Осмотры</button>
</div>
<section class="panel">
<div class="bulk">
<strong>Быстрый ввод</strong>
<p class="muted">Вставьте данные одной строкой — символы <code>|</code> не нужны. Мы распознаем заполненные поля и подскажем, что ещё указать.</p>
<textarea id="bulkText" placeholder="15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140"></textarea>
<button type="button" id="inspectBulk">Распознать данные</button>
<p class="muted bulk-status" id="bulkStatus"></p>
</div>
<form id="form">
<div id="coaching" class="grid mode">
<label>Дата<input name="date" value="15.08" required>
<div class="quick-actions"><button type="button" id="todayBtn" class="quick-btn">Сегодня</button></div>
</label>
<label>Навык<select name="skill"><option>ЛУ</option><option>ЗУ</option></select></label>
<label>Начало<input name="start" type="time" value="11:00" required></label>
<label>Конец<input name="end" type="time" value="11:20" required></label>
<label>Имя сопровождающего<input name="escort_name" required></label>
<label>ID сопровождающего<input name="escort_id" type="number" min="1" required></label>
<label>Имя котёнка<input name="kitten_name" required></label>
<label>ID котёнка<input name="kitten_id" type="number" min="1" required></label>
<label>Котёнок<select name="kitten_independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select><span class="muted status-help" id="statusHelp">Для ЛУ можно указать не более одного несамостоятельного котёнка.</span></label>
<div class="wide extra-kittens">
<label>Дополнительные котята <span class="muted">(общие баллы не суммируются; 2-й ×1,5, следующие ×1,15)</span></label>
<div id="extraKittens"></div>
<button type="button" id="addKitten">Добавить котёнка</button>
</div>
</div>
<div id="training" class="grid mode hidden">
<label>Имя сопровождающего<input name="escort_name"></label>
<label>ID сопровождающего<input name="escort_id" type="number" min="1"></label>
<label>Имя котёнка<input name="kitten_name"></label>
<label>ID котёнка<input name="kitten_id" type="number" min="1"></label>
</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>Место<select name="place"><option>дупло</option><option>расщелина</option></select></label>
<label>Количество осмотров<input name="inspections" type="number" min="0" value="0"></label>
<label class="wide">Ресурсы, по одному на строку: название; количество<br>
<div class="quick-actions"><button type="button" id="noResourcesBtn" class="quick-btn">Без ресурсов</button></div>
<textarea name="resources" placeholder="вьюнок; 2&#10;паук; 1"></textarea></label>
</div>
<label class="wide">Скриншоты отчёта<input id="screenshots" type="file" accept="image/*" multiple><span class="muted">Можно выбрать несколько фотографий. Они будут загружены на img.nyan404.ru.</span></label>
<div class="actions"><button class="primary" type="submit">Подготовить сообщение</button><button type="button" id="copy" disabled>Скопировать</button></div>
</form>
<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>
</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>
</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="confirmNo">Отмена</button>
</div>
</dialog>
<div class="result hidden" id="result"><h2>Сообщение</h2><textarea id="message" readonly></textarea><p class="muted" id="summary"></p></div>
<p class="error" id="error"></p>
</section>
</section>
<section id="applicationsSection" class="hidden" role="tabpanel" aria-labelledby="applicationsTab">
<div id="applicationWorkspace">
<h2>Новая заявка</h2>
<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>
<button class="application-type" type="button" aria-pressed="false" data-application-type="flying_squirrel">Хочу стать белкой-летягой</button>
<button class="application-type" type="button" aria-pressed="false" data-application-type="curator">Хочу стать куратором</button>
</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 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, JPG или JPEG до 15 МБ</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg" multiple></span></label><ul class="files"></ul></section>
<section id="applicationCuratorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>Нужен хотя бы один файл</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg" 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>
</div>
<p id="applicationError" class="error" role="alert"></p>
<div class="actions"><button class="primary" id="applicationSubmit" type="submit">Отправить заявку</button></div>
</form>
<div id="applicationSuccess" class="success hidden" role="status" aria-live="polite"></div>
</div>
</section>
</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>
<button type="button" id="closeIdentityDialog">Понятно</button>
</dialog>
<script>
const form = document.querySelector('#form');
const error = document.querySelector('#error');
const result = document.querySelector('#result');
const message = document.querySelector('#message');
const summary = document.querySelector('#summary');
const copy = document.querySelector('#copy');
const screenshots = document.querySelector('#screenshots');
const bulkText = document.querySelector('#bulkText');
const bulkStatus = document.querySelector('#bulkStatus');
const bulk = document.querySelector('.bulk');
const identityStatus = document.querySelector('#identityStatus');
const identityDialog = document.querySelector('#identityDialog');
const identityDialogText = document.querySelector('#identityDialogText');
const identityMissingLabel = document.querySelector('#identityMissingLabel');
const identityMissingValue = document.querySelector('#identityMissingValue');
let mode = 'coaching';
const extraKittens = document.querySelector('#extraKittens');
const statusHelp = document.querySelector('#statusHelp');
function addExtraKitten(values = {}) {
const row = document.createElement('div'); row.className = 'extra-kitten';
row.innerHTML = `<input data-extra="name" placeholder="Имя котёнка" required>
<input data-extra="id" type="number" min="1" placeholder="ID" required>
<select data-extra="independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select>
<button type="button" data-remove>Удалить</button>`;
row.querySelector('[data-extra="name"]').value = values.name || '';
row.querySelector('[data-extra="id"]').value = values.id || '';
row.querySelector('[data-extra="independence"]').value = values.independence || 'самостоятельно';
row.querySelector('[data-extra="independence"]').addEventListener('change', updateStatusRules);
row.querySelector('[data-remove]').addEventListener('click', () => row.remove());
extraKittens.append(row);
}
document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten());
function statusFields() { return [document.querySelector('#coaching [name="kitten_independence"]'), ...extraKittens.querySelectorAll('[data-extra="independence"]')]; }
function updateStatusRules(event) {
const fields = statusFields();
const isZu = document.querySelector('#coaching [name="skill"]').value === 'ЗУ';
if (isZu) {
fields.forEach(field => { field.value = 'самостоятельно'; field.disabled = true; });
statusHelp.textContent = 'Для ЗУ все котята должны быть самостоятельными.';
} else {
fields.forEach(field => { field.disabled = false; });
statusHelp.textContent = 'Для ЛУ можно указать не более одного несамостоятельного котёнка.';
}
}
function validateStatusRules() {
const fields = statusFields();
const skill = document.querySelector('#coaching [name="skill"]').value;
if (skill === 'ЗУ' && new Set(fields.map(field => field.value)).size > 1) return 'Для ЗУ статус всех котят должен совпадать.';
if (skill === 'ЛУ' && fields.filter(field => field.value === 'несамостоятельно').length > 1) return 'Для ЛУ допускается только один несамостоятельный котёнок.';
return '';
}
function selectMode(nextMode) {
mode = nextMode;
document.querySelectorAll('[data-mode]').forEach(item => item.classList.toggle('active', item.dataset.mode === mode));
document.querySelectorAll('.mode').forEach(panel => panel.classList.toggle('hidden', panel.id !== mode));
bulk.classList.toggle('hidden', mode !== 'coaching');
if (mode !== 'coaching') bulkStatus.textContent = '';
error.textContent = '';
}
document.querySelectorAll('[data-mode]').forEach(button => button.addEventListener('click', () => selectMode(button.dataset.mode)));
document.querySelector('#coaching [name="skill"]').addEventListener('change', updateStatusRules);
document.querySelector('#coaching [name="kitten_independence"]').addEventListener('change', updateStatusRules);
function setField(panel, name, value) {
const field = document.querySelector(`#${panel} [name="${name}"]`);
if (field && value !== undefined && value !== null) field.value = value;
}
document.querySelector('#inspectBulk').addEventListener('click', async () => {
bulkStatus.textContent = '';
try {
const response = await fetch('/api/inspect-bulk', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({text: bulkText.value}) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Не удалось распознать данные');
const fields = data.fields || {};
if (fields.mode) selectMode(fields.mode);
const target = fields.mode || mode;
Object.entries(fields).forEach(([key, value]) => {
if (['mode', 'raw', 'resources'].includes(key)) return;
setField(target, key, value);
});
if (fields.resources) setField(target, 'resources', fields.resources.map(item => `${item[0]}; ${item[1]}`).join('\n'));
(fields.extra_kittens || []).forEach(item => addExtraKitten({name: item[0], id: item[1], independence: item[2]}));
updateStatusRules();
bulkStatus.textContent = data.status === 'complete'
? 'Данные распознаны. Проверьте поля и нажмите «Подготовить сообщение».'
: `Нужно уточнить:\n${(data.questions || []).join('\n')}`;
} catch (err) { bulkStatus.textContent = err.message; }
});
document.querySelector('#resolveIdentity').addEventListener('click', async () => {
identityStatus.textContent = '';
try {
const name = document.querySelector('#inspection [name="character_name"]').value.trim();
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 (data.status === 'found') {
setField('inspection', 'character_name', data.name);
setField('inspection', 'character_id', data.character_id);
identityStatus.textContent = 'Связка найдена и подставлена.';
} else {
identityDialogText.textContent = data.message;
const missing = name ? 'ID персонажа' : 'Имя персонажа';
identityMissingLabel.firstChild.textContent = `Введите ${missing}`;
identityMissingValue.value = '';
identityMissingValue.type = name ? 'number' : 'text';
if (identityDialog.showModal) identityDialog.showModal();
else window.alert(data.message);
}
} catch (err) { identityStatus.textContent = err.message; }
});
document.querySelector('#saveIdentity').addEventListener('click', async () => {
const nameField = document.querySelector('#inspection [name="character_name"]');
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; }
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; }
setField('inspection', 'character_name', data.name); setField('inspection', 'character_id', data.character_id);
identityDialog.close(); identityStatus.textContent = 'Связка добавлена в текущий процесс.';
});
document.querySelector('#closeIdentityDialog').addEventListener('click', () => identityDialog.close());
function payload() {
const data = {};
document.querySelectorAll(`#${mode} [name]`).forEach(field => { data[field.name] = field.value; });
data.mode = mode;
['escort_id', 'kitten_id', 'character_id', 'inspections'].forEach(key => { if (data[key] !== undefined && data[key] !== '') data[key] = Number(data[key]); });
if (mode === 'inspection') {
data.resources = (data.resources || '').split('\n').map(line => line.trim()).filter(Boolean).map(line => {
const [name, amount] = line.split(';').map(item => item.trim());
return [name, Number(amount)];
});
}
if (mode === 'coaching') {
data.extra_kittens = [...extraKittens.querySelectorAll('.extra-kitten')].map(row => ({
name: row.querySelector('[data-extra="name"]').value.trim(),
id: Number(row.querySelector('[data-extra="id"]').value),
independence: row.querySelector('[data-extra="independence"]').value,
}));
}
return data;
}
async function uploadScreenshots() {
const files = [...(screenshots.files || [])];
const uploaded = [];
for (const file of files) {
const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
const response = await fetch('/api/web/upload', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name: file.name, type: file.type, data})});
const result = await response.json();
if (!response.ok) throw new Error(result.error || `Не удалось загрузить ${file.name}`);
uploaded.push({type: 'photo', url: result.url, name: file.name});
}
return uploaded;
}
form.addEventListener('submit', async event => {
event.preventDefault(); error.textContent = '';
try {
if (mode === 'coaching') {
const statusError = validateStatusRules();
if (statusError) throw new Error(statusError);
}
const reportPayload = payload();
reportPayload.attachments = await uploadScreenshots();
const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(reportPayload) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');
message.value = data.message; summary.textContent = data.result ? `Результат: ${JSON.stringify(data.result)}` : '';
result.classList.remove('hidden'); copy.disabled = false;
} catch (err) { error.textContent = err.message; }
});
copy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); copy.textContent = 'Скопировано'; setTimeout(() => copy.textContent = 'Скопировать', 1500); });
const reportsSection = document.querySelector('#reportsSection');
const applicationsSection = document.querySelector('#applicationsSection');
const sectionTabs = [...document.querySelectorAll('[data-section]')];
const applicationForm = document.querySelector('#applicationForm');
const applicationError = document.querySelector('#applicationError');
const applicationSuccess = document.querySelector('#applicationSuccess');
const applicationSubmit = document.querySelector('#applicationSubmit');
const applicationFeathers = document.querySelector('#applicationFeathers');
let applicationType = 'feather_donation';
function setSection(nextSection, updateUrl = true) {
const isApplications = nextSection === 'applications';
reportsSection.classList.toggle('hidden', isApplications);
applicationsSection.classList.toggle('hidden', !isApplications);
sectionTabs.forEach(tab => {
const selected = tab.dataset.section === nextSection;
tab.classList.toggle('active', selected);
tab.setAttribute('aria-selected', String(selected));
});
if (updateUrl) {
const url = new URL(window.location.href);
if (isApplications) url.searchParams.set('section', 'applications');
else url.searchParams.delete('section');
window.history.pushState({}, '', url);
}
}
sectionTabs.forEach(tab => tab.addEventListener('click', () => setSection(tab.dataset.section)));
window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section') === 'applications' ? 'applications' : 'reports', false));
function addApplicationFeather(values = {}) {
const row = document.createElement('div');
row.className = 'feather';
row.innerHTML = '<label>Количество<input data-application-field="amount" type="number" min="1" inputmode="numeric" required></label><label>Цвет<input data-application-field="color" placeholder="например, синие" required></label><label>Источник добычи<input data-application-field="source" placeholder="личные запасы, осмотр дупла…" required></label><button class="remove" type="button">Убрать</button>';
Object.entries(values).forEach(([name, value]) => { const field = row.querySelector(`[data-application-field="${name}"]`); if (field) field.value = value; });
row.querySelector('.remove').addEventListener('click', () => row.remove());
applicationFeathers.append(row);
}
document.querySelector('#applicationAddFeather').addEventListener('click', () => addApplicationFeather());
function setApplicationFieldsVisible(selector, visible) {
const section = document.querySelector(selector);
section.classList.toggle('hidden', !visible);
section.querySelectorAll('input, select, textarea, button').forEach(field => { field.disabled = !visible; });
}
function syncApplicationForm() {
const isFeather = applicationType === 'feather_donation';
setApplicationFieldsVisible('#applicationFeatherFields', isFeather);
setApplicationFieldsVisible('#applicationKittenFields', applicationType === 'kitten');
setApplicationFieldsVisible('#applicationCuratorFields', applicationType === 'curator');
setApplicationFieldsVisible('#applicationFlyingFields', applicationType === 'flying_squirrel');
setApplicationFieldsVisible('#applicationVkField', applicationType === 'flying_squirrel');
document.querySelectorAll('[data-application-type]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.applicationType === applicationType)));
applicationError.textContent = '';
}
document.querySelectorAll('[data-application-type]').forEach(button => button.addEventListener('click', () => { applicationType = button.dataset.applicationType; syncApplicationForm(); }));
document.querySelector('[name="practiced_before"]').addEventListener('change', event => {
const visible = event.target.value === 'yes' && applicationType === 'flying_squirrel';
setApplicationFieldsVisible('#applicationPracticeLink', visible);
});
document.querySelectorAll('.application-screenshots').forEach(input => input.addEventListener('change', () => {
const list = input.closest('section').querySelector('.files');
list.replaceChildren(...[...input.files].map(file => { const item = document.createElement('li'); item.textContent = file.name; return item; }));
}));
async function uploadApplicationScreenshots() {
const attachments = [];
const files = [...document.querySelectorAll('.application-screenshots:not(:disabled)')].flatMap(input => [...input.files]);
for (const file of files) {
const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
const response = await fetch('/api/web/upload', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name: file.name, type: file.type, data})});
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || `Не удалось загрузить ${file.name}`);
attachments.push({type: 'photo', url: payload.url, name: file.name});
}
return attachments;
}
applicationForm.addEventListener('submit', async event => {
event.preventDefault();
applicationError.textContent = '';
applicationSubmit.disabled = true;
applicationSubmit.textContent = 'Отправляем…';
try {
const payload = Object.fromEntries(new FormData(applicationForm).entries());
payload.type = applicationType;
payload.character_id = Number(payload.character_id);
payload.attachments = await uploadApplicationScreenshots();
if (applicationType === 'flying_squirrel') payload.practiced_before = payload.practiced_before === 'yes';
if (applicationType === 'feather_donation') payload.feathers = [...applicationFeathers.querySelectorAll('.feather')].map(row => ({
amount: Number(row.querySelector('[data-application-field="amount"]').value),
color: row.querySelector('[data-application-field="color"]').value,
source: row.querySelector('[data-application-field="source"]').value,
}));
const response = await fetch('/api/applications', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Не удалось отправить заявку');
applicationSuccess.textContent = `Заявка №${data.id} отправлена на рассмотрение.`;
applicationSuccess.classList.remove('hidden');
applicationForm.reset();
applicationFeathers.replaceChildren();
addApplicationFeather();
syncApplicationForm();
} catch (err) { applicationError.textContent = err.message; }
finally { applicationSubmit.disabled = false; applicationSubmit.textContent = 'Отправить заявку'; }
});
addApplicationFeather();
syncApplicationForm();
setSection(new URLSearchParams(window.location.search).get('section') === 'applications' ? 'applications' : 'reports', false);
</script>
</body>
</html>