feat: enforce KS-2/KS-3 stornation integrity
This commit is contained in:
@@ -220,4 +220,47 @@ def project_ks2_totals(db: Session, project_id: int):
|
||||
for document in documents:
|
||||
rows.append({"document": document, "item_count": len(document.items),
|
||||
"amount": sum((_decimal(line.amount) for line in document.items), ZERO)})
|
||||
return rows
|
||||
return rows
|
||||
|
||||
|
||||
def ks2_cancel_block_reason(db: Session, project_id: int, ks2_id: int) -> str | None:
|
||||
"""Return why KS-2 cannot be cancelled, or None if cancellation is allowed."""
|
||||
from app.models.ks3 import KS3, KS3KS2
|
||||
|
||||
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).first()
|
||||
if document is None:
|
||||
return "КС-2 не найден"
|
||||
if document.status == "cancelled":
|
||||
return "КС-2 уже сторнирован"
|
||||
active_link = db.query(KS3KS2).join(KS3, KS3.id == KS3KS2.ks3_id).filter(
|
||||
KS3KS2.ks2_id == ks2_id,
|
||||
KS3.project_id == project_id,
|
||||
KS3.status == "issued",
|
||||
).first()
|
||||
if active_link is not None:
|
||||
ks3_doc = db.query(KS3).filter(KS3.id == active_link.ks3_id).first()
|
||||
number = ks3_doc.number if ks3_doc else active_link.ks3_id
|
||||
return f"КС-2 включён в действующий КС-3 №{number}. Сначала сторнируйте КС-3."
|
||||
return None
|
||||
|
||||
|
||||
def cancel_ks2(db: Session, project_id: int, ks2_id: int):
|
||||
"""Cancel a KS-2 atomically. Blocked when linked to an issued KS-3."""
|
||||
try:
|
||||
reason = ks2_cancel_block_reason(db, project_id, ks2_id)
|
||||
if reason is not None:
|
||||
raise KS2ValidationError(reason)
|
||||
document = db.query(KS2).filter(
|
||||
KS2.id == ks2_id, KS2.project_id == project_id
|
||||
).with_for_update().first()
|
||||
if document is None:
|
||||
raise KS2ValidationError("КС-2 не найден")
|
||||
if document.status == "cancelled":
|
||||
raise KS2ValidationError("КС-2 уже сторнирован")
|
||||
document.status = "cancelled"
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
return document
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
Reference in New Issue
Block a user