diff --git a/main.py b/main.py index 583425b..6bb48e9 100644 --- a/main.py +++ b/main.py @@ -464,7 +464,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-11-10b" +APP_VERSION = "2026-11-10c" # Audit: path → action name mapping _AUDIT_MAP = [ @@ -661,6 +661,11 @@ async def security_headers_middleware(request: Request, call_next): response.headers.setdefault(k, v) if request.url.path == "/admin/v2" or request.url.path.startswith("/admin/v2/"): response.headers["Content-Security-Policy"] = ADMIN_V2_CSP + # Файлы админки v2 — без сборки и без меток версии в путях. Без явного no-cache + # браузер держал старые модули по своей эвристике, и правки «не появлялись» до + # ручной очистки кеша. no-cache не запрещает кэш: он требует перепроверку (ETag). + if request.url.path.startswith("/static/admin2/"): + response.headers["Cache-Control"] = "no-cache, must-revalidate" # Ответы API браузер не хранит: без запрета Firefox при открытии админки взял список # пользователей из своего кэша вчерашним, и новый человек был в «Диалогах», но не в # «Пользователях» (01.10.2026). setdefault — свой заголовок ручки (поток) главнее. diff --git a/static/admin2/app.js b/static/admin2/app.js index f0f991c..f3f3521 100644 --- a/static/admin2/app.js +++ b/static/admin2/app.js @@ -18,6 +18,7 @@ const TITLES = { }; const App = () => { const [section, setSection] = useState(sectionFromPath(location.pathname)); + const [version, setVersion] = useState(''); const firstRender = useRef(true); const [title, subtitle] = TITLES[section] || [SECTIONS.find(([key]) => key === section)?.[1] || 'Раздел', '']; @@ -29,6 +30,13 @@ const App = () => { return () => window.removeEventListener('popstate', onPop); }, []); + // Версия видна в меню: по ней человек понимает, что браузер взял свежий файл, + // а не старую копию из кеша. + useEffect(() => { + fetch('/api/version').then((r) => r.json()) + .then((d) => setVersion(d.version || '')).catch(() => {}); + }, []); + // Заголовок вкладки и фокус на заголовок раздела — только при переходе, не при // первой загрузке: иначе фокус отбирается у адресной строки на пустом месте. useEffect(() => { @@ -60,6 +68,7 @@ const App = () => { go(e, href)} class=${'nav-link' + (key === section ? ' active' : '')} aria-current=${key === section ? 'page' : null}>${label}`)} +
v.${version || '—'}

${title}

${subtitle}

diff --git a/static/admin2/pages/customer.js b/static/admin2/pages/customer.js index e07aa97..f4f6716 100644 --- a/static/admin2/pages/customer.js +++ b/static/admin2/pages/customer.js @@ -4,6 +4,7 @@ import htm from '/static/admin2/vendor/htm.module.js'; import { api } from '/static/admin2/api.js'; import { Drawer } from '/static/admin2/ui/drawer.js'; import { Toast } from '/static/admin2/ui/toast.js'; +import { Loading } from '/static/admin2/ui/loading.js'; const html = htm.bind(h); const rub = (v) => v == null ? '—' : Number(v).toLocaleString('ru-RU', @@ -116,7 +117,7 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) { ${error ? html`` : null} ${notice ? html`<${Toast} message=${notice} onUndo=${undoId ? undo : null} onClose=${() => { setNotice(''); setUndoId(null); }} />` : null} - ${!card ? html`

Загрузка…

` : html` + ${!card ? html`<${Loading} rows={2} />` : html` @@ -148,7 +149,7 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) {
Сообщений${card.activity.messages}
Файлов${card.activity.files}${card.activity.files_capped ? '+' : ''}
` : html`
${loading - ? html`

Загрузка…

` + ? html`<${Loading} rows={2} />` : rows.length === 0 ? html`

Пусто.

` : html`
${JSON.stringify(rows.slice(0, 20), null, 2)}
`}
`} `} diff --git a/static/admin2/pages/customers.js b/static/admin2/pages/customers.js index 5a79490..25b9df4 100644 --- a/static/admin2/pages/customers.js +++ b/static/admin2/pages/customers.js @@ -5,6 +5,7 @@ import { api } from '/static/admin2/api.js'; import { Table } from '/static/admin2/ui/table.js'; import { CustomerDrawer } from '/static/admin2/pages/customer.js'; import { Toast } from '/static/admin2/ui/toast.js'; +import { Loading } from '/static/admin2/ui/loading.js'; const html = htm.bind(h); const money = (v) => v == null ? '—' : Number(v).toLocaleString('ru-RU', @@ -66,7 +67,7 @@ export function CustomersPage() { ${error ? html`` : data ? html`<${Table} columns=${columns} rows=${data.items.map((r) => ({...r, key: r.raw_email || r.email}))} onRowClick=${(r) => setSelected(r.raw_email || r.email)} />` - : html`
Загрузка…
`} + : html`<${Loading} />`} ${selected ? html`<${CustomerDrawer} email=${selected} onClose=${() => setSelected('')} onChanged=${() => { setSelected(''); setReload((n) => n + 1); }} onDeleted=${(email) => { setSelected(''); setDeletedEmail(email); setNotice('Клиент удалён'); setReload((n) => n + 1); }} />` : null} diff --git a/static/admin2/pages/day.js b/static/admin2/pages/day.js index ada716a..83f992a 100644 --- a/static/admin2/pages/day.js +++ b/static/admin2/pages/day.js @@ -3,6 +3,7 @@ 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 { Loading } from '/static/admin2/ui/loading.js'; import { Task } from '/static/admin2/ui/task.js'; const html = htm.bind(h); @@ -35,7 +36,7 @@ export function DayPage() { }, []); if (error) return html``; - if (!data) return html`
Загрузка…
`; + if (!data) return html`<${Loading} />`; const w = data.work_24h, m = data.money, c = data.customers || {}; return html` diff --git a/static/admin2/pages/money.js b/static/admin2/pages/money.js index 02e4def..556338b 100644 --- a/static/admin2/pages/money.js +++ b/static/admin2/pages/money.js @@ -5,6 +5,7 @@ import { api } from '/static/admin2/api.js'; import { Card } from '/static/admin2/ui/card.js'; import { Bars, Line } from '/static/admin2/ui/chart.js'; import { Table } from '/static/admin2/ui/table.js'; +import { Loading } from '/static/admin2/ui/loading.js'; const html = htm.bind(h); const rub = (v) => v == null ? '—' : Number(v).toLocaleString('ru-RU', @@ -81,7 +82,7 @@ export function MoneyPage() { class=${d === days ? 'active' : ''} onClick=${() => { setDays(d); setPpage(1); }}>${d} дней`)} ${error ? html`` - : !data ? html`
Загрузка…
` : html` + : !data ? html`<${Loading} />` : html`
<${Card} title="Поступления" value=${rub(data.revenue_rub)} note=${'возвраты ' + rub(data.refunded_rub)} /> @@ -124,7 +125,7 @@ export function MoneyPage() { {key: 'status', label: 'Статус', render: (r) => html`${r.status}`}, {key: 'yk_payment_id', label: 'ID платежа'}, ]} rows=${payments.items.map((r) => ({...r, key: r.id}))} empty="Платежей за период нет" />` - : html`

Загрузка…

`} + : html`<${Loading} rows={2} />`}

Счета клиентов

diff --git a/static/admin2/pages/system.js b/static/admin2/pages/system.js index d9cfb5c..56b9104 100644 --- a/static/admin2/pages/system.js +++ b/static/admin2/pages/system.js @@ -3,6 +3,7 @@ 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 { Card } from '/static/admin2/ui/card.js'; +import { Loading } from '/static/admin2/ui/loading.js'; import { Table } from '/static/admin2/ui/table.js'; const html = htm.bind(h); @@ -34,7 +35,7 @@ export function SystemPage() { }, []); if (error) return html``; - if (!data) return html`
Загрузка…
`; + if (!data) return html`<${Loading} />`; const bad = (channels || []).filter((c) => !c.ok); return html`
diff --git a/static/admin2/pages/work.js b/static/admin2/pages/work.js index c99fd1a..49ef0c5 100644 --- a/static/admin2/pages/work.js +++ b/static/admin2/pages/work.js @@ -3,6 +3,7 @@ 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'; +import { Loading } from '/static/admin2/ui/loading.js'; const html = htm.bind(h); const CAT = {wrong_answer: 'неверный ответ', off_topic: 'не по делу', failure: 'сбой', @@ -63,7 +64,7 @@ function FeedbackTab() {
${error ? html`` : null} ${data ? html`<${Table} columns=${columns} rows=${data.items.map((r) => ({...r, key: r.id}))} - empty="Жалоб нет" />` : html`
Загрузка…
`}`; + empty="Жалоб нет" />` : html`<${Loading} rows={2} />`}`; } @@ -91,7 +92,7 @@ function Paged({ title, path, columns, search = true, extra = null, params = {}
${error ? html`` : null} ${data ? html`<${Table} columns=${columns} rows=${data.items.map((r) => ({...r, key: r.id || (r.username + r.tab_id)}))} empty="Пусто" />` - : html`
Загрузка…
`}`; + : html`<${Loading} rows={2} />`}`; } function DialogsTab() { diff --git a/static/admin2/styles.css b/static/admin2/styles.css index 9127c6d..40cc396 100644 --- a/static/admin2/styles.css +++ b/static/admin2/styles.css @@ -3,6 +3,13 @@ body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif} .shell{display:flex;min-height:100vh} .side{width:220px;background:var(--side);color:#cfd6e4;padding:18px 12px;display:flex;flex-direction:column;gap:4px} +.side-foot{margin-top:auto;padding:10px;color:#667085;font-size:11px} +@media(max-width:720px){.side-foot{display:none}} +.skeleton{display:flex;flex-direction:column;gap:10px;min-height:88px} +.sk-line{height:14px;border-radius:6px;background:linear-gradient(90deg,var(--line),#eef2f7,var(--line));background-size:200% 100%;animation:sk 1.2s ease-in-out infinite} +.sk-line:nth-child(2){width:70%}.sk-line:nth-child(3){width:45%} +@keyframes sk{0%{background-position:200% 0}100%{background-position:-200% 0}} +@media(prefers-reduced-motion:reduce){.sk-line{animation:none}} .brand{color:#fff;text-decoration:none;font-weight:700;font-size:16px;padding:6px 10px 16px} .brand span{color:#7ea2ff} .nav-link{color:#cfd6e4;text-decoration:none;padding:9px 10px;border-radius:8px} diff --git a/static/admin2/ui/loading.js b/static/admin2/ui/loading.js new file mode 100644 index 0000000..ff0db75 --- /dev/null +++ b/static/admin2/ui/loading.js @@ -0,0 +1,20 @@ +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'; + +const html = htm.bind(h); + +// Скелетон вместо слова «Загрузка»: быстрые ответы (0,2–0,4 с) не должны мигать +// надписью на каждом переключении. Показываем только если данных нет 150 мс; +// для чтения с экрана остаётся скрытое описание. +export const Loading = ({ rows = 3 }) => { + const [show, setShow] = useState(false); + useEffect(() => { + const t = setTimeout(() => setShow(true), 150); + return () => clearTimeout(t); + }, []); + if (!show) return null; + return html`
+ ${Array.from({length: Math.max(1, rows)}, (_, i) => html`
`)} +
`; +}; diff --git a/tests/test_admin_v2_e2e_api.py b/tests/test_admin_v2_e2e_api.py index c45d26c..d3bf401 100644 --- a/tests/test_admin_v2_e2e_api.py +++ b/tests/test_admin_v2_e2e_api.py @@ -46,6 +46,16 @@ def test_legacy_and_v2_sections(env): assert client.get(path, headers=h).status_code == 200, path +def test_admin2_static_revalidates(env): + """Модули админки v2 обязаны перепроверяться: без no-cache браузер держал + старые файлы по своей эвристике, и правки не появлялись после выката. + Мутация: убрать заголовок — тест упадёт.""" + client, h, db = env + r = client.get("/static/admin2/app.js") + assert r.status_code == 200 + assert "no-cache" in r.headers.get("cache-control", "") + + def test_customer_lifecycle(env): client, h, db = env import auth diff --git a/tests/test_admin_v2_visual.py b/tests/test_admin_v2_visual.py index 8d7625c..e7f7afe 100644 --- a/tests/test_admin_v2_visual.py +++ b/tests/test_admin_v2_visual.py @@ -4,6 +4,7 @@ import json import socketserver import sys import threading +import time from pathlib import Path import pytest @@ -27,6 +28,7 @@ MONEY = {"period_days": 30, "revenue_rub": 100, "refunded_rub": 0, "cost_rub": 5 # Один закрытый месяц — тот случай, на котором графики разъезжались: ширина viewBox # зависела от числа точек, и при одной точке SVG растягивался в многоэкранную полосу. FIN = {"months": [{"month": "2026-11", "revenue_rub": 0, "cost_rub": 714.31}], "days": 30} +SLOW = {"customers": 0.0} # задержка ответа, чтобы увидеть скелетон SYS = {"channels": [{"name": "database", "ok": True, "detail": "ок", "level": "fail"}], "settings": [{"key": "agent_killswitch", "value": "off"}], "history": [], "errors": {"items": [], "total": 0}, "generated_at": 1793000000} @@ -39,7 +41,10 @@ class H(http.server.SimpleHTTPRequestHandler): def do_GET(self): from urllib.parse import urlparse u = urlparse(self.path) + if u.path == "/api/admin/v2/customers" and SLOW["customers"]: + time.sleep(SLOW["customers"]) mapping = { + "/api/version": {"version": "2026-11-10c"}, "/api/admin/v2/dashboard": DASH, "/api/admin/v2/attention": {"items": [], "count": 0}, "/api/admin/v2/customers": {"items": [], "total": 0, "page": 1, "per_page": 50}, @@ -104,6 +109,26 @@ def test_sections_render(browser, site, path, title): page.close() +def test_switch_shows_skeleton_not_loading_word(browser, site): + """Пока данные идут, человек видит скелетон, а не слово «Загрузка». + + Мутация: вернуть текстовую заглушку — селектор .skeleton не найдётся.""" + SLOW["customers"] = 0.6 + page = browser.new_page(viewport={"width": 1280, "height": 800}) + try: + page.add_init_script("localStorage.setItem('token','t')") + page.goto(site + "/admin/v2") + page.wait_for_selector("h1") + page.click("a[href='/admin/v2/customers']") + page.wait_for_selector(".skeleton", timeout=1000) + assert "Загрузка" not in page.locator("main").inner_text() + page.wait_for_function("document.querySelector('main')?.innerText.includes('Всего')") + assert "Загрузка" not in page.locator("main").inner_text() + finally: + SLOW["customers"] = 0.0 + page.close() + + def test_nav_keeps_shell_without_reload(browser, site): """Переключение раздела не перезагружает страницу и не пересоздаёт левую панель.