From 33c289845d51fc32d16b109613cdbfaad24d8d31 Mon Sep 17 00:00:00 2001 From: anor Date: Tue, 10 Nov 2026 01:34:29 +1000 Subject: [PATCH] =?UTF-8?q?fix(=D0=B4=D0=B5=D0=BD=D1=8C=D0=B3=D0=B8):=20?= =?UTF-8?q?=D0=B2=D0=B7=D0=BD=D0=BE=D1=81=D1=8B=20=D0=BD=D0=B0=20=D1=81?= =?UTF-8?q?=D1=87=D1=91=D1=82=20=D0=B2=D1=85=D0=BE=D0=B4=D1=8F=D1=82=20?= =?UTF-8?q?=D0=B2=20=D0=BF=D0=BE=D1=81=D1=82=D1=83=D0=BF=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F,=20=D0=BA=D0=B0=D1=80=D1=82=D0=BE=D1=87=D0=BA?= =?UTF-8?q?=D0=B0=20=D1=81=D1=85=D0=BE=D0=B4=D0=B8=D1=82=D1=81=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Code --- admin_api.py | 4 ++-- db.py | 21 +++++++++++++++++++++ main.py | 2 +- money.py | 35 +++++++++++++++++++++++++++++++---- static/admin2/pages/money.js | 2 +- tests/test_admin_v2_day.py | 4 ++-- tests/test_admin_v2_money.py | 2 +- tests/test_admin_v2_visual.py | 2 +- tests/test_money_api.py | 14 ++++++++++---- 9 files changed, 70 insertions(+), 16 deletions(-) diff --git a/admin_api.py b/admin_api.py index bd4c6a2..c38586e 100644 --- a/admin_api.py +++ b/admin_api.py @@ -487,8 +487,8 @@ 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"]} + months = await asyncio.to_thread(money.finance_months, since) + return {"days": days, "months": months} @router.get("/money") diff --git a/db.py b/db.py index d47e1d6..7c2615e 100644 --- a/db.py +++ b/db.py @@ -1041,6 +1041,27 @@ def list_account_entries(username: str, limit: int = 200) -> list[dict]: 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: """Взносы человека одной строкой: {"entries", "deposited_kop", "first_ts"}; None — взносов не было, человек не на счёте.""" diff --git a/main.py b/main.py index 151bb85..c3d273c 100644 --- a/main.py +++ b/main.py @@ -464,7 +464,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через 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_MAP = [ diff --git a/money.py b/money.py index b87b625..1b488f9 100644 --- a/money.py +++ b/money.py @@ -18,14 +18,39 @@ def _kop(value): 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: 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 + from db import account_balances_all import balance 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) 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), "accounts_total_rub": accounts_total, "accounts_total_kop": accounts_kop, "accounts_count": len(rows), "unpriced": unpriced, - "topups_included": False, - "note": "поток = поступления − себестоимость; остатки на счетах — обязательство"} + "topups_rub": round(topups_raw, 2), "topups_kop": _kop(topups_raw), + "topups_included": True, + "note": "поток = поступления − себестоимость; поступления включают взносы; " + "остатки на счетах — обязательство"} diff --git a/static/admin2/pages/money.js b/static/admin2/pages/money.js index 556338b..6aaa2e7 100644 --- a/static/admin2/pages/money.js +++ b/static/admin2/pages/money.js @@ -85,7 +85,7 @@ export function MoneyPage() { : !data ? html`<${Loading} />` : html`
<${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)} note=${'цена клиентам ' + rub(data.charged_rub)} /> <${Card} title="Поток" value=${rub(data.flow_rub)} diff --git a/tests/test_admin_v2_day.py b/tests/test_admin_v2_day.py index b8d7533..307971b 100644 --- a/tests/test_admin_v2_day.py +++ b/tests/test_admin_v2_day.py @@ -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, "latency_agent_ms": 3000, "latency_agent_p95_ms": 9000}, "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}, "attention": {"failures": 1, "limit_hits": 0, "unpriced": 0}} 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.wait_for_selector(".grid .card") 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 page.locator(".task").count() == 2 assert "первый визит" not in page.locator(".grid").inner_text() diff --git a/tests/test_admin_v2_money.py b/tests/test_admin_v2_money.py index 77ac0cf..f2481f3 100644 --- a/tests/test_admin_v2_money.py +++ b/tests/test_admin_v2_money.py @@ -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, "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}, {"month": "2026-10", "revenue_rub": 500, "cost_rub": 150}] PAYMENTS = [ diff --git a/tests/test_admin_v2_visual.py b/tests/test_admin_v2_visual.py index e7f7afe..7489ad7 100644 --- a/tests/test_admin_v2_visual.py +++ b/tests/test_admin_v2_visual.py @@ -24,7 +24,7 @@ DASH = {"user": "boss@x", "generated_at": 1794000000, "last_visit": None, "attention": {"failures": 0, "limit_hits": 0, "unpriced": 0}} MONEY = {"period_days": 30, "revenue_rub": 100, "refunded_rub": 0, "cost_rub": 50, "flow_rub": 50, "charged_rub": 80, "accounts_total_rub": 200, - "accounts_count": 1, "unpriced": 0} + "accounts_count": 1, "unpriced": 0, "topups_rub": 0} # Один закрытый месяц — тот случай, на котором графики разъезжались: ширина viewBox # зависела от числа точек, и при одной точке SVG растягивался в многоэкранную полосу. FIN = {"months": [{"month": "2026-11", "revenue_rub": 0, "cost_rub": 714.31}], "days": 30} diff --git a/tests/test_money_api.py b/tests/test_money_api.py index 5eb7d3a..93f16b8 100644 --- a/tests/test_money_api.py +++ b/tests/test_money_api.py @@ -48,12 +48,18 @@ def test_money_kopecks_and_period(env): d = r.json() assert d["period_days"] == 30 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["flow_kop"] == 750 + assert d["flow_kop"] == 1750 + assert d["topups_included"] is True 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"] + # График по месяцам считает то же, что карточка: иначе «не сходится». + 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=9999", headers=h).json()["period_days"] == 366 @@ -75,5 +81,5 @@ def test_monthly_rounding_happens_once(env): "status, updated_at) VALUES (?,?,?,?,?,?,?)", (ts, "joe@x", "p", "0.125", "m-" + str(ts), "succeeded", ts)) d = client.get("/api/admin/v2/money?days=60", headers=h).json() - # 10,00 + 0,125 + 0,125 = 10,25 → 1025, а не 10,26 от помесячного округления - assert d["revenue_kop"] == 1025 + # Взнос 10,00 + платежи 0,125 + 0,125 = 20,25 → 2025, а не 20,26 от помесячного округления + assert d["revenue_kop"] == 2025