"""DOC-C12: payments finalization — end-to-end chain and storno semantics. Chain: КС-2 -> КС-3 -> Платёж -> allocation -> Получено / Распределено / Не распределено / Долг. One payment may cover several KS-3; storno keeps historical allocations while excluding the payment from active aggregates. """ import datetime import os from decimal import Decimal import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # issue_ks2/issue_ks3 persist DocumentArtifact rows; the model is imported # lazily inside the services, so pull it in before metadata.create_all. os.environ.setdefault("DOCUMENT_STORAGE_ROOT", "_c12_test_storage") from app.database.database import Base from app.models import ( # noqa: F401 agreement, boq, daily_report, document_artifact, ks2, ks3, payment, project, work_journal, ) from app.models.daily_report import DailyReport, DailyReportItem 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 issue_ks2, save_draft as save_ks2_draft 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, cancel_payment, ks3_payment_summary, project_payments, save_payment, ) ZERO = Decimal("0") @pytest.fixture def db_session(): engine = create_engine("sqlite:///:memory:") Base.metadata.create_all(engine) session = sessionmaker(bind=engine)() yield session session.close() def _make_ks3(db, project_id, number, wi_amount, wi_name): """BOQ -> DailyReport -> issued KS-2 -> issued KS-3 with one work item.""" boq = BoqDocument(project_id=project_id, name=f"BOQ-{number}") db.add(boq) db.flush() wi = WorkItem( project_id=project_id, boq_document_id=boq.id, name=wi_name, unit="шт", quantity=Decimal("1"), unit_price=wi_amount, amount=wi_amount, ) db.add(wi) db.flush() dr = DailyReport(project_id=project_id, report_date=datetime.date(2026, 2, 1)) db.add(dr) db.flush() db.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("1"))) db.flush() ks2 = issue_ks2(db, project_id, save_ks2_draft( db, project_id, f"K2-{number}", datetime.date(2026, 3, 1), None, [(wi.id, Decimal("1"))], reporting_period_from=datetime.date(2026, 2, 1), reporting_period_to=datetime.date(2026, 2, 28), ).id) ks3 = issue_ks3(db, project_id, save_ks3_draft( db, project_id, f"K3-{number}", datetime.date(2026, 4, 1), None, [ks2.id], reporting_period_from=datetime.date(2026, 2, 1), reporting_period_to=datetime.date(2026, 3, 31), ).id) return ks3 @pytest.fixture def chain(db_session): """Two KS-3 documents: 600 000 and 400 000.""" project = Project(name="DOC-C12", customer_name="C", contractor_name="K") db_session.add(project) db_session.commit() db_session.refresh(project) ks3_1 = _make_ks3(db_session, project.id, "1", Decimal("600000"), "W1") ks3_2 = _make_ks3(db_session, project.id, "2", Decimal("400000"), "W2") db_session.commit() return project, ks3_1, ks3_2 # --------------------------------------------------------------------------- # 1. создание платежа # --------------------------------------------------------------------------- def test_create_payment(db_session, chain): project, _, _ = chain p = save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", "по договору", [], document_number="P1") assert p.id is not None assert p.amount == Decimal("1000000") assert p.status == "active" assert p.document_number == "P1" # --------------------------------------------------------------------------- # 2-3. allocation на один и несколько КС-3 # --------------------------------------------------------------------------- def test_allocate_to_single_ks3(db_session, chain): project, ks3_1, _ = chain save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("600000"), "RUB", None, [{"ks3_id": ks3_1.id, "amount": Decimal("600000")}]) avail = available_ks3_for_payment(db_session, project.id) info = next(x for x in avail if x["id"] == ks3_1.id) assert info["paid"] == Decimal("600000") assert info["outstanding"] == ZERO def test_one_payment_across_multiple_ks3(db_session, chain): project, ks3_1, ks3_2 = chain save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("600000")}, {"ks3_id": ks3_2.id, "amount": Decimal("300000")}, ]) summary = ks3_payment_summary(db_session, project.id) assert summary["received"] == Decimal("1000000") assert summary["distributed"] == Decimal("900000") assert summary["unallocated"] == Decimal("100000") # --------------------------------------------------------------------------- # 4. частично распределённый платёж # --------------------------------------------------------------------------- def test_partially_allocated_payment(db_session, chain): project, ks3_1, ks3_2 = chain # 600 000 to KS-3 №1 + 100 000 to KS-3 №2 = 700 000 of a 1 000 000 payment save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("600000")}, {"ks3_id": ks3_2.id, "amount": Decimal("100000")}, ]) summary = ks3_payment_summary(db_session, project.id) assert summary["received"] == Decimal("1000000") assert summary["distributed"] == Decimal("700000") assert summary["unallocated"] == Decimal("300000") # --------------------------------------------------------------------------- # 5-6. серверная защита # --------------------------------------------------------------------------- def test_cannot_allocate_more_than_payment(db_session, chain): project, ks3_1, _ = chain with pytest.raises(PaymentValidationError, match="превышает"): save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("100"), "RUB", None, [{"ks3_id": ks3_1.id, "amount": Decimal("200")}]) def test_cannot_allocate_to_cancelled_ks3(db_session, chain): project, ks3_1, _ = chain from app.services.ks3_service import cancel_ks3 cancel_ks3(db_session, project.id, ks3_1.id) db_session.commit() with pytest.raises(PaymentValidationError, match="не проведён"): save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("100"), "RUB", None, [{"ks3_id": ks3_1.id, "amount": Decimal("50")}]) def test_negative_allocation_rejected(db_session, chain): project, ks3_1, _ = chain with pytest.raises(PaymentValidationError, match="больше нуля"): save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("100"), "RUB", None, [{"ks3_id": ks3_1.id, "amount": Decimal("-5")}]) def test_non_finite_amount_rejected(db_session, chain): """DOC-C12: NaN/Infinity must be a validation error, not a 500 / bad row.""" project, ks3_1, _ = chain for bad in (Decimal("NaN"), Decimal("Infinity")): with pytest.raises(PaymentValidationError): save_payment(db_session, project.id, datetime.date(2026, 5, 1), bad, "RUB", None, []) def test_non_finite_allocation_rejected(db_session, chain): project, ks3_1, _ = chain with pytest.raises(PaymentValidationError): save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("100"), "RUB", None, [{"ks3_id": ks3_1.id, "amount": Decimal("NaN")}]) # --------------------------------------------------------------------------- # 7-9. сторно платежа # --------------------------------------------------------------------------- def test_storno_excludes_from_active_aggregates(db_session, chain): project, ks3_1, ks3_2 = chain before = ks3_payment_summary(db_session, project.id) pay = save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("600000")}, {"ks3_id": ks3_2.id, "amount": Decimal("300000")}, ]) assert ks3_payment_summary(db_session, project.id)["received"] == Decimal("1000000") cancel_payment(db_session, project.id, pay.id) db_session.commit() after = ks3_payment_summary(db_session, project.id) assert after["received"] == ZERO assert after["distributed"] == ZERO assert after["unallocated"] == ZERO assert after["outstanding"] == before["outstanding"] def test_storno_keeps_historical_allocations(db_session, chain): project, ks3_1, ks3_2 = chain pay = save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("600000")}, {"ks3_id": ks3_2.id, "amount": Decimal("300000")}, ]) cancel_payment(db_session, project.id, pay.id) db_session.commit() db_session.refresh(pay) assert pay.status == "cancelled" amounts = sorted((a.ks3_id, a.amount) for a in pay.allocations) assert amounts == sorted([ (ks3_1.id, Decimal("600000")), (ks3_2.id, Decimal("300000")), ]) # still visible in history rows = project_payments(db_session, project.id) assert len(rows) == 1 assert rows[0]["payment"].status == "cancelled" def test_storno_restores_ks3_outstanding(db_session, chain): project, ks3_1, _ = chain save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("600000"), "RUB", None, [{"ks3_id": ks3_1.id, "amount": Decimal("600000")}]) avail = available_ks3_for_payment(db_session, project.id) assert next(x for x in avail if x["id"] == ks3_1.id)["outstanding"] == ZERO pay = project_payments(db_session, project.id)[0]["payment"] cancel_payment(db_session, project.id, pay.id) db_session.commit() avail = available_ks3_for_payment(db_session, project.id) info = next(x for x in avail if x["id"] == ks3_1.id) assert info["outstanding"] == Decimal("600000") assert info["paid"] == ZERO # --------------------------------------------------------------------------- # 10. Decimal-арифметика # --------------------------------------------------------------------------- def test_decimal_arithmetic_exact(db_session, chain): project, ks3_1, ks3_2 = chain save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("0.10"), "RUB", None, [{"ks3_id": ks3_1.id, "amount": Decimal("0.10")}]) summary = ks3_payment_summary(db_session, project.id) assert summary["received"] == Decimal("0.10") assert summary["distributed"] == Decimal("0.10") assert summary["unallocated"] == ZERO # no float artifacts: 0.1 + 0.2 style save_payment(db_session, project.id, datetime.date(2026, 5, 2), Decimal("0.30"), "RUB", None, [{"ks3_id": ks3_2.id, "amount": Decimal("0.20")}]) summary = ks3_payment_summary(db_session, project.id) assert summary["received"] == Decimal("0.40") assert summary["distributed"] == Decimal("0.30") assert summary["unallocated"] == Decimal("0.10") # --------------------------------------------------------------------------- # 11. сквозной КС-2 -> КС-3 -> Платёж (сценарий из задачи) # --------------------------------------------------------------------------- def test_full_chain_scenario(db_session, chain): project, ks3_1, ks3_2 = chain # totals of the two KS-3 documents avail = available_ks3_for_payment(db_session, project.id) totals = {x["id"]: x["total"] for x in avail} assert totals[ks3_1.id] == Decimal("600000") assert totals[ks3_2.id] == Decimal("400000") pay = save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("600000")}, {"ks3_id": ks3_2.id, "amount": Decimal("300000")}, ], document_number="P1") summary = ks3_payment_summary(db_session, project.id) assert summary["ks3_total"] == Decimal("1000000") assert summary["received"] == Decimal("1000000") assert summary["distributed"] == Decimal("900000") assert summary["unallocated"] == Decimal("100000") assert summary["outstanding"] == Decimal("100000") # top up the same payment so it becomes fully allocated # (edit keeps the payment amount and adds the missing 100 000 to KS-3 №2) save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("600000")}, {"ks3_id": ks3_2.id, "amount": Decimal("400000")}, ], payment_id=pay.id) summary = ks3_payment_summary(db_session, project.id) assert summary["received"] == Decimal("1000000") assert summary["distributed"] == Decimal("1000000") assert summary["unallocated"] == ZERO assert summary["outstanding"] == ZERO def test_edit_allocation_same_ks3_updates_in_place(db_session, chain): """DOC-C12 bug: editing an allocation to the same KS-3 used to crash on uq_payment_ks3 (clear() deferred the DELETE past the new INSERT).""" project, ks3_1, ks3_2 = chain pay = save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("300000")}, {"ks3_id": ks3_2.id, "amount": Decimal("200000")}, ]) pay = save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("400000")}, {"ks3_id": ks3_2.id, "amount": Decimal("200000")}, ], payment_id=pay.id) db_session.commit() amounts = {a.ks3_id: a.amount for a in pay.allocations} assert amounts == {ks3_1.id: Decimal("400000"), ks3_2.id: Decimal("200000")} assert len(pay.allocations) == 2 def test_edit_allocation_drops_removed_ks3(db_session, chain): project, ks3_1, ks3_2 = chain pay = save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("300000")}, {"ks3_id": ks3_2.id, "amount": Decimal("200000")}, ]) pay = save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [{"ks3_id": ks3_1.id, "amount": Decimal("300000")}], payment_id=pay.id) db_session.commit() assert [a.ks3_id for a in pay.allocations] == [ks3_1.id] def test_fully_allocated_payment(db_session, chain): project, ks3_1, ks3_2 = chain save_payment(db_session, project.id, datetime.date(2026, 5, 1), Decimal("1000000"), "RUB", None, [ {"ks3_id": ks3_1.id, "amount": Decimal("600000")}, {"ks3_id": ks3_2.id, "amount": Decimal("400000")}, ]) summary = ks3_payment_summary(db_session, project.id) assert summary["received"] == Decimal("1000000") assert summary["distributed"] == Decimal("1000000") assert summary["unallocated"] == ZERO assert summary["outstanding"] == ZERO