feat(админка): экран денег с графиками
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
"""P3.2: экран денег — период, карточки, SVG, пустое состояние."""
|
||||
import http.server
|
||||
import json
|
||||
import socketserver
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT)); sys.path.insert(0, str(ROOT / "tests"))
|
||||
pytest.importorskip("playwright.sync_api", reason="playwright не установлен")
|
||||
from test_admin_design_ui import browser # noqa: E402,F401
|
||||
|
||||
MONEY = {"period_days": 30, "revenue_rub": 1000, "refunded_rub": 0, "cost_rub": 250,
|
||||
"flow_rub": 750, "charged_rub": 800, "accounts_total_rub": 2000,
|
||||
"accounts_count": 2, "unpriced": 0}
|
||||
MONTHS = [{"month": "2026-09", "revenue_rub": 500, "cost_rub": 100},
|
||||
{"month": "2026-10", "revenue_rub": 500, "cost_rub": 150}]
|
||||
|
||||
|
||||
class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
calls = []
|
||||
|
||||
def __init__(self, *a, **kw):
|
||||
super().__init__(*a, directory=str(ROOT), **kw)
|
||||
|
||||
def do_GET(self):
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
u = urlparse(self.path)
|
||||
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/finance":
|
||||
return self._json({"months": MONTHS, "days": int(parse_qs(u.query).get("days", ["30"])[0])})
|
||||
if self.path == "/admin/v2" or self.path.startswith("/admin/v2/"):
|
||||
data = (ROOT / "static/admin2/index.html").read_bytes()
|
||||
self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data))); self.end_headers()
|
||||
self.wfile.write(data); return
|
||||
return super().do_GET()
|
||||
|
||||
def _json(self, obj):
|
||||
data = json.dumps(obj).encode()
|
||||
self.send_response(200); self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data))); self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def log_message(self, *a):
|
||||
return
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
Handler.calls = []
|
||||
class Quiet(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
srv = Quiet(("127.0.0.1", 0), Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{srv.server_address[1]}"
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def test_money_cards_charts_and_period(browser, site):
|
||||
Handler.calls = []
|
||||
page = browser.new_page()
|
||||
errors = []
|
||||
page.on("pageerror", lambda e: errors.append(str(e)))
|
||||
page.add_init_script("localStorage.setItem('token','t')")
|
||||
page.goto(site + "/admin/v2/money")
|
||||
page.wait_for_selector(".grid .card")
|
||||
assert page.locator(".grid .card").count() == 4
|
||||
assert page.locator(".chart").count() == 2
|
||||
assert "1\u00a0000" in page.locator(".grid").inner_text()
|
||||
page.locator(".toolbar button", has_text="90 дней").click()
|
||||
page.wait_for_timeout(500)
|
||||
assert any("days=90" in c for c in Handler.calls)
|
||||
assert errors == []
|
||||
page.close()
|
||||
|
||||
|
||||
def test_money_empty_months(browser, site):
|
||||
# страница с пустым рядом месяцев не должна падать и не рисовать пустые SVG
|
||||
page = browser.new_page()
|
||||
page.add_init_script("localStorage.setItem('token','t')")
|
||||
page.route("**/api/admin/v2/finance*",
|
||||
lambda route: route.fulfill(status=200, body=json.dumps({"months": []}),
|
||||
headers={"Content-Type": "application/json"}))
|
||||
page.goto(site + "/admin/v2/money")
|
||||
page.wait_for_selector(".note")
|
||||
assert page.locator(".chart").count() == 0
|
||||
page.close()
|
||||
@@ -0,0 +1,40 @@
|
||||
"""P3.2: /finance — права, форма месяцев, кламп периода."""
|
||||
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")
|
||||
db.create_user("joe@x", auth.hash_password("Passw0rd!ok"))
|
||||
db.admin_verify_user("joe@x")
|
||||
from fastapi.testclient import TestClient
|
||||
client = TestClient(main.app)
|
||||
h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")}
|
||||
return client, h, auth
|
||||
|
||||
|
||||
def test_finance_admin_only_and_clamp(env):
|
||||
client, h, auth = env
|
||||
assert client.get("/api/admin/v2/finance?days=9999", headers=h).json()["days"] == 366
|
||||
user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")}
|
||||
assert client.get("/api/admin/v2/finance", headers=user).status_code == 403
|
||||
assert client.get("/api/admin/v2/finance", headers=h).status_code == 200
|
||||
Reference in New Issue
Block a user