feat(web): combine reports and applications

This commit is contained in:
nyan404 committed 2026-08-21 14:07:19 +03:00
1 parent f73f99068a
commit 02126d768d
3 files changed
+196 -6

No files matched your search

+1 -1
View File
@@ -26,7 +26,7 @@
- 2026-08-21: CI final images use immutable registry base images. Any runtime dependency change requires rebuilding/pushing the matching base (`Dockerfile.base` for `requirements.txt`, `Dockerfile.gateway-base` for `nginx.conf`) and changing the tag used by the final Dockerfile.
- 2026-08-21: use Context7 for fresh official integration documentation and `prevent-eol` before dependency changes; lifecycle status is not a vulnerability verdict.
- 2026-08-21: project-local frontend instructions include `frontend-craft`, `frontend-design`, and `ui-ux-pro-max`; use them together for UI work.
- 2026-08-21: the public calculator and screenshot upload endpoint do not require `BELKI_WEB_PASSWORD`; password-gated access is limited to applications and admin flows.
- 2026-08-21: `/belki` is the single public Belki workspace: reports are available without `BELKI_WEB_PASSWORD`, while its “Заявки” tab uses the password-gated application flow. The old `/applications` route remains only as a direct legacy entry point.
# 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+2 -2
View File
@@ -23,7 +23,7 @@
- GitLab Runner retries source checkout up to three times (`GET_SOURCES_ATTEMPTS=3`) to absorb transient connectivity failures before the job script starts. A persistent inability to reach `git.nyan404.ru:443` still requires repair on the selected runner host.
- The local image is currently `belki-calculator:test`; the CI target is now `$DOCKER_REGISTRY/belki:latest`.
- GitLab CI runs `python -m compileall -q app tests` and `python -m unittest discover -s tests -q` in a dedicated `test` stage before build/deploy. The job explicitly clears `BELKI_DATABASE_URL` and uses `/tmp/belki-test-identities.sqlite3`, preventing unit tests from reaching the Kubernetes PostgreSQL service. Local validation was performed with the same tests, JavaScript syntax check, a local browser/API smoke test, and container health/API smoke.
- `/belki` is public: it creates reports and uploads their screenshots without a web-password session. `/applications` and `/admin` remain password-protected.
- `/belki` is the single public workspace: the “Отчёты” tab creates reports and uploads their screenshots without a web-password session; the “Заявки” tab contains the four typed application forms and requests `BELKI_WEB_PASSWORD` only when a user sends an application. `/applications` is kept as a legacy direct route. `/admin` remains password-protected.
- The VK dialog layer is covered by tests for step-by-step entry, bulk detection, clarification, confirmation, and cancellation.
- Bulk input accepts a natural one-line format without pipes, e.g. `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140`; the web form calls `/api/inspect-bulk` and fills recognized fields.
- Training and inspection have the same stepwise/bulk flow. Character identity can be resolved through `/api/resolve-identity` and the persistent SQLite directory; missing pairs produce an explicit prompt instead of guessed data.
@@ -32,7 +32,7 @@
- Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp.
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred.
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI.
- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. `/applications` reuses the existing password-gated web session and upload endpoint; `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one.
- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. The “Заявки” tab within `/belki` reuses the existing password-gated web session and upload endpoint; `/applications` remains a legacy direct page. `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one.
- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`; its context keyboard drives every selectable application branch, while users type only free-form values. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient.
- Google Sheets export is pre-wired but disabled by `BELKI_GOOGLE_EXPORT_ENABLED=0`. `ApplicationStore` records `application_created` and `application_accepted` snapshots in the PostgreSQL `belki_application_export_events` or SQLite `application_export_events` outbox. `GoogleSheetsExportService` sends FIFO JSON events only to an explicitly configured Google Apps Script Web App URL, retains failed events for retry, and is polled by the bot every 15 seconds when enabled.
- The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API.
+193 -3
View File
@@ -11,6 +11,8 @@
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; }
@@ -39,16 +41,33 @@
.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 { grid-template-columns: 1fr; } .wide { grid-column: auto; }.actions{flex-direction:column}.actions button{width:100%;} }
@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>
<p class="muted">Отчёты и заявки — в одном месте.</p>
<div class="tabs" role="tablist">
<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>
@@ -128,6 +147,43 @@
<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="applicationAuth" class="panel auth-panel">
<h2>Подача заявки</h2>
<p class="muted">Введите пароль, чтобы отправить заявку на рассмотрение и приложить скриншоты.</p>
<form id="applicationAuthForm">
<label>Пароль<input id="applicationPassword" type="password" autocomplete="current-password" required></label>
<p id="applicationAuthError" class="error" role="alert"></p>
<button class="primary" type="submit">Войти</button>
</form>
</div>
<div id="applicationWorkspace" class="hidden">
<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="url" placeholder="https://vk.com/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>
@@ -306,6 +362,140 @@
} 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 applicationAuth = document.querySelector('#applicationAuth');
const applicationWorkspace = document.querySelector('#applicationWorkspace');
const applicationAuthError = document.querySelector('#applicationAuthError');
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 (isApplications) checkApplicationSession();
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 showApplicationWorkspace() {
applicationAuth.classList.add('hidden');
applicationWorkspace.classList.remove('hidden');
}
async function checkApplicationSession() {
try {
const response = await fetch('/api/web/session');
const data = await response.json();
if (data.authenticated) showApplicationWorkspace();
} catch (_) { /* The login form remains available and explains any error. */ }
}
document.querySelector('#applicationAuthForm').addEventListener('submit', async event => {
event.preventDefault();
applicationAuthError.textContent = '';
const response = await fetch('/api/web/auth', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({password: document.querySelector('#applicationPassword').value}),
});
const data = await response.json();
if (!response.ok) { applicationAuthError.textContent = data.error || 'Не удалось войти'; return; }
showApplicationWorkspace();
});
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>