feat(админка): экран денег с графиками
This commit is contained in:
@@ -285,6 +285,15 @@ async def undo_action(action_id: int, request: Request):
|
||||
raise HTTPException(400, str(e)) from e
|
||||
|
||||
|
||||
@router.get("/finance")
|
||||
async def finance_series(request: Request, days: int = 90):
|
||||
require_admin(request)
|
||||
days = max(1, min(int(days), 366))
|
||||
since = time.time() - days * 86400
|
||||
data = await asyncio.to_thread(db.finance_by_month, since)
|
||||
return {"days": days, "months": data["months"]}
|
||||
|
||||
|
||||
@router.get("/money")
|
||||
async def money_summary(request: Request, days: int = 30):
|
||||
require_admin(request)
|
||||
|
||||
@@ -250,6 +250,13 @@
|
||||
- Тесты: golden 4 + money 2; account_balance 54.
|
||||
- `finance_by_month(round_kop=False)` для сводки: 0,125+0,125 = 25 коп., а не 26 от помесячного округления. Внешняя сверка с платёжкой — ждёт отчёт.
|
||||
|
||||
## 4.31. P3.2 — экран «Деньги»
|
||||
|
||||
- `pages/money.js`, `ui/chart.js`; период 7/30/90, 4 карточки, SVG-бары/линия, подписи месяцев, «период короче месяца».
|
||||
- `/api/admin/v2/finance`: 403 не-админу, `days` 1..366, форма месяцев.
|
||||
- Один месяц — точка вместо пустой линии; ошибка и загрузка взаимоисключающие.
|
||||
- Тесты: UI — 2, API — 1.
|
||||
|
||||
## 5. Следующий шаг
|
||||
|
||||
P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания).
|
||||
|
||||
@@ -3,6 +3,7 @@ import htm from '/static/admin2/vendor/htm.module.js';
|
||||
import { SECTIONS, sectionFromPath, hrefFor } from '/static/admin2/router.js';
|
||||
import { DayPage } from '/static/admin2/pages/day.js';
|
||||
import { CustomersPage } from '/static/admin2/pages/customers.js';
|
||||
import { MoneyPage } from '/static/admin2/pages/money.js';
|
||||
|
||||
const html = htm.bind(h);
|
||||
const TITLES = {
|
||||
@@ -27,7 +28,8 @@ const App = () => html`
|
||||
<main class="main">
|
||||
<header class="top"><div><h1>${title}</h1><p>${subtitle}</p></div></header>
|
||||
${section === 'today' ? html`<${DayPage} />`
|
||||
: section === 'customers' ? html`<${CustomersPage} />` : html`
|
||||
: section === 'customers' ? html`<${CustomersPage} />`
|
||||
: section === 'money' ? html`<${MoneyPage} />` : html`
|
||||
<section class="card" aria-labelledby="placeholder">
|
||||
<h2 id="placeholder">Раздел готовится</h2>
|
||||
<p>Данные и действия подключит следующий этап.</p>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { h } from '/static/admin2/vendor/preact.module.js';
|
||||
import { useEffect, useState } from '/static/admin2/vendor/hooks.module.js';
|
||||
import htm from '/static/admin2/vendor/htm.module.js';
|
||||
import { api } from '/static/admin2/api.js';
|
||||
import { Card } from '/static/admin2/ui/card.js';
|
||||
import { Bars, Line } from '/static/admin2/ui/chart.js';
|
||||
|
||||
const html = htm.bind(h);
|
||||
const rub = (v) => v == null ? '—' : Number(v).toLocaleString('ru-RU',
|
||||
{maximumFractionDigits: 2}) + ' ₽';
|
||||
|
||||
export function MoneyPage() {
|
||||
const [days, setDays] = useState(30);
|
||||
const [data, setData] = useState(null);
|
||||
const [series, setSeries] = useState([]);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setError('');
|
||||
Promise.all([api('/api/admin/v2/money?days=' + days),
|
||||
api('/api/admin/v2/finance?days=' + days)])
|
||||
.then(([m, f]) => { if (alive) { setData(m); setSeries(f.months || []); } })
|
||||
.catch((e) => { if (alive) setError(e.message || 'Не удалось загрузить'); });
|
||||
return () => { alive = false; };
|
||||
}, [days]);
|
||||
|
||||
return html`
|
||||
<div class="toolbar">
|
||||
${[7, 30, 90].map((d) => html`<button type="button" key=${d}
|
||||
class=${d === days ? 'active' : ''} onClick=${() => setDays(d)}>${d} дней</button>`)}
|
||||
</div>
|
||||
${error ? html`<div class="card error" role="alert">${error}</div>`
|
||||
: !data ? html`<div class="card">Загрузка…</div>` : html`
|
||||
<div class="grid">
|
||||
<${Card} title="Поступления" value=${rub(data.revenue_rub)}
|
||||
note=${'возвраты ' + rub(data.refunded_rub)} />
|
||||
<${Card} title="Себестоимость" value=${rub(data.cost_rub)}
|
||||
note=${'цена клиентам ' + rub(data.charged_rub)} />
|
||||
<${Card} title="Поток" value=${rub(data.flow_rub)}
|
||||
note="поступления − себестоимость" />
|
||||
<${Card} title="На счетах" value=${rub(data.accounts_total_rub)}
|
||||
note=${'клиентов ' + data.accounts_count + ' · без цены ' + (data.unpriced ?? '—')} />
|
||||
</div>
|
||||
${series.length ? html`<div class="charts">
|
||||
<${Bars} values=${series.map((m) => m.revenue_rub)}
|
||||
labels=${series.map((m) => m.month)} label="Поступления по месяцам" />
|
||||
<${Line} values=${series.map((m) => m.cost_rub || 0)} label="Себестоимость по месяцам" />
|
||||
</div>${days < 31 ? html`<p class="note">Период короче месяца — столбцы неполные.</p>` : null}`
|
||||
: html`<section class="card"><p class="note">За период нет закрытых месяцев.</p></section>`}
|
||||
`}`;
|
||||
}
|
||||
@@ -67,3 +67,10 @@ tr.clickable{cursor:pointer} tr.clickable:hover td{background:#f3f6ff}
|
||||
.toast{display:flex;gap:8px;align-items:center;background:#ecfdf3;border:1px solid #abefc6;color:#067647;padding:8px 10px;border-radius:8px;margin:8px 0}
|
||||
.toast button{font:inherit;border:0;background:transparent;color:#067647;text-decoration:underline;cursor:pointer}
|
||||
.toast-close{margin-left:auto;text-decoration:none;font-size:18px}
|
||||
|
||||
.toolbar button.active{background:#2457d6;color:#fff;border-color:#2457d6}
|
||||
.charts{display:grid;grid-template-columns:1fr 1fr;gap:12px}
|
||||
.chart{margin:0;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:10px}
|
||||
.chart figcaption{font-size:12px;color:var(--muted);margin-bottom:6px}
|
||||
.chart svg{width:100%;height:auto;display:block}
|
||||
@media(max-width:700px){.charts{grid-template-columns:1fr}}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { h } from '/static/admin2/vendor/preact.module.js';
|
||||
import htm from '/static/admin2/vendor/htm.module.js';
|
||||
const html = htm.bind(h);
|
||||
|
||||
// SVG-атрибуты, не style: CSP v2 запрещает inline-стили.
|
||||
export const Bars = ({ values, label, labels = [] }) => {
|
||||
const max = Math.max(1, ...values.map((v) => Math.max(0, v)));
|
||||
const w = 12, gap = 6, h0 = 90;
|
||||
const total = Math.max(1, values.length) * (w + gap);
|
||||
return html`<figure class="chart">
|
||||
<figcaption>${label}</figcaption>
|
||||
<svg viewBox=${`0 0 ${total} ${h0 + 18}`} role="img" aria-label=${label}>
|
||||
${values.map((v, i) => html`<rect key=${i} x=${i * (w + gap)} y=${h0 - Math.max(0, v) / max * h0}
|
||||
width=${w} height=${Math.max(1, v) / max * h0} rx="2" fill="#2457d6"></rect>`)}
|
||||
${labels.map((m, i) => html`<text key=${'l' + i} x=${i * (w + gap)} y=${h0 + 14}
|
||||
font-size="9" fill="#667085">${String(m).slice(5)}</text>`)}
|
||||
</svg>
|
||||
</figure>`;
|
||||
};
|
||||
|
||||
export const Line = ({ values, label }) => {
|
||||
const max = Math.max(1, ...values.map((v) => Math.max(0, v)));
|
||||
const pts = values.map((v, i) => `${i * 20},${90 - Math.max(0, v) / max * 80}`).join(' ');
|
||||
return html`<figure class="chart">
|
||||
<figcaption>${label}</figcaption>
|
||||
<svg viewBox=${`0 0 ${Math.max(1, (values.length - 1) * 20)} 94`} role="img" aria-label=${label}>
|
||||
${values.length > 1
|
||||
? html`<polyline points=${pts} fill="none" stroke="#067647" stroke-width="3"></polyline>`
|
||||
: html`<circle cx="0" cy=${90 - Math.max(0, values[0] || 0) / max * 80} r="3" fill="#067647"></circle>`}
|
||||
</svg>
|
||||
</figure>`;
|
||||
};
|
||||
@@ -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