Files
smeta-web/money.py
T

104 lines
5.7 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 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 account_balances_all
import balance
import billing
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)
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
profit = round(charged_raw - cost_raw, 2) if cost_raw is not None else None
charged = round(charged_raw, 2)
charged_kop = _kop(charged)
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,
# Прибыль — по начислению: что клиенты заплатили за израсходованные ответы
# (цена с наценкой), минус наша себестоимость ИИ. Это валовая прибыль, без
# прочих расходов. Поток выше — про деньги: он включает ещё не потраченную
# предоплату, поэтому прибылью не является.
"profit_rub": profit,
"profit_kop": (charged_kop - cost_kop
if charged_kop is not None and cost_kop is not None else None),
"charged_rub": charged, "charged_kop": charged_kop,
"accounts_total_rub": accounts_total, "accounts_total_kop": accounts_kop,
"accounts_count": len(rows), "unpriced": unpriced,
"topups_rub": round(topups_raw, 2), "topups_kop": _kop(topups_raw),
"topups_included": True,
"note": "поток = поступления − себестоимость; прибыль = начислено клиентам − "
"себестоимость; остатки на счетах — обязательство"}