feat(админка): ручной взнос v2 с идемпотентностью
This commit is contained in:
@@ -154,6 +154,63 @@ async def customer_history(email: str, request: Request):
|
|||||||
return {"items": data}
|
return {"items": data}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/customers/{email}/topup")
|
||||||
|
async def customer_topup(email: str, request: Request):
|
||||||
|
user = require_admin(request)
|
||||||
|
email = email.strip().lower()
|
||||||
|
try:
|
||||||
|
body = await request.json()
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
raise ValueError
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(400, "тело — JSON-объект") from None
|
||||||
|
from db import get_user_by_email
|
||||||
|
u = await asyncio.to_thread(get_user_by_email, email)
|
||||||
|
if not u:
|
||||||
|
raise HTTPException(404, "Клиент не найден")
|
||||||
|
import balance
|
||||||
|
if balance._is_our_own(email):
|
||||||
|
raise HTTPException(400, "Владельцу и служебным учёткам счёт не заводится")
|
||||||
|
try:
|
||||||
|
amount = balance.parse_amount(body.get("amount"))
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(400, str(e)) from e
|
||||||
|
if amount <= 0:
|
||||||
|
raise HTTPException(400, "взнос — только положительная сумма")
|
||||||
|
comment = str(body.get("comment") or "")[:200]
|
||||||
|
rid = str(body.get("request_id") or "").strip()
|
||||||
|
key = f"topup:{email.lower().strip()}:{rid}" if rid else None
|
||||||
|
if key:
|
||||||
|
claim = await asyncio.to_thread(db.claim_idempotency, key, "topup")
|
||||||
|
if claim["existing"]:
|
||||||
|
if claim["response"] is None:
|
||||||
|
raise HTTPException(409, "Этот взнос уже выполняется")
|
||||||
|
return {**claim["response"], "idempotent": True}
|
||||||
|
try:
|
||||||
|
result = await asyncio.to_thread(balance.deposit, email, amount, comment, user)
|
||||||
|
except LookupError as e:
|
||||||
|
if key:
|
||||||
|
await asyncio.to_thread(db.drop_idempotency, key)
|
||||||
|
raise HTTPException(404, str(e)) from e
|
||||||
|
except ValueError as e:
|
||||||
|
if key:
|
||||||
|
await asyncio.to_thread(db.drop_idempotency, key)
|
||||||
|
raise HTTPException(400, str(e)) from e
|
||||||
|
except Exception as e: # noqa: BLE001 — деньги могли записаться, ключ не должен залипнуть
|
||||||
|
if key:
|
||||||
|
await asyncio.to_thread(db.drop_idempotency, key)
|
||||||
|
raise HTTPException(500, "Неизвестно, записан ли взнос — проверьте счёт клиента") from e
|
||||||
|
response = {"ok": True, **result}
|
||||||
|
acc = result.get("account") or {}
|
||||||
|
db.log_action(user, "admin_deposit", "POST", f"/api/admin/v2/customers/{email}/topup",
|
||||||
|
detail=f"{email}: {amount:+.2f} ₽; на счёте "
|
||||||
|
+ (f"{acc['balance_rub']:.2f} ₽" if acc else "—")
|
||||||
|
+ (f"; {comment}" if comment else ""))
|
||||||
|
if key:
|
||||||
|
await asyncio.to_thread(db.complete_idempotency, key, response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
@router.post("/customers/{email}/delete")
|
@router.post("/customers/{email}/delete")
|
||||||
async def customer_delete(email: str, request: Request):
|
async def customer_delete(email: str, request: Request):
|
||||||
user = require_admin(request)
|
user = require_admin(request)
|
||||||
|
|||||||
@@ -274,6 +274,9 @@ def init_db():
|
|||||||
"target TEXT NOT NULL, action TEXT NOT NULL, "
|
"target TEXT NOT NULL, action TEXT NOT NULL, "
|
||||||
"before_json TEXT NOT NULL, after_json TEXT, "
|
"before_json TEXT NOT NULL, after_json TEXT, "
|
||||||
"created_at REAL NOT NULL, undone_at REAL)")
|
"created_at REAL NOT NULL, undone_at REAL)")
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS admin_idempotency ("
|
||||||
|
"key TEXT PRIMARY KEY, action TEXT NOT NULL, "
|
||||||
|
"response_json TEXT, created_at REAL NOT NULL)")
|
||||||
# Что просили у движка смет и что он ответил — пишет ОСНОВНОЙ процесс, а не агент.
|
# Что просили у движка смет и что он ответил — пишет ОСНОВНОЙ процесс, а не агент.
|
||||||
# Всё, что лежит в рабочей папке вкладки, агенту доступно на запись: 14.09.2026 он
|
# Всё, что лежит в рабочей папке вкладки, агенту доступно на запись: 14.09.2026 он
|
||||||
# переписал файл запрета и выгрузил неполную смету для экспертизы. База ему недоступна.
|
# переписал файл запрета и выгрузил неполную смету для экспертизы. База ему недоступна.
|
||||||
@@ -1660,6 +1663,32 @@ def record_admin_visit(email: str, now: float | None = None) -> dict:
|
|||||||
return {"previous": previous, "now": ts}
|
return {"previous": previous, "now": ts}
|
||||||
|
|
||||||
|
|
||||||
|
def claim_idempotency(key: str, action: str) -> dict:
|
||||||
|
"""Занять ключ. Возвращает {"existing": bool, "response": dict|None}."""
|
||||||
|
import json as _json
|
||||||
|
with _conn() as conn:
|
||||||
|
cur = conn.execute("INSERT OR IGNORE INTO admin_idempotency (key, action, created_at) "
|
||||||
|
"VALUES (?,?,?)", (key, action, time.time()))
|
||||||
|
inserted = cur.rowcount > 0
|
||||||
|
row = conn.execute("SELECT response_json FROM admin_idempotency WHERE key = ?",
|
||||||
|
(key,)).fetchone()
|
||||||
|
raw = row["response_json"] if row else None
|
||||||
|
return {"existing": not inserted,
|
||||||
|
"response": _json.loads(raw) if raw else None}
|
||||||
|
|
||||||
|
|
||||||
|
def complete_idempotency(key: str, response: dict) -> None:
|
||||||
|
import json as _json
|
||||||
|
with _conn() as conn:
|
||||||
|
conn.execute("UPDATE admin_idempotency SET response_json = ? WHERE key = ?",
|
||||||
|
(_json.dumps(response, ensure_ascii=False), key))
|
||||||
|
|
||||||
|
|
||||||
|
def drop_idempotency(key: str) -> None:
|
||||||
|
with _conn() as conn:
|
||||||
|
conn.execute("DELETE FROM admin_idempotency WHERE key = ?", (key,))
|
||||||
|
|
||||||
|
|
||||||
def record_admin_action(actor: str, target: str, action: str,
|
def record_admin_action(actor: str, target: str, action: str,
|
||||||
before: dict, after: dict, now: float | None = None) -> int:
|
before: dict, after: dict, now: float | None = None) -> int:
|
||||||
import json as _json
|
import json as _json
|
||||||
|
|||||||
@@ -236,6 +236,13 @@
|
|||||||
- Drawer: «Удалить» с подтверждением, тост «Клиент удалён» + «Отменить»; удалённая карточка — «Восстановить».
|
- Drawer: «Удалить» с подтверждением, тост «Клиент удалён» + «Отменить»; удалённая карточка — «Восстановить».
|
||||||
- Тесты: API delete/restore/conflict — 2; UI delete→undo — 8 в файле.
|
- Тесты: API delete/restore/conflict — 2; UI delete→undo — 8 в файле.
|
||||||
|
|
||||||
|
## 4.28. P2.9 — ручной взнос v2
|
||||||
|
|
||||||
|
- `/customers/{email}/topup`: положительная сумма, копейки, аудит; `request_id` через `admin_idempotency`, повтор не задваивает.
|
||||||
|
- Нормализация email, ghost/deleted/служебные → 400/404; сбой deposit снимает ключ, 500 с предупреждением.
|
||||||
|
- UI: «Внести» в карточке с prompt; тост.
|
||||||
|
- Тесты: `tests/test_topup_v2_api.py` — 4; UI — 9.
|
||||||
|
|
||||||
## 5. Следующий шаг
|
## 5. Следующий шаг
|
||||||
|
|
||||||
P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания).
|
P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания).
|
||||||
|
|||||||
@@ -68,6 +68,18 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) {
|
|||||||
} catch (e) { setNotice(e.message || 'Не удалось отменить'); }
|
} catch (e) { setNotice(e.message || 'Не удалось отменить'); }
|
||||||
finally { setBusy(false); }
|
finally { setBusy(false); }
|
||||||
};
|
};
|
||||||
|
const topup = async () => {
|
||||||
|
const amount = prompt('Сумма взноса, ₽', '1000');
|
||||||
|
if (!amount) return;
|
||||||
|
setBusy(true); setNotice('');
|
||||||
|
try {
|
||||||
|
const rid = (crypto && crypto.randomUUID) ? crypto.randomUUID() : String(Date.now());
|
||||||
|
await api('/api/admin/v2/customers/' + encodeURIComponent(email) + '/topup',
|
||||||
|
{method: 'POST', body: JSON.stringify({amount, request_id: rid})});
|
||||||
|
setNotice('Взнос записан'); setReload((n) => n + 1);
|
||||||
|
} catch (e) { setNotice(e.message || 'Взнос не записан'); }
|
||||||
|
finally { setBusy(false); }
|
||||||
|
};
|
||||||
const del = async () => {
|
const del = async () => {
|
||||||
if (!confirm('Удалить учётку ' + email + '? Переписка и файлы останутся, адрес освободится.')) return;
|
if (!confirm('Удалить учётку ' + email + '? Переписка и файлы останутся, адрес освободится.')) return;
|
||||||
setBusy(true); setNotice('');
|
setBusy(true); setNotice('');
|
||||||
@@ -109,6 +121,7 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) {
|
|||||||
<button type="button" disabled=${busy} onClick=${() => act('agent_access',
|
<button type="button" disabled=${busy} onClick=${() => act('agent_access',
|
||||||
{agent_access: !card.profile.agent_access}, card.profile.agent_access ? 'Доступ снят' : 'Доступ выдан')}>
|
{agent_access: !card.profile.agent_access}, card.profile.agent_access ? 'Доступ снят' : 'Доступ выдан')}>
|
||||||
${card.profile.agent_access ? 'Снять агента' : 'Выдать агента'}</button>
|
${card.profile.agent_access ? 'Снять агента' : 'Выдать агента'}</button>
|
||||||
|
<button type="button" disabled=${busy} onClick=${topup}>Внести</button>
|
||||||
<button type="button" disabled=${busy} onClick=${del}>Удалить</button>
|
<button type="button" disabled=${busy} onClick=${del}>Удалить</button>
|
||||||
</div>` : html`<div class="actions-bar">
|
</div>` : html`<div class="actions-bar">
|
||||||
<button type="button" disabled=${busy} onClick=${restore}>Восстановить</button>
|
<button type="button" disabled=${busy} onClick=${restore}>Восстановить</button>
|
||||||
|
|||||||
@@ -242,3 +242,20 @@ def test_delete_from_drawer_and_undo(browser, site):
|
|||||||
paths = [a["path"] for a in Handler.actions]
|
paths = [a["path"] for a in Handler.actions]
|
||||||
assert any("/delete" in p for p in paths) and any("/restore" in p for p in paths)
|
assert any("/delete" in p for p in paths) and any("/restore" in p for p in paths)
|
||||||
page.close()
|
page.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_topup_from_drawer(browser, site):
|
||||||
|
Handler.actions = []; Handler.blocked = False; Handler.fail_action = None; Handler.fail_card = False
|
||||||
|
page = browser.new_page()
|
||||||
|
page.add_init_script("localStorage.setItem('token','t')")
|
||||||
|
page.goto(site + "/admin/v2/customers")
|
||||||
|
page.locator("tr.clickable").first.click()
|
||||||
|
page.wait_for_selector(".drawer .kv")
|
||||||
|
page.on("dialog", lambda d: d.accept("500"))
|
||||||
|
page.locator(".actions-bar button", has_text="Внести").click()
|
||||||
|
page.wait_for_selector(".toast")
|
||||||
|
assert "Взнос записан" in page.locator(".toast").inner_text()
|
||||||
|
assert any("/customers/anna%40x/topup" in a["path"] for a in Handler.actions)
|
||||||
|
sent = next(a["body"] for a in Handler.actions if "/topup" in a["path"])
|
||||||
|
assert '"amount":"500"' in sent
|
||||||
|
page.close()
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""P2.9: ручной взнос через v2, идемпотентность по request_id."""
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
if ROOT not in sys.path:
|
||||||
|
sys.path.insert(0, ROOT)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def env(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
||||||
|
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")
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
client = TestClient(main.app)
|
||||||
|
h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")}
|
||||||
|
return db, client, h, auth
|
||||||
|
|
||||||
|
|
||||||
|
def test_topup_and_idempotency(env):
|
||||||
|
db, client, h, auth = env
|
||||||
|
body = {"amount": "100", "comment": "взнос", "request_id": "r1"}
|
||||||
|
r = client.post("/api/admin/v2/customers/joe@x/topup", json=body, headers=h)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
entry = r.json()["entry"]["id"]
|
||||||
|
assert db.account_summary("joe@x")["deposited_kop"] == 10000
|
||||||
|
again = client.post("/api/admin/v2/customers/joe@x/topup", json=body, headers=h)
|
||||||
|
assert again.status_code == 200 and again.json()["entry"]["id"] == entry
|
||||||
|
assert db.account_summary("joe@x")["deposited_kop"] == 10000
|
||||||
|
|
||||||
|
other = client.post("/api/admin/v2/customers/joe@x/topup",
|
||||||
|
json={**body, "request_id": "r2"}, headers=h)
|
||||||
|
assert other.status_code == 200
|
||||||
|
assert db.account_summary("joe@x")["deposited_kop"] == 20000
|
||||||
|
|
||||||
|
|
||||||
|
def test_topup_404_403(env):
|
||||||
|
db, client, h, auth = env
|
||||||
|
assert client.post("/api/admin/v2/customers/ghost@x/topup",
|
||||||
|
json={"amount": "10"}, headers=h).status_code == 404
|
||||||
|
user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")}
|
||||||
|
assert client.post("/api/admin/v2/customers/joe@x/topup",
|
||||||
|
json={"amount": "10"}, headers=user).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_case_normalization_negative_owner_and_stale_claim(env):
|
||||||
|
db, client, h, auth = env
|
||||||
|
r = client.post("/api/admin/v2/customers/JOE@X/topup",
|
||||||
|
json={"amount": "10", "request_id": "case"}, headers=h)
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert db.account_summary("joe@x")["deposited_kop"] == 1000
|
||||||
|
assert db.list_account_entries("joe@x")
|
||||||
|
|
||||||
|
assert client.post("/api/admin/v2/customers/joe@x/topup",
|
||||||
|
json={"amount": "-100"}, headers=h).status_code == 400
|
||||||
|
db.create_user("canary@local", auth.hash_password("Passw0rd!ok"))
|
||||||
|
assert client.post("/api/admin/v2/customers/canary@local/topup",
|
||||||
|
json={"amount": "10"}, headers=h).status_code == 400
|
||||||
|
|
||||||
|
db.claim_idempotency("topup:joe@x:busy", "topup")
|
||||||
|
assert client.post("/api/admin/v2/customers/joe@x/topup",
|
||||||
|
json={"amount": "10", "request_id": "busy"}, headers=h).status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_deleted_customer_topup_404(env):
|
||||||
|
db, client, h, auth = env
|
||||||
|
db.soft_delete_user("joe@x")
|
||||||
|
assert client.post("/api/admin/v2/customers/joe@x/topup",
|
||||||
|
json={"amount": "10"}, headers=h).status_code == 404
|
||||||
Reference in New Issue
Block a user