diff --git a/admin_api.py b/admin_api.py index 4306fba..987d496 100644 --- a/admin_api.py +++ b/admin_api.py @@ -10,6 +10,7 @@ import admin_actions import accounts_admin import attention import customers +import feedback_admin import db import metrics import money @@ -287,6 +288,33 @@ async def undo_action(action_id: int, request: Request): raise HTTPException(400, str(e)) from e +@router.get("/feedback") +async def feedback_list(request: Request, status: str = "", category: str = "", + page: int = 1, per_page: int = 50): + require_admin(request) + return await asyncio.to_thread(feedback_admin.listing, status, category, page, per_page) + + +@router.post("/feedback/{feedback_id}/status") +async def feedback_status(feedback_id: int, request: Request): + user = require_admin(request) + try: + body = await request.json() + if not isinstance(body, dict): + raise ValueError + except ValueError: + raise HTTPException(400, "тело — JSON-объект") from None + try: + ok = await asyncio.to_thread(feedback_admin.set_status, feedback_id, body.get("status")) + except ValueError as e: + raise HTTPException(400, str(e)) from e + if not ok: + raise HTTPException(404, "Жалоба не найдена") + db.log_action(user, "feedback_status", "POST", + f"/api/admin/v2/feedback/{feedback_id}/status", detail=str(body.get("status"))) + return {"ok": True, "id": feedback_id, "status": body.get("status")} + + @router.get("/accounts") async def accounts_list(request: Request, q: str = "", status: str = "", page: int = 1, per_page: int = 50): diff --git a/db.py b/db.py index 8ff856e..3db25a4 100644 --- a/db.py +++ b/db.py @@ -128,11 +128,12 @@ def ping(): def save_feedback(username: str, tab_id: str, comment: str, answer: str, category: str | None = None, source: str | None = None): """Жалоба пользователя на ответ ассистента (кнопка «сообщить об ошибке»).""" + status = "resolved" if category == "praise" else "new" with _conn() as conn: conn.execute( - "INSERT INTO feedback (timestamp, username, tab_id, comment, answer, category, source) " - "VALUES (?, ?, ?, ?, ?, ?, ?)", - (time.time(), username, tab_id, comment, answer, category, source), + "INSERT INTO feedback (timestamp, username, tab_id, comment, answer, category, source, status) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + (time.time(), username, tab_id, comment, answer, category, source, status), ) diff --git a/docs/ADMIN_V2_BASELINE.md b/docs/ADMIN_V2_BASELINE.md index 77d99ee..0530a1e 100644 --- a/docs/ADMIN_V2_BASELINE.md +++ b/docs/ADMIN_V2_BASELINE.md @@ -277,7 +277,7 @@ - `/api/feedback` валидирует категорию; чат: 4 кнопки, `source=chat`. - `attention:feedback:new` — новые жалобы в очереди. - Тесты: `tests/test_feedback_category.py` — 5 (old-schema миграция, praise, статус); чат-кнопки — 28 вместе с metrics. -- P4.1: v2-экран разбора и статусы new/resolved/deferred/ignored — остаток; старая админка уже умеет «Разобрано». +- P4.1: v2-экран «Работа» со статусами; похвала сразу resolved; ответ под комментарием; P4.1a (`feedback_since`, подпись) — ждёт владельца. ## 5. Следующий шаг diff --git a/feedback_admin.py b/feedback_admin.py new file mode 100644 index 0000000..5bb5b97 --- /dev/null +++ b/feedback_admin.py @@ -0,0 +1,34 @@ +"""Жалобы v2: разбор в два клика, без потери старых NULL.""" +from __future__ import annotations + +STATUSES = {"new", "resolved", "deferred", "ignored"} +CATEGORIES = {"wrong_answer", "off_topic", "failure", "praise"} + + +def listing(status: str = "", category: str = "", page: int = 1, + per_page: int = 50) -> dict: + import db + status = (status or "").strip() + category = (category or "").strip() + page = max(1, int(page)); per_page = max(1, min(int(per_page), 200)) + where, args = [], [] + if status: + where.append("status = ?"); args.append(status) + if category: + where.append("category = ?"); args.append(category) + sql = (" WHERE " + " AND ".join(where)) if where else "" + with db._conn() as conn: + total = conn.execute(f"SELECT COUNT(*) AS n FROM feedback{sql}", args).fetchone()["n"] + rows = conn.execute( + "SELECT id, timestamp, username, tab_id, comment, answer, category, source, status " + f"FROM feedback{sql} ORDER BY id DESC LIMIT ? OFFSET ?", + args + [per_page, (page - 1) * per_page]).fetchall() + return {"items": [dict(r) for r in rows], "total": total, "page": page, + "per_page": per_page} + + +def set_status(feedback_id: int, status: str) -> bool: + import db + if status not in STATUSES: + raise ValueError("неизвестный статус") + return db.set_feedback_status(feedback_id, status) diff --git a/static/admin2/app.js b/static/admin2/app.js index ca57002..ef1892d 100644 --- a/static/admin2/app.js +++ b/static/admin2/app.js @@ -4,6 +4,7 @@ import { SECTIONS, sectionFromPath, hrefFor } from '/static/admin2/router.js'; import { DayPage } from '/static/admin2/pages/day.js'; import { CustomersPage } from '/static/admin2/pages/customers.js'; import { MoneyPage } from '/static/admin2/pages/money.js'; +import { WorkPage } from '/static/admin2/pages/work.js'; const html = htm.bind(h); const TITLES = { @@ -29,7 +30,8 @@ const App = () => html`

${title}

${subtitle}

${section === 'today' ? html`<${DayPage} />` : section === 'customers' ? html`<${CustomersPage} />` - : section === 'money' ? html`<${MoneyPage} />` : html` + : section === 'money' ? html`<${MoneyPage} />` + : section === 'work' ? html`<${WorkPage} />` : html`

Раздел готовится

Данные и действия подключит следующий этап.

diff --git a/static/admin2/pages/work.js b/static/admin2/pages/work.js new file mode 100644 index 0000000..45f40df --- /dev/null +++ b/static/admin2/pages/work.js @@ -0,0 +1,67 @@ +import { h } from '/static/admin2/vendor/preact.module.js'; +import { useEffect, useState } from '/static/admin2/vendor/hooks.module.js'; +import htm from '/static/admin2/vendor/htm.module.js'; +import { api } from '/static/admin2/api.js'; +import { Table } from '/static/admin2/ui/table.js'; + +const html = htm.bind(h); +const CAT = {wrong_answer: 'неверный ответ', off_topic: 'не по делу', failure: 'сбой', + praise: 'похвала'}; +const ST = {new: 'новое', resolved: 'разобрано', deferred: 'отложено', ignored: 'игнор'}; +const when = (ts) => new Date(ts * 1000).toLocaleString('ru-RU'); + +export function WorkPage() { + const [status, setStatus] = useState('new'); + const [category, setCategory] = useState(''); + const [page, setPage] = useState(1); + const [data, setData] = useState(null); + const [error, setError] = useState(''); + const [reload, setReload] = useState(0); + + useEffect(() => { + let alive = true; + const p = new URLSearchParams({page: String(page), per_page: '50'}); + if (status) p.set('status', status); + if (category) p.set('category', category); + api('/api/admin/v2/feedback?' + p).then((d) => { + if (alive) { setData(d); setError(''); } + }).catch((e) => { if (alive) setError(e.message || 'Жалобы не загрузились'); }); + return () => { alive = false; }; + }, [status, category, page, reload]); + + const mark = async (id, next) => { + try { + await api('/api/admin/v2/feedback/' + id + '/status', + {method: 'POST', body: JSON.stringify({status: next})}); + setReload((n) => n + 1); + } catch (e) { setError(e.message || 'Не удалось разобрать'); } + }; + + const columns = [ + {key: 'timestamp', label: 'Когда', render: (r) => when(r.timestamp)}, + {key: 'username', label: 'Клиент'}, + {key: 'category', label: 'Категория', render: (r) => CAT[r.category] || 'без разбора'}, + {key: 'comment', label: 'Комментарий', render: (r) => html`
+ ${r.comment || 'без текста'}${r.answer ? html`${String(r.answer).slice(0, 160)}` : null}
`}, + {key: 'status', label: 'Статус', render: (r) => html`${ST[r.status] || r.status}`}, + {key: 'actions', label: 'Действие', render: (r) => html`
+ +
`}, + ]; + + return html` +
+ + + ${data ? 'Всего: ' + data.total : ''} + + +
+ ${error ? html`` : null} + ${data ? html`<${Table} columns=${columns} rows=${data.items.map((r) => ({...r, key: r.id}))} + empty="Жалоб нет" />` : html`
Загрузка…
`}`; +} diff --git a/static/admin2/styles.css b/static/admin2/styles.css index 9929e07..c60f679 100644 --- a/static/admin2/styles.css +++ b/static/admin2/styles.css @@ -79,3 +79,6 @@ tr.clickable{cursor:pointer} tr.clickable:hover td{background:#f3f6ff} .s-refunded{background:#f2f4f7;color:#667085}.s-canceled{background:#fde8e7;color:#b42318} .s-low{background:#fff4e5;color:#b54708}.s-ok{background:#e7f6ec;color:#067647} + +.s-new{background:#fff4e5;color:#b54708}.s-resolved{background:#e7f6ec;color:#067647} +.s-deferred,.s-ignored{background:#f2f4f7;color:#667085} diff --git a/tests/test_admin_v2_work.py b/tests/test_admin_v2_work.py new file mode 100644 index 0000000..668a3ea --- /dev/null +++ b/tests/test_admin_v2_work.py @@ -0,0 +1,83 @@ +"""P4.1: v2 жалобы — таблица, категория, разбор в один клик.""" +import http.server +import json +import socketserver +import sys +import threading +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)); sys.path.insert(0, str(ROOT / "tests")) +pytest.importorskip("playwright.sync_api", reason="playwright не установлен") +from test_admin_design_ui import browser # noqa: E402,F401 + +ROWS = [ + {"id": 1, "timestamp": 1793000000, "username": "a@x", "comment": "старая", + "answer": "", "category": None, "source": None, "status": "new"}, + {"id": 2, "timestamp": 1793000001, "username": "b@x", "comment": "не то", + "answer": "", "category": "off_topic", "source": "chat", "status": "new"}, +] + + +class Handler(http.server.SimpleHTTPRequestHandler): + calls = [] + resolved = set() + + def __init__(self, *a, **kw): + super().__init__(*a, directory=str(ROOT), **kw) + + def do_GET(self): + from urllib.parse import urlparse + if urlparse(self.path).path == "/api/admin/v2/feedback": + items = [r for r in ROWS if r["id"] not in Handler.resolved] + return self._json({"items": items, "total": len(items), "page": 1, "per_page": 50}) + if self.path == "/admin/v2" or self.path.startswith("/admin/v2/"): + data = (ROOT / "static/admin2/index.html").read_bytes() + self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(data))); self.end_headers() + self.wfile.write(data); return + return super().do_GET() + + def do_POST(self): + n = int(self.headers.get('Content-Length') or 0) + self.rfile.read(n) + Handler.calls.append(self.path) + if "/feedback/" in self.path: + Handler.resolved.add(int(self.path.split("/")[5])) + self._json({"ok": True}) + + def _json(self, obj): + data = json.dumps(obj).encode() + self.send_response(200); self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))); self.end_headers() + self.wfile.write(data) + + def log_message(self, *a): + return + + +@pytest.fixture(scope="module") +def site(): + class Quiet(socketserver.ThreadingTCPServer): + allow_reuse_address = True + daemon_threads = True + srv = Quiet(("127.0.0.1", 0), Handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{srv.server_address[1]}" + srv.shutdown() + + +def test_feedback_table_and_resolve(browser, site): + Handler.calls = []; Handler.resolved = set() + page = browser.new_page() + page.add_init_script("localStorage.setItem('token','t')") + page.goto(site + "/admin/v2/work") + page.wait_for_selector("table tbody tr") + assert page.locator("table tbody tr").count() == 2 + assert "без разбора" in page.locator("table").inner_text() + page.locator("table button", has_text="Разобрано").first.click() + page.wait_for_function("document.querySelectorAll('table tbody tr').length === 1") + assert any("/feedback/1/status" in c for c in Handler.calls) + page.close() diff --git a/tests/test_feedback_category.py b/tests/test_feedback_category.py index e8de2c1..da9f4bc 100644 --- a/tests/test_feedback_category.py +++ b/tests/test_feedback_category.py @@ -56,6 +56,7 @@ def test_old_null_category_still_counts(env): def test_praise_does_not_raise_red_alert(env): db, client, h, attention = env db.save_feedback("joe@x", "t1", "спасибо", "a", category="praise", source="chat") + assert db.get_feedback(1)[0]["status"] == "resolved" assert db.count_feedback_new() == 0 keys = {i["key"] for i in attention.collect({}, {"accounts_total_rub": 0})["items"]} assert "feedback:new" not in keys diff --git a/tests/test_feedback_v2_api.py b/tests/test_feedback_v2_api.py new file mode 100644 index 0000000..317428e --- /dev/null +++ b/tests/test_feedback_v2_api.py @@ -0,0 +1,58 @@ +"""P4.1: жалобы v2 — список/статус/категория, только админ.""" +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") + db.save_feedback("joe@x", "t1", "старая", "a") + db.save_feedback("joe@x", "t1", "не то", "a", category="off_topic", source="chat") + 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_list_filter_status(env): + db, client, h, auth = env + d = client.get("/api/admin/v2/feedback?status=new", headers=h).json() + assert d["total"] == 2 + assert client.get("/api/admin/v2/feedback?category=off_topic", headers=h).json()["total"] == 1 + fid = d["items"][0]["id"] + assert client.post(f"/api/admin/v2/feedback/{fid}/status", + json={"status": "resolved"}, headers=h).status_code == 200 + assert client.get("/api/admin/v2/feedback?status=new", headers=h).json()["total"] == 1 + assert client.post(f"/api/admin/v2/feedback/{fid}/status", + json={"status": "nope"}, headers=h).status_code == 400 + assert client.post("/api/admin/v2/feedback/99999/status", + json={"status": "resolved"}, headers=h).status_code == 404 + + +def test_feedback_v2_admin_only(env): + db, client, h, auth = env + user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")} + assert client.get("/api/admin/v2/feedback", headers=user).status_code == 403 + fid = db.get_feedback(1)[0]["id"] + assert client.post(f"/api/admin/v2/feedback/{fid}/status", + json={"status": "resolved"}, headers=user).status_code == 403