feat(пополнение): ручки /api/topups, возврат кнопкой, страница результата, финансы и допуск по счёту
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+12
-2
@@ -155,6 +155,12 @@ def provider_chain(username: str) -> list[ProviderProfile]:
|
||||
return [primary, secondary]
|
||||
|
||||
|
||||
def _account_positive(username: str) -> bool:
|
||||
import balance
|
||||
st = balance.state(username)
|
||||
return bool(st) and not st["exhausted"]
|
||||
|
||||
|
||||
def agent_allowed(username: str) -> bool:
|
||||
"""Гейт дорогого агентного пути (Ф1 публичного запуска, docs/PUBLIC_LAUNCH_PLAN.md).
|
||||
|
||||
@@ -194,7 +200,7 @@ def agent_allowed(username: str) -> bool:
|
||||
return False # записи нет — читать её поля нечем (зайка 08.09.2026)
|
||||
paid = db.has_successful_payment(username) and \
|
||||
float(row.get("agent_paid_until") or 0) > time.time()
|
||||
if not (paid or row.get("agent_access")):
|
||||
if not (paid or row.get("agent_access") or _account_positive(username)):
|
||||
return False
|
||||
# C6: блокировка действует НЕМЕДЛЕННО на money-path (JWT живёт 24ч — на подпись не
|
||||
# полагаемся). Нет строки в БД (env-only/удалён) → доступа к дорогому пути нет.
|
||||
@@ -203,7 +209,11 @@ def agent_allowed(username: str) -> bool:
|
||||
if row.get("agent_access"):
|
||||
return True
|
||||
# Оплаченный период (этап 3): сравнение с текущим временем, продление — payments.
|
||||
return float(row.get("agent_paid_until") or 0) > time.time()
|
||||
if float(row.get("agent_paid_until") or 0) > time.time():
|
||||
return True
|
||||
# Счёт в плюсе (28.10.2026): заплативший через пополнение не остаётся без агента в
|
||||
# день, когда саморегистрация откроется с agent_access=0.
|
||||
return _account_positive(username)
|
||||
except Exception: # noqa: BLE001 — fail-closed, см. docstring
|
||||
logging.getLogger("smeta_web").exception("agent_allowed: сбой БД — режем агентный путь")
|
||||
return False
|
||||
|
||||
@@ -1489,16 +1489,26 @@ def finance_by_month(since: float, until: float | None = None) -> dict:
|
||||
args_u.append(until)
|
||||
with _conn() as conn:
|
||||
pay = conn.execute(
|
||||
f"SELECT strftime('%Y-%m', ts, 'unixepoch', '{OWNER_TZ_SQL}') AS month, "
|
||||
# Два источника: старые платежи ЮKassa и пополнения онлайн (28.10.2026).
|
||||
# Возврат меняет состояние ТОЙ ЖЕ строки на 'refunded' — вычитать её
|
||||
# отдельно нельзя, иначе выручка уходит в минус (нашёл дипсик 09.09.2026).
|
||||
# Вернувшийся платёж просто перестаёт быть выручкой; сумма возвратов рядом.
|
||||
"SUM(CASE WHEN status='succeeded' THEN CAST(amount_rub AS REAL) ELSE 0 END) "
|
||||
"AS revenue_rub, "
|
||||
"SUM(CASE WHEN status='refunded' THEN CAST(amount_rub AS REAL) ELSE 0 END) "
|
||||
"AS refunded_rub, "
|
||||
"COUNT(DISTINCT CASE WHEN status='succeeded' THEN username END) AS payers "
|
||||
f"FROM payments WHERE ts >= ?{tail_p} GROUP BY month ORDER BY month",
|
||||
# У пополнения возврат бывает частичным: выручка — сумма минус возвращённое.
|
||||
"WITH src AS ("
|
||||
"SELECT ts, username, "
|
||||
"CASE WHEN status='succeeded' THEN CAST(amount_rub AS REAL) ELSE 0 END AS rev, "
|
||||
"CASE WHEN status='refunded' THEN CAST(amount_rub AS REAL) ELSE 0 END AS ref, "
|
||||
"status='succeeded' AS paid FROM payments "
|
||||
"UNION ALL "
|
||||
"SELECT ts, username, "
|
||||
"CASE WHEN status IN ('succeeded','refunded') "
|
||||
"THEN (amount_kop - refunded_kop) / 100.0 ELSE 0 END, "
|
||||
"CASE WHEN status IN ('succeeded','refunded') THEN refunded_kop / 100.0 ELSE 0 END, "
|
||||
"status='succeeded' FROM topups) "
|
||||
f"SELECT strftime('%Y-%m', ts, 'unixepoch', '{OWNER_TZ_SQL}') AS month, "
|
||||
"SUM(rev) AS revenue_rub, SUM(ref) AS refunded_rub, "
|
||||
"COUNT(DISTINCT CASE WHEN paid THEN username END) AS payers "
|
||||
f"FROM src WHERE ts >= ?{tail_p} GROUP BY month ORDER BY month",
|
||||
args_p,
|
||||
).fetchall()
|
||||
use = conn.execute(
|
||||
@@ -1646,6 +1656,40 @@ def list_payments(days: int = 30) -> list[dict]:
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def admin_payments_union(days: int = 30) -> list[dict]:
|
||||
"""«Платежи» в админке: старые платежи ЮKassa и пополнения онлайн одним списком.
|
||||
«Можно вернуть» — подсказка: min(остаток платежа, остаток на счёте), не меньше нуля."""
|
||||
import balance
|
||||
cutoff = time.time() - days * 86400
|
||||
out = [{"kind": "yookassa", "id": r["id"], "ts": r["ts"], "username": r["username"],
|
||||
"amount_rub": float(r["amount_rub"]), "provider": "yookassa",
|
||||
"provider_id": r["yk_payment_id"], "yk_payment_id": r["yk_payment_id"],
|
||||
"status": r["status"], "product": r["product"],
|
||||
"refunded_rub": float(r["amount_rub"]) if r["status"] == "refunded" else 0.0,
|
||||
"refundable_rub": None} for r in list_payments(days)]
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, ts, username, amount_kop, provider, provider_id, status, refunded_kop, "
|
||||
"paid_at FROM topups WHERE ts >= ? ORDER BY id DESC", (cutoff,)).fetchall()
|
||||
accounts: dict[str, float | None] = {}
|
||||
for r in rows:
|
||||
left = (r["amount_kop"] - r["refunded_kop"]) / 100 if r["status"] == "succeeded" else 0.0
|
||||
if r["username"] not in accounts:
|
||||
try:
|
||||
st = balance.state(r["username"])
|
||||
except Exception: # noqa: BLE001 — подсказка не важнее списка
|
||||
st = None
|
||||
accounts[r["username"]] = st["balance_rub"] if st else None
|
||||
bal = accounts[r["username"]]
|
||||
out.append({"kind": "topup", "id": r["id"], "ts": r["ts"], "username": r["username"],
|
||||
"amount_rub": r["amount_kop"] / 100, "provider": r["provider"],
|
||||
"provider_id": r["provider_id"], "status": r["status"], "product": "topup",
|
||||
"refunded_rub": r["refunded_kop"] / 100,
|
||||
"refundable_rub": round(max(0.0, min(left, bal if bal is not None else left)), 2)})
|
||||
out.sort(key=lambda x: x["ts"], reverse=True)
|
||||
return out
|
||||
|
||||
|
||||
def pending_payments_older_than(age_s: float) -> list[dict]:
|
||||
"""Зависшие pending для фоновой сверки (потерянные вебхуки). Свежие (юзер ещё платит)
|
||||
не трогаем — им положено быть pending."""
|
||||
|
||||
@@ -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):
|
||||
"""Открыть человеку доступ вручную — и СКАЗАТЬ ему об этом письмом.
|
||||
|
||||
+79
-31
@@ -8,12 +8,16 @@
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; display: flex; align-items: center; justify-content: center; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 2rem; width: 380px; box-shadow: 0 2px 12px rgba(0,0,0,.08); text-align: center; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 2rem; width: 380px; max-width: calc(100vw - 32px); box-shadow: 0 2px 12px rgba(0,0,0,.08); text-align: center; }
|
||||
h1 { font-size: 1.2rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .85rem; margin-bottom: 1.5rem; }
|
||||
.status { font-size: .95rem; margin-bottom: 1.2rem; line-height: 1.45; }
|
||||
.status.ok { color: var(--green); font-weight: 600; }
|
||||
.status.fail { color: var(--accent); }
|
||||
.hint { color: var(--muted); font-size: .85rem; margin: -.6rem 0 1.2rem; line-height: 1.4; }
|
||||
.btns { display: flex; flex-direction: column; gap: .5rem; }
|
||||
.btns .ghost { background: transparent; color: var(--text); border: 1px solid var(--border); }
|
||||
.btns .ghost:hover { background: var(--bg); }
|
||||
.spinner { width: 28px; height: 28px; margin: 0 auto 1rem; border: 3px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .9s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
button { width: 100%; padding: .7rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
@@ -35,52 +39,96 @@ html { color-scheme: light; }
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>Оплата</h1>
|
||||
<h1>Пополнение счёта</h1>
|
||||
<p class="subtitle">Сметный ИИ-ассистент</p>
|
||||
<div class="spinner" id="spinner"></div>
|
||||
<div class="status" id="status">Проверяем оплату…</div>
|
||||
<button onclick="window.location.href='/'">Вернуться в чат</button>
|
||||
<div class="status" id="status">Проверяем платёж…</div>
|
||||
<p class="hint" id="hint" hidden></p>
|
||||
<div class="btns">
|
||||
<button id="retry" class="ghost" hidden onclick="window.location.href='/?topup=1'">Попробовать снова</button>
|
||||
<button onclick="window.location.href='/'">Вернуться в чат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Страница — ТОЛЬКО UX: поллинг статуса СВОЕГО платежа. Доступ выдаёт сервер
|
||||
// (вебхук/сверка), даже если эту страницу закрыть — оплата не потеряется.
|
||||
// Страница — только показ: деньги зачисляют уведомление платёжки и сверка на сервере,
|
||||
// даже если эту страницу закрыть. Опрос своего платежа раз в 3 с до 2 минут.
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
// payment_id: из query (если положили в return_url вручную) или из localStorage —
|
||||
// кнопка «Оплатить» сохраняет его перед редиректом на ЮKassa.
|
||||
const paymentId = params.get('payment_id') || localStorage.getItem('last_payment_id') || '';
|
||||
const token = localStorage.getItem('token') || '';
|
||||
let topupId = params.get('t') || '';
|
||||
try { if (!topupId) topupId = localStorage.getItem('last_topup_id') || ''; } catch (e) {}
|
||||
// Старые платежи (до пополнения): payment_id → прежняя ручка статуса.
|
||||
let legacyId = params.get('payment_id') || '';
|
||||
try { if (!topupId && !legacyId) legacyId = localStorage.getItem('last_payment_id') || ''; } catch (e) {}
|
||||
let token = '';
|
||||
try { token = localStorage.getItem('token') || ''; } catch (e) {}
|
||||
const statusEl = document.getElementById('status');
|
||||
const hintEl = document.getElementById('hint');
|
||||
const spinnerEl = document.getElementById('spinner');
|
||||
const UNKNOWN = 'Не удалось проверить платёж. Если деньги списались — они появятся на счёте ' +
|
||||
'в течение часа; если нет — напишите на info@infosmeta.ru.';
|
||||
const WAITING = 'Банк ещё подтверждает платёж. Деньги появятся на счёте сами, страницу можно закрыть.';
|
||||
let tries = 0;
|
||||
|
||||
function show(text, cls) {
|
||||
statusEl.textContent = text;
|
||||
statusEl.className = 'status' + (cls ? ' ' + cls : '');
|
||||
if (cls) spinnerEl.style.display = 'none';
|
||||
function rub(v) {
|
||||
return Number(v).toLocaleString('ru-RU', {minimumFractionDigits: 0, maximumFractionDigits: 2}) + ' ₽';
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (!paymentId) { show('Платёж не найден. Если вы оплатили — доступ включится автоматически в течение нескольких минут.', 'fail'); return; }
|
||||
if (!token) { show('Вы не вошли в систему. Войдите — статус оплаты обновится автоматически.', 'fail'); return; }
|
||||
function show(text, cls, hint) {
|
||||
statusEl.textContent = text;
|
||||
statusEl.className = 'status' + (cls ? ' ' + cls : '');
|
||||
if (cls !== undefined) spinnerEl.style.display = 'none';
|
||||
hintEl.hidden = !hint;
|
||||
hintEl.textContent = hint || '';
|
||||
}
|
||||
|
||||
async function pollTopup() {
|
||||
if (!token) { show(UNKNOWN, 'fail', 'Войдите на сайт — состояние платежа обновится.'); return; }
|
||||
try {
|
||||
const r = await fetch('/api/payments/status?payment_id=' + encodeURIComponent(paymentId),
|
||||
{headers: {'Authorization': 'Bearer ' + token}});
|
||||
if (r.status === 401) { show('Сессия истекла. Войдите заново — оплата не потеряется.', 'fail'); return; }
|
||||
if (!r.ok) { show('Платёж не найден. Если деньги списались — доступ включится автоматически.', 'fail'); return; }
|
||||
const d = await r.json();
|
||||
if (d.status === 'succeeded') { show('Оплата прошла! Агентные функции активированы.', 'ok'); return; }
|
||||
if (d.status === 'canceled') { show('Оплата не завершена (отменена или отклонена). Деньги не списаны.', 'fail'); return; }
|
||||
if (d.status === 'refunded') { show('По этому платежу оформлен возврат.', 'fail'); return; }
|
||||
const r = await fetch('/api/topups/' + encodeURIComponent(topupId),
|
||||
{headers: {'Authorization': 'Bearer ' + token}, cache: 'no-store'});
|
||||
if (r.status === 401 || r.status === 404 || r.status === 400) { show(UNKNOWN, 'fail'); return; }
|
||||
if (r.ok) {
|
||||
const d = await r.json();
|
||||
if (d.status === 'succeeded') {
|
||||
try { localStorage.removeItem('last_topup_id'); } catch (e) {}
|
||||
show('Зачислено ' + rub(d.amount_rub) + '.', 'ok',
|
||||
d.balance_rub === null || d.balance_rub === undefined ? '' : 'На счёте ' + rub(d.balance_rub));
|
||||
return;
|
||||
}
|
||||
if (d.status === 'canceled') {
|
||||
document.getElementById('retry').hidden = false;
|
||||
show('Оплата не прошла, деньги не списаны.', 'fail');
|
||||
return;
|
||||
}
|
||||
if (d.status === 'refunded') { show('По этому платежу оформлен возврат.', 'fail'); return; }
|
||||
if (d.status === 'failed') { show(UNKNOWN, 'fail'); return; }
|
||||
show(WAITING);
|
||||
}
|
||||
} catch (e) { /* сеть моргнула — следующая попытка */ }
|
||||
tries++;
|
||||
if (tries >= 40) { // ~2 минуты: вебхук мог задержаться — доберёт фоновая сверка
|
||||
show('Оплата ещё обрабатывается. Доступ включится автоматически — можно вернуться в чат.', '');
|
||||
return;
|
||||
}
|
||||
setTimeout(poll, 3000);
|
||||
if (tries >= 40) { show(WAITING, ''); return; }
|
||||
setTimeout(pollTopup, 3000);
|
||||
}
|
||||
poll();
|
||||
|
||||
async function pollLegacy() {
|
||||
if (!token) { show(UNKNOWN, 'fail'); return; }
|
||||
try {
|
||||
const r = await fetch('/api/payments/status?payment_id=' + encodeURIComponent(legacyId),
|
||||
{headers: {'Authorization': 'Bearer ' + token}});
|
||||
if (!r.ok) { show(UNKNOWN, 'fail'); return; }
|
||||
const d = await r.json();
|
||||
if (d.status === 'succeeded') { show('Оплата прошла.', 'ok'); return; }
|
||||
if (d.status === 'canceled') { show('Оплата не прошла, деньги не списаны.', 'fail'); return; }
|
||||
if (d.status === 'refunded') { show('По этому платежу оформлен возврат.', 'fail'); return; }
|
||||
} catch (e) {}
|
||||
tries++;
|
||||
if (tries >= 40) { show(WAITING, ''); return; }
|
||||
setTimeout(pollLegacy, 3000);
|
||||
}
|
||||
|
||||
if (topupId) pollTopup();
|
||||
else if (legacyId) pollLegacy();
|
||||
else show(UNKNOWN, 'fail');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -335,6 +335,8 @@ def test_billing_settings_topup_limits(env):
|
||||
assert r.status_code == 400
|
||||
r = client.post("/api/admin/billing-settings", headers=ah, json={"topup_presets": "50"})
|
||||
assert r.status_code == 400
|
||||
r = client.post("/api/admin/billing-settings", headers=ah, json={"topup_min_rub": "0"})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
# --- допуск к агенту -----------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user