Files
cwshed-clone/web/calculator.html
T

870 lines
63 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:#2d2924; --muted:#675c50; --paper:#fffdf7; --ground:#f5efe3; --line:#ded3c2; --accent:#b56824; --gold:#d89a28; --leaf:#c96f25; --focus:#a9541d; --error:#8e3630; }
* { box-sizing: border-box; } html, body { max-width: 100%; } body { margin: 0; background: var(--ground); color: var(--ink); }
body::before { content:""; position:fixed; inset:0; pointer-events:none; z-index:-1; opacity:.42; background: radial-gradient(circle at 12% 8%, #fff8e7 0 0.7rem, transparent 13rem), radial-gradient(circle at 88% 24%, #ead8bd 0 0.45rem, transparent 15rem); }
main { position:relative; z-index:1; 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 a { display: inline-flex; align-items: center; min-height: 44px; border: 1px solid transparent; border-radius: 7px; padding: 9px 14px; color: var(--ink); text-decoration: none; }
.section-tabs a:hover { background: var(--paper); }
.section-tabs a[aria-current="page"] { border-color: var(--ink); text-decoration: underline; text-underline-offset: 5px; }
.mode-options { padding: 0; border: 0; min-width: 0; }
.mode-options legend { font-weight: 700; }
.mode-option { display: flex; align-items: center; gap: 8px; min-height: 48px; padding: 9px 14px; border: 1px solid var(--line); border-radius: 7px; background: var(--paper); cursor: pointer; font-weight: 400; }
.mode-option:has(:checked) { border-color: var(--ink); background: var(--ink); color: var(--paper); }
.mode-option input { width: 18px; min-height: 18px; margin: 0; accent-color: var(--accent); }
.mode-option:focus-within { outline: 3px solid var(--focus); outline-offset: 3px; }
button, select, input, textarea { font: inherit; }
button { min-height:44px; cursor: pointer; touch-action:manipulation; 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:#fff6e5; } button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline:3px solid var(--focus); outline-offset:3px; }
button:disabled { opacity: .55; cursor: not-allowed; }
input:user-invalid, textarea:user-invalid { border-color: var(--error); }
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; align-items: start; }
label { display: grid; gap: 6px; color: #403b36; font-weight:700; }
input, select, textarea { min-height:44px; width: 100%; border: 1px solid #c8bca9; border-radius: 7px; padding: 9px 12px; background: #fffefa; color: var(--ink); } input:focus,select:focus,textarea:focus { 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; }
.time-range { display: grid; grid-column: 1 / -1; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
.status-help { margin: -4px 0 0; font-size: .85rem; }
@media (max-width: 700px) { .extra-kitten, .time-range { 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:modal { overscroll-behavior: contain; }
dialog::backdrop { background: #211b1866; overflow: hidden; overscroll-behavior: contain; }
.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; text-decoration: underline; text-underline-offset: 4px; }
.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 { max-width: 100%; font-size: 1rem; }
.upload:focus-within { outline: 3px solid var(--focus); outline-offset: 3px; }
.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; }
.site-footer { margin-top: 48px; padding-top: 18px; border-top: 1px solid var(--line); color: var(--muted); font-size: .9rem; }
.site-footer a { color: inherit; text-underline-offset: 3px; }
.site-footer a:hover { color: var(--accent); }
.report-results { display: grid; gap: 14px; margin-top: 18px; }
.saved-report { padding: 20px; border: 1px solid var(--line); border-left: 4px solid var(--accent); border-radius: 8px; background: var(--paper); }
.saved-report h3 { margin: 0 0 12px; font-size: 1rem; }
.saved-report pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; line-height: 1.55; }
.saved-report img { display: block; width: min(100%, 680px); max-height: 480px; object-fit: contain; object-position: left; margin-top: 14px; border: 1px solid var(--line); border-radius: 6px; background: #f4efe7; }
@media (prefers-reduced-motion: reduce) { *,*::before,*::after { transition-duration:.01ms!important; } }
@media (max-width: 700px) {
main { width: calc(100% - 24px); max-width: 1060px; margin: 24px auto 40px; }
h1 { font-size: clamp(2rem, 11vw, 2.75rem); }
h2 { font-size: 1.4rem; }
.panel { padding: 16px; }
.section-tabs { margin-top: 24px; padding-bottom: 12px; }
.tabs { gap: 6px; margin: 18px 0 14px; }
.section-tabs a, .mode-option { flex: 1 1 144px; }
.grid, .application-types, .feather { grid-template-columns: 1fr; }
.wide { grid-column: auto; }
.actions { flex-direction: column; }
.actions button, .identity-tools button { width: 100%; }
.identity-tools { align-items: stretch; }
.bulk { margin-bottom: 20px; padding-bottom: 18px; }
.bulk textarea, textarea { min-height: 160px; }
.application-type { min-height: 56px; }
.upload { min-height: 116px; padding: 16px; }
dialog { width: calc(100% - 24px); max-width: none; padding: 16px; }
input, select, textarea { font-size: 16px; }
.site-footer { margin-top: 32px; }
}
</style>
<link rel="stylesheet" href="/api/weather/effect.css">
<script src="/api/weather/effect.js" defer></script>
</head>
<body class="weather-page">
<div class="weather-field" aria-hidden="true"></div>
<main>
<h1>Генератор отчётов и калькулятор</h1>
<p class="muted">Здесь можно подготовить отчёт, посчитать баллы и подать заявку.</p>
<nav class="tabs section-tabs" aria-label="Раздел Беличьей норы">
<a id="reportsTab" href="/belki" aria-current="page" data-section="reports">Отчёты</a>
<a id="sentReportsTab" href="/belki?section=sentReports" data-section="sentReports">Отчёты по ID кота</a>
<a id="applicationsTab" href="/belki?section=applications" data-section="applications">Заявки</a>
<a id="identityTab" href="/belki?section=identity" data-section="identity">Имя кота</a>
</nav>
<section id="reportsSection" aria-labelledby="reportsTab">
<p class="muted">На каждый заход нужен отдельный отчёт. Перед подготовкой отчёта об осмотре прикрепите скриншот. Для других отчётов он не нужен.</p>
<fieldset class="mode-options"><legend>Вид расчёта</legend><div class="tabs">
<label class="mode-option"><input type="radio" name="calculator_mode" value="coaching" data-mode="coaching" checked>Прокачка ЛУ/ЗУ</label>
<label class="mode-option"><input type="radio" name="calculator_mode" value="training" data-mode="training">Тренировка</label>
<label class="mode-option"><input type="radio" name="calculator_mode" value="inspection" data-mode="inspection">Осмотры</label>
<label class="mode-option"><input type="radio" name="calculator_mode" value="goal" data-mode="goal">Калькулятор цели</label>
<label class="mode-option"><input type="radio" name="calculator_mode" value="points" data-mode="points">Калькулятор баллов</label>
</div></fieldset>
<section class="panel">
<div class="bulk">
<label for="bulkText">Быстрый ввод</label>
<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" role="status"></p>
</div>
<form id="form" aria-label="Расчёт отчёта или баллов">
<div id="coaching" class="grid mode">
<label>Дата<input name="date" required>
<div class="quick-actions"><button type="button" id="todayBtn" class="today-btn 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="text" inputmode="numeric" pattern="[0-9]+" required></label>
<label>Имя котёнка<input name="kitten_name" required></label>
<label>ID котёнка<input name="kitten_id" type="text" inputmode="numeric" pattern="[0-9]+" 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="date" inputmode="numeric" pattern="\d{1,2}\.\d{1,2}" required>
<div class="quick-actions"><button type="button" class="today-btn quick-btn">Сегодня</button></div>
</label>
<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>
<div id="goal" class="grid mode hidden">
<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>
<label>Навык<select name="skill"><option>ЛУ</option><option>ЗУ</option></select></label>
<label>Статус котёнка<select name="kitten_independence"><option value="самостоятельно">самостоятельный</option><option value="несамостоятельно">несамостоятельный</option></select></label>
<label>Количество котят<input name="kitten_count" type="number" min="1" value="1"></label>
</div>
<div id="points" class="grid mode hidden">
<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>
<div class="time-range"><label>Начало<input name="start" type="time" value="11:00"></label><label>Конец<input name="end" type="time" value="11:20"></label></div>
<label>Бельчонков<select name="kitten_count"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select></label>
<label>Бельчонок 1<select name="kitten_status"><option value="самостоятельно">самостоятельный</option><option value="несамостоятельно">несамостоятельный</option></select></label>
<label class="points-extra hidden">Бельчонок 2<select name="kitten_status"><option value="самостоятельно">самостоятельный</option><option value="несамостоятельно">несамостоятельный</option></select></label>
<label class="points-extra hidden">Бельчонок 3<select name="kitten_status"><option value="самостоятельно">самостоятельный</option><option value="несамостоятельно">несамостоятельный</option></select></label>
</div>
<div id="pointsInspection" class="wide grid hidden"><label>Место<select name="place"><option>дупло</option><option>расщелина</option></select></label><label>Число осмотров<input name="inspections" type="number" min="0" value="0"></label><label class="wide">Ресурсы, по одному на строку: +количество название<textarea name="resources" placeholder="+2 вьюнок&#10;+1 паук"></textarea></label></div>
<p id="pointsTraining" class="wide muted hidden">За тренировку бельчонок получает 25 баллов.</p>
</div>
<label id="reportAttachments" class="wide hidden">Скриншот осмотра<input id="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple><span class="muted">Для осмотра нужен хотя бы один скриншот. Можно выбрать несколько PNG, JPEG или WebP.</span></label>
<div id="reportActions" class="actions"><button class="primary" type="submit">Подготовить сообщение</button><button type="button" id="copy" disabled>Скопировать</button></div>
<div id="goalActions" class="actions hidden"><button class="primary" type="submit">Рассчитать цель</button><button type="button" id="goalCopy" disabled>Скопировать</button></div>
<div id="pointsActions" class="actions hidden"><button class="primary" type="submit">Рассчитать баллы</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">Калькулятор подставит имя и ID из профиля в новые отчёты.</p>
</div>
<dialog id="confirmDialog" aria-labelledby="confirmTitle">
<h2 id="confirmTitle" style="margin-top:0">Подтверждение</h2>
<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" autofocus>Отмена</button>
</div>
</dialog>
<div class="result hidden" id="result"><h2><label for="message">Сообщение</label></h2><textarea id="message" readonly></textarea><div class="actions"><button type="button" id="sendReport" class="primary" disabled>Отправить отчёт</button></div><p class="muted" id="reportStatus" role="status"></p></div>
<div class="result hidden" id="pointsResult" aria-live="polite"><h2>Заработанные баллы</h2><div id="pointsSummary"></div></div>
<p class="error" id="error" role="alert"></p>
</section>
</section>
<section id="sentReportsSection" class="hidden" aria-labelledby="sentReportsTab">
<h2>Найти отчёты по ID кота</h2>
<p class="muted">Покажем до 100 последних отправленных отчётов, где этот кот указан как участник.</p>
<form id="sentReportsForm" class="panel">
<div class="grid">
<label>ID кота<input id="sentReportsCharacterId" name="character_id" type="text" inputmode="numeric" pattern="[0-9]+" required></label>
<div class="actions" style="align-items:end;margin-top:0"><button class="primary" id="sentReportsSubmit" type="submit">Найти отчёты</button></div>
</div>
<p id="sentReportsStatus" class="muted" role="status" aria-live="polite"></p>
<p id="sentReportsError" class="error" role="alert"></p>
</form>
<div id="sentReportsResults" class="report-results" aria-live="polite"></div>
</section>
<section id="applicationsSection" class="hidden" 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, 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 до 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="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>
<section id="identitySection" class="hidden" aria-labelledby="identityTab">
<div id="identityWorkspace">
<h2>Изменить имя кота</h2>
<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>
<label>Текущее имя<input id="renameIdentityCurrentName" type="text" readonly aria-readonly="true" placeholder="Сначала проверьте ID"></label>
<label class="wide">Новое имя<input id="renameIdentityNewName" name="new_name" type="text" maxlength="100" required></label>
</div>
<p class="muted" id="renameIdentityLookupStatus" role="status" aria-live="polite"></p>
<p class="error" id="renameIdentityError" role="alert"></p>
<div class="actions">
<button type="button" id="lookupIdentity">Проверить ID</button>
<button type="submit" id="renameIdentitySubmit" class="primary">Сохранить новое имя</button>
</div>
</form>
<div id="renameIdentitySuccess" class="success hidden" role="status" aria-live="polite"></div>
</div>
</section>
<footer class="site-footer snow-footer">Proudly made by Nyan404 and Codex | <a href="https://git.nyan404.ru/nyan404/cwshed-clone">GitLab Page</a>
<div class="footer-snowdrift" aria-hidden="true"></div>
</footer>
</main>
<dialog id="identityDialog" aria-label="Уточнить имя или ID кота" aria-describedby="identityDialogText">
<p id="identityDialogText" role="status"></p>
<label id="identityMissingLabel" for="identityMissingValue">Введите имя или ID кота<input id="identityMissingValue" autofocus></label>
<p class="muted">Калькулятор подставит имя и ID только в этот расчёт.</p>
<button type="button" id="saveIdentity">Добавить имя и ID</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 sendReport = document.querySelector('#sendReport');
const reportStatus = document.querySelector('#reportStatus');
let preparedReportPayload = null;
const message = document.querySelector('#message');
const copy = document.querySelector('#copy');
const goalCopy = document.querySelector('#goalCopy');
const screenshots = document.querySelector('#screenshots');
const reportAttachments = document.querySelector('#reportAttachments');
const reportActions = document.querySelector('#reportActions');
const goalActions = document.querySelector('#goalActions');
const pointsActions = document.querySelector('#pointsActions');
const pointsResult = document.querySelector('#pointsResult');
const pointsSummary = document.querySelector('#pointsSummary');
const pointsActivity = document.querySelector('#pointsActivity');
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';
let calculationVersion = 0;
let calculating = false;
// Any edit makes the previous result and an in-flight response obsolete.
function invalidateCalculation() {
calculationVersion += 1;
preparedReportPayload = null;
result.classList.add('hidden');
pointsResult.classList.add('hidden');
message.value = '';
copy.disabled = goalCopy.disabled = sendReport.disabled = true;
reportStatus.textContent = '';
error.textContent = '';
}
form.addEventListener('input', invalidateCalculation);
form.addEventListener('change', invalidateCalculation);
const extraKittens = document.querySelector('#extraKittens');
const statusHelp = document.querySelector('#statusHelp');
// Adds one repeatable kitten row and optionally fills it from saved values.
function addExtraKitten(values = {}) {
const row = document.createElement('div'); row.className = 'extra-kitten';
row.innerHTML = `<label>Имя котёнка<input data-extra="name" required></label>
<label>ID котёнка<input data-extra="id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" required></label>
<label>Самостоятельность<select data-extra="independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select></label>
<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(); invalidateCalculation(); document.querySelector('#addKitten').focus(); });
extraKittens.append(row);
row.querySelectorAll('input, select').forEach(field => { field.disabled = mode !== 'coaching'; });
invalidateCalculation();
}
document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten());
// Returns all independence controls participating in the current coaching form.
function statusFields() { return [document.querySelector('#coaching [name="kitten_independence"]'), ...extraKittens.querySelectorAll('[data-extra="independence"]')]; }
// Keeps every kitten's independence selection available for the chosen skill.
function updateStatusRules(event) {
const fields = statusFields();
fields.forEach(field => { field.disabled = mode !== 'coaching'; });
statusHelp.textContent = document.querySelector('#coaching [name="skill"]').value === 'ЛУ'
? 'Для ЛУ можно указать не более одного несамостоятельного котёнка.'
: 'Отметьте для каждого котёнка, самостоятельный он или нет.';
}
// Returns a user-facing validation error when kitten statuses conflict.
function validateStatusRules() {
const fields = statusFields();
const skill = document.querySelector('#coaching [name="skill"]').value;
if (skill === 'ЛУ' && fields.filter(field => field.value === 'несамостоятельно').length > 1) return 'Для ЛУ можно указать не более одного несамостоятельного котёнка.';
return '';
}
// Switches the visible calculator panel and disables fields in hidden panels.
function selectMode(nextMode) {
invalidateCalculation();
mode = nextMode;
document.querySelectorAll('[data-mode]').forEach(item => { item.checked = item.dataset.mode === mode; });
document.querySelectorAll('.mode').forEach(panel => panel.classList.toggle('hidden', panel.id !== mode));
document.querySelectorAll('.mode').forEach(panel => panel.querySelectorAll('input, select, textarea').forEach(field => { field.disabled = panel.id !== mode; }));
bulk.classList.toggle('hidden', mode !== 'coaching');
const inspection = mode === 'inspection';
reportAttachments.classList.toggle('hidden', !inspection);
screenshots.disabled = !inspection;
screenshots.required = inspection;
reportActions.classList.toggle('hidden', mode === 'goal' || mode === 'points');
goalActions.classList.toggle('hidden', mode !== 'goal');
pointsActions.classList.toggle('hidden', mode !== 'points');
if (mode !== 'coaching') bulkStatus.textContent = '';
error.textContent = '';
updatePointsFields();
}
document.querySelectorAll('[data-mode]').forEach(input => input.addEventListener('change', () => selectMode(input.value)));
function updatePointsFields() {
const activity = pointsActivity.value;
document.querySelector('#pointsCoaching').classList.toggle('hidden', activity !== 'coaching');
document.querySelector('#pointsInspection').classList.toggle('hidden', activity !== 'inspection');
document.querySelector('#pointsTraining').classList.toggle('hidden', activity !== 'training');
const count = Number(document.querySelector('#points [name="kitten_count"]').value);
document.querySelectorAll('.points-extra').forEach((field, index) => field.classList.toggle('hidden', activity !== 'coaching' || index >= count - 1));
document.querySelectorAll('#points input, #points select, #points textarea').forEach(field => {
field.disabled = mode !== 'points' || Boolean(field.closest('.hidden'));
});
}
pointsActivity.addEventListener('change', updatePointsFields);
document.querySelector('#points [name="kitten_count"]').addEventListener('change', updatePointsFields);
document.querySelector('#coaching [name="skill"]').addEventListener('change', updateStatusRules);
function setToday(button) {
const now = new Date();
button.closest('label').querySelector('input').value = `${String(now.getDate()).padStart(2, '0')}.${String(now.getMonth() + 1).padStart(2, '0')}`;
invalidateCalculation();
}
document.querySelectorAll('.today-btn').forEach(setToday);
document.querySelectorAll('.today-btn').forEach(button => button.addEventListener('click', () => setToday(button)));
document.querySelector('#coaching [name="kitten_independence"]').addEventListener('change', updateStatusRules);
document.querySelector('#noResourcesBtn').addEventListener('click', () => {
document.querySelector('#inspection [name="resources"]').value = '';
invalidateCalculation();
});
// Writes a value into a named field inside a calculator panel.
function setField(panel, name, value) {
const field = document.querySelector(`#${panel} [name="${name}"]`);
if (field && value !== undefined && value !== null) { field.value = value; invalidateCalculation(); }
}
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[1]} ${item[0]}`).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 || 'Не удалось найти имя или ID');
if (data.status === 'found') {
setField('inspection', 'character_name', data.name);
setField('inspection', 'character_id', data.character_id);
identityStatus.textContent = 'Калькулятор подставил имя и ID.';
} else {
identityDialogText.textContent = data.message;
const missing = name ? 'ID кота' : 'Имя кота';
identityMissingLabel.firstChild.textContent = `Введите ${missing}`;
identityMissingValue.value = '';
identityMissingValue.type = name ? 'number' : 'text';
identityDialog.showModal();
}
} 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 saveButton = document.querySelector('#saveIdentity');
if (saveButton.disabled) return;
saveButton.disabled = true;
try {
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) throw new Error(data.error || 'Не удалось сохранить имя и ID');
setField('inspection', 'character_name', data.name); setField('inspection', 'character_id', data.character_id);
identityDialog.close(); identityStatus.textContent = 'Имя и ID добавлены в этот расчёт.';
} catch (err) { identityDialogText.textContent = err.message; }
finally { saveButton.disabled = false; }
});
document.querySelector('#closeIdentityDialog').addEventListener('click', () => identityDialog.close());
// Serializes the active calculator form into the API payload shape.
function payload() {
if (mode === 'points') {
const activity = pointsActivity.value;
const data = {mode, activity};
if (activity === 'coaching') {
data.skill = document.querySelector('#pointsCoaching [name="skill"]').value;
data.start = document.querySelector('#pointsCoaching [name="start"]').value;
data.end = document.querySelector('#pointsCoaching [name="end"]').value;
const count = Number(document.querySelector('#points [name="kitten_count"]').value);
data.kitten_statuses = [...document.querySelectorAll('#pointsCoaching [name="kitten_status"]')].slice(0, count).map(field => field.value);
} else if (activity === 'inspection') {
data.place = document.querySelector('#pointsInspection [name="place"]').value;
data.inspections = Number(document.querySelector('#pointsInspection [name="inspections"]').value);
data.resources = document.querySelector('#pointsInspection [name="resources"]').value.split('\n').map(line => line.trim()).filter(Boolean).map(line => {
const match = line.match(/^\+\s*(\d+)\s+(.+)$/);
if (!match) throw new Error('Укажите ресурс так: +2 вьюнок.');
return [match[2].trim(), Number(match[1])];
});
}
return data;
}
const data = {};
document.querySelectorAll(`#${mode} [name]`).forEach(field => { data[field.name] = field.value; });
data.mode = mode;
['escort_id', 'kitten_id', 'character_id', 'inspections', 'current_points', 'target_points', 'minutes_per_session', 'kitten_count'].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 match = line.match(/^\+\s*(\d+)\s+(.+)$/);
if (!match) throw new Error('Укажите ресурс так: +2 вьюнок.');
return [match[2].trim(), Number(match[1])];
});
}
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;
}
// Uploads selected screenshots and returns attachment descriptors for the API.
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 = '';
if (calculating) return;
invalidateCalculation();
const version = calculationVersion;
const requestMode = mode;
const submitButton = event.submitter;
const submitLabel = submitButton?.textContent;
if (submitButton) submitButton.textContent = 'Рассчитываем…';
calculating = true;
form.setAttribute('aria-busy', 'true');
form.querySelectorAll('[type="submit"]').forEach(button => { button.disabled = true; });
try {
if (mode === 'coaching') {
const statusError = validateStatusRules();
if (statusError) throw new Error(statusError);
}
const reportPayload = payload();
preparedReportPayload = null;
reportStatus.textContent = '';
reportPayload.attachments = requestMode === 'inspection' ? 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 (version !== calculationVersion) return;
if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');
if (requestMode === 'points') {
const values = data.result;
const scores = Array.isArray(values.kitten_points)
? values.kitten_points.map((value, index) => [`Бельчонок ${index + 1}`, value])
: [[values.kitten_points !== undefined ? 'Бельчонок' : 'Баллы осмотра', values.kitten_points ?? values.points]];
if (values.curator_points !== undefined) scores.unshift(['Куратор', values.curator_points]);
pointsSummary.replaceChildren(...scores.map(([label, value]) => {
const line = document.createElement('p');
const score = document.createElement('strong');
score.textContent = value;
line.append(`${label}: `, score, ' баллов');
return line;
}));
pointsResult.classList.remove('hidden'); return;
}
message.value = data.message;
result.classList.remove('hidden');
copy.disabled = requestMode === 'goal';
goalCopy.disabled = requestMode !== 'goal';
sendReport.classList.toggle('hidden', requestMode === 'goal');
reportStatus.textContent = 'Расчёт готов. Проверьте сообщение.';
if (requestMode !== 'goal') {
preparedReportPayload = reportPayload;
sendReport.disabled = false;
sendReport.textContent = 'Отправить отчёт';
}
} catch (err) { if (version === calculationVersion) error.textContent = err.message; }
finally {
calculating = false;
form.removeAttribute('aria-busy');
form.querySelectorAll('[type="submit"]').forEach(button => { button.disabled = false; });
if (submitButton) submitButton.textContent = submitLabel;
}
});
sendReport.addEventListener('click', async () => {
if (!preparedReportPayload || sendReport.disabled) return;
sendReport.disabled = true;
sendReport.textContent = 'Отправляем…';
const version = calculationVersion;
try {
const response = await fetch('/api/reports', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(preparedReportPayload) });
const data = await response.json();
if (version !== calculationVersion) return;
if (!response.ok) throw new Error(data.error || 'Не удалось отправить отчёт');
preparedReportPayload = null;
sendReport.textContent = 'Отчёт отправлен';
reportStatus.textContent = 'Отчёт отправлен и сохранён.';
reportStatus.classList.remove('hidden');
} catch (err) {
if (version !== calculationVersion) return;
error.textContent = err.message;
sendReport.disabled = false;
sendReport.textContent = 'Отправить отчёт';
}
});
async function copyMessage() {
try {
await navigator.clipboard.writeText(message.value);
reportStatus.textContent = 'Сообщение скопировано.';
} catch {
message.focus();
message.select();
reportStatus.textContent = 'Не удалось скопировать автоматически. Текст выделен: скопируйте его через меню браузера или Ctrl+C / ⌘C.';
}
}
copy.addEventListener('click', copyMessage);
goalCopy.addEventListener('click', copyMessage);
const reportsSection = document.querySelector('#reportsSection');
const sentReportsSection = document.querySelector('#sentReportsSection');
const applicationsSection = document.querySelector('#applicationsSection');
const identitySection = document.querySelector('#identitySection');
const sectionTabs = [...document.querySelectorAll('[data-section]')];
const sentReportsForm = document.querySelector('#sentReportsForm');
const sentReportsCharacterId = document.querySelector('#sentReportsCharacterId');
const sentReportsSubmit = document.querySelector('#sentReportsSubmit');
const sentReportsStatus = document.querySelector('#sentReportsStatus');
const sentReportsError = document.querySelector('#sentReportsError');
const sentReportsResults = document.querySelector('#sentReportsResults');
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';
const renameIdentityForm = document.querySelector('#renameIdentityForm');
const renameIdentityId = document.querySelector('#renameIdentityId');
const renameIdentityCurrentName = document.querySelector('#renameIdentityCurrentName');
const renameIdentityNewName = document.querySelector('#renameIdentityNewName');
const lookupIdentity = document.querySelector('#lookupIdentity');
const renameIdentitySubmit = document.querySelector('#renameIdentitySubmit');
const renameIdentityLookupStatus = document.querySelector('#renameIdentityLookupStatus');
const renameIdentityError = document.querySelector('#renameIdentityError');
const renameIdentitySuccess = document.querySelector('#renameIdentitySuccess');
// Changes between reports, applications, and identity management while optionally updating the URL.
function setSection(nextSection, updateUrl = true) {
const selectedSection = ['reports', 'sentReports', 'applications', 'identity'].includes(nextSection) ? nextSection : 'reports';
reportsSection.classList.toggle('hidden', selectedSection !== 'reports');
sentReportsSection.classList.toggle('hidden', selectedSection !== 'sentReports');
applicationsSection.classList.toggle('hidden', selectedSection !== 'applications');
identitySection.classList.toggle('hidden', selectedSection !== 'identity');
sectionTabs.forEach(tab => {
const selected = tab.dataset.section === selectedSection;
if (selected) tab.setAttribute('aria-current', 'page');
else tab.removeAttribute('aria-current');
});
document.title = `${sectionTabs.find(tab => tab.dataset.section === selectedSection).textContent} — Беличья нора`;
if (updateUrl) {
const url = new URL(window.location.href);
if (selectedSection !== 'reports') url.searchParams.set('section', selectedSection);
else url.searchParams.delete('section');
if (url.href !== window.location.href) window.history.pushState({}, '', url);
}
}
sectionTabs.forEach(tab => tab.addEventListener('click', event => {
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
event.preventDefault();
setSection(tab.dataset.section);
}));
window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section'), false));
sentReportsForm.addEventListener('submit', async event => {
event.preventDefault();
sentReportsError.textContent = '';
sentReportsResults.replaceChildren();
const characterId = sentReportsCharacterId.value.trim();
if (!/^[0-9]+$/.test(characterId) || Number(characterId) <= 0) {
sentReportsError.textContent = 'Введите ID кота: целое число больше нуля.';
return;
}
sentReportsSubmit.disabled = true;
sentReportsStatus.textContent = 'Ищем отчёты…';
try {
const response = await fetch(`/api/reports?character_id=${encodeURIComponent(characterId)}`);
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Не удалось загрузить отчёты.');
const items = data.items || [];
sentReportsStatus.textContent = items.length ? `Найдено отчётов: ${items.length}${items.length === data.limit ? ' (показаны последние 100)' : ''}.` : 'Этот кот пока не указан ни в одном отправленном отчёте.';
items.forEach(item => {
const article = document.createElement('article');
article.className = 'saved-report';
const title = document.createElement('h3');
const date = item.created_at ? new Date(item.created_at) : null;
const dateLabel = date && !Number.isNaN(date.getTime()) ? new Intl.DateTimeFormat('ru-RU', {dateStyle: 'medium', timeStyle: 'short'}).format(date) : 'Дата неизвестна';
const labels = {coaching: 'Прокачка ЛУ/ЗУ', training: 'Тренировка', inspection: 'Осмотр'};
title.textContent = `${labels[item.mode] || 'Отчёт'} · ${dateLabel}`;
const message = document.createElement('pre');
message.textContent = item.message || '';
article.append(title, message);
(item.attachments || []).forEach(photo => {
const image = document.createElement('img');
image.src = photo.url;
image.alt = `Скриншот к отчёту кота ${characterId}`;
image.loading = 'lazy';
article.append(image);
});
sentReportsResults.append(article);
});
} catch (err) {
sentReportsStatus.textContent = '';
sentReportsError.textContent = err.message;
} finally {
sentReportsSubmit.disabled = false;
}
});
async function lookupRenameIdentity() {
renameIdentityError.textContent = '';
renameIdentitySuccess.classList.add('hidden');
renameIdentityLookupStatus.textContent = '';
const characterId = renameIdentityId.value.trim();
if (!characterId) { renameIdentityError.textContent = 'Укажите ID кота.'; return false; }
lookupIdentity.disabled = true;
lookupIdentity.textContent = 'Проверяем…';
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 нет сохранённого имени.');
renameIdentityCurrentName.value = data.name;
renameIdentityId.value = data.character_id;
renameIdentityLookupStatus.textContent = `Текущее имя: «${data.name}».`;
return true;
} catch (err) { renameIdentityCurrentName.value = ''; renameIdentityError.textContent = err.message; return false; }
finally { lookupIdentity.disabled = false; lookupIdentity.textContent = 'Проверить ID'; }
}
lookupIdentity.addEventListener('click', lookupRenameIdentity);
renameIdentityForm.addEventListener('submit', async event => {
event.preventDefault();
renameIdentityError.textContent = '';
renameIdentitySuccess.classList.add('hidden');
if (!renameIdentityCurrentName.value && !(await lookupRenameIdentity())) return;
renameIdentitySubmit.disabled = true;
renameIdentitySubmit.textContent = 'Сохраняем…';
try {
const response = await fetch('/api/rename-identity', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({character_id: renameIdentityId.value, new_name: renameIdentityNewName.value.trim()})});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Не удалось изменить имя.');
renameIdentityCurrentName.value = data.name;
renameIdentityNewName.value = '';
renameIdentityLookupStatus.textContent = `Текущее имя: «${data.name}».`;
renameIdentitySuccess.textContent = `Имя обновлено: «${data.old_name}» → «${data.name}».`;
renameIdentitySuccess.classList.remove('hidden');
} catch (err) { renameIdentityError.textContent = err.message; }
finally { renameIdentitySubmit.disabled = false; renameIdentitySubmit.textContent = 'Сохранить новое имя'; }
});
// Adds and initializes one feather row in the application form.
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());
// Toggles visibility and disabled state for an application subsection.
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; });
}
// Synchronizes application subsection visibility with the selected type.
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');
setApplicationFieldsVisible('#applicationPracticeLink', applicationType === 'flying_squirrel' && document.querySelector('[name="practiced_before"]').value === 'yes');
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; }));
}));
// Uploads screenshots selected for an application and returns attachment metadata.
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();
if (applicationSubmit.disabled) return;
applicationError.textContent = '';
applicationSuccess.classList.add('hidden');
applicationSubmit.disabled = true;
applicationSubmit.textContent = 'Отправляем…';
try {
const payload = Object.fromEntries(new FormData(applicationForm).entries());
payload.type = applicationType;
payload.character_id = Number(payload.character_id);
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,
}));
payload.attachments = await uploadApplicationScreenshots();
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();
selectMode(mode);
setSection(new URLSearchParams(window.location.search).get('section'), false);
</script>
</body>
</html>