diff --git a/admin_api.py b/admin_api.py index c0ccc15..5bcb807 100644 --- a/admin_api.py +++ b/admin_api.py @@ -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) diff --git a/db.py b/db.py index a8fafec..ede002d 100644 --- a/db.py +++ b/db.py @@ -274,6 +274,9 @@ def init_db(): "target TEXT NOT NULL, action TEXT NOT NULL, " "before_json TEXT NOT NULL, after_json TEXT, " "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 он # переписал файл запрета и выгрузил неполную смету для экспертизы. База ему недоступна. @@ -1660,6 +1663,32 @@ def record_admin_visit(email: str, now: float | None = None) -> dict: 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, before: dict, after: dict, now: float | None = None) -> int: import json as _json diff --git a/docs/ADMIN_V2_BASELINE.md b/docs/ADMIN_V2_BASELINE.md index 7e8608b..b6c4069 100644 --- a/docs/ADMIN_V2_BASELINE.md +++ b/docs/ADMIN_V2_BASELINE.md @@ -236,6 +236,13 @@ - Drawer: «Удалить» с подтверждением, тост «Клиент удалён» + «Отменить»; удалённая карточка — «Восстановить». - Тесты: 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. Следующий шаг P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания). diff --git a/static/admin2/pages/customer.js b/static/admin2/pages/customer.js index 7567b81..9ac0fa0 100644 --- a/static/admin2/pages/customer.js +++ b/static/admin2/pages/customer.js @@ -68,6 +68,18 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) { } catch (e) { setNotice(e.message || 'Не удалось отменить'); } 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 () => { if (!confirm('Удалить учётку ' + email + '? Переписка и файлы останутся, адрес освободится.')) return; setBusy(true); setNotice(''); @@ -109,6 +121,7 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) { + ` : html`