diff --git a/admin_api.py b/admin_api.py index 84ad118..6e1ae33 100644 --- a/admin_api.py +++ b/admin_api.py @@ -160,6 +160,19 @@ async def customer_history(email: str, request: Request): return {"items": data} +@router.get("/customers/{email}/export") +async def customer_export(email: str, request: Request): + user = require_admin(request) + data = await asyncio.to_thread(customers.export_zip, email) + if data is None: + raise HTTPException(404, "Клиент не найден") + db.log_action(user, "customer_export", "GET", + f"/api/admin/v2/customers/{email}/export", detail=f"{len(data)} байт") + from fastapi.responses import Response + return Response(data, media_type="application/zip", + headers={"Content-Disposition": f'attachment; filename="export.zip"'}) + + @router.post("/customers/{email}/topup") async def customer_topup(email: str, request: Request): user = require_admin(request) diff --git a/customers.py b/customers.py index 6994c02..6043f85 100644 --- a/customers.py +++ b/customers.py @@ -171,3 +171,40 @@ def files(email: str) -> list[dict] | None: if len(out) >= 500: break return out + + +def export_zip(email: str) -> bytes | None: + """Полная выгрузка клиента: профиль, сообщения, файлы, счёт, аудит.""" + import db + import balance + import json + import io + import zipfile + from pathlib import Path + u = db.get_user_by_email(email, include_deleted=True) + if not u: + return None + raw = u["email"] + profile = {k: u.get(k) for k in ("email", "deleted_email", "role", "verified", "blocked", + "read_only", "trial", "agent_provider", "agent_access", + "telegram", "tg_username", "created_at", "deleted_at")} + sessions = db.list_sessions(raw) + messages = [] + for s in sessions: + for m in db.get_history(raw, s["tab_id"], limit=100000): + messages.append({"tab_id": s["tab_id"], **m}) + ledger = {"entries": db.list_account_entries(raw, limit=1000), + "account": balance.state(raw)} + audit = db.get_audit_log(limit=1000, username=raw) + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("profile.json", json.dumps(profile, ensure_ascii=False, indent=2)) + z.writestr("messages.json", json.dumps(messages, ensure_ascii=False, indent=2)) + z.writestr("ledger.json", json.dumps(ledger, ensure_ascii=False, indent=2)) + z.writestr("audit.json", json.dumps(audit, ensure_ascii=False, indent=2)) + root = _root(raw) + if root and root.is_dir(): + for f in root.rglob("*"): + if f.is_file() and f.stat().st_size <= 20 * 1024 * 1024: + z.write(f, "files/" + str(f.relative_to(root))) + return buf.getvalue() diff --git a/docs/ADMIN_V2_BASELINE.md b/docs/ADMIN_V2_BASELINE.md index a14aff1..7c58327 100644 --- a/docs/ADMIN_V2_BASELINE.md +++ b/docs/ADMIN_V2_BASELINE.md @@ -291,6 +291,13 @@ - UI: 3 карточки, каналы, таблицы настроек/истории; автообновление 60 с. - Тесты: API — 2, UI — 1. +## 4.38. P4.7a — выгрузка клиента + +- `/customers/{email}/export`: zip с profile/messages/ledger/audit/files; 404/403; аудит. +- UI: «Выгрузить» в карточке через fetch+blob. +- Тесты: `tests/test_customer_export.py` — 2; UI карточки — 9. +- P4.7b (удаление/анонимизация) — после P0.4. + ## 5. Следующий шаг P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания). diff --git a/static/admin2/pages/customer.js b/static/admin2/pages/customer.js index 9ac0fa0..e07aa97 100644 --- a/static/admin2/pages/customer.js +++ b/static/admin2/pages/customer.js @@ -80,6 +80,19 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) { } catch (e) { setNotice(e.message || 'Взнос не записан'); } finally { setBusy(false); } }; + const exportData = async () => { + setBusy(true); + try { + const r = await fetch('/api/admin/v2/customers/' + encodeURIComponent(email) + '/export', + {headers: {Authorization: 'Bearer ' + (localStorage.getItem('token') || '')}}); + if (!r.ok) throw new Error('Ошибка ' + r.status); + const url = URL.createObjectURL(await r.blob()); + const a = document.createElement('a'); + a.href = url; a.download = 'export.zip'; a.click(); + URL.revokeObjectURL(url); + } catch (e) { setNotice(e.message || 'Не удалось выгрузить'); } + finally { setBusy(false); } + }; const del = async () => { if (!confirm('Удалить учётку ' + email + '? Переписка и файлы останутся, адрес освободится.')) return; setBusy(true); setNotice(''); @@ -122,6 +135,7 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) { {agent_access: !card.profile.agent_access}, card.profile.agent_access ? 'Доступ снят' : 'Доступ выдан')}> ${card.profile.agent_access ? 'Снять агента' : 'Выдать агента'} + ` : html`
diff --git a/tests/test_customer_export.py b/tests/test_customer_export.py new file mode 100644 index 0000000..bb376c0 --- /dev/null +++ b/tests/test_customer_export.py @@ -0,0 +1,60 @@ +"""P4.7a: выгрузка клиента — профиль/сообщения/файлы/счёт/аудит.""" +import importlib +import io +import os +import sys +import zipfile +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + + +@pytest.fixture() +def env(tmp_path, monkeypatch): + data = tmp_path / "data"; data.mkdir() + monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db")) + monkeypatch.setenv("DATA_DIR", str(data)) + 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.save_message("joe@x", "t1", "user", "секрет") + db.add_account_entry("joe@x", 10.0, "взнос", "boss@x") + (data / "joe@x").mkdir() + (data / "joe@x" / "a.txt").write_text("hello", encoding="utf-8") + 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_export_contains_all_parts(env): + db, client, h, auth = env + r = client.get("/api/admin/v2/customers/joe@x/export", headers=h) + assert r.status_code == 200 + assert r.headers["content-type"].startswith("application/zip") + z = zipfile.ZipFile(io.BytesIO(r.content)) + names = set(z.namelist()) + assert {"profile.json", "messages.json", "ledger.json", "audit.json", + "files/a.txt"} <= names + assert "секрет" in z.read("messages.json").decode() + assert any(r["action"] == "customer_export" for r in db.get_audit_log(10)) + + +def test_export_404_and_admin_only(env): + db, client, h, auth = env + assert client.get("/api/admin/v2/customers/ghost@x/export", headers=h).status_code == 404 + user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")} + assert client.get("/api/admin/v2/customers/joe@x/export", headers=user).status_code == 403