feat: add KS-3/payments, tech debt fixes, UI polish, and KS-2 Excel/Word export
Tasks 008-016: KS-6a journal, KS-3 documents, payments with allocations, tech debt cleanup, financial privacy, document tree, storno mechanism, row-click UI, BOQ collapse/sticky header, and KS-2 export to Excel/Word via shared DTO architecture.
This commit is contained in:
@@ -0,0 +1,365 @@
|
||||
import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
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.models.project import Project
|
||||
from app.models.boq import BoqDocument, WorkItem
|
||||
from app.services.ks2_service import save_draft as save_ks2_draft, issue_ks2
|
||||
from app.services.ks3_service import (
|
||||
KS3ValidationError, available_ks2, issue_ks3, project_ks3_totals, save_draft,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
from app.database.database import Base
|
||||
Base.metadata.create_all(engine)
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
yield session
|
||||
session.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(db_session):
|
||||
project = Project(name="KS-3 проект")
|
||||
db_session.add(project)
|
||||
db_session.commit()
|
||||
db_session.refresh(project)
|
||||
return project
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def work_item(db_session, project):
|
||||
boq_doc = BoqDocument(project_id=project.id, name="Ведомость")
|
||||
db_session.add(boq_doc)
|
||||
db_session.flush()
|
||||
wi = WorkItem(
|
||||
project_id=project.id, boq_document_id=boq_doc.id,
|
||||
name="Работа", unit="ед", quantity=Decimal("10"),
|
||||
unit_price=Decimal("100"), amount=Decimal("1000"),
|
||||
)
|
||||
db_session.add(wi)
|
||||
db_session.commit()
|
||||
db_session.refresh(wi)
|
||||
return wi
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def daily_report_item(db_session, project, work_item):
|
||||
dr = DailyReport(project_id=project.id, report_date=datetime.date(2024, 1, 1))
|
||||
db_session.add(dr)
|
||||
db_session.flush()
|
||||
dri = DailyReportItem(daily_report_id=dr.id, work_item_id=work_item.id,
|
||||
completed_quantity=Decimal("10"))
|
||||
db_session.add(dri)
|
||||
db_session.commit()
|
||||
db_session.refresh(dri)
|
||||
return dri
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def issued_ks2(db_session, project, work_item, daily_report_item):
|
||||
"""Create and issue a KS-2 with known amount."""
|
||||
doc = save_ks2_draft(
|
||||
db_session, project.id, "KS2-001", datetime.date(2024, 2, 1), "",
|
||||
[(work_item.id, "5")],
|
||||
reporting_period_from=datetime.date(2024, 1, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 31),
|
||||
)
|
||||
issued = issue_ks2(db_session, project.id, doc.id)
|
||||
return issued
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def issued_ks2_b(db_session, project, work_item, daily_report_item):
|
||||
"""Create and issue a second KS-2."""
|
||||
doc = save_ks2_draft(
|
||||
db_session, project.id, "KS2-002", datetime.date(2024, 2, 15), "",
|
||||
[(work_item.id, "3")],
|
||||
reporting_period_from=datetime.date(2024, 1, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 31),
|
||||
)
|
||||
issued = issue_ks2(db_session, project.id, doc.id)
|
||||
return issued
|
||||
|
||||
|
||||
DEFAULT_PERIOD_FROM = datetime.date(2024, 1, 1)
|
||||
DEFAULT_PERIOD_TO = datetime.date(2024, 1, 31)
|
||||
|
||||
|
||||
def test_create_draft(db_session, project, issued_ks2):
|
||||
"""1. Создание draft КС-3."""
|
||||
doc = save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "Тест",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
assert doc.number == "KS3-001"
|
||||
assert doc.status == "draft"
|
||||
assert len(doc.links) == 1
|
||||
assert doc.links[0].ks2_id == issued_ks2.id
|
||||
|
||||
|
||||
def test_period_required(db_session, project, issued_ks2):
|
||||
"""2. Обязательность периода."""
|
||||
with pytest.raises(KS3ValidationError, match="дату начала периода"):
|
||||
save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=None,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
with pytest.raises(KS3ValidationError, match="дату окончания периода"):
|
||||
save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=None,
|
||||
)
|
||||
|
||||
|
||||
def test_period_validation(db_session, project, issued_ks2):
|
||||
"""3. Проверка date_to >= date_from."""
|
||||
with pytest.raises(KS3ValidationError, match="не может быть раньше"):
|
||||
save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=datetime.date(2024, 2, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 1),
|
||||
)
|
||||
|
||||
|
||||
def test_select_single_ks2(db_session, project, issued_ks2):
|
||||
"""4. Выбор одного КС-2."""
|
||||
doc = save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
assert len(doc.links) == 1
|
||||
assert doc.links[0].ks2_id == issued_ks2.id
|
||||
|
||||
|
||||
def test_select_multiple_ks2(db_session, project, issued_ks2, issued_ks2_b):
|
||||
"""5. Выбор нескольких КС-2."""
|
||||
doc = save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id, issued_ks2_b.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
assert len(doc.links) == 2
|
||||
ids = {link.ks2_id for link in doc.links}
|
||||
assert ids == {issued_ks2.id, issued_ks2_b.id}
|
||||
|
||||
|
||||
def test_cannot_select_draft_ks2(db_session, project, work_item, daily_report_item):
|
||||
"""6. Нельзя выбрать draft КС-2."""
|
||||
draft_ks2 = save_ks2_draft(
|
||||
db_session, project.id, "KS2-DRAFT", datetime.date(2024, 2, 1), "",
|
||||
[(work_item.id, "5")],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
with pytest.raises(KS3ValidationError, match="не проведён"):
|
||||
save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[draft_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
|
||||
|
||||
def test_cannot_select_other_project_ks2(db_session, project, issued_ks2):
|
||||
"""7. Нельзя выбрать КС-2 другого проекта."""
|
||||
project2 = Project(name="Другой проект")
|
||||
db_session.add(project2)
|
||||
db_session.commit()
|
||||
db_session.refresh(project2)
|
||||
|
||||
with pytest.raises(KS3ValidationError, match="не принадлежит"):
|
||||
save_draft(
|
||||
db_session, project2.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
|
||||
|
||||
def test_ks3_amount_equals_sum_of_issued_ks2(db_session, project, issued_ks2, issued_ks2_b):
|
||||
"""8. Сумма КС-3 = сумме выбранных issued КС-2."""
|
||||
doc = save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id, issued_ks2_b.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
totals = project_ks3_totals(db_session, project.id)
|
||||
assert len(totals) == 1
|
||||
# ks2 amount: 5*100=500, ks2_b amount: 3*100=300, total=800
|
||||
assert totals[0]["amount"] == Decimal("800.000000000000")
|
||||
|
||||
|
||||
def test_ks3_does_not_modify_ks2(db_session, project, issued_ks2, issued_ks2_b):
|
||||
"""9. КС-3 не изменяет КС-2."""
|
||||
doc = save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id, issued_ks2_b.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
ks2a = db_session.query(KS2).filter(KS2.id == issued_ks2.id).first()
|
||||
ks2b = db_session.query(KS2).filter(KS2.id == issued_ks2_b.id).first()
|
||||
assert ks2a.status == "issued"
|
||||
assert ks2b.status == "issued"
|
||||
assert len(ks2a.items) == 1
|
||||
assert ks2a.items[0].quantity == Decimal("5")
|
||||
|
||||
|
||||
def test_issue_ks3(db_session, project, issued_ks2):
|
||||
"""10. Выпуск КС-3."""
|
||||
doc = save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
issued = issue_ks3(db_session, project.id, doc.id)
|
||||
assert issued.status == "issued"
|
||||
|
||||
|
||||
def test_issued_ks3_cannot_be_edited(db_session, project, issued_ks2):
|
||||
"""11. Issued КС-3 нельзя редактировать."""
|
||||
doc = save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
issue_ks3(db_session, project.id, doc.id)
|
||||
|
||||
with pytest.raises(KS3ValidationError, match="Проведённый КС-3 нельзя редактировать"):
|
||||
save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 2), "edit",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
ks3_id=doc.id,
|
||||
)
|
||||
|
||||
|
||||
def test_duplicate_ks2_in_same_ks3_rejected(db_session, project, issued_ks2):
|
||||
"""12. Повторный выбор одного КС-2 внутри одного КС-3 запрещён."""
|
||||
with pytest.raises(KS3ValidationError, match="дважды"):
|
||||
save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id, issued_ks2.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
|
||||
|
||||
def test_issue_atomicity(db_session, project, work_item, daily_report_item):
|
||||
"""13. Выпуск атомарен при изменении состояния КС-2."""
|
||||
ks2_doc = save_ks2_draft(
|
||||
db_session, project.id, "KS2-X", datetime.date(2024, 2, 1), "",
|
||||
[(work_item.id, "2")],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
ks2_issued = issue_ks2(db_session, project.id, ks2_doc.id)
|
||||
|
||||
ks3_doc = save_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[ks2_issued.id],
|
||||
reporting_period_from=DEFAULT_PERIOD_FROM,
|
||||
reporting_period_to=DEFAULT_PERIOD_TO,
|
||||
)
|
||||
|
||||
# Change KS-2 back to draft to simulate invalid state at issue time
|
||||
ks2_issued.status = "draft"
|
||||
db_session.commit()
|
||||
|
||||
with pytest.raises(KS3ValidationError, match="не проведён"):
|
||||
issue_ks3(db_session, project.id, ks3_doc.id)
|
||||
|
||||
# KS-3 remains draft
|
||||
ks3 = db_session.query(KS3).filter(KS3.id == ks3_doc.id).first()
|
||||
assert ks3.status == "draft"
|
||||
|
||||
|
||||
def test_ks3_count_on_project_page():
|
||||
"""Счётчик КС-3 отображается на странице проекта."""
|
||||
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.routers import projects as project_router, ks3 as ks3_router
|
||||
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
Base.metadata.create_all(engine)
|
||||
TestingSession = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
with TestingSession() as db:
|
||||
proj = Project(name="Count test")
|
||||
db.add(proj)
|
||||
db.commit()
|
||||
pid = proj.id
|
||||
|
||||
def override_db():
|
||||
db = TestingSession()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
for dep in (project_router.get_db, ks3_router.get_db):
|
||||
app.dependency_overrides[dep] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
# No KS-3 yet — no count shown
|
||||
page = client.get(f"/projects/{pid}")
|
||||
assert page.status_code == 200
|
||||
assert "КС-3" in page.text
|
||||
|
||||
# Create a KS-3 directly in DB
|
||||
with TestingSession() as db:
|
||||
doc = KS3(project_id=pid, number="C-001", status="draft",
|
||||
date=datetime.date(2024, 1, 1),
|
||||
reporting_period_from=datetime.date(2024, 1, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 31))
|
||||
db.add(doc)
|
||||
db.commit()
|
||||
|
||||
page2 = client.get(f"/projects/{pid}")
|
||||
assert page2.status_code == 200
|
||||
assert "КС-3 (1)" in page2.text
|
||||
|
||||
# Add a second one
|
||||
with TestingSession() as db:
|
||||
doc2 = KS3(project_id=pid, number="C-002", status="draft",
|
||||
date=datetime.date(2024, 2, 1),
|
||||
reporting_period_from=datetime.date(2024, 2, 1),
|
||||
reporting_period_to=datetime.date(2024, 2, 29))
|
||||
db.add(doc2)
|
||||
db.commit()
|
||||
|
||||
page3 = client.get(f"/projects/{pid}")
|
||||
assert page3.status_code == 200
|
||||
assert "КС-3 (2)" in page3.text
|
||||
finally:
|
||||
for dep in (project_router.get_db, ks3_router.get_db):
|
||||
app.dependency_overrides.pop(dep, None)
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,196 @@
|
||||
import datetime
|
||||
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 import boq
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||
from app.routers import projects as project_router, ks6a as ks6a_router
|
||||
|
||||
|
||||
def test_ks6a_full_workflow():
|
||||
"""Интеграционный тест КС-6а: все 11 требований."""
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
Base.metadata.create_all(engine)
|
||||
TestingSession = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
with TestingSession() as db:
|
||||
project = Project(name="KS-6a проект")
|
||||
db.add(project)
|
||||
db.flush()
|
||||
|
||||
system_a = boq.System(project_id=project.id, name="Система A", sort_order=1)
|
||||
system_b = boq.System(project_id=project.id, name="Система B", sort_order=2)
|
||||
db.add_all([system_a, system_b])
|
||||
db.flush()
|
||||
|
||||
section_a = boq.Section(system_id=system_a.id, name="Раздел A1")
|
||||
db.add(section_a)
|
||||
db.flush()
|
||||
|
||||
doc = boq.BoqDocument(project_id=project.id, name="Ведомость")
|
||||
db.add(doc)
|
||||
db.flush()
|
||||
|
||||
wi1 = boq.WorkItem(
|
||||
project_id=project.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 = boq.WorkItem(
|
||||
project_id=project.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"),
|
||||
)
|
||||
db.add_all([wi1, wi2])
|
||||
db.flush()
|
||||
|
||||
# Daily Reports в разные даты
|
||||
dr1 = DailyReport(project_id=project.id, report_date=datetime.date(2024, 3, 1))
|
||||
dr2 = DailyReport(project_id=project.id, report_date=datetime.date(2024, 3, 5))
|
||||
dr3 = DailyReport(project_id=project.id, report_date=datetime.date(2024, 3, 10))
|
||||
db.add_all([dr1, dr2, dr3])
|
||||
db.flush()
|
||||
|
||||
# 5 DailyReportItem: wi1 в 3 разных даты, wi2 в 2 даты
|
||||
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"))
|
||||
db.add_all([dri1, dri2, dri3, dri4, dri5])
|
||||
db.commit()
|
||||
|
||||
pid = project.id
|
||||
sa_id = system_a.id
|
||||
sb_id = system_b.id
|
||||
|
||||
def override_db():
|
||||
db = TestingSession()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
for dep in (project_router.get_db, ks6a_router.get_db):
|
||||
app.dependency_overrides[dep] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
# === 1. Страница КС-6а открывается ===
|
||||
page = client.get(f"/projects/{pid}/ks6a")
|
||||
assert page.status_code == 200
|
||||
assert "КС-6а" in page.text
|
||||
assert "Журнал выполненных работ" in page.text
|
||||
|
||||
# === 2. Отображается выбранный период ===
|
||||
report = client.get(f"/projects/{pid}/ks6a?date_from=2024-03-01&date_to=2024-03-31")
|
||||
assert report.status_code == 200
|
||||
assert "2024-03-01" in report.text
|
||||
assert "2024-03-31" in report.text
|
||||
|
||||
# === 3. Все DailyReportItem попадают в журнал ===
|
||||
assert "Монтаж трубы" in report.text
|
||||
assert "Укладка кабеля" in report.text
|
||||
assert "Строк: 5" in report.text
|
||||
|
||||
# === 4. Каждая DailyReportItem — отдельная строка ===
|
||||
# 3 строки wi1 + 2 строки wi2 = 5 строк
|
||||
assert report.text.count("Монтаж трубы") == 3
|
||||
assert report.text.count("Укладка кабеля") == 2
|
||||
|
||||
# === 5. Фильтр по системе работает ===
|
||||
sys_a_report = client.get(
|
||||
f"/projects/{pid}/ks6a?date_from=2024-03-01&date_to=2024-03-31&system_id={sa_id}"
|
||||
)
|
||||
assert sys_a_report.status_code == 200
|
||||
assert "Монтаж трубы" in sys_a_report.text
|
||||
assert "Укладка кабеля" not in sys_a_report.text
|
||||
assert "Строк: 3" in sys_a_report.text
|
||||
|
||||
# === 6. Фильтр по периоду работает ===
|
||||
short_period = client.get(
|
||||
f"/projects/{pid}/ks6a?date_from=2024-03-01&date_to=2024-03-03"
|
||||
)
|
||||
assert short_period.status_code == 200
|
||||
# Только dr1 (01.03)
|
||||
assert "Строк: 2" in short_period.text # dri1 + dri4
|
||||
|
||||
# === 7. date_to < date_from отклоняется ===
|
||||
bad_dates = client.get(
|
||||
f"/projects/{pid}/ks6a?date_from=2024-03-10&date_to=2024-03-01"
|
||||
)
|
||||
assert bad_dates.status_code == 200
|
||||
assert "не может быть раньше" in bad_dates.text
|
||||
|
||||
# === 8. KS-2 не влияет на наличие строки КС-6а ===
|
||||
# Проведём KS-2 по wi1
|
||||
with TestingSession() as db:
|
||||
ks2_doc = KS2(project_id=pid, number="KS-001", status="draft",
|
||||
date=datetime.date(2024, 3, 15),
|
||||
reporting_period_from=datetime.date(2024, 3, 1),
|
||||
reporting_period_to=datetime.date(2024, 3, 31))
|
||||
db.add(ks2_doc)
|
||||
db.flush()
|
||||
ks2_item = KS2Item(ks2_id=ks2_doc.id, work_item_id=wi1.id,
|
||||
quantity=Decimal("10"), unit_price=Decimal("50"),
|
||||
amount=Decimal("500"))
|
||||
db.add(ks2_item)
|
||||
db.flush()
|
||||
# Проведём вручную
|
||||
ks2_doc.status = "issued"
|
||||
db.add(KS2ItemSource(ks2_item_id=ks2_item.id,
|
||||
daily_report_item_id=dri1.id,
|
||||
quantity=Decimal("10")))
|
||||
db.commit()
|
||||
|
||||
# КС-6а всё равно показывает все 5 строк
|
||||
after_ks2 = client.get(
|
||||
f"/projects/{pid}/ks6a?date_from=2024-03-01&date_to=2024-03-31"
|
||||
)
|
||||
assert after_ks2.status_code == 200
|
||||
assert "Строк: 5" in after_ks2.text
|
||||
assert "Монтаж трубы" in after_ks2.text
|
||||
|
||||
# === 9. Цены и суммы не попадают в КС-6а ===
|
||||
# Нет денежных символов и формата "5 000"
|
||||
assert "₽" not in after_ks2.text
|
||||
assert "5 000" not in after_ks2.text
|
||||
# Проверяем что в строках таблицы нет unit_price как отдельного значения
|
||||
# Цена/Сумма отсутствуют как колонки
|
||||
assert "Цена" not in after_ks2.text
|
||||
assert "Сумма" not in after_ks2.text
|
||||
|
||||
# === 10. Несколько DailyReportItem одного WorkItem не агрегируются ===
|
||||
# wi1 имеет 3 строки в разные даты — проверяем что все 3 отображаются
|
||||
all_dates = client.get(
|
||||
f"/projects/{pid}/ks6a?date_from=2024-03-01&date_to=2024-03-31&system_id={sa_id}"
|
||||
)
|
||||
assert all_dates.status_code == 200
|
||||
assert "01.03.2024" in all_dates.text
|
||||
assert "05.03.2024" in all_dates.text
|
||||
assert "10.03.2024" in all_dates.text
|
||||
assert "Строк: 3" in all_dates.text
|
||||
|
||||
# === 11. Количество отображается с двумя знаками ===
|
||||
# Ищем формат "10.00", "15.00", "5.00", "20.00", "30.00"
|
||||
assert "10.00" in after_ks2.text
|
||||
assert "15.00" in after_ks2.text
|
||||
assert "5.00" in after_ks2.text
|
||||
|
||||
# Кнопка КС-6а на странице проекта
|
||||
project_page = client.get(f"/projects/{pid}")
|
||||
assert project_page.status_code == 200
|
||||
assert "КС-6а" in project_page.text
|
||||
finally:
|
||||
for dep in (project_router.get_db, ks6a_router.get_db):
|
||||
app.dependency_overrides.pop(dep, None)
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,548 @@
|
||||
import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
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.models.payment import Payment, PaymentAllocation
|
||||
from app.models.project import Project
|
||||
from app.models.boq import BoqDocument, WorkItem
|
||||
from app.services.ks2_service import save_draft as save_ks2_draft, issue_ks2
|
||||
from app.services.ks3_service import issue_ks3, save_draft as save_ks3_draft
|
||||
from app.services.payment_service import (
|
||||
PaymentValidationError, available_ks3_for_payment, delete_payment,
|
||||
ks3_payment_summary, project_payments, save_payment,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
from app.database.database import Base
|
||||
Base.metadata.create_all(engine)
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
yield session
|
||||
session.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(db_session):
|
||||
p = Project(name="Payment проект")
|
||||
db_session.add(p)
|
||||
db_session.commit()
|
||||
db_session.refresh(p)
|
||||
return p
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_b(db_session):
|
||||
p = Project(name="Другой проект")
|
||||
db_session.add(p)
|
||||
db_session.commit()
|
||||
db_session.refresh(p)
|
||||
return p
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def work_item(db_session, project):
|
||||
boq_doc = BoqDocument(project_id=project.id, name="Ведомость")
|
||||
db_session.add(boq_doc)
|
||||
db_session.flush()
|
||||
wi = WorkItem(
|
||||
project_id=project.id, boq_document_id=boq_doc.id,
|
||||
name="Работа", unit="ед", quantity=Decimal("10"),
|
||||
unit_price=Decimal("100"), amount=Decimal("1000"),
|
||||
)
|
||||
db_session.add(wi)
|
||||
db_session.commit()
|
||||
db_session.refresh(wi)
|
||||
return wi
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def daily_report_item(db_session, project, work_item):
|
||||
dr = DailyReport(project_id=project.id, report_date=datetime.date(2024, 1, 1))
|
||||
db_session.add(dr)
|
||||
db_session.flush()
|
||||
dri = DailyReportItem(daily_report_id=dr.id, work_item_id=work_item.id,
|
||||
completed_quantity=Decimal("10"))
|
||||
db_session.add(dri)
|
||||
db_session.commit()
|
||||
db_session.refresh(dri)
|
||||
return dri
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def issued_ks2(db_session, project, work_item, daily_report_item):
|
||||
doc = save_ks2_draft(
|
||||
db_session, project.id, "KS2-001", datetime.date(2024, 2, 1), "",
|
||||
[(work_item.id, "10")],
|
||||
reporting_period_from=datetime.date(2024, 1, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 31),
|
||||
)
|
||||
return issue_ks2(db_session, project.id, doc.id)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def issued_ks3(db_session, project, issued_ks2):
|
||||
doc = save_ks3_draft(
|
||||
db_session, project.id, "KS3-001", datetime.date(2024, 3, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=datetime.date(2024, 1, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 31),
|
||||
)
|
||||
return issue_ks3(db_session, project.id, doc.id)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def issued_ks3_b(db_session, project, work_item, daily_report_item, issued_ks2):
|
||||
dr2 = DailyReport(project_id=project.id, report_date=datetime.date(2024, 1, 15))
|
||||
db_session.add(dr2)
|
||||
db_session.flush()
|
||||
dri2 = DailyReportItem(daily_report_id=dr2.id, work_item_id=work_item.id,
|
||||
completed_quantity=Decimal("5"))
|
||||
db_session.add(dri2)
|
||||
db_session.flush()
|
||||
|
||||
doc2 = save_ks2_draft(
|
||||
db_session, project.id, "KS2-002", datetime.date(2024, 2, 15), "",
|
||||
[(work_item.id, "5")],
|
||||
reporting_period_from=datetime.date(2024, 1, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 31),
|
||||
)
|
||||
ks2_b = issue_ks2(db_session, project.id, doc2.id)
|
||||
|
||||
doc = save_ks3_draft(
|
||||
db_session, project.id, "KS3-002", datetime.date(2024, 3, 15), "",
|
||||
[ks2_b.id],
|
||||
reporting_period_from=datetime.date(2024, 1, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 31),
|
||||
)
|
||||
return issue_ks3(db_session, project.id, doc.id)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def draft_ks3(db_session, project, issued_ks2):
|
||||
return save_ks3_draft(
|
||||
db_session, project.id, "KS3-D", datetime.date(2024, 4, 1), "",
|
||||
[issued_ks2.id],
|
||||
reporting_period_from=datetime.date(2024, 1, 1),
|
||||
reporting_period_to=datetime.date(2024, 1, 31),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Создание платежа
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_create_payment(db_session, project, issued_ks3):
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", "Тестовый платёж", [],
|
||||
)
|
||||
assert payment.id is not None
|
||||
assert payment.amount == Decimal("1000")
|
||||
assert payment.currency == "RUB"
|
||||
assert payment.comment == "Тестовый платёж"
|
||||
assert payment.project_id == project.id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Обязательные / валидные поля
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_date_required(db_session, project):
|
||||
with pytest.raises((PaymentValidationError, Exception)):
|
||||
save_payment(
|
||||
db_session, project.id, None,
|
||||
Decimal("1000"), "RUB", None, [],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Сумма платежа > 0
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_amount_must_be_positive(db_session, project):
|
||||
with pytest.raises(PaymentValidationError, match="больше нуля"):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("0"), "RUB", None, [],
|
||||
)
|
||||
with pytest.raises(PaymentValidationError, match="больше нуля"):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("-100"), "RUB", None, [],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Создание платежа без распределения
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_create_without_allocation(db_session, project, issued_ks3):
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("500"), "RUB", None, [],
|
||||
)
|
||||
assert len(payment.allocations) == 0
|
||||
summary = ks3_payment_summary(db_session, project.id)
|
||||
assert summary["paid"] == Decimal("0")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Распределение на один КС-3
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_allocate_to_single_ks3(db_session, project, issued_ks3):
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("500")}],
|
||||
)
|
||||
assert len(payment.allocations) == 1
|
||||
assert payment.allocations[0].ks3_id == issued_ks3.id
|
||||
assert payment.allocations[0].amount == Decimal("500")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. Распределение одного платежа на несколько КС-3
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_allocate_to_multiple_ks3(db_session, project, issued_ks3, issued_ks3_b):
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1500"), "RUB", None,
|
||||
[
|
||||
{"ks3_id": issued_ks3.id, "amount": Decimal("1000")},
|
||||
{"ks3_id": issued_ks3_b.id, "amount": Decimal("500")},
|
||||
],
|
||||
)
|
||||
assert len(payment.allocations) == 2
|
||||
amounts = {a.ks3_id: a.amount for a in payment.allocations}
|
||||
assert amounts[issued_ks3.id] == Decimal("1000")
|
||||
assert amounts[issued_ks3_b.id] == Decimal("500")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. Нельзя распределять на draft КС-3
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_cannot_allocate_to_draft_ks3(db_session, project, draft_ks3):
|
||||
with pytest.raises(PaymentValidationError, match="не проведён"):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("500"), "RUB", None,
|
||||
[{"ks3_id": draft_ks3.id, "amount": Decimal("100")}],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 8. Нельзя распределять на КС-3 другого проекта
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_cannot_allocate_to_other_project_ks3(db_session, project, project_b, issued_ks3):
|
||||
with pytest.raises(PaymentValidationError, match="не принадлежит"):
|
||||
save_payment(
|
||||
db_session, project_b.id, datetime.date(2024, 4, 1),
|
||||
Decimal("500"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("100")}],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 9. Allocation > 0
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_allocation_must_be_positive(db_session, project, issued_ks3):
|
||||
with pytest.raises(PaymentValidationError, match="больше нуля"):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("0")}],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 10. Сумма allocations не превышает сумму платежа
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_allocations_exceed_payment(db_session, project, issued_ks3):
|
||||
with pytest.raises(PaymentValidationError, match="превышает"):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("100"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("200")}],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 11. Нельзя превысить outstanding КС-3
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_cannot_exceed_outstanding(db_session, project, issued_ks3):
|
||||
# issued_ks3 total = 1000 (10 items * 100 price)
|
||||
with pytest.raises(PaymentValidationError, match="остаток к оплате"):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("2000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("1500")}],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 12. Несколько платежей уменьшают outstanding одного КС-3
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_multiple_payments_reduce_outstanding(db_session, project, issued_ks3):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("600")}],
|
||||
)
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 5),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("400")}],
|
||||
)
|
||||
avail = available_ks3_for_payment(db_session, project.id)
|
||||
ks3_info = next(x for x in avail if x["id"] == issued_ks3.id)
|
||||
assert ks3_info["paid"] == Decimal("1000")
|
||||
assert ks3_info["outstanding"] == Decimal("0")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 13. Частично оплаченный КС-3
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_partially_paid_ks3(db_session, project, issued_ks3):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("400")}],
|
||||
)
|
||||
avail = available_ks3_for_payment(db_session, project.id)
|
||||
ks3_info = next(x for x in avail if x["id"] == issued_ks3.id)
|
||||
assert ks3_info["paid"] == Decimal("400")
|
||||
assert ks3_info["outstanding"] == Decimal("600")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 14. Полностью оплаченный КС-3
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_fully_paid_ks3(db_session, project, issued_ks3):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("1000")}],
|
||||
)
|
||||
avail = available_ks3_for_payment(db_session, project.id)
|
||||
ks3_info = next(x for x in avail if x["id"] == issued_ks3.id)
|
||||
assert ks3_info["outstanding"] == Decimal("0")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 15. Нераспределённый остаток платежа
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_unallocated_remainder(db_session, project, issued_ks3):
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("600")}],
|
||||
)
|
||||
rows = project_payments(db_session, project.id)
|
||||
row = rows[0]
|
||||
assert row["allocated"] == Decimal("600")
|
||||
assert row["unallocated"] == Decimal("400")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 16. Редактирование платежа корректно пересчитывает allocations
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_edit_payment_recalculates(db_session, project, issued_ks3, issued_ks3_b):
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("1000")}],
|
||||
)
|
||||
# Reassign allocation to ks3_b
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 2),
|
||||
Decimal("1000"), "RUB", "Изменён",
|
||||
[{"ks3_id": issued_ks3_b.id, "amount": Decimal("500")}],
|
||||
payment_id=payment.id,
|
||||
)
|
||||
assert len(payment.allocations) == 1
|
||||
assert payment.allocations[0].ks3_id == issued_ks3_b.id
|
||||
assert payment.allocations[0].amount == Decimal("500")
|
||||
assert payment.comment == "Изменён"
|
||||
# Original ks3 should have outstanding restored
|
||||
avail = available_ks3_for_payment(db_session, project.id)
|
||||
ks3_a_info = next(x for x in avail if x["id"] == issued_ks3.id)
|
||||
assert ks3_a_info["outstanding"] == Decimal("1000")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 17. Удаление платежа корректно возвращает outstanding
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_delete_payment_restores_outstanding(db_session, project, issued_ks3):
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("1000")}],
|
||||
)
|
||||
avail = available_ks3_for_payment(db_session, project.id)
|
||||
ks3_info = next(x for x in avail if x["id"] == issued_ks3.id)
|
||||
assert ks3_info["outstanding"] == Decimal("0")
|
||||
|
||||
delete_payment(db_session, project.id, payment.id)
|
||||
avail = available_ks3_for_payment(db_session, project.id)
|
||||
ks3_info = next(x for x in avail if x["id"] == issued_ks3.id)
|
||||
assert ks3_info["outstanding"] == Decimal("1000")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 18. Issued КС-3 не изменяется платежом
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_issued_ks3_not_modified_by_payment(db_session, project, issued_ks3):
|
||||
ks3_before = db_session.query(KS3).filter(KS3.id == issued_ks3.id).first()
|
||||
before_number = ks3_before.number
|
||||
before_status = ks3_before.status
|
||||
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("500")}],
|
||||
)
|
||||
db_session.expire_all()
|
||||
ks3_after = db_session.query(KS3).filter(KS3.id == issued_ks3.id).first()
|
||||
assert ks3_after.number == before_number
|
||||
assert ks3_after.status == before_status
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 19. Атомарность при невалидном распределении
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_atomicity_on_invalid_allocation(db_session, project, issued_ks3):
|
||||
payment_count_before = db_session.query(Payment).count()
|
||||
alloc_count_before = db_session.query(PaymentAllocation).count()
|
||||
|
||||
with pytest.raises(PaymentValidationError):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("100"), "RUB", None,
|
||||
[
|
||||
{"ks3_id": issued_ks3.id, "amount": Decimal("50")},
|
||||
{"ks3_id": 99999, "amount": Decimal("50")},
|
||||
],
|
||||
)
|
||||
|
||||
assert db_session.query(Payment).count() == payment_count_before
|
||||
assert db_session.query(PaymentAllocation).count() == alloc_count_before
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 20. Счётчик платежей в навигации проекта
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_payment_count_in_project(db_session, project, issued_ks3):
|
||||
assert db_session.query(Payment).filter(Payment.project_id == project.id).count() == 0
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("500"), "RUB", None, [],
|
||||
)
|
||||
assert db_session.query(Payment).filter(Payment.project_id == project.id).count() == 1
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 5),
|
||||
Decimal("300"), "RUB", None, [],
|
||||
)
|
||||
assert db_session.query(Payment).filter(Payment.project_id == project.id).count() == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 21. Проектная сводка оплачено / задолженность
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_project_payment_summary(db_session, project, issued_ks3, issued_ks3_b):
|
||||
summary = ks3_payment_summary(db_session, project.id)
|
||||
assert summary["ks3_count"] == 2
|
||||
assert summary["ks3_total"] == Decimal("1500")
|
||||
assert summary["paid"] == Decimal("0")
|
||||
assert summary["outstanding"] == Decimal("1500")
|
||||
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("2000"), "RUB", None,
|
||||
[
|
||||
{"ks3_id": issued_ks3.id, "amount": Decimal("800")},
|
||||
{"ks3_id": issued_ks3_b.id, "amount": Decimal("200")},
|
||||
],
|
||||
)
|
||||
summary = ks3_payment_summary(db_session, project.id)
|
||||
assert summary["paid"] == Decimal("1000")
|
||||
assert summary["outstanding"] == Decimal("500")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Дополнительно: дублирование КС-3 в одном платеже
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_duplicate_ks3_in_payment(db_session, project, issued_ks3):
|
||||
with pytest.raises(PaymentValidationError, match="несколько раз"):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", None,
|
||||
[
|
||||
{"ks3_id": issued_ks3.id, "amount": Decimal("300")},
|
||||
{"ks3_id": issued_ks3.id, "amount": Decimal("200")},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Дополнительно: валюта обязательна
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_currency_required(db_session, project):
|
||||
with pytest.raises(PaymentValidationError, match="валюту"):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "", None, [],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Дополнительно: project_payments возвращает корректные данные
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_project_payments_list(db_session, project, issued_ks3):
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("1000"), "RUB", "Первый",
|
||||
[{"ks3_id": issued_ks3.id, "amount": Decimal("400")}],
|
||||
)
|
||||
save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 5),
|
||||
Decimal("500"), "RUB", "Второй", [],
|
||||
)
|
||||
rows = project_payments(db_session, project.id)
|
||||
assert len(rows) == 2
|
||||
# Ordered by date desc
|
||||
assert rows[0]["payment"].comment == "Второй"
|
||||
assert rows[1]["payment"].comment == "Первый"
|
||||
assert rows[1]["allocated"] == Decimal("400")
|
||||
assert rows[1]["unallocated"] == Decimal("600")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Дополнительно: удаление несуществующего платежа
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_delete_nonexistent_payment(db_session, project):
|
||||
with pytest.raises(PaymentValidationError, match="не найден"):
|
||||
delete_payment(db_session, project.id, 99999)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Дополнительно: document_number необязателен
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_document_number_optional(db_session, project, issued_ks3):
|
||||
payment = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 1),
|
||||
Decimal("500"), "RUB", None, [],
|
||||
document_number=None,
|
||||
)
|
||||
assert payment.document_number is None
|
||||
|
||||
payment2 = save_payment(
|
||||
db_session, project.id, datetime.date(2024, 4, 2),
|
||||
Decimal("500"), "RUB", None, [],
|
||||
document_number=" PAY-001 ",
|
||||
)
|
||||
assert payment2.document_number == "PAY-001"
|
||||
@@ -0,0 +1,245 @@
|
||||
"""Regression tests for task 013: privacy, project lifecycle, payments, tree."""
|
||||
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.payment import Payment
|
||||
from app.models.ks2 import KS2
|
||||
from app.models.ks3 import KS3
|
||||
from app.routers import projects
|
||||
|
||||
|
||||
def _make_session(tmp_path):
|
||||
db_path = tmp_path / "t013-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 test_privacy_default_hidden_and_toggle(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
app.dependency_overrides[projects.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
resp = client.get("/projects/2")
|
||||
assert resp.status_code == 200
|
||||
assert 'class="bg-light money-hidden"' in resp.text
|
||||
assert 'id="toggleMoney"' in resp.text
|
||||
finally:
|
||||
app.dependency_overrides.pop(projects.get_db, None)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_privacy_mechanism(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
app.dependency_overrides[projects.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
resp = client.get("/projects/2/ks3")
|
||||
assert resp.status_code == 200
|
||||
assert 'id="toggleMoney"' in resp.text
|
||||
assert 'money-hidden' in resp.text
|
||||
finally:
|
||||
app.dependency_overrides.pop(projects.get_db, None)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_project_delete_without_history(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
app.dependency_overrides[projects.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
with Session() as s:
|
||||
p = Project(name="Delete me")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
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:
|
||||
app.dependency_overrides.pop(projects.get_db, None)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_project_archive(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
app.dependency_overrides[projects.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
with Session() as s:
|
||||
p = Project(name="Archive me")
|
||||
s.add(p)
|
||||
s.commit()
|
||||
pid = p.id
|
||||
resp = client.post(f"/projects/{pid}/archive", follow_redirects=False)
|
||||
assert resp.status_code == 303
|
||||
with Session() as s:
|
||||
assert s.get(Project, pid).status == "archived"
|
||||
finally:
|
||||
app.dependency_overrides.pop(projects.get_db, None)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_payment_summary_received_vs_distributed(tmp_path):
|
||||
from app.services.payment_service import ks3_payment_summary
|
||||
engine, Session = _make_session(tmp_path)
|
||||
with Session() as s:
|
||||
from app.models.ks3 import KS3KS2
|
||||
from app.models.ks2 import KS2Item
|
||||
from app.models.boq import WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.payment import PaymentAllocation
|
||||
|
||||
p = Project(name="Pay split test")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
wi = WorkItem(project_id=p.id, name="Test item", quantity=Decimal("10"), unit_price=Decimal("100"))
|
||||
s.add(wi)
|
||||
s.flush()
|
||||
dr = DailyReport(project_id=p.id, report_date=__import__("datetime").date(2026, 1, 1))
|
||||
s.add(dr)
|
||||
s.flush()
|
||||
dri = DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("10"))
|
||||
s.add(dri)
|
||||
s.flush()
|
||||
ks2 = KS2(project_id=p.id, number="K1", date=__import__("datetime").date(2026, 1, 2), status="issued")
|
||||
s.add(ks2)
|
||||
s.flush()
|
||||
ks2i = KS2Item(ks2_id=ks2.id, work_item_id=wi.id, quantity=Decimal("10"),
|
||||
unit_price=Decimal("100"), amount=Decimal("1000"))
|
||||
s.add(ks2i)
|
||||
s.flush()
|
||||
ks3 = KS3(project_id=p.id, number="KS3-1", date=__import__("datetime").date(2026, 1, 3), status="issued")
|
||||
s.add(ks3)
|
||||
s.flush()
|
||||
s.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
|
||||
s.flush()
|
||||
pay = Payment(project_id=p.id, date=__import__("datetime").date(2026, 1, 4),
|
||||
amount=Decimal("600"), currency="RUB", status="active")
|
||||
s.add(pay)
|
||||
s.flush()
|
||||
s.add(PaymentAllocation(payment_id=pay.id, ks3_id=ks3.id, amount=Decimal("600")))
|
||||
s.commit()
|
||||
|
||||
summary = ks3_payment_summary(s, p.id)
|
||||
assert summary["received"] == Decimal("600")
|
||||
assert summary["distributed"] == Decimal("600")
|
||||
assert summary["unallocated"] == Decimal("0")
|
||||
assert summary["outstanding"] == Decimal("400") # 1000 - 600
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_payment_cancelled_excluded_from_aggregates(tmp_path):
|
||||
from app.services.payment_service import ks3_payment_summary
|
||||
engine, Session = _make_session(tmp_path)
|
||||
with Session() as s:
|
||||
from app.models.ks3 import KS3KS2
|
||||
from app.models.ks2 import KS2Item
|
||||
from app.models.boq import WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.payment import PaymentAllocation
|
||||
|
||||
p = Project(name="Cancel pay test")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
wi = WorkItem(project_id=p.id, name="Item", quantity=Decimal("10"), unit_price=Decimal("100"))
|
||||
s.add(wi)
|
||||
s.flush()
|
||||
dr = DailyReport(project_id=p.id, report_date=__import__("datetime").date(2026, 1, 1))
|
||||
s.add(dr)
|
||||
s.flush()
|
||||
dri = DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("10"))
|
||||
s.add(dri)
|
||||
s.flush()
|
||||
ks2 = KS2(project_id=p.id, number="K1", date=__import__("datetime").date(2026, 1, 2), status="issued")
|
||||
s.add(ks2)
|
||||
s.flush()
|
||||
s.add(KS2Item(ks2_id=ks2.id, work_item_id=wi.id, quantity=Decimal("10"),
|
||||
unit_price=Decimal("100"), amount=Decimal("1000")))
|
||||
s.flush()
|
||||
ks3 = KS3(project_id=p.id, number="KS3-1", date=__import__("datetime").date(2026, 1, 3), status="issued")
|
||||
s.add(ks3)
|
||||
s.flush()
|
||||
s.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
|
||||
s.flush()
|
||||
pay = Payment(project_id=p.id, date=__import__("datetime").date(2026, 1, 4),
|
||||
amount=Decimal("500"), currency="RUB", status="cancelled")
|
||||
s.add(pay)
|
||||
s.flush()
|
||||
s.add(PaymentAllocation(payment_id=pay.id, ks3_id=ks3.id, amount=Decimal("500")))
|
||||
s.commit()
|
||||
|
||||
summary = ks3_payment_summary(s, p.id)
|
||||
assert summary["received"] == Decimal("0")
|
||||
assert summary["distributed"] == Decimal("0")
|
||||
assert summary["outstanding"] == Decimal("1000")
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_project_counters_on_detail_page(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
app.dependency_overrides[projects.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
resp = client.get("/projects/2")
|
||||
assert resp.status_code == 200
|
||||
text = resp.text
|
||||
assert "Ведомости" in text
|
||||
assert "Дополнительные соглашения" in text
|
||||
assert "Daily Reports" in text
|
||||
assert "КС-2" in text
|
||||
assert "КС-3" in text
|
||||
assert "Платежи" in text
|
||||
finally:
|
||||
app.dependency_overrides.pop(projects.get_db, None)
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Regression tests for task 014: boq delete/archive, storno UI, row click."""
|
||||
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.models.ks3 import KS3
|
||||
from app.models.payment import Payment
|
||||
from app.routers import projects, boq as boq_router, ks2 as ks2_router, ks3 as ks3_router, payments as payments_router
|
||||
|
||||
|
||||
def _make_session(tmp_path):
|
||||
db_path = tmp_path / "t014-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_all(Session):
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
for dep in (projects.get_db, boq_router.get_db, ks2_router.get_db, ks3_router.get_db, payments_router.get_db):
|
||||
app.dependency_overrides[dep] = override_db
|
||||
|
||||
|
||||
def _clear_overrides():
|
||||
for dep in (projects.get_db, boq_router.get_db, ks2_router.get_db, ks3_router.get_db, payments_router.get_db):
|
||||
app.dependency_overrides.pop(dep, None)
|
||||
|
||||
|
||||
def test_boq_delete_without_history(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
_override_all(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="BOQ del test")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="Test doc")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="Item", quantity=Decimal("10"))
|
||||
s.add(wi)
|
||||
s.commit()
|
||||
pid, did = p.id, doc.id
|
||||
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(f"/boq/{pid}/documents/{did}/delete", follow_redirects=False)
|
||||
assert resp.status_code == 303
|
||||
with Session() as s:
|
||||
assert s.get(BoqDocument, did) is None
|
||||
finally:
|
||||
_clear_overrides()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_boq_delete_blocked_with_history(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
_override_all(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="BOQ hist test")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="Doc with history")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="Item", quantity=Decimal("10"))
|
||||
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("5")))
|
||||
s.commit()
|
||||
pid, did = p.id, doc.id
|
||||
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(f"/boq/{pid}/documents/{did}/delete", follow_redirects=False)
|
||||
assert resp.status_code == 400
|
||||
with Session() as s:
|
||||
assert s.get(BoqDocument, did) is not None
|
||||
finally:
|
||||
_clear_overrides()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_boq_archive_with_history(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
_override_all(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="BOQ arch test")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="Doc to archive")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="Item", quantity=Decimal("10"))
|
||||
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("5")))
|
||||
s.commit()
|
||||
pid, did = p.id, doc.id
|
||||
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(f"/boq/{pid}/documents/{did}/archive", follow_redirects=False)
|
||||
assert resp.status_code == 303
|
||||
with Session() as s:
|
||||
assert s.get(BoqDocument, did).version == "archived"
|
||||
finally:
|
||||
_clear_overrides()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks2_cancel_button_visible_for_issued(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
_override_all(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="KS2 cancel test")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="Doc")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="Item", quantity=Decimal("10"), unit_price=Decimal("100"))
|
||||
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("10")))
|
||||
s.flush()
|
||||
ks2 = KS2(project_id=p.id, number="K1", date=__import__("datetime").date(2026, 1, 2), status="issued")
|
||||
s.add(ks2)
|
||||
s.commit()
|
||||
pid, kid = p.id, ks2.id
|
||||
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks2/{kid}")
|
||||
assert resp.status_code == 200
|
||||
assert "Сторнировать" in resp.text
|
||||
assert "cancel" in resp.text
|
||||
finally:
|
||||
_clear_overrides()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks2_cancelled_shows_status(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
_override_all(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="KS2 cancelled test")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
ks2 = KS2(project_id=p.id, number="K1", date=__import__("datetime").date(2026, 1, 2), status="cancelled")
|
||||
s.add(ks2)
|
||||
s.commit()
|
||||
pid, kid = p.id, ks2.id
|
||||
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks2/{kid}")
|
||||
assert resp.status_code == 200
|
||||
assert "Сторнирован" in resp.text
|
||||
assert "Сторнировать" not in resp.text # button hidden
|
||||
finally:
|
||||
_clear_overrides()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_payment_cancel_button_visible(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
_override_all(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Pay cancel test")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
pay = Payment(project_id=p.id, date=__import__("datetime").date(2026, 1, 1),
|
||||
amount=Decimal("100"), currency="RUB", status="active")
|
||||
s.add(pay)
|
||||
s.commit()
|
||||
pid, payid = p.id, pay.id
|
||||
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/payments/{payid}")
|
||||
assert resp.status_code == 200
|
||||
assert "Сторнировать" in resp.text
|
||||
finally:
|
||||
_clear_overrides()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_clickable_rows_in_lists(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
|
||||
_override_all(Session)
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
for path in ["/projects/2/ks2", "/projects/2/ks3", "/projects/2/payments"]:
|
||||
resp = client.get(path)
|
||||
assert resp.status_code == 200
|
||||
assert "clickable-row" in resp.text
|
||||
assert "data-url" in resp.text
|
||||
finally:
|
||||
_clear_overrides()
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,265 @@
|
||||
"""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 == "Итого:":
|
||||
total_cell = ws.cell(row=cell.row, column=7)
|
||||
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()
|
||||
@@ -1,4 +1,5 @@
|
||||
import shutil
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
@@ -7,10 +8,13 @@ from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import Base, DATABASE_PATH
|
||||
from app.main import app
|
||||
from app.models.boq import WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.work_journal import WorkJournalEntry
|
||||
from app.models.project import Project
|
||||
from app.routers import projects
|
||||
from app.services.project_dashboard import build_project_dashboard
|
||||
from app.services.effective_plan import build_effective_plan
|
||||
|
||||
|
||||
def test_project_work_journal_crud_and_dashboard_warnings(tmp_path):
|
||||
@@ -29,6 +33,23 @@ def test_project_work_journal_crud_and_dashboard_warnings(tmp_path):
|
||||
|
||||
app.dependency_overrides[projects.get_db] = override_db
|
||||
try:
|
||||
# Create over-plan data so dashboard warnings are deterministic
|
||||
with TestingSession() as session:
|
||||
eff = build_effective_plan(session, 2)
|
||||
target_item = None
|
||||
for row in eff["items"]:
|
||||
if row.quantity > 0 and row.item.system_id is not None:
|
||||
target_item = row.item
|
||||
break
|
||||
assert target_item is not None
|
||||
over_qty = Decimal(str(target_item.quantity)) + Decimal("5")
|
||||
dr = DailyReport(project_id=2, report_date=__import__("datetime").date(2026, 9, 1), system_id=target_item.system_id)
|
||||
session.add(dr)
|
||||
session.flush()
|
||||
dri = DailyReportItem(daily_report_id=dr.id, work_item_id=target_item.id, completed_quantity=over_qty)
|
||||
session.add(dri)
|
||||
session.commit()
|
||||
|
||||
with TestClient(app) as client:
|
||||
dashboard = client.get("/projects/2")
|
||||
assert dashboard.status_code == 200
|
||||
|
||||
Reference in New Issue
Block a user