fix: improve calculator accessibility and async result handling
This commit is contained in:
1 parent
ea2f0fbe05
commit
bb21a767d7
9 files changed
+469
-101
No files matched your search
@@ -3,6 +3,7 @@
|
|||||||
## Scope
|
## Scope
|
||||||
- This repository contains the Belki calculator/VK bot plus legacy CatWar userscript assets.
|
- This repository contains the Belki calculator/VK bot plus legacy CatWar userscript assets.
|
||||||
- Key files: [`app/`](./app), [`web/calculator.html`](./web/calculator.html), [`Dockerfile`](./Dockerfile), and [`deploy/k8s/`](./deploy/k8s).
|
- Key files: [`app/`](./app), [`web/calculator.html`](./web/calculator.html), [`Dockerfile`](./Dockerfile), and [`deploy/k8s/`](./deploy/k8s).
|
||||||
|
- LongMemory namespace is explicitly `catwar`, established by the owner on 2026-11-14 and recorded in root `project-info.txt`. Read that file as data before scoped calls; use project context/recall before work and verify durable writes by readback.
|
||||||
|
|
||||||
## Working Rules
|
## Working Rules
|
||||||
- Write Russian UI and bot copy for CatWar faction members. Preserve ЛУ/ЗУ, бельчата, белки-летяги, кураторы, осмотры, resource names, command examples, and rule limits. Prefer plain instructions; explain name/ID lookup without internal terms such as «связка». Keep required input separators and report templates intact when editing prose.
|
- Write Russian UI and bot copy for CatWar faction members. Preserve ЛУ/ЗУ, бельчата, белки-летяги, кураторы, осмотры, resource names, command examples, and rule limits. Prefer plain instructions; explain name/ID lookup without internal terms such as «связка». Keep required input separators and report templates intact when editing prose.
|
||||||
@@ -19,6 +20,9 @@
|
|||||||
- For web UI work, use the project-local `.codex/skills/frontend-craft`, `.codex/skills/frontend-design`, and `.codex/skills/ui-ux-pro-max` instructions: establish a deliberate visual direction, preserve accessibility and interaction quality, then inspect the rendered result.
|
- For web UI work, use the project-local `.codex/skills/frontend-craft`, `.codex/skills/frontend-design`, and `.codex/skills/ui-ux-pro-max` instructions: establish a deliberate visual direction, preserve accessibility and interaction quality, then inspect the rendered result.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
- Frontend regression: `node tests/browser/calculator.cjs` against a separately started isolated server at `http://127.0.0.1:8876` (override `BELKI_TEST_URL` only with another loopback URL). Use the remote test zone when exposed; it was unavailable on 2026-11-14. Playwright is test tooling, not a runtime dependency: use the bundled Node/Playwright returned by `load_workspace_dependencies`, setting `NODE_PATH` to its `node_modules` and optionally `CHROMIUM_PATH` to the browser executable. The suite closes its browser/contexts and intercepts weather and admin fixtures; real calculation requests require the normal Python dependencies.
|
||||||
|
- For a local fallback, create a temporary venv and install existing `requirements.txt`, then launch `python -m app.main` with `BELKI_DATABASE_URL=`, `BELKI_HOST=127.0.0.1`, `BELKI_PORT=8876`, and temporary absolute paths for `BELKI_HISTORY_DB` and `BELKI_IDENTITIES_DB`. Never reuse production stores. `BELKI_SCREENSHOT_DIR` optionally saves browser screenshots outside Git. Stop the server and remove the temporary venv, SQLite files, caches and screenshots after review.
|
||||||
|
- Browser coverage includes native radio arrow keys, report invalidation on edits/mode changes, delayed responses/double submissions, clipboard denial, dialog focus/Escape, section URLs/Back, both application entry points, admin filters/default sort and gallery. Keep API/data contracts intact: training points are a number, coaching kitten points are an array. Do not restore stale prepared reports when a calculation response arrives after an edit.
|
||||||
- Weather easter egg: `python -m unittest discover -s tests -p test_weather.py -q` and `node --check web/weather-effect.js`; inspect `/belki` and `/admin` with rain/snow/mixed fixtures, mobile widths, reduced motion, and API failure. Prefer the remote test-zone MCP when exposed; otherwise use an isolated local server with temporary SQLite paths and stop it after validation. Keep screenshots outside the repo.
|
- Weather easter egg: `python -m unittest discover -s tests -p test_weather.py -q` and `node --check web/weather-effect.js`; inspect `/belki` and `/admin` with rain/snow/mixed fixtures, mobile widths, reduced motion, and API failure. Prefer the remote test-zone MCP when exposed; otherwise use an isolated local server with temporary SQLite paths and stop it after validation. Keep screenshots outside the repo.
|
||||||
- For CI-only changes, prefer a targeted YAML parse and a diff review.
|
- For CI-only changes, prefer a targeted YAML parse and a diff review.
|
||||||
- For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together.
|
- For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together.
|
||||||
|
|||||||
@@ -130,3 +130,12 @@ Inspection results persist the base score for the number of inspections and each
|
|||||||
Calculator/admin share `web/weather-effect.js` and `.css`, served through `/api/weather/effect.*` so existing gateway routing works. `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint: observed wind/gusts control speed/drift, RA/DZ and SN/SG select rain/snow/mixed particles, intensity controls density. Trends/remarks/vicinity do not change observed weather. The cache is process-local (5 min success, 1 min failure), timeout 3 s, payload cap 64 KiB; observations expire after 2 h. Failure restores leaves. Browser polling is every 5 min, hidden tabs pause, reduced motion keeps at most seven faint static particles. No dependencies or storage changes. Remote test-zone MCP was unavailable; local fixtures and browser checks were used. On this Mac, Python HTTPS required `SSL_CERT_FILE=/etc/ssl/cert.pem`; never bypass TLS verification. Production is unverified until a separately requested push/deployment.
|
Calculator/admin share `web/weather-effect.js` and `.css`, served through `/api/weather/effect.*` so existing gateway routing works. `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint: observed wind/gusts control speed/drift, RA/DZ and SN/SG select rain/snow/mixed particles, intensity controls density. Trends/remarks/vicinity do not change observed weather. The cache is process-local (5 min success, 1 min failure), timeout 3 s, payload cap 64 KiB; observations expire after 2 h. Failure restores leaves. Browser polling is every 5 min, hidden tabs pause, reduced motion keeps at most seven faint static particles. No dependencies or storage changes. Remote test-zone MCP was unavailable; local fixtures and browser checks were used. On this Mac, Python HTTPS required `SSL_CERT_FILE=/etc/ssl/cert.pem`; never bypass TLS verification. Production is unverified until a separately requested push/deployment.
|
||||||
|
|
||||||
- 2026-10-18 20:19 MSK: operator's `98182c17` weather rollout verified live. Web/bot/gateway Ready, zero restarts; public `/api/weather/ulli` matched ULLI wind 3 m/s/CAVOK, CSS/JS matched local commit, calculator/admin rendered leaves with reduced motion respected and no console errors. This supersedes the earlier unverified-production status for the leaves/current-weather path; production rain/snow remain fixture-only evidence.
|
- 2026-10-18 20:19 MSK: operator's `98182c17` weather rollout verified live. Web/bot/gateway Ready, zero restarts; public `/api/weather/ulli` matched ULLI wind 3 m/s/CAVOK, CSS/JS matched local commit, calculator/admin rendered leaves with reduced motion respected and no console errors. This supersedes the earlier unverified-production status for the leaves/current-weather path; production rain/snow remain fixture-only evidence.
|
||||||
|
|
||||||
|
## Frontend contracts and LongMemory identity — 2026-11-14
|
||||||
|
|
||||||
|
- The owner explicitly chose LongMemory `project_id="catwar"`; root `project-info.txt` is the canonical literal identity. Do not derive a different namespace from the repository name. Initial project context/recall had no matching knowledge.
|
||||||
|
- `/belki` section choices are real links with URL/history behavior; calculation modes are native radios. Keep browser keyboard semantics and `aria-current`/pressed states aligned with visible selection. File pickers in both application forms must remain visible and keyboard reachable.
|
||||||
|
- Editing a report or changing modes invalidates its prepared payload/output. Ignore calculation responses whose version is older than the current form state; guard concurrent preparation/application requests. These frontend guards are not server-side idempotency.
|
||||||
|
- Training points have scalar `result.kitten_points` (25); coaching points use an array. Both shapes must render, and hidden activity fields must stay disabled for browser validation. The points renderer uses text nodes instead of HTML interpolation.
|
||||||
|
- Regression coverage is `tests/browser/calculator.cjs` with external Playwright and an isolated loopback server; see AGENTS.md. 49 focused Python checks and desktop/mobile browser flows passed in the local fallback environment. Other browsers and real assistive technology remain unverified; no deployment was made.
|
||||||
|
- Chrome extension guidance was reviewed, but the legacy CatWar entries are userscripts and were not converted to Manifest V3. Existing licensing/attribution and asset URLs remain intact.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
project_id="catwar"
|
||||||
+9
-1
@@ -1,10 +1,13 @@
|
|||||||
# Карта проекта «Беличья нора»
|
# Карта проекта «Беличья нора»
|
||||||
|
|
||||||
Актуально на 2026-10-18. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур.
|
Актуально на 2026-11-14. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
mindmap
|
mindmap
|
||||||
root((cwshed-clone))
|
root((cwshed-clone))
|
||||||
|
Project context
|
||||||
|
project-info.txt
|
||||||
|
LongMemory catwar
|
||||||
Belki
|
Belki
|
||||||
Domain
|
Domain
|
||||||
domain.py
|
domain.py
|
||||||
@@ -37,6 +40,8 @@ mindmap
|
|||||||
applications
|
applications
|
||||||
refresh WebSocket pool 8
|
refresh WebSocket pool 8
|
||||||
web/calculator.html
|
web/calculator.html
|
||||||
|
Native section links and mode radios
|
||||||
|
Prepared-result version and invalidation
|
||||||
Reports
|
Reports
|
||||||
Goal calculator
|
Goal calculator
|
||||||
Applications
|
Applications
|
||||||
@@ -47,6 +52,9 @@ mindmap
|
|||||||
Report entered checkbox
|
Report entered checkbox
|
||||||
Current calendar month by default
|
Current calendar month by default
|
||||||
web/applications.html
|
web/applications.html
|
||||||
|
tests/browser/calculator.cjs
|
||||||
|
Isolated loopback API and fixtures
|
||||||
|
Desktop and mobile Chromium
|
||||||
VK bot
|
VK bot
|
||||||
vk_bot.py
|
vk_bot.py
|
||||||
Callback API listener :8081
|
Callback API listener :8081
|
||||||
|
|||||||
@@ -1,5 +1,15 @@
|
|||||||
# Structure and Data
|
# Structure and Data
|
||||||
|
|
||||||
|
## Calculator and related UI guidance pass — 2026-11-14
|
||||||
|
|
||||||
|
- `web/calculator.html` keeps the existing warm palette and typography. Section navigation now uses real links with `aria-current` and browser history; calculation mode uses a native radio group with built-in arrow-key behavior. File inputs, repeatable kitten fields, quick input and output have accessible labels/focus; dialogs retain native modal focus and Escape handling. No new runtime dependencies or polyfills were required.
|
||||||
|
- Prepared reports/results are invalidated by edits, helper actions and mode changes. An incrementing version discards stale async responses; calculation/application submit guards prevent concurrent duplicate requests in the current page. Clipboard denial selects the output and gives manual-copy instructions. This does not provide server-side idempotency for retries after an uncertain network failure.
|
||||||
|
- Fixed the existing training-points display: `/api/calculate` returns `kitten_points: 25` for training, while coaching uses an array. The UI now accepts both and renders score text with DOM nodes. Inactive points fields cannot block native form validation; “Без ресурсов” clears inspection resources. Application practice-link visibility/disabled state is recomputed when changing type and after reset.
|
||||||
|
- `web/applications.html` keeps the standalone form, exposes the native file picker to keyboard users, reports pressed selection/success, snapshots application data before uploads and guards submission. `web/admin.html` gives password/gallery accessible names, uses `aria-pressed` for ordinary selection buttons, adds solid focus outlines and preserves native dialog dismissal. Existing current-month defaults, sorting and history persistence are retained.
|
||||||
|
- `tests/browser/calculator.cjs` uses external Playwright against an isolated loopback server, checks 1280/390 px flows and closes browser resources. Python dependencies and SQLite fixtures were kept in `/tmp/cwshed-ui-review`; no remote test-zone or token-optimizer MCP was exposed. Validation used Python 3.14.9 and Chromium 157 on Linux (the production Python 3.12 image was not rebuilt): 49 focused Python tests (calculator web, API, applications, history, lookup and admin/export), Python compilation, JS syntax, browser interactions and screenshot inspection. The temporary server, environment and artifacts are removed after review. No push/deployment.
|
||||||
|
- `chrome-extensions` was checked for applicability: the retained CatWar files are userscripts (`@match` / `@grant`), not an MV3 extension; no Chrome extension manifest or `chrome.*` integration exists in the inspected entry points. No manifest conversion or third-party asset updates were warranted. This is not a comprehensive audit of the legacy bundled code or installed browser extensions.
|
||||||
|
- Root `project-info.txt` records the owner-selected LongMemory namespace `catwar`; it is a literal identifier, never executable configuration. Project context and targeted recall were empty at the start of this pass.
|
||||||
|
|
||||||
## PHP CVE applicability review — 2026-10-21
|
## PHP CVE applicability review — 2026-10-21
|
||||||
|
|
||||||
- Static review of revision `765d4023605b2cf56c81e2027f5def606e45637f`: CVE-2026-109618 and CVE-2026-109619 are not actionable for the declared project stack because it has no PHP request runtime. Both concern PHP core; see the [PHP advisory](https://www.php.net/archive/2026.php).
|
- Static review of revision `765d4023605b2cf56c81e2027f5def606e45637f`: CVE-2026-109618 and CVE-2026-109619 are not actionable for the declared project stack because it has no PHP request runtime. Both concern PHP core; see the [PHP advisory](https://www.php.net/archive/2026.php).
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
// Run against an isolated Belki server. See AGENTS.md for setup and cleanup.
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { chromium } = require('playwright');
|
||||||
|
|
||||||
|
const origin = process.env.BELKI_TEST_URL || 'http://127.0.0.1:8876';
|
||||||
|
// This suite writes synthetic data. Refuse to run against a public/production host.
|
||||||
|
assert(['127.0.0.1', 'localhost', '[::1]'].includes(new URL(origin).hostname));
|
||||||
|
|
||||||
|
async function run() {
|
||||||
|
const browser = await chromium.launch({
|
||||||
|
headless: true,
|
||||||
|
...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}),
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
for (const width of [1280, 390]) {
|
||||||
|
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce', locale: 'ru-RU' });
|
||||||
|
try {
|
||||||
|
const errors = [];
|
||||||
|
const page = await context.newPage();
|
||||||
|
page.on('pageerror', error => errors.push(error.message));
|
||||||
|
page.on('console', message => { if (message.type() === 'error') errors.push(message.text()); });
|
||||||
|
await page.route('**/api/weather/ulli', route => route.fulfill({ json: { available: false } }));
|
||||||
|
await page.goto(`${origin}/belki`);
|
||||||
|
assert.equal(await page.title(), 'Отчёты — Беличья нора');
|
||||||
|
assert(await page.getByRole('heading', { level: 1 }).isVisible());
|
||||||
|
assert.deepEqual(await page.locator('input, select, textarea').evaluateAll(fields => fields
|
||||||
|
.filter(field => field.getClientRects().length && !field.labels?.length && !field.getAttribute('aria-label') && !field.getAttribute('aria-labelledby'))
|
||||||
|
.map(field => field.id || field.name)), []);
|
||||||
|
|
||||||
|
// Native radio keyboard behavior works without a custom focusgroup/polyfill.
|
||||||
|
await page.locator('[data-mode="coaching"]').focus();
|
||||||
|
assert.equal(await page.locator('[data-mode="coaching"]').evaluate(node => getComputedStyle(node.closest('label')).outlineStyle), 'solid');
|
||||||
|
await page.keyboard.press('ArrowRight');
|
||||||
|
assert(await page.locator('[data-mode="training"]').isChecked());
|
||||||
|
assert(await page.locator('#training').isVisible());
|
||||||
|
await page.keyboard.press('ArrowLeft');
|
||||||
|
assert(await page.locator('[data-mode="coaching"]').isChecked());
|
||||||
|
await page.locator('#addKitten').click();
|
||||||
|
assert(await page.locator('#extraKittens').getByLabel('Имя котёнка').isVisible());
|
||||||
|
await page.locator('#extraKittens [data-remove]').click();
|
||||||
|
assert(await page.locator('#addKitten').evaluate(node => node === document.activeElement));
|
||||||
|
|
||||||
|
// A real calculation is invalidated by edits, even before another submit.
|
||||||
|
for (const [name, value] of Object.entries({ escort_name: 'Тестовый куратор', escort_id: '101', kitten_name: 'Тестовый котёнок', kitten_id: '102' })) {
|
||||||
|
await page.locator(`#coaching [name="${name}"]`).fill(value);
|
||||||
|
}
|
||||||
|
await page.locator('#reportActions [type="submit"]').click();
|
||||||
|
await page.locator('#result').waitFor({ state: 'visible' });
|
||||||
|
assert(await page.locator('#sendReport').isEnabled());
|
||||||
|
await page.evaluate(() => Object.defineProperty(navigator, 'clipboard', {
|
||||||
|
configurable: true, value: { writeText: async () => { throw new Error('Permission denied'); } },
|
||||||
|
}));
|
||||||
|
await page.locator('#copy').click();
|
||||||
|
assert.match(await page.locator('#reportStatus').textContent(), /Текст выделен/);
|
||||||
|
assert(await page.locator('#message').evaluate(node => node.selectionEnd === node.value.length));
|
||||||
|
await page.locator('#coaching [name="kitten_name"]').fill('Другой котёнок');
|
||||||
|
assert(await page.locator('#result').isHidden());
|
||||||
|
assert(await page.locator('#sendReport').isDisabled());
|
||||||
|
|
||||||
|
// Reject a delayed response after switching modes; prevent duplicate submits.
|
||||||
|
let release;
|
||||||
|
const gate = new Promise(resolve => { release = resolve; });
|
||||||
|
let requests = 0;
|
||||||
|
const delayed = async route => { requests += 1; await gate; await route.fulfill({ json: { message: 'Устаревший отчёт' } }); };
|
||||||
|
await page.route('**/api/calculate', delayed);
|
||||||
|
const request = page.waitForRequest('**/api/calculate');
|
||||||
|
await page.locator('#reportActions [type="submit"]').click();
|
||||||
|
await request;
|
||||||
|
assert(await page.locator('#reportActions [type="submit"]').isDisabled());
|
||||||
|
await page.locator('#form').evaluate(form => form.requestSubmit());
|
||||||
|
await page.locator('[data-mode="points"]').check();
|
||||||
|
release();
|
||||||
|
await page.waitForFunction(() => !document.querySelector('#form').hasAttribute('aria-busy'));
|
||||||
|
assert.equal(requests, 1);
|
||||||
|
assert(await page.locator('#result').isHidden());
|
||||||
|
assert(await page.locator('#sendReport').isDisabled());
|
||||||
|
await page.unroute('**/api/calculate', delayed);
|
||||||
|
|
||||||
|
// Inactive activity fields must not block browser constraint validation.
|
||||||
|
await page.locator('#pointsInspection [name="inspections"]').evaluate(node => { node.value = '-1'; });
|
||||||
|
await page.locator('#pointsActivity').selectOption('training');
|
||||||
|
await page.locator('#pointsActions [type="submit"]').click();
|
||||||
|
await page.locator('#pointsResult').waitFor({ state: 'visible' });
|
||||||
|
assert.match(await page.locator('#pointsSummary').textContent(), /25/);
|
||||||
|
await page.locator('[data-mode="inspection"]').check();
|
||||||
|
assert(await page.locator('#pointsResult').isHidden());
|
||||||
|
await page.locator('#inspection [name="resources"]').fill('+2 вьюнок');
|
||||||
|
await page.locator('#noResourcesBtn').click();
|
||||||
|
assert.equal(await page.locator('#inspection [name="resources"]').inputValue(), '');
|
||||||
|
|
||||||
|
// Native modal contains focus, Escape closes it and returns focus.
|
||||||
|
await page.locator('#inspection [name="character_name"]').fill('Несохранённый кот');
|
||||||
|
await page.locator('#resolveIdentity').click();
|
||||||
|
await page.getByRole('dialog', { name: 'Уточнить имя или ID кота' }).waitFor();
|
||||||
|
assert(await page.locator('#identityMissingValue').evaluate(node => node === document.activeElement));
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
assert(await page.locator('#identityDialog').isHidden());
|
||||||
|
assert(await page.locator('#resolveIdentity').evaluate(node => node === document.activeElement));
|
||||||
|
|
||||||
|
// Native links keep URLs, browser Back, and context-menu/new-tab behavior.
|
||||||
|
assert.equal(await page.locator('#applicationsTab').getAttribute('href'), '/belki?section=applications');
|
||||||
|
await page.locator('#applicationsTab').click();
|
||||||
|
assert.equal(new URL(page.url()).searchParams.get('section'), 'applications');
|
||||||
|
await page.goBack();
|
||||||
|
assert(await page.locator('#reportsSection').isVisible());
|
||||||
|
await page.goForward();
|
||||||
|
assert(await page.locator('#applicationsSection').isVisible());
|
||||||
|
|
||||||
|
// Both application entry points expose file inputs and reset hidden fields.
|
||||||
|
for (const standalone of [false, true]) {
|
||||||
|
if (standalone) await page.goto(`${origin}/applications`);
|
||||||
|
const type = value => page.locator(standalone ? `[data-type="${value}"]` : `[data-application-type="${value}"]`);
|
||||||
|
const practiced = page.locator('[name="practiced_before"]');
|
||||||
|
const practiceLink = page.locator('[name="practice_review_link"]');
|
||||||
|
await type('flying_squirrel').click();
|
||||||
|
assert(await practiceLink.isDisabled());
|
||||||
|
await practiced.selectOption('yes');
|
||||||
|
assert(await practiceLink.isVisible());
|
||||||
|
await type('kitten').click();
|
||||||
|
const applicationForm = page.locator(standalone ? '#form' : '#applicationForm');
|
||||||
|
const file = applicationForm.locator('input[type="file"]:not(:disabled)');
|
||||||
|
assert(await file.isVisible());
|
||||||
|
await file.focus();
|
||||||
|
assert(await file.evaluate(node => node === document.activeElement));
|
||||||
|
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||||
|
if (process.env.BELKI_SCREENSHOT_DIR) {
|
||||||
|
await page.screenshot({ path: `${process.env.BELKI_SCREENSHOT_DIR}/applications-${standalone ? 'standalone' : 'main'}-${width}.png`, fullPage: true });
|
||||||
|
}
|
||||||
|
await type('flying_squirrel').click();
|
||||||
|
await practiced.selectOption('no');
|
||||||
|
assert(await practiceLink.isDisabled());
|
||||||
|
assert(await practiceLink.isHidden());
|
||||||
|
|
||||||
|
// An in-flight submission cannot post a duplicate application.
|
||||||
|
await type('feather_donation').click();
|
||||||
|
await applicationForm.locator('[name="name"]').fill('Тестовая белка');
|
||||||
|
await applicationForm.locator('[name="character_id"]').fill('103');
|
||||||
|
for (const [field, value] of Object.entries({ amount: '1', color: 'синее', source: 'тестовые запасы' })) {
|
||||||
|
await applicationForm.locator(`[data-field="${field}"], [data-application-field="${field}"]`).fill(value);
|
||||||
|
}
|
||||||
|
let finish;
|
||||||
|
const pending = new Promise(resolve => { finish = resolve; });
|
||||||
|
let submissions = 0;
|
||||||
|
const submitApplication = async route => { submissions += 1; await pending; await route.fulfill({ json: { id: 55 } }); };
|
||||||
|
await page.route('**/api/applications', submitApplication);
|
||||||
|
const submitted = page.waitForRequest('**/api/applications');
|
||||||
|
await applicationForm.locator('[type="submit"]').click();
|
||||||
|
await submitted;
|
||||||
|
assert(await applicationForm.locator('[type="submit"]').isDisabled());
|
||||||
|
await applicationForm.evaluate(form => form.requestSubmit());
|
||||||
|
finish();
|
||||||
|
await page.locator(standalone ? '#success' : '#applicationSuccess').waitFor({ state: 'visible' });
|
||||||
|
assert.equal(submissions, 1);
|
||||||
|
await page.unroute('**/api/applications', submitApplication);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture useful review artifacts only when explicitly requested outside Git.
|
||||||
|
await page.goto(`${origin}/belki`);
|
||||||
|
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||||
|
if (process.env.BELKI_SCREENSHOT_DIR) {
|
||||||
|
await page.screenshot({ path: `${process.env.BELKI_SCREENSHOT_DIR}/calculator-${width}.png`, fullPage: true });
|
||||||
|
}
|
||||||
|
await page.goto(`${origin}/admin`);
|
||||||
|
assert(await page.getByLabel('Пароль', { exact: true }).isVisible());
|
||||||
|
|
||||||
|
// Review screens use pressed buttons; native gallery Escape restores focus.
|
||||||
|
await page.route('**/api/admin/session', route => route.fulfill({ json: { authenticated: true } }));
|
||||||
|
const photo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j8WQAAAAASUVORK5CYII=';
|
||||||
|
await page.route('**/api/admin/calculations?*', route => route.fulfill({ json: { items: [
|
||||||
|
{ id: 1, created_at: '2026-11-14T10:00:00Z', message: 'Тестовый отчёт', input: { mode: 'training', attachments: [{ url: photo }] } },
|
||||||
|
] } }));
|
||||||
|
await page.route('**/api/admin/applications?*', route => route.fulfill({ json: { items: [] } }));
|
||||||
|
await page.routeWebSocket('**/api/admin/updates', () => {});
|
||||||
|
await page.reload();
|
||||||
|
await page.locator('#appView').waitFor({ state: 'visible' });
|
||||||
|
assert.equal(await page.locator('#reportPeriod').inputValue(), 'current_month');
|
||||||
|
assert.equal(await page.locator('#sort').inputValue(), 'date');
|
||||||
|
assert.equal(await page.locator('#direction').inputValue(), 'desc');
|
||||||
|
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||||
|
await page.locator('[data-category="training"]').click();
|
||||||
|
assert.equal(await page.locator('[data-category="training"]').getAttribute('aria-pressed'), 'true');
|
||||||
|
const thumbnail = page.getByRole('button', { name: 'Открыть фото 1' });
|
||||||
|
await thumbnail.click();
|
||||||
|
await page.getByRole('dialog', { name: 'Скриншоты отчёта' }).waitFor();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
assert(await page.locator('#galleryDialog').isHidden());
|
||||||
|
assert(await thumbnail.evaluate(node => node === document.activeElement));
|
||||||
|
if (process.env.BELKI_SCREENSHOT_DIR) {
|
||||||
|
await page.screenshot({ path: `${process.env.BELKI_SCREENSHOT_DIR}/admin-${width}.png`, fullPage: true });
|
||||||
|
}
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
console.log(`PASS ${width}px: labels, keyboard, calculations, races, clipboard, dialogs, links, applications, admin filters`);
|
||||||
|
} finally {
|
||||||
|
await context.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run().catch(error => { console.error(error); process.exitCode = 1; });
|
||||||
+32
-27
@@ -21,11 +21,14 @@
|
|||||||
.tabs { display: flex; flex-wrap: wrap; gap: 8px; padding: 22px 0 4px; border-bottom: 1px solid var(--line); }
|
.tabs { display: flex; flex-wrap: wrap; gap: 8px; padding: 22px 0 4px; border-bottom: 1px solid var(--line); }
|
||||||
.tab { min-height: 36px; padding: 7px 13px; border: 1px solid transparent; border-radius: 999px; background: transparent; color: var(--muted); font-size: .84rem; }
|
.tab { min-height: 36px; padding: 7px 13px; border: 1px solid transparent; border-radius: 999px; background: transparent; color: var(--muted); font-size: .84rem; }
|
||||||
.tab:hover { border-color: #cfc8bf; background: #fffaf3; color: var(--ink); }
|
.tab:hover { border-color: #cfc8bf; background: #fffaf3; color: var(--ink); }
|
||||||
.tab[aria-selected="true"] { border-color: var(--ink); background: var(--ink); color: #fffdfa; }
|
.tab[aria-pressed="true"] { text-decoration:underline; text-underline-offset:4px; border-color: var(--ink); background: var(--ink); color: #fffdfa; }
|
||||||
.auth-view { width: min(480px, 100%); margin: 14vh auto 0; padding: 34px; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); box-shadow: 0 12px 35px #3b302414; }
|
.auth-view { width: min(480px, 100%); margin: 14vh auto 0; padding: 34px; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); box-shadow: 0 12px 35px #3b302414; }
|
||||||
.auth-view p { margin: 0 0 24px; color: var(--muted); line-height: 1.55; }
|
.auth-view p { margin: 0 0 24px; color: var(--muted); line-height: 1.55; }
|
||||||
.auth-form { display: flex; gap: 10px; }
|
.auth-form { display: flex; gap: 10px; }
|
||||||
.auth-form input { flex: 1; min-width: 0; }
|
.auth-form input { width:100%; min-width:0; }
|
||||||
|
.password-field { display:grid; gap:6px; flex:1; min-width:0; }
|
||||||
|
.auth-form { align-items:end; }
|
||||||
|
.auth-view h1 { font-size:2rem; margin-bottom:8px; }
|
||||||
.controls { display: flex; flex-wrap: wrap; align-items: end; gap: 12px; padding: 20px 0; }
|
.controls { display: flex; flex-wrap: wrap; align-items: end; gap: 12px; padding: 20px 0; }
|
||||||
.control-group { display: grid; gap: 6px; color: var(--muted); font-size: .72rem; font-weight: 750; letter-spacing: .055em; text-transform: uppercase; }
|
.control-group { display: grid; gap: 6px; color: var(--muted); font-size: .72rem; font-weight: 750; letter-spacing: .055em; text-transform: uppercase; }
|
||||||
.control-group input, .control-group select { align-self: start; }
|
.control-group input, .control-group select { align-self: start; }
|
||||||
@@ -52,7 +55,7 @@
|
|||||||
input { min-width: 245px; }
|
input { min-width: 245px; }
|
||||||
input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px #b86f3b22; }
|
input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px #b86f3b22; }
|
||||||
button { border: 1px solid var(--ink); padding: 9px 16px; background: var(--ink); color: #fffdfa; cursor: pointer; font-weight: 650; transition: background-color 160ms ease-out, border-color 160ms ease-out, color 160ms ease-out; }
|
button { border: 1px solid var(--ink); padding: 9px 16px; background: var(--ink); color: #fffdfa; cursor: pointer; font-weight: 650; transition: background-color 160ms ease-out, border-color 160ms ease-out, color 160ms ease-out; }
|
||||||
button:focus-visible, a:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; }
|
input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible, a:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; }
|
||||||
button:hover { background: #45413d; }
|
button:hover { background: #45413d; }
|
||||||
.export-link { display: inline-flex; min-height: 42px; align-items: center; justify-content: center; padding: 9px 16px; border: 1px solid var(--accent); border-radius: 7px; color: var(--accent); font-weight: 650; text-decoration: none; }
|
.export-link { display: inline-flex; min-height: 42px; align-items: center; justify-content: center; padding: 9px 16px; border: 1px solid var(--accent); border-radius: 7px; color: var(--accent); font-weight: 650; text-decoration: none; }
|
||||||
.export-link:hover { background: #fff4ea; }
|
.export-link:hover { background: #fff4ea; }
|
||||||
@@ -90,15 +93,17 @@
|
|||||||
.admin-section { padding-top: 28px; }
|
.admin-section { padding-top: 28px; }
|
||||||
.applications { padding-top: 4px; }
|
.applications { padding-top: 4px; }
|
||||||
.application-layout { display: grid; grid-template-columns: minmax(260px, .8fr) minmax(380px, 1.2fr); border: 1px solid var(--line); border-radius: 9px; overflow: hidden; background: var(--paper); }
|
.application-layout { display: grid; grid-template-columns: minmax(260px, .8fr) minmax(380px, 1.2fr); border: 1px solid var(--line); border-radius: 9px; overflow: hidden; background: var(--paper); }
|
||||||
.application-list { border-right: 1px solid var(--line); }.application-item { display: block; width: 100%; min-height: 76px; padding: 15px 16px; border: 0; border-bottom: 1px solid #ebe7e0; border-radius: 0; background: transparent; color: var(--ink); text-align: left; }.application-item:last-child { border-bottom: 0; }.application-item[aria-selected="true"] { background: #f0f7ee; }.application-item strong,.application-item span { display:block; }.application-item span { margin-top:4px; color:var(--muted); font-size:.82rem; }.application-detail { min-height: 360px; padding: 25px; }.application-detail dl { display:grid; grid-template-columns: 150px 1fr; gap:12px 16px; margin:22px 0; }.application-detail dt { color:var(--muted); font-size:.8rem; font-weight:750; text-transform:uppercase; letter-spacing:.05em; }.application-detail dd { margin:0; white-space:pre-wrap; }.application-detail .photos { max-width:none; margin:0 0 18px; }.application-detail .photos button { width:120px; height:90px; }.application-actions { display:flex; flex-wrap:wrap; gap:10px; margin-top:18px; }.accept { border-color:#247036; background:#247036; }.accept:hover { background:#185627; }.reject { border-color:#a23d35; background:transparent; color:#8e3630; }.reject:hover { background:#fff1ef; }
|
.application-list { border-right: 1px solid var(--line); }.application-item { display: block; width: 100%; min-height: 76px; padding: 15px 16px; border: 0; border-bottom: 1px solid #ebe7e0; border-radius: 0; background: transparent; color: var(--ink); text-align: left; }.application-item:last-child { border-bottom: 0; }.application-item[aria-pressed="true"] { text-decoration:underline; text-underline-offset:4px; background: #f0f7ee; }.application-item strong,.application-item span { display:block; }.application-item span { margin-top:4px; color:var(--muted); font-size:.82rem; }.application-detail { min-height: 360px; padding: 25px; }.application-detail dl { display:grid; grid-template-columns: 150px 1fr; gap:12px 16px; margin:22px 0; }.application-detail dt { color:var(--muted); font-size:.8rem; font-weight:750; text-transform:uppercase; letter-spacing:.05em; }.application-detail dd { margin:0; white-space:pre-wrap; }.application-detail .photos { max-width:none; margin:0 0 18px; }.application-detail .photos button { width:120px; height:90px; }.application-actions { display:flex; flex-wrap:wrap; gap:10px; margin-top:18px; }.accept { border-color:#247036; background:#247036; }.accept:hover { background:#185627; }.reject { border-color:#a23d35; background:transparent; color:#8e3630; }.reject:hover { background:#fff1ef; }
|
||||||
dialog { width: min(900px, calc(100% - 32px)); padding: 0; border: 1px solid #5a524b; border-radius: 10px; background: #24211f; color: #fffdfa; box-shadow: 0 24px 80px #211b18aa; }
|
dialog { width: min(900px, calc(100% - 32px)); padding: 0; border: 1px solid #5a524b; border-radius: 10px; background: #24211f; color: #fffdfa; box-shadow: 0 24px 80px #211b18aa; }
|
||||||
dialog::backdrop { background: #211b1877; }
|
dialog:modal { overscroll-behavior:contain; }
|
||||||
|
dialog::backdrop { background: #211b1877; overflow:hidden; overscroll-behavior:contain; }
|
||||||
.gallery { display: grid; grid-template-columns: 52px 1fr 52px; align-items: center; gap: 12px; padding: 16px; }
|
.gallery { display: grid; grid-template-columns: 52px 1fr 52px; align-items: center; gap: 12px; padding: 16px; }
|
||||||
.gallery img { display: block; width: 100%; max-height: 72vh; object-fit: contain; }
|
.gallery img { display: block; width: 100%; max-height: 72vh; object-fit: contain; }
|
||||||
.gallery button { width: 44px; min-height: 44px; padding: 0; border-color: #665d56; background: #3a3430; font-size: 1.25rem; }
|
.gallery button { width: 44px; min-height: 44px; padding: 0; border-color: #665d56; background: #3a3430; font-size: 1.25rem; }
|
||||||
.gallery button:hover { background: #514840; }
|
.gallery button:hover { background: #514840; }
|
||||||
.gallery-footer { display: flex; justify-content: space-between; align-items: center; padding: 0 18px 16px; color: #c8bfb8; font-size: .85rem; }
|
.gallery-footer { display: flex; justify-content: space-between; align-items: center; padding: 0 18px 16px; color: #c8bfb8; font-size: .85rem; }
|
||||||
.gallery-footer button { min-height: 34px; padding: 5px 10px; }
|
.gallery-footer button { min-height: 34px; padding: 5px 10px; }
|
||||||
|
@media (pointer: coarse) { .tab, .delete, .gallery-footer button, .weekday-options label { min-height:48px; } }
|
||||||
@media (max-width: 720px) { main { width: calc(100% - 28px); padding-top: 28px; } .topbar { display: block; } .record-count { display: block; margin-top: 18px; } .controls { display: grid; grid-template-columns: 1fr 1fr; } .control-group:first-child, .controls > button, .controls > .export-link { grid-column: 1 / -1; } input { min-width: 0; width: 100%; } .auth-form { display: grid; } .application-layout { grid-template-columns:1fr; }.application-list { border-right:0; border-bottom:1px solid var(--line); }.application-detail dl { grid-template-columns:1fr; gap:4px; }.application-detail dd { margin-bottom:14px; } .weekday-field { grid-column: 1 / -1; min-width: 0; } .weekday-options { gap: 4px; } }
|
@media (max-width: 720px) { main { width: calc(100% - 28px); padding-top: 28px; } .topbar { display: block; } .record-count { display: block; margin-top: 18px; } .controls { display: grid; grid-template-columns: 1fr 1fr; } .control-group:first-child, .controls > button, .controls > .export-link { grid-column: 1 / -1; } input { min-width: 0; width: 100%; } .auth-form { display: grid; } .application-layout { grid-template-columns:1fr; }.application-list { border-right:0; border-bottom:1px solid var(--line); }.application-detail dl { grid-template-columns:1fr; gap:4px; }.application-detail dd { margin-bottom:14px; } .weekday-field { grid-column: 1 / -1; min-width: 0; } .weekday-options { gap: 4px; } }
|
||||||
</style>
|
</style>
|
||||||
<link rel="stylesheet" href="/api/weather/effect.css">
|
<link rel="stylesheet" href="/api/weather/effect.css">
|
||||||
@@ -108,10 +113,10 @@
|
|||||||
<div class="leaf-field" aria-hidden="true"><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span></div>
|
<div class="leaf-field" aria-hidden="true"><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span><span class="leaf"></span></div>
|
||||||
<main>
|
<main>
|
||||||
<section id="authView" class="auth-view">
|
<section id="authView" class="auth-view">
|
||||||
<h2>Админская панель</h2>
|
<h1>Админская панель</h1>
|
||||||
<p>Введите пароль администратора, чтобы открыть историю отчётов.</p>
|
<p>Введите пароль администратора, чтобы открыть историю отчётов.</p>
|
||||||
<form id="authForm" class="auth-form">
|
<form id="authForm" class="auth-form">
|
||||||
<input id="password" type="password" autocomplete="current-password" placeholder="Пароль" required>
|
<label for="password" class="password-field">Пароль<input id="password" type="password" autocomplete="current-password" name="password" required></label>
|
||||||
<button type="submit" id="authButton">Войти</button>
|
<button type="submit" id="authButton">Войти</button>
|
||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
@@ -121,21 +126,21 @@
|
|||||||
<div><h1>Админская панель</h1><p class="intro">Расчёты и заявки из бота VK и с сайта.</p></div>
|
<div><h1>Админская панель</h1><p class="intro">Расчёты и заявки из бота VK и с сайта.</p></div>
|
||||||
</header>
|
</header>
|
||||||
<nav class="tabs" aria-label="Раздел админской панели">
|
<nav class="tabs" aria-label="Раздел админской панели">
|
||||||
<button class="admin-tab tab" type="button" data-admin-view="reports" aria-selected="true">Отчёты</button>
|
<button class="admin-tab tab" type="button" data-admin-view="reports" aria-pressed="true">Отчёты</button>
|
||||||
<button class="admin-tab tab" type="button" data-admin-view="applications" aria-selected="false">Заявки</button>
|
<button class="admin-tab tab" type="button" data-admin-view="applications" aria-pressed="false">Заявки</button>
|
||||||
<button class="admin-tab tab" type="button" data-admin-view="vk" aria-selected="false">Беседы VK</button>
|
<button class="admin-tab tab" type="button" data-admin-view="vk" aria-pressed="false">Беседы VK</button>
|
||||||
</nav>
|
</nav>
|
||||||
<section id="reportsView" class="admin-section">
|
<section id="reportsView" class="admin-section">
|
||||||
<header class="topbar">
|
<header class="topbar">
|
||||||
<div><h1>История отчётов</h1><p class="intro">Подтверждённые расчёты из VK-бота и веб-калькулятора.</p></div>
|
<div><h2>История отчётов</h2><p class="intro">Подтверждённые расчёты из VK-бота и веб-калькулятора.</p></div>
|
||||||
<div class="record-count" id="recordCount">Записи не загружены</div>
|
<div class="record-count" id="recordCount">Записи не загружены</div>
|
||||||
</header>
|
</header>
|
||||||
<nav class="tabs" aria-label="Категория отчётов">
|
<nav class="tabs" aria-label="Категория отчётов">
|
||||||
<button class="tab" type="button" data-category="all" aria-selected="true">Все</button>
|
<button class="tab" type="button" data-category="all" aria-pressed="true">Все</button>
|
||||||
<button class="tab" type="button" data-category="inspection" aria-selected="false">Осмотры</button>
|
<button class="tab" type="button" data-category="inspection" aria-pressed="false">Осмотры</button>
|
||||||
<button class="tab" type="button" data-category="lu" aria-selected="false">Лазание (ЛУ)</button>
|
<button class="tab" type="button" data-category="lu" aria-pressed="false">Лазание (ЛУ)</button>
|
||||||
<button class="tab" type="button" data-category="zu" aria-selected="false">Зоркость (ЗУ)</button>
|
<button class="tab" type="button" data-category="zu" aria-pressed="false">Зоркость (ЗУ)</button>
|
||||||
<button class="tab" type="button" data-category="training" aria-selected="false">ПУ / уроки</button>
|
<button class="tab" type="button" data-category="training" aria-pressed="false">ПУ / уроки</button>
|
||||||
</nav>
|
</nav>
|
||||||
<section class="controls" aria-label="Фильтры истории">
|
<section class="controls" aria-label="Фильтры истории">
|
||||||
<label class="control-group">Сортировать по<select id="sort"><option value="date" selected>Дате</option><option value="cat">Коту</option><option value="kitten">Котёнку</option><option value="photo">Фото</option><option value="message">Сообщению</option><option value="author">Автору</option><option value="id">ID</option></select></label>
|
<label class="control-group">Сортировать по<select id="sort"><option value="date" selected>Дате</option><option value="cat">Коту</option><option value="kitten">Котёнку</option><option value="photo">Фото</option><option value="message">Сообщению</option><option value="author">Автору</option><option value="id">ID</option></select></label>
|
||||||
@@ -151,7 +156,7 @@
|
|||||||
<p class="error" id="error" role="alert"></p>
|
<p class="error" id="error" role="alert"></p>
|
||||||
<div class="table-wrap"><table><thead><tr><th>Внесено</th><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Баллы</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="10">Загрузка истории…</td></tr></tbody></table></div>
|
<div class="table-wrap"><table><thead><tr><th>Внесено</th><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Баллы</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="10">Загрузка истории…</td></tr></tbody></table></div>
|
||||||
</section>
|
</section>
|
||||||
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые заявки из бота VK и с сайта.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-selected="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
|
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые заявки из бота VK и с сайта.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-pressed="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-pressed="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-pressed="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
|
||||||
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
|
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
|
||||||
<header class="topbar"><div><h2 id="vkTitle">Беседы VK</h2><p class="intro">Беседы и расписания сообщений. Время указано по Москве. Каждое расписание включается отдельно.</p></div><div class="record-count" id="vkCount">Не загружено</div></header>
|
<header class="topbar"><div><h2 id="vkTitle">Беседы VK</h2><p class="intro">Беседы и расписания сообщений. Время указано по Москве. Каждое расписание включается отдельно.</p></div><div class="record-count" id="vkCount">Не загружено</div></header>
|
||||||
<section class="vk-step" aria-labelledby="vkTemplateStep"><h3 id="vkTemplateStep">1. Шаблон сообщения</h3><p>Сначала сохраните текст сообщения. Переносы строк сохранятся.</p><div class="vk-template-grid"><label class="control-group">Текст сообщения<textarea id="vkTemplateText" maxlength="4096" placeholder="Например: напоминание об еженедельном отчёте"></textarea><span id="vkTemplateCount" class="muted">0 / 4096</span></label><div><div class="control-group">Предпросмотр</div><pre id="vkTemplatePreview" class="vk-template-preview">Выберите сохранённый шаблон или напишите новый текст.</pre></div></div><div class="vk-template-actions"><label class="control-group">Название шаблона<input id="vkTemplateName" maxlength="100" placeholder="Например, Понедельник"></label><button id="saveVkTemplate" type="button">Сохранить шаблон</button><button id="loadVk" type="button">Обновить данные</button></div></section>
|
<section class="vk-step" aria-labelledby="vkTemplateStep"><h3 id="vkTemplateStep">1. Шаблон сообщения</h3><p>Сначала сохраните текст сообщения. Переносы строк сохранятся.</p><div class="vk-template-grid"><label class="control-group">Текст сообщения<textarea id="vkTemplateText" maxlength="4096" placeholder="Например: напоминание об еженедельном отчёте"></textarea><span id="vkTemplateCount" class="muted">0 / 4096</span></label><div><div class="control-group">Предпросмотр</div><pre id="vkTemplatePreview" class="vk-template-preview">Выберите сохранённый шаблон или напишите новый текст.</pre></div></div><div class="vk-template-actions"><label class="control-group">Название шаблона<input id="vkTemplateName" maxlength="100" placeholder="Например, Понедельник"></label><button id="saveVkTemplate" type="button">Сохранить шаблон</button><button id="loadVk" type="button">Обновить данные</button></div></section>
|
||||||
@@ -162,9 +167,9 @@
|
|||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<dialog id="galleryDialog">
|
<dialog id="galleryDialog" aria-label="Скриншоты отчёта">
|
||||||
<div class="gallery"><button id="prevPhoto" type="button" aria-label="Предыдущее фото">←</button><img id="galleryImage" alt="Фото отчёта"><button id="nextPhoto" type="button" aria-label="Следующее фото">→</button></div>
|
<div class="gallery"><button id="prevPhoto" type="button" aria-label="Предыдущее фото">←</button><img id="galleryImage" alt="Фото отчёта"><button id="nextPhoto" type="button" aria-label="Следующее фото">→</button></div>
|
||||||
<div class="gallery-footer"><span id="galleryCounter"></span><button id="closeGallery" type="button">Закрыть</button></div>
|
<div class="gallery-footer"><span id="galleryCounter" role="status"></span><button id="closeGallery" type="button">Закрыть</button></div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
@@ -211,7 +216,7 @@
|
|||||||
function photoCell(attachments) {
|
function photoCell(attachments) {
|
||||||
const node = document.createElement('td'); const gallery = document.createElement('div'); gallery.className = 'photos';
|
const node = document.createElement('td'); const gallery = document.createElement('div'); gallery.className = 'photos';
|
||||||
const validPhotos = (attachments || []).filter(photo => photo.mirror_url || photo.url);
|
const validPhotos = (attachments || []).filter(photo => photo.mirror_url || photo.url);
|
||||||
validPhotos.forEach((photo, index) => { const url = photo.mirror_url || photo.url; const button = document.createElement('button'); button.type = 'button'; button.title = 'Открыть фото'; const image = document.createElement('img'); image.src = url; image.alt = 'Фото отчёта'; image.loading = 'lazy'; button.append(image); button.addEventListener('click', () => openGallery(validPhotos, index)); gallery.append(button); });
|
validPhotos.forEach((photo, index) => { const url = photo.mirror_url || photo.url; const button = document.createElement('button'); button.type = 'button'; button.setAttribute('aria-label', `Открыть фото ${index + 1}`); const image = document.createElement('img'); image.src = url; image.alt = 'Фото отчёта'; image.loading = 'lazy'; button.append(image); button.addEventListener('click', () => openGallery(validPhotos, index)); gallery.append(button); });
|
||||||
if (gallery.childElementCount) node.append(gallery); else node.textContent = '—'; return node;
|
if (gallery.childElementCount) node.append(gallery); else node.textContent = '—'; return node;
|
||||||
}
|
}
|
||||||
// Formats stored ISO timestamps for the Russian admin table without shifting their clock time.
|
// Formats stored ISO timestamps for the Russian admin table without shifting their clock time.
|
||||||
@@ -236,13 +241,13 @@
|
|||||||
// Extracts display fields from one application for the detail panel.
|
// Extracts display fields from one application for the detail panel.
|
||||||
function applicationFields(item) { const a = item.application || {}; const fields = [['Тип', applicationLabels[a.type] || a.type], ['Персонаж', `${a.name || '—'}${a.character_id ? ` [${a.character_id}]` : ''}`], ['Источник', item.source === 'vk' ? 'VK-бот' : 'Веб-форма']]; if (a.vk_link) fields.push(['VK', a.vk_link]); if (a.type === 'flying_squirrel') { fields.push(['Практика ранее', a.practiced_before ? 'Да' : 'Нет']); if (a.practice_review_link) fields.push(['Комментарий практики', a.practice_review_link]); } if (a.type === 'feather_donation') fields.push(['Перья', (a.feathers || []).map(x => `${x.amount} ${x.color}, источник: ${x.source}`).join('\n')]); if (a.type === 'curator') fields.push(['Подтверждение', 'Скриншот ЛУ с дробью']); return fields; }
|
function applicationFields(item) { const a = item.application || {}; const fields = [['Тип', applicationLabels[a.type] || a.type], ['Персонаж', `${a.name || '—'}${a.character_id ? ` [${a.character_id}]` : ''}`], ['Источник', item.source === 'vk' ? 'VK-бот' : 'Веб-форма']]; if (a.vk_link) fields.push(['VK', a.vk_link]); if (a.type === 'flying_squirrel') { fields.push(['Практика ранее', a.practiced_before ? 'Да' : 'Нет']); if (a.practice_review_link) fields.push(['Комментарий практики', a.practice_review_link]); } if (a.type === 'feather_donation') fields.push(['Перья', (a.feathers || []).map(x => `${x.amount} ${x.color}, источник: ${x.source}`).join('\n')]); if (a.type === 'curator') fields.push(['Подтверждение', 'Скриншот ЛУ с дробью']); return fields; }
|
||||||
// Renders pending or accepted applications and their actions.
|
// Renders pending or accepted applications and their actions.
|
||||||
function renderApplications() { syncApplicationsExport(); const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications; document.querySelector('#applicationCount').textContent = `${visible.length} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const actions=document.createElement('div');actions.className='application-actions';const review=async(action,button)=>{button.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/${action}`,{method:'PATCH'}),data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось изменить статус заявки');await loadApplications()}catch(err){error.textContent=err.message;button.disabled=false}};const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=()=>review('accept',accept);const reject=document.createElement('button');reject.className='reject';reject.type='button';reject.textContent='Отклонить';reject.onclick=()=>review('reject',reject);actions.append(accept,reject);detail.append(actions)} }
|
function renderApplications() { syncApplicationsExport(); const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications; document.querySelector('#applicationCount').textContent = `${visible.length} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-pressed', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const actions=document.createElement('div');actions.className='application-actions';const review=async(action,button)=>{button.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/${action}`,{method:'PATCH'}),data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось изменить статус заявки');await loadApplications()}catch(err){error.textContent=err.message;button.disabled=false}};const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=()=>review('accept',accept);const reject=document.createElement('button');reject.className='reject';reject.type='button';reject.textContent='Отклонить';reject.onclick=()=>review('reject',reject);actions.append(accept,reject);detail.append(actions)} }
|
||||||
// Loads applications from the admin API and renders the selected status.
|
// Loads applications from the admin API and renders the selected status.
|
||||||
async function loadApplications() { try { const response=await fetch(`/api/admin/applications?${queryFor(applicationPeriod, applicationDateFrom, applicationDateTo, {status: activeApplicationStatus})}`), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
|
async function loadApplications() { try { const response=await fetch(`/api/admin/applications?${queryFor(applicationPeriod, applicationDateFrom, applicationDateTo, {status: activeApplicationStatus})}`), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
|
||||||
// Opens the authenticated admin view and starts both data loaders.
|
// Opens the authenticated admin view and starts both data loaders.
|
||||||
async function openAdmin() { authView.classList.add('hidden'); appView.classList.remove('hidden'); await load(); await loadApplications(); connectUpdates(); }
|
async function openAdmin() { authView.classList.add('hidden'); appView.classList.remove('hidden'); await load(); await loadApplications(); connectUpdates(); }
|
||||||
// Authenticates the administrator and transitions to the admin view.
|
// Authenticates the administrator and transitions to the admin view.
|
||||||
async function authenticate(event) { event.preventDefault(); error.textContent = ''; authButton.disabled = true; try { const response = await fetch('/api/admin/auth', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({password: password.value})}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось войти'); password.value = ''; await openAdmin(); } catch (err) { const message = document.createElement('p'); message.textContent = err.message; message.className = 'error'; const old = authView.querySelector('.error'); if (old) old.remove(); authView.append(message); } finally { authButton.disabled = false; } }
|
async function authenticate(event) { event.preventDefault(); error.textContent = ''; authButton.disabled = true; try { const response = await fetch('/api/admin/auth', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({password: password.value})}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось войти'); password.value = ''; await openAdmin(); } catch (err) { const message = document.createElement('p'); message.textContent = err.message; message.className = 'error'; const old = authView.querySelector('.error'); if (old) old.remove(); message.setAttribute('role', 'alert'); authView.append(message); } finally { authButton.disabled = false; } }
|
||||||
// Maintains the live update WebSocket and reconnects after disconnects.
|
// Maintains the live update WebSocket and reconnects after disconnects.
|
||||||
function connectUpdates() { if (updatesSocket && (updatesSocket.readyState === WebSocket.OPEN || updatesSocket.readyState === WebSocket.CONNECTING)) return; const scheme = location.protocol === 'https:' ? 'wss' : 'ws'; updatesSocket = new WebSocket(`${scheme}://${location.host}/api/admin/updates`); updatesSocket.onmessage = async event => { try { if (JSON.parse(event.data).type === 'refresh') { await load(); await loadApplications(); } } catch (_) {} }; updatesSocket.onclose = () => { updatesSocket = null; clearTimeout(updatesRetry); updatesRetry = setTimeout(connectUpdates, 5000); }; }
|
function connectUpdates() { if (updatesSocket && (updatesSocket.readyState === WebSocket.OPEN || updatesSocket.readyState === WebSocket.CONNECTING)) return; const scheme = location.protocol === 'https:' ? 'wss' : 'ws'; updatesSocket = new WebSocket(`${scheme}://${location.host}/api/admin/updates`); updatesSocket.onmessage = async event => { try { if (JSON.parse(event.data).type === 'refresh') { await load(); await loadApplications(); } } catch (_) {} }; updatesSocket.onclose = () => { updatesSocket = null; clearTimeout(updatesRetry); updatesRetry = setTimeout(connectUpdates, 5000); }; }
|
||||||
// Restores an existing admin session when the page is reopened.
|
// Restores an existing admin session when the page is reopened.
|
||||||
@@ -250,13 +255,13 @@
|
|||||||
// Updates the current gallery image and counter.
|
// Updates the current gallery image and counter.
|
||||||
function updateGallery() { const photo = galleryPhotos[galleryIndex]; galleryImage.src = photo.mirror_url || photo.url; galleryCounter.textContent = `${galleryIndex + 1} из ${galleryPhotos.length}`; }
|
function updateGallery() { const photo = galleryPhotos[galleryIndex]; galleryImage.src = photo.mirror_url || photo.url; galleryCounter.textContent = `${galleryIndex + 1} из ${galleryPhotos.length}`; }
|
||||||
// Opens the photo gallery at the requested image index.
|
// Opens the photo gallery at the requested image index.
|
||||||
function openGallery(photos, index) { galleryPhotos = photos.filter(photo => photo.mirror_url || photo.url); galleryIndex = Math.min(index, galleryPhotos.length - 1); updateGallery(); if (galleryDialog.showModal) galleryDialog.showModal(); else galleryDialog.setAttribute('open', ''); }
|
function openGallery(photos, index) { galleryPhotos = photos.filter(photo => photo.mirror_url || photo.url); galleryIndex = Math.min(index, galleryPhotos.length - 1); updateGallery(); galleryDialog.showModal(); }
|
||||||
// Closes the photo gallery dialog.
|
// Closes the photo gallery dialog.
|
||||||
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
|
function closeGallery() { galleryDialog.close(); }
|
||||||
// Switches between report and application admin views.
|
// Switches between report and application admin views.
|
||||||
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelector('#vkView').classList.toggle('hidden', view !== 'vk'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); if(view==='vk')loadVk(); }
|
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelector('#vkView').classList.toggle('hidden', view !== 'vk'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-pressed', String(tab.dataset.adminView === view))); if(view==='vk')loadVk(); }
|
||||||
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', load); kittenFilter.addEventListener('change', load); [reportPeriod, reportDateFrom, reportDateTo].forEach(control => control.addEventListener('change', load)); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-selected', String(item === tab))); load(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
|
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', load); kittenFilter.addEventListener('change', load); [reportPeriod, reportDateFrom, reportDateTo].forEach(control => control.addEventListener('change', load)); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-pressed', String(item === tab))); load(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
|
||||||
document.querySelector('#loadApplications').addEventListener('click', loadApplications); [applicationPeriod, applicationDateFrom, applicationDateTo].forEach(control => control.addEventListener('change', loadApplications)); document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); loadApplications(); }));
|
document.querySelector('#loadApplications').addEventListener('click', loadApplications); [applicationPeriod, applicationDateFrom, applicationDateTo].forEach(control => control.addEventListener('change', loadApplications)); document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-pressed', String(item === tab))); loadApplications(); }));
|
||||||
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
|
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
|
||||||
document.querySelector('#loadVk').addEventListener('click', loadVk); document.querySelector('#saveVkTemplate').addEventListener('click', createVkTemplate);
|
document.querySelector('#loadVk').addEventListener('click', loadVk); document.querySelector('#saveVkTemplate').addEventListener('click', createVkTemplate);
|
||||||
document.querySelector('#saveVkSchedule').addEventListener('click', createVkSchedule);
|
document.querySelector('#saveVkSchedule').addEventListener('click', createVkSchedule);
|
||||||
|
|||||||
+47
-9
@@ -10,39 +10,77 @@
|
|||||||
.intro, .hint, .status { color: #62675f; line-height: 1.55; } .intro { margin: 13px 0 31px; max-width: 640px; }
|
.intro, .hint, .status { color: #62675f; line-height: 1.55; } .intro { margin: 13px 0 31px; max-width: 640px; }
|
||||||
.topnav { display:flex; justify-content:space-between; gap:15px; align-items:center; margin-bottom:52px; padding-bottom:18px; border-bottom:1px solid #e6e7e2; } .brand { color:#1d622e; font-weight:800; text-decoration:none; font-size:1.05rem; } .topnav a:not(.brand) { color:#4f554d; text-decoration:none; font-size:.92rem; }
|
.topnav { display:flex; justify-content:space-between; gap:15px; align-items:center; margin-bottom:52px; padding-bottom:18px; border-bottom:1px solid #e6e7e2; } .brand { color:#1d622e; font-weight:800; text-decoration:none; font-size:1.05rem; } .topnav a:not(.brand) { color:#4f554d; text-decoration:none; font-size:.92rem; }
|
||||||
.auth { max-width:470px; margin: 14vh auto; border:1px solid #e1e4dc; border-radius:14px; padding:28px; box-shadow:0 12px 35px #3340130b; }
|
.auth { max-width:470px; margin: 14vh auto; border:1px solid #e1e4dc; border-radius:14px; padding:28px; box-shadow:0 12px 35px #3340130b; }
|
||||||
.auth label, label { display:grid; gap:7px; color:#40453f; font-size:.84rem; font-weight:700; } input, select, textarea, button { font:inherit; } input, select, textarea { width:100%; min-height:44px; padding:10px 12px; border:1px solid #cfd4cb; border-radius:8px; background:#fff; color:#20241f; } textarea { min-height:105px; resize:vertical; } input:focus, select:focus, textarea:focus { outline:3px solid #2f813529; border-color:#2f8135; } button:focus-visible, a:focus-visible { outline:3px solid var(--focus); outline-offset:3px; }
|
.auth label, label { display:grid; gap:7px; color:#40453f; font-size:.84rem; font-weight:700; } input, select, textarea, button { font:inherit; } input, select, textarea { font-size:1rem; width:100%; min-height:44px; padding:10px 12px; border:1px solid #cfd4cb; border-radius:8px; background:#fff; color:#20241f; } textarea { min-height:105px; resize:vertical; } input:focus, select:focus, textarea:focus { outline:3px solid #2f813529; border-color:#2f8135; } input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible, a:focus-visible { outline:3px solid var(--focus); outline-offset:3px; }
|
||||||
.types { display:grid; grid-template-columns:repeat(2, minmax(0,1fr)); gap:10px; margin:25px 0 27px; } .type { display:flex; align-items:center; min-height:76px; padding:14px; text-align:left; color:#333a32; border:1px solid #dce1d8; border-radius:10px; background:#fff; cursor:pointer; font-weight:700; } .type::before { content:""; width:14px; height:14px; border:1px solid #aeb7ab; border-radius:50%; margin-right:11px; flex:0 0 auto; } .type.active { border-color:#237530; box-shadow:inset 0 0 0 1px #237530; } .type.active::before { border:4px solid #237530; }
|
.types { display:grid; grid-template-columns:repeat(2, minmax(0,1fr)); gap:10px; margin:25px 0 27px; } .type { display:flex; align-items:center; min-height:76px; padding:14px; text-align:left; color:#333a32; border:1px solid #dce1d8; border-radius:10px; background:#fff; cursor:pointer; font-weight:700; } .type::before { content:""; width:14px; height:14px; border:1px solid #aeb7ab; border-radius:50%; margin-right:11px; flex:0 0 auto; } .type.active { border-color:#237530; box-shadow:inset 0 0 0 1px #237530; } .type.active::before { border:4px solid #237530; }
|
||||||
.panel { border:1px solid #e0e4dc; border-radius:14px; padding:28px; box-shadow:0 14px 40px #3142190a; } .grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:16px; } .wide { grid-column:1/-1; } .hidden { display:none!important; }
|
.panel { border:1px solid #e0e4dc; border-radius:14px; padding:28px; box-shadow:0 14px 40px #3142190a; } .grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:16px; } .wide { grid-column:1/-1; } .hidden { display:none!important; }
|
||||||
.upload { display:grid; justify-items:center; gap:8px; min-height:150px; padding:24px; text-align:center; border:1px dashed #b8c3b3; border-radius:10px; background:#fbfdf9; color:#596259; cursor:pointer; } .upload strong { color:#333a32; } .upload input { display:none; } .files { margin:10px 0 0; padding-left:18px; color:#5a6258; font-size:.86rem; }
|
.upload { display:grid; justify-items:center; gap:8px; min-height:150px; padding:24px; text-align:center; border:1px dashed #b8c3b3; border-radius:10px; background:#fbfdf9; color:#596259; cursor:pointer; } .upload strong { color:#333a32; } .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:#5a6258; font-size:.86rem; }
|
||||||
.feather { display:grid; grid-template-columns:110px 1fr 1.3fr auto; gap:9px; align-items:end; margin-bottom:9px; } .remove { min-height:44px; padding:9px; background:#fff; border:1px solid #d9aaa5; color:#9b423a; border-radius:8px; cursor:pointer; } button.primary { min-height:48px; padding:10px 18px; border:1px solid #1e6a2b; border-radius:8px; background:#1e6a2b; color:#fff; cursor:pointer; font-weight:750; } button.primary:hover { background:#165521; } button.secondary { border:1px solid #bbc5b8; border-radius:8px; padding:9px 12px; background:#fff; color:#354234; cursor:pointer; }
|
.feather { display:grid; grid-template-columns:110px 1fr 1.3fr auto; gap:9px; align-items:end; margin-bottom:9px; } .remove { min-height:44px; padding:9px; background:#fff; border:1px solid #d9aaa5; color:#9b423a; border-radius:8px; cursor:pointer; } button.primary { min-height:48px; padding:10px 18px; border:1px solid #1e6a2b; border-radius:8px; background:#1e6a2b; color:#fff; cursor:pointer; font-weight:750; } button.primary:hover { background:#165521; } button.secondary { min-height:44px; border:1px solid #bbc5b8; border-radius:8px; padding:9px 12px; background:#fff; color:#354234; cursor:pointer; }
|
||||||
.actions { display:flex; justify-content:space-between; align-items:center; gap:16px; margin-top:25px; } .error { min-height:22px; color:#a13d35; white-space:pre-wrap; } .success { margin-top:24px; padding:18px; border-left:4px solid #268038; background:#f4fbf3; color:#244b2c; border-radius:7px; }
|
.actions { display:flex; justify-content:space-between; align-items:center; gap:16px; margin-top:25px; } .error { min-height:22px; color:#a13d35; white-space:pre-wrap; } .success { margin-top:24px; padding:18px; border-left:4px solid #268038; background:#f4fbf3; color:#244b2c; border-radius:7px; }
|
||||||
@media (max-width:640px) { main{width:calc(100% - 26px);padding-top:26px}.topnav{margin-bottom:34px}.types,.grid{grid-template-columns:1fr}.panel{padding:20px}.wide{grid-column:auto}.feather{grid-template-columns:1fr}.actions{align-items:stretch;flex-direction:column-reverse}.actions button{width:100%} }
|
@media (max-width:640px) { main{width:calc(100% - 26px);padding-top:26px}.topnav{margin-bottom:34px}.types,.grid{grid-template-columns:1fr}.panel{padding:20px}.wide{grid-column:auto}.feather{grid-template-columns:1fr}.actions{align-items:stretch;flex-direction:column-reverse}.actions button{width:100%} }
|
||||||
|
button:disabled { opacity:.55; cursor:not-allowed; }
|
||||||
|
input:user-invalid, textarea:user-invalid { border-color:#a13d35; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body><main>
|
<body><main>
|
||||||
<nav class="topnav"><a class="brand" href="/belki">Беличья нора</a><a href="/belki">Калькулятор отчётов</a></nav>
|
<nav class="topnav"><a class="brand" href="/belki">Беличья нора</a><a href="/belki">Калькулятор отчётов</a></nav>
|
||||||
<section id="app"><h1>Новая заявка</h1><p class="intro">Заполните форму, и администратор получит заявку. Готовить форумную отпись не нужно.</p>
|
<section id="app"><h1>Новая заявка</h1><p class="intro">Заполните форму, и администратор получит заявку. Готовить форумную отпись не нужно.</p>
|
||||||
<div class="types" role="radiogroup" aria-label="Тип заявки">
|
<div class="types" role="group" aria-label="Тип заявки">
|
||||||
<button class="type active" type="button" data-type="feather_donation">Пожертвовать перо отряду</button><button class="type" type="button" data-type="kitten">Хочу стать бельчонком</button><button class="type" type="button" data-type="flying_squirrel">Хочу стать белкой-летягой</button><button class="type" type="button" data-type="curator">Хочу стать куратором</button>
|
<button class="type active" type="button" data-type="feather_donation">Пожертвовать перо отряду</button><button class="type" type="button" data-type="kitten">Хочу стать бельчонком</button><button class="type" type="button" data-type="flying_squirrel">Хочу стать белкой-летягой</button><button class="type" type="button" data-type="curator">Хочу стать куратором</button>
|
||||||
</div>
|
</div>
|
||||||
<form id="form" class="panel"><div class="grid">
|
<form id="form" class="panel"><div class="grid">
|
||||||
<label>Имя кота<input name="name" required></label><label>ID кота<input name="character_id" type="number" min="1" required></label>
|
<label>Имя кота<input name="name" required></label><label>ID кота<input name="character_id" type="number" min="1" required></label>
|
||||||
<label id="vkField" class="wide">Ссылка на страницу VK <span class="hint">(необязательно)</span><input name="vk_link" type="text" inputmode="url" placeholder="vk.com/id… или vk.ru/id…"></label>
|
<label id="vkField" class="wide">Ссылка на страницу VK <span class="hint">(необязательно)</span><input name="vk_link" type="text" inputmode="url" placeholder="vk.com/id… или vk.ru/id…"></label>
|
||||||
<section id="kittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Перетащите изображение сюда или выберите файл</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
<section id="kittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Выберите изображение</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
||||||
<section id="curatorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
<section id="curatorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
||||||
<section id="flyingFields" class="wide hidden"><label>Уже сдавали практику?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="practiceLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/... или https://vk.com/... "></label></section>
|
<section id="flyingFields" class="wide hidden"><label>Уже сдавали практику?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="practiceLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/... или https://vk.com/... "></label></section>
|
||||||
<section id="featherFields" class="wide"><h2>Перья для казны</h2><p class="hint">Укажите цвет, количество и откуда получены перья.</p><div id="feathers"></div><button id="addFeather" class="secondary" type="button">Добавить перо</button></section>
|
<section id="featherFields" class="wide"><h2>Перья для казны</h2><p class="hint">Укажите цвет, количество и откуда получены перья.</p><div id="feathers"></div><button id="addFeather" class="secondary" type="button">Добавить перо</button></section>
|
||||||
</div><p id="error" class="error" role="alert"></p><div class="actions"><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden"></div>
|
</div><p id="error" class="error" role="alert"></p><div class="actions"><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden" role="status"></div>
|
||||||
</section>
|
</section>
|
||||||
</main><script>
|
</main><script>
|
||||||
/* Form helpers manage repeatable feather rows, conditional sections, image
|
/* Form helpers manage repeatable feather rows, conditional sections, image
|
||||||
uploads, and final serialization into the applications API payload. */
|
uploads, and final serialization into the applications API payload. */
|
||||||
const form=document.querySelector('#form'), error=document.querySelector('#error'); let active='feather_donation';
|
const form=document.querySelector('#form'), error=document.querySelector('#error'); let active='feather_donation', submitting=false;
|
||||||
function addFeather(data={}){const row=document.createElement('div');row.className='feather';row.innerHTML='<label>Количество<input data-field="amount" type="number" min="1" required></label><label>Цвет<input data-field="color" placeholder="например, синие" required></label><label>Источник добычи<input data-field="source" placeholder="личные запасы, осмотр дупла…" required></label><button class="remove" type="button">Убрать</button>';Object.entries(data).forEach(([k,v])=>{const el=row.querySelector(`[data-field="${k}"]`);if(el)el.value=v});row.querySelector('.remove').onclick=()=>row.remove();document.querySelector('#feathers').append(row)} addFeather();document.querySelector('#addFeather').onclick=()=>addFeather();
|
function addFeather(data={}){const row=document.createElement('div');row.className='feather';row.innerHTML='<label>Количество<input data-field="amount" type="number" min="1" required></label><label>Цвет<input data-field="color" placeholder="например, синие" required></label><label>Источник добычи<input data-field="source" placeholder="личные запасы, осмотр дупла…" required></label><button class="remove" type="button">Убрать</button>';Object.entries(data).forEach(([k,v])=>{const el=row.querySelector(`[data-field="${k}"]`);if(el)el.value=v});row.querySelector('.remove').onclick=()=>row.remove();document.querySelector('#feathers').append(row)} addFeather();document.querySelector('#addFeather').onclick=()=>addFeather();
|
||||||
function setVisible(selector,visible){const section=document.querySelector(selector);section.classList.toggle('hidden',!visible);section.querySelectorAll('input,select,textarea,button').forEach(field=>field.disabled=!visible)}
|
function setVisible(selector,visible){const section=document.querySelector(selector);section.classList.toggle('hidden',!visible);section.querySelectorAll('input,select,textarea,button').forEach(field=>field.disabled=!visible)}
|
||||||
function sync(){setVisible('#featherFields',active==='feather_donation');setVisible('#kittenFields',active==='kitten');setVisible('#curatorFields',active==='curator');setVisible('#flyingFields',active==='flying_squirrel');setVisible('#vkField',active==='flying_squirrel');const practiced=document.querySelector('[name="practiced_before"]');setVisible('#practiceLink',active==='flying_squirrel'&&practiced.value==='yes');document.querySelectorAll('.type').forEach(x=>x.classList.toggle('active',x.dataset.type===active))} document.querySelectorAll('.type').forEach(b=>b.onclick=()=>{active=b.dataset.type;sync()});sync();
|
function sync(){setVisible('#featherFields',active==='feather_donation');setVisible('#kittenFields',active==='kitten');setVisible('#curatorFields',active==='curator');setVisible('#flyingFields',active==='flying_squirrel');setVisible('#vkField',active==='flying_squirrel');const practiced=document.querySelector('[name="practiced_before"]');setVisible('#practiceLink',active==='flying_squirrel'&&practiced.value==='yes');document.querySelectorAll('.type').forEach(x=>{x.classList.toggle('active',x.dataset.type===active);x.setAttribute('aria-pressed',String(x.dataset.type===active))})} document.querySelectorAll('.type').forEach(b=>b.onclick=()=>{active=b.dataset.type;sync()});sync();
|
||||||
document.querySelector('[name="practiced_before"]').onchange=()=>sync();
|
document.querySelector('[name="practiced_before"]').onchange=()=>sync();
|
||||||
document.querySelectorAll('.screenshots').forEach(input=>input.onchange=()=>{const list=input.closest('section').querySelector('.files');list.replaceChildren(...[...input.files].map(file=>{const li=document.createElement('li');li.textContent=file.name;return li}))});
|
document.querySelectorAll('.screenshots').forEach(input=>input.onchange=()=>{const list=input.closest('section').querySelector('.files');list.replaceChildren(...[...input.files].map(file=>{const li=document.createElement('li');li.textContent=file.name;return li}))});
|
||||||
async function uploads(){const items=[];for(const file of [...document.querySelectorAll('.screenshots:not(:disabled)')].flatMap(x=>[...x.files])){const data=await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(file)});const r=await fetch('/api/web/upload',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:file.name,type:file.type,data})});const d=await r.json();if(!r.ok)throw new Error(d.error||`Не удалось загрузить ${file.name}`);items.push({type:'photo',url:d.url,name:file.name})}return items}
|
async function uploads(){const items=[];for(const file of [...document.querySelectorAll('.screenshots:not(:disabled)')].flatMap(x=>[...x.files])){const data=await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(file)});const r=await fetch('/api/web/upload',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:file.name,type:file.type,data})});const d=await r.json();if(!r.ok)throw new Error(d.error||`Не удалось загрузить ${file.name}`);items.push({type:'photo',url:d.url,name:file.name})}return items}
|
||||||
form.addEventListener('submit',async e=>{e.preventDefault();error.textContent='';try{const data=Object.fromEntries(new FormData(form).entries());data.type=active;data.character_id=Number(data.character_id);data.attachments=await uploads();if(active==='flying_squirrel'){data.practiced_before=data.practiced_before==='yes'}if(active==='feather_donation')data.feathers=[...document.querySelectorAll('.feather')].map(row=>({amount:Number(row.querySelector('[data-field="amount"]').value),color:row.querySelector('[data-field="color"]').value,source:row.querySelector('[data-field="source"]').value}));const r=await fetch('/api/applications',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Не удалось отправить заявку');const success=document.querySelector('#success');success.textContent=`Заявка №${d.id} отправлена на рассмотрение.`;success.classList.remove('hidden');form.reset();document.querySelector('#feathers').replaceChildren();addFeather();sync()}catch(err){error.textContent=err.message}});
|
form.addEventListener('submit', async event => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (submitting) return;
|
||||||
|
submitting = true;
|
||||||
|
const submit = form.querySelector('[type="submit"]');
|
||||||
|
submit.disabled = true;
|
||||||
|
submit.textContent = 'Отправляем…';
|
||||||
|
error.textContent = '';
|
||||||
|
document.querySelector('#success').classList.add('hidden');
|
||||||
|
try {
|
||||||
|
const data = Object.fromEntries(new FormData(form).entries());
|
||||||
|
data.type = active;
|
||||||
|
data.character_id = Number(data.character_id);
|
||||||
|
if (active === 'flying_squirrel') data.practiced_before = data.practiced_before === 'yes';
|
||||||
|
if (active === 'feather_donation') data.feathers = [...document.querySelectorAll('.feather')].map(row => ({
|
||||||
|
amount: Number(row.querySelector('[data-field="amount"]').value),
|
||||||
|
color: row.querySelector('[data-field="color"]').value,
|
||||||
|
source: row.querySelector('[data-field="source"]').value,
|
||||||
|
}));
|
||||||
|
data.attachments = await uploads();
|
||||||
|
const response = await fetch('/api/applications', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)});
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok) throw new Error(result.error || 'Не удалось отправить заявку');
|
||||||
|
const success = document.querySelector('#success');
|
||||||
|
success.textContent = `Заявка №${result.id} отправлена на рассмотрение.`;
|
||||||
|
success.classList.remove('hidden');
|
||||||
|
form.reset();
|
||||||
|
document.querySelector('#feathers').replaceChildren();
|
||||||
|
addFeather();
|
||||||
|
sync();
|
||||||
|
} catch (err) { error.textContent = err.message; }
|
||||||
|
finally {
|
||||||
|
submitting = false;
|
||||||
|
submit.disabled = false;
|
||||||
|
submit.textContent = 'Отправить заявку';
|
||||||
|
}
|
||||||
|
});
|
||||||
</script></body></html>
|
</script></body></html>
|
||||||
+156
-64
@@ -14,15 +14,25 @@
|
|||||||
h2 { font: 500 1.55rem/1.15 Georgia, "Times New Roman", serif; } .muted { color: var(--muted); line-height: 1.55; }
|
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; }
|
.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 { margin-top: 32px; border-bottom: 1px solid var(--line); padding-bottom: 16px; }
|
||||||
.section-tabs button { border-color: transparent; background: transparent; }
|
.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, 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 { 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 { outline:3px solid var(--focus); outline-offset:3px; }
|
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; }
|
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; }
|
.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; }
|
.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; }
|
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 { outline:3px solid #b5682433; border-color:var(--accent); }
|
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; }
|
textarea { min-height: 210px; resize: vertical; }
|
||||||
.wide { grid-column: 1 / -1; }
|
.wide { grid-column: 1 / -1; }
|
||||||
.actions { display: flex; gap: 10px; margin-top: 18px; }
|
.actions { display: flex; gap: 10px; margin-top: 18px; }
|
||||||
@@ -38,7 +48,8 @@
|
|||||||
.status-help { margin: -4px 0 0; font-size: .85rem; }
|
.status-help { margin: -4px 0 0; font-size: .85rem; }
|
||||||
@media (max-width: 700px) { .extra-kitten, .time-range { grid-template-columns: 1fr; } }
|
@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 { 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; }
|
dialog:modal { overscroll-behavior: contain; }
|
||||||
|
dialog::backdrop { background: #211b1866; overflow: hidden; overscroll-behavior: contain; }
|
||||||
.result { margin-top: 20px; }
|
.result { margin-top: 20px; }
|
||||||
.hidden { display: none; }
|
.hidden { display: none; }
|
||||||
.error { color: var(--error); font-weight:700; white-space: pre-wrap; }
|
.error { color: var(--error); font-weight:700; white-space: pre-wrap; }
|
||||||
@@ -47,9 +58,11 @@
|
|||||||
.application-intro { max-width: 68ch; margin: 0 0 24px; }
|
.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-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 { 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; }
|
.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 { 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; }
|
.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); }
|
.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; }
|
.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; }
|
.remove { color: var(--error); border-color: #d9aaa5; }
|
||||||
@@ -70,7 +83,7 @@
|
|||||||
.panel { padding: 16px; }
|
.panel { padding: 16px; }
|
||||||
.section-tabs { margin-top: 24px; padding-bottom: 12px; }
|
.section-tabs { margin-top: 24px; padding-bottom: 12px; }
|
||||||
.tabs { gap: 6px; margin: 18px 0 14px; }
|
.tabs { gap: 6px; margin: 18px 0 14px; }
|
||||||
.tabs button { flex: 1 1 144px; }
|
.section-tabs a, .mode-option { flex: 1 1 144px; }
|
||||||
.grid, .application-types, .feather { grid-template-columns: 1fr; }
|
.grid, .application-types, .feather { grid-template-columns: 1fr; }
|
||||||
.wide { grid-column: auto; }
|
.wide { grid-column: auto; }
|
||||||
.actions { flex-direction: column; }
|
.actions { flex-direction: column; }
|
||||||
@@ -94,32 +107,32 @@
|
|||||||
<h1>Генератор отчётов и калькулятор</h1>
|
<h1>Генератор отчётов и калькулятор</h1>
|
||||||
<p class="muted">Здесь можно подготовить отчёт, посчитать баллы и подать заявку.</p>
|
<p class="muted">Здесь можно подготовить отчёт, посчитать баллы и подать заявку.</p>
|
||||||
|
|
||||||
<nav class="tabs section-tabs" role="tablist" aria-label="Раздел Беличьей норы">
|
<nav class="tabs section-tabs" aria-label="Раздел Беличьей норы">
|
||||||
<button class="active" id="reportsTab" type="button" role="tab" aria-selected="true" aria-controls="reportsSection" data-section="reports">Отчёты</button>
|
<a id="reportsTab" href="/belki" aria-current="page" data-section="reports">Отчёты</a>
|
||||||
<button id="sentReportsTab" type="button" role="tab" aria-selected="false" aria-controls="sentReportsSection" data-section="sentReports">Отчёты по ID кота</button>
|
<a id="sentReportsTab" href="/belki?section=sentReports" data-section="sentReports">Отчёты по ID кота</a>
|
||||||
<button id="applicationsTab" type="button" role="tab" aria-selected="false" aria-controls="applicationsSection" data-section="applications">Заявки</button>
|
<a id="applicationsTab" href="/belki?section=applications" data-section="applications">Заявки</a>
|
||||||
<button id="identityTab" type="button" role="tab" aria-selected="false" aria-controls="identitySection" data-section="identity">Имя кота</button>
|
<a id="identityTab" href="/belki?section=identity" data-section="identity">Имя кота</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<section id="reportsSection" role="tabpanel" aria-labelledby="reportsTab">
|
<section id="reportsSection" aria-labelledby="reportsTab">
|
||||||
<p class="muted">На каждый заход нужен отдельный отчёт. Для осмотра прикрепите скриншот перед подготовкой сообщения. Для других отчётов он не нужен.</p>
|
<p class="muted">На каждый заход нужен отдельный отчёт. Для осмотра прикрепите скриншот перед подготовкой сообщения. Для других отчётов он не нужен.</p>
|
||||||
<div class="tabs" role="tablist" aria-label="Вид отчёта">
|
<fieldset class="mode-options"><legend>Вид расчёта</legend><div class="tabs">
|
||||||
<button class="active" data-mode="coaching">Прокачка ЛУ/ЗУ</button>
|
<label class="mode-option"><input type="radio" name="calculator_mode" value="coaching" data-mode="coaching" checked>Прокачка ЛУ/ЗУ</label>
|
||||||
<button data-mode="training">Тренировка</button>
|
<label class="mode-option"><input type="radio" name="calculator_mode" value="training" data-mode="training">Тренировка</label>
|
||||||
<button data-mode="inspection">Осмотры</button>
|
<label class="mode-option"><input type="radio" name="calculator_mode" value="inspection" data-mode="inspection">Осмотры</label>
|
||||||
<button data-mode="goal">Калькулятор цели</button>
|
<label class="mode-option"><input type="radio" name="calculator_mode" value="goal" data-mode="goal">Калькулятор цели</label>
|
||||||
<button data-mode="points">Калькулятор баллов</button>
|
<label class="mode-option"><input type="radio" name="calculator_mode" value="points" data-mode="points">Калькулятор баллов</label>
|
||||||
</div>
|
</div></fieldset>
|
||||||
|
|
||||||
<section class="panel">
|
<section class="panel">
|
||||||
<div class="bulk">
|
<div class="bulk">
|
||||||
<strong>Быстрый ввод</strong>
|
<label for="bulkText">Быстрый ввод</label>
|
||||||
<p class="muted">Вставьте данные одной строкой без разделителей <code>|</code>. Калькулятор заполнит поля и подскажет, чего не хватает.</p>
|
<p class="muted">Вставьте данные одной строкой без разделителей <code>|</code>. Калькулятор заполнит поля и подскажет, чего не хватает.</p>
|
||||||
<textarea id="bulkText" placeholder="15 августа, 11:00–11:20, Дикая Вишня 1604614, Серолап 1617140"></textarea>
|
<textarea id="bulkText" placeholder="15 августа, 11:00–11:20, Дикая Вишня 1604614, Серолап 1617140"></textarea>
|
||||||
<button type="button" id="inspectBulk">Распознать данные</button>
|
<button type="button" id="inspectBulk">Распознать данные</button>
|
||||||
<p class="muted bulk-status" id="bulkStatus"></p>
|
<p class="muted bulk-status" id="bulkStatus" role="status"></p>
|
||||||
</div>
|
</div>
|
||||||
<form id="form">
|
<form id="form" aria-label="Расчёт отчёта или баллов">
|
||||||
<div id="coaching" class="grid mode">
|
<div id="coaching" class="grid mode">
|
||||||
<label>Дата<input name="date" required>
|
<label>Дата<input name="date" required>
|
||||||
<div class="quick-actions"><button type="button" id="todayBtn" class="today-btn quick-btn">Сегодня</button></div>
|
<div class="quick-actions"><button type="button" id="todayBtn" class="today-btn quick-btn">Сегодня</button></div>
|
||||||
@@ -203,21 +216,21 @@
|
|||||||
<p class="muted">Имя и ID из профиля будут подставляться в новые отчёты.</p>
|
<p class="muted">Имя и ID из профиля будут подставляться в новые отчёты.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<dialog id="confirmDialog">
|
<dialog id="confirmDialog" aria-labelledby="confirmTitle">
|
||||||
<h3 style="margin-top:0">Подтверждение</h3>
|
<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 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;">
|
<div style="display:flex;gap:10px;">
|
||||||
<button type="button" id="confirmYes" class="primary">Да, подготовить</button>
|
<button type="button" id="confirmYes" class="primary">Да, подготовить</button>
|
||||||
<button type="button" id="confirmNo">Отмена</button>
|
<button type="button" id="confirmNo" autofocus>Отмена</button>
|
||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<div class="result hidden" id="result"><h2>Сообщение</h2><textarea id="message" readonly></textarea><div class="actions"><button type="button" id="sendReport" class="primary" disabled>Отправить отчёт</button></div><p class="muted hidden" id="reportStatus" aria-live="polite"></p></div>
|
<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>
|
<div class="result hidden" id="pointsResult" aria-live="polite"><h2>Заработанные баллы</h2><div id="pointsSummary"></div></div>
|
||||||
<p class="error" id="error"></p>
|
<p class="error" id="error" role="alert"></p>
|
||||||
</section>
|
</section>
|
||||||
</section>
|
</section>
|
||||||
<section id="sentReportsSection" class="hidden" role="tabpanel" aria-labelledby="sentReportsTab">
|
<section id="sentReportsSection" class="hidden" aria-labelledby="sentReportsTab">
|
||||||
<h2>Найти отчёты по ID кота</h2>
|
<h2>Найти отчёты по ID кота</h2>
|
||||||
<p class="muted">Покажем последние 100 отправленных отчётов, где кот указан участником.</p>
|
<p class="muted">Покажем последние 100 отправленных отчётов, где кот указан участником.</p>
|
||||||
<form id="sentReportsForm" class="panel">
|
<form id="sentReportsForm" class="panel">
|
||||||
@@ -231,7 +244,7 @@
|
|||||||
<div id="sentReportsResults" class="report-results" aria-live="polite"></div>
|
<div id="sentReportsResults" class="report-results" aria-live="polite"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section id="applicationsSection" class="hidden" role="tabpanel" aria-labelledby="applicationsTab">
|
<section id="applicationsSection" class="hidden" aria-labelledby="applicationsTab">
|
||||||
<div id="applicationWorkspace">
|
<div id="applicationWorkspace">
|
||||||
<h2>Новая заявка</h2>
|
<h2>Новая заявка</h2>
|
||||||
<p class="muted application-intro">Заполните форму, и администратор получит заявку. Готовить форумную отпись не нужно.</p>
|
<p class="muted application-intro">Заполните форму, и администратор получит заявку. Готовить форумную отпись не нужно.</p>
|
||||||
@@ -246,7 +259,7 @@
|
|||||||
<label>Имя кота<input name="name" required></label>
|
<label>Имя кота<input name="name" required></label>
|
||||||
<label>ID кота<input name="character_id" type="number" min="1" inputmode="numeric" 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>
|
<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="applicationKittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Выберите изображение</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
||||||
<section id="applicationCuratorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
<section id="applicationCuratorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
||||||
<section id="applicationFlyingFields" class="wide hidden"><label>Уже сдавали практику?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="applicationPracticeLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/… или https://vk.com/…"></label></section>
|
<section id="applicationFlyingFields" class="wide hidden"><label>Уже сдавали практику?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="applicationPracticeLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/… или https://vk.com/…"></label></section>
|
||||||
<section id="applicationFeatherFields" class="wide"><h2>Перья для казны</h2><p class="muted">Укажите количество и цвет перьев, а также откуда они получены.</p><div id="applicationFeathers"></div><button id="applicationAddFeather" type="button">Добавить перо</button></section>
|
<section id="applicationFeatherFields" class="wide"><h2>Перья для казны</h2><p class="muted">Укажите количество и цвет перьев, а также откуда они получены.</p><div id="applicationFeathers"></div><button id="applicationAddFeather" type="button">Добавить перо</button></section>
|
||||||
@@ -257,7 +270,7 @@
|
|||||||
<div id="applicationSuccess" class="success hidden" role="status" aria-live="polite"></div>
|
<div id="applicationSuccess" class="success hidden" role="status" aria-live="polite"></div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<section id="identitySection" class="hidden" role="tabpanel" aria-labelledby="identityTab">
|
<section id="identitySection" class="hidden" aria-labelledby="identityTab">
|
||||||
<div id="identityWorkspace">
|
<div id="identityWorkspace">
|
||||||
<h2>Изменить имя кота</h2>
|
<h2>Изменить имя кота</h2>
|
||||||
<p class="muted">Введите ID кота, чьё имя уже сохранено. Проверьте текущее имя и укажите новое.</p>
|
<p class="muted">Введите ID кота, чьё имя уже сохранено. Проверьте текущее имя и укажите новое.</p>
|
||||||
@@ -279,9 +292,9 @@
|
|||||||
</section>
|
</section>
|
||||||
<footer class="site-footer">Proudly made by Nyan404 | <a href="https://git.nyan404.ru/nyan404/cwshed-clone">GitLab Page</a></footer>
|
<footer class="site-footer">Proudly made by Nyan404 | <a href="https://git.nyan404.ru/nyan404/cwshed-clone">GitLab Page</a></footer>
|
||||||
</main>
|
</main>
|
||||||
<dialog id="identityDialog">
|
<dialog id="identityDialog" aria-label="Уточнить имя или ID кота" aria-describedby="identityDialogText">
|
||||||
<p id="identityDialogText"></p>
|
<p id="identityDialogText" role="status"></p>
|
||||||
<label id="identityMissingLabel">Имя или ID, которого не хватает<input id="identityMissingValue"></label>
|
<label id="identityMissingLabel" for="identityMissingValue">Имя или ID, которого не хватает<input id="identityMissingValue" autofocus></label>
|
||||||
<p class="muted">Эти имя и ID будут использованы только в текущем расчёте.</p>
|
<p class="muted">Эти имя и ID будут использованы только в текущем расчёте.</p>
|
||||||
<button type="button" id="saveIdentity">Добавить имя и ID</button>
|
<button type="button" id="saveIdentity">Добавить имя и ID</button>
|
||||||
<button type="button" id="closeIdentityDialog">Понятно</button>
|
<button type="button" id="closeIdentityDialog">Понятно</button>
|
||||||
@@ -313,21 +326,38 @@
|
|||||||
const identityMissingLabel = document.querySelector('#identityMissingLabel');
|
const identityMissingLabel = document.querySelector('#identityMissingLabel');
|
||||||
const identityMissingValue = document.querySelector('#identityMissingValue');
|
const identityMissingValue = document.querySelector('#identityMissingValue');
|
||||||
let mode = 'coaching';
|
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 extraKittens = document.querySelector('#extraKittens');
|
||||||
const statusHelp = document.querySelector('#statusHelp');
|
const statusHelp = document.querySelector('#statusHelp');
|
||||||
// Adds one repeatable kitten row and optionally fills it from saved values.
|
// Adds one repeatable kitten row and optionally fills it from saved values.
|
||||||
function addExtraKitten(values = {}) {
|
function addExtraKitten(values = {}) {
|
||||||
const row = document.createElement('div'); row.className = 'extra-kitten';
|
const row = document.createElement('div'); row.className = 'extra-kitten';
|
||||||
row.innerHTML = `<input data-extra="name" placeholder="Имя котёнка" required>
|
row.innerHTML = `<label>Имя котёнка<input data-extra="name" required></label>
|
||||||
<input data-extra="id" type="text" inputmode="numeric" pattern="[0-9]+" placeholder="ID" required>
|
<label>ID котёнка<input data-extra="id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" required></label>
|
||||||
<select data-extra="independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select>
|
<label>Самостоятельность<select data-extra="independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select></label>
|
||||||
<button type="button" data-remove>Удалить</button>`;
|
<button type="button" data-remove>Удалить</button>`;
|
||||||
row.querySelector('[data-extra="name"]').value = values.name || '';
|
row.querySelector('[data-extra="name"]').value = values.name || '';
|
||||||
row.querySelector('[data-extra="id"]').value = values.id || '';
|
row.querySelector('[data-extra="id"]').value = values.id || '';
|
||||||
row.querySelector('[data-extra="independence"]').value = values.independence || 'самостоятельно';
|
row.querySelector('[data-extra="independence"]').value = values.independence || 'самостоятельно';
|
||||||
row.querySelector('[data-extra="independence"]').addEventListener('change', updateStatusRules);
|
row.querySelector('[data-extra="independence"]').addEventListener('change', updateStatusRules);
|
||||||
row.querySelector('[data-remove]').addEventListener('click', () => row.remove());
|
row.querySelector('[data-remove]').addEventListener('click', () => { row.remove(); invalidateCalculation(); document.querySelector('#addKitten').focus(); });
|
||||||
extraKittens.append(row);
|
extraKittens.append(row);
|
||||||
|
row.querySelectorAll('input, select').forEach(field => { field.disabled = mode !== 'coaching'; });
|
||||||
|
invalidateCalculation();
|
||||||
}
|
}
|
||||||
document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten());
|
document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten());
|
||||||
// Returns all independence controls participating in the current coaching form.
|
// Returns all independence controls participating in the current coaching form.
|
||||||
@@ -335,7 +365,7 @@
|
|||||||
// Keeps every kitten's independence selection available for the chosen skill.
|
// Keeps every kitten's independence selection available for the chosen skill.
|
||||||
function updateStatusRules(event) {
|
function updateStatusRules(event) {
|
||||||
const fields = statusFields();
|
const fields = statusFields();
|
||||||
fields.forEach(field => { field.disabled = false; });
|
fields.forEach(field => { field.disabled = mode !== 'coaching'; });
|
||||||
statusHelp.textContent = document.querySelector('#coaching [name="skill"]').value === 'ЛУ'
|
statusHelp.textContent = document.querySelector('#coaching [name="skill"]').value === 'ЛУ'
|
||||||
? 'Для ЛУ можно указать не более одного несамостоятельного котёнка.'
|
? 'Для ЛУ можно указать не более одного несамостоятельного котёнка.'
|
||||||
: 'Укажите самостоятельность каждого котёнка отдельно.';
|
: 'Укажите самостоятельность каждого котёнка отдельно.';
|
||||||
@@ -349,8 +379,9 @@
|
|||||||
}
|
}
|
||||||
// Switches the visible calculator panel and disables fields in hidden panels.
|
// Switches the visible calculator panel and disables fields in hidden panels.
|
||||||
function selectMode(nextMode) {
|
function selectMode(nextMode) {
|
||||||
|
invalidateCalculation();
|
||||||
mode = nextMode;
|
mode = nextMode;
|
||||||
document.querySelectorAll('[data-mode]').forEach(item => item.classList.toggle('active', item.dataset.mode === mode));
|
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.classList.toggle('hidden', panel.id !== mode));
|
||||||
document.querySelectorAll('.mode').forEach(panel => panel.querySelectorAll('input, select, textarea').forEach(field => { field.disabled = 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');
|
bulk.classList.toggle('hidden', mode !== 'coaching');
|
||||||
@@ -363,8 +394,9 @@
|
|||||||
pointsActions.classList.toggle('hidden', mode !== 'points');
|
pointsActions.classList.toggle('hidden', mode !== 'points');
|
||||||
if (mode !== 'coaching') bulkStatus.textContent = '';
|
if (mode !== 'coaching') bulkStatus.textContent = '';
|
||||||
error.textContent = '';
|
error.textContent = '';
|
||||||
|
updatePointsFields();
|
||||||
}
|
}
|
||||||
document.querySelectorAll('[data-mode]').forEach(button => button.addEventListener('click', () => selectMode(button.dataset.mode)));
|
document.querySelectorAll('[data-mode]').forEach(input => input.addEventListener('change', () => selectMode(input.value)));
|
||||||
function updatePointsFields() {
|
function updatePointsFields() {
|
||||||
const activity = pointsActivity.value;
|
const activity = pointsActivity.value;
|
||||||
document.querySelector('#pointsCoaching').classList.toggle('hidden', activity !== 'coaching');
|
document.querySelector('#pointsCoaching').classList.toggle('hidden', activity !== 'coaching');
|
||||||
@@ -372,6 +404,9 @@
|
|||||||
document.querySelector('#pointsTraining').classList.toggle('hidden', activity !== 'training');
|
document.querySelector('#pointsTraining').classList.toggle('hidden', activity !== 'training');
|
||||||
const count = Number(document.querySelector('#points [name="kitten_count"]').value);
|
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-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);
|
pointsActivity.addEventListener('change', updatePointsFields);
|
||||||
document.querySelector('#points [name="kitten_count"]').addEventListener('change', updatePointsFields);
|
document.querySelector('#points [name="kitten_count"]').addEventListener('change', updatePointsFields);
|
||||||
@@ -379,14 +414,19 @@
|
|||||||
function setToday(button) {
|
function setToday(button) {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
button.closest('label').querySelector('input').value = `${String(now.getDate()).padStart(2, '0')}.${String(now.getMonth() + 1).padStart(2, '0')}`;
|
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(setToday);
|
||||||
document.querySelectorAll('.today-btn').forEach(button => button.addEventListener('click', () => setToday(button)));
|
document.querySelectorAll('.today-btn').forEach(button => button.addEventListener('click', () => setToday(button)));
|
||||||
document.querySelector('#coaching [name="kitten_independence"]').addEventListener('change', updateStatusRules);
|
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.
|
// Writes a value into a named field inside a calculator panel.
|
||||||
function setField(panel, name, value) {
|
function setField(panel, name, value) {
|
||||||
const field = document.querySelector(`#${panel} [name="${name}"]`);
|
const field = document.querySelector(`#${panel} [name="${name}"]`);
|
||||||
if (field && value !== undefined && value !== null) field.value = value;
|
if (field && value !== undefined && value !== null) { field.value = value; invalidateCalculation(); }
|
||||||
}
|
}
|
||||||
document.querySelector('#inspectBulk').addEventListener('click', async () => {
|
document.querySelector('#inspectBulk').addEventListener('click', async () => {
|
||||||
bulkStatus.textContent = '';
|
bulkStatus.textContent = '';
|
||||||
@@ -427,8 +467,7 @@
|
|||||||
identityMissingLabel.firstChild.textContent = `Введите ${missing}`;
|
identityMissingLabel.firstChild.textContent = `Введите ${missing}`;
|
||||||
identityMissingValue.value = '';
|
identityMissingValue.value = '';
|
||||||
identityMissingValue.type = name ? 'number' : 'text';
|
identityMissingValue.type = name ? 'number' : 'text';
|
||||||
if (identityDialog.showModal) identityDialog.showModal();
|
identityDialog.showModal();
|
||||||
else window.alert(data.message);
|
|
||||||
}
|
}
|
||||||
} catch (err) { identityStatus.textContent = err.message; }
|
} catch (err) { identityStatus.textContent = err.message; }
|
||||||
});
|
});
|
||||||
@@ -438,11 +477,17 @@
|
|||||||
const name = nameField.value.trim() || (identityMissingValue.type === 'text' ? identityMissingValue.value.trim() : '');
|
const name = nameField.value.trim() || (identityMissingValue.type === 'text' ? identityMissingValue.value.trim() : '');
|
||||||
const characterId = idField.value.trim() || (identityMissingValue.type === 'number' ? identityMissingValue.value.trim() : '');
|
const characterId = idField.value.trim() || (identityMissingValue.type === 'number' ? identityMissingValue.value.trim() : '');
|
||||||
if (!name || !characterId) { identityDialogText.textContent = 'Нужно указать и имя, и ID кота.'; return; }
|
if (!name || !characterId) { identityDialogText.textContent = 'Нужно указать и имя, и ID кота.'; return; }
|
||||||
|
const 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 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();
|
const data = await response.json();
|
||||||
if (!response.ok) { identityDialogText.textContent = data.error || 'Не удалось сохранить имя и ID'; return; }
|
if (!response.ok) throw new Error(data.error || 'Не удалось сохранить имя и ID');
|
||||||
setField('inspection', 'character_name', data.name); setField('inspection', 'character_id', data.character_id);
|
setField('inspection', 'character_name', data.name); setField('inspection', 'character_id', data.character_id);
|
||||||
identityDialog.close(); identityStatus.textContent = 'Имя и ID добавлены в текущий расчёт.';
|
identityDialog.close(); identityStatus.textContent = 'Имя и ID добавлены в текущий расчёт.';
|
||||||
|
} catch (err) { identityDialogText.textContent = err.message; }
|
||||||
|
finally { saveButton.disabled = false; }
|
||||||
});
|
});
|
||||||
document.querySelector('#closeIdentityDialog').addEventListener('click', () => identityDialog.close());
|
document.querySelector('#closeIdentityDialog').addEventListener('click', () => identityDialog.close());
|
||||||
// Serializes the active calculator form into the API payload shape.
|
// Serializes the active calculator form into the API payload shape.
|
||||||
@@ -502,6 +547,16 @@
|
|||||||
}
|
}
|
||||||
form.addEventListener('submit', async event => {
|
form.addEventListener('submit', async event => {
|
||||||
event.preventDefault(); error.textContent = '';
|
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 {
|
try {
|
||||||
if (mode === 'coaching') {
|
if (mode === 'coaching') {
|
||||||
const statusError = validateStatusRules();
|
const statusError = validateStatusRules();
|
||||||
@@ -509,50 +564,79 @@
|
|||||||
}
|
}
|
||||||
const reportPayload = payload();
|
const reportPayload = payload();
|
||||||
preparedReportPayload = null;
|
preparedReportPayload = null;
|
||||||
reportStatus.classList.add('hidden');
|
|
||||||
reportStatus.textContent = '';
|
reportStatus.textContent = '';
|
||||||
reportPayload.attachments = mode === 'inspection' ? await uploadScreenshots() : [];
|
reportPayload.attachments = requestMode === 'inspection' ? await uploadScreenshots() : [];
|
||||||
const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(reportPayload) });
|
const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(reportPayload) });
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
if (version !== calculationVersion) return;
|
||||||
if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');
|
if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');
|
||||||
if (mode === 'points') {
|
if (requestMode === 'points') {
|
||||||
const values = data.result;
|
const values = data.result;
|
||||||
const lines = values.kitten_points ? values.kitten_points.map((value, index) => `<p>Бельчонок ${index + 1}: <strong>${value}</strong> баллов</p>`) : [`<p>Баллы осмотра: <strong>${values.points}</strong></p>`];
|
const scores = Array.isArray(values.kitten_points)
|
||||||
if (values.curator_points !== undefined) lines.unshift(`<p>Куратор: <strong>${values.curator_points}</strong> баллов</p>`);
|
? values.kitten_points.map((value, index) => [`Бельчонок ${index + 1}`, value])
|
||||||
pointsSummary.innerHTML = lines.join(''); pointsResult.classList.remove('hidden'); return;
|
: [[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;
|
message.value = data.message;
|
||||||
result.classList.remove('hidden');
|
result.classList.remove('hidden');
|
||||||
copy.disabled = mode === 'goal';
|
copy.disabled = requestMode === 'goal';
|
||||||
goalCopy.disabled = mode !== 'goal';
|
goalCopy.disabled = requestMode !== 'goal';
|
||||||
sendReport.classList.toggle('hidden', mode === 'goal');
|
sendReport.classList.toggle('hidden', requestMode === 'goal');
|
||||||
if (mode !== 'goal') {
|
reportStatus.textContent = 'Расчёт готов. Проверьте сообщение.';
|
||||||
|
if (requestMode !== 'goal') {
|
||||||
preparedReportPayload = reportPayload;
|
preparedReportPayload = reportPayload;
|
||||||
sendReport.disabled = false;
|
sendReport.disabled = false;
|
||||||
sendReport.textContent = 'Отправить отчёт';
|
sendReport.textContent = 'Отправить отчёт';
|
||||||
}
|
}
|
||||||
} catch (err) { error.textContent = err.message; }
|
} 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 () => {
|
sendReport.addEventListener('click', async () => {
|
||||||
if (!preparedReportPayload || sendReport.disabled) return;
|
if (!preparedReportPayload || sendReport.disabled) return;
|
||||||
sendReport.disabled = true;
|
sendReport.disabled = true;
|
||||||
sendReport.textContent = 'Отправляем…';
|
sendReport.textContent = 'Отправляем…';
|
||||||
|
const version = calculationVersion;
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/reports', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(preparedReportPayload) });
|
const response = await fetch('/api/reports', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(preparedReportPayload) });
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
if (version !== calculationVersion) return;
|
||||||
if (!response.ok) throw new Error(data.error || 'Не удалось отправить отчёт');
|
if (!response.ok) throw new Error(data.error || 'Не удалось отправить отчёт');
|
||||||
preparedReportPayload = null;
|
preparedReportPayload = null;
|
||||||
sendReport.textContent = 'Отчёт отправлен';
|
sendReport.textContent = 'Отчёт отправлен';
|
||||||
reportStatus.textContent = 'Отчёт отправлен и сохранён.';
|
reportStatus.textContent = 'Отчёт отправлен и сохранён.';
|
||||||
reportStatus.classList.remove('hidden');
|
reportStatus.classList.remove('hidden');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (version !== calculationVersion) return;
|
||||||
error.textContent = err.message;
|
error.textContent = err.message;
|
||||||
sendReport.disabled = false;
|
sendReport.disabled = false;
|
||||||
sendReport.textContent = 'Отправить отчёт';
|
sendReport.textContent = 'Отправить отчёт';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
copy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); copy.textContent = 'Скопировано'; setTimeout(() => copy.textContent = 'Скопировать', 1500); });
|
async function copyMessage() {
|
||||||
goalCopy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); goalCopy.textContent = 'Скопировано'; setTimeout(() => goalCopy.textContent = 'Скопировать', 1500); });
|
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 reportsSection = document.querySelector('#reportsSection');
|
||||||
const sentReportsSection = document.querySelector('#sentReportsSection');
|
const sentReportsSection = document.querySelector('#sentReportsSection');
|
||||||
@@ -590,17 +674,22 @@
|
|||||||
identitySection.classList.toggle('hidden', selectedSection !== 'identity');
|
identitySection.classList.toggle('hidden', selectedSection !== 'identity');
|
||||||
sectionTabs.forEach(tab => {
|
sectionTabs.forEach(tab => {
|
||||||
const selected = tab.dataset.section === selectedSection;
|
const selected = tab.dataset.section === selectedSection;
|
||||||
tab.classList.toggle('active', selected);
|
if (selected) tab.setAttribute('aria-current', 'page');
|
||||||
tab.setAttribute('aria-selected', String(selected));
|
else tab.removeAttribute('aria-current');
|
||||||
});
|
});
|
||||||
|
document.title = `${sectionTabs.find(tab => tab.dataset.section === selectedSection).textContent} — Беличья нора`;
|
||||||
if (updateUrl) {
|
if (updateUrl) {
|
||||||
const url = new URL(window.location.href);
|
const url = new URL(window.location.href);
|
||||||
if (selectedSection !== 'reports') url.searchParams.set('section', selectedSection);
|
if (selectedSection !== 'reports') url.searchParams.set('section', selectedSection);
|
||||||
else url.searchParams.delete('section');
|
else url.searchParams.delete('section');
|
||||||
window.history.pushState({}, '', url);
|
if (url.href !== window.location.href) window.history.pushState({}, '', url);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sectionTabs.forEach(tab => tab.addEventListener('click', () => setSection(tab.dataset.section)));
|
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));
|
window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section'), false));
|
||||||
|
|
||||||
sentReportsForm.addEventListener('submit', async event => {
|
sentReportsForm.addEventListener('submit', async event => {
|
||||||
@@ -713,6 +802,7 @@
|
|||||||
setApplicationFieldsVisible('#applicationCuratorFields', applicationType === 'curator');
|
setApplicationFieldsVisible('#applicationCuratorFields', applicationType === 'curator');
|
||||||
setApplicationFieldsVisible('#applicationFlyingFields', applicationType === 'flying_squirrel');
|
setApplicationFieldsVisible('#applicationFlyingFields', applicationType === 'flying_squirrel');
|
||||||
setApplicationFieldsVisible('#applicationVkField', 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)));
|
document.querySelectorAll('[data-application-type]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.applicationType === applicationType)));
|
||||||
applicationError.textContent = '';
|
applicationError.textContent = '';
|
||||||
}
|
}
|
||||||
@@ -740,20 +830,22 @@
|
|||||||
}
|
}
|
||||||
applicationForm.addEventListener('submit', async event => {
|
applicationForm.addEventListener('submit', async event => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
if (applicationSubmit.disabled) return;
|
||||||
applicationError.textContent = '';
|
applicationError.textContent = '';
|
||||||
|
applicationSuccess.classList.add('hidden');
|
||||||
applicationSubmit.disabled = true;
|
applicationSubmit.disabled = true;
|
||||||
applicationSubmit.textContent = 'Отправляем…';
|
applicationSubmit.textContent = 'Отправляем…';
|
||||||
try {
|
try {
|
||||||
const payload = Object.fromEntries(new FormData(applicationForm).entries());
|
const payload = Object.fromEntries(new FormData(applicationForm).entries());
|
||||||
payload.type = applicationType;
|
payload.type = applicationType;
|
||||||
payload.character_id = Number(payload.character_id);
|
payload.character_id = Number(payload.character_id);
|
||||||
payload.attachments = await uploadApplicationScreenshots();
|
|
||||||
if (applicationType === 'flying_squirrel') payload.practiced_before = payload.practiced_before === 'yes';
|
if (applicationType === 'flying_squirrel') payload.practiced_before = payload.practiced_before === 'yes';
|
||||||
if (applicationType === 'feather_donation') payload.feathers = [...applicationFeathers.querySelectorAll('.feather')].map(row => ({
|
if (applicationType === 'feather_donation') payload.feathers = [...applicationFeathers.querySelectorAll('.feather')].map(row => ({
|
||||||
amount: Number(row.querySelector('[data-application-field="amount"]').value),
|
amount: Number(row.querySelector('[data-application-field="amount"]').value),
|
||||||
color: row.querySelector('[data-application-field="color"]').value,
|
color: row.querySelector('[data-application-field="color"]').value,
|
||||||
source: row.querySelector('[data-application-field="source"]').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 response = await fetch('/api/applications', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)});
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (!response.ok) throw new Error(data.error || 'Не удалось отправить заявку');
|
if (!response.ok) throw new Error(data.error || 'Не удалось отправить заявку');
|
||||||
|
|||||||
Reference in new issue
Block a user