diff --git a/agent_provider.py b/agent_provider.py index 3d4e768..c6741da 100644 --- a/agent_provider.py +++ b/agent_provider.py @@ -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 diff --git a/db.py b/db.py index 16221a0..87651f0 100644 --- a/db.py +++ b/db.py @@ -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.""" diff --git a/main.py b/main.py index d056ccd..2478b03 100644 --- a/main.py +++ b/main.py @@ -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): """Открыть человеку доступ вручную — и СКАЗАТЬ ему об этом письмом. diff --git a/static/payment_result.html b/static/payment_result.html index 5eeb699..6cca22a 100644 --- a/static/payment_result.html +++ b/static/payment_result.html @@ -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; }
-

Оплата

+

Пополнение счёта

Сметный ИИ-ассистент

-
Проверяем оплату…
- +
Проверяем платёж…
+ +
+ + +
diff --git a/tests/test_topup_api.py b/tests/test_topup_api.py index b2bd765..699b8c4 100644 --- a/tests/test_topup_api.py +++ b/tests/test_topup_api.py @@ -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 # --- допуск к агенту -----------------------------------------------------------------------