diff --git a/MEMORY.md b/MEMORY.md index 6b06211..2028ce2 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -58,6 +58,7 @@ - 2026-08-25: authenticated admin refresh WebSockets use a separate pool of eight slots so they cannot consume the bounded general HTTP worker pool. History sorting normalizes old string IDs with current numeric IDs. - 2026-09-01: admin XLSX downloads are session/password-protected routes. Keep report category/cat/kitten and application status plus period/date-range query parameters identical between the API list and export endpoint so the file matches the visible selection. - 2026-09-01: all web-facing Belki dates are UTC+3. Never change persisted UTC moments to implement this; convert at the UI/XLSX boundary and interpret calendar inputs in UTC+3. +- 2026-09-01: report attachments are a web inspection-only requirement. Enforce it in `validate_web_report_attachments`, not only by hiding the field, and retain optional dated output for legacy bot training sessions. # 2026-08-16 — несколько котят в прокачке `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. diff --git a/app/belki/api.py b/app/belki/api.py index cf33609..3cba89d 100644 --- a/app/belki/api.py +++ b/app/belki/api.py @@ -235,6 +235,7 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]: escort_id=_int(payload, "escort_id"), kitten_name=str(_required(payload, "kitten_name")), kitten_id=_int(payload, "kitten_id"), + date=str(payload.get("date", "")), ) result = calculate_training(session) return {"mode": mode, "result": asdict(result), "message": render_training(session, result)} diff --git a/app/belki/domain.py b/app/belki/domain.py index 35ef65b..c2fbbb3 100644 --- a/app/belki/domain.py +++ b/app/belki/domain.py @@ -230,6 +230,7 @@ class TrainingSession: escort_id: int kitten_name: str kitten_id: int + date: str = "" def __post_init__(self) -> None: """Валидирует данные сессии тренировки.""" @@ -238,6 +239,8 @@ class TrainingSession: raise ValueError("Имена участников не могут быть пустыми") _positive_id(self.escort_id, "ID сопровождающего") _positive_id(self.kitten_id, "ID котёнка") + if self.date: + parse_report_date(self.date) if self.escort_id == self.kitten_id: raise ValueError("Сопровождающий и котёнок должны быть разными персонажами") diff --git a/app/belki/reports.py b/app/belki/reports.py index 377a4f2..c748e50 100644 --- a/app/belki/reports.py +++ b/app/belki/reports.py @@ -108,11 +108,11 @@ def render_training(session: TrainingSession, result: TrainingResult | None = No Имя [ID], провёл(-ла) урок Котёнок [ID]. """ result = result or TrainingResult() - return ( - "#урок\n" - f"{session.escort_name} [{session.escort_id}], провёл(-ла) урок " - f"{session.kitten_name} [{session.kitten_id}]." - ) + lines = ["#урок"] + if session.date: + lines.append(session.date) + lines.append(f"{session.escort_name} [{session.escort_id}], провёл(-ла) урок {session.kitten_name} [{session.kitten_id}].") + return "\n".join(lines) def render_inspection(report: InspectionReport, result: InspectionResult | None = None) -> str: diff --git a/app/main.py b/app/main.py index 35ac665..be75515 100644 --- a/app/main.py +++ b/app/main.py @@ -102,6 +102,16 @@ def validate_web_attachments(value: object, *, now: float | None = None) -> list return attachments +def validate_web_report_attachments(payload: dict) -> list[dict]: + """Apply the web rule: screenshots are required only for an inspection.""" + attachments = validate_web_attachments(payload.get("attachments", [])) + if payload.get("mode") == "inspection" and not attachments: + raise ApiError("Для осмотра приложите хотя бы один скриншот") + if payload.get("mode") != "inspection" and attachments: + raise ApiError("Скриншоты прикладываются только к осмотрам") + return attachments + + def allow_admin_auth_attempt(client_ip: str, *, now: float | None = None) -> bool: """Apply a bounded per-source budget to the password-only admin login.""" timestamp = time.monotonic() if now is None else now @@ -531,13 +541,13 @@ class Handler(BaseHTTPRequestHandler): elif self.path == "/api/resolve-identity": self._json(200, resolve_identity_payload(payload)) elif self.path == "/api/applications": - payload["attachments"] = validate_web_attachments(payload.get("attachments", [])) + payload["attachments"] = validate_web_report_attachments(payload) application = validate_application(payload) 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", [])) + payload["attachments"] = validate_web_report_attachments(payload) self._json(200, calculate_payload(payload)) else: payload["attachments"] = validate_web_attachments(payload.get("attachments", [])) diff --git a/project_mind_map.md b/project_mind_map.md index e1bba20..53aa427 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -107,6 +107,7 @@ mindmap ```mermaid flowchart LR Browser[Публичный браузер] --> Web[BelkiHTTPServer] + Browser -->|inspection screenshot only| Web VK[VK Long Poll] --> Bot[BelkiDialog] Web --> Domain[Расчётное ядро] Bot --> Domain diff --git a/structure_and_data.md b/structure_and_data.md index 068684c..75ec800 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -111,6 +111,7 @@ - 2026-08-25: the earned-points calculator groups coaching start and end times in one responsive time-range row. - 2026-09-01: authenticated `/admin` report and application views share named (all/year/month/week/day/12–1 h) and explicit date-range filters with their XLSX links. `app/belki/admin_filters.py` is the single UTC-boundary parser; `xlsx_export.py` writes a styled one-sheet workbook with typed dates, column filters, and a frozen header. - 2026-09-01: web-facing timestamps and calendar ranges use UTC+3. The database still stores UTC moments; `WEB_TIMEZONE` converts visible admin/XLSX dates, while date-only filters are converted from UTC+3 boundaries before querying records. +- 2026-09-01: the public report form now requires screenshots only for inspections (and validates that rule server-side). Web lessons collect a `ДД.ММ` date and generate the dated `#урок` format; bot-only forms such as `#выход` and `#помощь` remain outside the public calculator. - 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: shared two-column form grids align controls at the start of their row, preventing a date field with its helper button from stretching the adjacent skill select. - 2026-08-25: mobile adaptation is a required acceptance criterion for all frontend changes; validate narrow-width layout, touch usability, focus/error states, and absence of horizontal overflow alongside desktop rendering. diff --git a/tests/test_belki.py b/tests/test_belki.py index e2e3e46..35876ca 100644 --- a/tests/test_belki.py +++ b/tests/test_belki.py @@ -206,6 +206,10 @@ class ReportTests(unittest.TestCase): self.assertIn("#урок", text) self.assertIn("провёл(-ла) урок", text) + def test_training_report_includes_the_web_date(self): + text = render_training(TrainingSession("Белка", 1, "Котёнок", 2, date="01.09")) + self.assertEqual(text, "#урок\n01.09\nБелка [1], провёл(-ла) урок Котёнок [2].") + def test_inspection_report_lists_zero_and_resources(self): text = render_inspection( InspectionReport( diff --git a/tests/test_image_host.py b/tests/test_image_host.py index 286d398..7b57c0d 100644 --- a/tests/test_image_host.py +++ b/tests/test_image_host.py @@ -7,11 +7,15 @@ from app.main import (ADMIN_SESSION_TTL_SECONDS, MAX_ADMIN_AUTH_ATTEMPTS, MAX_AD _ADMIN_AUTH_ATTEMPTS, _ADMIN_SESSIONS, _ISSUED_WEB_UPLOAD_URLS, admin_session_authorized, allow_admin_auth_attempt, acquire_admin_update_slot, clear_admin_auth_attempts, detect_raster_image_type, forget_admin_session, remember_admin_session, remember_issued_web_upload, release_admin_update_slot, safe_upload_name, - validate_web_attachments, WEB_UPLOAD_URL_TTL_SECONDS) + validate_web_attachments, validate_web_report_attachments, WEB_UPLOAD_URL_TTL_SECONDS) from app.belki.api import ApiError class ImageHostClientTests(unittest.TestCase): + def test_web_report_screenshots_are_required_only_for_inspections(self) -> None: + with self.assertRaisesRegex(ApiError, "осмотра"): + validate_web_report_attachments({"mode": "inspection", "attachments": []}) + self.assertEqual(validate_web_report_attachments({"mode": "coaching", "attachments": []}), []) def test_upload_input_helpers_accept_only_supported_raster_signatures(self) -> None: self.assertEqual(detect_raster_image_type(b"\x89PNG\r\n\x1a\ncontent"), "image/png") self.assertEqual(detect_raster_image_type(b"\xff\xd8\xffcontent"), "image/jpeg") diff --git a/web/calculator.html b/web/calculator.html index 094254b..6c37d97 100644 --- a/web/calculator.html +++ b/web/calculator.html @@ -91,7 +91,7 @@
-

Один заход — один отчёт. Скриншоты к готовому отчёту нужно приложить вручную.

+

Один заход — один отчёт. Скриншот нужен только для осмотра; прикрепите его перед формированием сообщения.

@@ -129,6 +129,9 @@
- +
@@ -307,7 +310,10 @@ document.querySelectorAll('.mode').forEach(panel => panel.classList.toggle('hidden', panel.id !== mode)); document.querySelectorAll('.mode').forEach(panel => panel.querySelectorAll('input, select, textarea').forEach(field => { field.disabled = panel.id !== mode; })); bulk.classList.toggle('hidden', mode !== 'coaching'); - reportAttachments.classList.toggle('hidden', mode === 'goal' || mode === 'points'); + const inspection = mode === 'inspection'; + reportAttachments.classList.toggle('hidden', !inspection); + screenshots.disabled = !inspection; + screenshots.required = inspection; reportActions.classList.toggle('hidden', mode === 'goal' || mode === 'points'); goalActions.classList.toggle('hidden', mode !== 'goal'); pointsActions.classList.toggle('hidden', mode !== 'points'); @@ -326,6 +332,10 @@ pointsActivity.addEventListener('change', updatePointsFields); document.querySelector('#points [name="kitten_count"]').addEventListener('change', updatePointsFields); document.querySelector('#coaching [name="skill"]').addEventListener('change', updateStatusRules); + document.querySelectorAll('.today-btn').forEach(button => button.addEventListener('click', () => { + const now = new Date(); + button.closest('label').querySelector('input').value = `${String(now.getDate()).padStart(2, '0')}.${String(now.getMonth() + 1).padStart(2, '0')}`; + })); document.querySelector('#coaching [name="kitten_independence"]').addEventListener('change', updateStatusRules); // Writes a value into a named field inside a calculator panel. function setField(panel, name, value) { @@ -455,7 +465,7 @@ preparedReportPayload = null; reportStatus.classList.add('hidden'); reportStatus.textContent = ''; - reportPayload.attachments = mode === 'goal' ? [] : await uploadScreenshots(); + reportPayload.attachments = mode === 'inspection' ? await uploadScreenshots() : []; const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(reportPayload) }); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');