feat(админка): очередь внимания

This commit is contained in:
anor
2026-11-06 21:15:28 +10:00
parent b658ac347b
commit 0e7fd76fa1
6 changed files with 237 additions and 1 deletions
+45 -1
View File
@@ -4,8 +4,9 @@ from __future__ import annotations
import asyncio
import time
from fastapi import APIRouter, Request
from fastapi import APIRouter, HTTPException, Request
import attention
import db
import metrics
import money
@@ -50,6 +51,49 @@ async def visit(request: Request):
return {"ok": True, **result}
def _attention_snapshot() -> dict:
work = metrics.collect(1)["work"]
cash = money.summary()
return attention.collect(work, cash)
@router.get("/attention")
async def attention_queue(request: Request):
require_admin(request)
return await asyncio.to_thread(_attention_snapshot)
@router.post("/attention/{key}/done")
async def attention_done(key: str, request: Request):
require_admin(request)
snap = await asyncio.to_thread(_attention_snapshot)
keys = {i["key"] for i in snap["items"]}
if key not in keys and not attention.state_of(key):
raise HTTPException(404, "Такого сигнала нет")
ok = await asyncio.to_thread(attention.mark_done, key)
return {"ok": ok, "key": key}
@router.post("/attention/{key}/snooze")
async def attention_snooze(key: str, request: Request):
require_admin(request)
try:
body = await request.json()
if not isinstance(body, dict):
raise ValueError
minutes = int(body.get("minutes") or 0)
except (ValueError, TypeError):
raise HTTPException(400, "minutes 1..10080") from None
snap = await asyncio.to_thread(_attention_snapshot)
keys = {i["key"] for i in snap["items"]}
if key not in keys and not attention.state_of(key):
raise HTTPException(404, "Такого сигнала нет")
ok = await asyncio.to_thread(attention.snooze, key, minutes)
if not ok:
raise HTTPException(400, "minutes 1..10080")
return {"ok": True, "key": key, "minutes": minutes}
@router.get("/dashboard")
async def dashboard(request: Request):
user = require_admin(request)
+70
View File
@@ -0,0 +1,70 @@
"""Очередь внимания: системные сигналы с устойчивыми ключами и состоянием done/snooze."""
from __future__ import annotations
import time
def collect(work: dict, cash: dict, now: float | None = None) -> dict:
now = time.time() if now is None else now
items: list[dict] = []
def add(key: str, severity: str, title: str, detail: str, action: str | None = None):
items.append({"key": key, "severity": severity, "title": title,
"detail": detail, "action": action})
if (work.get("failures") or 0) > 0:
add("failures:24h", "high", "Сбои за сутки",
f"{work['failures']} обращений закончились сбоем", "/admin/v2/work")
if (work.get("limit_hits") or 0) > 0:
add("limits:24h", "medium", "Упоры в суточный предел",
f"{work['limit_hits']} раз людям отказали по пределу", "/admin/v2/customers")
if (cash.get("unpriced") or 0) > 0:
add("unpriced", "medium", "Прогоны без цены",
f"{cash['unpriced']} ответов не получили цену — сверьте учёт", "/admin/v2/money")
if cash.get("accounts_total_rub") is None:
add("accounts:unread", "high", "Счета не прочитаны",
"Остатки на счетах неизвестны — не принимайте денежных решений", "/admin/v2/money")
# done/snooze живут отдельно от правил: сигнал может исчезнуть сам, состояние останется.
import db
states = db.get_attention_states()
current = {i["key"] for i in items}
# done — «прочитано, пока сигнал активен», а не вечное выключение.
for key, st in list(states.items()):
if st.get("status") == "done" and key not in current:
db.clear_attention_state(key)
states.pop(key, None)
visible = []
for item in items:
st = states.get(item["key"]) or {}
if st.get("status") == "done":
continue
until = st.get("snooze_until")
if until and float(until) > now:
continue
item = dict(item)
item["snoozed_until"] = until
visible.append(item)
return {"items": visible, "count": len(visible), "generated_at": now}
def state_of(key: str) -> dict | None:
import db
return db.get_attention_states().get(key)
def mark_done(key: str) -> bool:
import db
if not key:
return False
db.set_attention_state(key, "done")
return True
def snooze(key: str, minutes: int, now: float | None = None) -> bool:
import db
if not key or minutes < 1 or minutes > 10080:
return False
now = time.time() if now is None else now
db.set_attention_state(key, "snoozed", now + minutes * 60)
return True
+25
View File
@@ -266,6 +266,9 @@ def init_db():
"ON account_entries(username, ts)")
conn.execute("CREATE TABLE IF NOT EXISTS admin_visits ("
"email TEXT PRIMARY KEY, last_seen REAL NOT NULL)")
conn.execute("CREATE TABLE IF NOT EXISTS attention_state ("
"key TEXT PRIMARY KEY, status TEXT NOT NULL, "
"snooze_until REAL, updated_at REAL NOT NULL)")
# Что просили у движка смет и что он ответил — пишет ОСНОВНОЙ процесс, а не агент.
# Всё, что лежит в рабочей папке вкладки, агенту доступно на запись: 14.09.2026 он
# переписал файл запрета и выгрузил неполную смету для экспертизы. База ему недоступна.
@@ -1643,6 +1646,28 @@ def record_admin_visit(email: str, now: float | None = None) -> dict:
return {"previous": previous, "now": ts}
def get_attention_states() -> dict:
with _conn() as conn:
rows = conn.execute("SELECT key, status, snooze_until FROM attention_state").fetchall()
return {r["key"]: {"status": r["status"], "snooze_until": r["snooze_until"]} for r in rows}
def clear_attention_state(key: str) -> None:
with _conn() as conn:
conn.execute("DELETE FROM attention_state WHERE key = ?", (key,))
def set_attention_state(key: str, status: str, snooze_until: float | None = None,
now: float | None = None) -> None:
ts = time.time() if now is None else now
with _conn() as conn:
conn.execute("INSERT INTO attention_state (key, status, snooze_until, updated_at) "
"VALUES (?,?,?,?) ON CONFLICT(key) DO UPDATE SET "
"status=excluded.status, snooze_until=excluded.snooze_until, "
"updated_at=excluded.updated_at",
(key, status, snooze_until, ts))
def get_admin_visit(email: str) -> float | None:
with _conn() as conn:
row = conn.execute("SELECT last_seen FROM admin_visits WHERE email = ?",
+7
View File
@@ -185,6 +185,13 @@
- Замер на копии прода: первый ответ 528 мс (холодный), повторные 1,3–2,3 мс.
- Тесты: `tests/test_admin_dashboard_api.py` — 6 passed.
## 4.20. P2.4 — очередь внимания
- `/api/admin/v2/attention`: failures:24h, limits:24h, unpriced, accounts:unread.
- `attention_state` (done/snooze); done скрывает только пока сигнал активен, исчез — состояние снимается.
- `/attention/{key}/done` и `/snooze`; 400 на пустое/битое тело, 404 на неизвестный ключ; done идемпотентен, пока сигнал в очереди.
- Тесты: `tests/test_attention.py` — 3 passed (включая реальный snapshot без подмены).
## 5. Следующий шаг
P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания).
+1
View File
@@ -12,6 +12,7 @@
- P0.1 — прод-бэкап `2026-11-06_1632.gz` (2,7 МБ gz / 12 МБ), `integrity_check=ok`, users 24, messages 5397; `SMETA_USER/PASS` заданы (env-вход — реальный); индекс на копии 46 мс. Админка на копии открыта (`/admin` 200, users/stats/overview 200). Осталось: 5 вопросов владельца.
- P0.2 — выравнивание сделано; pre-release `feat/topup` проверен: 155 тестов зелёные, отчёт `docs/ADMIN_V2_TOPUP_PRERELEASE.md`; **релиз не начинался** (нужен go/no-go и тест-магазин).
- **P0.5 — готово:** спайк в `sandbox/admin-spike/`; Preact+htm: 8,7 КБ gzip, 106 строк, 37,2 мс; vanilla: 3,3 КБ, 116 строк, 34,5 мс; CSP 0 ошибок у обоих; решение — Preact+htm, fallback vanilla; ревью Зайкой 3 круга, последний без дефектов. `docs/ADMIN_V2_DECISIONS.md`.
- **P2.4 — готово:** `attention.py` (failures/limits/unpriced/accounts), стабильные ключи, `attention_state` done/snooze, done снимается при исчезновении сигнала, 400 на кривое тело; 3 теста. Зайка P1 (unpriced не управлялся, 500 на теле, вечный done) исправлены.
- **P2.3 — готово:** `money.summary`, `/api/admin/v2/dashboard` одним ответом, `/visit` с предыдущим визитом, кэш 15 с (общий, personal-поля вне кэша), p95 полей задержки, unpriced из счетов; 6 тестов. Зайка P1 (чужой user/last_visit в кэше, мёртвый unpriced) исправлены.
- **P2.2 — готово:** `/admin/v2` + deep link `{section:path}`, `admin_api.py`/`admin_auth.py`, `/api/admin/v2/ping` admin-only, strict CSP только v2 (legacy сохраняет текущую политику), audit `admin.v2.*`; 4 теста.
- **P2.1a/b — готово:** оболочка `/static/admin2/` (5 разделов, Preact+htm, абсолютные импорты), deep link + F5, CSP без inline, 3 теста; Зайка P2 (дубли путей/заголовков) исправлены.
+89
View File
@@ -0,0 +1,89 @@
"""P2.4: устойчивые ключи, done/snooze, идемпотентность, не врём про done."""
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
import admin_api
import attention
for m in (db, auth, main, admin_api, attention):
importlib.reload(m)
db.init_db()
db.create_user("boss@x", auth.hash_password("Passw0rd!ok"), role="admin")
db.admin_verify_user("boss@x")
from fastapi.testclient import TestClient
client = TestClient(main.app)
h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")}
return db, attention, client, h, monkeypatch
def test_collect_stable_keys_and_state(env):
db, attention, client, h, monkeypatch = env
work = {"failures": 2, "limit_hits": 1}
cash = {"unpriced": 3, "accounts_total_rub": 0}
snap = attention.collect(work, cash)
keys = {i["key"] for i in snap["items"]}
assert {"failures:24h", "limits:24h", "unpriced"} <= keys
db.set_attention_state("failures:24h", "done")
db.set_attention_state("limits:24h", "snoozed", 9_999_999_999)
snap2 = attention.collect(work, cash)
assert "failures:24h" not in {i["key"] for i in snap2["items"]}
assert "limits:24h" not in {i["key"] for i in snap2["items"]}
assert "unpriced" in {i["key"] for i in snap2["items"]}
# Сигнал исчез — done снимается, чтобы завтрашний возврат снова был виден.
snap3 = attention.collect({}, {"unpriced": 0, "accounts_total_rub": 0})
assert "failures:24h" not in {i["key"] for i in snap3["items"]}
assert not attention.state_of("failures:24h")
def test_endpoint_done_snooze_and_unknown(env):
db, attention, client, h, monkeypatch = env
import admin_api
monkeypatch.setattr(admin_api, "_attention_snapshot",
lambda: {"items": [{"key": "failures:24h", "title": "x"},
{"key": "unpriced", "title": "y"}], "count": 2})
assert client.get("/api/admin/v2/attention", headers=h).status_code == 200
assert client.post("/api/admin/v2/attention/failures:24h/done", headers=h).status_code == 200
# повтор done — идемпотентен, хотя сигнала уже нет
assert client.post("/api/admin/v2/attention/failures:24h/done", headers=h).status_code == 200
assert client.post("/api/admin/v2/attention/nope:1/done", headers=h).status_code == 404
assert client.post("/api/admin/v2/attention/failures:24h/snooze",
json={"minutes": 0}, headers=h).status_code == 400
assert client.post("/api/admin/v2/attention/failures:24h/snooze",
headers=h).status_code == 400
assert client.post("/api/admin/v2/attention/failures:24h/snooze",
json={"minutes": "abc"}, headers=h).status_code == 400
assert client.post("/api/admin/v2/attention/failures:24h/snooze",
json={"minutes": 10}, headers=h).status_code == 200
assert client.post("/api/admin/v2/attention/unpriced/done", headers=h).status_code == 200
assert client.post("/api/admin/v2/attention/unpriced/snooze",
json={"minutes": 5}, headers=h).status_code == 200
def test_real_snapshot_without_monkeypatch(env):
db, attention, client, h, monkeypatch = env
db.add_account_entry("joe@x", 1000.0, "взнос", "boss@x", ts=0)
with db._conn() as c:
c.execute("INSERT INTO llm_usage (ts, username, tab_id, path, provider, model, "
"input_tokens, cache_tokens, output_tokens, cost_usd, cost_rub, price_rub) "
"VALUES (1,'joe@x','t','agent','deepseek','m',1,0,1,0,0,NULL)")
r = client.get("/api/admin/v2/attention", headers=h)
assert r.status_code == 200
keys = {i["key"] for i in r.json()["items"]}
assert "unpriced" in keys