diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 4fbb0b7..30a75e1 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 098b970..22de921 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 2.4.0 + +- Любой вошедший пользователь может подтвердить список ДПО в карточке сотрудника. Справочник и XLSX учитывают подтверждённое количество, включая ноль. Фильтр повышения квалификации учитывает вид и год подтверждённых курсов. +- При изменении сведений о ДПО в профиле карточка снова требует проверки. До повторного подтверждения действует предыдущий список. + ## Эксплуатация · 2026-11-24 - После слияния в `main` Workers запрашивает запуск `workers-cd.yml` в `admin/infra-platform`. Результат выкладки фиксируется в Actions платформы. diff --git a/app/admin.py b/app/admin.py index 4d21fdc..d2c9a26 100644 --- a/app/admin.py +++ b/app/admin.py @@ -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, diff --git a/app/models.py b/app/models.py index ba130d0..a804aec 100644 --- a/app/models.py +++ b/app/models.py @@ -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__ = ( diff --git a/app/services/admin_data.py b/app/services/admin_data.py index 9a78a99..762bd69 100644 --- a/app/services/admin_data.py +++ b/app/services/admin_data.py @@ -1,5 +1,7 @@ from __future__ import annotations +import hashlib +import json import re from datetime import date, datetime, time from math import ceil @@ -114,6 +116,41 @@ def _display_sections(data): 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")) @@ -124,7 +161,8 @@ def employee_display_payload(employee: Employee, *, sections=None) -> dict[str, 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"] + education = dpo_sections(sections) + review = employee.dpo_review dpo_count = sum(len(s.get("items", [])) for s in education) return { "id": employee.id, @@ -142,8 +180,8 @@ def employee_display_payload(employee: Employee, *, sections=None) -> dict[str, "address": contacts.get("address"), "academic_degree_text": "; ".join(degree_values), "publications_count": _count_section_items(sections, "publications"), - "dpo_count": dpo_count or None, - "dpo_uncertain": any(not s.get("items") or 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, @@ -161,6 +199,8 @@ def employee_detail_payload(employee: Employee) -> dict[str, Any]: contacts = _as_dict(data.get("contacts")) return { **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"), @@ -252,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: diff --git a/app/static/admin.css b/app/static/admin.css index e976fc1..b6533ff 100644 --- a/app/static/admin.css +++ b/app/static/admin.css @@ -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; } diff --git a/app/static/dpo.js b/app/static/dpo.js new file mode 100644 index 0000000..e3e9ec2 --- /dev/null +++ b/app/static/dpo.js @@ -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; + } +}); diff --git a/app/templates/employee_detail.html b/app/templates/employee_detail.html index 8356bea..38f401d 100644 --- a/app/templates/employee_detail.html +++ b/app/templates/employee_detail.html @@ -15,6 +15,7 @@ {{ employee_view.canonical_url }} + Проверить ДПО {% if refresh_status == "success" %}

Данные сотрудника обновлены.

{% elif refresh_status == "error" %} @@ -241,16 +242,6 @@ {% endif %} {% endfor %} - {% if employee_view.dpo_uncertain %} -
-

Количество ДПО требует проверки

- {% for section in profile_sections %} - {% if section.type == "additional_education" and not section.list_items %}

В разделе ДПО не удалось выделить отдельные записи.

{% endif %} - {% for text in section.unresolved %}

{{ text }}

{% endfor %} - {% for doc in section.unresolved_documents %}

{% if doc.url.startswith(('https://', 'http://')) %}{{ doc.text }}{% else %}{{ doc.text }}{% endif %}

{% endfor %} - {% endfor %} -
- {% endif %} {% else %}

Разделы профиля не найдены.

@@ -258,6 +249,7 @@ +{% include "employee_dpo.html" %}

Снапшоты

@@ -270,3 +262,5 @@
{% endblock %} + +{% block scripts %}{% endblock %} diff --git a/app/templates/employee_dpo.html b/app/templates/employee_dpo.html new file mode 100644 index 0000000..ec8c367 --- /dev/null +++ b/app/templates/employee_dpo.html @@ -0,0 +1,46 @@ +{% set review = employee.dpo_review %} +{% set kinds = {'training':'Повышение квалификации', 'retraining':'Профессиональная переподготовка', 'other':'Другое ДПО'} %} +{% macro row(course) %} +
+ Курс ДПО + + + + + +
+{% endmacro %} +
+

Проверка ДПО

+ {% if review %} +

Подтверждено курсов: {{ review.courses | length }} · {{ review.updated_by }} · {{ review.updated_at | admin_datetime }}

+ {% if review.courses %}
    {% for course in review.courses %} +
  1. {{ course.title }} · {{ kinds[course.kind] }}{% if course.year %} · {{ course.year }}{% endif %}{% if course.evidence %} · {{ course.evidence }}{% endif %}
  2. + {% endfor %}
{% endif %} + {% endif %} + {% if employee_view.dpo_uncertain %} +

Количество ДПО требует проверки

+ {% if review %}

Сведения о ДПО изменились. В справочнике учтён последний подтверждённый список.

{% endif %} + {% endif %} + {% if employee_view.dpo_uncertain or review %} + {% for section in employee_view.sections if section.type == 'additional_education' %} +

{{ section.title }} · сведения профиля

+ {% if not section.list_items %}

В разделе ДПО не удалось выделить отдельные записи.

{% endif %} + {% for item in section.list_items %}

{{ item }}

{% endfor %} + {% for text in section.unresolved %}

{{ text }}

{% endfor %} + {% for doc in section.unresolved_documents %}

{% if doc.url.startswith(('https://', 'http://')) %}{{ doc.text }}{% else %}{{ doc.text }}{% endif %}

{% endfor %} + {% endfor %} + {% endif %} +
Проверить список ДПО +
+ +

Оставьте по одной строке на каждое прохождение курса. Если удостоверение дублирует курс, перенесите его в основание и исключите лишнюю строку.

+
{% for course in employee_view.dpo_courses %}{{ row(course) }}{% endfor %}
+ + + + +

+
+
+
diff --git a/app/version.py b/app/version.py index 8751ead..8a0f729 100644 --- a/app/version.py +++ b/app/version.py @@ -1,3 +1,3 @@ -APP_VERSION = "2.3.1" -FRONTEND_VERSION = "2.3.1" -BACKEND_VERSION = "2.3.1" +APP_VERSION = "2.4.0" +FRONTEND_VERSION = "2.4.0" +BACKEND_VERSION = "2.4.0" diff --git a/migrations/015_dpo_reviews.sql b/migrations/015_dpo_reviews.sql new file mode 100644 index 0000000..8e34551 --- /dev/null +++ b/migrations/015_dpo_reviews.sql @@ -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 +); diff --git a/pyproject.toml b/pyproject.toml index e22b603..935ad71 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "miem-workers" -version = "2.3.1" +version = "2.4.0" description = "MIEM employees parser, admin API, and web admin" requires-python = ">=3.11" dependencies = [ diff --git a/tests/test_api.py b/tests/test_api.py index da80ba1..0af5303 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -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.1" + assert response.json()["backend_version"] == "2.4.0" def test_api_employees_and_stats_require_admin_session(): diff --git a/tests/test_council.py b/tests/test_council.py index 26fa097..a3c6058 100644 --- a/tests/test_council.py +++ b/tests/test_council.py @@ -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.1 · Frontend 2.3.1" 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 diff --git a/tests/test_users.py b/tests/test_users.py index a41bf84..0a21ded 100644 --- a/tests/test_users.py +++ b/tests/test_users.py @@ -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