diff --git a/accounts_admin.py b/accounts_admin.py new file mode 100644 index 0000000..31366d2 --- /dev/null +++ b/accounts_admin.py @@ -0,0 +1,40 @@ +"""Счета клиентов v2: остатки, «исчерпан/мало», выгрузка.""" +from __future__ import annotations + + +def listing(query: str = "", status: str = "", page: int = 1, per_page: int = 50) -> dict: + import db + import balance + import billing + q = (query or "").strip().lower() + st = (status or "").strip().lower() + page = max(1, int(page)); per_page = max(1, min(int(per_page), 1000)) + rows = [] + for email, a in db.account_balances_all().items(): + if billing._is_our_own(email): + continue + stt = balance.compose(a["deposited_kop"], a["charged"], a["first_ts"], a["unpriced"]) + if not stt: + continue + if stt["exhausted"]: + s = "exhausted" + elif stt["low"]: + s = "low" + else: + s = "ok" + if q and q not in email.lower(): + continue + if st and s != st: + continue + rows.append({"email": email, "balance_kop": stt["balance_kop"], + "balance_rub": stt["balance_rub"], + "deposited_rub": stt["deposited_rub"], + "charged_rub": stt["charged_rub"], "since": stt["since"], + "status": s, "unpriced": stt["unpriced"]}) + rows.sort(key=lambda r: r["balance_kop"]) + total = len(rows) + total_kop = sum(r["balance_kop"] for r in rows) + start = (page - 1) * per_page + return {"items": rows[start:start + per_page], "total": total, + "total_kop": total_kop, "total_rub": total_kop / 100, + "page": page, "per_page": per_page} diff --git a/admin_api.py b/admin_api.py index 11cc6b4..4306fba 100644 --- a/admin_api.py +++ b/admin_api.py @@ -7,6 +7,7 @@ import time from fastapi import APIRouter, HTTPException, Request import admin_actions +import accounts_admin import attention import customers import db @@ -286,6 +287,37 @@ async def undo_action(action_id: int, request: Request): raise HTTPException(400, str(e)) from e +@router.get("/accounts") +async def accounts_list(request: Request, q: str = "", status: str = "", + page: int = 1, per_page: int = 50): + require_admin(request) + return await asyncio.to_thread(accounts_admin.listing, q, status, page, per_page) + + +@router.get("/accounts.csv") +async def accounts_csv(request: Request, q: str = "", status: str = ""): + require_admin(request) + import csv + import io + from fastapi.responses import Response + rows, page = [], 1 + while True: + chunk = await asyncio.to_thread(accounts_admin.listing, q, status, page, 1000) + rows.extend(chunk["items"]) + if len(chunk["items"]) < 1000: + break + page += 1 + data = {"items": rows} + buf = io.StringIO() + w = csv.writer(buf, delimiter=";") + w.writerow(["email", "balance_rub", "deposited_rub", "charged_rub", "status", "unpriced"]) + for r in data["items"]: + w.writerow([r["email"], f"{r['balance_rub']:.2f}", f"{r['deposited_rub']:.2f}", + f"{r['charged_rub']:.4f}", r["status"], r["unpriced"]]) + return Response(buf.getvalue(), media_type="text/csv; charset=utf-8", + headers={"Content-Disposition": 'attachment; filename="accounts.csv"'}) + + @router.get("/payments") async def payments_list(request: Request, days: int = 30, q: str = "", status: str = "", page: int = 1, per_page: int = 50): diff --git a/docs/ADMIN_V2_BASELINE.md b/docs/ADMIN_V2_BASELINE.md index 4d04062..09d6afd 100644 --- a/docs/ADMIN_V2_BASELINE.md +++ b/docs/ADMIN_V2_BASELINE.md @@ -264,6 +264,13 @@ - Цвета статусов; период проверен платежом старше 30 дней. - Тесты: API — 2, UI — 3. +## 4.33. P3.5 — счета клиентов + +- `/api/admin/v2/accounts`: остатки, `total_kop`, low/exhausted/ok, поиск. +- `/accounts.csv`: все страницы, `;`, баланс/внесено/списано/статус/без цены. +- UI: таблица в «Деньгах», фильтр, CSV через fetch с токеном. +- Тесты: API — 2, UI — 4. + ## 5. Следующий шаг P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания). diff --git a/static/admin2/pages/money.js b/static/admin2/pages/money.js index e668b5e..02e4def 100644 --- a/static/admin2/pages/money.js +++ b/static/admin2/pages/money.js @@ -21,6 +21,9 @@ export function MoneyPage() { const [ppage, setPpage] = useState(1); const [perror, setPerror] = useState(''); const reqSeq = useRef(0); + const [accounts, setAccounts] = useState(null); + const [aq, setAq] = useState(''); + const [astatus, setAstatus] = useState(''); useEffect(() => { let alive = true; @@ -48,6 +51,30 @@ export function MoneyPage() { return () => { alive = false; clearTimeout(timer); }; }, [days, pq, pstatus, ppage]); + useEffect(() => { + let alive = true; + const p = new URLSearchParams({page: '1', per_page: '50'}); + if (aq.trim()) p.set('q', aq.trim()); + if (astatus) p.set('status', astatus); + api('/api/admin/v2/accounts?' + p).then((d) => { + if (alive) setAccounts(d); + }).catch(() => { if (alive) setAccounts(null); }); + return () => { alive = false; }; + }, [aq, astatus]); + + const downloadCsv = async () => { + const p = new URLSearchParams(); + if (aq.trim()) p.set('q', aq.trim()); + if (astatus) p.set('status', astatus); + const r = await fetch('/api/admin/v2/accounts.csv?' + p, + {headers: {Authorization: 'Bearer ' + (localStorage.getItem('token') || '')}}); + if (!r.ok) return; + const url = URL.createObjectURL(await r.blob()); + const a = document.createElement('a'); + a.href = url; a.download = 'accounts.csv'; a.click(); + URL.revokeObjectURL(url); + }; + return html`