Подтверждение курсов ДПО в карточке сотрудника #84
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,5 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
## 2.4.0
|
||||
|
||||
- Любой вошедший пользователь может подтвердить список ДПО в карточке сотрудника. Справочник и XLSX учитывают подтверждённое количество, включая ноль. Фильтр повышения квалификации учитывает вид и год подтверждённых курсов.
|
||||
- При изменении сведений о ДПО в профиле карточка снова требует проверки. До повторного подтверждения действует предыдущий список.
|
||||
|
||||
## Эксплуатация · 2026-11-24
|
||||
|
||||
- После слияния в `main` Workers запрашивает запуск `workers-cd.yml` в `admin/infra-platform`. Результат выкладки фиксируется в Actions платформы.
|
||||
|
||||
+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__ = (
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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; }
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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" %}
|
||||
@@ -241,16 +242,6 @@
|
||||
{% endif %}
|
||||
</article>
|
||||
{% endfor %}
|
||||
{% if employee_view.dpo_uncertain %}
|
||||
<div id="unresolved-dpo" tabindex="-1">
|
||||
<h4>Количество ДПО требует проверки</h4>
|
||||
{% for section in profile_sections %}
|
||||
{% if section.type == "additional_education" and not section.list_items %}<p>В разделе ДПО не удалось выделить отдельные записи.</p>{% endif %}
|
||||
{% 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>
|
||||
@@ -258,6 +249,7 @@
|
||||
</section>
|
||||
</section>
|
||||
|
||||
{% include "employee_dpo.html" %}
|
||||
<section class="panel">
|
||||
<h2 class="panel__title">Снапшоты</h2>
|
||||
<table class="table">
|
||||
@@ -270,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.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"
|
||||
@@ -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
|
||||
);
|
||||
+1
-1
@@ -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 = [
|
||||
|
||||
+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.1"
|
||||
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.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
|
||||
|
||||
@@ -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