From 33240f6ddd3d70e8f904305448f2dc5920fcdebe Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 6 Nov 2026 21:23:53 +1000 Subject: [PATCH] =?UTF-8?q?feat(=D0=B0=D0=B4=D0=BC=D0=B8=D0=BD=D0=BA=D0=B0?= =?UTF-8?q?):=20=D0=9C=D0=BE=D0=B9=20=D0=B4=D0=B5=D0=BD=D1=8C=20=D1=81=20?= =?UTF-8?q?=D0=BE=D1=87=D0=B5=D1=80=D0=B5=D0=B4=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- admin_api.py | 4 +- docs/ADMIN_V2_BASELINE.md | 8 ++ docs/PLAN_2026-11-06_admin_v2.md | 1 + static/admin2/api.js | 14 ++++ static/admin2/app.js | 10 ++- static/admin2/pages/day.js | 64 +++++++++++++++ static/admin2/styles.css | 14 ++++ static/admin2/ui/card.js | 11 +++ static/admin2/ui/task.js | 32 ++++++++ static/admin2/vendor/hooks.module.js | 2 + tests/test_admin_dashboard_api.py | 3 +- tests/test_admin_v2_day.py | 118 +++++++++++++++++++++++++++ 12 files changed, 274 insertions(+), 7 deletions(-) create mode 100644 static/admin2/api.js create mode 100644 static/admin2/pages/day.js create mode 100644 static/admin2/ui/card.js create mode 100644 static/admin2/ui/task.js create mode 100644 static/admin2/vendor/hooks.module.js create mode 100644 tests/test_admin_v2_day.py diff --git a/admin_api.py b/admin_api.py index 87ffa35..d831b86 100644 --- a/admin_api.py +++ b/admin_api.py @@ -32,6 +32,7 @@ def _build(user: str) -> dict: "latency_agent_ms": work["latency"]["agent"]["median_ms"], "latency_agent_p95_ms": work["latency"]["agent"]["p95_ms"]}, "money": cash, + "customers": {"total": db.count_living_users(), "active_24h": work["people"]}, "attention": {"failures": work["failures"], "limit_hits": work["limit_hits"], "unpriced": cash.get("unpriced")}} @@ -46,8 +47,7 @@ async def ping(request: Request): async def visit(request: Request): user = require_admin(request) result = await asyncio.to_thread(db.record_admin_visit, user) - _CACHE["ts"] = 0.0 - _CACHE["data"] = None + # Кэш общий и personal-поля в него не входят: визит не должен его сбрасывать. return {"ok": True, **result} diff --git a/docs/ADMIN_V2_BASELINE.md b/docs/ADMIN_V2_BASELINE.md index db2dd62..63c70b0 100644 --- a/docs/ADMIN_V2_BASELINE.md +++ b/docs/ADMIN_V2_BASELINE.md @@ -192,6 +192,14 @@ - `/attention/{key}/done` и `/snooze`; 400 на пустое/битое тело, 404 на неизвестный ключ; done идемпотентен, пока сигнал в очереди. - Тесты: `tests/test_attention.py` — 3 passed (включая реальный snapshot без подмены). +## 4.21. P2.5a/b — «Мой день» + +- `pages/day.js`: 5 карточек; `api.js`, `ui/card.js`, `ui/task.js`; hooks Preact вендорены. +- Деньги — с бейджем «предварительно» (пополнения до P0.2 не в выручке); очередь attention с done/snooze. +- Ошибка клика видна над очередью, кнопки гаснут; предыдущий визит из `/visit`. +- Визит больше не сбрасывает кэш dashboard (personal-поля вне кэша). +- Тесты: `tests/test_admin_v2_day.py` — 2 passed; dashboard — 6. + ## 5. Следующий шаг P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания). diff --git a/docs/PLAN_2026-11-06_admin_v2.md b/docs/PLAN_2026-11-06_admin_v2.md index eaf7389..b787ce1 100644 --- a/docs/PLAN_2026-11-06_admin_v2.md +++ b/docs/PLAN_2026-11-06_admin_v2.md @@ -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.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`. +- **P2.5a/b — готово:** «Мой день» — 5 карточек (деньги, внимание, сервис, клиенты, прошлый визит), очередь с «Готово»/«1 ч», ошибки клика видны, деньги с бейджем «предварительно»; 2 UI-теста. Зайка P1 (молчащий отказ, кэш от визита, снуз без теста) исправлены. - **P2.4 — готово:** `attention.py` (failures/limits/unpriced/accounts), стабильные ключи, `attention_state` done/snooze, done снимается при исчезновении сигнала, 400 на кривое тело; 3 теста. Зайка P1 (unpriced не управлялся, 500 на теле, вечный done) исправлены. - **P2.3 — готово:** `money.summary`, `/api/admin/v2/dashboard` одним ответом, `/visit` с предыдущим визитом, кэш 15 с (общий, personal-поля вне кэша), p95 полей задержки, unpriced из счетов; 6 тестов. Зайка P1 (чужой user/last_visit в кэше, мёртвый unpriced) исправлены. - **P2.2 — готово:** `/admin/v2` + deep link `{section:path}`, `admin_api.py`/`admin_auth.py`, `/api/admin/v2/ping` admin-only, strict CSP только v2 (legacy сохраняет текущую политику), audit `admin.v2.*`; 4 теста. diff --git a/static/admin2/api.js b/static/admin2/api.js new file mode 100644 index 0000000..e645dfa --- /dev/null +++ b/static/admin2/api.js @@ -0,0 +1,14 @@ +export class ApiError extends Error { + constructor(status, message) { super(message); this.status = status; } +} + +export async function api(path, opts = {}) { + const token = localStorage.getItem('token') || ''; + const headers = {...(opts.headers || {})}; + if (token) headers.Authorization = 'Bearer ' + token; + if (opts.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json'; + const r = await fetch(path, {...opts, headers}); + if (r.status === 401 || r.status === 403) throw new ApiError(r.status, 'Нужен вход оператора'); + if (!r.ok) throw new ApiError(r.status, 'Ошибка ' + r.status); + return r.json(); +} diff --git a/static/admin2/app.js b/static/admin2/app.js index 6674f86..6bbe785 100644 --- a/static/admin2/app.js +++ b/static/admin2/app.js @@ -1,6 +1,7 @@ import { h, render } from '/static/admin2/vendor/preact.module.js'; import htm from '/static/admin2/vendor/htm.module.js'; import { SECTIONS, sectionFromPath, hrefFor } from '/static/admin2/router.js'; +import { DayPage } from '/static/admin2/pages/day.js'; const html = htm.bind(h); const TITLES = { @@ -24,10 +25,11 @@ const App = () => html`

${title}

${subtitle}

-
-

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

-

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

-
+ ${section === 'today' ? html`<${DayPage} />` : html` +
+

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

+

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

+
`}
`; diff --git a/static/admin2/pages/day.js b/static/admin2/pages/day.js new file mode 100644 index 0000000..ada716a --- /dev/null +++ b/static/admin2/pages/day.js @@ -0,0 +1,64 @@ +import { h } from '/static/admin2/vendor/preact.module.js'; +import { useState, useEffect } from '/static/admin2/vendor/hooks.module.js'; +import htm from '/static/admin2/vendor/htm.module.js'; +import { api } from '/static/admin2/api.js'; +import { Card } from '/static/admin2/ui/card.js'; +import { Task } from '/static/admin2/ui/task.js'; + +const html = htm.bind(h); +const rub = (v) => v == null ? '—' : Number(v).toLocaleString('ru-RU', {maximumFractionDigits: 2}) + ' ₽'; +const when = (ts) => ts ? new Date(ts * 1000).toLocaleString('ru-RU', + {day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit'}) : 'первый визит'; + +export function DayPage() { + const [data, setData] = useState(null); + const [items, setItems] = useState([]); + const [error, setError] = useState(''); + const [previous, setPrevious] = useState(null); + const [queueError, setQueueError] = useState(''); + + useEffect(() => { + let alive = true; + (async () => { + try { + const visit = await api('/api/admin/v2/visit', {method: 'POST'}); + if (alive) setPrevious(visit.previous); + const [dash, att] = await Promise.all([ + api('/api/admin/v2/dashboard'), api('/api/admin/v2/attention')]); + if (!alive) return; + setData(dash); setItems(att.items || []); + } catch (e) { + if (alive) setError(e.message || 'Не удалось загрузить'); + } + })(); + return () => { alive = false; }; + }, []); + + if (error) return html``; + if (!data) return html`
Загрузка…
`; + + const w = data.work_24h, m = data.money, c = data.customers || {}; + return html` +
+ <${Card} title="Деньги за 30 дней" value=${rub(m.revenue_rub)} + badge=${m.topups_included === false ? 'предварительно' : null} + note=${'поток ' + rub(m.flow_rub) + ' · на счетах ' + rub(m.accounts_total_rub)} /> + <${Card} title="Требует внимания" value=${String(items.length)} + note=${items.length ? 'очередь ниже' : 'ничего срочного'} /> + <${Card} title="Сервис за сутки" value=${String(w.requests)} + note=${'сбоев ' + w.failures + ' · p95 ' + (w.latency_agent_p95_ms || '—') + ' мс'} /> + <${Card} title="Клиенты" value=${String(c.total ?? '—')} + note=${'активных за сутки ' + (c.active_24h ?? w.people)} /> + <${Card} title="С прошлого визита" value=${when(previous)} + note=${'снимок ' + new Date(data.generated_at * 1000).toLocaleTimeString('ru-RU', + {hour: '2-digit', minute: '2-digit'})} /> +
+
+

Очередь

+ ${queueError && html``} + ${items.length ? items.map((item) => html`<${Task} key=${item.key} item=${item} + onDone=${(key) => setItems((prev) => prev.filter((x) => x.key !== key))} + onError=${setQueueError} />`) + : html`

Всё спокойно.

`} +
`; +} diff --git a/static/admin2/styles.css b/static/admin2/styles.css index 0fd6c1a..6553a39 100644 --- a/static/admin2/styles.css +++ b/static/admin2/styles.css @@ -15,3 +15,17 @@ body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.45 -apple-system .card h2{margin:0 0 6px;font-size:16px} .card p{margin:0;color:var(--muted)} @media (max-width:720px){.shell{flex-direction:column}.side{width:auto;flex-direction:row;flex-wrap:wrap;align-items:center}.brand{padding:4px 10px;width:100%}.main{padding:16px}} + +.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin-bottom:16px} +.card-head{display:flex;justify-content:space-between;gap:8px;align-items:center} +.card-head h2{margin:0;font-size:14px;color:var(--muted);font-weight:600} +.value{font-size:24px;font-weight:700;margin:8px 0 4px;font-variant-numeric:tabular-nums} +.badge{background:#fff4e5;color:#b54708;border-radius:999px;padding:2px 8px;font-size:11px} +.note{color:var(--muted);margin:0;font-size:12px} +.queue{margin-top:8px} +.task{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;padding:10px 0;border-top:1px solid var(--line)} +.task:first-of-type{border-top:0} +.task p{margin:2px 0 0;color:var(--muted);font-size:12px} +.task-actions{display:flex;gap:6px;flex-shrink:0} +.task button{font:inherit;padding:6px 10px;border:1px solid var(--line);border-radius:8px;background:#fff;cursor:pointer} +.error{color:#b42318;border-color:#fda29b} diff --git a/static/admin2/ui/card.js b/static/admin2/ui/card.js new file mode 100644 index 0000000..d519b8f --- /dev/null +++ b/static/admin2/ui/card.js @@ -0,0 +1,11 @@ +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 Card = ({ title, value, note, children, badge }) => html` +
+

${title}

${badge && html`${badge}`}
+ ${value != null && html`
${value}
`} + ${note && html`

${note}

`} + ${children} +
`; diff --git a/static/admin2/ui/task.js b/static/admin2/ui/task.js new file mode 100644 index 0000000..253913e --- /dev/null +++ b/static/admin2/ui/task.js @@ -0,0 +1,32 @@ +import { h } from '/static/admin2/vendor/preact.module.js'; +import { useState } from '/static/admin2/vendor/hooks.module.js'; +import htm from '/static/admin2/vendor/htm.module.js'; +import { api } from '/static/admin2/api.js'; +const html = htm.bind(h); + +export const Task = ({ item, onDone, onError }) => { + const [busy, setBusy] = useState(false); + const run = async (path, body) => { + setBusy(true); + try { + await api(path, body ? {method: 'POST', body: JSON.stringify(body)} + : {method: 'POST'}); + onDone(item.key); + } catch (e) { + onError(e.message || 'Не удалось выполнить'); + } finally { + setBusy(false); + } + }; + return html` +
+
${item.title}

${item.detail}

+
+ + +
+
`; +}; diff --git a/static/admin2/vendor/hooks.module.js b/static/admin2/vendor/hooks.module.js new file mode 100644 index 0000000..1cdd5bb --- /dev/null +++ b/static/admin2/vendor/hooks.module.js @@ -0,0 +1,2 @@ +import{options as n}from"/static/admin2/vendor/preact.module.js";var t,r,u,i,o=0,f=[],c=n,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function d(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function h(n){return o=1,p(D,n)}function p(n,u,i){var o=d(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):D(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}))}],o.__c=r,!r.u)){var f=function(n,t,r){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(n){return!!n.__c});if(u.every(function(n){return!n.__N}))return!c||c.call(this,n,t,r);var i=o.__c.props!==n;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),c&&c.call(this,n,t,r)||i};r.u=!0;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u}e&&e.call(this,n,t,r)},r.shouldComponentUpdate=f}return o.__N||o.__}function y(n,u){var i=d(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.i=u,r.__H.__h.push(i))}function _(n,u){var i=d(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.i=u,r.__h.push(i))}function A(n){return o=5,T(function(){return{current:n}},[])}function F(n,t,r){o=6,_(function(){return"function"==typeof n?(n(t()),function(){return n(null)}):n?(n.current=t(),function(){return n.current=null}):void 0},null==r?r:r.concat(n))}function T(n,r){var u=d(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=d(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function P(n,t){c.useDebugValue&&c.useDebugValue(t?t(n):n)}function b(n){var u=d(t++,10),i=h();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function g(){var n=d(t++,11);if(!n.__){for(var u=r.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__="P"+i[0]+"-"+i[1]++}return n.__}function j(){for(var n;n=f.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(z),n.__H.__h.forEach(B),n.__H.__h=[]}catch(t){n.__H.__h=[],c.__e(t,n.__v)}}c.__b=function(n){r=null,e&&e(n)},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),s&&s(n,t)},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.i=n.__N=void 0})):(i.__h.forEach(z),i.__h.forEach(B),i.__h=[],t=0)),u=r},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.forEach(function(n){n.i&&(n.__H=n.i),n.i=void 0})),u=r=null},c.__c=function(n,t){t.some(function(n){try{n.__h.forEach(z),n.__h=n.__h.filter(function(n){return!n.__||B(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],c.__e(r,n.__v)}}),l&&l(n,t)},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{z(n)}catch(n){t=n}}),r.__H=void 0,t&&c.__e(t,r.__v))};var k="function"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,100);k&&(t=requestAnimationFrame(r))}function z(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t}function B(n){var t=r;n.__c=n.__(),r=t}function C(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return"function"==typeof t?t(n):t}export{q as useCallback,x as useContext,P as useDebugValue,y as useEffect,b as useErrorBoundary,g as useId,F as useImperativeHandle,_ as useLayoutEffect,T as useMemo,p as useReducer,A as useRef,h as useState}; +//# sourceMappingURL=hooks.module.js.map diff --git a/tests/test_admin_dashboard_api.py b/tests/test_admin_dashboard_api.py index e7045e9..10e1511 100644 --- a/tests/test_admin_dashboard_api.py +++ b/tests/test_admin_dashboard_api.py @@ -68,7 +68,8 @@ def test_dashboard_is_cached_for_15_seconds(env, monkeypatch): assert calls["n"] == 1 client.post("/api/admin/v2/visit", headers=h) assert client.get("/api/admin/v2/dashboard", headers=h).status_code == 200 - assert calls["n"] == 2 + # визит больше не сбрасывает кэш: personal-поля дописываются поверх + assert calls["n"] == 1 def test_dashboard_is_admin_only(env): diff --git a/tests/test_admin_v2_day.py b/tests/test_admin_v2_day.py new file mode 100644 index 0000000..b8d7533 --- /dev/null +++ b/tests/test_admin_v2_day.py @@ -0,0 +1,118 @@ +"""P2.5a: «Мой день» — 5 карточек, деньги с бейджем, задача закрывается в 1–2 клика.""" +import functools +import http.server +import json +import os +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 + +DASH = {"user": "boss@x", "generated_at": 1794000000, "last_visit": None, + "work_24h": {"people": 3, "requests": 20, "failures": 1, "failure_share": 0.05, + "limit_hits": 0, "latency_qa_ms": 200, "latency_qa_p95_ms": 500, + "latency_agent_ms": 3000, "latency_agent_p95_ms": 9000}, + "money": {"revenue_rub": 1000, "flow_rub": 400, "accounts_total_rub": 2500, + "topups_included": False, "unpriced": 0}, + "customers": {"total": 12, "active_24h": 3}, + "attention": {"failures": 1, "limit_hits": 0, "unpriced": 0}} +ATT = {"items": [{"key": "failures:24h", "severity": "high", "title": "Сбои", + "detail": "1 сбой", "action": "/admin/v2/work"}, + {"key": "unpriced", "severity": "medium", "title": "Без цены", + "detail": "1 прогон", "action": "/admin/v2/money"}], "count": 2} + + +class Handler(http.server.SimpleHTTPRequestHandler): + calls = [] + fail_done = False + + def __init__(self, *a, **kw): + super().__init__(*a, directory=str(ROOT), **kw) + + def do_GET(self): + if self.path.startswith("/api/admin/v2/dashboard"): + return self._json(DASH) + if self.path.startswith("/api/admin/v2/attention"): + return self._json(ATT) + 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) + body = self.rfile.read(n).decode() if n else '' + Handler.calls.append({"path": self.path, "body": body}) + if Handler.fail_done and self.path.endswith('/done'): + self.send_response(500); self.end_headers(); return + self._json({"ok": True, "previous": 1793000000, "key": "failures:24h"}) + + 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(): + Handler.calls = [] + 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_five_cards_money_badge_and_done(browser, site): + page = browser.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.add_init_script("localStorage.setItem('token','t')") + page.goto(site + "/admin/v2") + page.wait_for_selector(".grid .card") + assert page.locator(".grid .card").count() == 5 + assert "предварительно" in page.locator(".badge").first.inner_text() + assert "1\u00a0000" in page.locator(".grid").inner_text() + assert page.locator(".task").count() == 2 + assert "первый визит" not in page.locator(".grid").inner_text() + page.locator(".task button", has_text="Готово").first.click() + page.wait_for_timeout(400) + assert page.locator(".task").count() == 1 + page.locator(".task button", has_text="1 ч").click() + page.wait_for_timeout(400) + assert page.locator(".task").count() == 0 + paths = [c["path"] for c in Handler.calls] + assert any("/api/admin/v2/attention/failures%3A24h/done" in p for p in paths) + assert any("/api/admin/v2/attention/unpriced/snooze" in p for p in paths) + assert any('"minutes":60' in c["body"] for c in Handler.calls if "snooze" in c["path"]) + assert errors == [] + page.close() + + +def test_task_failure_is_visible(browser, site): + Handler.fail_done = True + Handler.calls = [] + page = browser.new_page() + page.add_init_script("localStorage.setItem('token','t')") + page.goto(site + "/admin/v2") + page.wait_for_selector(".task") + page.locator(".task button", has_text="Готово").first.click() + page.wait_for_timeout(400) + assert "Ошибка 500" in page.locator(".queue .error").inner_text() + page.close() + Handler.fail_done = False