feat(пополнение): ручки /api/topups, возврат кнопкой, страница результата, финансы и допуск по счёту
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -239,10 +239,21 @@ READ_ONLY_TEXT = ("Баланс исчерпан: новые вопросы и
|
||||
"info@infosmeta.ru.")
|
||||
|
||||
|
||||
def _account_exhausted_text(balance_rub: float) -> str:
|
||||
return (f"Баланс исчерпан: на счёте {_rub(balance_rub)}. Новые вопросы и загрузка файлов "
|
||||
f"закрыты, диалоги доступны для просмотра. Чтобы пополнить счёт, напишите на "
|
||||
f"info@infosmeta.ru.")
|
||||
def _account_exhausted_text(balance_rub: float, user: str | None = None) -> str:
|
||||
head = (f"Баланс исчерпан: на счёте {_rub(balance_rub)}. Новые вопросы и загрузка файлов "
|
||||
f"закрыты, диалоги доступны для просмотра.")
|
||||
if user and _topup_block(user):
|
||||
return head + " Чтобы продолжить работу, нажмите «Пополнить счёт»."
|
||||
return head + " Чтобы пополнить счёт, напишите на info@infosmeta.ru."
|
||||
|
||||
|
||||
def _topup_block(user: str) -> dict | None:
|
||||
try:
|
||||
import topup
|
||||
return topup.person_block(user)
|
||||
except Exception: # noqa: BLE001 — кнопка не важнее ответа
|
||||
logger.exception("_topup_block: блок пополнения не собран")
|
||||
return None
|
||||
|
||||
|
||||
def _read_only_reason(user: str) -> str | None:
|
||||
@@ -279,7 +290,7 @@ def _refuse_if_read_only(user: str) -> None:
|
||||
except Exception: # noqa: BLE001 — отказ уже решён, текст без суммы
|
||||
logger.exception("_refuse_if_read_only: счёт не перечитан")
|
||||
st = None
|
||||
raise HTTPException(402, _account_exhausted_text(st["balance_rub"]) if st else READ_ONLY_TEXT)
|
||||
raise HTTPException(402, _account_exhausted_text(st["balance_rub"], user) if st else READ_ONLY_TEXT)
|
||||
|
||||
|
||||
def _trial_state(user: str) -> dict | None:
|
||||
@@ -358,6 +369,9 @@ def _person_view(user: str) -> dict:
|
||||
trial = _trial_state(user)
|
||||
if trial:
|
||||
snap = {**snap, "trial": trial}
|
||||
topup_blk = _topup_block(user)
|
||||
if topup_blk:
|
||||
snap = {**snap, "topup": topup_blk}
|
||||
return snap
|
||||
|
||||
|
||||
@@ -561,6 +575,11 @@ async def startup():
|
||||
app.state._payments_task = asyncio.create_task(payments.reconciliation_loop())
|
||||
except Exception: # noqa: BLE001 — сверка не должна ронять старт
|
||||
logger.exception("payments reconciliation failed to start")
|
||||
try:
|
||||
import topup
|
||||
app.state._topup_task = asyncio.create_task(topup.reconciliation_loop())
|
||||
except Exception: # noqa: BLE001 — сверка пополнений не должна ронять старт
|
||||
logger.exception("topup reconciliation failed to start")
|
||||
# Подмести одноразовые копии дома агента, оставшиеся от прошлых обрывов. При старте —
|
||||
# потому что служба могла падать в момент прогона; после каждого прогона это делает
|
||||
# сам мост. К 07.09.2026 так натекло 91 каталог на 536 МБ.
|
||||
@@ -597,6 +616,13 @@ async def _stop_payments_reconciliation():
|
||||
t.cancel()
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def _stop_topup_reconciliation():
|
||||
t = getattr(app.state, "_topup_task", None)
|
||||
if t:
|
||||
t.cancel()
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def _stop_home_sweep():
|
||||
t = getattr(app.state, "_sweep_task", None)
|
||||
@@ -3284,7 +3310,13 @@ async def get_billing_settings_endpoint(request: Request):
|
||||
"rate_missing": billing.rate_missing(),
|
||||
"credit_missing": billing.credit_missing(),
|
||||
"credit_rub": billing.credit_rub(),
|
||||
"credit_price_rub": billing.credit_price_rub("client@example")}
|
||||
"credit_price_rub": billing.credit_price_rub("client@example"),
|
||||
"topup": _topup_settings()}
|
||||
|
||||
|
||||
def _topup_settings() -> dict:
|
||||
import topup
|
||||
return topup.settings()
|
||||
|
||||
|
||||
@app.post("/api/admin/billing-settings")
|
||||
@@ -3294,7 +3326,7 @@ async def set_billing_settings_endpoint(request: Request):
|
||||
_require_admin(request)
|
||||
body = await _json_body(request)
|
||||
import pricing
|
||||
from db import set_app_setting
|
||||
from db import set_app_setting, set_app_settings
|
||||
said = []
|
||||
if "usd_rub_rate" in body:
|
||||
try:
|
||||
@@ -3348,6 +3380,38 @@ async def set_billing_settings_endpoint(request: Request):
|
||||
"(плюс 50 % = 1,5)")
|
||||
set_app_setting("price_markup", f"{k:g}")
|
||||
said.append(f"наценка=×{k:g}")
|
||||
# Пополнение онлайн: пределы и пресеты — целые рубли; сохраняем только согласованный
|
||||
# набор, иначе кнопки показали бы сумму, которую ручка создания отвергнет.
|
||||
topup_new = {}
|
||||
for key in ("topup_min_rub", "topup_max_rub"):
|
||||
if key in body:
|
||||
try:
|
||||
v = int(str(body.get(key)).strip())
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, f"{key}: целое число рублей")
|
||||
if v <= 0:
|
||||
raise HTTPException(400, f"{key}: больше нуля")
|
||||
topup_new[key] = v
|
||||
if "topup_presets" in body:
|
||||
try:
|
||||
presets = [int(x) for x in str(body.get("topup_presets")).split(",") if x.strip()]
|
||||
except ValueError:
|
||||
raise HTTPException(400, "topup_presets: целые суммы через запятую")
|
||||
if not presets:
|
||||
raise HTTPException(400, "topup_presets: хотя бы одна сумма")
|
||||
topup_new["topup_presets"] = presets
|
||||
if topup_new:
|
||||
cur = _topup_settings()
|
||||
lo = topup_new.get("topup_min_rub", cur["min"])
|
||||
hi = topup_new.get("topup_max_rub", cur["max"])
|
||||
presets = topup_new.get("topup_presets", cur["presets"])
|
||||
if lo > hi:
|
||||
raise HTTPException(400, "минимум пополнения больше максимума")
|
||||
if not all(lo <= x <= hi for x in presets):
|
||||
raise HTTPException(400, f"пресеты пополнения должны быть от {lo} до {hi} ₽")
|
||||
set_app_settings({"topup_min_rub": str(lo), "topup_max_rub": str(hi),
|
||||
"topup_presets": ",".join(str(x) for x in presets)})
|
||||
said.append(f"пополнение {lo}–{hi} ₽, пресеты {presets}")
|
||||
if not said:
|
||||
raise HTTPException(400, "не указано ни одной настройки")
|
||||
log_action(_get_user(request), "billing_settings", "POST", "/api/admin/billing-settings",
|
||||
@@ -3725,7 +3789,7 @@ async def admin_payments_endpoint(request: Request, days: int = 30):
|
||||
"""Платежи за период — секция «Платежи» в админке. Admin only."""
|
||||
_require_admin(request)
|
||||
import db as _db
|
||||
rows = await asyncio.to_thread(_db.list_payments, min(days, 365))
|
||||
rows = await asyncio.to_thread(_db.admin_payments_union, min(days, 365))
|
||||
return {"payments": rows}
|
||||
|
||||
|
||||
@@ -3736,6 +3800,79 @@ async def payment_result_page():
|
||||
return Path("static/payment_result.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# === Пополнение счёта онлайн (28.10.2026) — правила денег в topup.py, платёжка в pay_*.py ===
|
||||
|
||||
@app.post("/api/topups")
|
||||
async def topups_create_endpoint(request: Request):
|
||||
"""Создать платёж пополнения — только на учётку из пропуска; сумма проверяется на
|
||||
сервере и пишется в нашу строку до обращения к платёжке."""
|
||||
import topup
|
||||
user = _get_user(request)
|
||||
_check_rate_limit(user)
|
||||
body = await _тело(request)
|
||||
ip = _client_ip(request) or None
|
||||
try:
|
||||
res = await asyncio.to_thread(topup.start, user, body.get("amount"), ip)
|
||||
except topup.TopupError as e:
|
||||
raise HTTPException(e.status, e.text) from None
|
||||
row = await asyncio.to_thread(db.get_topup, res["topup_id"])
|
||||
log_action(user, "topup_create", "POST", "/api/topups",
|
||||
f"№{res['topup_id']} {topup._rub(row['amount_kop'])}", ip, 200)
|
||||
return res
|
||||
|
||||
|
||||
@app.post("/api/topups/notify")
|
||||
async def topups_notify_endpoint(request: Request):
|
||||
"""Уведомление платёжки (без входа). Ответ — что велит переходник (Robokassa:
|
||||
текст OK{InvId}); отказ — 200 с пустым телом, подробности только в журнал."""
|
||||
import topup
|
||||
from urllib.parse import parse_qsl
|
||||
ip = _client_ip(request)
|
||||
try:
|
||||
raw = (await request.body()).decode("utf-8", errors="replace")
|
||||
body = dict(parse_qsl(raw, keep_blank_values=True))
|
||||
except Exception: # noqa: BLE001 — тело чужое
|
||||
body = {}
|
||||
code, text, ctype = await asyncio.to_thread(
|
||||
topup.handle_notification, dict(request.headers), body, ip)
|
||||
from fastapi.responses import Response
|
||||
return Response(content=text, status_code=code, media_type=ctype)
|
||||
|
||||
|
||||
@app.get("/api/topups/{topup_id}")
|
||||
async def topups_status_endpoint(request: Request, topup_id: int):
|
||||
"""Состояние СВОЕГО платежа для страницы результата; ничего не зачисляет."""
|
||||
import topup
|
||||
user = _get_user(request)
|
||||
st = await asyncio.to_thread(topup.status_for_person, user, topup_id)
|
||||
if st is None:
|
||||
raise HTTPException(404, "Платёж не найден")
|
||||
return st
|
||||
|
||||
|
||||
@app.post("/api/admin/topups/{topup_id}/refund")
|
||||
async def admin_topup_refund_endpoint(request: Request, topup_id: int):
|
||||
"""Кнопка «Возврат проведён»: Хозяин вводит сумму, которую уже вернул в кабинете
|
||||
платёжки. Предел — остаток платежа; уход счёта в минус допустим (деньги потрачены)."""
|
||||
import balance
|
||||
import topup
|
||||
_require_admin(request)
|
||||
admin = _get_user(request)
|
||||
body = await _тело(request)
|
||||
try:
|
||||
rub = balance.parse_amount(body.get("amount"))
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from None
|
||||
if rub <= 0:
|
||||
raise HTTPException(400, "сумма возврата должна быть больше нуля")
|
||||
try:
|
||||
res = await asyncio.to_thread(topup.apply_refund, topup_id, int(round(rub * 100)),
|
||||
"admin", admin)
|
||||
except topup.TopupError as e:
|
||||
raise HTTPException(e.status, e.text) from None
|
||||
return {"ok": True, "refunded_rub": res["refunded_kop"] / 100, "status": res["status"]}
|
||||
|
||||
|
||||
@app.post("/api/admin/users/verify")
|
||||
async def admin_verify_endpoint(request: Request):
|
||||
"""Открыть человеку доступ вручную — и СКАЗАТЬ ему об этом письмом.
|
||||
|
||||
Reference in New Issue
Block a user