426 lines
15 KiB
Python
426 lines
15 KiB
Python
"""Regression tests for task 018: KS-6a Excel/Word export."""
|
||
import datetime
|
||
import io
|
||
import shutil
|
||
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.main import app
|
||
from app.models.project import Project
|
||
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||
from app.models.daily_report import DailyReport, DailyReportItem
|
||
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||
from app.models.ks3 import KS3, KS3KS2
|
||
from app.routers import projects, ks2 as ks2_router, ks3 as ks3_router, ks6a as ks6a_router
|
||
|
||
|
||
def _make_session(tmp_path):
|
||
db_path = tmp_path / "t018-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(Session):
|
||
def override_db():
|
||
s = Session()
|
||
try:
|
||
yield s
|
||
finally:
|
||
s.close()
|
||
for dep in (projects.get_db, ks2_router.get_db, ks3_router.get_db, ks6a_router.get_db):
|
||
app.dependency_overrides[dep] = override_db
|
||
|
||
|
||
def _clear():
|
||
for dep in (projects.get_db, ks2_router.get_db, ks3_router.get_db, ks6a_router.get_db):
|
||
app.dependency_overrides.pop(dep, None)
|
||
|
||
|
||
def _create_ks6a_data(Session):
|
||
"""Project with 5 DailyReportItems across 2 systems and 3 dates."""
|
||
with Session() as s:
|
||
p = Project(name="KS6a export test", customer="Customer LLC", contract_number="DOG-789")
|
||
s.add(p)
|
||
s.flush()
|
||
|
||
system_a = System(project_id=p.id, name="Система A", sort_order=1)
|
||
system_b = System(project_id=p.id, name="Система B", sort_order=2)
|
||
s.add_all([system_a, system_b])
|
||
s.flush()
|
||
|
||
section_a = Section(system_id=system_a.id, name="Раздел A1")
|
||
s.add(section_a)
|
||
s.flush()
|
||
|
||
doc = BoqDocument(project_id=p.id, name="BOQ")
|
||
s.add(doc)
|
||
s.flush()
|
||
|
||
wi1 = WorkItem(
|
||
project_id=p.id, boq_document_id=doc.id,
|
||
system_id=system_a.id, section_id=section_a.id,
|
||
source_number="1.1", name="Монтаж трубы", unit="м",
|
||
quantity=Decimal("100"), unit_price=Decimal("50"), amount=Decimal("5000"),
|
||
)
|
||
wi2 = WorkItem(
|
||
project_id=p.id, boq_document_id=doc.id,
|
||
system_id=system_b.id,
|
||
source_number="2.1", name="Укладка кабеля", unit="м",
|
||
quantity=Decimal("200"), unit_price=Decimal("30"), amount=Decimal("6000"),
|
||
)
|
||
s.add_all([wi1, wi2])
|
||
s.flush()
|
||
|
||
dr1 = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 1))
|
||
dr2 = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 5))
|
||
dr3 = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 10))
|
||
s.add_all([dr1, dr2, dr3])
|
||
s.flush()
|
||
|
||
dri1 = DailyReportItem(daily_report_id=dr1.id, work_item_id=wi1.id, completed_quantity=Decimal("10"))
|
||
dri2 = DailyReportItem(daily_report_id=dr2.id, work_item_id=wi1.id, completed_quantity=Decimal("15"))
|
||
dri3 = DailyReportItem(daily_report_id=dr3.id, work_item_id=wi1.id, completed_quantity=Decimal("5"))
|
||
dri4 = DailyReportItem(daily_report_id=dr1.id, work_item_id=wi2.id, completed_quantity=Decimal("20"))
|
||
dri5 = DailyReportItem(daily_report_id=dr2.id, work_item_id=wi2.id, completed_quantity=Decimal("30"))
|
||
s.add_all([dri1, dri2, dri3, dri4, dri5])
|
||
s.commit()
|
||
return {
|
||
"pid": p.id,
|
||
"sa_id": system_a.id,
|
||
"sb_id": system_b.id,
|
||
"wi1_id": wi1.id,
|
||
"dri1_id": dri1.id,
|
||
}
|
||
|
||
|
||
PERIOD = "date_from=2026-03-01&date_to=2026-03-31"
|
||
|
||
|
||
def _excel_text(resp):
|
||
from openpyxl import load_workbook
|
||
wb = load_workbook(io.BytesIO(resp.content))
|
||
ws = wb.active
|
||
return wb, ws, "\n".join(str(cell.value) for row in ws.iter_rows() for cell in row if cell.value is not None)
|
||
|
||
|
||
def _word_text(resp):
|
||
from docx import Document
|
||
d = Document(io.BytesIO(resp.content))
|
||
text = "\n".join(p.text for p in d.paragraphs)
|
||
for table in d.tables:
|
||
for row in table.rows:
|
||
text += "\n" + " | ".join(c.text for c in row.cells)
|
||
return d, text
|
||
|
||
|
||
def test_ks6a_excel_endpoint_exists(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
assert resp.status_code == 200
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_word_endpoint_exists(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
|
||
assert resp.status_code == 200
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_export_content_types(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
excel = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
assert "spreadsheetml" in excel.headers["content-type"]
|
||
word = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
|
||
assert "wordprocessingml" in word.headers["content-type"]
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_filename_contains_period(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
excel = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
disposition = excel.headers["content-disposition"]
|
||
assert "01.03.2026-31.03.2026" in disposition
|
||
assert "КС-6а" in disposition or "filename" in disposition
|
||
word = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
|
||
assert "01.03.2026-31.03.2026" in word.headers["content-disposition"]
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_excel_opens_with_openpyxl(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
from openpyxl import load_workbook
|
||
wb = load_workbook(io.BytesIO(resp.content))
|
||
assert wb.active is not None
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_word_opens_with_python_docx(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
|
||
from docx import Document
|
||
d = Document(io.BytesIO(resp.content))
|
||
assert len(d.tables) > 0
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_excel_contains_all_daily_report_items(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
_, _, text = _excel_text(resp)
|
||
assert text.count("Монтаж трубы") == 3
|
||
assert text.count("Укладка кабеля") == 2
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_word_contains_all_daily_report_items(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
|
||
_, text = _word_text(resp)
|
||
assert text.count("Монтаж трубы") == 3
|
||
assert text.count("Укладка кабеля") == 2
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_export_system_filter(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(
|
||
f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}&system_id={data['sa_id']}"
|
||
)
|
||
assert resp.status_code == 200
|
||
_, _, text = _excel_text(resp)
|
||
assert "Монтаж трубы" in text
|
||
assert "Укладка кабеля" not in text
|
||
assert "Система A" in text
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_export_period_filter(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(
|
||
f"/projects/{data['pid']}/ks6a/export/excel?date_from=2026-03-01&date_to=2026-03-03"
|
||
)
|
||
assert resp.status_code == 200
|
||
_, _, text = _excel_text(resp)
|
||
# Only dr1 (01.03): dri1 + dri4
|
||
assert text.count("Монтаж трубы") == 1
|
||
assert text.count("Укладка кабеля") == 1
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_same_work_item_stays_as_separate_rows(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(
|
||
f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}&system_id={data['sa_id']}"
|
||
)
|
||
wb, ws, _ = _excel_text(resp)
|
||
# Collect dates and quantities of "Монтаж трубы" rows
|
||
rows = []
|
||
for row in ws.iter_rows():
|
||
values = [cell.value for cell in row]
|
||
if "Монтаж трубы" in values:
|
||
rows.append(values)
|
||
assert len(rows) == 3
|
||
dates = {r[1] for r in rows}
|
||
assert dates == {"01.03.2026", "05.03.2026", "10.03.2026"}
|
||
quantities = {float(r[7]) for r in rows}
|
||
assert quantities == {10.0, 15.0, 5.0}
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_export_has_no_price_or_amount(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
excel = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
_, _, excel_text = _excel_text(excel)
|
||
for banned in ("Цена", "Стоимость", "Сумма", "unit_price", "amount"):
|
||
assert banned not in excel_text
|
||
# Money values from WorkItem must not appear
|
||
assert "5000" not in excel_text
|
||
assert "6000" not in excel_text
|
||
|
||
word = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
|
||
_, word_text = _word_text(word)
|
||
for banned in ("Цена", "Стоимость", "Сумма"):
|
||
assert banned not in word_text
|
||
assert "5000" not in word_text
|
||
assert "6000" not in word_text
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_quantity_exported_as_number(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
_, ws, _ = _excel_text(resp)
|
||
numeric_quantities = []
|
||
for row in ws.iter_rows():
|
||
values = [cell.value for cell in row]
|
||
if "Монтаж трубы" in values or "Укладка кабеля" in values:
|
||
qty_cell = row[7]
|
||
assert isinstance(qty_cell.value, (int, float))
|
||
assert not isinstance(qty_cell.value, str)
|
||
numeric_quantities.append(float(qty_cell.value))
|
||
assert sorted(numeric_quantities) == [5.0, 10.0, 15.0, 20.0, 30.0]
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_rows_unaffected_by_ks2(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with Session() as s:
|
||
ks2 = KS2(
|
||
project_id=data["pid"], number="KS-001", status="issued",
|
||
date=datetime.date(2026, 3, 15),
|
||
reporting_period_from=datetime.date(2026, 3, 1),
|
||
reporting_period_to=datetime.date(2026, 3, 31),
|
||
)
|
||
s.add(ks2)
|
||
s.flush()
|
||
item = KS2Item(
|
||
ks2_id=ks2.id, work_item_id=data["wi1_id"],
|
||
quantity=Decimal("999"), unit_price=Decimal("50"), amount=Decimal("49950"),
|
||
)
|
||
s.add(item)
|
||
s.flush()
|
||
s.add(KS2ItemSource(
|
||
ks2_item_id=item.id,
|
||
daily_report_item_id=data["dri1_id"],
|
||
quantity=Decimal("10"),
|
||
))
|
||
s.commit()
|
||
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
_, _, text = _excel_text(resp)
|
||
assert text.count("Монтаж трубы") == 3
|
||
assert text.count("Укладка кабеля") == 2
|
||
# Quantity is still the DailyReportItem fact, not the KS-2 amount
|
||
assert "999" not in text
|
||
assert "49950" not in text
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_ks6a_rows_unaffected_by_ks3(tmp_path):
|
||
engine, Session = _make_session(tmp_path)
|
||
_override(Session)
|
||
try:
|
||
data = _create_ks6a_data(Session)
|
||
with Session() as s:
|
||
ks2 = KS2(
|
||
project_id=data["pid"], number="KS-100", status="issued",
|
||
date=datetime.date(2026, 3, 20),
|
||
)
|
||
s.add(ks2)
|
||
s.flush()
|
||
s.add(KS2Item(
|
||
ks2_id=ks2.id, work_item_id=data["wi1_id"],
|
||
quantity=Decimal("1"), unit_price=Decimal("50"), amount=Decimal("50"),
|
||
))
|
||
ks3 = KS3(
|
||
project_id=data["pid"], number="KS3-1", status="issued",
|
||
date=datetime.date(2026, 3, 25),
|
||
)
|
||
s.add(ks3)
|
||
s.flush()
|
||
s.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
|
||
s.commit()
|
||
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
|
||
_, _, text = _excel_text(resp)
|
||
assert text.count("Монтаж трубы") == 3
|
||
assert text.count("Укладка кабеля") == 2
|
||
# KS-3 identifiers/amounts must not alter KS-6a rows
|
||
assert "KS3-1" not in text
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|