Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ec1ad828f | ||
|
|
7f268abde1 | ||
|
|
fef738ee27 | ||
|
|
832a8a71b6 | ||
|
|
5f6997eef8 | ||
|
|
e0599b946a | ||
|
|
8d332c7d60 |
No files matched your search
@@ -1,5 +1,15 @@
|
||||
# Changelog
|
||||
|
||||
## 2.2.1
|
||||
|
||||
- При применении фильтров справочника, переключении ППС, сортировки и размера страницы появляется заглушка «Обновляем список…». Поля, кнопки и ссылки справочника заблокированы до завершения запроса.
|
||||
- Живой поиск показывает «Идёт поиск…» и оставляет управление доступным. Ошибка или тайм-аут снимают блокировку и сохраняют предыдущие результаты; устаревшие ответы не заменяют новый список.
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- Поиск по ФИО или ссылке обновляет список с четвёртого символа. ППС, сортировка и размер страницы применяются сразу. XLSX выгружает все найденные строки с применёнными фильтрами и сортировкой.
|
||||
- Кнопка «Применить фильтры» осталась внутри дополнительных фильтров. Из панели убраны видимые заголовки «Статус и данные», «Повышение квалификации» и «Период обнаружения».
|
||||
|
||||
## 2.1.1
|
||||
|
||||
- В справочнике всегда видны поиск по ФИО или ссылке, чекбокс «ППС», поле сортировки, стрелки направления и число сотрудников на странице. Остальные условия находятся в сворачиваемой панели.
|
||||
|
||||
@@ -47,7 +47,7 @@ uvicorn app.main:app --reload
|
||||
- «Сотрудники»: поиск, фильтры, сортировка, пагинация и выбор колонок. По умолчанию показаны ФИО, статус, должности, дата последнего обнаружения и внешний профиль. В диалоге колонок доступны наборы «Проверка», «Контакты» и «Все поля»; ранее сохранённый выбор сохраняется.
|
||||
- «Запуски»: история обходов, ошибки и доступный индикатор прогресса.
|
||||
|
||||
Поиск по ФИО или ссылке, ППС, сортировка и число строк видны всегда. Остальные условия находятся в «Дополнительных фильтрах». «Применить фильтры» обновляет список и возвращает на первую страницу, «Сбросить» очищает условия. «Скачать XLSX» выгружает все колонки и все строки, найденные с применёнными условиями, в выбранном порядке. Пояснения дат и статусов находятся под фильтрами.
|
||||
Поиск по ФИО или ссылке срабатывает с четвёртого символа. ППС, сортировка и число строк применяются сразу. Остальные условия находятся в «Дополнительных фильтрах» и применяются кнопкой внутри панели. Изменение условий возвращает на первую страницу, «Сбросить» очищает условия. «Скачать XLSX» выгружает все колонки и все строки, найденные с применёнными условиями, в выбранном порядке. Пояснения дат и статусов находятся под фильтрами.
|
||||
|
||||
Каталог поддерживает навигацию с клавиатуры и системный диалог колонок с Escape и возвратом фокуса. На узких экранах таблица прокручивается внутри страницы, колонка ФИО закреплена. Используется системный шрифт без внешних загрузок.
|
||||
|
||||
|
||||
+23
-8
@@ -679,14 +679,6 @@
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.directory__filter-legend {
|
||||
grid-column: 1 / -1;
|
||||
margin-bottom: 2px;
|
||||
color: #374151;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.directory__field {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
@@ -736,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;
|
||||
|
||||
+139
-5
@@ -78,6 +78,144 @@
|
||||
});
|
||||
}
|
||||
|
||||
function setupDirectoryFilters() {
|
||||
const form = document.querySelector("[data-directory-filters]");
|
||||
if (!form) return;
|
||||
const search = form.elements.q;
|
||||
const summary = document.querySelector("[data-directory-summary]");
|
||||
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);
|
||||
return new URLSearchParams(fields.map((name) => [name, data.get(name) || ""]));
|
||||
};
|
||||
let applied = readControls();
|
||||
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;
|
||||
}, true);
|
||||
form.addEventListener("formdata", (event) => {
|
||||
const text = search.value.trim();
|
||||
if (Array.from(text).length >= 4) event.formData.set("q", text);
|
||||
else event.formData.delete("q");
|
||||
});
|
||||
|
||||
async function refresh(blocking = false, manual = false) {
|
||||
const next = readControls();
|
||||
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;
|
||||
setLoading(true, blocking);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]),
|
||||
});
|
||||
if (!response.ok) throw new Error("directory request failed");
|
||||
const page = new DOMParser().parseFromString(await response.text(), "text/html");
|
||||
if (request.signal.aborted) return;
|
||||
const nextSummary = page.querySelector("[data-directory-summary]");
|
||||
const nextExport = page.querySelector("[data-directory-export]");
|
||||
const nextResults = page.querySelector("[data-directory-results]");
|
||||
const nextPagination = page.querySelector("[data-directory-pagination]");
|
||||
if (!nextSummary || !nextExport || !nextResults || !nextPagination) throw new Error("directory results missing");
|
||||
history.replaceState(history.state, "", url);
|
||||
results.replaceChildren(...nextResults.childNodes);
|
||||
pagination.replaceChildren(...nextPagination.childNodes);
|
||||
applyColumns(readColumns());
|
||||
exportLink.setAttribute("href", nextExport.getAttribute("href"));
|
||||
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) {
|
||||
setLoading(false);
|
||||
pending = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function schedule(delay = 0, blocking = false, manual = false) {
|
||||
clearTimeout(timer);
|
||||
pending?.abort();
|
||||
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);
|
||||
});
|
||||
search.addEventListener("compositionend", () => schedule(250));
|
||||
search.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter" && !event.isComposing) {
|
||||
event.preventDefault();
|
||||
schedule();
|
||||
}
|
||||
});
|
||||
form.querySelector(".directory__toolbar").addEventListener("change", (event) => {
|
||||
if (event.target !== search) schedule(0, true);
|
||||
});
|
||||
}
|
||||
|
||||
function setupProgress() {
|
||||
const panel = document.querySelector("[data-progress-panel]");
|
||||
if (!panel) return;
|
||||
@@ -148,11 +286,7 @@
|
||||
}, 4000);
|
||||
}
|
||||
|
||||
const directoryFilters = document.querySelector(".directory__filter-panel");
|
||||
directoryFilters?.addEventListener("invalid", () => {
|
||||
directoryFilters.open = true;
|
||||
}, true);
|
||||
|
||||
setupColumns();
|
||||
setupDirectoryFilters();
|
||||
setupProgress();
|
||||
})();
|
||||
+2
-2
@@ -11,7 +11,7 @@
|
||||
intro: (councilAccess ? 'Найдите сотрудника, подберите кандидатов в диссовет и проверьте публикации. '
|
||||
: 'Найдите сотрудника и изучите его профиль. ') + 'Подсказки можно повторить из меню «Как пользоваться».'},
|
||||
{id: 'employee-search', path: directory, title: 'Найдите сотрудника', region: '.directory__toolbar', tips: [
|
||||
['[name="q"]', 'Введите фамилию, часть ФИО или ссылку на профиль ВШЭ.'],
|
||||
['[name="q"]', 'Введите фамилию или ссылку на профиль ВШЭ. Поиск срабатывает с четвёртого символа.'],
|
||||
['[name="pps"]', 'Оставьте сотрудников профессорско-преподавательского состава.'],
|
||||
]},
|
||||
{id: 'employee-filters', path: directory, title: 'Уточните список', region: '.directory__filter-panel', tips: [
|
||||
@@ -25,7 +25,7 @@
|
||||
]},
|
||||
{id: 'employee-sort', path: directory, title: 'Настройте порядок списка', region: '.directory__toolbar', tips: [
|
||||
['[name="sort"]', 'Выберите поле сортировки. Стрелка вниз покажет наибольшие значения или новые даты первыми.'],
|
||||
['[name="limit"]', 'Выберите число строк и нажмите «Применить фильтры».'],
|
||||
['[name="limit"]', 'Выберите число строк. Список обновится автоматически.'],
|
||||
]},
|
||||
{id: 'employee-profile', path: directory, title: 'Откройте карточку сотрудника', region: '.directory__header', tips: [
|
||||
['[data-columns-open]', 'Выберите столбцы: например, должности, контакты и число публикаций.'],
|
||||
|
||||
@@ -7,19 +7,19 @@
|
||||
<h2 class="directory__title">Сотрудники</h2>
|
||||
{% set range_start = page.offset + 1 if page.total else 0 %}
|
||||
{% set range_end = [page.offset + page.employees|length, page.total]|min %}
|
||||
<p class="directory__summary" role="status">Показаны {{ range_start }}–{{ range_end }} из {{ page.total }}</p>
|
||||
<p class="directory__summary" role="status" data-directory-summary>Показаны {{ range_start }}–{{ range_end }} из {{ page.total }}</p>
|
||||
</div>
|
||||
<div class="directory__actions">
|
||||
<a class="button button--secondary" href="{{ export_url }}">Скачать XLSX</a>
|
||||
<a class="button button--secondary" href="{{ export_url }}" data-directory-export>Скачать XLSX</a>
|
||||
<button class="button" type="button" data-columns-open aria-controls="columns-dialog" aria-expanded="false">Настроить колонки</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% set has_extra_filters = filters.status or filters.has_email or filters.has_academic_degree or filters.started_from or filters.started_to or filters.has_training or filters.training_since_year %}
|
||||
{% set has_filters = filters.q or filters.pps or has_extra_filters %}
|
||||
<form method="get" action="/admin/directory">
|
||||
<form method="get" action="/admin/directory" data-directory-filters>
|
||||
<div class="directory__toolbar">
|
||||
<label class="directory__field directory__search">ФИО или ссылка<input class="directory__input" name="q" value="{{ filters.q }}" placeholder="Например, Иванов или hse.ru"></label>
|
||||
<label class="directory__field directory__search">ФИО или ссылка<input class="directory__input" name="q" value="{{ filters.q }}" placeholder="Введите не менее 4 символов"></label>
|
||||
<label class="directory__checkbox"><input type="checkbox" name="pps" value="true" {% if filters.pps %}checked{% endif %}> ППС</label>
|
||||
<label class="directory__field directory__sort">Сортировать по<select class="directory__input" name="sort">
|
||||
{% for value, label in [("full_name", "ФИО"), ("status", "Статус"), ("hse_start_year", "Год начала"), ("first_seen_at", "Впервые найден"), ("last_seen_at", "Последний раз найден"), ("dismissed_at", "Дата увольнения")] %}
|
||||
@@ -44,14 +44,12 @@
|
||||
<option value="{{ value }}" {% if filters.limit == value %}selected{% endif %}>{{ value }}</option>
|
||||
{% endfor %}
|
||||
</select></label>
|
||||
<button class="button" type="submit">Применить фильтры</button>
|
||||
<a class="button button--ghost" href="/admin/directory">Сбросить</a>
|
||||
</div>
|
||||
<details class="directory__filter-panel">
|
||||
<summary>Дополнительные фильтры{% if has_extra_filters %} · применены{% endif %}</summary>
|
||||
<div class="directory__filters">
|
||||
<fieldset class="directory__filter-group">
|
||||
<legend class="directory__filter-legend">Статус и данные</legend>
|
||||
<fieldset class="directory__filter-group" aria-label="Статус и данные">
|
||||
<label class="directory__field">Статус<select class="directory__input" name="status">
|
||||
<option value="" {% if not filters.status %}selected{% endif %}>Все статусы</option>
|
||||
<option value="active" {% if filters.status == "active" %}selected{% endif %}>Работает</option>
|
||||
@@ -69,8 +67,7 @@
|
||||
<option value="false" {% if filters.has_academic_degree == "false" %}selected{% endif %}>Нет учёной степени</option>
|
||||
</select></label>
|
||||
</fieldset>
|
||||
<fieldset class="directory__filter-group">
|
||||
<legend class="directory__filter-legend">Повышение квалификации</legend>
|
||||
<fieldset class="directory__filter-group" aria-label="Повышение квалификации">
|
||||
<label class="directory__field">Курсы в профиле<select class="directory__input" name="has_training">
|
||||
<option value="" {% if not filters.has_training %}selected{% endif %}>Любое</option>
|
||||
<option value="true" {% if filters.has_training == "true" %}selected{% endif %}>Есть курсы</option>
|
||||
@@ -81,8 +78,7 @@
|
||||
</label>
|
||||
<small class="directory__filter-hint" id="training-year-hint">Если указан только год, будут показаны сотрудники с курсами.</small>
|
||||
</fieldset>
|
||||
<fieldset class="directory__filter-group">
|
||||
<legend class="directory__filter-legend">Период обнаружения</legend>
|
||||
<fieldset class="directory__filter-group" aria-label="Период обнаружения">
|
||||
<label class="directory__field">От<input class="directory__input" type="date" name="started_from" value="{{ filters.started_from }}"></label>
|
||||
<label class="directory__field">До<input class="directory__input" type="date" name="started_to" value="{{ filters.started_to }}"></label>
|
||||
</fieldset>
|
||||
@@ -98,7 +94,9 @@
|
||||
<p>«Год начала» — начало работы в ВШЭ. «Впервые найден» и «Последний раз найден» — даты обнаружения сотрудника в списке источника, а не даты приёма и увольнения. «Требует проверки» означает, что профиль недоступен и увольнение ещё не подтверждено.</p>
|
||||
</details>
|
||||
|
||||
<div class="directory__table-wrap">
|
||||
<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>
|
||||
<tr>
|
||||
@@ -140,8 +138,9 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="directory__pagination">
|
||||
<div class="directory__pagination" data-directory-pagination>
|
||||
{% set prev_offset = filters.offset - filters.limit %}
|
||||
{% set next_offset = filters.offset + filters.limit %}
|
||||
{% if filters.offset > 0 %}
|
||||
|
||||
@@ -13,12 +13,12 @@
|
||||
</section>
|
||||
<section class="guide__step" data-guide-step>
|
||||
<h3 class="guide__heading" tabindex="-1">Найдите сотрудника и откройте профиль</h3>
|
||||
<p>В разделе «Сотрудники» введите в поле «ФИО или ссылка» фамилию, часть ФИО или ссылку на профиль ВШЭ. Отметьте «ППС», чтобы оставить только профессорско-преподавательский состав. Остальные условия находятся в панели «Дополнительные фильтры».</p>
|
||||
<p>Введите фамилию, часть ФИО или ссылку на профиль ВШЭ. Поиск срабатывает с четвёртого символа. Отметьте «ППС», чтобы оставить профессорско-преподавательский состав. Остальные условия находятся в панели «Дополнительные фильтры» и применяются её кнопкой.</p>
|
||||
<dl class="guide__fields">
|
||||
<dt>Статус, Email, Учёная степень</dt><dd>Ограничивают список по состоянию сотрудника и наличию сведений в профиле. Звание профессора или доцента не заменяет учёную степень.</dd>
|
||||
<dt>Повышение квалификации</dt><dd>Выберите «Есть курсы» или «Нет курсов» по записям в профиле ВШЭ. Например, «Нет курсов» и 2024 покажут сотрудников без записей о курсах за 2024 год и позже. Если указать только год, отобразятся сотрудники с курсами за этот период.</dd>
|
||||
<dt>Период обнаружения: От / До</dt><dd>Введите даты первого обнаружения профиля системой. Это не период приёма на работу.</dd>
|
||||
<dt>Порядок списка</dt><dd>Выберите поле сортировки, направление стрелкой и число строк. «Применить фильтры» обновит список, «Сбросить» вернёт исходные параметры.</dd>
|
||||
<dt>Порядок списка</dt><dd>Поле сортировки, направление и число строк сразу обновляют список. «Сбросить» вернёт исходные параметры.</dd>
|
||||
<dt>Настроить колонки</dt><dd>Позволяет выбрать видимые сведения: должности, контакты, степень, число публикаций, курсов и новостей, даты обнаружения.</dd>
|
||||
<dt>Скачать XLSX</dt><dd>В файл попадут все колонки и все сотрудники, найденные с применёнными фильтрами, в выбранном порядке.</dd>
|
||||
</dl>
|
||||
|
||||
+3
-3
@@ -1,3 +1,3 @@
|
||||
APP_VERSION = "2.1.1"
|
||||
FRONTEND_VERSION = "2.1.1"
|
||||
BACKEND_VERSION = "2.1.1"
|
||||
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.1.1"
|
||||
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.1.1"
|
||||
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.1.1 · Frontend 2.1.1" 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