diff --git a/app/main.py b/app/main.py index 00ddf55..a9fd455 100644 --- a/app/main.py +++ b/app/main.py @@ -12,7 +12,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import parse_qs, unquote, urlparse -from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload +from .belki.api import ApiError, calculate_and_store, calculate_payload, inspect_bulk_payload, resolve_identity_payload from .belki.history import CalculationStore from .belki.applications import ApplicationError, ApplicationStore, validate_application from .belki.google_sheets_export import GoogleSheetsExportService @@ -403,7 +403,7 @@ class Handler(BaseHTTPRequestHandler): parsed = urlparse(self.path) is_sudoku_create = parsed.path == "/api/sudoku/games" is_sudoku_regenerate = parsed.path.startswith("/api/sudoku/games/") and parsed.path.endswith("/regenerate") - if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity", + if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/reports", "/api/inspect-bulk", "/api/resolve-identity", "/api/applications") and not is_sudoku_create and not is_sudoku_regenerate: self._json(404, {"error": "Не найдено"}) return @@ -467,9 +467,12 @@ class Handler(BaseHTTPRequestHandler): application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web") sync_application_exports() self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."}) + elif self.path == "/api/calculate": + payload["attachments"] = validate_web_attachments(payload.get("attachments", [])) + self._json(200, calculate_payload(payload)) else: payload["attachments"] = validate_web_attachments(payload.get("attachments", [])) - self._json(200, calculate_and_store(payload, actor_id=None, source="web")) + self._json(201, calculate_and_store(payload, actor_id=None, source="web")) except (ApiError, ApplicationError, SudokuError) as exc: self._json(400, {"error": str(exc)}) except (ValueError, json.JSONDecodeError) as exc: diff --git a/docs/staging/bugs/2026-08-25-belki-bugs.md b/docs/staging/bugs/2026-08-25-belki-bugs.md index a226610..8b9b0b1 100644 --- a/docs/staging/bugs/2026-08-25-belki-bugs.md +++ b/docs/staging/bugs/2026-08-25-belki-bugs.md @@ -2,7 +2,7 @@ ## 20. Явная отправка итогового отчёта из веб-формы -**Статус:** ожидает исправления. +**Статус:** выполнено 25.08.2026. **Источник:** сообщение пользователя со скриншотом от 25.08.2026. @@ -19,6 +19,8 @@ - повторное нажатие не создаёт дубликат отчёта; - пользователь может скопировать подготовленный текст до отправки. +**Исправление:** `/api/calculate` теперь только подготавливает расчёт и сообщение. Итог сохраняется отдельным запросом к `/api/reports` после нажатия «Отправить отчёт»; кнопка сразу блокируется, а после успеха показывается текстовое подтверждение. + ## 19. В калькуляторе прокачки начало и конец должны быть в одной строке **Статус:** выполнено 25.08.2026. diff --git a/structure_and_data.md b/structure_and_data.md index ded5df5..09e5556 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -106,6 +106,7 @@ - 2026-08-25: the deploy job waits for `deployment/belki-postgres` to become `Available`, rather than waiting for every Pod with the shared PostgreSQL label. Historical ReplicaSet Pods can remain during cleanup and must not fail a release after the current database replica is ready. - 2026-08-25: coaching reports allow an independence status for every kitten in both ЛУ and ЗУ. Natural input attaches `сам`/`не сам` written after a participant ID to that participant, and web ID fields use numeric-text input instead of spinner controls. - 2026-08-25: the earned-points calculator groups coaching start and end times in one responsive time-range row. +- 2026-08-25: web reports use a two-step flow: `/api/calculate` prepares the message without saving it, then `/api/reports` stores it only after the user explicitly selects «Отправить отчёт». The UI disables that action while it is in progress and after success. - 2026-08-25: removed unreferenced root-level legacy BBCode copies `belki.md`, `belki2.md`, and `belkifix.md`; the first two were byte-identical and the third differed only by a closing BBCode tag. They were neither served nor referenced by the calculator, bot, or documentation. # Обновление 2026-08-16: несколько котят diff --git a/web/calculator.html b/web/calculator.html index 644eb0e..6cfadf0 100644 --- a/web/calculator.html +++ b/web/calculator.html @@ -178,7 +178,7 @@ - +

@@ -223,6 +223,9 @@ const form = document.querySelector('#form'); const error = document.querySelector('#error'); const result = document.querySelector('#result'); + const sendReport = document.querySelector('#sendReport'); + const reportStatus = document.querySelector('#reportStatus'); + let preparedReportPayload = null; const message = document.querySelector('#message'); const copy = document.querySelector('#copy'); const goalCopy = document.querySelector('#goalCopy'); @@ -429,6 +432,9 @@ if (statusError) throw new Error(statusError); } const reportPayload = payload(); + preparedReportPayload = null; + reportStatus.classList.add('hidden'); + reportStatus.textContent = ''; reportPayload.attachments = mode === 'goal' ? [] : await uploadScreenshots(); const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(reportPayload) }); const data = await response.json(); @@ -443,8 +449,32 @@ result.classList.remove('hidden'); copy.disabled = mode === 'goal'; goalCopy.disabled = mode !== 'goal'; + sendReport.classList.toggle('hidden', mode === 'goal'); + if (mode !== 'goal') { + preparedReportPayload = reportPayload; + sendReport.disabled = false; + sendReport.textContent = 'Отправить отчёт'; + } } catch (err) { error.textContent = err.message; } }); + sendReport.addEventListener('click', async () => { + if (!preparedReportPayload || sendReport.disabled) return; + sendReport.disabled = true; + sendReport.textContent = 'Отправляем…'; + try { + const response = await fetch('/api/reports', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(preparedReportPayload) }); + const data = await response.json(); + if (!response.ok) throw new Error(data.error || 'Не удалось отправить отчёт'); + preparedReportPayload = null; + sendReport.textContent = 'Отчёт отправлен'; + reportStatus.textContent = 'Отчёт отправлен и сохранён.'; + reportStatus.classList.remove('hidden'); + } catch (err) { + error.textContent = err.message; + sendReport.disabled = false; + sendReport.textContent = 'Отправить отчёт'; + } + }); copy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); copy.textContent = 'Скопировано'; setTimeout(() => copy.textContent = 'Скопировать', 1500); }); goalCopy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); goalCopy.textContent = 'Скопировано'; setTimeout(() => goalCopy.textContent = 'Скопировать', 1500); });