"""Regression tests for task 016: KS-2 Excel/Word export.""" import io import shutil from decimal import Decimal from pathlib import Path 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, WorkItem from app.models.daily_report import DailyReport, DailyReportItem from app.models.ks2 import KS2, KS2Item from app.routers import projects, ks2 as ks2_router def _make_session(tmp_path): db_path = tmp_path / "t016-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): app.dependency_overrides[dep] = override_db def _clear(): for dep in (projects.get_db, ks2_router.get_db): app.dependency_overrides.pop(dep, None) def _create_ks2(Session): with Session() as s: p = Project(name="Export test", customer="Customer LLC", contract_number="DOG-123") s.add(p) s.flush() doc = BoqDocument(project_id=p.id, name="BOQ") s.add(doc) s.flush() wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="Монтаж трубы", source_number="1.1", unit="м", quantity=Decimal("100"), unit_price=Decimal("50"), amount=Decimal("5000")) s.add(wi) s.flush() dr = DailyReport(project_id=p.id, report_date=__import__("datetime").date(2026, 1, 1)) s.add(dr) s.flush() s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("30"))) s.flush() ks2 = KS2(project_id=p.id, number="2", date=__import__("datetime").date(2026, 9, 30), status="issued", reporting_period_from=__import__("datetime").date(2026, 9, 1), reporting_period_to=__import__("datetime").date(2026, 9, 30)) s.add(ks2) s.flush() s.add(KS2Item(ks2_id=ks2.id, work_item_id=wi.id, quantity=Decimal("30"), unit_price=Decimal("50"), amount=Decimal("1500"))) s.commit() return p.id, ks2.id def test_excel_endpoint_exists(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/excel") assert resp.status_code == 200 finally: _clear() engine.dispose() def test_word_endpoint_exists(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/word") assert resp.status_code == 200 finally: _clear() engine.dispose() def test_excel_content_type(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/excel") assert "spreadsheetml" in resp.headers["content-type"] finally: _clear() engine.dispose() def test_word_content_type(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/word") assert "wordprocessingml" in resp.headers["content-type"] finally: _clear() engine.dispose() def test_filename_contains_ks2_number(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/excel") assert "КС-2" in resp.headers["content-disposition"] or "filename" in resp.headers["content-disposition"] finally: _clear() engine.dispose() def test_excel_opens_with_openpyxl(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) ws = wb.active assert ws is not None finally: _clear() engine.dispose() def test_word_opens_with_python_docx(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/word") from docx import Document d = Document(io.BytesIO(resp.content)) assert len(d.tables) > 0 finally: _clear() engine.dispose() def test_excel_contains_rows(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) ws = wb.active text = "\n".join(str(cell.value) for row in ws.iter_rows() for cell in row if cell.value) assert "Монтаж трубы" in text finally: _clear() engine.dispose() def test_word_contains_rows(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/word") 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) assert "Монтаж трубы" in text finally: _clear() engine.dispose() def test_excel_total_matches(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) ws = wb.active # Find total row total_found = False for row in ws.iter_rows(): for cell in row: if cell.value and "ВСЕГО" in str(cell.value): total_cell = ws.cell(row=cell.row, column=11) assert abs(float(total_cell.value) - 1500.0) < 0.01 total_found = True assert total_found finally: _clear() engine.dispose() def test_export_does_not_modify_document(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with Session() as s: before_status = s.get(KS2, kid).status before_count = s.query(KS2Item).filter(KS2Item.ks2_id == kid).count() with TestClient(app) as client: client.get(f"/projects/{pid}/ks2/{kid}/export/excel") client.get(f"/projects/{pid}/ks2/{kid}/export/word") with Session() as s: assert s.get(KS2, kid).status == before_status assert s.query(KS2Item).filter(KS2Item.ks2_id == kid).count() == before_count finally: _clear() engine.dispose() def test_export_includes_money_regardless_of_privacy(tmp_path): """Export always contains real amounts regardless of UI privacy state.""" engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks2(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks2/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) ws = wb.active text = "\n".join(str(cell.value) for row in ws.iter_rows() for cell in row if cell.value) assert "1500" in text # amount present finally: _clear() engine.dispose()