feat(админка): денежный поток вместо прибыли + итог по счетам
This commit is contained in:
@@ -2770,7 +2770,7 @@ async def list_users_endpoint(request: Request):
|
||||
seen = last_seen_all()
|
||||
accounts_failed = False
|
||||
try:
|
||||
accounts = account_balances_all()
|
||||
accounts = await asyncio.to_thread(account_balances_all)
|
||||
except Exception: # noqa: BLE001 — сбой счетов не должен прятать список людей
|
||||
logger.exception("admin/users: счета не прочитаны")
|
||||
accounts = {}
|
||||
@@ -3476,14 +3476,17 @@ async def admin_finance_endpoint(request: Request, days: int = 180,
|
||||
date_to: str = Query("", alias="to")):
|
||||
"""Финансовый итог: поступления, себестоимость обслуживания и что осталось.
|
||||
|
||||
Считаем так, как это делают в подобных службах: выручка — только успешные платежи
|
||||
(возврат её не создаёт и не вычитает дважды, он показан отдельно), себестоимость — наш
|
||||
расход на ИИ за тот же период, прибыль — разница, доля прибыли — её часть в выручке.
|
||||
Считаем так: выручка — только успешные платежи (возврат её не создаёт и не вычитает
|
||||
дважды, он показан отдельно), себестоимость — наш расход на ИИ за тот же период,
|
||||
денежный поток — разница, его доля — часть в поступлениях. Это не бухгалтерская
|
||||
прибыль: остатки на счетах клиентов — обязательство, они показаны отдельной строкой.
|
||||
Ни одно среднее не считается на нулевом делителе: нет платящих — прочерк, а не
|
||||
выдуманное число (обе беды нашли рецензенты по плану 09.09.2026).
|
||||
"""
|
||||
_require_admin(request)
|
||||
from db import finance_by_month
|
||||
from db import finance_by_month, account_balances_all
|
||||
import balance
|
||||
import billing
|
||||
since, until = _report_window(date_from, date_to, days)
|
||||
data = await asyncio.to_thread(finance_by_month, since, until)
|
||||
months = data["months"]
|
||||
@@ -3495,16 +3498,34 @@ async def admin_finance_endpoint(request: Request, days: int = 180,
|
||||
unpriced = sum(m["unpriced"] for m in months)
|
||||
costs = [m["cost_rub"] for m in months if m["cost_rub"] is not None]
|
||||
cost = round(sum(costs), 2) if costs else None
|
||||
profit = round(revenue - cost, 2) if cost is not None else None
|
||||
# Денежный поток, а не бухгалтерская прибыль: остатки на счетах клиентов —
|
||||
# обязательство, его нельзя называть заработанным.
|
||||
flow = round(revenue - cost, 2) if cost is not None else None
|
||||
try:
|
||||
accounts = await asyncio.to_thread(account_balances_all)
|
||||
account_rows = [balance.compose(a["deposited_kop"], a["charged"],
|
||||
a["first_ts"], a["unpriced"])
|
||||
for email, a in accounts.items() if not billing._is_our_own(email)]
|
||||
account_rows = [r for r in account_rows if r]
|
||||
accounts_total = round(sum(r["balance_rub"] for r in account_rows), 2)
|
||||
except Exception: # noqa: BLE001 — счета не должны ронять отчёт
|
||||
logger.exception("finance: счета не прочитаны")
|
||||
accounts_total = None
|
||||
account_rows = []
|
||||
share = (round(flow / revenue, 4)
|
||||
if flow is not None and revenue > 0 else None)
|
||||
return {"months": months,
|
||||
"totals": {"revenue_rub": revenue,
|
||||
"refunded_rub": refunded,
|
||||
"cost_rub": cost,
|
||||
"profit_rub": profit,
|
||||
# Доля прибыли в выручке — только когда выручка есть. При нулевой
|
||||
# это не «минус сто процентов», а «не о чем говорить».
|
||||
"margin_share": (round(profit / revenue, 4)
|
||||
if profit is not None and revenue > 0 else None),
|
||||
"profit_rub": flow, # совместимость со старым ключом
|
||||
"flow_rub": flow,
|
||||
# Доля потока в поступлениях — только когда выручка есть.
|
||||
"margin_share": share,
|
||||
"flow_share": share,
|
||||
"accounts_total_rub": accounts_total,
|
||||
"accounts_count": len(account_rows),
|
||||
"topups_included": False, # до релиза P0.2 пополнений нет
|
||||
"payers": payers,
|
||||
"people": people,
|
||||
"requests": requests,
|
||||
|
||||
Reference in New Issue
Block a user