Files
work-volume-tracker/tests/test_task023_ui_ux_cleanup.py
2026-09-30 18:59:06 +03:00

444 lines
16 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Regression tests for task 023: UI/UX cleanup V1."""
import shutil
from datetime import date
from decimal import Decimal
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.database.database import Base, DATABASE_PATH
from app.importer.excel_importer import import_excel_data
from app.main import app
from app.models.project import Project
from app.models.boq import BoqDocument, System, Section, WorkItem
from app.models.agreement import Agreement
from app.models.daily_report import DailyReport, DailyReportItem
from app.routers import (
projects as project_router,
boq as boq_router,
agreements as agreement_router,
daily_reports,
ks2 as ks2_router,
ks3 as ks3_router,
payments as payments_router,
)
def _make_session(tmp_path):
db_path = tmp_path / "t023-copy.db"
shutil.copy2(DATABASE_PATH, db_path)
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
Base.metadata.create_all(bind=engine)
return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False)
def _override(*deps):
# Use the first dep's session factory via closure over module-level Session
pass
def _bind_session(Session, *deps):
def override_db():
s = Session()
try:
yield s
finally:
s.close()
for dep in deps:
app.dependency_overrides[dep] = override_db
def _clear(*deps):
for dep in deps:
app.dependency_overrides.pop(dep, None)
ALL_DEPS = (
project_router.get_db,
boq_router.get_db,
agreement_router.get_db,
daily_reports.get_db,
ks2_router.get_db,
ks3_router.get_db,
payments_router.get_db,
)
def _seed_project(Session):
with Session() as s:
p = Project(name="UI cleanup", status="active", contract_number="D-1")
s.add(p)
s.flush()
doc = BoqDocument(project_id=p.id, name="BOQ Import - Ведомость ОВ")
s.add(doc)
s.flush()
system = System(project_id=p.id, name="Система", sort_order=1)
s.add(system)
s.flush()
section = Section(system_id=system.id, name="Раздел", sort_order=1)
s.add(section)
s.flush()
item = WorkItem(
project_id=p.id, boq_document_id=doc.id, system_id=system.id, section_id=section.id,
source_number="1", name="Позиция", unit="шт", quantity=10,
unit_price=Decimal("100"), amount=Decimal("1000"),
)
s.add(item)
s.commit()
return p.id, doc.id, item.id
# --- 1/2. Agreements row-click markup ---
def test_agreement_list_rows_are_clickable(tmp_path):
engine, Session = _make_session(tmp_path)
_bind_session(Session, *ALL_DEPS)
try:
pid, doc_id, _ = _seed_project(Session)
with Session() as s:
agr = Agreement(
project_id=pid, number="A-1", date=date(2026, 1, 1),
title="ДС", status="draft",
)
s.add(agr)
s.commit()
agr_id = agr.id
with TestClient(app) as client:
resp = client.get(f"/projects/{pid}/agreements")
assert resp.status_code == 200
html = resp.text
assert f'data-url="/projects/{pid}/agreements/{agr_id}"' in html
assert "clickable-row" in html
# Action button must not fall through to row navigation
assert "e.target.closest('a, button, form, input, select, textarea')" in html
assert f'href="/projects/{pid}/agreements/{agr_id}"' in html
finally:
_clear(*ALL_DEPS)
engine.dispose()
# --- 3. BOQ display name in agreement scope selector ---
def test_agreement_scope_shows_display_name_not_technical(tmp_path):
engine, Session = _make_session(tmp_path)
_bind_session(Session, *ALL_DEPS)
try:
pid, doc_id, _ = _seed_project(Session)
with TestClient(app) as client:
resp = client.get(f"/projects/{pid}/agreements/new")
assert resp.status_code == 200
html = resp.text
assert "Ведомость ОВ" in html
assert "BOQ Import" not in html
finally:
_clear(*ALL_DEPS)
engine.dispose()
def test_boq_display_name_property():
doc = BoqDocument(id=1, project_id=1, name="BOQ Import - Ведомость ОВ")
assert doc.display_name == "Ведомость ОВ"
doc2 = BoqDocument(id=2, project_id=1, name="Импорт ведомости — Лист 1")
assert doc2.display_name == "Лист 1"
doc3 = BoqDocument(id=3, project_id=1, name="Основная ведомость")
assert doc3.display_name == "Основная ведомость"
# --- 4. Import requisites ---
def test_import_excel_saves_document_requisites(tmp_path):
import openpyxl
path = tmp_path / "boq.xlsx"
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Ведомость ОВ"
for _ in range(4):
ws.append([None])
ws.append(["№", "Наименование", "Модель", "Производитель", "Ед", "Кол-во", "Цена", "Сумма"])
ws.append([1, "Работа", None, None, "шт", 2, 10, 20])
wb.save(path)
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)()
project = Project(name="Import requisites")
session.add(project)
session.commit()
result = import_excel_data(
session, str(path), "Ведомость ОВ", 5, 6, project.id,
document_name="Основная ведомость",
document_number="БО-01",
document_date=date(2026, 3, 1),
contract="Договор 42",
)
doc = session.get(BoqDocument, result["document_id"])
assert doc.name == "Основная ведомость"
assert doc.document_number == "БО-01"
assert doc.document_date == date(2026, 3, 1)
assert doc.contract == "Договор 42"
assert doc.display_name == "Основная ведомость"
session.close()
def test_import_preview_exposes_requisites_fields(tmp_path):
import openpyxl
path = tmp_path / "boq.xlsx"
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Лист1"
for _ in range(4):
ws.append([None])
ws.append(["№", "Наименование", "Модель", "Производитель", "Ед", "Кол-во", "Цена", "Сумма"])
ws.append([1, "Работа", None, None, "шт", 1, 5, 5])
upload_dir = tmp_path / "uploads"
upload_dir.mkdir()
saved = upload_dir / "boq.xlsx"
wb.save(saved)
engine, Session = _make_session(tmp_path)
_bind_session(Session, boq_router.get_db, project_router.get_db)
try:
with Session() as s:
p = Project(name="Import UI", contract_number="PC-9")
s.add(p)
s.commit()
pid = p.id
# Point UPLOAD_DIR at temp
import app.routers.boq as boq_mod
old_upload = boq_mod.UPLOAD_DIR
boq_mod.UPLOAD_DIR = upload_dir
try:
with TestClient(app) as client:
resp = client.post(f"/boq/{pid}/import/preview", data={
"filename": "boq.xlsx",
"sheet_name": "Лист1",
"header_row": "5",
"start_row": "6",
})
assert resp.status_code == 200
html = resp.text
assert 'name="document_name"' in html
assert 'name="document_number"' in html
assert 'name="document_date"' in html
assert 'name="contract"' in html
assert "Реквизиты ведомости" in html
# Default name comes from sheet
assert "Лист1" in html
finally:
boq_mod.UPLOAD_DIR = old_upload
finally:
_clear(boq_router.get_db, project_router.get_db)
engine.dispose()
# --- 5. Delete project blocked → UI modal, not raw JSON to browser ---
def test_delete_project_blocked_keeps_api_json_and_page_has_modal(tmp_path):
engine, Session = _make_session(tmp_path)
_bind_session(Session, *ALL_DEPS)
try:
with Session() as s:
p = Project(name="Has history")
s.add(p)
s.flush()
doc = BoqDocument(project_id=p.id, name="BOQ")
s.add(doc)
s.flush()
item = WorkItem(project_id=p.id, boq_document_id=doc.id, name="I", quantity=1)
s.add(item)
s.flush()
dr = DailyReport(project_id=p.id, report_date=date(2026, 1, 1))
s.add(dr)
s.flush()
s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=item.id, completed_quantity=1))
s.commit()
pid = p.id
with TestClient(app) as client:
# API contract preserved for non-browser clients
resp = client.post(f"/projects/{pid}/delete", follow_redirects=False)
assert resp.status_code == 400
assert resp.json()["detail"]
# Browser UI: page contains modal + JS handler, not a bare form post
page = client.get(f"/projects/{pid}")
html = page.text
assert 'id="deleteBlockedModal"' in html
assert "Проект нельзя удалить" in html
assert "Рекомендуется архивировать проект" in html
assert "Архивировать проект" in html
assert 'id="delete-project-form"' in html
assert "bootstrap.Modal" in html
# Status badge is visually distinct
assert "text-bg-success" in html # active
# Daily report button near top / status block
assert "Дневной отчёт" in html
# Package button is not full-width
assert "Сформировать комплект" in html
assert "btn-primary w-100" not in html or "Сформировать комплект" not in html.split("btn-primary w-100")[0][-50:]
# Eye toggle is separated from business nav
assert "Финансовые суммы" in html
# BOQ and DS are adjacent entry points
assert "Ведомости" in html and "Дополнительные соглашения" in html
finally:
_clear(*ALL_DEPS)
engine.dispose()
def test_delete_project_without_related_data_still_works(tmp_path):
engine, Session = _make_session(tmp_path)
_bind_session(Session, *ALL_DEPS)
try:
with Session() as s:
p = Project(name="Clean")
s.add(p)
s.commit()
pid = p.id
with TestClient(app) as client:
resp = client.post(f"/projects/{pid}/delete", follow_redirects=False)
assert resp.status_code == 303
with Session() as s:
assert s.get(Project, pid) is None
finally:
_clear(*ALL_DEPS)
engine.dispose()
# --- 6. Existing import flow still works ---
def test_import_confirm_flow_still_works(tmp_path):
import openpyxl
path = tmp_path / "boq.xlsx"
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Ведомость"
for _ in range(4):
ws.append([None])
ws.append(["№", "Наименование", "Модель", "Производитель", "Ед", "Кол-во", "Цена", "Сумма"])
ws.append([1, "Работа", None, None, "шт", 1, 5, 5])
upload_dir = tmp_path / "uploads"
upload_dir.mkdir()
wb.save(upload_dir / "boq.xlsx")
engine, Session = _make_session(tmp_path)
_bind_session(Session, boq_router.get_db, project_router.get_db)
try:
with Session() as s:
p = Project(name="Import flow")
s.add(p)
s.commit()
pid = p.id
import app.routers.boq as boq_mod
old_upload = boq_mod.UPLOAD_DIR
boq_mod.UPLOAD_DIR = upload_dir
try:
with TestClient(app) as client:
resp = client.post(f"/boq/{pid}/import/confirm", data={
"filename": "boq.xlsx",
"sheet_name": "Ведомость",
"header_row": "5",
"start_row": "6",
"document_name": "Моя ведомость",
"document_number": "12",
"document_date": "2026-02-02",
"contract": "К-1",
})
assert resp.status_code == 200
assert "Импорт завершен" in resp.text
assert "Моя ведомость" in resp.text
finally:
boq_mod.UPLOAD_DIR = old_upload
with Session() as s:
doc = s.query(BoqDocument).filter_by(project_id=pid).one()
assert doc.name == "Моя ведомость"
assert doc.document_number == "12"
assert doc.document_date == date(2026, 2, 2)
assert doc.contract == "К-1"
items = s.query(WorkItem).filter_by(boq_document_id=doc.id).all()
assert len(items) == 1
finally:
_clear(boq_router.get_db, project_router.get_db)
engine.dispose()
# --- 7. Eye toggle not broken ---
def test_eye_toggle_present_on_project_and_base_pages(tmp_path):
engine, Session = _make_session(tmp_path)
_bind_session(Session, *ALL_DEPS)
try:
pid, doc_id, _ = _seed_project(Session)
with TestClient(app) as client:
project_page = client.get(f"/projects/{pid}")
assert "id=\"toggleMoney\"" in project_page.text
assert "money-hidden" in project_page.text
assert "classList.toggle('money-hidden')" in project_page.text
boq_page = client.get(f"/boq/{pid}/documents/{doc_id}")
assert "id=\"toggleMoney\"" in boq_page.text
assert "money-hidden" in boq_page.text
# KS-2 / KS-3 / Payments pages extend base.html
for path in (f"/projects/{pid}/ks2", f"/projects/{pid}/ks3", f"/projects/{pid}/payments"):
page = client.get(path)
assert page.status_code == 200
assert "id=\"toggleMoney\"" in page.text
assert "money-hidden" in page.text
finally:
_clear(*ALL_DEPS)
engine.dispose()
# --- Status badge + package button + requisites shown ---
def test_project_page_status_badge_and_package_button(tmp_path):
engine, Session = _make_session(tmp_path)
_bind_session(Session, *ALL_DEPS)
try:
with Session() as s:
p = Project(name="Status", status="on_hold")
s.add(p)
s.commit()
pid = p.id
with TestClient(app) as client:
html = client.get(f"/projects/{pid}").text
assert "text-bg-warning" in html # on_hold
assert "Приостановлен" in html
# Package button fits its column responsively
import re
match = re.search(r'<button type="submit" class="([^"]*)">Сформировать комплект</button>', html)
assert match
assert "w-100" in match.group(1) or "w-auto" in match.group(1)
finally:
_clear(*ALL_DEPS)
engine.dispose()
def test_boq_document_shows_requisites(tmp_path):
engine, Session = _make_session(tmp_path)
_bind_session(Session, *ALL_DEPS)
try:
with Session() as s:
p = Project(name="Req display")
s.add(p)
s.flush()
doc = BoqDocument(
project_id=p.id, name="Основная ведомость",
document_number="БО-7", document_date=date(2026, 5, 5),
contract="Договор 1",
)
s.add(doc)
s.commit()
pid, did = p.id, doc.id
with TestClient(app) as client:
html = client.get(f"/boq/{pid}/documents/{did}").text
assert "Основная ведомость" in html
assert "БО-7" in html
assert "Договор 1" in html
assert "05.05.2026" in html
finally:
_clear(*ALL_DEPS)
engine.dispose()