From 00bbe66c7744edb8903268b6c53808c8ed164c5c Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Tue, 1 Sep 2026 01:48:39 +0300 Subject: [PATCH] feat: export filtered admin data to xlsx --- MEMORY.md | 1 + app/belki/admin_filters.py | 49 +++++++++++++++++++++++++ app/belki/xlsx_export.py | 49 +++++++++++++++++++++++++ app/main.py | 73 ++++++++++++++++++++++++++++++++++++-- project_mind_map.md | 3 ++ structure_and_data.md | 1 + tests/test_admin_export.py | 55 ++++++++++++++++++++++++++++ web/admin.html | 29 ++++++++++----- 8 files changed, 249 insertions(+), 11 deletions(-) create mode 100644 app/belki/admin_filters.py create mode 100644 app/belki/xlsx_export.py create mode 100644 tests/test_admin_export.py 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
КотКотятаФотоДатаСообщениеАвторID
Загрузка истории…
- + @@ -133,6 +139,8 @@ const direction = document.querySelector('#direction'); const catFilter = document.querySelector('#catFilter'); 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 error = document.querySelector('#error'); const recordCount = document.querySelector('#recordCount'); @@ -168,20 +176,23 @@ // 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'; } // 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. 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. - 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); }); } - 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; } } + 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 = 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. const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'}; // 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; } // 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. - 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. 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. @@ -198,8 +209,8 @@ function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); } // 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))); } - 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(); }); - 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(); })); + 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.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))); restoreAdminSession();