"""Клиенты v2: один серверный список вместо N+1 на строку.""" from __future__ import annotations import time STATUSES = {"active", "blocked", "deleted", "read_only", "exhausted", "trial", "unverified"} def _status(u: dict, account: dict | None) -> str: if u.get("deleted_at"): return "deleted" if u.get("blocked"): return "blocked" if u.get("read_only"): return "read_only" if account and account.get("exhausted"): return "exhausted" if u.get("trial"): return "trial" return "active" if u.get("verified") else "unverified" def list_customers(query: str = "", status: str = "", page: int = 1, per_page: int = 50, sort: str = "last_seen") -> dict: import db import balance import billing query = (query or "").strip().lower() status = (status or "").strip().lower() if status and status not in STATUSES: raise ValueError("неизвестный статус") page = max(1, int(page)) per_page = max(1, min(int(per_page), 200)) if sort not in ("last_seen", "email", "created"): raise ValueError("неверная сортировка") users = db.list_users(include_deleted=(status == "deleted")) seen = db.last_seen_all() accounts_failed = False try: accounts = db.account_balances_all() except Exception: # noqa: BLE001 — без балансов список людей остаётся полезным accounts = {} accounts_failed = True if status == "exhausted" and accounts_failed: raise LookupError("счета не прочитаны") import agent_provider owners = agent_provider._owner_set() since = time.time() - 86400 spent = db.spend_by_user_since(since) 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"]) row = {"email": u.get("deleted_email") or email, "raw_email": email, "role": u.get("role"), "status": _status(u, composed), "verified": bool(u.get("verified")), "blocked": bool(u.get("blocked")), "trial": bool(u.get("trial")), "read_only": bool(u.get("read_only")), "telegram": u.get("telegram"), "tg_username": u.get("tg_username"), "deleted_email": u.get("deleted_email"), "last_seen": seen.get(email), "created_at": u.get("created_at"), "agent_provider": u.get("agent_provider"), "agent_access": bool(u.get("agent_access")), "is_owner": email.lower() in owners, "balance_rub": composed["balance_rub"] if composed else None, "spent_rub_24h": round((spent.get(email) or {}).get("rub", 0.0), 2)} out.append(row) if query: fields = ("email", "raw_email", "telegram", "tg_username", "deleted_email") out = [r for r in out if query in " ".join(str(r.get(k) or "") for k in fields).lower()] if status: out = [r for r in out if r["status"] == status] if sort == "email": out.sort(key=lambda r: (r.get("email") or "").lower()) elif sort == "created": out.sort(key=lambda r: r.get("created_at") or 0, reverse=True) else: out.sort(key=lambda r: r.get("last_seen") or 0, reverse=True) total = len(out) start = (page - 1) * per_page return {"items": out[start:start + per_page], "total": total, "page": page, "per_page": per_page}