feat(админка): система — каналы и история
This commit is contained in:
@@ -15,6 +15,7 @@ import db
|
||||
import metrics
|
||||
import money
|
||||
import payments_admin
|
||||
import system_admin
|
||||
import work_admin
|
||||
from admin_auth import require_admin
|
||||
|
||||
@@ -23,6 +24,7 @@ router = APIRouter(prefix="/api/admin/v2", tags=["admin-v2"])
|
||||
# Один снимок на 15 секунд: «Мой день» не должен пересчитывать метрики на каждый F5.
|
||||
_CACHE: dict = {"ts": 0.0, "data": None}
|
||||
_CACHE_TTL = 15
|
||||
_SYS = {"ts": 0.0, "data": None}
|
||||
|
||||
|
||||
def _build(user: str) -> dict:
|
||||
@@ -316,6 +318,21 @@ async def feedback_status(feedback_id: int, request: Request):
|
||||
return {"ok": True, "id": feedback_id, "status": body.get("status")}
|
||||
|
||||
|
||||
@router.get("/system")
|
||||
async def system_snapshot(request: Request):
|
||||
require_admin(request)
|
||||
import health_checks
|
||||
now = time.time()
|
||||
if _SYS["data"] is not None and now - _SYS["ts"] < 60:
|
||||
return _SYS["data"]
|
||||
data = {"channels": await asyncio.to_thread(system_admin.channels),
|
||||
"settings": await asyncio.to_thread(system_admin.settings),
|
||||
"history": await asyncio.to_thread(system_admin.history, 50),
|
||||
"generated_at": now}
|
||||
_SYS["ts"], _SYS["data"] = now, data
|
||||
return data
|
||||
|
||||
|
||||
@router.get("/work/dialogs")
|
||||
async def work_dialogs(request: Request, q: str = "", page: int = 1, per_page: int = 50):
|
||||
require_admin(request)
|
||||
|
||||
@@ -754,6 +754,12 @@ def admin_verify_telegram(email: str, telegram: str) -> None:
|
||||
"WHERE email = ?", (telegram, name, time.time(), email.lower().strip()))
|
||||
|
||||
|
||||
def list_app_settings() -> list[dict]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute("SELECT key, value FROM app_settings ORDER BY key").fetchall()
|
||||
return [dict(r) for r in rows if not str(r["key"]).startswith("_")]
|
||||
|
||||
|
||||
def get_app_setting(key: str, default: str = "") -> str:
|
||||
"""Глобальная настройка из БД (agent_killswitch и т.п.)."""
|
||||
with _conn() as conn:
|
||||
|
||||
@@ -285,6 +285,12 @@
|
||||
- Вкладки в «Работе»; журнал с русскими названиями; debounce 300 мс.
|
||||
- Тесты: API — 2 (второй диалог, page 2, action/q), UI — 2.
|
||||
|
||||
## 4.37. P4.4 — «Система»
|
||||
|
||||
- `/system`: каналы (health_checks), настройки (без `_`), история с русскими названиями; кэш 60 с.
|
||||
- UI: 3 карточки, каналы, таблицы настроек/истории; автообновление 60 с.
|
||||
- Тесты: API — 2, UI — 1.
|
||||
|
||||
## 5. Следующий шаг
|
||||
|
||||
P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания).
|
||||
|
||||
@@ -5,6 +5,7 @@ import { DayPage } from '/static/admin2/pages/day.js';
|
||||
import { CustomersPage } from '/static/admin2/pages/customers.js';
|
||||
import { MoneyPage } from '/static/admin2/pages/money.js';
|
||||
import { WorkPage } from '/static/admin2/pages/work.js';
|
||||
import { SystemPage } from '/static/admin2/pages/system.js';
|
||||
|
||||
const html = htm.bind(h);
|
||||
const TITLES = {
|
||||
@@ -31,7 +32,8 @@ const App = () => html`
|
||||
${section === 'today' ? html`<${DayPage} />`
|
||||
: section === 'customers' ? html`<${CustomersPage} />`
|
||||
: section === 'money' ? html`<${MoneyPage} />`
|
||||
: section === 'work' ? html`<${WorkPage} />` : html`
|
||||
: section === 'work' ? html`<${WorkPage} />`
|
||||
: section === 'system' ? html`<${SystemPage} />` : html`
|
||||
<section class="card" aria-labelledby="placeholder">
|
||||
<h2 id="placeholder">Раздел готовится</h2>
|
||||
<p>Данные и действия подключит следующий этап.</p>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { h } from '/static/admin2/vendor/preact.module.js';
|
||||
import { useEffect, useState } from '/static/admin2/vendor/hooks.module.js';
|
||||
import htm from '/static/admin2/vendor/htm.module.js';
|
||||
import { api } from '/static/admin2/api.js';
|
||||
import { Card } from '/static/admin2/ui/card.js';
|
||||
import { Table } from '/static/admin2/ui/table.js';
|
||||
|
||||
const html = htm.bind(h);
|
||||
const when = (ts) => new Date(ts * 1000).toLocaleString('ru-RU');
|
||||
|
||||
export function SystemPage() {
|
||||
const [data, setData] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const load = () => api('/api/admin/v2/system').then((d) => {
|
||||
if (alive) { setData(d); setError(''); }
|
||||
}).catch((e) => { if (alive) setError(e.message || 'Система не отвечает'); });
|
||||
load();
|
||||
const t = setInterval(load, 60000);
|
||||
return () => { alive = false; clearInterval(t); };
|
||||
}, []);
|
||||
|
||||
if (error) return html`<div class="card error" role="alert">${error}</div>`;
|
||||
if (!data) return html`<div class="card">Загрузка…</div>`;
|
||||
const bad = data.channels.filter((c) => !c.ok);
|
||||
return html`
|
||||
<div class="grid">
|
||||
<${Card} title="Каналы" value=${bad.length ? bad.length + ' сбоя' : 'все живы'}
|
||||
note=${'проверено ' + when(data.generated_at)} />
|
||||
<${Card} title="Настройки" value=${data.settings.length} note="только чтение" />
|
||||
<${Card} title="События" value=${data.history.length} note="последние 50" />
|
||||
</div>
|
||||
<section class="card">
|
||||
<h2>Каналы</h2>
|
||||
${data.channels.map((c) => html`<div class="kv" key=${c.name}>
|
||||
<div><span>${c.name}</span><b class=${c.ok ? 'ok' : 'bad'}>${c.ok ? 'ок' : 'сбой'}</b></div>
|
||||
<div><span>${c.detail || ''}</span></div></div>`)}
|
||||
</section>
|
||||
<section class="card">
|
||||
<h2>Настройки</h2>
|
||||
<${Table} columns=${[
|
||||
{key: 'key', label: 'Ключ'}, {key: 'value', label: 'Значение'},
|
||||
]} rows=${data.settings.map((r) => ({...r, key: r.key}))} empty="Настроек нет" />
|
||||
</section>
|
||||
<section class="card">
|
||||
<h2>История</h2>
|
||||
<${Table} columns=${[
|
||||
{key: 'timestamp', label: 'Когда', render: (r) => when(r.timestamp)},
|
||||
{key: 'label', label: 'Событие'}, {key: 'username', label: 'Кто'},
|
||||
{key: 'detail', label: 'Было → стало'},
|
||||
]} rows=${data.history.map((r, i) => ({...r, key: r.id || i}))} empty="Событий нет" />
|
||||
</section>`;
|
||||
}
|
||||
@@ -82,3 +82,5 @@ tr.clickable{cursor:pointer} tr.clickable:hover td{background:#f3f6ff}
|
||||
|
||||
.s-new{background:#fff4e5;color:#b54708}.s-resolved{background:#e7f6ec;color:#067647}
|
||||
.s-deferred,.s-ignored{background:#f2f4f7;color:#667085}
|
||||
|
||||
.badge.ok,.ok{color:#067647}.bad,.badge.bad{color:#b42318}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Система v2: каналы, настройки, история."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def channels() -> list[dict]:
|
||||
import health_checks
|
||||
return [{"name": c.name, "ok": bool(c.ok), "detail": c.detail, "level": c.level}
|
||||
for c in health_checks.run_all()]
|
||||
|
||||
|
||||
def settings() -> list[dict]:
|
||||
import db
|
||||
return db.list_app_settings()
|
||||
|
||||
|
||||
def history(limit: int = 100) -> list[dict]:
|
||||
import db
|
||||
labels = {"layer_switch": "переключение слоя", "killswitch": "аварийный стоп",
|
||||
"registration_toggle": "регистрация", "admin_settings": "настройки"}
|
||||
return [{**r, "label": labels.get(r.get("action"), r.get("action") or "событие")}
|
||||
for r in db.get_audit_log(limit=max(1, min(int(limit), 500)))]
|
||||
@@ -0,0 +1,71 @@
|
||||
"""P4.4: экран «Система» — каналы, настройки, история."""
|
||||
import http.server
|
||||
import json
|
||||
import socketserver
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT)); sys.path.insert(0, str(ROOT / "tests"))
|
||||
pytest.importorskip("playwright.sync_api", reason="playwright не установлен")
|
||||
from test_admin_design_ui import browser # noqa: E402,F401
|
||||
|
||||
SYS = {"channels": [{"name": "database", "ok": True, "detail": "ок", "level": "fail"},
|
||||
{"name": "smtp", "ok": False, "detail": "нет входа", "level": "fail"}],
|
||||
"settings": [{"key": "agent_killswitch", "value": "off"}],
|
||||
"history": [{"id": 1, "timestamp": 1793000000, "label": "переключение слоя",
|
||||
"username": "boss@x", "detail": "x → on"}],
|
||||
"generated_at": 1793000000}
|
||||
|
||||
|
||||
class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
def __init__(self, *a, **kw):
|
||||
super().__init__(*a, directory=str(ROOT), **kw)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/api/admin/v2/system"):
|
||||
return self._json(SYS)
|
||||
if self.path == "/admin/v2" or self.path.startswith("/admin/v2/"):
|
||||
data = (ROOT / "static/admin2/index.html").read_bytes()
|
||||
self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data))); self.end_headers()
|
||||
self.wfile.write(data); return
|
||||
return super().do_GET()
|
||||
|
||||
def _json(self, obj):
|
||||
data = json.dumps(obj).encode()
|
||||
self.send_response(200); self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data))); self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def log_message(self, *a):
|
||||
return
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
class Quiet(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
srv = Quiet(("127.0.0.1", 0), Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{srv.server_address[1]}"
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def test_system_page(browser, site):
|
||||
page = browser.new_page()
|
||||
errors = []
|
||||
page.on("pageerror", lambda e: errors.append(str(e)))
|
||||
page.add_init_script("localStorage.setItem('token','t')")
|
||||
page.goto(site + "/admin/v2/system")
|
||||
page.wait_for_selector(".grid .card")
|
||||
assert page.locator(".grid .card").count() == 3
|
||||
assert "smtp" in page.locator("main").inner_text()
|
||||
assert "agent_killswitch" in page.locator("main").inner_text()
|
||||
assert "переключение слоя" in page.locator("main").inner_text()
|
||||
assert errors == []
|
||||
page.close()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""P4.4: система — каналы/настройки/история, только админ, кэш 60 с."""
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def env(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
||||
monkeypatch.setenv("SESSION_SECRET", "test-secret")
|
||||
monkeypatch.setenv("AI_BACKEND", "claude")
|
||||
monkeypatch.chdir(ROOT)
|
||||
import auth
|
||||
import db
|
||||
import main
|
||||
for m in (db, auth, main):
|
||||
importlib.reload(m)
|
||||
db.init_db()
|
||||
db.create_user("boss@x", auth.hash_password("Passw0rd!ok"), role="admin")
|
||||
db.admin_verify_user("boss@x")
|
||||
db.create_user("joe@x", auth.hash_password("Passw0rd!ok"))
|
||||
db.admin_verify_user("joe@x")
|
||||
db.set_app_setting("agent_killswitch", "off")
|
||||
db.log_action("boss@x", "layer_switch", "POST", "/api/admin/layers", "x=on")
|
||||
from fastapi.testclient import TestClient
|
||||
client = TestClient(main.app)
|
||||
h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")}
|
||||
return db, client, h, auth
|
||||
|
||||
|
||||
def test_system_snapshot(env, monkeypatch):
|
||||
db, client, h, auth = env
|
||||
import health_checks
|
||||
monkeypatch.setattr(health_checks, "run_all",
|
||||
lambda: [health_checks.Check("database", True, "ок")])
|
||||
d = client.get("/api/admin/v2/system", headers=h).json()
|
||||
assert d["channels"][0]["name"] == "database"
|
||||
assert any(x["key"] == "agent_killswitch" for x in d["settings"])
|
||||
assert d["history"][0]["label"] == "переключение слоя"
|
||||
|
||||
|
||||
def test_system_admin_only(env):
|
||||
db, client, h, auth = env
|
||||
user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")}
|
||||
assert client.get("/api/admin/v2/system", headers=user).status_code == 403
|
||||
Reference in New Issue
Block a user