feat: official KS-2 Excel/Word forms with template markers and single-table flow

Replace the simplified KS-2 exports with the official unified form:

- Excel: official blank as working template, merge-safe row insertion,
  compact layout, header/signer polish, 0.00 money format
- Word: official blank via named template markers (DOC-C4), one dynamic
  works table with repeating header rows, separate closing totals block
  (Итого / Всего по акту), system group rows merged across 8 columns
- Word money formatter (space thousands, comma decimals) and split
  contract date day/month/year boxes
- Issue persists both xlsx and docx artifacts; UI keeps Excel and adds
  Word download
- Daily reports: multi-system item selection in the form

Regression tests for renderers, artifacts and layout; docs/tasks +
docs/implementation for the DOC-C* series.
This commit is contained in:
Арсентьев Александр
2026-10-03 19:48:29 +03:00
parent 79c7d4f335
commit bd64bb6307
49 changed files with 6917 additions and 353 deletions
+182
View File
@@ -0,0 +1,182 @@
"""DOC-C5: one Daily Report can hold positions of several systems.
Regression tests for the bug where, after adding a position of the first
system, positions of other systems stopped loading (and added positions
disappeared when switching the selected system).
"""
import re
from decimal import Decimal
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database.database import Base
from app.main import app
from app.models.project import Project
from app.models.boq import BoqDocument, System, Section, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.routers import daily_reports
def _seed(session):
project = Project(name="Multi system daily report")
session.add(project)
session.flush()
document = BoqDocument(project_id=project.id, name="BOQ")
session.add(document)
session.flush()
systems = {}
items = {}
for code, names in (("A", ["POS-A1", "POS-A2"]), ("B", ["POS-B1", "POS-B2"])):
system = System(project_id=project.id, name=f"System {code}")
session.add(system)
session.flush()
section = Section(system_id=system.id, name=f"Section {code}")
session.add(section)
session.flush()
systems[code] = system
items[code] = []
for number, name in enumerate(names, start=1):
item = WorkItem(project_id=project.id, boq_document_id=document.id, system_id=system.id,
section_id=section.id, source_number=str(number), name=name,
unit="pcs", quantity=Decimal("10"), amount=Decimal("100"))
items[code].append(item)
session.add(item)
session.flush()
return project.id, document.id, systems, items
def _row_tag(html, name):
match = re.search(rf'<tr[^>]*data-name="{re.escape(name)}"[^>]*>', html)
assert match, f"row {name} not found in form"
return match.group(0)
def test_multi_system_report_create_edit_and_switch():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
def override_db():
session = TestingSession()
try:
yield session
finally:
session.close()
with TestingSession() as session:
project_id, _document_id, systems, items = _seed(session)
session.commit()
a_id, b_id = systems["A"].id, systems["B"].id
a1, _a2 = (item.id for item in items["A"])
b1, _b2 = (item.id for item in items["B"])
app.dependency_overrides[daily_reports.get_db] = override_db
try:
with TestClient(app) as client:
# 2. Система A -> позиции загружаются; форма несёт позиции всех систем.
form_a = client.get(f"/projects/{project_id}/daily-reports/new?system_id={a_id}")
assert form_a.status_code == 200
assert "POS-A1" in form_a.text and "POS-A2" in form_a.text
for item_id in (a1, b1):
assert f'name="quantity_{item_id}"' in form_a.text
# 8. Повторный/другой выбор системы снова загружает её позиции.
form_b = client.get(f"/projects/{project_id}/daily-reports/new?system_id={b_id}")
assert form_b.status_code == 200
assert "POS-B1" in form_b.text and "POS-B2" in form_b.text
assert "POS-A1" in form_b.text
# 1./3./5./6./7. Один отчёт содержит позиции обеих систем.
created = client.post(f"/projects/{project_id}/daily-reports", data={
"report_date": "2026-03-01", "system_id": str(b_id),
f"quantity_{a1}": "3", f"quantity_{b1}": "5",
}, follow_redirects=False)
assert created.status_code == 303
report_id = int(created.headers["location"].rsplit("/", 1)[-1])
with TestingSession() as session:
report = session.query(DailyReport).one()
assert report.id == report_id
lines = {line.work_item_id: line.completed_quantity for line in report.items}
assert lines == {a1: Decimal("3"), b1: Decimal("5")}
view = client.get(f"/projects/{project_id}/daily-reports/{report_id}")
assert view.status_code == 200
assert "POS-A1" in view.text and "POS-B1" in view.text
# 4./8. Переключение на систему A в редактировании загружает её позиции,
# уже добавленные позиции другой системы остаются в форме.
edit_a = client.get(f"/projects/{project_id}/daily-reports/{report_id}/edit?system_id={a_id}")
assert edit_a.status_code == 200
assert f'name="quantity_{a1}"' in edit_a.text
assert f'name="quantity_{b1}"' in edit_a.text
assert re.search(rf'name="quantity_{b1}" value="5', edit_a.text)
assert "hidden" not in _row_tag(edit_a.text, "POS-B1")
assert "hidden" not in _row_tag(edit_a.text, "POS-A2")
assert "hidden" in _row_tag(edit_a.text, "POS-B2")
# Сохранение не удаляет позиции другой системы.
edited = client.post(f"/projects/{project_id}/daily-reports/{report_id}/edit", data={
"report_date": "2026-03-01", "system_id": str(a_id),
f"quantity_{a1}": "3", f"quantity_{b1}": "5",
}, follow_redirects=False)
assert edited.status_code == 303
# 8. Снова система B — позиции загружаются.
edit_b = client.get(f"/projects/{project_id}/daily-reports/{report_id}/edit?system_id={b_id}")
assert edit_b.status_code == 200
assert "POS-B1" in edit_b.text and "POS-B2" in edit_b.text
with TestingSession() as session:
report = session.query(DailyReport).one()
lines = {line.work_item_id: line.completed_quantity for line in report.items}
assert lines == {a1: Decimal("3"), b1: Decimal("5")}
finally:
app.dependency_overrides.pop(daily_reports.get_db, None)
engine.dispose()
def test_multi_system_edit_switch_to_unclassified_still_works():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
def override_db():
session = TestingSession()
try:
yield session
finally:
session.close()
with TestingSession() as session:
project_id, document_id, systems, items = _seed(session)
free = WorkItem(project_id=project_id, boq_document_id=document_id, system_id=None,
section_id=None, source_number="9", name="POS-FREE",
unit="pcs", quantity=Decimal("4"), amount=Decimal("40"))
session.add(free)
session.commit()
a_id = systems["A"].id
a1 = items["A"][0].id
free_id = free.id
app.dependency_overrides[daily_reports.get_db] = override_db
try:
with TestClient(app) as client:
created = client.post(f"/projects/{project_id}/daily-reports", data={
"report_date": "2026-03-02", "system_id": str(a_id),
f"quantity_{a1}": "1", f"quantity_{free_id}": "2",
}, follow_redirects=False)
assert created.status_code == 303
report_id = int(created.headers["location"].rsplit("/", 1)[-1])
edit_free = client.get(
f"/projects/{project_id}/daily-reports/{report_id}/edit?system_id=unclassified")
assert edit_free.status_code == 200
assert "POS-FREE" in edit_free.text
assert f'name="quantity_{a1}"' in edit_free.text
finally:
app.dependency_overrides.pop(daily_reports.get_db, None)
engine.dispose()