feat: polish document exports and fix filename extensions

This commit is contained in:
Арсентьев Александр
2026-09-27 17:18:15 +03:00
parent d8e92386d9
commit b3741ca106
14 changed files with 920 additions and 112 deletions
+356
View File
@@ -0,0 +1,356 @@
"""Regression tests for task 020: export polish (requisites, filenames, formats)."""
import datetime
import io
import shutil
from decimal import Decimal
from urllib.parse import unquote
from fastapi.testclient import TestClient
from openpyxl import load_workbook
from docx import Document
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.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 / "t020-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_export_data(Session):
with Session() as s:
p = Project(
name="Export polish",
customer="Заказчик ООО",
contract_number="DOG-2026-7",
contract_date=datetime.date(2026, 1, 15),
currency="RUB",
)
s.add(p)
s.flush()
boq = BoqDocument(project_id=p.id, name="BOQ")
s.add(boq)
s.flush()
wi = WorkItem(
project_id=p.id, boq_document_id=boq.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=datetime.date(2026, 3, 10))
s.add(dr)
s.flush()
s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("10")))
s.flush()
ks2 = KS2(
project_id=p.id, number="7", date=datetime.date(2026, 3, 20),
status="issued",
reporting_period_from=datetime.date(2026, 3, 1),
reporting_period_to=datetime.date(2026, 3, 31),
comment="Проверка экспорта",
)
s.add(ks2)
s.flush()
s.add(KS2Item(ks2_id=ks2.id, work_item_id=wi.id,
quantity=Decimal("10"), unit_price=Decimal("50"), amount=Decimal("500")))
s.flush()
ks3 = KS3(
project_id=p.id, number="3", date=datetime.date(2026, 3, 25),
status="issued",
reporting_period_from=datetime.date(2026, 3, 1),
reporting_period_to=datetime.date(2026, 3, 31),
)
s.add(ks3)
s.flush()
s.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
s.commit()
return {"pid": p.id, "ks2_id": ks2.id, "ks3_id": ks3.id}
PERIOD = "date_from=2026-03-01&date_to=2026-03-31"
def _filename_from_disposition(disposition: str) -> str:
from urllib.parse import unquote
marker = "filename*=UTF-8''"
if marker in disposition:
return unquote(disposition.split(marker, 1)[1].strip())
return disposition
def _excel_text(resp):
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 is not None)
return wb, ws, text
def _word_text(resp):
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_ks2_excel_export_key_values(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel")
assert resp.status_code == 200
_, _, text = _excel_text(resp)
assert "Акт КС-2 №7" in text
assert "Export polish" in text
assert "Заказчик ООО" in text
assert "DOG-2026-7" in text
assert "15.01.2026" in text
assert "RUB" in text
assert "01.03.2026 — 31.03.2026" in text
assert "Монтаж трубопровода" in text
assert "500" in text
assert "Итого:" in text
finally:
_clear()
engine.dispose()
def test_ks2_word_export_key_values(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/word")
assert resp.status_code == 200
_, text = _word_text(resp)
assert "Акт КС-2 №7" in text
assert "DOG-2026-7" in text
assert "15.01.2026" in text
assert "RUB" in text
assert "Итого:" in text
assert "500.00" in text
finally:
_clear()
engine.dispose()
def test_ks3_export_key_values(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
excel = client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/excel")
assert excel.status_code == 200
_, _, text = _excel_text(excel)
assert "Акт КС-3 №3" in text
assert "DOG-2026-7" in text
assert "RUB" in text
assert "№7" in text
assert "Итого:" in text
word = client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/word")
assert word.status_code == 200
_, wtext = _word_text(word)
assert "Акт КС-3 №3" in wtext
assert "500.00" in wtext
finally:
_clear()
engine.dispose()
def test_ks6a_export_key_values(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
excel = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
assert excel.status_code == 200
_, _, text = _excel_text(excel)
assert "КС-6а" in text
assert "Export polish" in text
assert "DOG-2026-7" in text
assert "15.01.2026" in text
assert "RUB" in text
assert "Монтаж трубопровода" in text
assert "10.00" in text or "10" in text
word = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
assert word.status_code == 200
_, wtext = _word_text(word)
assert "КС-6а" in wtext
assert "DOG-2026-7" in wtext
finally:
_clear()
engine.dispose()
def test_no_double_extension_in_filenames(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
checks = [
client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel"),
client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/word"),
client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/excel"),
client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/word"),
client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}"),
client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}"),
]
for resp in checks:
assert resp.status_code == 200
filename = _filename_from_disposition(resp.headers["content-disposition"])
assert not filename.endswith(".xlsx.xlsx")
assert not filename.endswith(".docx.docx")
assert not filename.endswith(".xlsx.docx")
assert not filename.endswith(".docx.xlsx")
assert filename.count(".xlsx") <= 1
assert filename.count(".docx") <= 1
finally:
_clear()
engine.dispose()
def test_ks2_filenames_keep_type_number_date(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
excel = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel")
name = _filename_from_disposition(excel.headers["content-disposition"])
assert "КС-2" in name
assert "7" in name
assert "20.03.2026" in name
assert name.endswith(".xlsx")
word = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/word")
wname = _filename_from_disposition(word.headers["content-disposition"])
assert wname.endswith(".docx")
assert "КС-2" in wname
finally:
_clear()
engine.dispose()
def test_excel_quantity_is_numeric(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel")
_, ws, _ = _excel_text(resp)
found_qty = False
for row in ws.iter_rows():
for cell in row:
if isinstance(cell.value, (int, float)) and float(cell.value) == 10.0:
found_qty = True
assert found_qty
finally:
_clear()
engine.dispose()
def test_export_money_regardless_of_privacy(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel")
_, _, text = _excel_text(resp)
assert "500" in text # amount present without eye icon
finally:
_clear()
engine.dispose()
def test_package_still_works_after_polish(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
import zipfile
with TestClient(app) as client:
resp = client.get(
f"/projects/{data['pid']}/export/package?{PERIOD}"
f"&include=ks6a&include=ks2&include=ks3&format=both"
)
assert resp.status_code == 200
assert "application/zip" in resp.headers["content-type"]
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
names = zf.namelist()
assert any(n.startswith("КС-2/") for n in names)
assert any(n.startswith("КС-3/") for n in names)
assert any(n.startswith("КС-6а/") for n in names)
# Members open correctly
xlsx_name = next(n for n in names if n.startswith("КС-2/") and n.endswith(".xlsx"))
wb = load_workbook(io.BytesIO(zf.read(xlsx_name)))
assert wb.active is not None
docx_name = next(n for n in names if n.startswith("КС-3/") and n.endswith(".docx"))
d = Document(io.BytesIO(zf.read(docx_name)))
assert len(d.tables) > 0
finally:
_clear()
engine.dispose()
def test_long_work_name_wrapped_in_excel(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_export_data(Session)
with TestClient(app) as client:
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel")
_, ws, text = _excel_text(resp)
assert "Монтаж трубопровода системы отопления" in text
for row in ws.iter_rows():
for cell in row:
if isinstance(cell.value, str) and cell.value.startswith("Монтаж трубопровода"):
assert cell.alignment.wrap_text is True
finally:
_clear()
engine.dispose()