Files
smeta-web/tests/test_customer_card_api.py
T
anorandClaude Code 378668ecd9 feat(админка): возврат онлайн-пополнения кнопкой прямо в карточке клиента
Хозяин 21.11.2026: «я тебе должен держать в голове все URL-ы старой админки?» — кнопка
возврата жила только на странице «Платежи» прежней админки. Теперь к строке зачисления
в счёте клиента прирастают платёж и остаток к возврату; кнопка «Вернуть N ₽» спрашивает
сумму и зовёт тот же рубеж /api/admin/topups/{id}/refund. После возврата кнопки нет.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-21 00:52:19 +10:00

119 lines
5.4 KiB
Python

"""P2.7 backend: карточка клиента и ленивые вкладки."""
import importlib
import os
import sys
from pathlib import Path
from urllib.parse import quote
import pytest
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
@pytest.fixture()
def env(tmp_path, monkeypatch):
data = tmp_path / "data"
data.mkdir()
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
monkeypatch.setenv("DATA_DIR", str(data))
monkeypatch.setenv("SESSION_SECRET", "test-secret")
monkeypatch.setenv("AI_BACKEND", "claude")
monkeypatch.chdir(ROOT)
import auth
import db
import main
for m in (db, auth, main):
importlib.reload(m)
db.init_db()
db.create_user("boss@x", auth.hash_password("Passw0rd!ok"), role="admin")
db.admin_verify_user("boss@x")
db.create_user("joe@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("joe@x")
db.save_message("joe@x", "t1", "user", "привет")
db.add_account_entry("joe@x", 1000.0, "взнос", "boss@x", ts=0)
(data / "joe@x").mkdir()
(data / "joe@x" / "a.txt").write_text("x", encoding="utf-8")
from fastapi.testclient import TestClient
client = TestClient(main.app)
h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")}
return db, client, h, auth, data
def test_card_and_tabs(env):
db, client, h, auth, data = env
r = client.get("/api/admin/v2/customers/joe@x", headers=h)
assert r.status_code == 200
d = r.json()
assert d["profile"]["email"] == "joe@x"
assert d["account"]["balance_rub"] == 1000.0
assert d["activity"]["messages"] == 1 and d["activity"]["files"] == 1
assert client.get("/api/admin/v2/customers/joe@x/dialogs", headers=h).json()["items"]
led = client.get("/api/admin/v2/customers/joe@x/ledger", headers=h).json()
assert led["entries"] and led["own"] is False
assert client.get("/api/admin/v2/customers/joe@x/files", headers=h).json()["items"][0]["name"] == "a.txt"
assert client.get("/api/admin/v2/customers/joe@x/history", headers=h).status_code == 200
def test_ledger_marks_refundable_topup(env):
"""Онлайн-пополнение приносит в счёт платёж и остаток к возврату; после возврата
кнопки нет (Хозяин 21.11.2026 — возврат из карточки, а не со старой страницы)."""
db, client, h, auth, data = env
tid = db.insert_topup("joe@x", 50000, "robokassa", "joe@x")
db.attach_topup(tid, "77", None)
assert db.credit_topup(tid, 50000, None) == "credited"
led = client.get("/api/admin/v2/customers/joe@x/ledger", headers=h).json()
row = next(e for e in led["entries"] if e.get("topup_id") == tid)
assert row["refundable_rub"] == 500.0
assert client.post(f"/api/admin/topups/{tid}/refund", headers=h,
json={"amount": "500"}).status_code == 200
led = client.get("/api/admin/v2/customers/joe@x/ledger", headers=h).json()
assert not any(e.get("topup_id") == tid for e in led["entries"])
def test_ledger_marks_owner_account(env, monkeypatch):
"""Владельцу счёт не ведётся — карточка должна знать причину, а не говорить
«не заведён» (вопрос Хозяина 21.11.2026)."""
db, client, h, auth, data = env
monkeypatch.setenv("AGENT_OWNER_EMAILS", "joe@x")
led = client.get("/api/admin/v2/customers/joe@x/ledger", headers=h).json()
assert led["own"] is True and led["account"] is None and led["entries"]
def test_card_404_and_admin_only(env):
db, client, h, auth, data = env
assert client.get("/api/admin/v2/customers/ghost@x", headers=h).status_code == 404
user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")}
assert client.get("/api/admin/v2/customers/joe@x", headers=user).status_code == 403
def test_deleted_card_shows_original_email(env):
db, client, h, auth, data = env
archived = db.soft_delete_user("joe@x")
d = client.get("/api/admin/v2/customers/" + quote(archived, safe=""), headers=h).json()
assert d["profile"]["email"] == "joe@x"
assert d["profile"]["deleted_at"] is not None
def test_delete_and_restore_from_card(env):
db, client, h, auth, data = env
r = client.post("/api/admin/v2/customers/joe@x/delete", headers=h)
assert r.status_code == 200, r.text
archived = r.json()["archived_as"]
assert archived.startswith("joe@x#deleted-")
assert client.post("/api/admin/v2/customers/joe@x/delete", headers=h).status_code == 404
# восстановление по архивному имени — именно так открыта карточка удалённого
assert client.post("/api/admin/v2/customers/" + quote(archived, safe="") + "/restore",
headers=h).status_code == 200
assert db.get_user_by_email("joe@x")["deleted_at"] is None
assert client.post("/api/admin/v2/customers/joe@x/restore", headers=h).status_code == 404
def test_delete_self_refused_and_restore_conflict(env):
db, client, h, auth, data = env
assert client.post("/api/admin/v2/customers/boss@x/delete", headers=h).status_code == 400
client.post("/api/admin/v2/customers/joe@x/delete", headers=h)
db.create_user("joe@x", auth.hash_password("Passw0rd!ok"))
r = client.post("/api/admin/v2/customers/joe@x/restore", headers=h)
assert r.status_code == 409