feat: export filtered admin data to xlsx

This commit is contained in:
nyan404 committed 2026-09-01 01:51:29 +03:00
1 parent ab3bbd6672
commit 00bbe66c77
8 files changed
+249 -11

No files matched your search

+71 -2
View File
@@ -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()