feat: enforce KS-2/KS-3 stornation integrity

This commit is contained in:
Арсентьев Александр
2026-09-27 18:12:19 +03:00
parent 80b7d4732e
commit 9992a435b2
15 changed files with 947 additions and 20 deletions
+47 -1
View File
@@ -1,6 +1,7 @@
from datetime import date
from decimal import Decimal, InvalidOperation
from sqlalchemy import func
from sqlalchemy.orm import Session, joinedload
from app.models.ks2 import KS2, KS2Item
@@ -176,4 +177,49 @@ def project_ks3_totals(db: Session, project_id: int):
"ks2_count": len(doc.links),
"amount": total,
})
return rows
return rows
def ks3_cancel_block_reason(db: Session, project_id: int, ks3_id: int) -> str | None:
"""Return why KS-3 cannot be cancelled, or None if cancellation is allowed."""
from decimal import Decimal as D
from app.models.payment import Payment, PaymentAllocation
document = db.query(KS3).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
if document is None:
return "КС-3 не найден"
if document.status == "cancelled":
return "КС-3 уже сторнирован"
paid = db.query(func.coalesce(func.sum(PaymentAllocation.amount), ZERO)).join(
Payment, Payment.id == PaymentAllocation.payment_id
).filter(
PaymentAllocation.ks3_id == ks3_id,
Payment.status != "cancelled",
PaymentAllocation.amount > 0,
).scalar()
if D(str(paid or 0)) > 0:
return "На КС-3 распределены платежи. Сначала отмените распределения платежей."
return None
def cancel_ks3(db: Session, project_id: int, ks3_id: int):
"""Cancel a KS-3 atomically. Blocked when payment allocations exist."""
try:
reason = ks3_cancel_block_reason(db, project_id, ks3_id)
if reason is not None:
raise KS3ValidationError(reason)
document = db.query(KS3).filter(
KS3.id == ks3_id, KS3.project_id == project_id
).with_for_update().first()
if document is None:
raise KS3ValidationError("КС-3 не найден")
if document.status == "cancelled":
raise KS3ValidationError("КС-3 уже сторнирован")
document.status = "cancelled"
db.commit()
db.refresh(document)
return document
except Exception:
db.rollback()
raise