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`
${[7, 30, 90].map((d) => html` +
+ ${accounts ? html`<${Table} columns=${[ + {key: 'email', label: 'Клиент'}, + {key: 'balance_rub', label: 'Остаток', num: true, render: (r) => rub(r.balance_rub)}, + {key: 'deposited_rub', label: 'Внесено', num: true, render: (r) => rub(r.deposited_rub)}, + {key: 'charged_rub', label: 'Списано', num: true, render: (r) => rub(r.charged_rub)}, + {key: 'status', label: 'Статус', render: (r) => html`${r.status}`}, + ]} rows=${accounts.items.map((r) => ({...r, key: r.email}))} empty="Счетов нет" />` + : html`

Счета не прочитаны.

`} `; } diff --git a/static/admin2/styles.css b/static/admin2/styles.css index 19c20bc..9929e07 100644 --- a/static/admin2/styles.css +++ b/static/admin2/styles.css @@ -77,3 +77,5 @@ tr.clickable{cursor:pointer} tr.clickable:hover td{background:#f3f6ff} .s-succeeded{background:#e7f6ec;color:#067647}.s-pending{background:#fff4e5;color:#b54708} .s-refunded{background:#f2f4f7;color:#667085}.s-canceled{background:#fde8e7;color:#b42318} + +.s-low{background:#fff4e5;color:#b54708}.s-ok{background:#e7f6ec;color:#067647} diff --git a/tests/test_accounts_admin.py b/tests/test_accounts_admin.py new file mode 100644 index 0000000..45e934a --- /dev/null +++ b/tests/test_accounts_admin.py @@ -0,0 +1,60 @@ +"""P3.5: счета v2 — итог, статусы, CSV сходится.""" +import importlib +import os +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + + +@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") + for email, price in (("ok@x", 1), ("low@x", 9.5), ("zero@x", 1500)): + db.create_user(email, auth.hash_password("Passw0rd!ok")) + db.admin_verify_user(email) + db.add_account_entry(email, 10.0, "взнос", "boss@x", ts=0) + with db._conn() as c: + c.execute("INSERT INTO llm_usage (ts, username, tab_id, path, provider, model, " + "input_tokens, cache_tokens, output_tokens, cost_usd, cost_rub, price_rub) " + "VALUES (1,?,'t','agent','deepseek','m',1,0,1,0,0,?)", (email, price)) + from fastapi.testclient import TestClient + client = TestClient(main.app) + h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")} + return client, h, auth + + +def test_accounts_total_status_and_csv(env): + client, h, auth = env + d = client.get("/api/admin/v2/accounts", headers=h).json() + assert d["total"] == 3 + assert d["total_kop"] == (900 + 50 + -149000) + assert client.get("/api/admin/v2/accounts?status=zero", headers=h).json()["total"] == 0 + assert client.get("/api/admin/v2/accounts?status=exhausted", headers=h).json()["total"] == 1 + assert client.get("/api/admin/v2/accounts?status=low", headers=h).json()["total"] == 1 + csv = client.get("/api/admin/v2/accounts.csv", headers=h) + assert csv.status_code == 200 + lines = [x for x in csv.text.splitlines() if x] + assert len(lines) == 4 # header + 3 + assert "zero@x" in csv.text and "-1490.00" in csv.text + + +def test_accounts_admin_only(env): + client, h, auth = env + user = {"Authorization": "Bearer " + auth._make_token("ok@x", "user")} + assert client.get("/api/admin/v2/accounts", headers=user).status_code == 403 + assert client.get("/api/admin/v2/accounts.csv", headers=user).status_code == 403 diff --git a/tests/test_admin_v2_money.py b/tests/test_admin_v2_money.py index e7776ae..77ac0cf 100644 --- a/tests/test_admin_v2_money.py +++ b/tests/test_admin_v2_money.py @@ -38,6 +38,18 @@ class Handler(http.server.SimpleHTTPRequestHandler): if u.path == "/api/admin/v2/money": Handler.calls.append(u.query) return self._json({**MONEY, "period_days": int(parse_qs(u.query).get("days", ["30"])[0])}) + if u.path == "/api/admin/v2/accounts": + return self._json({"items": [ + {"email": "anna@x", "balance_rub": 100.0, "deposited_rub": 200.0, + "charged_rub": 100.0, "status": "ok"}, + {"email": "bob@x", "balance_rub": 0.0, "deposited_rub": 100.0, + "charged_rub": 100.0, "status": "exhausted"}], + "total": 2, "total_kop": 10000, "total_rub": 100.0}) + if u.path == "/api/admin/v2/accounts.csv": + body = "email;balance_rub\nanna@x;100.00\n".encode() + self.send_response(200); self.send_header("Content-Type", "text/csv") + self.send_header("Content-Length", str(len(body))); self.end_headers() + self.wfile.write(body); return if u.path == "/api/admin/v2/payments": q = parse_qs(u.query) items = PAYMENTS @@ -112,10 +124,23 @@ def test_payments_table_and_filter(browser, site): page = browser.new_page() page.add_init_script("localStorage.setItem('token','t')") page.goto(site + "/admin/v2/money") - page.wait_for_selector("table tbody tr") - assert page.locator("table tbody tr").count() == 2 - assert "yk1" in page.locator("table").inner_text() - page.fill("input[type=search]", "bob") - page.wait_for_function("document.querySelectorAll('table tbody tr').length === 1") - assert "bob@x" in page.locator("table").inner_text() + page.wait_for_selector(".payments table tbody tr") + assert page.locator(".payments table tbody tr").count() == 2 + assert "yk1" in page.locator(".payments table").inner_text() + page.fill(".payments input[type=search]", "bob") + page.wait_for_function("document.querySelectorAll('.payments table tbody tr').length === 1") + assert page.locator(".payments table tbody tr").count() == 1 + assert "bob@x" in page.locator(".payments table").inner_text() + page.close() + + +def test_accounts_table_and_csv(browser, site): + page = browser.new_page() + page.add_init_script("localStorage.setItem('token','t')") + page.goto(site + "/admin/v2/money") + page.wait_for_selector(".accounts table") + assert "anna@x" in page.locator(".accounts table").inner_text() + with page.expect_download() as dl: + page.locator("button", has_text="CSV").click() + assert dl.value.suggested_filename == "accounts.csv" page.close()