fix(админка): свежие файлы без ручной чистки кеша, скелетон вместо «Загрузки»

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
anor
2026-11-10 01:26:08 +10:00
co-authored by Claude Code
parent 40dcb44a7c
commit 55aca56b3f
12 changed files with 92 additions and 10 deletions
+6 -1
View File
@@ -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 — свой заголовок ручки (поток) главнее.
+9
View File
@@ -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 = () => {
<a key=${key} href=${href} onClick=${(e) => go(e, href)}
class=${'nav-link' + (key === section ? ' active' : '')}
aria-current=${key === section ? 'page' : null}>${label}</a>`)}
<div class="side-foot">v.${version || '—'}</div>
</nav>
<main class="main">
<header class="top"><div><h1 tabIndex="-1">${title}</h1><p>${subtitle}</p></div></header>
+3 -2
View File
@@ -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`<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`<${Loading} rows={2} />` : html`
<nav class="tabs">${TABS.map(([k, label]) => html`
<button type="button" key=${k} class=${k === tab ? 'tab active' : 'tab'}
onClick=${() => { setRows([]); setTab(k); }}>${label}</button>`)}</nav>
@@ -148,7 +149,7 @@ export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) {
<div><span>Сообщений</span><b>${card.activity.messages}</b></div>
<div><span>Файлов</span><b>${card.activity.files}${card.activity.files_capped ? '+' : ''}</b></div>
</div>` : html`<div class="tab-body">${loading
? html`<p class="note">Загрузка…</p>`
? html`<${Loading} rows={2} />`
: rows.length === 0 ? html`<p class="note">Пусто.</p>`
: html`<pre class="json">${JSON.stringify(rows.slice(0, 20), null, 2)}</pre>`}</div>`}
`}
+2 -1
View File
@@ -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`<div class="card error" role="alert">${error}
<button type="button" onClick=${() => { setError(''); setData(null); setAttempt(a => a + 1); }}>Повторить</button></div>`
: 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`<div class="card">Загрузка…</div>`}
: 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}
+2 -1
View File
@@ -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`<div class="card error" role="alert">${error}</div>`;
if (!data) return html`<div class="card">Загрузка…</div>`;
if (!data) return html`<${Loading} />`;
const w = data.work_24h, m = data.money, c = data.customers || {};
return html`
+3 -2
View File
@@ -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} дней</button>`)}
</div>
${error ? html`<div class="card error" role="alert">${error}</div>`
: !data ? html`<div class="card">Загрузка…</div>` : html`
: !data ? html`<${Loading} />` : html`
<div class="grid">
<${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`<span class=${'badge s-' + r.status}>${r.status}</span>`},
{key: 'yk_payment_id', label: 'ID платежа'},
]} rows=${payments.items.map((r) => ({...r, key: r.id}))} empty="Платежей за период нет" />`
: html`<p class="note">Загрузка…</p>`}
: html`<${Loading} rows={2} />`}
</section>
<section class="card accounts">
<h2>Счета клиентов</h2>
+2 -1
View File
@@ -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`<div class="card error" role="alert">${error}</div>`;
if (!data) return html`<div class="card">Загрузка…</div>`;
if (!data) return html`<${Loading} />`;
const bad = (channels || []).filter((c) => !c.ok);
return html`
<div class="grid">
+3 -2
View File
@@ -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() {
</div>
${error ? html`<div class="card error" role="alert">${error}</div>` : null}
${data ? html`<${Table} columns=${columns} rows=${data.items.map((r) => ({...r, key: r.id}))}
empty="Жалоб нет" />` : html`<div class="card">Загрузка…</div>`}`;
empty="Жалоб нет" />` : html`<${Loading} rows={2} />`}`;
}
@@ -91,7 +92,7 @@ function Paged({ title, path, columns, search = true, extra = null, params = {}
</div>
${error ? html`<div class="card error" role="alert">${error}</div>` : null}
${data ? html`<${Table} columns=${columns} rows=${data.items.map((r) => ({...r, key: r.id || (r.username + r.tab_id)}))} empty="Пусто" />`
: html`<div class="card">Загрузка…</div>`}`;
: html`<${Loading} rows={2} />`}`;
}
function DialogsTab() {
+7
View File
@@ -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}
+20
View File
@@ -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`<div class="card skeleton" role="status" aria-label="Загружаем раздел">
${Array.from({length: Math.max(1, rows)}, (_, i) => html`<div class="sk-line" key=${i}></div>`)}
</div>`;
};
+10
View File
@@ -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
+25
View File
@@ -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):
"""Переключение раздела не перезагружает страницу и не пересоздаёт левую панель.