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

+1
View File
@@ -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: 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: 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-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 — несколько котят в прокачке # 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+49
View File
@@ -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)
+49
View File
@@ -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'<c r="{reference}" s="2"><v>{serial:.10f}</v></c>'
if isinstance(value, (int, float)) and not isinstance(value, bool):
return f'<c r="{reference}"{style}><v>{value}</v></c>'
return f'<c r="{reference}" t="inlineStr"{style}><is><t>{escape(str(value or ""))}</t></is></c>'
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 = [
'<row r="1" ht="24">' + ''.join(_cell(index, 1, value, header=True) for index, value in enumerate(headers, 1)) + '</row>'
]
for row_number, row in enumerate(rows, 2):
sheet_rows.append('<row r="%d">%s</row>' % (row_number, ''.join(
_cell(index, value_row, value) for index, value in enumerate(row, 1) for value_row in (row_number,)
)))
widths = ''.join(f'<col min="{index}" max="{index}" width="{min(max(max([len(header)] + [len(str(row[index - 1] or "")) for row in rows]) + 2, 14), 48)}" customWidth="1"/>' for index, header in enumerate(headers, 1))
sheet = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
'<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>'
f'<cols>{widths}</cols><sheetData>{"".join(sheet_rows)}</sheetData><autoFilter ref="A1:{chr(64 + len(headers))}{len(rows) + 1}"/></worksheet>')
buffer = BytesIO()
with ZipFile(buffer, 'w', ZIP_DEFLATED) as archive:
archive.writestr('[Content_Types].xml', '<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>')
archive.writestr('_rels/.rels', '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>')
archive.writestr('xl/workbook.xml', f'<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="{escape(sheet_name)}" sheetId="1" r:id="rId1"/></sheets></workbook>')
archive.writestr('xl/_rels/workbook.xml.rels', '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>')
archive.writestr('xl/styles.xml', '<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="1"><numFmt numFmtId="164" formatCode="dd.mm.yyyy hh:mm"/></numFmts><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><color rgb="FFFFFFFF"/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="solid"><fgColor rgb="FF9A542E"/><bgColor indexed="64"/></patternFill></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellXfs count="3"><xf fontId="0" fillId="0" borderId="0"/><xf fontId="1" fillId="1" borderId="0" applyFont="1" applyFill="1"/><xf fontId="0" fillId="0" borderId="0" numFmtId="164" applyNumberFormat="1"/></cellXfs></styleSheet>')
archive.writestr('xl/worksheets/sheet1.xml', sheet)
return buffer.getvalue()
+71 -2
View File
@@ -8,6 +8,7 @@ import os
import secrets import secrets
import threading import threading
import time import time
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse 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.api import ApiError, calculate_and_store, calculate_payload, inspect_bulk_payload, resolve_identity_payload
from .belki.history import CalculationStore from .belki.history import CalculationStore
from .belki.applications import ApplicationError, ApplicationStore, validate_application 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.google_sheets_export import GoogleSheetsExportService
from .belki.identity import IdentityDirectory from .belki.identity import IdentityDirectory
from .belki.image_host import ImageHostClient, ImageHostError from .belki.image_host import ImageHostClient, ImageHostError
from .belki.xlsx_export import build_xlsx
from .sudoku import SudokuError, SudokuStore from .sudoku import SudokuError, SudokuStore
@@ -203,6 +206,25 @@ def sync_application_exports() -> int:
return GoogleSheetsExportService(application_store()).sync_pending() 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): class BelkiHTTPServer(ThreadingHTTPServer):
"""Threaded server with bounded slow-client and worker resource use.""" """Threaded server with bounded slow-client and worker resource use."""
@@ -245,6 +267,23 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers() self.end_headers()
self.wfile.write(encoded) 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: def _session_token(self, name: str) -> str:
"""Извлекает именованный токен из cookie текущего запроса.""" """Извлекает именованный токен из cookie текущего запроса."""
cookies = self.headers.get("Cookie", "") cookies = self.headers.get("Cookie", "")
@@ -347,20 +386,50 @@ class Handler(BaseHTTPRequestHandler):
if not self._admin_authorized(): if not self._admin_authorized():
return return
query = parse_qs(urlparse(self.path).query) 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] sort_by = query.get("sort", ["escort_id"])[0]
descending = query.get("direction", ["desc"])[0] != "asc" descending = query.get("direction", ["desc"])[0] != "asc"
try: try:
limit = int(query.get("limit", ["100"])[0]) limit = int(query.get("limit", ["100"])[0])
except ValueError: except ValueError:
limit = 100 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 return
if path == "/api/admin/applications": if path == "/api/admin/applications":
if not self._admin_authorized(): if not self._admin_authorized():
return return
query = parse_qs(urlparse(self.path).query) query = parse_qs(urlparse(self.path).query)
status = query.get("status", [None])[0] or None 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 return
requested = unquote(path).lstrip("/") requested = unquote(path).lstrip("/")
candidate = (WEB_ROOT / requested).resolve() candidate = (WEB_ROOT / requested).resolve()
+3
View File
@@ -116,6 +116,8 @@ flowchart LR
Web --> Sudoku[Sudoku game store] Web --> Sudoku[Sudoku game store]
Bot --> ImageHost Bot --> ImageHost
Admin[Администратор] -->|session cookie| Web Admin[Администратор] -->|session cookie| Web
Admin -->|same filters| XLSX[Отчёты и заявки XLSX]
Web --> XLSX
Web --> Admin Web --> Admin
Bot -. when enabled .-> Sheets[Google Apps Script] Bot -. when enabled .-> Sheets[Google Apps Script]
``` ```
@@ -126,6 +128,7 @@ flowchart LR
- Диалоги, команды и естественный ввод проверяются в `tests/test_vk_conversation.py`. - Диалоги, команды и естественный ввод проверяются в `tests/test_vk_conversation.py`.
- Границы image-host и HTTP-предохранители проверяются в `tests/test_image_host.py`. - Границы image-host и HTTP-предохранители проверяются в `tests/test_image_host.py`.
- Заявки, экспортная очередь и уведомления проверяются в `tests/test_applications.py`; совместимость сортировки истории — в `tests/test_history.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'`. - Перед 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'`.
## Ограничения развёртывания ## Ограничения развёртывания
+1
View File
@@ -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: 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: 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: 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: 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: 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. - 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.
+55
View File
@@ -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
+20 -9
View File
@@ -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 { 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:focus-visible, a:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; }
button:hover { background: #45413d; } 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; } button:disabled { cursor: wait; opacity: .55; }
.error { min-height: 22px; margin: 0 0 12px; color: var(--danger); font-size: .9rem; } .error { min-height: 22px; margin: 0 0 12px; color: var(--danger); font-size: .9rem; }
.hidden { display: none !important; } .hidden { display: none !important; }
@@ -68,7 +70,7 @@
.gallery button:hover { background: #514840; } .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 { 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; } .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; } }
</style> </style>
</head> </head>
<body> <body>
@@ -107,12 +109,16 @@
<label class="control-group">Порядок<select id="direction"><option value="asc">По возрастанию</option><option value="desc" selected>По убыванию</option></select></label> <label class="control-group">Порядок<select id="direction"><option value="asc">По возрастанию</option><option value="desc" selected>По убыванию</option></select></label>
<label class="control-group">Кот<select id="catFilter"><option value="">Все коты</option></select></label> <label class="control-group">Кот<select id="catFilter"><option value="">Все коты</option></select></label>
<label class="control-group">Котёнок<select id="kittenFilter"><option value="">Все котята</option></select></label> <label class="control-group">Котёнок<select id="kittenFilter"><option value="">Все котята</option></select></label>
<label class="control-group">Период<select id="reportPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label>
<label class="control-group">С даты<input id="reportDateFrom" type="date"></label>
<label class="control-group">По дату<input id="reportDateTo" type="date"></label>
<button id="load" type="button">Обновить</button> <button id="load" type="button">Обновить</button>
<a id="reportsExport" class="export-link" href="/api/admin/calculations.xlsx">Скачать XLSX</a>
</section> </section>
<p class="error" id="error" role="alert"></p> <p class="error" id="error" role="alert"></p>
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div> <div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div>
</section> </section>
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="rejected" aria-selected="false">Отклонённые</button></nav><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section> <section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-selected="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
</section> </section>
</main> </main>
@@ -133,6 +139,8 @@
const direction = document.querySelector('#direction'); const direction = document.querySelector('#direction');
const catFilter = document.querySelector('#catFilter'); const catFilter = document.querySelector('#catFilter');
const kittenFilter = document.querySelector('#kittenFilter'); const kittenFilter = document.querySelector('#kittenFilter');
const reportPeriod = document.querySelector('#reportPeriod'), reportDateFrom = document.querySelector('#reportDateFrom'), reportDateTo = document.querySelector('#reportDateTo');
const applicationPeriod = document.querySelector('#applicationPeriod'), applicationDateFrom = document.querySelector('#applicationDateFrom'), applicationDateTo = document.querySelector('#applicationDateTo');
const rows = document.querySelector('#rows'); const rows = document.querySelector('#rows');
const error = document.querySelector('#error'); const error = document.querySelector('#error');
const recordCount = document.querySelector('#recordCount'); const recordCount = document.querySelector('#recordCount');
@@ -168,20 +176,23 @@
// Maps an input payload to the report category used by tabs and filters. // Maps an input payload to the report category used by tabs and filters.
function categoryFor(item) { const input = item.input || {}; if (input.mode === 'inspection') return 'inspection'; if (input.mode === 'training') return 'training'; if (input.skill === 'ЛУ') return 'lu'; if (input.skill === 'ЗУ') return 'zu'; return 'other'; } function categoryFor(item) { const input = item.input || {}; if (input.mode === 'inspection') return 'inspection'; if (input.mode === 'training') return 'training'; if (input.skill === 'ЛУ') return 'lu'; if (input.skill === 'ЗУ') return 'zu'; return 'other'; }
// Applies active category/person filters and returns sorted reports. // Applies active category/person filters and returns sorted reports.
function filteredItems() { const cat = catFilter.value; const kitten = kittenFilter.value; return items.filter(item => { const input = item.input || {}; const person = personData(input); const kittens = kittenEntries(input); return (activeCategory === 'all' || categoryFor(item) === activeCategory) && (!cat || String(person.id) === cat) && (!kitten || kittens.some(entry => String(entry.id) === kitten)); }).sort((a, b) => { const av = textForSort(a, sort.value), bv = textForSort(b, sort.value); const result = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv), 'ru', {numeric: true, sensitivity: 'base'}); return direction.value === 'asc' ? result : -result; }); } function queryFor(period, dateFrom, dateTo, extra = {}) { const query = new URLSearchParams({...extra, period: period.value}); if (dateFrom.value || dateTo.value) { query.set('date_from', dateFrom.value); query.set('date_to', dateTo.value); } return query; }
function syncReportsExport() { document.querySelector('#reportsExport').href = `/api/admin/calculations.xlsx?${queryFor(reportPeriod, reportDateFrom, reportDateTo, {category: activeCategory, cat: catFilter.value, kitten: kittenFilter.value})}`; }
function syncApplicationsExport() { document.querySelector('#applicationsExport').href = `/api/admin/applications.xlsx?${queryFor(applicationPeriod, applicationDateFrom, applicationDateTo, {status: activeApplicationStatus})}`; }
function filteredItems() { return items.sort((a, b) => { const av = textForSort(a, sort.value), bv = textForSort(b, sort.value); const result = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv), 'ru', {numeric: true, sensitivity: 'base'}); return direction.value === 'asc' ? result : -result; }); }
// Rebuilds cat and kitten filter options from loaded records. // Rebuilds cat and kitten filter options from loaded records.
function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; } function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; }
// Re-renders the report table, including empty and filtered states. // Re-renders the report table, including empty and filtered states.
function render() { rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} из ${items.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = displayDate(item.created_at); return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE'}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); } function render() { syncReportsExport(); rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = displayDate(item.created_at); return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE'}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); }
async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = new URLSearchParams({sort: 'escort_name', direction: 'asc', limit: '500'}); const response = await fetch(`/api/admin/calculations?${query}`); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } } async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = queryFor(reportPeriod, reportDateFrom, reportDateTo, {sort: 'escort_name', direction: 'asc', limit: '500', category: activeCategory, cat: catFilter.value, kitten: kittenFilter.value}); const response = await fetch(`/api/admin/calculations?${query}`); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }
// Loads report history from the admin API and refreshes filters/table. // Loads report history from the admin API and refreshes filters/table.
const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'}; const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'};
// Extracts display fields from one application for the detail panel. // Extracts display fields from one application for the detail panel.
function applicationFields(item) { const a = item.application || {}; const fields = [['Тип', applicationLabels[a.type] || a.type], ['Персонаж', `${a.name || '—'}${a.character_id ? ` [${a.character_id}]` : ''}`], ['Источник', item.source === 'vk' ? 'VK-бот' : 'Веб-форма']]; if (a.vk_link) fields.push(['VK', a.vk_link]); if (a.type === 'flying_squirrel') { fields.push(['Практика ранее', a.practiced_before ? 'Да' : 'Нет']); if (a.practice_review_link) fields.push(['Комментарий практики', a.practice_review_link]); } if (a.type === 'feather_donation') fields.push(['Перья', (a.feathers || []).map(x => `${x.amount} ${x.color} — ${x.source}`).join('\n')]); if (a.type === 'curator') fields.push(['Подтверждение', 'Скриншот ЛУ с дробью']); return fields; } function applicationFields(item) { const a = item.application || {}; const fields = [['Тип', applicationLabels[a.type] || a.type], ['Персонаж', `${a.name || '—'}${a.character_id ? ` [${a.character_id}]` : ''}`], ['Источник', item.source === 'vk' ? 'VK-бот' : 'Веб-форма']]; if (a.vk_link) fields.push(['VK', a.vk_link]); if (a.type === 'flying_squirrel') { fields.push(['Практика ранее', a.practiced_before ? 'Да' : 'Нет']); if (a.practice_review_link) fields.push(['Комментарий практики', a.practice_review_link]); } if (a.type === 'feather_donation') fields.push(['Перья', (a.feathers || []).map(x => `${x.amount} ${x.color} — ${x.source}`).join('\n')]); if (a.type === 'curator') fields.push(['Подтверждение', 'Скриншот ЛУ с дробью']); return fields; }
// Renders pending or accepted applications and their actions. // Renders pending or accepted applications and their actions.
function renderApplications() { const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications.filter(item => item.status === activeApplicationStatus); document.querySelector('#applicationCount').textContent = `${visible.length} ${({pending:'новых', accepted:'принятых', rejected:'отклонённых'}[activeApplicationStatus])} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const actions=document.createElement('div');actions.className='application-actions';const review=async(action,button)=>{button.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/${action}`,{method:'PATCH'}),data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось изменить статус заявки');await loadApplications()}catch(err){error.textContent=err.message;button.disabled=false}};const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=()=>review('accept',accept);const reject=document.createElement('button');reject.className='reject';reject.type='button';reject.textContent='Отклонить';reject.onclick=()=>review('reject',reject);actions.append(accept,reject);detail.append(actions)} } function renderApplications() { syncApplicationsExport(); const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications; document.querySelector('#applicationCount').textContent = `${visible.length} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const actions=document.createElement('div');actions.className='application-actions';const review=async(action,button)=>{button.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/${action}`,{method:'PATCH'}),data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось изменить статус заявки');await loadApplications()}catch(err){error.textContent=err.message;button.disabled=false}};const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=()=>review('accept',accept);const reject=document.createElement('button');reject.className='reject';reject.type='button';reject.textContent='Отклонить';reject.onclick=()=>review('reject',reject);actions.append(accept,reject);detail.append(actions)} }
// Loads applications from the admin API and renders the selected status. // Loads applications from the admin API and renders the selected status.
async function loadApplications() { try { const response=await fetch('/api/admin/applications'), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } } async function loadApplications() { try { const response=await fetch(`/api/admin/applications?${queryFor(applicationPeriod, applicationDateFrom, applicationDateTo, {status: activeApplicationStatus})}`), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
// Opens the authenticated admin view and starts both data loaders. // Opens the authenticated admin view and starts both data loaders.
async function openAdmin() { authView.classList.add('hidden'); appView.classList.remove('hidden'); await load(); await loadApplications(); connectUpdates(); } async function openAdmin() { authView.classList.add('hidden'); appView.classList.remove('hidden'); await load(); await loadApplications(); connectUpdates(); }
// Authenticates the administrator and transitions to the admin view. // Authenticates the administrator and transitions to the admin view.
@@ -198,8 +209,8 @@
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); } function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
// Switches between report and application admin views. // Switches between report and application admin views.
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); } function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); }
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', render); kittenFilter.addEventListener('change', render); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-selected', String(item === tab))); render(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); }); authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', load); kittenFilter.addEventListener('change', load); [reportPeriod, reportDateFrom, reportDateTo].forEach(control => control.addEventListener('change', load)); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-selected', String(item === tab))); load(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); renderApplications(); })); document.querySelector('#loadApplications').addEventListener('click', loadApplications); [applicationPeriod, applicationDateFrom, applicationDateTo].forEach(control => control.addEventListener('change', loadApplications)); document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); loadApplications(); }));
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView))); document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
restoreAdminSession(); restoreAdminSession();
</script> </script>