feat(админка): действия в карточке и тост отмены

This commit is contained in:
anor
2026-11-06 22:01:23 +10:00
parent e15369c4d4
commit 0e9a95e95b
9 changed files with 166 additions and 9 deletions
+2
View File
@@ -70,6 +70,8 @@ def _apply(email: str, action: str, value: dict) -> None:
def perform(actor: str, email: str, action: str, value: dict) -> dict: def perform(actor: str, email: str, action: str, value: dict) -> dict:
if action not in ACTIONS: if action not in ACTIONS:
raise ValueError("неизвестное действие") raise ValueError("неизвестное действие")
if action in ("role", "block") and actor.strip().lower() == email.strip().lower():
raise ValueError("свою роль и блокировку менять нельзя")
before = _before(email, action) before = _before(email, action)
_apply(email, action, value) _apply(email, action, value)
after = _before(email, action) after = _before(email, action)
+3 -2
View File
@@ -222,12 +222,13 @@
- Тесты: `tests/test_customer_card_api.py` — 3, UI — 4; lazy-вкладка проверяется счётчиком. - Тесты: `tests/test_customer_card_api.py` — 3, UI — 4; lazy-вкладка проверяется счётчиком.
- P2: фокус-трап drawer — остаток. - P2: фокус-трап drawer — остаток.
## 4.25. P2.8 (частично) — обратимые действия ## 4.25. P2.8 — обратимые действия
- `admin_actions` (before/after, undone_at), `/customers/{email}/action`, `/actions/{id}/undo`. - `admin_actions` (before/after, undone_at), `/customers/{email}/action`, `/actions/{id}/undo`.
- Роль/блок/режим/пробный/доступ/пределы; bool строго, битый JSON → 400, undo после удаления → 404 без ложного «готово». - Роль/блок/режим/пробный/доступ/пределы; bool строго, битый JSON → 400, undo после удаления → 404 без ложного «готово».
- `perform`/`undo` пишут `audit_log`. - `perform`/`undo` пишут `audit_log`.
- Тесты: `tests/test_admin_actions.py` — 5 passed. UI-тост — остаток. - Тесты: `tests/test_admin_actions.py` — 6 passed; UI (блок/undo/ошибка/вкладка) — 7.
- Само-разжалование/само-блокировка — 400; read_only себе можно.
## 5. Следующий шаг ## 5. Следующий шаг
+1
View File
@@ -12,6 +12,7 @@
- P0.1 — прод-бэкап `2026-11-06_1632.gz` (2,7 МБ gz / 12 МБ), `integrity_check=ok`, users 24, messages 5397; `SMETA_USER/PASS` заданы (env-вход — реальный); индекс на копии 46 мс. Админка на копии открыта (`/admin` 200, users/stats/overview 200). Осталось: 5 вопросов владельца. - P0.1 — прод-бэкап `2026-11-06_1632.gz` (2,7 МБ gz / 12 МБ), `integrity_check=ok`, users 24, messages 5397; `SMETA_USER/PASS` заданы (env-вход — реальный); индекс на копии 46 мс. Админка на копии открыта (`/admin` 200, users/stats/overview 200). Осталось: 5 вопросов владельца.
- P0.2 — выравнивание сделано; pre-release `feat/topup` проверен: 155 тестов зелёные, отчёт `docs/ADMIN_V2_TOPUP_PRERELEASE.md`; **релиз не начинался** (нужен go/no-go и тест-магазин). - P0.2 — выравнивание сделано; pre-release `feat/topup` проверен: 155 тестов зелёные, отчёт `docs/ADMIN_V2_TOPUP_PRERELEASE.md`; **релиз не начинался** (нужен go/no-go и тест-магазин).
- **P0.5 — готово:** спайк в `sandbox/admin-spike/`; Preact+htm: 8,7 КБ gzip, 106 строк, 37,2 мс; vanilla: 3,3 КБ, 116 строк, 34,5 мс; CSP 0 ошибок у обоих; решение — Preact+htm, fallback vanilla; ревью Зайкой 3 круга, последний без дефектов. `docs/ADMIN_V2_DECISIONS.md`. - **P0.5 — готово:** спайк в `sandbox/admin-spike/`; Preact+htm: 8,7 КБ gzip, 106 строк, 37,2 мс; vanilla: 3,3 КБ, 116 строк, 34,5 мс; CSP 0 ошибок у обоих; решение — Preact+htm, fallback vanilla; ревью Зайкой 3 круга, последний без дефектов. `docs/ADMIN_V2_DECISIONS.md`.
- **P2.8 — готово:** `admin_actions` + undo; UI-кнопки блок/режим/роль/агент и тост «Отменить»; ошибка не оставляет чужой undo, вкладка сохраняется, тост переживает сбой перезагрузки; само-роль/блок запрещены; 6 backend + 7 UI тестов.
- **P2.8 — частично:** `admin_actions` + undo для роли/блока/режима/пробного/доступа/пределов; идемпотентность, проверка bool/JSON, отказ после удаления, аудит; 5 тестов. UI-тост «Отменить» — остаток. - **P2.8 — частично:** `admin_actions` + undo для роли/блока/режима/пробного/доступа/пределов; идемпотентность, проверка bool/JSON, отказ после удаления, аудит; 5 тестов. UI-тост «Отменить» — остаток.
- **P2.7 — готово:** карточка клиента + drawer, 6 вопросов, lazy-вкладки (диалоги/счёт/файлы/история), Escape/клик по фону, удалённый по исходному адресу; 3 API + 4 UI теста. Зайка P1 (loading/empty, files 100+) исправлены. - **P2.7 — готово:** карточка клиента + drawer, 6 вопросов, lazy-вкладки (диалоги/счёт/файлы/история), Escape/клик по фону, удалённый по исходному адресу; 3 API + 4 UI теста. Зайка P1 (loading/empty, files 100+) исправлены.
- **P2.6b — готово:** таблица клиентов v2 (6 колонок), поиск/статус/пагинация, URL-состояние, ошибка с «Повторить», мобильный скролл без разъезда страницы; 3 UI-теста. Зайка P1 (URL-состояние, тавтологичный мобильный тест) исправлены. - **P2.6b — готово:** таблица клиентов v2 (6 колонок), поиск/статус/пагинация, URL-состояние, ошибка с «Повторить», мобильный скролл без разъезда страницы; 3 UI-теста. Зайка P1 (URL-состояние, тавтологичный мобильный тест) исправлены.
+5 -1
View File
@@ -9,6 +9,10 @@ export async function api(path, opts = {}) {
if (opts.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json'; if (opts.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
const r = await fetch(path, {...opts, headers}); const r = await fetch(path, {...opts, headers});
if (r.status === 401 || r.status === 403) throw new ApiError(r.status, 'Нужен вход оператора'); if (r.status === 401 || r.status === 403) throw new ApiError(r.status, 'Нужен вход оператора');
if (!r.ok) throw new ApiError(r.status, 'Ошибка ' + r.status); if (!r.ok) {
let detail = '';
try { detail = String((await r.json()).detail || ''); } catch (e) { /* не JSON */ }
throw new ApiError(r.status, detail || ('Ошибка ' + r.status));
}
return r.json(); return r.json();
} }
+49 -3
View File
@@ -1,8 +1,9 @@
import { h } from '/static/admin2/vendor/preact.module.js'; import { h } from '/static/admin2/vendor/preact.module.js';
import { useEffect, useState } from '/static/admin2/vendor/hooks.module.js'; import { useEffect, useRef, useState } from '/static/admin2/vendor/hooks.module.js';
import htm from '/static/admin2/vendor/htm.module.js'; import htm from '/static/admin2/vendor/htm.module.js';
import { api } from '/static/admin2/api.js'; import { api } from '/static/admin2/api.js';
import { Drawer } from '/static/admin2/ui/drawer.js'; import { Drawer } from '/static/admin2/ui/drawer.js';
import { Toast } from '/static/admin2/ui/toast.js';
const html = htm.bind(h); const html = htm.bind(h);
const rub = (v) => v == null ? '—' : Number(v).toLocaleString('ru-RU', const rub = (v) => v == null ? '—' : Number(v).toLocaleString('ru-RU',
@@ -17,15 +18,24 @@ export function CustomerDrawer({ email, onClose }) {
const [rows, setRows] = useState([]); const [rows, setRows] = useState([]);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [reload, setReload] = useState(0);
const [undoId, setUndoId] = useState(null);
const [notice, setNotice] = useState('');
const [busy, setBusy] = useState(false);
const prevEmail = useRef(email);
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
setCard(null); setError(''); setTab('overview'); setRows([]); setLoading(false); const switched = prevEmail.current !== email;
prevEmail.current = email;
setCard(null); setError('');
if (switched) { setTab('overview'); setRows([]); }
setLoading(false);
api('/api/admin/v2/customers/' + encodeURIComponent(email)) api('/api/admin/v2/customers/' + encodeURIComponent(email))
.then((d) => { if (alive) setCard(d); }) .then((d) => { if (alive) setCard(d); })
.catch((e) => { if (alive) setError(e.message || 'Не удалось загрузить'); }); .catch((e) => { if (alive) setError(e.message || 'Не удалось загрузить'); });
return () => { alive = false; }; return () => { alive = false; };
}, [email]); }, [email, reload]);
useEffect(() => { useEffect(() => {
if (tab === 'overview' || !card) return; if (tab === 'overview' || !card) return;
@@ -39,14 +49,50 @@ export function CustomerDrawer({ email, onClose }) {
return () => { alive = false; }; return () => { alive = false; };
}, [tab, card, email]); }, [tab, card, email]);
const act = async (action, value, label) => {
setBusy(true); setNotice(''); setUndoId(null);
try {
const r = await api('/api/admin/v2/customers/' + encodeURIComponent(email) + '/action',
{method: 'POST', body: JSON.stringify({action, value})});
setUndoId(r.id); setNotice(label); setReload((n) => n + 1);
} catch (e) {
setNotice(e.message || 'Не выполнено');
} finally { setBusy(false); }
};
const undo = async () => {
if (!undoId) return;
setBusy(true);
try {
await api('/api/admin/v2/actions/' + undoId + '/undo', {method: 'POST'});
setNotice('Отменено'); setUndoId(null); setReload((n) => n + 1);
} catch (e) { setNotice(e.message || 'Не удалось отменить'); }
finally { setBusy(false); }
};
const title = card ? card.profile.email : 'Карточка клиента'; const title = card ? card.profile.email : 'Карточка клиента';
return html` return html`
<${Drawer} title=${title} onClose=${onClose}> <${Drawer} title=${title} onClose=${onClose}>
${error ? html`<p class="error" role="alert">${error}</p>` : null} ${error ? html`<p class="error" role="alert">${error}</p>` : null}
${notice ? html`<${Toast} message=${notice} onUndo=${undoId ? undo : null}
onClose=${() => { setNotice(''); setUndoId(null); }} />` : null}
${!card ? html`<p class="note">Загрузка…</p>` : html` ${!card ? html`<p class="note">Загрузка…</p>` : html`
<nav class="tabs">${TABS.map(([k, label]) => html` <nav class="tabs">${TABS.map(([k, label]) => html`
<button type="button" key=${k} class=${k === tab ? 'tab active' : 'tab'} <button type="button" key=${k} class=${k === tab ? 'tab active' : 'tab'}
onClick=${() => { setRows([]); setTab(k); }}>${label}</button>`)}</nav> onClick=${() => { setRows([]); setTab(k); }}>${label}</button>`)}</nav>
${!card.profile.deleted_at ? html`<div class="actions-bar">
<button type="button" disabled=${busy} onClick=${() => act('block',
{blocked: !card.profile.blocked}, card.profile.blocked ? 'Разблокирован' : 'Заблокирован')}>
${card.profile.blocked ? 'Разблокировать' : 'Заблокировать'}</button>
<button type="button" disabled=${busy} onClick=${() => act('read_only',
{read_only: !card.profile.read_only}, card.profile.read_only ? 'Работа открыта' : 'Только просмотр')}>
${card.profile.read_only ? 'Открыть работу' : 'Только просмотр'}</button>
<button type="button" disabled=${busy} onClick=${() => act('role',
{role: card.profile.role === 'admin' ? 'user' : 'admin'},
card.profile.role === 'admin' ? 'Теперь user' : 'Теперь admin')}>
${card.profile.role === 'admin' ? 'Сделать user' : 'Сделать admin'}</button>
<button type="button" disabled=${busy} onClick=${() => act('agent_access',
{agent_access: !card.profile.agent_access}, card.profile.agent_access ? 'Доступ снят' : 'Доступ выдан')}>
${card.profile.agent_access ? 'Снять агента' : 'Выдать агента'}</button>
</div>` : null}
${tab === 'overview' ? html`<div class="kv"> ${tab === 'overview' ? html`<div class="kv">
<div><span>Статус</span><b>${card.profile.deleted_at ? 'удалён' : card.profile.blocked ? 'заблокирован' : 'активен'}</b></div> <div><span>Статус</span><b>${card.profile.deleted_at ? 'удалён' : card.profile.blocked ? 'заблокирован' : 'активен'}</b></div>
<div><span>Баланс</span><b>${rub(card.account && card.account.balance_rub)}</b></div> <div><span>Баланс</span><b>${rub(card.account && card.account.balance_rub)}</b></div>
+7
View File
@@ -60,3 +60,10 @@ tr.clickable{cursor:pointer} tr.clickable:hover td{background:#f3f6ff}
.kv div{display:flex;justify-content:space-between;gap:8px;border-bottom:1px solid var(--line);padding:6px 0} .kv div{display:flex;justify-content:space-between;gap:8px;border-bottom:1px solid var(--line);padding:6px 0}
.kv span{color:var(--muted)} .kv span{color:var(--muted)}
.json{white-space:pre-wrap;font-size:12px;background:#f8fafc;padding:10px;border-radius:8px;overflow:auto} .json{white-space:pre-wrap;font-size:12px;background:#f8fafc;padding:10px;border-radius:8px;overflow:auto}
.actions-bar{display:flex;gap:6px;flex-wrap:wrap;margin:10px 0}
.actions-bar button{font:inherit;padding:6px 10px;border:1px solid var(--line);border-radius:8px;background:#fff;cursor:pointer}
.actions-bar button:disabled{opacity:.5}
.toast{display:flex;gap:8px;align-items:center;background:#ecfdf3;border:1px solid #abefc6;color:#067647;padding:8px 10px;border-radius:8px;margin:8px 0}
.toast button{font:inherit;border:0;background:transparent;color:#067647;text-decoration:underline;cursor:pointer}
.toast-close{margin-left:auto;text-decoration:none;font-size:18px}
+10
View File
@@ -0,0 +1,10 @@
import { h } from '/static/admin2/vendor/preact.module.js';
import htm from '/static/admin2/vendor/htm.module.js';
const html = htm.bind(h);
export const Toast = ({ message, onUndo, onClose }) => html`
<div class="toast" role="status">
<span>${message}</span>
${onUndo && html`<button type="button" onClick=${onUndo}>Отменить</button>`}
<button type="button" class="toast-close" onClick=${onClose} aria-label="Закрыть">×</button>
</div>`;
+13
View File
@@ -92,3 +92,16 @@ def test_undo_after_soft_delete_does_not_lie(env):
assert "не найден" in r.json()["detail"] assert "не найден" in r.json()["detail"]
# состояние не помечено undone — откат не врёт # состояние не помечено undone — откат не врёт
assert db.get_admin_action(aid)["undone_at"] is None assert db.get_admin_action(aid)["undone_at"] is None
def test_admin_cannot_demote_or_block_self(env):
db, client, h, auth = env
for action, value in (("role", {"role": "user"}), ("block", {"blocked": True})):
r = client.post("/api/admin/v2/customers/boss@x/action",
json={"action": action, "value": value}, headers=h)
assert r.status_code == 400
assert db.get_user_by_email("boss@x")["role"] == "admin"
assert db.get_user_by_email("boss@x")["blocked"] == 0
assert client.post("/api/admin/v2/customers/boss@x/action",
json={"action": "read_only", "value": {"read_only": True}},
headers=h).status_code == 200
+76 -3
View File
@@ -25,6 +25,10 @@ ROWS = [
class Handler(http.server.SimpleHTTPRequestHandler): class Handler(http.server.SimpleHTTPRequestHandler):
lazy = 0 lazy = 0
actions = []
blocked = False
fail_action = None
fail_card = False
def __init__(self, *a, **kw): def __init__(self, *a, **kw):
super().__init__(*a, directory=str(ROOT), **kw) super().__init__(*a, directory=str(ROOT), **kw)
@@ -41,9 +45,12 @@ class Handler(http.server.SimpleHTTPRequestHandler):
return self._json({"items": [{"name": "a.txt", "size": 3}]}) return self._json({"items": [{"name": "a.txt", "size": 3}]})
if path.endswith('/history'): if path.endswith('/history'):
return self._json({"items": [{"action": "chat"}]}) return self._json({"items": [{"action": "chat"}]})
if Handler.fail_card:
return self._json({"detail": "карточка недоступна"}, status=500)
return self._json({ return self._json({
"profile": {"email": "anna@x", "agent_access": True, "profile": {"email": "anna@x", "agent_access": True,
"agent_provider": "claude", "deleted_at": None, "blocked": False}, "agent_provider": "claude", "deleted_at": None,
"blocked": Handler.blocked, "role": "user", "read_only": False},
"account": {"balance_rub": 1000.0}, "account": {"balance_rub": 1000.0},
"activity": {"last_seen": 1793000000, "messages": 2, "files": 1}}) "activity": {"last_seen": 1793000000, "messages": 2, "files": 1}})
if self.path.startswith("/api/admin/v2/customers"): if self.path.startswith("/api/admin/v2/customers"):
@@ -63,9 +70,22 @@ class Handler(http.server.SimpleHTTPRequestHandler):
self.wfile.write(data); return self.wfile.write(data); return
return super().do_GET() return super().do_GET()
def _json(self, obj): def do_POST(self):
n = int(self.headers.get('Content-Length') or 0)
body = self.rfile.read(n).decode() if n else ''
Handler.actions.append({"path": self.path, "body": body})
if self.path.endswith('/undo'):
Handler.blocked = False
return self._json({"ok": True})
if Handler.fail_action and Handler.fail_action in body:
return self._json({"detail": "провал действия"}, status=500)
if '"block"' in body:
Handler.blocked = True
return self._json({"ok": True, "id": 7})
def _json(self, obj, status=200):
data = json.dumps(obj).encode() data = json.dumps(obj).encode()
self.send_response(200); self.send_header("Content-Type", "application/json") self.send_response(status); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers() self.send_header("Content-Length", str(len(data))); self.end_headers()
self.wfile.write(data) self.wfile.write(data)
@@ -150,3 +170,56 @@ def test_drawer_opens_tabs_and_closes(browser, site):
page.keyboard.press("Escape") page.keyboard.press("Escape")
page.wait_for_selector(".drawer", state="detached") page.wait_for_selector(".drawer", state="detached")
page.close() page.close()
def test_block_action_and_undo(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.wait_for_selector("tr.clickable")
page.locator("tr.clickable").first.click()
page.wait_for_selector(".drawer .kv")
page.locator(".actions-bar button", has_text="Заблокировать").click()
page.wait_for_selector(".toast")
assert "Заблокирован" in page.locator(".toast").inner_text()
body = next(a["body"] for a in Handler.actions if "/action" in a["path"])
assert '"action":"block"' in body and '"blocked":true' in body
page.wait_for_selector(".actions-bar button:has-text('Разблокировать')")
page.locator(".toast button", has_text="Отменить").click()
page.wait_for_timeout(500)
assert "Отменено" in page.locator(".toast").inner_text()
assert page.locator(".actions-bar button", has_text="Заблокировать").count() == 1
assert any("/actions/7/undo" in a["path"] for a in Handler.actions)
page.close()
def test_failed_action_does_not_keep_old_undo_and_tab_survives(browser, site):
Handler.actions = []; Handler.blocked = False; Handler.fail_action = "role"; 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.locator(".tab", has_text="История").click()
page.wait_for_timeout(300)
page.locator(".actions-bar button", has_text="Сделать admin").click()
page.wait_for_selector(".toast")
assert "провал действия" in page.locator(".toast").inner_text()
assert page.locator(".toast button", has_text="Отменить").count() == 0
assert page.locator(".tab.active").inner_text() == "История"
page.close()
def test_toast_survives_failed_card_reload(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")
Handler.fail_card = True
page.locator(".actions-bar button", has_text="Заблокировать").click()
page.wait_for_selector(".drawer .error")
assert page.locator(".toast button", has_text="Отменить").count() == 1
page.close()