Показывать загрузку и блокировать фильтры справочника #80
No files matched your search
@@ -1,5 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
## 2.2.1
|
||||
|
||||
- При применении фильтров справочника, переключении ППС, сортировки и размера страницы появляется заглушка «Обновляем список…». Поля, кнопки и ссылки справочника заблокированы до завершения запроса.
|
||||
- Живой поиск показывает «Идёт поиск…» и оставляет управление доступным. Ошибка или тайм-аут снимают блокировку и сохраняют предыдущие результаты; устаревшие ответы не заменяют новый список.
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- Поиск по ФИО или ссылке обновляет список с четвёртого символа. ППС, сортировка и размер страницы применяются сразу. XLSX выгружает все найденные строки с применёнными фильтрами и сортировкой.
|
||||
|
||||
@@ -728,6 +728,29 @@
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.directory__results {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.directory__loading:not([hidden]) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 3;
|
||||
display: grid;
|
||||
place-items: start center;
|
||||
padding: 32px 16px;
|
||||
color: #1f2937;
|
||||
background: rgb(255 255 255 / 92%);
|
||||
border-radius: 8px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.directory--loading :is(input:disabled, select:disabled, button:disabled, a[inert], summary[inert], .directory__direction input:disabled + span) {
|
||||
cursor: wait;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.directory__pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+49
-8
@@ -86,6 +86,8 @@
|
||||
const exportLink = document.querySelector("[data-directory-export]");
|
||||
const results = document.querySelector("[data-directory-results]");
|
||||
const pagination = document.querySelector("[data-directory-pagination]");
|
||||
const directory = form.closest(".directory");
|
||||
const overlay = directory.querySelector("[data-directory-loading]");
|
||||
const fields = ["q", "pps", "sort", "direction", "limit"];
|
||||
const readControls = () => {
|
||||
const data = new FormData(form);
|
||||
@@ -95,6 +97,28 @@
|
||||
let appliedSummary = summary.textContent;
|
||||
let timer;
|
||||
let pending;
|
||||
let lockedControls = [];
|
||||
let lockedLinks = [];
|
||||
|
||||
function setLoading(loading, blocking = false) {
|
||||
lockedControls.forEach((control) => { control.disabled = false; });
|
||||
lockedLinks.forEach((link) => { link.inert = false; });
|
||||
lockedControls = [];
|
||||
lockedLinks = [];
|
||||
overlay.hidden = !loading || !blocking;
|
||||
results.toggleAttribute("inert", loading && blocking);
|
||||
results.setAttribute("aria-busy", String(loading));
|
||||
directory.classList.toggle("directory--loading", loading && blocking);
|
||||
if (loading) {
|
||||
summary.textContent = blocking ? "Обновляем список…" : "Идёт поиск…";
|
||||
}
|
||||
if (loading && blocking) {
|
||||
lockedControls = Array.from(directory.querySelectorAll("input:not(:disabled), select:not(:disabled), button:not(:disabled)"));
|
||||
lockedLinks = Array.from(directory.querySelectorAll("a:not([inert]), summary:not([inert])"));
|
||||
lockedControls.forEach((control) => { control.disabled = true; });
|
||||
lockedLinks.forEach((link) => { link.inert = true; });
|
||||
}
|
||||
}
|
||||
|
||||
form.querySelector(".directory__filter-panel").addEventListener("invalid", (event) => {
|
||||
event.currentTarget.open = true;
|
||||
@@ -105,22 +129,24 @@
|
||||
else event.formData.delete("q");
|
||||
});
|
||||
|
||||
async function refresh() {
|
||||
async function refresh(blocking = false, manual = false) {
|
||||
const next = readControls();
|
||||
if (next.toString() === applied.toString()) {
|
||||
if (!manual && next.toString() === applied.toString()) {
|
||||
setLoading(false);
|
||||
if (summary.textContent !== appliedSummary) summary.textContent = appliedSummary;
|
||||
return;
|
||||
}
|
||||
// Keep applied additional filters even if their fields have unsubmitted edits.
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("offset");
|
||||
if (manual) url.search = new URLSearchParams(new FormData(form)).toString();
|
||||
for (const [name, value] of next) {
|
||||
if (value) url.searchParams.set(name, value);
|
||||
else url.searchParams.delete(name);
|
||||
}
|
||||
const request = new AbortController();
|
||||
pending = request;
|
||||
results.setAttribute("aria-busy", "true");
|
||||
setLoading(true, blocking);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]),
|
||||
@@ -141,25 +167,40 @@
|
||||
appliedSummary = nextSummary.textContent;
|
||||
summary.textContent = appliedSummary;
|
||||
applied = next;
|
||||
if (manual) {
|
||||
const panel = form.querySelector(".directory__filter-panel");
|
||||
panel.querySelector("summary").textContent = page.querySelector(".directory__filter-panel > summary").textContent;
|
||||
panel.open = false;
|
||||
}
|
||||
} catch (_error) {
|
||||
if (!request.signal.aborted) {
|
||||
summary.textContent = "Не удалось обновить список. Показаны предыдущие результаты.";
|
||||
}
|
||||
} finally {
|
||||
if (pending === request) {
|
||||
results.removeAttribute("aria-busy");
|
||||
setLoading(false);
|
||||
pending = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function schedule(delay = 0) {
|
||||
function schedule(delay = 0, blocking = false, manual = false) {
|
||||
clearTimeout(timer);
|
||||
pending?.abort();
|
||||
if (delay) timer = setTimeout(refresh, delay);
|
||||
else refresh();
|
||||
pending = null;
|
||||
setLoading(false);
|
||||
if (delay) {
|
||||
if (readControls().toString() !== applied.toString()) setLoading(true);
|
||||
else summary.textContent = appliedSummary;
|
||||
timer = setTimeout(() => refresh(), delay);
|
||||
} else refresh(blocking, manual);
|
||||
}
|
||||
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
schedule(0, true, true);
|
||||
});
|
||||
|
||||
search.addEventListener("input", (event) => {
|
||||
if (!event.isComposing) schedule(250);
|
||||
});
|
||||
@@ -171,7 +212,7 @@
|
||||
}
|
||||
});
|
||||
form.querySelector(".directory__toolbar").addEventListener("change", (event) => {
|
||||
if (event.target !== search) schedule();
|
||||
if (event.target !== search) schedule(0, true);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -94,6 +94,8 @@
|
||||
<p>«Год начала» — начало работы в ВШЭ. «Впервые найден» и «Последний раз найден» — даты обнаружения сотрудника в списке источника, а не даты приёма и увольнения. «Требует проверки» означает, что профиль недоступен и увольнение ещё не подтверждено.</p>
|
||||
</details>
|
||||
|
||||
<div class="directory__results">
|
||||
<div class="directory__loading" data-directory-loading hidden aria-hidden="true">Обновляем список…</div>
|
||||
<div class="directory__table-wrap" data-directory-results>
|
||||
<table class="directory-table" data-directory-table>
|
||||
<thead>
|
||||
@@ -136,6 +138,7 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="directory__pagination" data-directory-pagination>
|
||||
{% set prev_offset = filters.offset - filters.limit %}
|
||||
|
||||
+3
-3
@@ -1,3 +1,3 @@
|
||||
APP_VERSION = "2.2.0"
|
||||
FRONTEND_VERSION = "2.2.0"
|
||||
BACKEND_VERSION = "2.2.0"
|
||||
APP_VERSION = "2.2.1"
|
||||
FRONTEND_VERSION = "2.2.1"
|
||||
BACKEND_VERSION = "2.2.1"
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "miem-workers"
|
||||
version = "2.2.0"
|
||||
version = "2.2.1"
|
||||
description = "MIEM employees parser, admin API, and web admin"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
|
||||
@@ -77,7 +77,7 @@ def main():
|
||||
|
||||
filters = page.locator(".directory__filter-panel")
|
||||
expect(filters).not_to_have_attribute("open", "")
|
||||
expect(page.get_by_label("ФИО или ссылка")).to_be_hidden()
|
||||
expect(page.get_by_label("ФИО или ссылка")).to_be_visible()
|
||||
filters.locator("summary").focus()
|
||||
page.keyboard.press("Enter")
|
||||
expect(page.get_by_label("ФИО или ссылка")).to_be_visible()
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Directory request states with delayed responses; no production access.
|
||||
|
||||
Run: python tests/browser_directory_loading.py (Playwright + Chromium required).
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from tempfile import mkdtemp
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.config import Settings, get_settings
|
||||
from app.db import Base, get_db
|
||||
from app.main import app
|
||||
from app.models import Employee
|
||||
from app.security import SESSION_COOKIE, sign_session
|
||||
|
||||
|
||||
def main():
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
Base.metadata.create_all(engine)
|
||||
factory = sessionmaker(bind=engine)
|
||||
with factory() as db:
|
||||
db.add_all([
|
||||
Employee(profile_key="staff:1", canonical_url="https://www.hse.ru/staff/1",
|
||||
full_name="Иванов Иван", current_data={"positions": ["Кафедра математики"]}),
|
||||
Employee(profile_key="staff:2", canonical_url="https://www.hse.ru/staff/2",
|
||||
full_name="Петров Пётр", current_data={"positions": ["Администрация"]}),
|
||||
])
|
||||
db.commit()
|
||||
|
||||
def database():
|
||||
with factory() as db:
|
||||
yield db
|
||||
|
||||
settings = Settings(_env_file=None, session_secret="browser-loading-test-secret")
|
||||
app.dependency_overrides[get_db] = database
|
||||
app.dependency_overrides[get_settings] = lambda: settings
|
||||
client = TestClient(app)
|
||||
client.cookies.set(SESSION_COOKIE, sign_session(settings.admin_username, settings))
|
||||
pending = []
|
||||
output = Path(mkdtemp(prefix="miem-directory-loading-"))
|
||||
|
||||
def fulfill(route):
|
||||
url = urlsplit(route.request.url)
|
||||
response = client.get(url.path + ("?" + url.query if url.query else ""))
|
||||
route.fulfill(status=response.status_code, body=response.content,
|
||||
content_type=response.headers.get("content-type", "text/plain"))
|
||||
|
||||
def serve(route):
|
||||
if route.request.resource_type == "fetch" and urlsplit(route.request.url).path == "/admin/directory":
|
||||
pending.append(route)
|
||||
else:
|
||||
fulfill(route)
|
||||
|
||||
try:
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(executable_path=os.getenv("BROWSER_EXECUTABLE"))
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 1000})
|
||||
page.route("**/*", serve)
|
||||
errors = []
|
||||
page.on("pageerror", lambda error: errors.append(str(error)))
|
||||
page.goto("http://miem.test/admin/directory")
|
||||
summary = page.locator("[data-directory-summary]")
|
||||
results = page.locator("[data-directory-results]")
|
||||
overlay = page.locator("[data-directory-loading]")
|
||||
search = page.get_by_label("ФИО или ссылка")
|
||||
pps = page.get_by_label("ППС", exact=True)
|
||||
apply = page.get_by_role("button", name="Применить фильтры", include_hidden=True)
|
||||
columns = page.get_by_role("button", name="Настроить колонки")
|
||||
panel = page.locator(".directory__filter-panel")
|
||||
|
||||
# Immediate filter feedback, actual disabled controls, inert links.
|
||||
pps.check()
|
||||
expect(overlay).to_be_visible()
|
||||
expect(summary).to_have_text("Обновляем список…")
|
||||
expect(pps).to_be_disabled()
|
||||
expect(columns).to_be_disabled()
|
||||
expect(apply).to_be_disabled()
|
||||
expect(search).to_be_disabled()
|
||||
expect(page.locator("[data-directory-export]")).to_have_attribute("inert", "")
|
||||
expect(results).to_have_attribute("aria-busy", "true")
|
||||
page.wait_for_timeout(100)
|
||||
assert len(pending) == 1
|
||||
assert "pps=true" in pending[0].request.url
|
||||
page.screenshot(path=str(output / "desktop-loading.png"), full_page=True)
|
||||
page.set_viewport_size({"width": 390, "height": 844})
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= innerWidth")
|
||||
page.screenshot(path=str(output / "mobile-loading.png"), full_page=True)
|
||||
fulfill(pending.pop(0))
|
||||
expect(summary).to_have_text("Показаны 1–1 из 1")
|
||||
expect(pps).to_be_enabled()
|
||||
expect(overlay).to_be_hidden()
|
||||
expect(results).to_have_attribute("aria-busy", "false")
|
||||
assert "pps=True" in page.locator("[data-directory-export]").get_attribute("href")
|
||||
|
||||
# Live search leaves ALL controls usable, including during debounce.
|
||||
search.fill("Иван")
|
||||
expect(summary).to_have_text("Идёт поиск…")
|
||||
expect(search).to_be_enabled()
|
||||
expect(pps).to_be_enabled()
|
||||
expect(columns).to_be_enabled()
|
||||
expect(overlay).to_be_hidden()
|
||||
page.wait_for_timeout(350)
|
||||
assert len(pending) == 1
|
||||
stale = pending.pop(0)
|
||||
search.fill("Петр")
|
||||
page.wait_for_timeout(350)
|
||||
assert len(pending) == 1
|
||||
fulfill(pending.pop(0))
|
||||
expect(summary).to_have_text("Показаны 0–0 из 0")
|
||||
fulfill(stale)
|
||||
page.wait_for_timeout(100)
|
||||
expect(summary).to_have_text("Показаны 0–0 из 0")
|
||||
expect(search).to_have_value("Петр")
|
||||
|
||||
# Cancelling back to the applied query must clear the indicator.
|
||||
search.fill("Петров")
|
||||
page.wait_for_timeout(350)
|
||||
stale = pending.pop(0)
|
||||
search.fill("Петр")
|
||||
expect(summary).to_have_text("Показаны 0–0 из 0")
|
||||
fulfill(stale)
|
||||
page.wait_for_timeout(350)
|
||||
assert not pending
|
||||
expect(results).to_have_attribute("aria-busy", "false")
|
||||
|
||||
# Manual submission serializes values BEFORE disabling controls.
|
||||
panel.locator("summary").click()
|
||||
panel.locator('[name="has_email"]').select_option("true")
|
||||
apply.click()
|
||||
expect(apply).to_be_disabled()
|
||||
expect(overlay).to_be_visible()
|
||||
page.wait_for_timeout(100)
|
||||
assert len(pending) == 1
|
||||
assert "has_email=true" in pending[0].request.url and "pps=true" in pending[0].request.url
|
||||
fulfill(pending.pop(0))
|
||||
expect(overlay).to_be_hidden()
|
||||
expect(panel.locator("summary")).to_contain_text("применены")
|
||||
assert "has_email=true" in page.url
|
||||
|
||||
# Failure preserves results and releases every lock; retry works.
|
||||
pps.uncheck()
|
||||
expect(overlay).to_be_visible()
|
||||
page.wait_for_timeout(100)
|
||||
pending.pop(0).fulfill(status=503, body="unavailable")
|
||||
expect(summary).to_contain_text("Не удалось обновить список")
|
||||
expect(overlay).to_be_hidden()
|
||||
expect(pps).to_be_enabled()
|
||||
expect(columns).to_be_enabled()
|
||||
expect(search).to_be_enabled()
|
||||
expect(page.locator("[data-directory-export]")).not_to_have_attribute("inert", "")
|
||||
panel.locator("summary").click()
|
||||
apply.click()
|
||||
page.wait_for_timeout(100)
|
||||
fulfill(pending.pop(0))
|
||||
expect(summary).to_have_text("Показаны 0–0 из 0")
|
||||
expect(overlay).to_be_hidden()
|
||||
assert not errors, errors
|
||||
browser.close()
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
client.close()
|
||||
engine.dispose()
|
||||
print(f"Directory loading checks passed; screenshots: {output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+1
-1
@@ -22,7 +22,7 @@ def test_health_returns_versions():
|
||||
response = TestClient(app).get("/api/health")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["backend_version"] == "2.2.0"
|
||||
assert response.json()["backend_version"] == "2.2.1"
|
||||
|
||||
|
||||
def test_api_employees_and_stats_require_admin_session():
|
||||
|
||||
@@ -230,7 +230,7 @@ def test_public_page_data_minimization_and_safe_links(db_session, export):
|
||||
assert "javascript:" not in fragment.text and "private@example.org" not in fragment.text
|
||||
assert "javascript:" not in response.text and "private@example.org" not in response.text
|
||||
assert "/admin/employees/" not in response.text and "/admin/logout" not in response.text
|
||||
assert "Backend 2.2.0 · Frontend 2.2.0" in response.text
|
||||
assert "Backend 2.2.1 · Frontend 2.2.1" in response.text
|
||||
assert "Вход в систему" in response.text
|
||||
assert client.get("/admin/directory", follow_redirects=False).status_code in (302, 303, 401, 403)
|
||||
assert "Сотрудники не найдены" in client.get("/admin/council?q=missing").text
|
||||
|
||||
Reference in new issue
Block a user