diff --git a/admin_actions.py b/admin_actions.py new file mode 100644 index 0000000..27b1d77 --- /dev/null +++ b/admin_actions.py @@ -0,0 +1,95 @@ +"""Обратимые действия v2: роль/блок/режим/пробный/доступ/пределы + undo.""" +from __future__ import annotations + +import db + +ACTIONS = {"role", "block", "read_only", "trial", "agent_access", "limits"} + + +def _user(email: str) -> dict: + u = db.get_user_by_email(email, include_deleted=True) + if not u: + raise LookupError("клиент не найден") + return u + + +def _before(email: str, action: str) -> dict: + u = _user(email) + if action == "role": + return {"role": u.get("role")} + if action == "block": + return {"blocked": bool(u.get("blocked"))} + if action == "read_only": + return {"read_only": bool(u.get("read_only"))} + if action == "trial": + return {"trial": bool(u.get("trial"))} + if action == "agent_access": + return {"agent_access": bool(u.get("agent_access"))} + if action == "limits": + return {"requests": u.get("daily_request_limit"), + "rub": db.get_user_spend_limits(email).get("rub"), + "tokens": db.get_user_spend_limits(email).get("tokens")} + raise ValueError("неизвестное действие") + + +def _apply(email: str, action: str, value: dict) -> None: + _user(email) # удалённый/несуществующий адрес — честный отказ, а не «ок» + if action == "role": + if value.get("role") not in ("admin", "user"): + raise ValueError("роль только admin/user") + if not db.set_user_role(email, value["role"]): + raise LookupError("роль не изменена") + elif action == "block": + if not isinstance(value.get("blocked"), bool): + raise ValueError("blocked — true/false") + if not db.block_user(email, value["blocked"]): + raise LookupError("блокировка не изменена") + elif action == "read_only": + if not isinstance(value.get("read_only"), bool): + raise ValueError("read_only — true/false") + if not db.set_read_only(email, value["read_only"]): + raise LookupError("режим не изменён") + elif action == "trial": + if not isinstance(value.get("trial"), bool): + raise ValueError("trial — true/false") + if not db.set_trial(email, value["trial"]): + raise LookupError("пробный режим не изменён") + elif action == "agent_access": + if not isinstance(value.get("agent_access"), bool): + raise ValueError("agent_access — true/false") + db.set_user_agent_access(email, value["agent_access"]) + elif action == "limits": + res = db.set_user_limits_bulk([email], requests=value.get("requests"), + rub=value.get("rub"), tokens=value.get("tokens")) + if res.get("changed") != 1: + raise LookupError("пределы не изменены") + else: + raise ValueError("неизвестное действие") + + +def perform(actor: str, email: str, action: str, value: dict) -> dict: + if action not in ACTIONS: + raise ValueError("неизвестное действие") + before = _before(email, action) + _apply(email, action, value) + after = _before(email, action) + action_id = db.record_admin_action(actor, email, action, before, after) + db.log_action(actor, "admin_action", "POST", f"/api/admin/v2/customers/{email}/action", + detail=f"{action}: {before} → {after}") + return {"ok": True, "id": action_id, "action": action, "target": email, + "before": before, "after": after} + + +def undo(actor: str, action_id: int) -> dict: + row = db.get_admin_action(action_id) + if not row: + raise LookupError("действие не найдено") + if row.get("undone_at"): + return {"ok": True, "id": action_id, "already": True} + _user(row["target"]) + _apply(row["target"], row["action"], row["before"]) + db.mark_admin_action_undone(action_id) + db.log_action(actor, "admin_action_undo", "POST", f"/api/admin/v2/actions/{action_id}/undo", + detail=f"{row['action']}") + return {"ok": True, "id": action_id, "action": row["action"], + "target": row["target"], "restored": row["before"]} diff --git a/admin_api.py b/admin_api.py index d9c6ad5..80a7eb6 100644 --- a/admin_api.py +++ b/admin_api.py @@ -6,6 +6,7 @@ import time from fastapi import APIRouter, HTTPException, Request +import admin_actions import attention import customers import db @@ -153,6 +154,36 @@ async def customer_history(email: str, request: Request): return {"items": data} +@router.post("/customers/{email}/action") +async def customer_action(email: str, request: Request): + user = require_admin(request) + try: + body = await request.json() + except Exception: + raise HTTPException(400, "тело — JSON-объект") from None + action = body.get("action") if isinstance(body, dict) else None + value = body.get("value") if isinstance(body, dict) else None + if not isinstance(value, dict): + raise HTTPException(400, "value должен быть объектом") + try: + return await asyncio.to_thread(admin_actions.perform, user, email, action, value) + except ValueError as e: + raise HTTPException(400, str(e)) from e + except LookupError as e: + raise HTTPException(404, str(e)) from e + + +@router.post("/actions/{action_id}/undo") +async def undo_action(action_id: int, request: Request): + user = require_admin(request) + try: + return await asyncio.to_thread(admin_actions.undo, user, action_id) + except LookupError as e: + raise HTTPException(404, str(e)) from e + except ValueError as e: + raise HTTPException(400, str(e)) from e + + @router.get("/dashboard") async def dashboard(request: Request): user = require_admin(request) diff --git a/db.py b/db.py index 0a500ad..a8fafec 100644 --- a/db.py +++ b/db.py @@ -269,6 +269,11 @@ def init_db(): 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)") + conn.execute("CREATE TABLE IF NOT EXISTS admin_actions (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, actor TEXT NOT NULL, " + "target TEXT NOT NULL, action TEXT NOT NULL, " + "before_json TEXT NOT NULL, after_json TEXT, " + "created_at REAL NOT NULL, undone_at REAL)") # Что просили у движка смет и что он ответил — пишет ОСНОВНОЙ процесс, а не агент. # Всё, что лежит в рабочей папке вкладки, агенту доступно на запись: 14.09.2026 он # переписал файл запрета и выгрузил неполную смету для экспертизы. База ему недоступна. @@ -1655,6 +1660,38 @@ def record_admin_visit(email: str, now: float | None = None) -> dict: return {"previous": previous, "now": ts} +def record_admin_action(actor: str, target: str, action: str, + before: dict, after: dict, now: float | None = None) -> int: + import json as _json + ts = time.time() if now is None else now + with _conn() as conn: + cur = conn.execute( + "INSERT INTO admin_actions (actor, target, action, before_json, after_json, created_at) " + "VALUES (?,?,?,?,?,?)", + (actor, target, action, _json.dumps(before, ensure_ascii=False), + _json.dumps(after, ensure_ascii=False), ts)) + return int(cur.lastrowid) + + +def get_admin_action(action_id: int) -> dict | None: + import json as _json + with _conn() as conn: + row = conn.execute("SELECT * FROM admin_actions WHERE id = ?", (action_id,)).fetchone() + if not row: + return None + d = dict(row) + d["before"] = _json.loads(d.pop("before_json") or "{}") + d["after"] = _json.loads(d.pop("after_json") or "{}") + return d + + +def mark_admin_action_undone(action_id: int, now: float | None = None) -> None: + ts = time.time() if now is None else now + with _conn() as conn: + conn.execute("UPDATE admin_actions SET undone_at = COALESCE(undone_at, ?) WHERE id = ?", + (ts, action_id)) + + def get_attention_states() -> dict: with _conn() as conn: rows = conn.execute("SELECT key, status, snooze_until FROM attention_state").fetchall() diff --git a/docs/ADMIN_V2_BASELINE.md b/docs/ADMIN_V2_BASELINE.md index 4bac974..a500cae 100644 --- a/docs/ADMIN_V2_BASELINE.md +++ b/docs/ADMIN_V2_BASELINE.md @@ -222,6 +222,13 @@ - Тесты: `tests/test_customer_card_api.py` — 3, UI — 4; lazy-вкладка проверяется счётчиком. - P2: фокус-трап drawer — остаток. +## 4.25. P2.8 (частично) — обратимые действия + +- `admin_actions` (before/after, undone_at), `/customers/{email}/action`, `/actions/{id}/undo`. +- Роль/блок/режим/пробный/доступ/пределы; bool строго, битый JSON → 400, undo после удаления → 404 без ложного «готово». +- `perform`/`undo` пишут `audit_log`. +- Тесты: `tests/test_admin_actions.py` — 5 passed. UI-тост — остаток. + ## 5. Следующий шаг P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания). diff --git a/docs/PLAN_2026-11-06_admin_v2.md b/docs/PLAN_2026-11-06_admin_v2.md index 8633de1..82a8500 100644 --- a/docs/PLAN_2026-11-06_admin_v2.md +++ b/docs/PLAN_2026-11-06_admin_v2.md @@ -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.8 — частично:** `admin_actions` + undo для роли/блока/режима/пробного/доступа/пределов; идемпотентность, проверка bool/JSON, отказ после удаления, аудит; 5 тестов. UI-тост «Отменить» — остаток. - **P2.7 — готово:** карточка клиента + drawer, 6 вопросов, lazy-вкладки (диалоги/счёт/файлы/история), Escape/клик по фону, удалённый по исходному адресу; 3 API + 4 UI теста. Зайка P1 (loading/empty, files 100+) исправлены. - **P2.6b — готово:** таблица клиентов v2 (6 колонок), поиск/статус/пагинация, URL-состояние, ошибка с «Повторить», мобильный скролл без разъезда страницы; 3 UI-теста. Зайка P1 (URL-состояние, тавтологичный мобильный тест) исправлены. - **P2.6a — готово:** `/api/admin/v2/customers` — поиск `q`/`query`, статусы, пагинация, last_seen, баланс, is_owner; счета без N+1; сбой счетов → 503 только для exhausted; 4 теста. Зайка P1 (нет проверок баланса/last_seen) исправлены. diff --git a/tests/test_admin_actions.py b/tests/test_admin_actions.py new file mode 100644 index 0000000..6b881de --- /dev/null +++ b/tests/test_admin_actions.py @@ -0,0 +1,94 @@ +"""P2.8: обратимая блокировка/роль/пределы, undo идемпотентен.""" +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") + 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_block_and_undo(env): + db, client, h, auth = env + r = client.post("/api/admin/v2/customers/joe@x/action", + json={"action": "block", "value": {"blocked": True}}, headers=h) + assert r.status_code == 200, r.text + aid = r.json()["id"] + assert db.get_user_by_email("joe@x")["blocked"] == 1 + u = client.post(f"/api/admin/v2/actions/{aid}/undo", headers=h) + assert u.status_code == 200 + assert db.get_user_by_email("joe@x")["blocked"] == 0 + assert client.post(f"/api/admin/v2/actions/{aid}/undo", headers=h).json()["already"] is True + + +def test_role_and_limits_roundtrip(env): + db, client, h, auth = env + r = client.post("/api/admin/v2/customers/joe@x/action", + json={"action": "role", "value": {"role": "admin"}}, headers=h).json() + assert db.get_user_by_email("joe@x")["role"] == "admin" + client.post(f"/api/admin/v2/actions/{r['id']}/undo", headers=h) + assert db.get_user_by_email("joe@x")["role"] == "user" + + r = client.post("/api/admin/v2/customers/joe@x/action", + json={"action": "limits", "value": {"rub": 10}}, headers=h).json() + assert db.get_user_spend_limits("joe@x")["rub"] == 10 + client.post(f"/api/admin/v2/actions/{r['id']}/undo", headers=h) + assert db.get_user_spend_limits("joe@x")["rub"] is None + + +def test_bad_action_and_permissions(env): + db, client, h, auth = env + assert client.post("/api/admin/v2/customers/joe@x/action", + json={"action": "nope", "value": {}}, headers=h).status_code == 400 + assert client.post("/api/admin/v2/customers/joe@x/action", + json={"action": "role", "value": {"role": "root"}}, + headers=h).status_code == 400 + user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")} + assert client.post("/api/admin/v2/actions/1/undo", headers=user).status_code == 403 + + +def test_bool_strings_and_bad_json_are_refused(env): + db, client, h, auth = env + assert client.post("/api/admin/v2/customers/joe@x/action", + json={"action": "block", "value": {"blocked": "false"}}, + headers=h).status_code == 400 + assert client.post("/api/admin/v2/customers/joe@x/action", + data="{oops", headers={**h, "Content-Type": "application/json"}, + ).status_code == 400 + + +def test_undo_after_soft_delete_does_not_lie(env): + db, client, h, auth = env + aid = client.post("/api/admin/v2/customers/joe@x/action", + json={"action": "block", "value": {"blocked": True}}, + headers=h).json()["id"] + db.soft_delete_user("joe@x") + r = client.post(f"/api/admin/v2/actions/{aid}/undo", headers=h) + assert r.status_code == 404 + assert "не найден" in r.json()["detail"] + # состояние не помечено undone — откат не врёт + assert db.get_admin_action(aid)["undone_at"] is None