fix: preserve guide progress across navigation

This commit is contained in:
codex committed 2026-11-11 14:12:07 +03:00
1 parent c92523f235
commit d9420db50c
8 files changed
+86 -53

No files matched your search

+49 -39
View File
@@ -25,7 +25,7 @@
]},
{id: 'employee-profile', path: directory, title: 'Откройте карточку сотрудника', region: '.directory__header', tips: [
['[data-columns-open]', 'Выберите столбцы: например, должности, контакты и число публикаций.'],
['.directory__help', 'Нажмите на ФИО в таблице, чтобы открыть контакты, степени, публикации и другие данные профиля.'],
['.directory-table__cell[data-column="full_name"] a', 'Нажмите на ФИО, чтобы открыть контакты, степени и публикации сотрудника.'],
]},
{id: 'council-filters', path: council, title: 'Задайте параметры подбора', region: '.council__search', tips: [
['#council-branch', 'Отрасль определяет публикационный минимум для доктора наук. Варианты зависят от специальности ВАК.'],
@@ -42,6 +42,11 @@
['[data-guide-count="total"]', 'Уникальные работы Q1/Q2/К1/RSCI. Для докторов учитывается также К2.', 'inside'],
['[data-guide-count="all"]', 'Публикации из ЛК и выгрузки ВШЭ за все годы, без дублей.', 'inside'],
]},
{id: 'council-sources', path: council, title: 'Сравните счётчики публикаций', region: '.council__list-heading',
intro: 'В раскрытой карточке можно проверить источник записи, DOI и основания зачёта.', tips: [
['[data-guide-count="q1"]', 'Одна работа может входить сразу в несколько счётчиков Q1, Q2 и К1.', 'inside'],
['[data-guide-count="hse"]', 'Здесь только публикации из личного кабинета сотрудника ВШЭ за все годы.', 'inside'],
]},
{id: 'council-export', path: council, title: 'Проверьте расчёт и выгрузите список', region: '.council__notice', tips: [
['.council__notice', 'Здесь описаны период оценки, минимумы по отраслям и правила учёта работ.'],
['[formaction="/admin/council/export.xlsx"]', 'В XLSX попадут все найденные сотрудники и их публикации, включая другие страницы списка.'],
@@ -68,13 +73,15 @@
const heading = guide.querySelector('#guide-title');
const progress = guide.querySelector('[data-guide-progress]');
const intro = guide.querySelector('[data-guide-intro]');
const reference = guide.querySelector('[data-guide-reference]');
const back = guide.querySelector('[data-guide-back]');
const next = guide.querySelector('[data-guide-next]');
const close = guide.querySelector('[data-guide-close]');
const error = guide.querySelector('[data-guide-error]');
const unsaved = guide.querySelector('[data-guide-unsaved]');
const hashFor = step => '#guide-' + step.id;
const storageKey = 'workers-guide:' + guide.dataset.guideUser;
let index = 0;
let paused = false;
let saving = false;
let removeTips = [];
@@ -119,19 +126,24 @@
function showStep(focus = true) {
const step = steps[index];
paused = Boolean(step.path && step.path !== location.pathname);
clearTips();
const region = step.region && main.querySelector(step.region);
const region = !paused && step.region && main.querySelector(step.region);
if (region) region.before(guide);
else main.prepend(guide);
heading.textContent = step.title;
heading.textContent = paused ? 'Продолжите обучение' : step.title;
progress.textContent = `Шаг ${index + 1} из ${steps.length}`;
intro.textContent = step.intro || '';
intro.hidden = !step.intro;
intro.textContent = paused ? step.title + '.' : step.intro || '';
intro.hidden = !intro.textContent;
reference.hidden = index !== 0;
error.hidden = unsaved.hidden = true;
back.hidden = paused;
back.disabled = index === 0;
next.textContent = index === steps.length - 1 ? 'Завершить подсказки' : 'Далее';
step.tips?.forEach((tip, number) => addTip(tip, number));
step.editorTips?.forEach((tip, number) => addTip(tip, 'editor-' + number, true));
next.textContent = paused ? 'Продолжить' : index === steps.length - 1 ? 'Завершить подсказки' : 'Далее';
if (!paused) {
step.tips?.forEach((tip, number) => addTip(tip, number));
step.editorTips?.forEach((tip, number) => addTip(tip, 'editor-' + number, true));
}
guide.hidden = false;
if (focus) {
heading.focus({preventScroll: true});
@@ -140,20 +152,20 @@
}
function goTo(number, path = steps[number].path || '/admin/account') {
const step = steps[number];
sessionStorage.setItem(storageKey, steps[number].id);
if (path !== location.pathname) {
location.assign(path + hashFor(step));
location.assign(path);
return;
}
index = number;
history.replaceState(history.state, '', hashFor(step));
showStep();
}
function hide() {
function hide(remember = true) {
clearTips();
guide.hidden = true;
history.replaceState(history.state, '', location.pathname + location.search);
if (remember) sessionStorage.setItem(storageKey, 'closed');
else sessionStorage.removeItem(storageKey);
trigger?.focus();
}
@@ -195,36 +207,34 @@
});
back.addEventListener('click', () => goTo(index - 1));
next.addEventListener('click', () => {
if (index === steps.length - 1) finish();
if (paused) goTo(index);
else if (index === steps.length - 1) finish();
else goTo(index + 1);
});
close.addEventListener('click', finish);
unsaved.addEventListener('click', hide);
document.addEventListener('keydown', event => {
if (event.key !== 'Escape' || event.defaultPrevented || guide.hidden || document.querySelector('dialog[open]')) return;
unsaved.addEventListener('click', () => hide(false));
guide.addEventListener('keydown', event => {
if (event.key !== 'Escape' || event.defaultPrevented) return;
event.preventDefault();
finish();
});
main.addEventListener('submit', event => {
const form = event.target;
if (guide.hidden || !steps[index].path || form.method !== 'get' || event.submitter?.hasAttribute('formaction')) return;
const action = new URL(form.action);
if (action.origin !== location.origin || action.pathname !== location.pathname) return;
const original = form.getAttribute('action');
action.hash = hashFor(steps[index]);
form.action = action;
setTimeout(() => {
if (original === null) form.removeAttribute('action');
else form.setAttribute('action', original);
});
});
const requested = steps.findIndex(step => hashFor(step) === location.hash && (!step.path || step.path === location.pathname));
if (requested >= 0) {
index = requested;
showStep();
} else if (guide.dataset.guidePending === 'true') {
history.replaceState(history.state, '', hashFor(steps[0]));
showStep(false);
function restore(allowAutoStart) {
const active = sessionStorage.getItem(storageKey);
const requested = steps.findIndex(step => step.id === active);
if (requested >= 0) {
index = requested;
showStep(!allowAutoStart || index > 0);
} else if (allowAutoStart && active !== 'closed' && guide.dataset.guidePending === 'true') {
sessionStorage.setItem(storageKey, steps[0].id);
showStep(false);
} else {
clearTips();
guide.hidden = true;
}
}
window.addEventListener('pageshow', event => {
if (event.persisted) restore(false);
});
restore(true);
})();
+2 -2
View File
@@ -81,11 +81,11 @@
<summary class="council__candidate-summary">
<span class="council__candidate-identity"><strong>{{ candidate.name }}</strong><small>{{ candidate.degree }}{% if candidate.dismissed %} · Уволен{% endif %}</small><small>{{ candidate.assessment_status }} · подтверждено {{ candidate.confirmed_count }}</small></span>
<span class="council__counts">
<span class="council__candidate-count"><strong>{{ candidate.q1_count }}</strong><small>Q1</small></span>
<span class="council__candidate-count" data-guide-count="q1"><strong>{{ candidate.q1_count }}</strong><small>Q1</small></span>
<span class="council__candidate-count"><strong>{{ candidate.q2_count }}</strong><small>Q2</small></span>
<span class="council__candidate-count"><strong>{{ candidate.k1_count }}</strong><small>К1</small></span>
<span class="council__candidate-count" data-guide-count="total"><strong>{{ candidate.total_count }}</strong><small>ВСЕГО (предв.)</small></span>
<span class="council__candidate-count"><strong>{{ candidate.db_count }}</strong><small>ЛК сотрудника ВШЭ</small></span>
<span class="council__candidate-count" data-guide-count="hse"><strong>{{ candidate.db_count }}</strong><small>ЛК сотрудника ВШЭ</small></span>
<span class="council__candidate-count" data-guide-count="all"><strong>{{ candidate.count }}</strong><small>Все публикации</small></span>
</span>
<span class="council__candidate-cue" aria-hidden="true"></span>
+2 -1
View File
@@ -1,4 +1,4 @@
<section class="guide" data-guide data-guide-pending="{{ 'true' if request.state.guide_pending|default(false) else 'false' }}" data-guide-csrf="{{ csrf_token }}" aria-labelledby="guide-title" hidden>
<section class="guide" data-guide data-guide-user="{{ current_user.id }}" data-guide-pending="{{ 'true' if request.state.guide_pending|default(false) else 'false' }}" data-guide-csrf="{{ csrf_token }}" aria-labelledby="guide-title" hidden>
<div class="guide__header">
<div>
<p class="guide__progress" data-guide-progress></p>
@@ -11,6 +11,7 @@
</div>
</div>
<p class="guide__intro" data-guide-intro hidden></p>
<a class="admin__link" href="/admin/guide" target="_blank" rel="noopener" data-guide-reference hidden>Подробная справка ↗</a>
<p class="users__error" data-guide-error role="alert" hidden></p>
<button class="button button--ghost" type="button" data-guide-unsaved hidden>Продолжить без сохранения</button>
</section>
+3 -3
View File
@@ -1,3 +1,3 @@
APP_VERSION = "1.6.0"
FRONTEND_VERSION = "1.6.0"
BACKEND_VERSION = "1.6.0"
APP_VERSION = "1.6.1"
FRONTEND_VERSION = "1.6.1"
BACKEND_VERSION = "1.6.1"
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "miem-workers"
version = "1.6.0"
version = "1.6.1"
description = "MIEM employees parser, admin API, and web admin"
requires-python = ">=3.11"
dependencies = [
+27 -5
View File
@@ -117,6 +117,7 @@ def main():
page.unroute('**/admin/guide/dismiss')
page.reload()
expect(guide).to_be_visible()
guide.get_by_role('heading').focus()
page.keyboard.press('Escape')
expect(guide).not_to_be_visible()
expect(page.get_by_role('link', name='Как пользоваться', exact=True)).to_be_focused()
@@ -129,19 +130,22 @@ def main():
tips = page.locator('.guide__tip:visible')
go_next.click()
expect(guide.get_by_role('heading', name='Найдите сотрудника', exact=True)).to_be_focused()
assert page.url.endswith('/admin/directory#guide-employee-search')
assert page.url.endswith('/admin/directory')
expect(tips).to_have_count(3)
search = page.get_by_role('textbox', name='ФИО или ссылка', exact=True)
expect(search).to_have_accessible_description('Введите фамилию, часть ФИО или ссылку на профиль ВШЭ.')
search.fill('Сотрудник')
page.get_by_role('button', name='Применить фильтры', exact=True).click()
expect(tips).to_have_count(3)
assert page.url.endswith('#guide-employee-search')
expect(search).to_have_value('Сотрудник')
page.get_by_role('link', name='Сбросить', exact=True).click()
expect(search).to_have_value('')
expect(tips).to_have_count(3)
go_back.click()
expect(guide.get_by_role('heading', name='Познакомьтесь с Workers')).to_be_visible()
for _ in range(5):
go_next.click()
assert page.url.endswith('/admin/council#guide-council-filters')
assert page.url.endswith('/admin/council')
expect(tips).to_have_count(3)
for width in (1440, 320):
page.set_viewport_size({'width': width, 'height': 900})
@@ -158,7 +162,13 @@ def main():
guide.evaluate("node => node.scrollIntoView({block: 'start'})")
page.screenshot(path=str(output / f'guide-council-{width}.png'))
go_back.click()
assert page.url.endswith('/admin/directory#guide-employee-profile')
expect(guide.get_by_role('heading', name='Откройте карточку сотрудника')).to_be_visible()
profile = page.get_by_role('link', name='Сотрудник для проверки', exact=True)
expect(profile).to_have_accessible_description('Нажмите на ФИО, чтобы открыть контакты, степени и публикации сотрудника.')
profile.click()
expect(guide.get_by_role('heading', name='Продолжите обучение')).to_be_visible()
guide.get_by_role('button', name='Продолжить', exact=True).click()
expect(guide.get_by_role('heading', name='Откройте карточку сотрудника')).to_be_visible()
go_next.click()
go_next.click()
go_next.click()
@@ -167,10 +177,19 @@ def main():
page.screenshot(path=str(output / 'guide-counts-mobile.png'))
go_next.click()
expect(tips).to_have_count(2)
expect(page.locator('[data-guide-count="hse"] .guide__tip')).to_contain_text('личного кабинета')
go_next.click()
assert page.url.endswith('/admin/council/publications#guide-publication-search')
expect(tips).to_have_count(2)
go_next.click()
assert page.url.endswith('/admin/council/publications')
go_next.click()
expect(tips).to_have_count(3)
warning = page.locator('[data-warning] button').first
warning.focus()
expect(warning).to_have_attribute('aria-expanded', 'true')
page.keyboard.press('Escape')
expect(warning).to_have_attribute('aria-expanded', 'false')
expect(guide).to_be_visible()
page.locator('[data-council-article]').click()
page.get_by_role('button', name='Редактировать статью: Статья для проверки', exact=True).click()
guide_editor = page.get_by_role('dialog', name='Редактирование статьи')
@@ -184,6 +203,9 @@ def main():
guide.get_by_role('button', name='Завершить подсказки', exact=True).click()
expect(guide).not_to_be_visible()
expect(tips).to_have_count(0)
page.go_back()
expect(guide).not_to_be_visible()
expect(tips).to_have_count(0)
no_js = browser.new_context(java_script_enabled=False)
nojs_page = no_js.new_page()
nojs_page.goto(base_url + '/admin/login')
+1 -1
View File
@@ -18,7 +18,7 @@ def test_health_returns_versions():
response = TestClient(app).get("/api/health")
assert response.status_code == 200
assert response.json()["backend_version"] == "1.6.0"
assert response.json()["backend_version"] == "1.6.1"
def test_api_employees_and_stats_require_admin_session():
+1 -1
View File
@@ -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 1.6.0 · Frontend 1.6.0" in response.text
assert "Backend 1.6.1 · Frontend 1.6.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