feat(админка): ручной взнос v2 с идемпотентностью

This commit is contained in:
anor
2026-11-06 22:18:45 +10:00
parent 19834cd1dc
commit 99b62fb5fb
6 changed files with 207 additions and 0 deletions
+57
View File
@@ -154,6 +154,63 @@ async def customer_history(email: str, request: Request):
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")
async def customer_delete(email: str, request: Request):
user = require_admin(request)