forked from admin/miem_workers
feat: add council publication and journal quartile editor
This commit is contained in:
1 parent
2e0c71367d
commit
f45c66e069
18 files changed
+684
-25
No files matched your search
@@ -28,6 +28,7 @@ jobs:
|
||||
- run: python -m pip install -r requirements.txt
|
||||
- run: python -m pytest -q
|
||||
- run: node --check app/static/admin.js
|
||||
- run: node --check app/static/council.js
|
||||
- run: sh -n infra/postgres-backup.sh
|
||||
- run: sh -n infra/install-postgres-backup-cron.sh
|
||||
|
||||
|
||||
@@ -94,6 +94,10 @@ Compose запускает `api`, `worker` и `postgres`. API привязан
|
||||
|
||||
Отдельно показаны предварительные Q1/Q2/К1/К2/RSCI, их объединение ВСЕГО и подтверждённое число, порог, монографии, пункт и причины проверки. Одна работа учитывается один раз, основания сохраняют исходные записи. Без подтверждения высшей степени, даты, отрасли и достаточного числа проверенных работ результат — «Требует проверки». Недостаток записей не доказывает отсутствие работ; соответствие публикационным критериям не означает автоматического включения в совет.
|
||||
|
||||
Кнопка «Статьи, журналы и квартили» открывает `/admin/council/publications` в отдельной вкладке. Здесь доступны совместные фильтры по ФИО, названию статьи и журнала. Нажатие на карточку статьи (или Enter/пробел с клавиатуры) показывает иконку редактирования; она открывает форму названия статьи, журнала и квартиля. Та же форма доступна в карточках основного списка. Для сохранения требуется вход администратора.
|
||||
|
||||
Ручные изменения хранятся в отдельной таблице `council_corrections`, создаваемой при запуске приложения (`migrations/012_council_corrections.sql` для ручного обновления схемы). Исходные публикации и файлы выгрузки не перезаписываются. Квартиль применяется к выбранному журналу за год статьи, в том числе к другим статьям и сотрудникам; при неизвестном или конфликтующем годе можно исправить только название и журнал. Правки учитываются в фильтрах, предварительных счётчиках и XLSX, но требуют повторного подтверждения источниками для зачёта. Одновременное сохранение из устаревшей вкладки отклоняется: нужно обновить страницу. Привязка статьи использует исходный DOI или название и год; при изменении этих идентификаторов в источнике ручную привязку нужно проверить заново.
|
||||
|
||||
Сервис читает подготовленный `app/data/council_articles.json` и таблицу `employee_publications`. Справочник преобразуется из CSV скриптом `scripts/prepare_council_articles.py`, проверяет схему и индекс авторов; импорт/парсинг CSV не объявляется доказательством выполнения критериев. Сопоставление данных ВШЭ по полному ФИО разрешено только при единственном совпадении. Дедупликация использует DOI либо нормализованные название и год при отсутствии неоднозначных DOI. Источники с разными годами не переносят категории между периодами.
|
||||
|
||||
К1/К2 сопоставляются по точным нормализованным названиям журнала и документированным алиасам; название статьи, переводы и нечёткое совпадение не используются. Справочник К1 содержит 773 журнала, К2 — 1539; экстрактор проверяет все 3134 строки, даты и SHA-256 источника. Это текущие категории, а не историческое доказательство. Q1/Q2 читаются также из двух тематических JSON-каталогов (схемы 1.0.0/1.1.0, 229 уникальных журналов): ISSN/eISSN, категории CiteScore/JCR, источники и версии паспортов. Снимок метрик 2025 не распространяется автоматически на другие годы; текущая индексация не проверена. Каталоги не являются белым списком. Аналитические прямые/условные связи журнала показываются отдельно от рассмотрения статьи по паспорту.
|
||||
|
||||
+88
-8
@@ -1,14 +1,16 @@
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, Form, Request
|
||||
from copy import deepcopy
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, Form, Request, HTTPException
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy import desc, func, select
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy import desc, func, select, update
|
||||
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import Settings, get_settings
|
||||
from app.db import SessionLocal, get_db
|
||||
from app.models import CrawlError, CrawlRun, Employee
|
||||
from app.security import SESSION_COOKIE, require_admin, sign_session, verify_admin
|
||||
from app.models import CrawlError, CrawlRun, Employee, CouncilCorrections
|
||||
from app.security import SESSION_COOKIE, require_admin, sign_session, verify_admin, read_session
|
||||
from app.services.admin_data import (
|
||||
employee_detail_payload,
|
||||
format_admin_datetime,
|
||||
@@ -19,7 +21,7 @@ from app.services.admin_data import (
|
||||
)
|
||||
from app.services.crawl_control import get_running_run, run_crawl_if_idle
|
||||
from app.services.crawler import refresh_dismissed_status, refresh_employee
|
||||
from app.services.council import CouncilInputError, council_candidates
|
||||
from app.services.council import CouncilInputError, council_candidates, _journal_key
|
||||
from app.services.council_export import council_xlsx
|
||||
from app.version import BACKEND_VERSION, FRONTEND_VERSION
|
||||
|
||||
@@ -136,7 +138,7 @@ def directory(
|
||||
|
||||
@router.get("/council", response_class=HTMLResponse)
|
||||
def council(request: Request, q: str = "", offset: int = 0, sort: str = "total_count", direction: str = "desc", specialty: str = "",
|
||||
db: Session = Depends(get_db)):
|
||||
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
|
||||
try:
|
||||
result = council_candidates(db, q=q, offset=offset, sort=sort, direction=direction, specialty=specialty,
|
||||
branch="технические")
|
||||
@@ -145,7 +147,85 @@ def council(request: Request, q: str = "", offset: int = 0, sort: str = "total_c
|
||||
except (SQLAlchemyError, OSError, ValueError, KeyError):
|
||||
db.rollback()
|
||||
return _render(request, "council.html", {"error": True, "public_page": True}, status_code=503)
|
||||
return _render(request, "council.html", {"error": False, "public_page": True, **result})
|
||||
return _render(request, "council.html", {"error": False, "public_page": True, "can_edit": read_session(request.cookies.get(SESSION_COOKIE), settings) == settings.admin_username, **result})
|
||||
|
||||
|
||||
class CouncilArticleEdit(BaseModel):
|
||||
model_config = ConfigDict(str_strip_whitespace=True, extra="forbid", strict=True)
|
||||
employee_id: int = Field(gt=0)
|
||||
edit_key: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
revision: int = Field(ge=0)
|
||||
title: str = Field(min_length=1, max_length=2000)
|
||||
journal: str = Field(min_length=1, max_length=500)
|
||||
quartile: str = Field(pattern=r"^(Q[1-4])?$")
|
||||
|
||||
|
||||
@router.get("/council/publications", response_class=HTMLResponse)
|
||||
def council_publications(request: Request, employee: str = "", title: str = "", journal: str = "", offset: int = 0,
|
||||
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
|
||||
context = {"public_page": True, "employee": employee, "title": title, "journal": journal,
|
||||
"can_edit": read_session(request.cookies.get(SESSION_COOKIE), settings) == settings.admin_username}
|
||||
try:
|
||||
result = council_candidates(db, paginate=False, sort="full_name", direction="asc")
|
||||
articles = [{**article, "employee_id": candidate["employee_id"], "employee_name": candidate["name"]}
|
||||
for candidate in result["candidates"] for article in candidate["articles"]
|
||||
if employee.casefold().strip() in candidate["name"].casefold()
|
||||
and title.casefold().strip() in article["title"].casefold()
|
||||
and journal.casefold().strip() in " ".join(article["journals"]).casefold()]
|
||||
total, limit = len(articles), 50
|
||||
offset = min(max(0, offset), ((total - 1) // limit) * limit) if total else 0
|
||||
return _render(request, "council_publications.html", {**context, "error": False,
|
||||
"articles": articles[offset:offset + limit], "matched": total, "offset": offset, "limit": limit,
|
||||
"revision": result["revision"], "journal_names": result["journal_names"]})
|
||||
except (SQLAlchemyError, OSError, ValueError, KeyError):
|
||||
db.rollback()
|
||||
return _render(request, "council_publications.html", {**context, "error": True}, status_code=503)
|
||||
|
||||
|
||||
@router.post("/council/publications")
|
||||
def edit_council_publication(request: Request, change: CouncilArticleEdit,
|
||||
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
|
||||
username = read_session(request.cookies.get(SESSION_COOKIE), settings)
|
||||
if username != settings.admin_username:
|
||||
raise HTTPException(401, "Для сохранения войдите в админку")
|
||||
# A custom header plus JSON prevents cross-site form submissions; CORS is disabled.
|
||||
if request.headers.get("X-Council-Edit") != "1":
|
||||
raise HTTPException(403, "Недопустимый запрос на изменение")
|
||||
if not _journal_key(change.journal):
|
||||
raise HTTPException(422, "Укажите название журнала")
|
||||
try:
|
||||
result = council_candidates(db, paginate=False)
|
||||
article = next((a for c in result["candidates"] if c["employee_id"] == change.employee_id
|
||||
for a in c["articles"] if a["edit_key"] == change.edit_key), None)
|
||||
if not article:
|
||||
raise HTTPException(404, "Статья не найдена. Обновите страницу")
|
||||
if article["year"] is None and change.quartile:
|
||||
raise HTTPException(422, "Для квартиля необходим однозначный год публикации")
|
||||
record = db.get(CouncilCorrections, 1)
|
||||
revision = record.revision if record else 0
|
||||
if revision != change.revision:
|
||||
raise HTTPException(409, "Данные уже изменены. Обновите страницу перед сохранением")
|
||||
data = deepcopy(record.data) if record else {"articles": {}, "journals": {}}
|
||||
data["articles"][f"{change.employee_id}:{change.edit_key}"] = {"title": change.title, "journal": change.journal}
|
||||
if article["year"] is not None:
|
||||
data["journals"][f"{_journal_key(change.journal)}:{article['year']}"] = change.quartile
|
||||
if record:
|
||||
count = db.execute(update(CouncilCorrections).where(CouncilCorrections.id == 1,
|
||||
CouncilCorrections.revision == change.revision).values(data=data, revision=revision + 1,
|
||||
updated_by=username)).rowcount
|
||||
if not count:
|
||||
db.rollback()
|
||||
raise HTTPException(409, "Данные уже изменены. Обновите страницу перед сохранением")
|
||||
else:
|
||||
db.add(CouncilCorrections(id=1, data=data, revision=1, updated_by=username))
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(409, "Данные уже изменены. Обновите страницу перед сохранением")
|
||||
except (SQLAlchemyError, OSError, ValueError, KeyError):
|
||||
db.rollback()
|
||||
raise HTTPException(503, "Не удалось сохранить изменения. Попробуйте ещё раз")
|
||||
return {"saved": True}
|
||||
|
||||
|
||||
@router.get("/council/export.xlsx")
|
||||
|
||||
@@ -243,3 +243,14 @@ class ParseResourceCache(Base):
|
||||
body_snapshot: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
|
||||
parser_version: Mapped[str | None] = mapped_column(String(32))
|
||||
fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, nullable=False)
|
||||
|
||||
|
||||
class CouncilCorrections(Base):
|
||||
"""Manual council data, outside crawler-owned publications."""
|
||||
__tablename__ = "council_corrections"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
revision: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
data: Mapped[dict] = mapped_column(json_type, nullable=False)
|
||||
updated_by: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, onupdate=utcnow, nullable=False)
|
||||
+51
-9
@@ -14,7 +14,7 @@ from zoneinfo import ZoneInfo
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session, selectinload
|
||||
|
||||
from app.models import Employee
|
||||
from app.models import Employee, CouncilCorrections
|
||||
from app.services.academic_degrees import academic_degrees
|
||||
from app.services.council_source import _doi, _journal_names, _name, load_reference, _description_journals
|
||||
from app.services.council_catalog import catalog, publication_catalog
|
||||
@@ -133,7 +133,7 @@ def _database_article(publication) -> dict:
|
||||
"url": _safe_url(publication.url)}
|
||||
|
||||
|
||||
def _unique_articles(articles: list[dict], start: date, end: date) -> list[dict]:
|
||||
def _unique_articles(articles: list[dict], start: date, end: date, corrections=None, employee_id=None) -> list[dict]:
|
||||
k1_journals = _k1_journals()
|
||||
specialties = _k1_specialties()["by_journal"]
|
||||
title_years = defaultdict(set)
|
||||
@@ -171,8 +171,23 @@ def _unique_articles(articles: list[dict], start: date, end: date) -> list[dict]
|
||||
merged["in_csv"] |= article["in_csv"]
|
||||
merged["in_db"] |= article["in_db"]
|
||||
merged["url"] = merged["url"] or article["url"]
|
||||
for article in unique.values():
|
||||
for identity, article in unique.items():
|
||||
evidence = article.pop("evidence")
|
||||
article["edit_key"] = hashlib.sha256(json.dumps(
|
||||
identity,
|
||||
ensure_ascii=False).encode()).hexdigest()
|
||||
correction = (corrections or {}).get("articles", {}).get(f"{employee_id}:{article['edit_key']}")
|
||||
article["manually_corrected"] = bool(correction)
|
||||
if correction:
|
||||
journal_changed = article["journals"] != [correction["journal"]]
|
||||
article["title"] = correction["title"]
|
||||
article["journals"] = [correction["journal"]]
|
||||
if journal_changed:
|
||||
article["issns"] = []
|
||||
article["quartiles"] = []
|
||||
article["quartile_issues"] = []
|
||||
evidence = [{**item, "journals": article["journals"],
|
||||
"quartiles": [] if journal_changed else item["quartiles"]} for item in evidence]
|
||||
years = sorted({item["year"] for item in evidence if item["year"] is not None})
|
||||
# Never pick a conflicting source year merely because that row came first.
|
||||
year = article["year"] = years[0] if len(years) == 1 else None
|
||||
@@ -237,6 +252,9 @@ def council_candidates(db: Session, today: date | None = None, q: str = "", offs
|
||||
name_counts = Counter(_name(employee.full_name or "") for employee in employees)
|
||||
by_author = _articles_by_author()
|
||||
verified = evidence()
|
||||
corrections_record = db.get(CouncilCorrections, 1)
|
||||
corrections = corrections_record.data if corrections_record else {}
|
||||
revision = corrections_record.revision if corrections_record else 0
|
||||
candidates = []
|
||||
for employee in employees:
|
||||
author = _name(employee.full_name or "")
|
||||
@@ -250,9 +268,11 @@ def council_candidates(db: Session, today: date | None = None, q: str = "", offs
|
||||
employee_evidence = verified["employees"].get(employee.profile_key, {})
|
||||
if not any(degree_level(degree) for degree in degrees) and not employee_evidence.get("degrees"):
|
||||
continue
|
||||
articles = _unique_articles([*csv_articles, *(_database_article(p) for p in employee.publications)], start, end)
|
||||
articles = _unique_articles([*csv_articles, *(_database_article(p) for p in employee.publications)], start, end, corrections, employee.id)
|
||||
for article in articles:
|
||||
proofs = publication_proofs(employee_evidence, article)
|
||||
article["manual_review"] = article["manually_corrected"] or (len(article["journals"]) == 1 and
|
||||
f"{_journal_key(article['journals'][0])}:{article['year']}" in corrections.get("journals", {}))
|
||||
proofs = [] if article["manual_review"] else publication_proofs(employee_evidence, article)
|
||||
kinds = {proof["kind"] for proof in proofs if proof.get("kind") and sourced(proof.get("kind_evidence"))}
|
||||
kind = next(iter(kinds)) if len(kinds) == 1 else None
|
||||
preliminary_type_allowed = len(kinds) <= 1 and publication_type_allowed(
|
||||
@@ -260,7 +280,7 @@ def council_candidates(db: Session, today: date | None = None, q: str = "", offs
|
||||
if not preliminary_type_allowed:
|
||||
for flag in ("q1", "q2", "k1", "k2", "rsci"):
|
||||
article[flag] = False
|
||||
identifiers = [*article["issns"], *(value for proof in proofs for value in proof.get("issns", []))]
|
||||
identifiers = [] if article["manually_corrected"] else [*article["issns"], *(value for proof in proofs for value in proof.get("issns", []))]
|
||||
for name in article["journals"]:
|
||||
canonical = _k1_journals().get(_journal_key(name))
|
||||
identifiers.extend(_k1_specialties()["journal_issns"].get(canonical, []))
|
||||
@@ -278,13 +298,35 @@ def council_candidates(db: Session, today: date | None = None, q: str = "", offs
|
||||
key = {"К1": "k1", "К2": "k2", "Q1": "q1", "Q2": "q2", "RSCI": "rsci"}.get(basis.get("basis"))
|
||||
if key:
|
||||
article[key] = True
|
||||
assessment = assess_candidate(degrees, articles, employee_evidence, branch, specialty, start, end)
|
||||
journal_key = _journal_key(article["journals"][0]) if len(article["journals"]) == 1 else ""
|
||||
manual_quartile = corrections.get("journals", {}).get(f"{journal_key}:{article['year']}")
|
||||
if manual_quartile is not None:
|
||||
article["quartiles"] = [f"Ручная корректировка {manual_quartile}"] if manual_quartile else []
|
||||
article["q1"] = bool(manual_quartile == "Q1" and preliminary_type_allowed and article["year"] is not None and start.year <= article["year"] <= end.year)
|
||||
article["q2"] = bool(manual_quartile == "Q2" and preliminary_type_allowed and article["year"] is not None and start.year <= article["year"] <= end.year)
|
||||
article["criteria"] = [c for c in article["criteria"] if not c.endswith((" Q1", " Q2", " Q3", " Q4")) and c != "Q1/Q2 и К1 не подтверждены доступными данными"]
|
||||
article["criteria"].append(f"Квартиль журнала за {article['year']}: {manual_quartile or 'не указан'} · ручная корректировка, требует подтверждения")
|
||||
article["qualifies"] = article["q1"] or article["q2"] or article["k1"]
|
||||
labels = {q[-2:] for q in article["quartiles"] if q.endswith((" Q1", " Q2", " Q3", " Q4"))}
|
||||
if manual_quartile is None:
|
||||
labels.update(metric["quartile"] for record in article["catalog_records"] for metric in record["metrics"]
|
||||
if metric["year"] == article["year"] and metric["quartile"] in {"Q1", "Q2", "Q3", "Q4"})
|
||||
labels.update(basis["basis"] for proof in proofs for basis in proof.get("bases", [])
|
||||
if isinstance(basis, dict) and basis.get("applicable_year") == article["year"] and basis.get("basis") in {"Q1", "Q2", "Q3", "Q4"})
|
||||
article["edit_quartile"] = manual_quartile if manual_quartile is not None else next(iter(labels)) if len(labels) == 1 else ""
|
||||
article["edit_journal"] = article["journals"][0] if len(article["journals"]) == 1 else ""
|
||||
changed = [a for a in articles if a["manual_review"]]
|
||||
adjusted_evidence = {**employee_evidence, "publications": [p for p in employee_evidence.get("publications", [])
|
||||
if not any((a["doi"] and p.get("doi") == a["doi"]) or p.get("source_hash") in a["source_hashes"] for a in changed)]}
|
||||
assessment = assess_candidate(degrees, articles, adjusted_evidence, branch, specialty, start, end)
|
||||
for article in changed:
|
||||
article["confirmation_reasons"].append("Ручная корректировка требует повторного подтверждения источниками")
|
||||
specialty_count = sum(specialty in a["specialty_codes"] for a in articles) if specialty else 0
|
||||
for article in articles:
|
||||
article["matches_specialty"] = bool(specialty and specialty in article["specialty_codes"])
|
||||
if article["matches_specialty"]:
|
||||
article["criteria"].append(f"По специальности {specialty}: {specialty_name} (журнал К1, Перечень ВАК)")
|
||||
candidates.append({**assessment, "specialty_count": specialty_count,"name": employee.full_name or "ФИО не указано",
|
||||
candidates.append({**assessment, "specialty_count": specialty_count,"name": employee.full_name or "ФИО не указано", "employee_id": employee.id,
|
||||
"count": len(articles),
|
||||
**{f"{key}_count": sum(a[key] for a in articles) for key in ("q1", "q2", "k1", "k2", "rsci")},
|
||||
"total_count": sum(a["qualifies"] for a in articles),
|
||||
@@ -303,7 +345,7 @@ def council_candidates(db: Session, today: date | None = None, q: str = "", offs
|
||||
matched = len(candidates)
|
||||
limit = 25
|
||||
offset = min(max(0, offset), ((matched - 1) // limit) * limit) if matched else 0
|
||||
return {"candidates": candidates[offset:offset + limit] if paginate else candidates,
|
||||
return {"journal_names": sorted({name for c in candidates for a in c["articles"] for name in a["journals"]}), "revision": revision, "candidates": candidates[offset:offset + limit] if paginate else candidates,
|
||||
"start": start, "end": end, "total": total,
|
||||
"specialties": specialties, "specialty": specialty, "specialty_name": specialty_name,
|
||||
"branch": branch,
|
||||
|
||||
@@ -913,3 +913,22 @@
|
||||
.council__title { font-size: clamp(23px, 7vw, 29px); overflow-wrap: anywhere; }
|
||||
.council__article-heading { flex-direction: column; gap: 4px; }
|
||||
}
|
||||
|
||||
.council__article[data-council-article] { position: relative; padding-inline-end: 60px; cursor: pointer; }
|
||||
.council__article[data-council-article]:hover { background: #f3f7f5; }
|
||||
.council__article--active { background: #e7f0eb; }
|
||||
.council__article[data-council-article]:focus-visible { outline: 3px solid #0f766e; outline-offset: 2px; }
|
||||
.council__edit { position: absolute; inset-inline-end: 4px; top: 12px; min-width: 44px; min-height: 44px; visibility: hidden; display: inline-flex; align-items: center; justify-content: center; }
|
||||
.council__article--active > .council__edit,
|
||||
.council__article:focus-within > .council__edit { visibility: visible; }
|
||||
.council__articles--editor { padding: 20px 20px 20px 42px; background: #fff; border: 1px solid #d6dddc; border-radius: 12px; }
|
||||
.council__articles--editor .council__hint { margin-block: 8px; }
|
||||
.council-editor { display: grid; gap: 16px; margin-top: 20px; }
|
||||
.council-editor .directory__field { min-width: 0; }
|
||||
.council-editor textarea { resize: vertical; min-height: 90px; font: inherit; }
|
||||
.council-editor__actions { display: flex; flex-wrap: wrap; gap: 12px; }
|
||||
.council-editor__error { margin: 0; color: #991b1b; line-height: 1.5; }
|
||||
@media (max-width: 600px) {
|
||||
.council__articles--editor { padding-inline: 28px 12px; }
|
||||
.council-editor .directory__input { font-size: 16px; }
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
(() => {
|
||||
const dialog = document.querySelector('[data-council-dialog]');
|
||||
if (!dialog) return;
|
||||
const form = dialog.querySelector('[data-edit-form]');
|
||||
let selected;
|
||||
let trigger;
|
||||
let saving = false;
|
||||
const openKey = 'miem.council.openCandidates';
|
||||
|
||||
try {
|
||||
const opened = JSON.parse(sessionStorage.getItem(openKey) || '[]');
|
||||
document.querySelectorAll('[data-employee-id]').forEach(node => {
|
||||
if (opened.includes(node.dataset.employeeId)) node.open = true;
|
||||
});
|
||||
sessionStorage.removeItem(openKey);
|
||||
} catch (_error) { /* Storage is optional. */ }
|
||||
|
||||
function activate(article) {
|
||||
document.querySelectorAll('.council__article--active').forEach(node => {
|
||||
node.classList.remove('council__article--active');
|
||||
});
|
||||
article.classList.add('council__article--active');
|
||||
}
|
||||
|
||||
document.querySelectorAll('[data-council-article]').forEach(article => {
|
||||
article.addEventListener('click', event => {
|
||||
if (!event.target.closest('a, button')) activate(article);
|
||||
});
|
||||
article.addEventListener('keydown', event => {
|
||||
if (event.target === article && ['Enter', ' '].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
activate(article);
|
||||
article.querySelector('[data-council-edit]').focus();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-council-edit]').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
trigger = button;
|
||||
selected = JSON.parse(button.dataset.article);
|
||||
if (form) {
|
||||
form.elements.title.value = selected.title;
|
||||
form.elements.journal.value = selected.journal;
|
||||
form.elements.quartile.value = selected.quartile;
|
||||
form.elements.quartile.disabled = selected.year === null;
|
||||
form.querySelector('[data-edit-error]').hidden = true;
|
||||
form.querySelector('[data-edit-note]').textContent = selected.year === null
|
||||
? 'Год публикации не указан или неоднозначен. Можно изменить название статьи и журнал; квартиль недоступен.'
|
||||
: `Изменение квартиля применяется ко всем статьям выбранного журнала за ${selected.year} год. Проверьте квартиль при смене журнала.`;
|
||||
}
|
||||
dialog.showModal();
|
||||
});
|
||||
});
|
||||
|
||||
dialog.querySelectorAll('[data-edit-close]').forEach(button => {
|
||||
button.addEventListener('click', () => { if (!saving) dialog.close(); });
|
||||
});
|
||||
dialog.addEventListener('cancel', event => { if (saving) event.preventDefault(); });
|
||||
dialog.addEventListener('click', event => { if (event.target === dialog && !saving) dialog.close(); });
|
||||
dialog.addEventListener('close', () => trigger?.focus());
|
||||
|
||||
form?.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (saving) return;
|
||||
const error = form.querySelector('[data-edit-error]');
|
||||
const submit = form.querySelector('[type="submit"]');
|
||||
const payload = {
|
||||
employee_id: selected.employee_id, edit_key: selected.edit_key, revision: selected.revision,
|
||||
title: form.elements.title.value.trim(), journal: form.elements.journal.value.trim(),
|
||||
quartile: selected.year === null ? '' : form.elements.quartile.value,
|
||||
};
|
||||
saving = true;
|
||||
submit.disabled = true;
|
||||
submit.textContent = 'Сохраняем…';
|
||||
form.setAttribute('aria-busy', 'true');
|
||||
error.hidden = true;
|
||||
try {
|
||||
const response = await fetch('/admin/council/publications', {
|
||||
method: 'POST', credentials: 'same-origin',
|
||||
headers: {'Content-Type': 'application/json', 'X-Council-Edit': '1'},
|
||||
body: JSON.stringify(payload), signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
throw new Error(typeof data.detail === 'string' ? data.detail : 'Проверьте название статьи, журнал и квартиль.');
|
||||
}
|
||||
try {
|
||||
sessionStorage.setItem(openKey, JSON.stringify(Array.from(document.querySelectorAll('[data-employee-id][open]')).map(node => node.dataset.employeeId)));
|
||||
} catch (_error) { /* Storage is optional. */ }
|
||||
window.location.reload();
|
||||
} catch (failure) {
|
||||
error.textContent = failure.name === 'TimeoutError'
|
||||
? 'Не получен ответ сервера. Обновите страницу, чтобы проверить сохранение.'
|
||||
: failure.message === 'Failed to fetch' ? 'Нет связи с сервером. Проверьте подключение и попробуйте ещё раз.' : failure.message;
|
||||
error.hidden = false;
|
||||
} finally {
|
||||
saving = false;
|
||||
submit.disabled = false;
|
||||
submit.textContent = 'Сохранить';
|
||||
form.removeAttribute('aria-busy');
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -9,6 +9,8 @@
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<a class="button button--secondary" href="/admin/council/publications" target="_blank" rel="noopener noreferrer">Статьи, журналы и квартили ↗</a>
|
||||
|
||||
{% if error %}
|
||||
<div class="council__message" role="alert">
|
||||
<h3>{% if input_error %}Проверьте параметры оценки{% elif export_error %}Не удалось создать XLSX{% else %}Не удалось загрузить публикации{% endif %}</h3>
|
||||
@@ -66,7 +68,7 @@
|
||||
<p class="council__hint">Откройте сотрудника, чтобы увидеть публикации, источники и основания. XLSX содержит всех найденных сотрудников и их публикации, включая другие страницы списка.</p>
|
||||
<div class="council__list">
|
||||
{% for candidate in candidates %}
|
||||
<details class="council__candidate">
|
||||
<details class="council__candidate" data-employee-id="{{ candidate.employee_id }}">
|
||||
<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 }}{% if candidate.minimum is not none %} из {{ candidate.minimum }}{% endif %}</small></span>
|
||||
<span class="council__counts">
|
||||
@@ -89,7 +91,9 @@
|
||||
{% if candidate.ambiguous %}<p class="council__hint">Есть сотрудники с одинаковым ФИО. Публикации из данных ВШЭ не присвоены автоматически; показаны записи из личного кабинета этого сотрудника.</p>{% endif %}
|
||||
<ol class="council__articles">
|
||||
{% for article in candidate.articles %}
|
||||
<li class="council__article">
|
||||
<li class="council__article" tabindex="0" data-council-article aria-label="{{ article.title }}. Нажмите, чтобы показать редактирование">
|
||||
{% set employee_id = candidate.employee_id %}
|
||||
{% include "council_edit_button.html" %}
|
||||
<div class="council__article-heading">
|
||||
<strong>{{ article.title }}</strong>
|
||||
<span>{{ article.year or 'Год не указан' }}</span>
|
||||
@@ -101,6 +105,7 @@
|
||||
{% if article.url %}<a class="admin__link" href="{{ article.url }}" target="_blank" rel="noopener noreferrer">Публикация на сайте</a>{% endif %}
|
||||
{% if article.rows %}<span>Строки выгрузки ВШЭ: {{ article.rows|join(', ') }}</span>{% endif %}
|
||||
</div>
|
||||
<p class="council__hint">Журнал: {{ article.journals|join(" / ") or "не указан" }} · Квартиль: {{ article.edit_quartile or "не указан или неоднозначен" }}</p>
|
||||
<ul class="council__evidence" aria-label="Критерии и подтверждения">
|
||||
<li>Зачёт в подтверждённое число: {{ 'да' if article.confirmed else 'требует проверки' }}{% if article.publication_date %}; точная дата: {{ article.publication_date.strftime('%d.%m.%Y') }}{% endif %}</li>
|
||||
<li>{{ article.thematic_status }}</li>
|
||||
@@ -137,5 +142,8 @@
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% if not error %}{% include "council_edit_dialog.html" %}{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/council.js?v={{ frontend_version }}" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,3 @@
|
||||
<button class="button button--ghost council__edit" type="button" aria-label="Редактировать статью: {{ article.title }}" aria-haspopup="dialog" data-council-edit data-article='{{ {"employee_id": employee_id, "edit_key": article.edit_key, "revision": revision, "title": article.title, "journal": article.edit_journal, "quartile": article.edit_quartile, "year": article.year}|tojson|forceescape }}'>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16 3 5 5-12 12-6 1 1-6Z"/><path d="m14 5 5 5"/></svg>
|
||||
</button>
|
||||
@@ -0,0 +1,34 @@
|
||||
<dialog class="columns-modal" data-council-dialog aria-labelledby="article-edit-title">
|
||||
<div class="columns-modal__panel">
|
||||
<div class="columns-modal__header">
|
||||
<h3 class="columns-modal__title" id="article-edit-title">Редактирование статьи</h3>
|
||||
<button class="button button--ghost" type="button" data-edit-close aria-label="Закрыть редактирование">✕</button>
|
||||
</div>
|
||||
{% if can_edit %}
|
||||
<form class="council-editor" data-edit-form>
|
||||
<label class="directory__field" for="article-edit-name">Название статьи
|
||||
<textarea class="directory__input" id="article-edit-name" name="title" required maxlength="2000" rows="3"></textarea>
|
||||
</label>
|
||||
<label class="directory__field" for="article-edit-journal">Название журнала
|
||||
<input class="directory__input" id="article-edit-journal" name="journal" required maxlength="500" list="council-journals">
|
||||
</label>
|
||||
<label class="directory__field" for="article-edit-quartile">Квартиль
|
||||
<select class="directory__input" id="article-edit-quartile" name="quartile">
|
||||
<option value="">Не указан</option>{% for q in ['Q1', 'Q2', 'Q3', 'Q4'] %}<option value="{{ q }}">{{ q }}</option>{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<p class="council__hint" data-edit-note></p>
|
||||
<p class="council__hint">Ручная корректировка требует повторного подтверждения источниками для зачёта работы.</p>
|
||||
<p class="council-editor__error" data-edit-error role="alert" hidden></p>
|
||||
<div class="council-editor__actions">
|
||||
<button class="button" type="submit">Сохранить</button>
|
||||
<button class="button button--secondary" type="button" data-edit-close>Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
<datalist id="council-journals">{% for name in journal_names|default([]) %}<option value="{{ name }}">{% endfor %}</datalist>
|
||||
{% else %}
|
||||
<p>Для редактирования статей и квартилей войдите в админку.</p>
|
||||
<a class="button" href="/admin/login">Войти в админку</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</dialog>
|
||||
@@ -0,0 +1,43 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Статьи, журналы и квартили · MIEM Employees{% endblock %}
|
||||
{% block content %}
|
||||
<section class="council" aria-labelledby="publications-title">
|
||||
<header class="council__hero"><div class="council__hero-copy">
|
||||
<h2 class="council__title" id="publications-title">Статьи, журналы и квартили</h2>
|
||||
<p class="council__intro">Публикации сотрудников из списка диссовета. Квартиль журнала относится к году публикации.</p>
|
||||
</div></header>
|
||||
<a class="admin__link" href="/admin/council">Вернуться к диссовету</a>
|
||||
<form class="council__search" method="get" role="search">
|
||||
<label class="directory__field" for="publications-employee">ФИО сотрудника<input class="directory__input" type="search" id="publications-employee" name="employee" value="{{ employee }}"></label>
|
||||
<label class="directory__field" for="publications-article">Название статьи<input class="directory__input" type="search" id="publications-article" name="title" value="{{ title }}"></label>
|
||||
<label class="directory__field" for="publications-journal">Название журнала<input class="directory__input" type="search" id="publications-journal" name="journal" value="{{ journal }}"></label>
|
||||
<button class="button" type="submit">Найти</button>
|
||||
{% if employee or title or journal %}<a class="admin__link" href="/admin/council/publications">Сбросить фильтры</a>{% endif %}
|
||||
</form>
|
||||
{% if error %}
|
||||
<div class="council__message" role="alert"><h3>Не удалось загрузить публикации</h3><p>Попробуйте ещё раз позже.</p><a class="admin__link" href="{{ request.url.path }}?{{ request.url.query }}">Повторить загрузку</a></div>
|
||||
{% else %}
|
||||
<p class="council__hint" role="status">Найдено статей: {{ matched }}{% if matched %} · Показаны {{ offset + 1 }}–{{ [offset + limit, matched]|min }}{% endif %}</p>
|
||||
{% if not can_edit %}<p class="council__hint">Просмотр доступен без входа. Для сохранения изменений <a class="admin__link" href="/admin/login">войдите в админку</a>.</p>{% endif %}
|
||||
<ol class="council__articles council__articles--editor" start="{{ offset + 1 }}">
|
||||
{% for article in articles %}
|
||||
<li class="council__article" tabindex="0" data-council-article aria-label="{{ article.title }}. Нажмите, чтобы показать редактирование">
|
||||
{% set employee_id = article.employee_id %}{% include "council_edit_button.html" %}
|
||||
<p class="council__hint">{{ article.employee_name }}</p>
|
||||
<div class="council__article-heading"><strong>{{ article.title }}</strong><span>{{ article.year or 'Год не указан' }}</span></div>
|
||||
<p class="council__hint">Журнал: {{ article.journals|join(' / ') or 'не указан' }} · Квартиль: {{ article.edit_quartile or 'не указан или неоднозначен' }}</p>
|
||||
{% if article.manual_review %}<p class="council__hint">Ручная корректировка · требует подтверждения</p>{% endif %}
|
||||
</li>
|
||||
{% else %}<li class="council__message">Статьи не найдены. Попробуйте изменить фильтры.</li>{% endfor %}
|
||||
</ol>
|
||||
{% if matched > limit %}<nav class="directory__pagination" aria-label="Страницы статей">
|
||||
{% set filters = 'employee=' ~ (employee|urlencode) ~ '&title=' ~ (title|urlencode) ~ '&journal=' ~ (journal|urlencode) %}
|
||||
{% if offset > 0 %}<a class="admin__link" href="?{{ filters }}&offset={{ offset - limit }}">Назад</a>{% endif %}
|
||||
<span>{{ offset // limit + 1 }} / {{ (matched + limit - 1) // limit }}</span>
|
||||
{% if offset + limit < matched %}<a class="admin__link" href="?{{ filters }}&offset={{ offset + limit }}">Далее</a>{% endif %}
|
||||
</nav>{% endif %}
|
||||
{% include "council_edit_dialog.html" %}
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/council.js?v={{ frontend_version }}" defer></script>{% endblock %}
|
||||
+3
-3
@@ -1,3 +1,3 @@
|
||||
APP_VERSION = "0.18.1"
|
||||
FRONTEND_VERSION = "0.18.1"
|
||||
BACKEND_VERSION = "0.18.1"
|
||||
APP_VERSION = "0.19.0"
|
||||
FRONTEND_VERSION = "0.19.0"
|
||||
BACKEND_VERSION = "0.19.0"
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Additive storage: original employee publications remain unchanged.
|
||||
CREATE TABLE IF NOT EXISTS council_corrections (
|
||||
id INTEGER PRIMARY KEY,
|
||||
revision INTEGER NOT NULL,
|
||||
data JSONB NOT NULL,
|
||||
updated_by VARCHAR(255) NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "miem-workers"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
description = "MIEM employees parser, admin API, and web admin"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Offline editor UX check: python tests/browser_council_editor.py."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
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, EmployeePublication
|
||||
from app.security import SESSION_COOKIE, sign_session
|
||||
from app.services import council
|
||||
|
||||
|
||||
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:
|
||||
person = Employee(profile_key='editor', full_name='Иванов Иван Иванович',
|
||||
canonical_url='https://www.hse.ru/staff/test',
|
||||
current_data={'sections': [{'title': 'Учёные степени', 'items': ['Доктор технических наук']}]})
|
||||
db.add(person)
|
||||
db.flush()
|
||||
db.add(EmployeePublication(employee_id=person.id, title='Исследование передачи данных',
|
||||
year=2024, publication_type='ARTICLE', raw_data={'journal': 'Журнал связи'}, source_hash='editor'))
|
||||
db.commit()
|
||||
|
||||
def database():
|
||||
with factory() as db:
|
||||
yield db
|
||||
|
||||
settings = Settings(_env_file=None, session_secret='browser-editor-test', admin_username='admin', admin_password='test')
|
||||
original = council._articles_by_author
|
||||
council._articles_by_author = lambda: {}
|
||||
app.dependency_overrides[get_db] = database
|
||||
app.dependency_overrides[get_settings] = lambda: settings
|
||||
client = TestClient(app)
|
||||
output = Path('.impeccable/review/council-editor')
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def serve(route):
|
||||
request = route.request
|
||||
url = urlsplit(request.url)
|
||||
response = client.request(request.method, url.path + ('?' + url.query if url.query else ''),
|
||||
content=request.post_data_buffer,
|
||||
headers={k: v for k, v in request.headers.items() if k in {'content-type', 'x-council-edit'}})
|
||||
route.fulfill(status=response.status_code, body=response.content,
|
||||
headers={k: v for k, v in response.headers.items() if k in {'content-type', 'content-disposition'}})
|
||||
|
||||
try:
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(executable_path=os.getenv('BROWSER_EXECUTABLE'))
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 1000})
|
||||
context.route('**/*', serve)
|
||||
page = context.new_page()
|
||||
errors = []
|
||||
page.on('pageerror', lambda error: errors.append(str(error)))
|
||||
page.goto('http://miem.test/admin/council')
|
||||
page.locator('.council__candidate-summary').click()
|
||||
article = page.locator('[data-council-article]')
|
||||
pencil = article.locator('[data-council-edit]')
|
||||
expect(pencil).to_be_hidden()
|
||||
article.locator('strong').click()
|
||||
expect(pencil).to_be_visible()
|
||||
pencil.click()
|
||||
expect(page.get_by_role('dialog')).to_be_visible()
|
||||
expect(page.get_by_role('link', name='Войти в админку', exact=True)).to_be_visible()
|
||||
page.keyboard.press('Escape')
|
||||
expect(pencil).to_be_focused()
|
||||
client.cookies.set(SESSION_COOKIE, sign_session('admin', settings))
|
||||
page.reload()
|
||||
page.locator('.council__candidate-summary').click()
|
||||
article.focus()
|
||||
page.keyboard.press('Enter')
|
||||
expect(pencil).to_be_focused()
|
||||
page.keyboard.press('Enter')
|
||||
expect(page.get_by_label('Название статьи', exact=True)).to_have_value('Исследование передачи данных')
|
||||
page.get_by_label('Название статьи', exact=True).fill('Уточнённое исследование')
|
||||
page.get_by_label('Название журнала', exact=True).fill('Новый журнал')
|
||||
page.get_by_label('Квартиль').select_option('Q1')
|
||||
page.screenshot(path=str(output / 'edit-desktop.png'))
|
||||
page.set_viewport_size({'width': 320, 'height': 844})
|
||||
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth')
|
||||
assert page.get_by_role('dialog').evaluate('e => e.scrollWidth <= e.clientWidth')
|
||||
page.screenshot(path=str(output / 'edit-mobile.png'))
|
||||
page.get_by_role('button', name='Сохранить', exact=True).click()
|
||||
expect(article.locator('strong')).to_have_text('Уточнённое исследование')
|
||||
expect(page.locator('.council__candidate')).to_have_attribute('open', '')
|
||||
with context.expect_page() as opened:
|
||||
page.get_by_role('link', name='Статьи, журналы и квартили').click()
|
||||
window = opened.value
|
||||
window.wait_for_load_state()
|
||||
window.on('pageerror', lambda error: errors.append(str(error)))
|
||||
window.get_by_label('ФИО сотрудника').fill('Иванов')
|
||||
window.get_by_role('searchbox', name='Название статьи', exact=True).fill('уточнённое')
|
||||
window.get_by_role('searchbox', name='Название журнала', exact=True).fill('новый')
|
||||
window.get_by_role('button', name='Найти', exact=True).click()
|
||||
expect(window.locator('[data-council-article]')).to_have_count(1)
|
||||
for width in (1440, 390, 320):
|
||||
window.set_viewport_size({'width': width, 'height': 900})
|
||||
assert window.evaluate('document.documentElement.scrollWidth <= innerWidth')
|
||||
if width in (1440, 320):
|
||||
window.screenshot(path=str(output / f'list-{width}.png'), full_page=True)
|
||||
window.locator('[data-council-article] strong').click()
|
||||
window.locator('[data-council-edit]').click()
|
||||
window.get_by_label('Квартиль').select_option('Q2')
|
||||
window.get_by_role('button', name='Сохранить', exact=True).click()
|
||||
expect(window.get_by_text('Журнал: Новый журнал · Квартиль: Q2', exact=True)).to_be_visible()
|
||||
# The original tab now carries a stale revision.
|
||||
article.locator('strong').click()
|
||||
pencil.click()
|
||||
page.get_by_role('button', name='Сохранить', exact=True).click()
|
||||
expect(page.get_by_role('alert')).to_contain_text('Данные уже изменены')
|
||||
page.keyboard.press('Escape')
|
||||
page.reload()
|
||||
page.locator('.council__candidate-summary').click()
|
||||
expect(page.get_by_text('Журнал: Новый журнал · Квартиль: Q2', exact=True)).to_be_visible()
|
||||
window.get_by_role('searchbox', name='Название статьи', exact=True).fill('Нет совпадений')
|
||||
window.get_by_role('button', name='Найти', exact=True).click()
|
||||
expect(window.get_by_text('Статьи не найдены.', exact=False)).to_be_visible()
|
||||
assert not errors, errors
|
||||
browser.close()
|
||||
finally:
|
||||
council._articles_by_author = original
|
||||
app.dependency_overrides.clear()
|
||||
client.close()
|
||||
engine.dispose()
|
||||
print(f'Council editor browser checks passed; screenshots: {output}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+1
-1
@@ -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"] == "0.18.1"
|
||||
assert response.json()["backend_version"] == "0.19.0"
|
||||
|
||||
|
||||
def test_api_employees_and_stats_require_admin_session():
|
||||
|
||||
@@ -219,7 +219,7 @@ def test_public_page_data_minimization_and_safe_links(db_session, export):
|
||||
assert "<script>" in response.text and "<script>" not in response.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 0.18.1 · Frontend 0.18.1" in response.text
|
||||
assert "Backend 0.19.0 · Frontend 0.19.0" 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
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.config import Settings, get_settings
|
||||
from app.db import get_db
|
||||
from app.main import app
|
||||
from app.models import CouncilCorrections, Employee, EmployeePublication
|
||||
from app.security import SESSION_COOKIE, sign_session
|
||||
from app.services import council
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def editor(db_session, monkeypatch):
|
||||
monkeypatch.setattr(council, '_articles_by_author', lambda: {})
|
||||
for number in range(2):
|
||||
person = Employee(profile_key=f'editor:{number}', full_name=f'Иванов {number}',
|
||||
canonical_url='https://www.hse.ru/staff/test',
|
||||
current_data={'sections': [{'title': 'Учёные степени', 'items': ['Доктор технических наук']}]})
|
||||
db_session.add(person)
|
||||
db_session.flush()
|
||||
db_session.add(EmployeePublication(employee_id=person.id, title=f'Статья {number}', year=2024,
|
||||
publication_type='ARTICLE', source_hash=f'editor:{number}', raw_data={'journal': 'Общий журнал'}))
|
||||
db_session.commit()
|
||||
settings = Settings(_env_file=None, admin_username='admin', admin_password='test', session_secret='editor-test')
|
||||
app.dependency_overrides[get_db] = lambda: db_session
|
||||
app.dependency_overrides[get_settings] = lambda: settings
|
||||
client = TestClient(app)
|
||||
client.cookies.set(SESSION_COOKIE, sign_session('admin', settings))
|
||||
candidate = council.council_candidates(db_session)['candidates'][0]
|
||||
article = candidate['articles'][0]
|
||||
payload = {'employee_id': candidate['employee_id'], 'edit_key': article['edit_key'], 'revision': 0,
|
||||
'title': 'Исправленная статья', 'journal': 'Общий журнал', 'quartile': 'Q1'}
|
||||
try:
|
||||
yield client, payload
|
||||
finally:
|
||||
client.close()
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def save(client, payload):
|
||||
return client.post('/admin/council/publications', json=payload, headers={'X-Council-Edit': '1'})
|
||||
|
||||
|
||||
def test_editor_shared_quartile_persistence_filter_and_export(editor, db_session):
|
||||
client, payload = editor
|
||||
assert save(client, payload).status_code == 200
|
||||
db_session.expire_all()
|
||||
result = council.council_candidates(db_session, today=date(2026, 10, 9))
|
||||
assert result['revision'] == 1
|
||||
assert [c['q1_count'] for c in result['candidates']] == [1, 1]
|
||||
articles = [a for c in result['candidates'] for a in c['articles']]
|
||||
assert all(a['manual_review'] and not a['confirmed'] for a in articles)
|
||||
assert next(a for a in articles if a['edit_key'] == payload['edit_key'] and a['title'] == payload['title'])
|
||||
assert db_session.scalars(select(EmployeePublication.title)).all() == ['Статья 0', 'Статья 1']
|
||||
for filters in ({'title': 'исправленная'}, {'employee': 'иванов 0'}, {'journal': 'общий ЖУРНАЛ'}):
|
||||
response = client.get('/admin/council/publications', params=filters)
|
||||
assert response.status_code == 200
|
||||
assert payload['title'] in response.text
|
||||
assert 'Статьи не найдены' in client.get('/admin/council/publications?title=absent').text
|
||||
main = client.get('/admin/council')
|
||||
assert 'data-council-edit' in main.text and payload['title'] in main.text
|
||||
from io import BytesIO
|
||||
from openpyxl import load_workbook
|
||||
workbook = load_workbook(BytesIO(client.get('/admin/council/export.xlsx').content))
|
||||
assert any(payload['title'] in str(row) for row in workbook['Публикации'].values)
|
||||
# A stale window must not overwrite another save.
|
||||
assert save(client, {**payload, 'title': 'Устаревшая правка'}).status_code == 409
|
||||
assert db_session.get(CouncilCorrections, 1).revision == 1
|
||||
|
||||
|
||||
def test_editor_permissions_csrf_validation_and_missing_article(editor, db_session):
|
||||
client, payload = editor
|
||||
assert client.post('/admin/council/publications', json=payload).status_code == 403
|
||||
for values in ({'title': ' '}, {'journal': ' '}, {'journal': '!!!'}, {'quartile': 'Q5'}, {'quartile': '<script>'}, {'revision': -1}):
|
||||
assert save(client, {**payload, **values}).status_code == 422
|
||||
assert save(client, {**payload, 'edit_key': '0' * 64}).status_code == 404
|
||||
assert db_session.get(CouncilCorrections, 1) is None
|
||||
client.cookies.clear()
|
||||
assert save(client, payload).status_code == 401
|
||||
response = client.get('/admin/council/publications')
|
||||
assert response.status_code == 200 and 'Для редактирования' in response.text
|
||||
|
||||
|
||||
def test_editor_journal_reassignment_year_scope_and_unknown_year(editor, db_session):
|
||||
client, payload = editor
|
||||
old = db_session.scalar(select(EmployeePublication).where(EmployeePublication.employee_id != payload['employee_id']))
|
||||
old.year = 2023
|
||||
db_session.commit()
|
||||
assert save(client, {**payload, 'journal': 'Новый журнал', 'quartile': 'Q2'}).status_code == 200
|
||||
db_session.expire_all()
|
||||
result = council.council_candidates(db_session)
|
||||
corrected = next(c for c in result['candidates'] if c['employee_id'] == payload['employee_id'])
|
||||
assert corrected['q2_count'] == 1
|
||||
assert corrected['articles'][0]['journals'] == ['Новый журнал']
|
||||
untouched = next(c for c in result['candidates'] if c['employee_id'] != payload['employee_id'])
|
||||
assert untouched['q2_count'] == 0
|
||||
assert untouched['articles'][0]['journals'] == ['Общий журнал']
|
||||
old.year = None
|
||||
db_session.commit()
|
||||
article = next(c for c in council.council_candidates(db_session)['candidates'] if c['employee_id'] == old.employee_id)['articles'][0]
|
||||
unknown = {**payload, 'employee_id': old.employee_id, 'edit_key': article['edit_key'], 'revision': 1}
|
||||
assert save(client, unknown).status_code == 422
|
||||
assert save(client, {**unknown, 'quartile': ''}).status_code == 200
|
||||
|
||||
|
||||
def test_editor_csv_only_and_escaping(editor, db_session, monkeypatch):
|
||||
client, payload = editor
|
||||
monkeypatch.setattr(council, '_articles_by_author', lambda: {'иванов 0': [{
|
||||
'title': 'Выгрузка', 'year': 2024, 'doi': '10.1234/csv', 'types': [], 'journals': [],
|
||||
'quartiles': [], 'origins': ['Данные ВШЭ'], 'rows': [2], 'in_csv': True, 'in_db': False, 'url': None}]})
|
||||
article = next(a for c in council.council_candidates(db_session)['candidates']
|
||||
for a in c['articles'] if a['doi'] == '10.1234/csv')
|
||||
payload.update(edit_key=article['edit_key'], title='<script>alert(1)</script>', journal='Журнал', quartile='Q4')
|
||||
assert save(client, payload).status_code == 200
|
||||
page = client.get('/admin/council/publications')
|
||||
assert '<script>alert(1)</script>' not in page.text
|
||||
assert '<script>' in page.text
|
||||
|
||||
|
||||
def test_editor_reassignment_clears_old_journal_evidence(editor, db_session):
|
||||
client, payload = editor
|
||||
source = db_session.scalar(select(EmployeePublication).where(EmployeePublication.employee_id == payload['employee_id']))
|
||||
source.raw_data = {'journal': 'Бизнес-информатика', 'issn': '1998-0663'}
|
||||
db_session.commit()
|
||||
before = next(c for c in council.council_candidates(db_session)['candidates'] if c['employee_id'] == payload['employee_id'])
|
||||
assert before['k1_count'] == 1
|
||||
assert save(client, {**payload, 'journal': 'Неизвестный журнал', 'quartile': 'Q4'}).status_code == 200
|
||||
after = next(c for c in council.council_candidates(db_session)['candidates'] if c['employee_id'] == payload['employee_id'])
|
||||
assert (after['k1_count'], after['q1_count'], after['q2_count']) == (0, 0, 0)
|
||||
assert after['articles'][0]['catalog_records'] == []
|
||||
assert not after['articles'][0]['specialty_codes']
|
||||
assert source.raw_data['issn'] == '1998-0663'
|
||||
|
||||
|
||||
def test_editor_pagination_preserves_filters(editor, db_session):
|
||||
client, payload = editor
|
||||
for number in range(55):
|
||||
db_session.add(EmployeePublication(employee_id=payload['employee_id'], title=f'Пагинация {number:02}',
|
||||
year=2024, source_hash=f'page:{number}', raw_data={'journal': 'Тестовый журнал'}))
|
||||
db_session.commit()
|
||||
response = client.get('/admin/council/publications?employee=Иванов&title=Пагинация&journal=Тестовый&offset=999')
|
||||
assert response.status_code == 200
|
||||
assert 'Показаны 51–55' in response.text
|
||||
assert response.text.count('data-council-article') == 5
|
||||
assert 'offset=0' in response.text
|
||||
assert 'name="employee" value="Иванов"' in response.text
|
||||
|
||||
|
||||
def test_editor_database_failure_preserves_data(editor, db_session, monkeypatch):
|
||||
from sqlalchemy.exc import OperationalError
|
||||
client, payload = editor
|
||||
def unavailable():
|
||||
raise OperationalError('UPDATE', {}, Exception('private database details'))
|
||||
monkeypatch.setattr(db_session, 'commit', unavailable)
|
||||
response = save(client, payload)
|
||||
assert response.status_code == 503
|
||||
assert 'private database details' not in response.text
|
||||
assert db_session.get(CouncilCorrections, 1) is None
|
||||
Reference in new issue
Block a user