feat: add agreement cancellation with conservative KS-2 usage guard
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.models import boq
|
||||
from app.models.agreement import Agreement, AgreementItem
|
||||
from app.services.effective_plan import (
|
||||
@@ -8,6 +10,8 @@ from app.services.effective_plan import (
|
||||
work_item_scope_document_id,
|
||||
)
|
||||
|
||||
ZERO = Decimal("0")
|
||||
|
||||
|
||||
def decimal_value(value, label):
|
||||
try:
|
||||
@@ -305,3 +309,59 @@ def delete_draft_agreement(db, agreement):
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
raise ValueError(f"Failed to delete agreement: {exc}") from exc
|
||||
|
||||
|
||||
def _closed_quantity_for_work_item(db, work_item_id: int) -> Decimal:
|
||||
"""Sum of KS2ItemSource quantities for a work item, excluding cancelled KS-2."""
|
||||
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||
from app.models.daily_report import DailyReportItem
|
||||
|
||||
total = db.query(func.coalesce(func.sum(KS2ItemSource.quantity), ZERO)).join(
|
||||
KS2Item, KS2Item.id == KS2ItemSource.ks2_item_id
|
||||
).join(
|
||||
KS2, KS2.id == KS2Item.ks2_id
|
||||
).filter(
|
||||
KS2Item.work_item_id == work_item_id,
|
||||
KS2.status != "cancelled",
|
||||
).scalar()
|
||||
return Decimal(str(total or 0))
|
||||
|
||||
|
||||
def agreement_cancel_block_reason(db, agreement) -> str | None:
|
||||
"""Return why an approved agreement cannot be cancelled, or None."""
|
||||
if agreement.status == "draft":
|
||||
return "Черновик нельзя отменить. Сначала утвердите ДС."
|
||||
if agreement.status == "cancelled":
|
||||
return "ДС уже отменено."
|
||||
# Conservative V1: block if any affected WorkItem has closed volume in non-cancelled KS-2
|
||||
for line in agreement.items:
|
||||
closed = _closed_quantity_for_work_item(db, line.work_item_id)
|
||||
if closed > ZERO:
|
||||
return "Нельзя отменить ДС: его объём уже использован в закрытых КС-2."
|
||||
return None
|
||||
|
||||
|
||||
def cancel_agreement(db, agreement):
|
||||
"""
|
||||
Cancel an approved agreement atomically.
|
||||
|
||||
The agreement becomes cancelled and drops out of the effective plan.
|
||||
AgreementItems, WorkItems and history are preserved.
|
||||
"""
|
||||
try:
|
||||
reason = agreement_cancel_block_reason(db, agreement)
|
||||
if reason is not None:
|
||||
raise ValueError(reason)
|
||||
# Re-check status inside the transaction
|
||||
if agreement.status != "approved":
|
||||
raise ValueError("Отменить можно только утверждённое ДС")
|
||||
agreement.status = "cancelled"
|
||||
db.commit()
|
||||
db.refresh(agreement)
|
||||
return agreement
|
||||
except ValueError:
|
||||
db.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
raise ValueError(f"Не удалось отменить ДС: {exc}") from exc
|
||||
|
||||
Reference in New Issue
Block a user