Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbe94db9ef | ||
|
|
7d1939a598 | ||
|
|
a4b188d562 | ||
|
|
21a6d51432 | ||
|
|
41467471e2 | ||
|
|
8dde82ab8a | ||
|
|
10b91314e3 |
No files matched your search
@@ -29,6 +29,7 @@ jobs:
|
||||
- run: python -m pytest -q
|
||||
- run: node --check app/static/admin.js
|
||||
- run: node --check app/static/council.js
|
||||
- run: node --check app/static/dpo.js
|
||||
- run: node --check app/static/users.js
|
||||
- run: node --check app/static/guide.js
|
||||
- run: sh -n infra/postgres-backup.sh
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
# Changelog
|
||||
|
||||
## 2.4.0
|
||||
|
||||
- Любой вошедший пользователь может подтвердить список ДПО в карточке сотрудника. Справочник и XLSX учитывают подтверждённое количество, включая ноль. Фильтр повышения квалификации учитывает вид и год подтверждённых курсов.
|
||||
- При изменении сведений о ДПО в профиле карточка снова требует проверки. До повторного подтверждения действует предыдущий список.
|
||||
|
||||
## Эксплуатация · 2026-11-24
|
||||
|
||||
- После слияния в `main` Workers запрашивает запуск `workers-cd.yml` в `admin/infra-platform`. Результат выкладки фиксируется в Actions платформы.
|
||||
|
||||
## 2.3.1
|
||||
|
||||
- Исправлен подсчёт ДПО для многострочных записей и ранее сохранённых профилей. Возможные повторы отмечаются в справочнике и карточке. При смене страницы виден индикатор загрузки. Профессиональные интересы показаны ссылками.
|
||||
|
||||
## 2.3.0
|
||||
|
||||
- Раздел ДПО объединяет сведения из профиля и документов. Справочник показывает отдельный счётчик ДПО, а предупреждение ведёт к нераспознанным фрагментам в карточке.
|
||||
|
||||
+49
-2
@@ -6,11 +6,12 @@ from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy import desc, func, select, update
|
||||
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm import Session, lazyload
|
||||
from sqlalchemy.orm.exc import StaleDataError
|
||||
|
||||
from app.config import Settings, get_settings
|
||||
from app.db import SessionLocal, get_db
|
||||
from app.models import CrawlError, CrawlRun, Employee, CouncilCorrections, UserAction
|
||||
from app.models import CrawlError, CrawlRun, Employee, DpoReview, utcnow, CouncilCorrections, UserAction
|
||||
from app.security import (SESSION_COOKIE, LOGIN_CSRF_COOKIE, SESSION_SECONDS, USER_ROLES, require_admin, require_user,
|
||||
optional_user, sign_session, authenticate, can_use_council, check_csrf)
|
||||
import secrets
|
||||
@@ -18,6 +19,7 @@ from app.services.admin_data import (
|
||||
DIRECTORY_COLUMNS,
|
||||
EMPLOYEE_SORTS,
|
||||
employee_detail_payload,
|
||||
dpo_sections, dpo_source_digest, _display_sections,
|
||||
format_admin_datetime,
|
||||
list_employees_page,
|
||||
run_detail_payload,
|
||||
@@ -379,6 +381,51 @@ def employee_detail(
|
||||
)
|
||||
|
||||
|
||||
class DpoCourse(BaseModel):
|
||||
model_config = ConfigDict(str_strip_whitespace=True)
|
||||
title: str = Field(min_length=1, max_length=8000)
|
||||
kind: Literal["training", "retraining", "other"]
|
||||
year: int | None = Field(default=None, ge=1900, le=2100)
|
||||
evidence: str = Field(default="", max_length=4000)
|
||||
|
||||
|
||||
class DpoConfirmation(BaseModel):
|
||||
courses: list[DpoCourse] = Field(max_length=1000)
|
||||
confirm_empty: bool = False
|
||||
revision: int = Field(ge=0)
|
||||
source: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
|
||||
|
||||
@router.post("/employees/{employee_id}/dpo")
|
||||
def confirm_dpo(employee_id: int, change: DpoConfirmation, request: Request,
|
||||
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
|
||||
actor = require_user(request, settings, db)
|
||||
if not change.courses and not change.confirm_empty:
|
||||
raise HTTPException(422, "Подтвердите отсутствие курсов ДПО.")
|
||||
employee = db.scalar(select(Employee).options(lazyload(Employee.dpo_review))
|
||||
.where(Employee.id == employee_id).with_for_update())
|
||||
if employee is None:
|
||||
raise HTTPException(404, "Сотрудник не найден.")
|
||||
digest = dpo_source_digest(dpo_sections(_display_sections(employee.current_data or {})))
|
||||
review = employee.dpo_review
|
||||
conflict = "Данные изменились. Обновите карточку и сверьте список."
|
||||
if digest != change.source or (review.revision if review else 0) != change.revision:
|
||||
raise HTTPException(409, conflict)
|
||||
if review is None:
|
||||
review = DpoReview(employee_id=employee_id)
|
||||
db.add(review)
|
||||
review.courses = [course.model_dump() for course in change.courses]
|
||||
review.source_digest = digest
|
||||
review.updated_by = actor.username
|
||||
review.updated_at = utcnow()
|
||||
try:
|
||||
db.commit()
|
||||
except (IntegrityError, StaleDataError):
|
||||
db.rollback()
|
||||
raise HTTPException(409, conflict)
|
||||
return {"saved": True}
|
||||
|
||||
|
||||
@router.post("/employees/{employee_id}/refresh")
|
||||
def refresh_employee_detail(
|
||||
employee_id: int,
|
||||
|
||||
@@ -43,6 +43,8 @@ class Employee(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, onupdate=utcnow, nullable=False)
|
||||
|
||||
dpo_review: Mapped["DpoReview | None"] = relationship(lazy="joined", cascade="all, delete-orphan")
|
||||
|
||||
snapshots: Mapped[list["EmployeeSnapshot"]] = relationship(back_populates="employee")
|
||||
profile_urls: Mapped[list["EmployeeProfileUrl"]] = relationship(back_populates="employee", cascade="all, delete-orphan")
|
||||
tabs: Mapped[list["ProfileTab"]] = relationship(back_populates="employee", cascade="all, delete-orphan")
|
||||
@@ -51,6 +53,18 @@ class Employee(Base):
|
||||
crawl_run_changes: Mapped[list["CrawlRunEmployeeChange"]] = relationship(back_populates="employee")
|
||||
|
||||
|
||||
class DpoReview(Base):
|
||||
__tablename__ = "dpo_reviews"
|
||||
|
||||
employee_id: Mapped[int] = mapped_column(ForeignKey("employees.id", ondelete="CASCADE"), primary_key=True)
|
||||
revision: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
courses: Mapped[list] = mapped_column(json_type, nullable=False)
|
||||
source_digest: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
updated_by: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, nullable=False)
|
||||
__mapper_args__ = {"version_id_col": revision}
|
||||
|
||||
|
||||
class EmployeeProfileUrl(Base):
|
||||
__tablename__ = "employee_profile_urls"
|
||||
__table_args__ = (
|
||||
|
||||
+16
-1
@@ -7,6 +7,16 @@ _QUOTE = re.compile(r'«([^»]+)»|"([^"]+)"')
|
||||
_EVENT = re.compile(r"стажиров|стипенди|исследовательск|обучени|квалификаци|переподготовк|прош[её]л|прошла|семинар|сертификаци|программ[аеуы]|курсы?\b", re.I)
|
||||
_CONTINUES = re.compile(r"(?:по программе|присвоением степени|на тему|по курсу|по теме|по специальности)[:\s]*$", re.I)
|
||||
_CAPTION = re.compile(r"^(?:удостоверение|сертификат|свидетельство)(?: о повышении квалификации)?[.:]?$", re.I)
|
||||
_DATED_ROW = re.compile(r'\s+(?=(?:19|20)\d{2}\s*г\.\s*["«])')
|
||||
|
||||
|
||||
def education_title(title):
|
||||
labels = {"дополнительное образование", "повышение квалификации", "курсы повышения квалификации"}
|
||||
return any(part.strip().rstrip(":") in labels for part in str(title).casefold().split("/"))
|
||||
|
||||
|
||||
def split_dated_rows(text):
|
||||
return _DATED_ROW.split(text) if re.match(r"^(?:19|20)\d{2}\s*г\.", text) else [text]
|
||||
|
||||
|
||||
def _key(text):
|
||||
@@ -39,11 +49,14 @@ def assemble(rows):
|
||||
pending.append([text, year, structured, list_item])
|
||||
|
||||
for text, year, structured, _ in pending:
|
||||
if not structured and (len(_key(text).split()) < 2 or not (_EVENT.search(text) or YEAR.match(text))):
|
||||
certificate = re.match(r"^сертификат\s+[«\"]", text, re.I)
|
||||
if not structured and (len(_key(text).split()) < 2 or not (_EVENT.search(text) or YEAR.match(text) or certificate)):
|
||||
unresolved.append(text)
|
||||
continue
|
||||
quotes = [a or b for a, b in _QUOTE.findall(text)]
|
||||
title = _key(quotes[-1]) if quotes else ""
|
||||
if re.match(r'^(?:19|20)\d{2}\s*г\.\s*["«]', text) and quotes:
|
||||
title = _key(quotes[0])
|
||||
if structured and text.lstrip("0123456789 ").startswith("«"):
|
||||
title = _key(text.split("«", 1)[1].rsplit("»", 1)[0])
|
||||
provider = _provider(text.rsplit("»", 1)[-1] if structured and "»" in text else text)
|
||||
@@ -60,6 +73,8 @@ def assemble(rows):
|
||||
continue
|
||||
if any(e["text"] == text for e in events):
|
||||
continue
|
||||
if title and any(e["title"] == title and e["year"] == year for e in events):
|
||||
unresolved.append("Возможный повтор: " + text)
|
||||
events.append(dict(text=text, year=year, structured=structured, title=title, provider=provider))
|
||||
return events, unresolved
|
||||
|
||||
+26
-5
@@ -8,7 +8,7 @@ from urllib.parse import urljoin
|
||||
from bs4 import BeautifulSoup, Comment, NavigableString, Tag
|
||||
from requests import Session
|
||||
|
||||
from app.parser.education import assemble
|
||||
from app.parser.education import assemble, education_title, split_dated_rows
|
||||
from app.parser.education_document import read_document
|
||||
from app.parser.profile_url import normalize_profile_url, parse_profile_identity
|
||||
from app.version import BACKEND_VERSION
|
||||
@@ -111,9 +111,8 @@ def extract_sections(soup: BeautifulSoup, source_url: str, document_reader=None)
|
||||
if not title or "расписание занятий" in title.lower():
|
||||
continue
|
||||
nodes = _collect_between_h2(h2)
|
||||
education_titles = {part.strip().rstrip(":") for part in title.casefold().split("/")}
|
||||
if (h2.find_parent(attrs={"tab-node": "additional_education"})
|
||||
or education_titles & {"дополнительное образование", "повышение квалификации", "курсы повышения квалификации"}):
|
||||
or education_title(title)):
|
||||
sections.append(_parse_additional_education(title, nodes, source_url, document_reader))
|
||||
continue
|
||||
raw_text = _nodes_raw_text(nodes)
|
||||
@@ -125,6 +124,9 @@ def extract_sections(soup: BeautifulSoup, source_url: str, document_reader=None)
|
||||
links.extend(_extract_links(node, source_url))
|
||||
|
||||
section_type = _infer_section_type(title, nodes)
|
||||
if title.casefold().rstrip(":") == "профессиональные интересы":
|
||||
sections.append({"title": title, "slug": _slugify(title), "type": "links", "links": links})
|
||||
continue
|
||||
section = {
|
||||
"title": title,
|
||||
"slug": _slugify(title),
|
||||
@@ -625,6 +627,9 @@ def _parse_additional_education(title: str, nodes: list, source_url: str, docume
|
||||
for original in nodes:
|
||||
node = deepcopy(original)
|
||||
if isinstance(node, Tag):
|
||||
for image in node.select("img[src]"):
|
||||
if _FILE_URL.search(image["src"]) and not image.find_parent("a", href=True):
|
||||
documents.setdefault(urljoin(source_url, image["src"]), image.get("alt") or "Изображение документа")
|
||||
for anchor in node.select("a[href]"):
|
||||
following = anchor.next_sibling
|
||||
suffix = following.get_text(strip=True) if isinstance(following, Tag) else str(following or "")
|
||||
@@ -644,7 +649,23 @@ def _parse_additional_education(title: str, nodes: list, source_url: str, docume
|
||||
links.extend(block_links)
|
||||
year_node = block.find(class_="person-list-hangover", recursive=False) if is_tag else None
|
||||
year_match = _INITIAL_YEAR.match(year_node.get_text(strip=True)) if year_node else None
|
||||
rows.append((text, int(year_match[0]) if year_match else None, bool(year_node), is_tag and block.name == "li"))
|
||||
if is_tag and not year_node and block.find("br"):
|
||||
for br in block.find_all("br"):
|
||||
br.replace_with("\n")
|
||||
lines = []
|
||||
for line in block.get_text(" ", strip=False).splitlines():
|
||||
line = normalize_ws(_FILE_SIZE.sub("", _FILE_CAPTION.sub("", line)))
|
||||
if not re.search(r"\w", line):
|
||||
continue
|
||||
if lines and not (_INITIAL_YEAR.match(line) or re.match(r"^(?:курс|повышение квалификации)\b", line, re.I)):
|
||||
lines[-1] += " " + line
|
||||
else:
|
||||
lines.append(line)
|
||||
else:
|
||||
lines = [text]
|
||||
for line in lines:
|
||||
for part in split_dated_rows(line):
|
||||
rows.append((part, int(year_match[0]) if year_match else None, bool(year_node), is_tag and block.name == "li"))
|
||||
for url, caption in documents.items():
|
||||
recognized = document_reader(url) if document_reader else None
|
||||
if recognized:
|
||||
@@ -656,7 +677,7 @@ def _parse_additional_education(title: str, nodes: list, source_url: str, docume
|
||||
year_entries = [{"year": event["year"], "text": event["text"], "links": []}
|
||||
for event in events if event["structured"]]
|
||||
return {
|
||||
"title": title, "slug": _slugify(title), "type": "additional_education",
|
||||
"title": title, "slug": _slugify(title), "type": "additional_education", "education_format": 2,
|
||||
"items": items, "paragraphs": [], "year_entries": year_entries,
|
||||
"unresolved": unresolved, "unresolved_documents": unresolved_documents,
|
||||
"raw_text": "\n".join(items), "links": links,
|
||||
|
||||
+92
-11
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import date, datetime, time
|
||||
from math import ceil
|
||||
@@ -10,6 +12,7 @@ from sqlalchemy import Select, Text, and_, desc, func, or_, select
|
||||
from sqlalchemy.orm import Session, selectinload
|
||||
|
||||
from app.models import CrawlError, CrawlRun, CrawlRunEmployeeChange, Employee, EmployeeNewsLink
|
||||
from app.parser.education import assemble, education_title, split_dated_rows
|
||||
from app.services.academic_degrees import academic_degrees
|
||||
|
||||
EMPLOYEE_SORTS = {
|
||||
@@ -32,7 +35,7 @@ DIRECTORY_COLUMNS = (
|
||||
("address", "Адрес", "address"),
|
||||
("academic_degree", "Учёная степень", "academic_degree_text"),
|
||||
("publications_count", "Публикации", "publications_count"),
|
||||
("courses_count", "Курсы", "courses_count"),
|
||||
("courses_count", "Преподаваемые курсы", "courses_count"),
|
||||
("news_count", "Новости", "news_count"),
|
||||
("first_seen_at", "Впервые найден", "first_seen_display"),
|
||||
("last_seen_at", "Последний раз найден", "last_seen_display"),
|
||||
@@ -83,17 +86,84 @@ def _has_training(data: dict[str, Any], since_year: int | None) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def employee_display_payload(employee: Employee) -> dict[str, Any]:
|
||||
def _display_sections(data):
|
||||
sections = []
|
||||
for section in _as_list(data.get("sections")):
|
||||
if not isinstance(section, dict) or section.get("education_format") == 2:
|
||||
sections.append(section)
|
||||
continue
|
||||
typed = section.get("type") == "additional_education"
|
||||
if not typed and not education_title(section.get("title")):
|
||||
sections.append(section)
|
||||
continue
|
||||
# Profiles collected before dedicated DPO parsing retain years and free text separately.
|
||||
rows = [(entry["text"], entry.get("year"), True, False)
|
||||
for entry in section.get("year_entries", []) if isinstance(entry, dict) and entry.get("text")]
|
||||
texts = _clean_list(section.get("paragraphs")) + _clean_list(section.get("items"))
|
||||
if not rows and not texts:
|
||||
texts = str(section.get("raw_text") or "").splitlines()
|
||||
structured_texts = {row[0] for row in rows}
|
||||
for text in texts:
|
||||
if text not in structured_texts:
|
||||
rows.extend((part, None, False, False) for part in split_dated_rows(text))
|
||||
events, unresolved = assemble(rows)
|
||||
unresolved.extend(_clean_list(section.get("unresolved")))
|
||||
if not typed:
|
||||
unresolved.append("Сведения взяты из прежней версии профиля. Требуется обновление карточки.")
|
||||
sections.append({**section, "type": "additional_education", "paragraphs": [],
|
||||
"items": [e["text"] for e in events],
|
||||
"unresolved": list(dict.fromkeys(unresolved))})
|
||||
return sections
|
||||
|
||||
|
||||
def dpo_sections(sections):
|
||||
return [s for s in sections if isinstance(s, dict) and s.get("type") == "additional_education"]
|
||||
|
||||
|
||||
def dpo_source_digest(education):
|
||||
# Ignore presentation order and unrelated profile updates.
|
||||
def canonical(value):
|
||||
return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
sources = [canonical({key: sorted(canonical(v) for v in section.get(key, []))
|
||||
for key in ("items", "year_entries", "unresolved", "unresolved_documents", "links")}
|
||||
| {"title": section.get("title")}) for section in education]
|
||||
return hashlib.sha256(canonical(sorted(sources)).encode()).hexdigest()
|
||||
|
||||
|
||||
def dpo_suggestions(education):
|
||||
courses = []
|
||||
for section in education:
|
||||
years = {entry.get("text"): entry["year"] for entry in _as_list(section.get("year_entries"))
|
||||
if isinstance(entry, dict) and type(entry.get("year")) is int}
|
||||
for title in section.get("items", []):
|
||||
dedicated = str(section.get("title") or "").casefold().strip().rstrip(":") in {
|
||||
_TRAINING_LABEL, "курсы повышения квалификации"}
|
||||
text = _QUOTED_TEXT.sub("", title)
|
||||
year = years.get(title)
|
||||
if year is None and (match := _TRAINING_YEAR.search(text)):
|
||||
year = int(match.group(1) or match.group(2))
|
||||
kind = "training" if dedicated or _TRAINING_MENTION.search(text) else "other"
|
||||
if "переподготовк" in text.casefold():
|
||||
kind = "retraining"
|
||||
courses.append({"title": title, "kind": kind, "year": year,
|
||||
"evidence": ""})
|
||||
return courses
|
||||
|
||||
|
||||
def employee_display_payload(employee: Employee, *, sections=None) -> dict[str, Any]:
|
||||
data = _as_dict(employee.current_data)
|
||||
contacts = _as_dict(data.get("contacts"))
|
||||
sections = _as_list(data.get("sections"))
|
||||
if sections is None:
|
||||
sections = _display_sections(data)
|
||||
stored_news_links = _stored_news_links(employee)
|
||||
positions = _clean_list(data.get("positions"))
|
||||
emails = _clean_list(contacts.get("emails"))
|
||||
phones = _clean_list(contacts.get("phones"))
|
||||
degree_values = academic_degrees(data)
|
||||
education = [s for s in sections if isinstance(s, dict) and s.get("type") == "additional_education"]
|
||||
parsed_education = bool(education) or data.get("education_parsed", False)
|
||||
education = dpo_sections(sections)
|
||||
review = employee.dpo_review
|
||||
dpo_count = sum(len(s.get("items", [])) for s in education)
|
||||
return {
|
||||
"id": employee.id,
|
||||
"full_name": employee.full_name,
|
||||
@@ -110,8 +180,8 @@ def employee_display_payload(employee: Employee) -> dict[str, Any]:
|
||||
"address": contacts.get("address"),
|
||||
"academic_degree_text": "; ".join(degree_values),
|
||||
"publications_count": _count_section_items(sections, "publications"),
|
||||
"dpo_count": sum(len(s.get("items", [])) for s in education) if parsed_education else None,
|
||||
"dpo_uncertain": any(s.get("unresolved") or s.get("unresolved_documents") for s in education),
|
||||
"dpo_count": len(review.courses) if review else dpo_count or None,
|
||||
"dpo_uncertain": review.source_digest != dpo_source_digest(education) if review else any(not s.get("items") or s.get("unresolved") or s.get("unresolved_documents") for s in education),
|
||||
"courses_count": _count_section_items(sections, "courses_by_year"),
|
||||
"news_count": len(stored_news_links) or _count_section_items(sections, "news"),
|
||||
"first_seen_at": employee.first_seen_at.isoformat() if employee.first_seen_at else None,
|
||||
@@ -125,9 +195,12 @@ def employee_display_payload(employee: Employee) -> dict[str, Any]:
|
||||
|
||||
def employee_detail_payload(employee: Employee) -> dict[str, Any]:
|
||||
data = _as_dict(employee.current_data)
|
||||
sections = _display_sections(data)
|
||||
contacts = _as_dict(data.get("contacts"))
|
||||
return {
|
||||
**employee_display_payload(employee),
|
||||
**employee_display_payload(employee, sections=sections),
|
||||
"dpo_source": dpo_source_digest(dpo_sections(sections)),
|
||||
"dpo_courses": employee.dpo_review.courses if employee.dpo_review else dpo_suggestions(dpo_sections(sections)),
|
||||
"profile_type": employee.profile_type or data.get("profile_type"),
|
||||
"profile_id": employee.profile_id or data.get("profile_id"),
|
||||
"parser_version": employee.parser_version or data.get("parser_version"),
|
||||
@@ -139,7 +212,7 @@ def employee_detail_payload(employee: Employee) -> dict[str, Any]:
|
||||
},
|
||||
"external_ids": _normalize_external_ids(data.get("external_ids")),
|
||||
"news_links": _detail_news_links(employee, data),
|
||||
"sections": [_normalize_section(section) for section in _as_list(data.get("sections"))],
|
||||
"sections": [_normalize_section(section) for section in sections],
|
||||
}
|
||||
|
||||
|
||||
@@ -219,8 +292,13 @@ def list_employees_page(
|
||||
if pps and not any("кафедра" in position.casefold() or "департамент" in position.casefold()
|
||||
for position in _clean_list(data.get("positions"))):
|
||||
continue
|
||||
if has_training is not None and _has_training(data, training_since_year) != has_training:
|
||||
continue
|
||||
if has_training is not None:
|
||||
review = employee.dpo_review
|
||||
matches = (any(course["kind"] == "training" and
|
||||
(training_since_year is None or (course["year"] or 0) >= training_since_year)
|
||||
for course in review.courses) if review else _has_training(data, training_since_year))
|
||||
if matches != has_training:
|
||||
continue
|
||||
if paginate and offset and total < limit:
|
||||
first_page.append(employee)
|
||||
if not paginate or offset <= total < offset + limit:
|
||||
@@ -453,6 +531,9 @@ def _normalize_section(section: Any) -> dict[str, Any]:
|
||||
return {"title": "Раздел", "type": "generic", "paragraphs": [str(section)], "items": [], "links": []}
|
||||
|
||||
section_type = section.get("type") or "generic"
|
||||
if str(section.get("title", "")).strip().casefold().rstrip(":") == "профессиональные интересы":
|
||||
section = {"title": section["title"], "links": section.get("links")}
|
||||
section_type = "links"
|
||||
paragraphs = _clean_list(section.get("paragraphs"))
|
||||
items = _clean_list(section.get("items"))
|
||||
raw_text = str(section.get("raw_text") or "").strip()
|
||||
|
||||
@@ -1175,3 +1175,8 @@
|
||||
|
||||
.dpo-warning { color: #ab202b; text-decoration: none; }
|
||||
#unresolved-dpo:target { outline: 2px solid #ab202b; outline-offset: 3px; }
|
||||
|
||||
.dpo-review__row { display: flex; flex-wrap: wrap; align-items: end; gap: .75rem; margin: .75rem 0; }
|
||||
.dpo-review__row label { display: grid; gap: .25rem; max-width: 100%; }
|
||||
.dpo-review__row label:first-of-type { flex: 1 1 20rem; }
|
||||
.dpo-review__row input { min-width: 0; }
|
||||
@@ -196,6 +196,25 @@
|
||||
} else refresh(blocking, manual);
|
||||
}
|
||||
|
||||
pagination.addEventListener("click", (event) => {
|
||||
const link = event.target.closest("a[href]");
|
||||
if (!link || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||
event.preventDefault();
|
||||
clearTimeout(timer);
|
||||
pending?.abort();
|
||||
pending = null;
|
||||
setLoading(true, true);
|
||||
pagination.querySelector("[data-page-status]").hidden = false;
|
||||
window.location.assign(link.href);
|
||||
});
|
||||
window.addEventListener("pageshow", (event) => {
|
||||
if (event.persisted) {
|
||||
setLoading(false);
|
||||
summary.textContent = appliedSummary;
|
||||
pagination.querySelector("[data-page-status]").hidden = true;
|
||||
}
|
||||
});
|
||||
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
schedule(0, true, true);
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
const form = document.querySelector("form[data-dpo]");
|
||||
const rows = form.querySelector("[data-rows]");
|
||||
const empty = form.elements.confirm_empty;
|
||||
|
||||
function syncEmpty() {
|
||||
empty.required = !rows.children.length;
|
||||
empty.closest("label").hidden = !empty.required;
|
||||
if (!empty.required) empty.checked = false;
|
||||
}
|
||||
|
||||
form.querySelector("[data-add]").addEventListener("click", () => {
|
||||
rows.append(form.querySelector("template").content.cloneNode(true));
|
||||
rows.lastElementChild.querySelector("input").focus();
|
||||
syncEmpty();
|
||||
});
|
||||
rows.addEventListener("click", event => {
|
||||
if (event.target.closest("[data-remove]")) {
|
||||
event.target.closest("fieldset").remove();
|
||||
syncEmpty();
|
||||
}
|
||||
});
|
||||
syncEmpty();
|
||||
|
||||
form.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
const submit = form.querySelector('[type="submit"]');
|
||||
const status = form.querySelector("[data-status]");
|
||||
const courses = Array.from(rows.children, row => {
|
||||
const {title, year, kind, evidence} = row.elements;
|
||||
return {title: title.value.trim(), year: year.value ? Number(year.value) : null,
|
||||
kind: kind.value, evidence: evidence.value.trim()};
|
||||
});
|
||||
submit.disabled = true;
|
||||
try {
|
||||
const response = await fetch(form.action, {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json", "X-CSRF-Token": form.elements.csrf_token.value},
|
||||
body: JSON.stringify({courses, confirm_empty: empty.checked, source: form.dataset.source,
|
||||
revision: Number(form.dataset.revision)})
|
||||
});
|
||||
if (!response.ok || response.redirected) {
|
||||
const error = await response.json().catch(() => ({}));
|
||||
status.textContent = typeof error.detail === "string" ? error.detail : "Не удалось сохранить список. Проверьте поля и вход в систему.";
|
||||
return;
|
||||
}
|
||||
history.replaceState(null, "", "#unresolved-dpo");
|
||||
location.reload();
|
||||
} catch {
|
||||
status.textContent = "Не удалось связаться с сервером. Введённые данные сохранены в форме.";
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -108,7 +108,7 @@
|
||||
<tbody>
|
||||
{% for employee in page.employees %}
|
||||
<tr class="directory-table__row">
|
||||
<td class="directory-table__cell" data-column="full_name"><a class="admin__link" href="/admin/employees/{{ employee.id }}">{{ employee.full_name or "Без имени" }}</a></td>
|
||||
<td class="directory-table__cell" data-column="full_name"><a class="admin__link" href="/admin/employees/{{ employee.id }}">{{ employee.full_name or "Без имени" }}</a>{% if employee.dpo_uncertain %} <a class="dpo-warning" href="/admin/employees/{{ employee.id }}#unresolved-dpo" aria-label="Проверить количество ДПО" title="Проверить количество ДПО">⚠︎</a>{% endif %}</td>
|
||||
<td class="directory-table__cell" data-column="status"><span class="badge {% if employee.status == "dismissed" %}badge--dismissed{% elif employee.status == "verification_required" %}badge--verification{% endif %}">{{ employee.status_display }}</span></td>
|
||||
<td class="directory-table__cell" data-column="positions">{{ employee.positions_text }}</td>
|
||||
<td class="directory-table__cell" data-column="hse_start_year">{{ employee.hse_start_year or "" }}</td>
|
||||
@@ -123,7 +123,7 @@
|
||||
<td class="directory-table__cell" data-column="last_seen_at">{{ employee.last_seen_display }}</td>
|
||||
<td class="directory-table__cell" data-column="dismissed_at">{{ employee.dismissed_display }}</td>
|
||||
<td class="directory-table__cell" data-column="profile"><a class="admin__link" href="{{ employee.canonical_url }}" target="_blank" rel="noopener">Внешний профиль</a></td>
|
||||
<td class="directory-table__cell" data-column="dpo_count">{{ employee.dpo_count if employee.dpo_count is not none else "—" }}{% if employee.dpo_uncertain %} <a class="dpo-warning" href="/admin/employees/{{ employee.id }}#unresolved-dpo" title="Часть сведений о ДПО не распознана. Количество может быть неполным." aria-label="Часть сведений о ДПО не распознана. Количество может быть неполным."><span aria-hidden="true">⚠︎</span></a>{% endif %}</td>
|
||||
<td class="directory-table__cell" data-column="dpo_count">{{ employee.dpo_count if employee.dpo_count is not none else "—" }}{% if employee.dpo_uncertain %} <a class="dpo-warning" href="/admin/employees/{{ employee.id }}#unresolved-dpo" title="Количество ДПО требует проверки" aria-label="Количество ДПО требует проверки"><span aria-hidden="true">⚠︎</span></a>{% endif %}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td class="directory-table__empty" colspan="{{ directory_columns|length }}">
|
||||
@@ -142,6 +142,7 @@
|
||||
</div>
|
||||
|
||||
<div class="directory__pagination" data-directory-pagination>
|
||||
<span role="status" data-page-status hidden>Загружаем страницу…</span>
|
||||
{% set prev_offset = filters.offset - filters.limit %}
|
||||
{% set next_offset = filters.offset + filters.limit %}
|
||||
{% if filters.offset > 0 %}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<section class="employee-card">
|
||||
<div class="employee-card__header">
|
||||
<div class="employee-card__identity">
|
||||
<h2 class="employee-card__title">{{ employee_view.full_name or employee.profile_key }}{% if employee_view.dpo_uncertain %} <a class="dpo-warning" href="#unresolved-dpo" title="Часть сведений о ДПО не распознана. Количество может быть неполным." aria-label="Часть сведений о ДПО не распознана. Количество может быть неполным."><span aria-hidden="true">⚠︎</span></a>{% endif %}</h2>
|
||||
<h2 class="employee-card__title">{{ employee_view.full_name or employee.profile_key }}{% if employee_view.dpo_uncertain %} <a class="dpo-warning" href="#unresolved-dpo" title="Количество ДПО требует проверки" aria-label="Количество ДПО требует проверки"><span aria-hidden="true">⚠︎</span></a>{% endif %}</h2>
|
||||
<span class="badge {% if employee_view.status == "dismissed" %}badge--dismissed{% endif %}">{{ employee_view.status_display }}</span>
|
||||
</div>
|
||||
<div class="employee-card__actions">
|
||||
@@ -15,6 +15,7 @@
|
||||
<a class="admin__link" href="{{ employee_view.canonical_url }}">{{ employee_view.canonical_url }}</a>
|
||||
</div>
|
||||
</div>
|
||||
<a class="admin__link" href="#unresolved-dpo">Проверить ДПО</a>
|
||||
{% if refresh_status == "success" %}
|
||||
<p class="employee-card__notice employee-card__notice--success">Данные сотрудника обновлены.</p>
|
||||
{% elif refresh_status == "error" %}
|
||||
@@ -216,7 +217,7 @@
|
||||
</div>
|
||||
{% else %}
|
||||
{% if section.type == "additional_education" and section.list_items %}
|
||||
<p class="employee-section__note">Всего: {{ section.list_items | length }}</p>
|
||||
<p class="employee-section__note">Распознано записей: {{ section.list_items | length }}</p>
|
||||
{% endif %}
|
||||
{% if section.paragraphs %}
|
||||
{% for paragraph in section.paragraphs %}
|
||||
@@ -241,14 +242,6 @@
|
||||
{% endif %}
|
||||
</article>
|
||||
{% endfor %}
|
||||
{% if employee_view.dpo_uncertain %}
|
||||
<div id="unresolved-dpo" tabindex="-1">
|
||||
{% for section in profile_sections %}
|
||||
{% for text in section.unresolved %}<p>{{ text }}</p>{% endfor %}
|
||||
{% for doc in section.unresolved_documents %}<p>{% if doc.url.startswith(('https://', 'http://')) %}<a href="{{ doc.url }}">{{ doc.text }}</a>{% else %}{{ doc.text }}{% endif %}</p>{% endfor %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="employee-section__text">Разделы профиля не найдены.</p>
|
||||
@@ -256,6 +249,7 @@
|
||||
</section>
|
||||
</section>
|
||||
|
||||
{% include "employee_dpo.html" %}
|
||||
<section class="panel">
|
||||
<h2 class="panel__title">Снапшоты</h2>
|
||||
<table class="table">
|
||||
@@ -268,3 +262,5 @@
|
||||
</table>
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/dpo.js?v={{ frontend_version }}" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,46 @@
|
||||
{% set review = employee.dpo_review %}
|
||||
{% set kinds = {'training':'Повышение квалификации', 'retraining':'Профессиональная переподготовка', 'other':'Другое ДПО'} %}
|
||||
{% macro row(course) %}
|
||||
<fieldset class="dpo-review__row">
|
||||
<legend>Курс ДПО</legend>
|
||||
<label>Название <input name="title" required maxlength="8000" value="{{ course.title }}"></label>
|
||||
<label>Вид <select name="kind">{% for key, label in kinds.items() %}<option value="{{ key }}" {% if course.kind == key %}selected{% endif %}>{{ label }}</option>{% endfor %}</select></label>
|
||||
<label>Год <input type="number" name="year" min="1900" max="2100" value="{{ course.year or '' }}"></label>
|
||||
<label>Основание <input name="evidence" maxlength="4000" value="{{ course.evidence }}" placeholder="Документ или ссылка"></label>
|
||||
<button type="button" class="button button--ghost" data-remove>Исключить из списка</button>
|
||||
</fieldset>
|
||||
{% endmacro %}
|
||||
<section class="panel" id="unresolved-dpo" tabindex="-1">
|
||||
<h2 class="panel__title">Проверка ДПО</h2>
|
||||
{% if review %}
|
||||
<p>Подтверждено курсов: <strong>{{ review.courses | length }}</strong> · {{ review.updated_by }} · {{ review.updated_at | admin_datetime }}</p>
|
||||
{% if review.courses %}<ol>{% for course in review.courses %}
|
||||
<li>{{ course.title }} · {{ kinds[course.kind] }}{% if course.year %} · {{ course.year }}{% endif %}{% if course.evidence %} · {{ course.evidence }}{% endif %}</li>
|
||||
{% endfor %}</ol>{% endif %}
|
||||
{% endif %}
|
||||
{% if employee_view.dpo_uncertain %}
|
||||
<h3>Количество ДПО требует проверки</h3>
|
||||
{% if review %}<p>Сведения о ДПО изменились. В справочнике учтён последний подтверждённый список.</p>{% endif %}
|
||||
{% endif %}
|
||||
{% if employee_view.dpo_uncertain or review %}
|
||||
{% for section in employee_view.sections if section.type == 'additional_education' %}
|
||||
<h4>{{ section.title }} · сведения профиля</h4>
|
||||
{% if not section.list_items %}<p>В разделе ДПО не удалось выделить отдельные записи.</p>{% endif %}
|
||||
{% for item in section.list_items %}<p>{{ item }}</p>{% endfor %}
|
||||
{% for text in section.unresolved %}<p>{{ text }}</p>{% endfor %}
|
||||
{% for doc in section.unresolved_documents %}<p>{% if doc.url.startswith(('https://', 'http://')) %}<a class="admin__link" href="{{ doc.url }}">{{ doc.text }}</a>{% else %}{{ doc.text }}{% endif %}</p>{% endfor %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
<details {% if employee_view.dpo_uncertain %}open{% endif %}><summary>Проверить список ДПО</summary>
|
||||
<form data-dpo method="post" action="/admin/employees/{{ employee.id }}/dpo" data-source="{{ employee_view.dpo_source }}" data-revision="{{ review.revision if review else 0 }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
|
||||
<p>Оставьте по одной строке на каждое прохождение курса. Если удостоверение дублирует курс, перенесите его в основание и исключите лишнюю строку.</p>
|
||||
<div data-rows>{% for course in employee_view.dpo_courses %}{{ row(course) }}{% endfor %}</div>
|
||||
<template>{{ row({'kind':'other'}) }}</template>
|
||||
<button type="button" class="button button--ghost" data-add>Добавить курс</button>
|
||||
<label data-empty><input type="checkbox" name="confirm_empty"> Подтверждаю отсутствие курсов ДПО</label>
|
||||
<button class="button" type="submit">Подтвердить список</button>
|
||||
<p role="status" data-status></p>
|
||||
</form>
|
||||
</details>
|
||||
</section>
|
||||
+3
-3
@@ -1,3 +1,3 @@
|
||||
APP_VERSION = "2.3.0"
|
||||
FRONTEND_VERSION = "2.3.0"
|
||||
BACKEND_VERSION = "2.3.0"
|
||||
APP_VERSION = "2.4.0"
|
||||
FRONTEND_VERSION = "2.4.0"
|
||||
BACKEND_VERSION = "2.4.0"
|
||||
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE IF NOT EXISTS dpo_reviews (
|
||||
employee_id INTEGER PRIMARY KEY REFERENCES employees(id) ON DELETE CASCADE,
|
||||
revision INTEGER NOT NULL,
|
||||
courses JSONB NOT NULL,
|
||||
source_digest VARCHAR(64) NOT NULL,
|
||||
updated_by VARCHAR(64) NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "miem-workers"
|
||||
version = "2.3.0"
|
||||
description = "MIEM employees parser, admin API, and web admin"
|
||||
version = "2.4.0"
|
||||
description = "MIEM employees parser, admin API, and web admin"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"apscheduler>=3.10.4",
|
||||
@@ -12,7 +12,7 @@ dependencies = [
|
||||
"lxml>=5.2.0",
|
||||
"psycopg[binary]>=3.2.0",
|
||||
"pydantic-settings>=2.4.0",
|
||||
"openpyxl>=3.1.5,<4",
|
||||
"openpyxl>=3.1.5,<4",
|
||||
"python-multipart>=0.0.9",
|
||||
"requests>=2.32.0",
|
||||
"sqlalchemy>=2.0.32",
|
||||
|
||||
@@ -163,6 +163,18 @@ def main():
|
||||
fulfill(pending.pop(0))
|
||||
expect(summary).to_have_text("Показаны 0–0 из 0")
|
||||
expect(overlay).to_be_hidden()
|
||||
with factory() as db:
|
||||
db.add_all(Employee(profile_key=f"staff:{i}", canonical_url=f"https://www.hse.ru/staff/{i}",
|
||||
full_name=f"Сотрудник {i}") for i in range(3, 27))
|
||||
db.commit()
|
||||
page.goto("http://miem.test/admin/directory?limit=25")
|
||||
page.route("**/*offset=25*", lambda route: pending.append(route))
|
||||
page.get_by_role("link", name="Вперед").click(no_wait_after=True)
|
||||
expect(page.locator("[data-page-status]")).to_be_visible()
|
||||
expect(overlay).to_be_visible()
|
||||
fulfill(pending.pop())
|
||||
expect(summary).to_have_text("Показаны 26–26 из 26")
|
||||
expect(overlay).to_be_hidden()
|
||||
assert not errors, errors
|
||||
browser.close()
|
||||
finally:
|
||||
|
||||
+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.3.0"
|
||||
assert response.json()["backend_version"] == "2.4.0"
|
||||
|
||||
|
||||
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.3.0 · Frontend 2.3.0" in response.text
|
||||
assert "Backend 2.4.0 · Frontend 2.4.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
|
||||
|
||||
@@ -3,6 +3,35 @@ from bs4 import BeautifulSoup
|
||||
from app.parser.education_document import _certificate
|
||||
from app.parser.profile import extract_sections
|
||||
from app.services.resource_cache import ResourceCache
|
||||
from app.services.admin_data import _display_sections
|
||||
|
||||
|
||||
def test_dated_lines_and_wrapped_title_survive_old_and_new_profiles():
|
||||
html = ('<h2>Дополнительное образование</h2><p>2002 г. "Первый курс".<br>'
|
||||
'2006 г. "Второй курс".<br>Продолжение описания.</p>')
|
||||
section, = extract_sections(BeautifulSoup(html, "html.parser"), "https://www.hse.ru")
|
||||
expected = ['2002 г. "Первый курс".', '2006 г. "Второй курс". Продолжение описания.']
|
||||
assert section["items"] == expected
|
||||
for old in ({"type": "additional_education", "items": [" ".join(expected)]},
|
||||
{"type": "paragraphs", "paragraphs": [" ".join(expected)]}):
|
||||
saved, = _display_sections({"sections": [{**old, "title": section["title"]}]})
|
||||
assert saved["items"] == expected
|
||||
|
||||
|
||||
def test_possible_duplicate_requires_review_even_without_attachments():
|
||||
html = ('<h2>Повышение квалификации</h2>'
|
||||
'<p>2018 г. "Комплексная безопасность". МАИ.</p>'
|
||||
'<p>2018 г. "Комплексная безопасность". Удостоверение.</p>')
|
||||
section, = extract_sections(BeautifulSoup(html, "html.parser"), "https://www.hse.ru")
|
||||
assert len(section["items"]) == 2
|
||||
assert section["unresolved"] == ["Возможный повтор: " + section["items"][1]]
|
||||
|
||||
|
||||
def test_unlinked_certificate_images_are_reviewed_once():
|
||||
html = '<h2>Повышение квалификации</h2><p>' + '<img src="/mirror/pubs/share/12">' * 2 + '</p>'
|
||||
section, = extract_sections(BeautifulSoup(html, "html.parser"), "https://www.hse.ru", lambda url: None)
|
||||
assert not section["items"]
|
||||
assert section["unresolved_documents"] == [{"text": "Изображение документа", "url": "https://www.hse.ru/mirror/pubs/share/12"}]
|
||||
|
||||
|
||||
def test_education_events_preserve_ambiguities_and_separate_periods():
|
||||
|
||||
@@ -427,3 +427,52 @@ def test_postgres_concurrent_admin_demotions_keep_an_admin(accounts):
|
||||
finally:
|
||||
for other in clients:
|
||||
other.close()
|
||||
|
||||
|
||||
def test_reader_confirms_dpo_and_changed_sources_require_review(accounts):
|
||||
from io import BytesIO
|
||||
from openpyxl import load_workbook
|
||||
from app.services.admin_data import employee_detail_payload, list_employees_page
|
||||
from app.services.directory_export import directory_xlsx
|
||||
|
||||
client, db, settings, _, user, employee = accounts
|
||||
headers = act_as(client, user, settings)
|
||||
url = f"/admin/employees/{employee.id}/dpo"
|
||||
title = "Работа с данными, повышение квалификации"
|
||||
section = {"type": "additional_education", "title": "Дополнительное образование",
|
||||
"education_format": 2, "items": [title], "year_entries": [{"text": title, "year": 2024}]}
|
||||
employee.current_data = {"sections": [section]}
|
||||
db.commit()
|
||||
card = BeautifulSoup(client.get(url[:-4]).text, "html.parser")
|
||||
form = card.select_one("form[data-dpo]")
|
||||
assert form.select_one('[name="title"]')["value"] == title
|
||||
assert form.select_one('[name="kind"] option[selected]')["value"] == "training"
|
||||
assert form.select_one('[name="year"]')["value"] == "2024"
|
||||
payload = {"courses": [{"title": "Инженерная практика", "kind": "training", "year": 2025}],
|
||||
"source": form["data-source"], "revision": 0}
|
||||
assert client.post(url, json=payload).status_code == 403
|
||||
assert client.post(url, json=payload, headers=headers).status_code == 200
|
||||
assert client.post(url, json=payload, headers=headers).status_code == 409
|
||||
assert not employee_detail_payload(employee)["dpo_uncertain"]
|
||||
result = list_employees_page(db, training_since_year=2025)["employees"]
|
||||
assert [row["dpo_count"] for row in result] == [1]
|
||||
sheet = load_workbook(BytesIO(directory_xlsx(result))).active
|
||||
assert sheet.cell(2, sheet.max_column).value == 1
|
||||
employee.current_data = {"sections": [section], "phone": "changed"}
|
||||
db.commit()
|
||||
assert not employee_detail_payload(employee)["dpo_uncertain"]
|
||||
employee.current_data = {"sections": [{"type": "additional_education", "education_format": 2,
|
||||
"items": ["Новый курс"]}]}
|
||||
db.commit()
|
||||
view = employee_detail_payload(employee)
|
||||
assert view["dpo_uncertain"] and view["dpo_count"] == 1
|
||||
payload.update(courses=[], revision=1, confirm_empty=True)
|
||||
assert client.post(url, json=payload, headers=headers).status_code == 409
|
||||
payload.update(source=view["dpo_source"], confirm_empty=False)
|
||||
assert client.post(url, json=payload, headers=headers).status_code == 422
|
||||
payload.update(confirm_empty=True)
|
||||
assert client.post(url, json=payload, headers=headers).status_code == 200
|
||||
view = employee_detail_payload(employee)
|
||||
assert view["dpo_count"] == 0 and not view["dpo_uncertain"]
|
||||
assert list_employees_page(db, has_training=True)["total"] == 0
|
||||
assert list_employees_page(db, has_training=False)["total"] == 1
|
||||
Reference in new issue
Block a user