fix: align web reports with current rules

This commit is contained in:
nyan404 committed 2026-09-01 02:03:55 +03:00
1 parent cffaaac755
commit aecbb3bf6a
10 files changed
+47 -12

No files matched your search

+1
View File
@@ -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-команде.
+1
View File
@@ -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)}
+3
View File
@@ -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("Сопровождающий и котёнок должны быть разными персонажами")
+5 -5
View File
@@ -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:
+12 -2
View File
@@ -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", []))
+1
View File
@@ -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
+1
View File
@@ -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.
+4
View File
@@ -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(
+5 -1
View File
@@ -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")
+14 -4
View File
@@ -91,7 +91,7 @@
</nav>
<section id="reportsSection" role="tabpanel" aria-labelledby="reportsTab">
<p class="muted">Один заход — один отчёт. Скриншоты к готовому отчёту нужно приложить вручную.</p>
<p class="muted">Один заход — один отчёт. Скриншот нужен только для осмотра; прикрепите его перед формированием сообщения.</p>
<div class="tabs" role="tablist" aria-label="Вид отчёта">
<button class="active" data-mode="coaching">Прокачка ЛУ/ЗУ</button>
<button data-mode="training">Тренировка</button>
@@ -129,6 +129,9 @@
</div>
<div id="training" class="grid mode hidden">
<label>Дата<input name="date" value="15.08" inputmode="numeric" pattern="\d{1,2}\.\d{1,2}" required>
<div class="quick-actions"><button type="button" class="today-btn quick-btn">Сегодня</button></div>
</label>
<label>Имя сопровождающего<input name="escort_name"></label>
<label>ID сопровождающего<input name="escort_id" type="number" min="1"></label>
<label>Имя котёнка<input name="kitten_name"></label>
@@ -171,7 +174,7 @@
<p id="pointsTraining" class="wide muted hidden">За тренировку бельчонок получает 25 баллов.</p>
</div>
<label id="reportAttachments" class="wide">Скриншоты отчёта<input id="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple><span class="muted">Можно выбрать несколько изображений PNG, JPEG или WebP. Они будут загружены на img.nyan404.ru.</span></label>
<label id="reportAttachments" class="wide hidden">Скриншот осмотра<input id="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple><span class="muted">Для осмотра нужен хотя бы один скриншот. Можно выбрать несколько PNG, JPEG или WebP.</span></label>
<div id="reportActions" class="actions"><button class="primary" type="submit">Подготовить сообщение</button><button type="button" id="copy" disabled>Скопировать</button></div>
<div id="goalActions" class="actions hidden"><button class="primary" type="submit">Рассчитать цель</button><button type="button" id="goalCopy" disabled>Скопировать</button></div>
<div id="pointsActions" class="actions hidden"><button class="primary" type="submit">Рассчитать баллы</button></div>
@@ -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 || 'Ошибка калькулятора');