feat: allow deleting draft agreements while keeping approved read-only

This commit is contained in:
Арсентьев Александр
2026-09-28 21:55:29 +03:00
parent 2821208c65
commit 1b5bad0baf
9 changed files with 933 additions and 2 deletions
+67 -1
View File
@@ -1,4 +1,4 @@
from decimal import Decimal, InvalidOperation
from decimal import Decimal, InvalidOperation
from app.models import boq
from app.models.agreement import Agreement, AgreementItem
@@ -239,3 +239,69 @@ def delete_draft_item(db, agreement, line):
).first():
db.delete(document)
db.flush()
def _work_item_is_orphan_for_draft(db, item, agreement) -> bool:
"""True when this WorkItem exists only because of the given draft agreement."""
if item is None:
return False
if item.boq_document_id is not None:
return False
other_lines = db.query(AgreementItem.id).filter(
AgreementItem.work_item_id == item.id,
AgreementItem.agreement_id != agreement.id,
).first()
if other_lines is not None:
return False
from app.models.daily_report import DailyReportItem
from app.models.ks2 import KS2Item, KS2ItemSource
if db.query(DailyReportItem.id).filter(DailyReportItem.work_item_id == item.id).first():
return False
if db.query(KS2Item.id).filter(KS2Item.work_item_id == item.id).first():
return False
return True
def delete_draft_agreement(db, agreement):
"""
Delete a draft Agreement and its items atomically.
Orphan WorkItems created solely for this draft (new_position) are removed.
Base WorkItems are never deleted. Approved agreements are rejected.
"""
try:
if agreement is None:
raise ValueError("Agreement not found")
_require_draft(agreement)
lines = list(agreement.items)
orphan_items = []
for line in lines:
if line.change_type == "new_position" and _work_item_is_orphan_for_draft(
db, line.work_item, agreement
):
orphan_items.append(line.work_item)
for item in orphan_items:
db.delete(item)
db.flush()
document = item.boq_document
if (
document is not None
and document.agreement_id == agreement.id
and not db.query(boq.WorkItem.id)
.filter(boq.WorkItem.boq_document_id == document.id)
.first()
):
db.delete(document)
db.flush()
# ORM cascade on Agreement.items removes AgreementItem rows.
db.delete(agreement)
db.commit()
except ValueError:
db.rollback()
raise
except Exception as exc:
db.rollback()
raise ValueError(f"Failed to delete agreement: {exc}") from exc