feat(админка): копейки и money API

This commit is contained in:
anor
2026-11-06 22:29:09 +10:00
parent 99b62fb5fb
commit 7ad2368719
6 changed files with 151 additions and 17 deletions
+6
View File
@@ -285,6 +285,12 @@ async def undo_action(action_id: int, request: Request):
raise HTTPException(400, str(e)) from e
@router.get("/money")
async def money_summary(request: Request, days: int = 30):
require_admin(request)
return await asyncio.to_thread(money.summary, None, days)
@router.get("/dashboard")
async def dashboard(request: Request):
user = require_admin(request)
+20 -11
View File
@@ -24,6 +24,7 @@ from __future__ import annotations
import logging
import math
from decimal import Decimal, ROUND_HALF_UP
_log = logging.getLogger("smeta_web")
@@ -39,19 +40,27 @@ def _is_our_own(username: str) -> bool:
def compose(deposited_kop: int, charged_rub: float, first_ts: float,
unpriced: int) -> dict | None:
"""Одно вычисление счёта на оба пути (человек и список админки): два расчёта разошлись
бы при первой правке. Копейки округляем ДО сравнения: 0,9 − (0,2 + 0,7) во float даёт
+1e-16, и счёт считался бы живым; «+ 0.0» убирает минус у нуля («−0,00 ₽»).
бы при первой правке. Баланс считается в копейках Decimal и округляется ОДИН раз
(ROUND_HALF_UP), а не по каждой цене: 1,00 − (0,125 + 0,25) = 62,5 → 63.
None — взносы отменены целиком и с них ничего не потрачено: это был взнос не тому
человеку, и запирать его на нуле нельзя (рецензент fable 01.10.2026)."""
if deposited_kop == 0 and round(charged_rub, 2) == 0:
charged = Decimal(str(charged_rub))
deposited = (Decimal(int(deposited_kop)) / 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
# Баланс — разница в копейках, округлённая ОДИН раз в конце. Округлять каждую цену
# до копейки нельзя: 1,00 − (0,125 + 0,25) дало бы 62, а не 63.
bal_kop = int((Decimal(int(deposited_kop)) - charged * 100).quantize(
Decimal("1"), rounding=ROUND_HALF_UP))
# Взнос отменён целиком и списание округлилось к нулю — это не счёт, а отсутствие счёта.
if deposited_kop == 0 and bal_kop == 0:
return None
deposited = deposited_kop / 100
bal = round(deposited - charged_rub, 2) + 0.0
return {"balance_rub": bal, "deposited_rub": round(deposited, 2),
"charged_rub": round(charged_rub, 2), "since": first_ts,
"exhausted": bal <= 0, "unpriced": int(unpriced),
"low": deposited > 0 and 0 < bal < deposited * 0.1}
bal = float(Decimal(bal_kop) / 100)
return {"balance_kop": bal_kop, "balance_rub": bal,
"deposited_rub": float(deposited),
"charged_rub": float(charged),
"since": first_ts,
"exhausted": bal_kop <= 0, "unpriced": int(unpriced),
"low": deposited_kop > 0 and 0 < bal_kop * 10 < deposited_kop}
def state(username: str) -> dict | None:
@@ -74,8 +83,8 @@ def exhausted(username: str) -> bool:
def person_view(st: dict) -> dict:
"""Человеку — только деньги: без счётчика ответов без цены (это наша кухня)."""
return {k: st[k] for k in ("balance_rub", "deposited_rub", "charged_rub", "since",
"exhausted", "low")}
return {k: st[k] for k in ("balance_kop", "balance_rub", "deposited_rub", "charged_rub",
"since", "exhausted", "low")}
def person_entries(username: str) -> list[dict]:
+7
View File
@@ -243,6 +243,13 @@
- UI: «Внести» в карточке с prompt; тост.
- Тесты: `tests/test_topup_v2_api.py` — 4; UI — 9.
## 4.29. P3.1a/b — копейки
- `balance.compose`: Decimal, `ROUND_HALF_UP`, `balance_kop`; 1,00−0,71=29; 1,00−0,375=63; dust-списание не создаёт счёт; `low` на целых.
- `money.summary` + `/api/admin/v2/money`: `*_kop`, `flow_kop=revenue_kop−cost_kop`; период 1..366.
- Тесты: golden 4 + money 2; account_balance 54.
- P2: finance_by_month округляет месяц до копейки до сводки — двойное округление; исправить в P3.1b.
## 5. Следующий шаг
P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания).
+24 -6
View File
@@ -7,17 +7,25 @@ from __future__ import annotations
import logging
import time
from decimal import Decimal, ROUND_HALF_UP
logger = logging.getLogger(__name__)
def summary(now: float | None = None) -> dict:
def _kop(value):
if value is None:
return None
return int((Decimal(str(value)) * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def summary(now: float | None = None, days: int = 30) -> dict:
now = time.time() if now is None else now
days = max(1, min(int(days), 366))
from db import finance_by_month, account_balances_all
import balance
import billing
months = finance_by_month(now - 30 * 86400)["months"]
months = finance_by_month(now - days * 86400)["months"]
revenue = round(sum(m["revenue_rub"] for m in months), 2)
refunded = round(sum(m["refunded_rub"] for m in months), 2)
costs = [m["cost_rub"] for m in months if m["cost_rub"] is not None]
@@ -36,8 +44,18 @@ def summary(now: float | None = None) -> dict:
accounts_total = None
unpriced = None
rows = []
return {"period_days": 30, "revenue_rub": revenue, "refunded_rub": refunded,
"cost_rub": cost, "flow_rub": flow, "charged_rub": charged,
"accounts_total_rub": accounts_total, "accounts_count": len(rows),
"unpriced": unpriced, "topups_included": False,
accounts_kop = (sum(int(r.get("balance_kop") or _kop(r.get("balance_rub")) or 0)
for r in rows) if accounts_total is not None else None)
revenue_kop, cost_kop = _kop(revenue), _kop(cost)
flow_kop = (revenue_kop - cost_kop
if revenue_kop is not None and cost_kop is not None else None)
return {"period_days": days,
"revenue_rub": revenue, "revenue_kop": revenue_kop,
"refunded_rub": refunded, "refunded_kop": _kop(refunded),
"cost_rub": cost, "cost_kop": cost_kop,
"flow_rub": flow, "flow_kop": flow_kop,
"charged_rub": charged, "charged_kop": _kop(charged),
"accounts_total_rub": accounts_total, "accounts_total_kop": accounts_kop,
"accounts_count": len(rows), "unpriced": unpriced,
"topups_included": False,
"note": "поток = поступления − себестоимость; остатки на счетах — обязательство"}
+29
View File
@@ -0,0 +1,29 @@
"""P3.1a: копейки и ROUND_HALF_UP — golden из плана."""
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
import balance # noqa: E402
def test_golden_1_ruble_minus_71_kopecks():
st = balance.compose(100, 0.71, 0.0, 0)
assert st["balance_kop"] == 29
assert st["balance_rub"] == 0.29
def test_golden_half_kopeck_rounds_up_not_even():
st = balance.compose(100, 0.125 + 0.25, 0.0, 0)
assert st["balance_kop"] == 63
assert st["balance_rub"] == 0.63
def test_zero_entries_still_none():
assert balance.compose(0, 0.0, 0.0, 0) is None
def test_dust_charge_does_not_create_account_and_low_is_not_truncated():
assert balance.compose(0, 0.0008, 0.0, 0) is None
st = balance.compose(29, 0.27, 0.0, 0)
assert st["balance_kop"] == 2 and st["low"] is True
+65
View File
@@ -0,0 +1,65 @@
"""P3.1b: один период — один итог в копейках; /api/admin/v2/money."""
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")
db.add_account_entry("joe@x", 10.0, "взнос", "boss@x")
import time as _time
now = _time.time()
with db._conn() as c:
c.execute("INSERT INTO payments (ts, username, product, amount_rub, yk_payment_id, "
"status, updated_at) VALUES (?,?,?,?,?,?,?)",
(now, "joe@x", "p", "10.00", "m1", "succeeded", now))
db.record_llm_usage("joe@x", "t", "agent", "deepseek", "m", 1, 0, 1, 0,
cost_rub=2.5, price_rub=0, ts=now)
from fastapi.testclient import TestClient
client = TestClient(main.app)
h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")}
return db, client, h
def test_money_kopecks_and_period(env):
db, client, h = env
r = client.get("/api/admin/v2/money?days=30", headers=h)
assert r.status_code == 200
d = r.json()
assert d["period_days"] == 30
assert d["accounts_total_kop"] == 1000
assert d["revenue_kop"] == 1000
assert d["cost_kop"] == 250
assert d["flow_kop"] == 750
assert isinstance(d["revenue_kop"], int)
assert isinstance(d["flow_kop"], int) or d["flow_kop"] is None
assert d["flow_kop"] == d["revenue_kop"] - d["cost_kop"]
assert client.get("/api/admin/v2/money?days=0", headers=h).json()["period_days"] == 1
assert client.get("/api/admin/v2/money?days=9999", headers=h).json()["period_days"] == 366
def test_money_is_admin_only(env):
db, client, h = env
import auth
user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")}
assert client.get("/api/admin/v2/money", headers=user).status_code == 403