Files
smeta-web/money.py
T

44 lines
2.2 KiB
Python

"""Деньги кокпита: один сводный ответ вместо семи запросов фронта.
Источник правды — db.finance_by_month (успешные платежи минус себестоимость) и
account_balances_all (обязательства перед клиентами). Никаких собственных таблиц.
"""
from __future__ import annotations
import logging
import time
logger = logging.getLogger(__name__)
def summary(now: float | None = None) -> dict:
now = time.time() if now is None else now
from db import finance_by_month, account_balances_all
import balance
import billing
months = finance_by_month(now - 30 * 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]
cost = round(sum(costs), 2) if costs else None
flow = round(revenue - cost, 2) if cost is not None else None
charged = round(sum(m["price_rub"] or 0 for m in months), 2)
try:
accounts = account_balances_all()
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)]
rows = [r for r in rows if r]
accounts_total = round(sum(r["balance_rub"] for r in rows), 2)
unpriced = sum(int(r.get("unpriced") or 0) for r in rows)
except Exception: # noqa: BLE001 — деньги не должны ронять весь кокпит
logger.exception("money: счета не прочитаны")
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,
"note": "поток = поступления − себестоимость; остатки на счетах — обязательство"}