diff --git a/MEMORY.md b/MEMORY.md
index 2c0b3ef..0a3a5ba 100644
--- a/MEMORY.md
+++ b/MEMORY.md
@@ -56,6 +56,7 @@
- 2026-08-25: free-form input also accepts Russian written dates and month abbreviations, normalizing them to `ДД.ММ`; report dates are then calendar-validated in the domain before storage.
- 2026-08-25: application validation limits text, rows, per-row feather amounts, and attachments across web and VK. Persisted media/review links require HTTPS, and a profile link is accepted only for a VK host.
- 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-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
diff --git a/app/belki/admin_filters.py b/app/belki/admin_filters.py
new file mode 100644
index 0000000..4f96acc
--- /dev/null
+++ b/app/belki/admin_filters.py
@@ -0,0 +1,49 @@
+"""Shared parsing and application of the administrative time filters."""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+from typing import Any
+
+
+PERIODS = {
+ "all": None, "year": timedelta(days=365), "month": timedelta(days=30),
+ "week": timedelta(days=7), "day": timedelta(days=1), "12h": timedelta(hours=12),
+ "6h": timedelta(hours=6), "4h": timedelta(hours=4), "2h": timedelta(hours=2),
+ "1h": timedelta(hours=1),
+}
+
+
+def parse_timestamp(value: str, *, end_of_day: bool = False) -> datetime:
+ """Parse an ISO date/time stored by either SQLite or PostgreSQL as UTC."""
+ text = value.strip().replace("Z", "+00:00")
+ if len(text) == 10:
+ text += "T23:59:59.999999" if end_of_day else "T00:00:00"
+ try:
+ result = datetime.fromisoformat(text)
+ except ValueError as exc:
+ raise ValueError("Дата должна быть в формате ГГГГ-ММ-ДД") from exc
+ return result.replace(tzinfo=result.tzinfo or timezone.utc).astimezone(timezone.utc)
+
+
+def period_bounds(period: str, date_from: str | None, date_to: str | None, *, now: datetime | None = None) -> tuple[datetime | None, datetime | None]:
+ """Return inclusive UTC bounds for a named period or an explicit range."""
+ if date_from or date_to:
+ if not date_from or not date_to:
+ raise ValueError("Укажите обе даты диапазона")
+ start, end = parse_timestamp(date_from), parse_timestamp(date_to, end_of_day=True)
+ if start > end:
+ raise ValueError("Дата начала не может быть позже даты окончания")
+ return start, end
+ if period not in PERIODS:
+ raise ValueError("Неизвестный период")
+ duration = PERIODS[period]
+ if duration is None:
+ return None, None
+ end = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
+ return end - duration, end
+
+
+def matches_period(record: dict[str, Any], start: datetime | None, end: datetime | None) -> bool:
+ """Check a serialized store record against inclusive UTC bounds."""
+ created = parse_timestamp(str(record["created_at"]))
+ return (start is None or created >= start) and (end is None or created <= end)
diff --git a/app/belki/xlsx_export.py b/app/belki/xlsx_export.py
new file mode 100644
index 0000000..9bb9d08
--- /dev/null
+++ b/app/belki/xlsx_export.py
@@ -0,0 +1,49 @@
+"""Minimal XLSX writer for administrative exports without a runtime dependency."""
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from io import BytesIO
+from xml.sax.saxutils import escape
+from zipfile import ZIP_DEFLATED, ZipFile
+
+
+def _cell(column: int, row: int, value: object, *, header: bool = False) -> str:
+ name = ""
+ number = column
+ while number:
+ number, remainder = divmod(number - 1, 26)
+ name = chr(65 + remainder) + name
+ reference = f"{name}{row}"
+ style = ' s="1"' if header else ''
+ if isinstance(value, datetime):
+ timestamp = value.replace(tzinfo=value.tzinfo or timezone.utc).astimezone(timezone.utc)
+ serial = (timestamp - datetime(1899, 12, 30, tzinfo=timezone.utc)).total_seconds() / 86400
+ return f'{serial:.10f}'
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return f'{value}'
+ return f'{escape(str(value or ""))}'
+
+
+def build_xlsx(*, sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes:
+ """Builds one readable XLSX worksheet with a frozen, styled header row."""
+ sheet_rows = [
+ '' + ''.join(_cell(index, 1, value, header=True) for index, value in enumerate(headers, 1)) + ''
+ ]
+ for row_number, row in enumerate(rows, 2):
+ sheet_rows.append('%s' % (row_number, ''.join(
+ _cell(index, value_row, value) for index, value in enumerate(row, 1) for value_row in (row_number,)
+ )))
+ widths = ''.join(f'
' for index, header in enumerate(headers, 1))
+ sheet = (''
+ ''
+ ''
+ f'{widths}{"".join(sheet_rows)}')
+ buffer = BytesIO()
+ with ZipFile(buffer, 'w', ZIP_DEFLATED) as archive:
+ archive.writestr('[Content_Types].xml', '')
+ archive.writestr('_rels/.rels', '')
+ archive.writestr('xl/workbook.xml', f'')
+ archive.writestr('xl/_rels/workbook.xml.rels', '')
+ archive.writestr('xl/styles.xml', '')
+ archive.writestr('xl/worksheets/sheet1.xml', sheet)
+ return buffer.getvalue()
diff --git a/app/main.py b/app/main.py
index a9fd455..bfd4971 100644
--- a/app/main.py
+++ b/app/main.py
@@ -8,6 +8,7 @@ import os
import secrets
import threading
import time
+from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
@@ -15,9 +16,11 @@ from urllib.parse import parse_qs, unquote, urlparse
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.admin_filters import matches_period, period_bounds
from .belki.google_sheets_export import GoogleSheetsExportService
from .belki.identity import IdentityDirectory
from .belki.image_host import ImageHostClient, ImageHostError
+from .belki.xlsx_export import build_xlsx
from .sudoku import SudokuError, SudokuStore
@@ -203,6 +206,25 @@ def sync_application_exports() -> int:
return GoogleSheetsExportService(application_store()).sync_pending()
+def report_matches_filters(record: dict, query: dict[str, list[str]]) -> bool:
+ """Match the report-only filters that are also represented in the admin URL."""
+ payload = record.get("input", {})
+ category = query.get("category", ["all"])[0]
+ actual = "inspection" if payload.get("mode") == "inspection" else "training" if payload.get("mode") == "training" else "lu" if payload.get("skill") == "ЛУ" else "zu" if payload.get("skill") == "ЗУ" else "other"
+ if category != "all" and category != actual:
+ return False
+ cat = query.get("cat", [""])[0]
+ if cat and str(payload.get("escort_id", payload.get("character_id", ""))) != cat:
+ return False
+ kitten = query.get("kitten", [""])[0]
+ if kitten:
+ ids = [payload.get("kitten_id")]
+ ids.extend(item.get("id") if isinstance(item, dict) else item[1] if isinstance(item, (list, tuple)) and len(item) > 1 else None for item in payload.get("extra_kittens", []))
+ if kitten not in {str(value) for value in ids if value is not None}:
+ return False
+ return True
+
+
class BelkiHTTPServer(ThreadingHTTPServer):
"""Threaded server with bounded slow-client and worker resource use."""
@@ -245,6 +267,23 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(encoded)
+ def _xlsx(self, filename: str, content: bytes) -> None:
+ """Send an authenticated administrative spreadsheet attachment."""
+ self.send_response(200)
+ self.send_header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+ self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
+ self.send_header("Content-Length", str(len(content)))
+ self.end_headers()
+ self.wfile.write(content)
+
+ def _admin_period(self, query: dict[str, list[str]]):
+ """Parse the common period query and return an API error for invalid dates."""
+ try:
+ return period_bounds(query.get("period", ["all"])[0], query.get("date_from", [None])[0], query.get("date_to", [None])[0])
+ except ValueError as exc:
+ self._json(400, {"error": str(exc)})
+ return None
+
def _session_token(self, name: str) -> str:
"""Извлекает именованный токен из cookie текущего запроса."""
cookies = self.headers.get("Cookie", "")
@@ -347,20 +386,50 @@ class Handler(BaseHTTPRequestHandler):
if not self._admin_authorized():
return
query = parse_qs(urlparse(self.path).query)
+ bounds = self._admin_period(query)
+ if bounds is None:
+ return
sort_by = query.get("sort", ["escort_id"])[0]
descending = query.get("direction", ["desc"])[0] != "asc"
try:
limit = int(query.get("limit", ["100"])[0])
except ValueError:
limit = 100
- self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit)})
+ records = [item for item in history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit) if matches_period(item, *bounds) and report_matches_filters(item, query)]
+ self._json(200, {"items": records})
+ return
+ if path == "/api/admin/calculations.xlsx":
+ if not self._admin_authorized():
+ return
+ query = parse_qs(urlparse(self.path).query)
+ bounds = self._admin_period(query)
+ if bounds is None:
+ return
+ records = [item for item in history_store().list_calculations(sort_by="escort_id", descending=True, limit=500) if matches_period(item, *bounds) and report_matches_filters(item, query)]
+ rows = [[item["id"], datetime.fromisoformat(str(item["created_at"]).replace("Z", "+00:00")), item["mode"], item["source"], item["actor_id"], item["message"]] for item in records]
+ self._xlsx("belki-reports.xlsx", build_xlsx(sheet_name="Отчёты", headers=["ID", "Создан", "Тип", "Источник", "Автор", "Отчёт"], rows=rows))
return
if path == "/api/admin/applications":
if not self._admin_authorized():
return
query = parse_qs(urlparse(self.path).query)
status = query.get("status", [None])[0] or None
- self._json(200, {"items": application_store().list(status=status)})
+ bounds = self._admin_period(query)
+ if bounds is None:
+ return
+ self._json(200, {"items": [item for item in application_store().list(status=status) if matches_period(item, *bounds)]})
+ return
+ if path == "/api/admin/applications.xlsx":
+ if not self._admin_authorized():
+ return
+ query = parse_qs(urlparse(self.path).query)
+ status = query.get("status", [None])[0] or None
+ bounds = self._admin_period(query)
+ if bounds is None:
+ return
+ records = [item for item in application_store().list(status=status) if matches_period(item, *bounds)]
+ rows = [[item["id"], datetime.fromisoformat(str(item["created_at"]).replace("Z", "+00:00")), item["status"], item["source"], item["application"].get("type", ""), item["application"].get("name", ""), item["application"].get("character_id")] for item in records]
+ self._xlsx("belki-applications.xlsx", build_xlsx(sheet_name="Заявки", headers=["ID", "Создана", "Статус", "Источник", "Тип", "Имя", "ID персонажа"], rows=rows))
return
requested = unquote(path).lstrip("/")
candidate = (WEB_ROOT / requested).resolve()
diff --git a/project_mind_map.md b/project_mind_map.md
index da5bd0b..66322e3 100644
--- a/project_mind_map.md
+++ b/project_mind_map.md
@@ -116,6 +116,8 @@ flowchart LR
Web --> Sudoku[Sudoku game store]
Bot --> ImageHost
Admin[Администратор] -->|session cookie| Web
+ Admin -->|same filters| XLSX[Отчёты и заявки XLSX]
+ Web --> XLSX
Web --> Admin
Bot -. when enabled .-> Sheets[Google Apps Script]
```
@@ -126,6 +128,7 @@ flowchart LR
- Диалоги, команды и естественный ввод проверяются в `tests/test_vk_conversation.py`.
- Границы image-host и HTTP-предохранители проверяются в `tests/test_image_host.py`.
- Заявки, экспортная очередь и уведомления проверяются в `tests/test_applications.py`; совместимость сортировки истории — в `tests/test_history.py`.
+- Периоды админки, защищённые XLSX-маршруты и целостность XLSX ZIP проверяются в `tests/test_admin_export.py`.
- Перед CI используйте Python 3.12 в Docker: `docker run --rm -v "$PWD:/work" -w /work python:3.12-slim sh -lc 'python -m compileall -q app tests && python -m unittest discover -s tests -q'`.
## Ограничения развёртывания
diff --git a/structure_and_data.md b/structure_and_data.md
index e2e7de7..10c512a 100644
--- a/structure_and_data.md
+++ b/structure_and_data.md
@@ -109,6 +109,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-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-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_admin_export.py b/tests/test_admin_export.py
new file mode 100644
index 0000000..5674d78
--- /dev/null
+++ b/tests/test_admin_export.py
@@ -0,0 +1,55 @@
+import http.client
+import os
+import tempfile
+import threading
+import unittest
+import zipfile
+from datetime import datetime, timezone
+from io import BytesIO
+from pathlib import Path
+
+from app.belki.admin_filters import matches_period, period_bounds
+from app.belki.xlsx_export import build_xlsx
+from app.main import BelkiHTTPServer, Handler
+
+
+class AdminFilterAndExportTests(unittest.TestCase):
+ def test_named_and_custom_periods_filter_records(self) -> None:
+ now = datetime(2026, 9, 1, 12, tzinfo=timezone.utc)
+ recent = {"created_at": "2026-09-01T11:30:00+00:00"}
+ old = {"created_at": "2026-08-30T11:30:00+00:00"}
+ self.assertTrue(matches_period(recent, *period_bounds("2h", None, None, now=now)))
+ self.assertFalse(matches_period(old, *period_bounds("2h", None, None, now=now)))
+ self.assertTrue(matches_period(old, *period_bounds("all", "2026-08-30", "2026-08-30", now=now)))
+
+ def test_xlsx_is_a_valid_workbook_with_filters_and_typed_values(self) -> None:
+ content = build_xlsx(sheet_name="Отчёты", headers=["ID", "Создан", "Текст"], rows=[[7, datetime(2026, 9, 1, 12, 30, tzinfo=timezone.utc), "Только выбранная строка"]])
+ with zipfile.ZipFile(BytesIO(content)) as archive:
+ self.assertTrue(archive.testzip() is None)
+ sheet = archive.read("xl/worksheets/sheet1.xml").decode()
+ self.assertIn("Только выбранная строка", sheet)
+ self.assertIn('autoFilter ref="A1:C2"', sheet)
+ self.assertIn('s="2"', sheet)
+
+ def test_xlsx_routes_require_admin_authorization(self) -> None:
+ prior = os.environ.get("BELKI_ADMIN_PASSWORD")
+ os.environ["BELKI_ADMIN_PASSWORD"] = "test-password"
+ server = BelkiHTTPServer(("127.0.0.1", 0), Handler)
+ worker = threading.Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ try:
+ for path in ("/api/admin/calculations.xlsx", "/api/admin/applications.xlsx"):
+ connection = http.client.HTTPConnection("127.0.0.1", server.server_port)
+ connection.request("GET", path)
+ response = connection.getresponse()
+ self.assertEqual(response.status, 401)
+ response.read()
+ connection.close()
+ finally:
+ server.shutdown()
+ server.server_close()
+ worker.join(timeout=2)
+ if prior is None:
+ del os.environ["BELKI_ADMIN_PASSWORD"]
+ else:
+ os.environ["BELKI_ADMIN_PASSWORD"] = prior
diff --git a/web/admin.html b/web/admin.html
index 75b7970..255bcaa 100644
--- a/web/admin.html
+++ b/web/admin.html
@@ -33,6 +33,8 @@
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; }
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:hover { background: #fff4ea; }
button:disabled { cursor: wait; opacity: .55; }
.error { min-height: 22px; margin: 0 0 12px; color: var(--danger); font-size: .9rem; }
.hidden { display: none !important; }
@@ -68,7 +70,7 @@
.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 button { min-height: 34px; padding: 5px 10px; }
- @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 { 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; } }
+ @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; } }
@@ -107,12 +109,16 @@
+
+
+
+ Скачать XLSX