feat(админка): CSV клиентов, платежей и журнала
This commit is contained in:
@@ -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."""
|
||||
|
||||
Reference in New Issue
Block a user