fix(деньги): взносы на счёт входят в поступления, карточка сходится
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+2
-2
@@ -487,8 +487,8 @@ async def finance_series(request: Request, days: int = 90):
|
|||||||
require_admin(request)
|
require_admin(request)
|
||||||
days = max(1, min(int(days), 366))
|
days = max(1, min(int(days), 366))
|
||||||
since = time.time() - days * 86400
|
since = time.time() - days * 86400
|
||||||
data = await asyncio.to_thread(db.finance_by_month, since)
|
months = await asyncio.to_thread(money.finance_months, since)
|
||||||
return {"days": days, "months": data["months"]}
|
return {"days": days, "months": months}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/money")
|
@router.get("/money")
|
||||||
|
|||||||
@@ -1041,6 +1041,27 @@ def list_account_entries(username: str, limit: int = 200) -> list[dict]:
|
|||||||
return [dict(r) for r in rows]
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def topups_by_month(since: float, until: float | None = None) -> dict[str, float]:
|
||||||
|
"""Ручные взносы на счёт по месяцам: пополнения минус сторно, в рублях.
|
||||||
|
|
||||||
|
Это не платежи ЮKassa, но такие же полученные деньги: в «Деньгах» кокпита они
|
||||||
|
складываются с платежами, иначе при предоплате поступления показывали ноль.
|
||||||
|
Месяцы — в поясе Хозяина, как finance_by_month."""
|
||||||
|
tail, args = "", [since]
|
||||||
|
if until is not None:
|
||||||
|
tail, args = " AND ts < ?", [since, until]
|
||||||
|
with _conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
f"SELECT strftime('%Y-%m', ts, 'unixepoch', '{OWNER_TZ_SQL}') AS month, "
|
||||||
|
"COALESCE(SUM(CASE WHEN amount_kop > 0 THEN amount_kop ELSE 0 END),0) AS dep_kop, "
|
||||||
|
"COALESCE(SUM(CASE WHEN amount_kop < 0 THEN -amount_kop ELSE 0 END),0) AS cor_kop "
|
||||||
|
f"FROM account_entries WHERE ts >= ?{tail} GROUP BY month ORDER BY month",
|
||||||
|
args,
|
||||||
|
).fetchall()
|
||||||
|
return {r["month"]: (int(r["dep_kop"] or 0) - int(r["cor_kop"] or 0)) / 100
|
||||||
|
for r in rows}
|
||||||
|
|
||||||
|
|
||||||
def account_summary(username: str) -> dict | None:
|
def account_summary(username: str) -> dict | None:
|
||||||
"""Взносы человека одной строкой: {"entries", "deposited_kop", "first_ts"}; None — взносов
|
"""Взносы человека одной строкой: {"entries", "deposited_kop", "first_ts"}; None — взносов
|
||||||
не было, человек не на счёте."""
|
не было, человек не на счёте."""
|
||||||
|
|||||||
@@ -464,7 +464,7 @@ MAX_MESSAGE_LEN = 10_000
|
|||||||
|
|
||||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||||
APP_VERSION = "2026-11-10d"
|
APP_VERSION = "2026-11-10e"
|
||||||
|
|
||||||
# Audit: path → action name mapping
|
# Audit: path → action name mapping
|
||||||
_AUDIT_MAP = [
|
_AUDIT_MAP = [
|
||||||
|
|||||||
@@ -18,14 +18,39 @@ def _kop(value):
|
|||||||
return int((Decimal(str(value)) * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
return int((Decimal(str(value)) * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
def finance_months(since: float, until: float | None = None,
|
||||||
|
round_kop: bool = False) -> list[dict]:
|
||||||
|
"""Месяцы для кокпита: платежи ЮKassa + ручные взносы на счёт.
|
||||||
|
|
||||||
|
finance_by_month остаётся про платежи (им живёт старый экран), а здесь деньги
|
||||||
|
предоплаты складываются с платежами: при работе «внесу вручную» иначе поступления
|
||||||
|
показывали ноль, хотя человек внёс деньги."""
|
||||||
|
from db import finance_by_month, topups_by_month
|
||||||
|
data = finance_by_month(since, until, round_kop=round_kop)
|
||||||
|
tops = topups_by_month(since, until)
|
||||||
|
months = {m["month"]: dict(m) for m in data["months"]}
|
||||||
|
for month, amount in tops.items():
|
||||||
|
m = months.setdefault(month, {"month": month, "revenue_rub": 0.0,
|
||||||
|
"refunded_rub": 0.0, "payers": 0,
|
||||||
|
"cost_rub": None, "price_rub": None,
|
||||||
|
"requests": 0, "people": 0, "unpriced": 0})
|
||||||
|
value = round(amount, 2) if round_kop else amount
|
||||||
|
m["topups_rub"] = value
|
||||||
|
m["revenue_rub"] = ((m.get("revenue_rub") or 0) + value)
|
||||||
|
for m in months.values():
|
||||||
|
m.setdefault("topups_rub", 0.0)
|
||||||
|
return [months[k] for k in sorted(months)]
|
||||||
|
|
||||||
|
|
||||||
def summary(now: float | None = None, days: int = 30) -> dict:
|
def summary(now: float | None = None, days: int = 30) -> dict:
|
||||||
now = time.time() if now is None else now
|
now = time.time() if now is None else now
|
||||||
days = max(1, min(int(days), 366))
|
days = max(1, min(int(days), 366))
|
||||||
from db import finance_by_month, account_balances_all
|
from db import account_balances_all
|
||||||
import balance
|
import balance
|
||||||
import billing
|
import billing
|
||||||
|
|
||||||
months = finance_by_month(now - days * 86400, round_kop=False)["months"]
|
months = finance_months(now - days * 86400, round_kop=False)
|
||||||
|
topups_raw = sum(m.get("topups_rub") or 0 for m in months)
|
||||||
# Суммы — сырые; копейки округляем ОДИН раз, а не каждый месяц до сводки.
|
# Суммы — сырые; копейки округляем ОДИН раз, а не каждый месяц до сводки.
|
||||||
revenue_raw = sum(m["revenue_rub"] for m in months)
|
revenue_raw = sum(m["revenue_rub"] for m in months)
|
||||||
refunded_raw = sum(m["refunded_rub"] for m in months)
|
refunded_raw = sum(m["refunded_rub"] for m in months)
|
||||||
@@ -63,5 +88,7 @@ def summary(now: float | None = None, days: int = 30) -> dict:
|
|||||||
"charged_rub": charged, "charged_kop": _kop(charged),
|
"charged_rub": charged, "charged_kop": _kop(charged),
|
||||||
"accounts_total_rub": accounts_total, "accounts_total_kop": accounts_kop,
|
"accounts_total_rub": accounts_total, "accounts_total_kop": accounts_kop,
|
||||||
"accounts_count": len(rows), "unpriced": unpriced,
|
"accounts_count": len(rows), "unpriced": unpriced,
|
||||||
"topups_included": False,
|
"topups_rub": round(topups_raw, 2), "topups_kop": _kop(topups_raw),
|
||||||
"note": "поток = поступления − себестоимость; остатки на счетах — обязательство"}
|
"topups_included": True,
|
||||||
|
"note": "поток = поступления − себестоимость; поступления включают взносы; "
|
||||||
|
"остатки на счетах — обязательство"}
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ export function MoneyPage() {
|
|||||||
: !data ? html`<${Loading} />` : html`
|
: !data ? html`<${Loading} />` : html`
|
||||||
<div class="grid">
|
<div class="grid">
|
||||||
<${Card} title="Поступления" value=${rub(data.revenue_rub)}
|
<${Card} title="Поступления" value=${rub(data.revenue_rub)}
|
||||||
note=${'возвраты ' + rub(data.refunded_rub)} />
|
note=${'взносы ' + rub(data.topups_rub) + ' · возвраты ' + rub(data.refunded_rub)} />
|
||||||
<${Card} title="Себестоимость" value=${rub(data.cost_rub)}
|
<${Card} title="Себестоимость" value=${rub(data.cost_rub)}
|
||||||
note=${'цена клиентам ' + rub(data.charged_rub)} />
|
note=${'цена клиентам ' + rub(data.charged_rub)} />
|
||||||
<${Card} title="Поток" value=${rub(data.flow_rub)}
|
<${Card} title="Поток" value=${rub(data.flow_rub)}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ DASH = {"user": "boss@x", "generated_at": 1794000000, "last_visit": None,
|
|||||||
"limit_hits": 0, "latency_qa_ms": 200, "latency_qa_p95_ms": 500,
|
"limit_hits": 0, "latency_qa_ms": 200, "latency_qa_p95_ms": 500,
|
||||||
"latency_agent_ms": 3000, "latency_agent_p95_ms": 9000},
|
"latency_agent_ms": 3000, "latency_agent_p95_ms": 9000},
|
||||||
"money": {"revenue_rub": 1000, "flow_rub": 400, "accounts_total_rub": 2500,
|
"money": {"revenue_rub": 1000, "flow_rub": 400, "accounts_total_rub": 2500,
|
||||||
"topups_included": False, "unpriced": 0},
|
"topups_included": True, "unpriced": 0},
|
||||||
"customers": {"total": 12, "active_24h": 3},
|
"customers": {"total": 12, "active_24h": 3},
|
||||||
"attention": {"failures": 1, "limit_hits": 0, "unpriced": 0}}
|
"attention": {"failures": 1, "limit_hits": 0, "unpriced": 0}}
|
||||||
ATT = {"items": [{"key": "failures:24h", "severity": "high", "title": "Сбои",
|
ATT = {"items": [{"key": "failures:24h", "severity": "high", "title": "Сбои",
|
||||||
@@ -86,7 +86,7 @@ def test_five_cards_money_badge_and_done(browser, site):
|
|||||||
page.goto(site + "/admin/v2")
|
page.goto(site + "/admin/v2")
|
||||||
page.wait_for_selector(".grid .card")
|
page.wait_for_selector(".grid .card")
|
||||||
assert page.locator(".grid .card").count() == 5
|
assert page.locator(".grid .card").count() == 5
|
||||||
assert "предварительно" in page.locator(".badge").first.inner_text()
|
assert "предварительно" not in page.locator("main").inner_text()
|
||||||
assert "1\u00a0000" in page.locator(".grid").inner_text()
|
assert "1\u00a0000" in page.locator(".grid").inner_text()
|
||||||
assert page.locator(".task").count() == 2
|
assert page.locator(".task").count() == 2
|
||||||
assert "первый визит" not in page.locator(".grid").inner_text()
|
assert "первый визит" not in page.locator(".grid").inner_text()
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from test_admin_design_ui import browser # noqa: E402,F401
|
|||||||
|
|
||||||
MONEY = {"period_days": 30, "revenue_rub": 1000, "refunded_rub": 0, "cost_rub": 250,
|
MONEY = {"period_days": 30, "revenue_rub": 1000, "refunded_rub": 0, "cost_rub": 250,
|
||||||
"flow_rub": 750, "charged_rub": 800, "accounts_total_rub": 2000,
|
"flow_rub": 750, "charged_rub": 800, "accounts_total_rub": 2000,
|
||||||
"accounts_count": 2, "unpriced": 0}
|
"accounts_count": 2, "unpriced": 0, "topups_rub": 0}
|
||||||
MONTHS = [{"month": "2026-09", "revenue_rub": 500, "cost_rub": 100},
|
MONTHS = [{"month": "2026-09", "revenue_rub": 500, "cost_rub": 100},
|
||||||
{"month": "2026-10", "revenue_rub": 500, "cost_rub": 150}]
|
{"month": "2026-10", "revenue_rub": 500, "cost_rub": 150}]
|
||||||
PAYMENTS = [
|
PAYMENTS = [
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ DASH = {"user": "boss@x", "generated_at": 1794000000, "last_visit": None,
|
|||||||
"attention": {"failures": 0, "limit_hits": 0, "unpriced": 0}}
|
"attention": {"failures": 0, "limit_hits": 0, "unpriced": 0}}
|
||||||
MONEY = {"period_days": 30, "revenue_rub": 100, "refunded_rub": 0, "cost_rub": 50,
|
MONEY = {"period_days": 30, "revenue_rub": 100, "refunded_rub": 0, "cost_rub": 50,
|
||||||
"flow_rub": 50, "charged_rub": 80, "accounts_total_rub": 200,
|
"flow_rub": 50, "charged_rub": 80, "accounts_total_rub": 200,
|
||||||
"accounts_count": 1, "unpriced": 0}
|
"accounts_count": 1, "unpriced": 0, "topups_rub": 0}
|
||||||
# Один закрытый месяц — тот случай, на котором графики разъезжались: ширина viewBox
|
# Один закрытый месяц — тот случай, на котором графики разъезжались: ширина viewBox
|
||||||
# зависела от числа точек, и при одной точке SVG растягивался в многоэкранную полосу.
|
# зависела от числа точек, и при одной точке SVG растягивался в многоэкранную полосу.
|
||||||
FIN = {"months": [{"month": "2026-11", "revenue_rub": 0, "cost_rub": 714.31}], "days": 30}
|
FIN = {"months": [{"month": "2026-11", "revenue_rub": 0, "cost_rub": 714.31}], "days": 30}
|
||||||
|
|||||||
+10
-4
@@ -48,12 +48,18 @@ def test_money_kopecks_and_period(env):
|
|||||||
d = r.json()
|
d = r.json()
|
||||||
assert d["period_days"] == 30
|
assert d["period_days"] == 30
|
||||||
assert d["accounts_total_kop"] == 1000
|
assert d["accounts_total_kop"] == 1000
|
||||||
assert d["revenue_kop"] == 1000
|
# Взнос 10 ₽ + платёж 10 ₽: поступления — это и предоплата, и платёж.
|
||||||
|
assert d["topups_kop"] == 1000
|
||||||
|
assert d["revenue_kop"] == 2000
|
||||||
assert d["cost_kop"] == 250
|
assert d["cost_kop"] == 250
|
||||||
assert d["flow_kop"] == 750
|
assert d["flow_kop"] == 1750
|
||||||
|
assert d["topups_included"] is True
|
||||||
assert isinstance(d["revenue_kop"], int)
|
assert isinstance(d["revenue_kop"], int)
|
||||||
assert isinstance(d["flow_kop"], int) or d["flow_kop"] is None
|
assert isinstance(d["flow_kop"], int) or d["flow_kop"] is None
|
||||||
assert d["flow_kop"] == d["revenue_kop"] - d["cost_kop"]
|
assert d["flow_kop"] == d["revenue_kop"] - d["cost_kop"]
|
||||||
|
# График по месяцам считает то же, что карточка: иначе «не сходится».
|
||||||
|
series = client.get("/api/admin/v2/finance?days=30", headers=h).json()["months"]
|
||||||
|
assert sum(m["revenue_rub"] for m in series) == pytest.approx(20.0)
|
||||||
assert client.get("/api/admin/v2/money?days=0", headers=h).json()["period_days"] == 1
|
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
|
assert client.get("/api/admin/v2/money?days=9999", headers=h).json()["period_days"] == 366
|
||||||
|
|
||||||
@@ -75,5 +81,5 @@ def test_monthly_rounding_happens_once(env):
|
|||||||
"status, updated_at) VALUES (?,?,?,?,?,?,?)",
|
"status, updated_at) VALUES (?,?,?,?,?,?,?)",
|
||||||
(ts, "joe@x", "p", "0.125", "m-" + str(ts), "succeeded", ts))
|
(ts, "joe@x", "p", "0.125", "m-" + str(ts), "succeeded", ts))
|
||||||
d = client.get("/api/admin/v2/money?days=60", headers=h).json()
|
d = client.get("/api/admin/v2/money?days=60", headers=h).json()
|
||||||
# 10,00 + 0,125 + 0,125 = 10,25 → 1025, а не 10,26 от помесячного округления
|
# Взнос 10,00 + платежи 0,125 + 0,125 = 20,25 → 2025, а не 20,26 от помесячного округления
|
||||||
assert d["revenue_kop"] == 1025
|
assert d["revenue_kop"] == 2025
|
||||||
|
|||||||
Reference in New Issue
Block a user