Files
smeta-web/money.py
T

68 lines
3.3 KiB
Python

"""Деньги кокпита: один сводный ответ вместо семи запросов фронта.
Источник правды — db.finance_by_month (успешные платежи минус себестоимость) и
account_balances_all (обязательства перед клиентами). Никаких собственных таблиц.
"""
from __future__ import annotations
import logging
import time
from decimal import Decimal, ROUND_HALF_UP
logger = logging.getLogger(__name__)
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 - days * 86400, round_kop=False)["months"]
# Суммы — сырые; копейки округляем ОДИН раз, а не каждый месяц до сводки.
revenue_raw = sum(m["revenue_rub"] for m in months)
refunded_raw = sum(m["refunded_rub"] for m in months)
costs = [m["cost_rub"] for m in months if m["cost_rub"] is not None]
cost_raw = sum(costs) if costs else None
charged_raw = sum(m["price_rub"] or 0 for m in months)
revenue = round(revenue_raw, 2)
refunded = round(refunded_raw, 2)
cost = round(cost_raw, 2) if cost_raw is not None else None
flow = round(revenue_raw - cost_raw, 2) if cost_raw is not None else None
charged = round(charged_raw, 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 = []
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 = _kop(revenue_raw)
cost_kop = _kop(cost_raw) if cost_raw is not None else None
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": "поток = поступления − себестоимость; остатки на счетах — обязательство"}