diff --git a/docs/ADMIN_V2_BASELINE.md b/docs/ADMIN_V2_BASELINE.md
index b615574..9f74cfd 100644
--- a/docs/ADMIN_V2_BASELINE.md
+++ b/docs/ADMIN_V2_BASELINE.md
@@ -110,6 +110,15 @@
- `unapplied` не считается оплатой — решение в `docs/ADMIN_V2_DECISIONS.md`.
- Тесты: `tests/test_metrics.py` — 22 passed; topup до регистрации и `paid_at` проверяются; Зайка P2 исправлены.
+## 4.10. P1.5 — CSV
+
+- `/api/admin/export/users.csv`, `payments.csv`, `audit.csv`; admin-only; BOM + `;`.
+- Пользователи: q по raw/показываемому email, Telegram, tg_username, deleted_email; status; баланс в RU-формате.
+- Платежи за 30 дней; журнал с фильтрами и маркером «выгружены не все»; время UTC+10.
+- Формулы `= + - @` обезврежены; числовые колонки — числом; при сбое счетов — notice/503.
+- UI: кнопки CSV, скачивание blob с Bearer.
+- Тесты: `tests/test_admin_export.py` — 8 passed; Зайка ACCEPT.
+
## 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 fd645c7..ecd20fc 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`.
+- **P1.5 — готово:** CSV клиентов/платежей/журнала с BOM/`;`, фильтрами q/status, UTC+10, числовым форматом RU, защитой от формул, 503 при сбое счетов и маркером обрезки; 8 тестов; Зайка ACCEPT (P2 закреплены).
- **P1.2 — готово:** воронка set-based (3 запроса вместо N+1), `paid` = legacy `payments.succeeded` + `topups.succeeded` (если таблица есть), cohort после регистрации, служебные исключены; 22 теста; Зайка: код чист, P2 в тесте (topup до регистрации/paid_at) исправлены.
- **P1.3 — готово:** «Прибыль» → «Денежный поток», итог по счетам клиентов отдельной строкой («сейчас», обязательство), честная пометка «без пополнений (до P0.2)»; `flow_rub`/`flow_share` + старые `profit_rub`/`margin_share`; 26 тестов; Зайка ACCEPT (P2 закрыты).
- **P1.1b — готово:** 7 колонок, меню «…», `table-wrap`, липкая первая, поиск/статус/пагинация, «Загрузка…»/ошибка/«обновлено»; строка ≤72 на длинном адресе; 7 UI-тестов; Зайка 4 круга, последний REVISE — длинный адрес раздувал строку, исправлено (`ellipsis`).
diff --git a/main.py b/main.py
index 0ef4c53..a5692a4 100644
--- a/main.py
+++ b/main.py
@@ -2,6 +2,8 @@
import asyncio
import calendar
+import csv
+import io
import hmac
import json
import logging
@@ -2603,6 +2605,159 @@ async def admin_sessions(request: Request):
return out
+def _csv_cell(value) -> str:
+ """Ячейка CSV: Excel не должен исполнить =/+/-/@ как формулу."""
+ text = "" if value is None else str(value)
+ if text[:1] in ("=", "+", "-", "@"):
+ text = "'" + text
+ return text
+
+
+def _csv_ts(value) -> str:
+ """Время в UTC+10 (часы Хозяина), а не в поясе сервера: файл живёт дольше сессии."""
+ try:
+ return time.strftime("%Y-%m-%d %H:%M", time.gmtime(float(value) + 10 * 3600))
+ except (TypeError, ValueError, OSError):
+ return ""
+
+
+def _csv_response(rows: list[dict], columns: list[tuple[str, str]], filename: str,
+ numeric: set[str] | None = None, notice: str | None = None) -> Response:
+ buf = io.StringIO()
+ buf.write("\ufeff") # Excel и кириллица без BOM превращаются в кракозябры
+ writer = csv.writer(buf, delimiter=";", lineterminator="\r\n")
+ writer.writerow([label for _, label in columns])
+ for row in rows:
+ cells = []
+ for key, _ in columns:
+ value = row.get(key)
+ if numeric and key in numeric and value not in (None, ""):
+ try:
+ # Числовая колонка — не пользовательский текст: минус оставляем числом,
+ # иначе Excel видит "'-500,00" как текст.
+ value = f"{float(value):.2f}".replace(".", ",")
+ cells.append(value)
+ continue
+ except (TypeError, ValueError):
+ pass
+ cells.append(_csv_cell(value))
+ writer.writerow(cells)
+ if notice:
+ writer.writerow([notice] + [""] * (len(columns) - 1))
+ return Response(content=buf.getvalue().encode("utf-8"),
+ media_type="text/csv; charset=utf-8",
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'})
+
+
+@app.get("/api/admin/export/users.csv")
+async def admin_export_users_csv(request: Request):
+ """Клиенты в CSV: те же поля, что видит оператор, без токенов и паролей."""
+ _require_admin(request)
+ q = (request.query_params.get("q") or "").strip().lower()
+ status = (request.query_params.get("status") or "").strip().lower()
+ allowed = {"active", "blocked", "deleted", "read_only", "exhausted", "trial", "unverified"}
+ if status and status not in allowed:
+ raise HTTPException(400, "Неизвестный статус")
+ show_deleted = (request.query_params.get("deleted") in ("1", "true", "yes")
+ or status == "deleted")
+
+ accounts_failed = False
+
+ def _rows():
+ nonlocal accounts_failed
+ from db import list_users, last_seen_all, account_balances_all
+ import balance
+ import billing
+ users = list_users(include_deleted=show_deleted)
+ seen = last_seen_all()
+ try:
+ accounts = account_balances_all()
+ except Exception: # noqa: BLE001 — выгрузка не должна падать из-за счетов
+ logger.exception("export/users: счета не прочитаны")
+ accounts = {}
+ accounts_failed = True
+ out = []
+ for u in users:
+ email = u.get("email", "")
+ acc = accounts.get(email)
+ composed = None
+ if acc and not billing._is_our_own(email):
+ composed = balance.compose(acc["deposited_kop"], acc["charged"],
+ acc["first_ts"], acc["unpriced"])
+ status = ("deleted" if u.get("deleted_at") else "blocked" if u.get("blocked")
+ else "read_only" if u.get("read_only")
+ else "exhausted" if (composed and composed.get("exhausted"))
+ else "trial" if u.get("trial")
+ else "active" if u.get("verified") else "unverified")
+ out.append({"email": u.get("deleted_email") or email, "raw_email": email,
+ "deleted_email": u.get("deleted_email"),
+ "tg_username": u.get("tg_username"), "role": u.get("role"),
+ "status": status, "verified": u.get("verified"),
+ "blocked": u.get("blocked"), "read_only": u.get("read_only"),
+ "trial": u.get("trial"), "telegram": u.get("telegram"),
+ "agent_provider": u.get("agent_provider"),
+ "agent_access": u.get("agent_access"),
+ "created_at": _csv_ts(u.get("created_at")),
+ "last_seen": _csv_ts(seen.get(email)),
+ "deleted_at": _csv_ts(u.get("deleted_at")),
+ "balance_rub": composed["balance_rub"] if composed else ""})
+ return out
+
+ rows = await asyncio.to_thread(_rows)
+ if status == "exhausted" and accounts_failed:
+ raise HTTPException(503, "Счета не прочитаны")
+ if q:
+ rows = [r for r in rows
+ if q in " ".join(str(r.get(k) or "") for k in
+ ("email", "raw_email", "telegram", "tg_username",
+ "deleted_email")).lower()]
+ if status:
+ rows = [r for r in rows if r.get("status") == status]
+ columns = [("email", "Email"), ("role", "Роль"), ("status", "Статус"),
+ ("verified", "Подтверждён"), ("blocked", "Заблокирован"),
+ ("read_only", "Только просмотр"), ("trial", "Пробный"),
+ ("telegram", "Telegram"), ("agent_provider", "Провайдер"),
+ ("agent_access", "Агент"), ("created_at", "Создан"),
+ ("last_seen", "Был(а)"), ("deleted_at", "Удалён"),
+ ("balance_rub", "Баланс, ₽")]
+ notice = ("балансы не прочитаны — колонка «Баланс» неполная" if accounts_failed else None)
+ return _csv_response(rows, columns, "users.csv", numeric={"balance_rub"}, notice=notice)
+
+
+@app.get("/api/admin/export/payments.csv")
+async def admin_export_payments_csv(request: Request, days: int = 30):
+ """Платежи в CSV за тот же период, что показывает экран."""
+ _require_admin(request)
+ from db import list_payments
+ rows = await asyncio.to_thread(list_payments, max(1, min(days, 3650)))
+ for r in rows:
+ r["ts"] = _csv_ts(r.get("ts"))
+ columns = [("ts", "Время (UTC+10)"), ("username", "Пользователь"), ("product", "Тариф"),
+ ("amount_rub", "Сумма, ₽"), ("status", "Статус"),
+ ("yk_payment_id", "ID платежа")]
+ return _csv_response(rows, columns, "payments.csv", numeric={"amount_rub"})
+
+
+@app.get("/api/admin/export/audit.csv")
+async def admin_export_audit_csv(request: Request):
+ """Журнал действий в CSV с теми же фильтрами, что на экране."""
+ _require_admin(request)
+ limit = max(1, min(_целое(request, "limit", 1000), 5000))
+ offset = max(0, _целое(request, "offset", 0))
+ username = request.query_params.get("username") or None
+ action = request.query_params.get("action") or None
+ rows = await asyncio.to_thread(get_audit_log, limit + 1, offset, username, action)
+ truncated = len(rows) > limit
+ rows = rows[:limit]
+ for r in rows:
+ r["timestamp"] = _csv_ts(r.get("timestamp"))
+ columns = [("timestamp", "Время (UTC+10)"), ("username", "Пользователь"),
+ ("action", "Действие"), ("method", "Метод"), ("path", "Путь"),
+ ("detail", "Детали"), ("ip", "IP"), ("status_code", "Код")]
+ notice = ("выгружены не все — сузьте фильтр" if truncated else None)
+ return _csv_response(rows, columns, "audit.csv", notice=notice)
+
+
@app.get("/api/admin/audit")
async def admin_audit(request: Request):
"""Full audit log — admin only."""
diff --git a/static/admin.html b/static/admin.html
index 2665530..d81d88f 100644
--- a/static/admin.html
+++ b/static/admin.html
@@ -639,6 +639,7 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
+
Платежи
+
| Время | Пользователь | Тариф | ₽ | Статус | ID ЮKassa |
@@ -927,6 +929,7 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
+
| Время | Пользователь | Действие | Путь | Детали | IP | Код |
@@ -1440,6 +1443,40 @@ async function applyLimits() {
}
}
+async function downloadCsv(url, filename) {
+ await пропускГотов;
+ try {
+ const r = await fetch(url, {headers: H});
+ if (!r.ok) { alert('Не удалось выгрузить CSV: HTTP ' + r.status); return; }
+ const blob = await r.blob();
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
+ } catch (e) {
+ alert('Не удалось выгрузить CSV: ' + (e.message || 'сеть'));
+ }
+}
+function downloadUsersCsv() {
+ const p = new URLSearchParams();
+ const q = (document.getElementById('users-q') || {}).value || '';
+ const status = (document.getElementById('users-status') || {}).value || '';
+ if (q.trim()) p.set('q', q.trim());
+ if (status) p.set('status', status);
+ if ((document.getElementById('show-deleted') || {}).checked) p.set('deleted', '1');
+ downloadCsv('/api/admin/export/users.csv?' + p.toString(), 'users.csv');
+}
+function downloadAuditCsv() {
+ const p = new URLSearchParams({limit: '5000'});
+ const u = (document.getElementById('audit-user') || {}).value || '';
+ const a = (document.getElementById('audit-action') || {}).value || '';
+ if (u) p.set('username', u);
+ if (a) p.set('action', a);
+ downloadCsv('/api/admin/export/audit.csv?' + p.toString(), 'audit.csv');
+}
let usersPage = 1, usersTotal = 0, usersTimer = null, usersReq = 0;
const USERS_PER_PAGE = 50;
const USERS_HEAD = '| Клиент | Статус | Был(а) | 24 ч | Баланс | Доступ | Действия |
';
diff --git a/tests/test_admin_export.py b/tests/test_admin_export.py
new file mode 100644
index 0000000..9eabec3
--- /dev/null
+++ b/tests/test_admin_export.py
@@ -0,0 +1,138 @@
+"""CSV клиентов/платежей/журнала: Excel-совместимость, суммы, защита от формул."""
+import csv
+import importlib
+import io
+import os
+import sys
+import time
+from urllib.parse import quote
+
+import pytest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+if ROOT not in sys.path:
+ sys.path.insert(0, ROOT)
+ADMIN_HTML = os.path.join(ROOT, "static", "admin.html")
+
+
+def _read(text: str):
+ assert text.startswith("\ufeff"), "нет BOM — Excel сломает кириллицу"
+ return list(csv.reader(io.StringIO(text[1:]), delimiter=";"))
+
+
+@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.add_account_entry("joe@x", 1000.0, "взнос", "boss@x")
+ db.create_user("ex@x", auth.hash_password("Passw0rd!ok"))
+ db.admin_verify_user("ex@x")
+ db.add_account_entry("ex@x", 1000.0, "взнос", "boss@x")
+ db.record_llm_usage("ex@x", "t1", "agent", "deepseek", "m", 1, 0, 1, 0,
+ cost_rub=0, price_rub=1500)
+ db.create_user("old@x", auth.hash_password("Passw0rd!ok"))
+ db.admin_verify_user("old@x")
+ db.soft_delete_user("old@x")
+ with db._conn() as conn:
+ conn.execute("INSERT INTO payments (ts, username, product, amount_rub, "
+ "yk_payment_id, status, updated_at) VALUES (?,?,?,?,?,?,?)",
+ (1700000000, "joe@x", "agent-month", "990.00", "yk-1", "succeeded", 1700000000))
+ db.log_action("joe@x", "chat", "POST", "/api/chat", "=HYPERLINK(\"x\")", "1.2.3.4", 200)
+ 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_users_csv_has_sum_and_headers(env):
+ db, client, h, auth = env
+ r = client.get("/api/admin/export/users.csv", headers=h)
+ assert r.status_code == 200
+ assert r.headers["content-type"].startswith("text/csv")
+ rows = _read(r.text)
+ assert rows[0][:3] == ["Email", "Роль", "Статус"]
+ joe = next(row for row in rows[1:] if row[0] == "joe@x")
+ assert joe[2] == "active"
+ assert joe[-1] == "1000,00"
+
+
+def test_users_csv_respects_search_and_status(env):
+ db, client, h, auth = env
+ rows = _read(client.get("/api/admin/export/users.csv?q=joe", headers=h).text)
+ assert [r[0] for r in rows[1:]] == ["joe@x"]
+ rows = _read(client.get("/api/admin/export/users.csv?status=blocked", headers=h).text)
+ assert rows[1:] == []
+
+
+def test_users_csv_finds_deleted_and_marks_exhausted(env):
+ db, client, h, auth = env
+ deleted = _read(client.get("/api/admin/export/users.csv?q=old@x&deleted=1", headers=h).text)
+ assert any(r[0] == "old@x" and r[2] == "deleted" for r in deleted[1:])
+ with db._conn() as conn:
+ archived = conn.execute("SELECT email FROM users WHERE deleted_email='old@x'").fetchone()[0]
+ raw = _read(client.get("/api/admin/export/users.csv?q=" + quote(archived) + "&deleted=1",
+ headers=h).text)
+ assert any(r[0] == "old@x" for r in raw[1:]), "поиск по архивному raw_email не работает"
+ exhausted = _read(client.get("/api/admin/export/users.csv?status=exhausted", headers=h).text)
+ row = next(r for r in exhausted[1:] if r[0] == "ex@x")
+ assert row[-1] == "-500,00"
+
+
+def test_payments_and_audit_csv(env):
+ db, client, h, auth = env
+ pay = _read(client.get("/api/admin/export/payments.csv?days=3650", headers=h).text)
+ assert pay[0][:3] == ["Время (UTC+10)", "Пользователь", "Тариф"]
+ assert any(row[2] == "agent-month" and row[3] == "990,00" for row in pay[1:])
+ assert pay[1][0] == time.strftime("%Y-%m-%d %H:%M", time.gmtime(1700000000 + 10 * 3600))
+
+ audit = _read(client.get("/api/admin/export/audit.csv?limit=1000", headers=h).text)
+ assert audit[0][:3] == ["Время (UTC+10)", "Пользователь", "Действие"]
+ cell = next(row for row in audit[1:] if row[2] == "chat")
+ assert cell[5].startswith("'="), "формула не обезврежена"
+ assert cell[7] == "200", "код ответа потерян"
+
+
+def test_audit_limit_marks_truncation(env):
+ db, client, h, auth = env
+ db.log_action("joe@x", "login", "POST", "/api/login", "", "1.2.3.4", 200)
+ rows = _read(client.get("/api/admin/export/audit.csv?limit=1", headers=h).text)
+ assert rows[-1][0] == "выгружены не все — сузьте фильтр"
+
+
+def test_users_csv_survives_accounts_failure(env, monkeypatch):
+ db, client, h, auth = env
+ monkeypatch.setattr(db, "account_balances_all",
+ lambda: (_ for _ in ()).throw(RuntimeError("down")))
+ r = client.get("/api/admin/export/users.csv", headers=h)
+ assert r.status_code == 200
+ assert "балансы не прочитаны" in r.text
+ assert client.get("/api/admin/export/users.csv?status=exhausted",
+ headers=h).status_code == 503
+
+
+def test_export_is_admin_only(env):
+ db, client, h, auth = env
+ stranger = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")}
+ for path in ("/api/admin/export/users.csv", "/api/admin/export/payments.csv",
+ "/api/admin/export/audit.csv"):
+ assert client.get(path, headers=stranger).status_code == 403
+
+
+def test_ui_has_csv_buttons():
+ html = open(ADMIN_HTML, encoding="utf-8").read()
+ for path in ("/api/admin/export/users.csv", "/api/admin/export/payments.csv",
+ "/api/admin/export/audit.csv"):
+ assert path in html
+ assert "downloadCsv" in html and "downloadUsersCsv" in html and "downloadAuditCsv" in html