261 lines
12 KiB
Python
261 lines
12 KiB
Python
from dataclasses import dataclass
|
|
from decimal import Decimal
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models import boq
|
|
from app.models.agreement import Agreement, AgreementItem
|
|
|
|
ZERO = Decimal("0")
|
|
|
|
|
|
class BaseBoqConfigurationError(ValueError):
|
|
"""A BOQ or agreement scope does not match the project plan."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class EffectiveItem:
|
|
item: boq.WorkItem
|
|
quantity: Decimal
|
|
amount: Decimal
|
|
|
|
|
|
def _decimal(value):
|
|
return Decimal(str(value)) if value is not None else ZERO
|
|
|
|
|
|
def _base_documents(db: Session, project_id: int):
|
|
return db.query(boq.BoqDocument).filter(
|
|
boq.BoqDocument.project_id == project_id,
|
|
boq.BoqDocument.agreement_id.is_(None),
|
|
).order_by(boq.BoqDocument.id).all()
|
|
|
|
|
|
def _validate_agreement_scope(db: Session, agreement: Agreement):
|
|
if agreement.boq_document_id is None:
|
|
return None
|
|
doc = db.query(boq.BoqDocument).filter(
|
|
boq.BoqDocument.id == agreement.boq_document_id,
|
|
boq.BoqDocument.project_id == agreement.project_id,
|
|
boq.BoqDocument.agreement_id.is_(None),
|
|
).first()
|
|
if doc is None:
|
|
raise BaseBoqConfigurationError(
|
|
f"Agreement {agreement.id} references a BOQ outside project {agreement.project_id}"
|
|
)
|
|
return doc
|
|
|
|
|
|
def work_item_scope_document_id(db: Session, item: boq.WorkItem):
|
|
origin = db.query(AgreementItem, Agreement).join(
|
|
Agreement, Agreement.id == AgreementItem.agreement_id
|
|
).filter(
|
|
AgreementItem.work_item_id == item.id,
|
|
AgreementItem.change_type == "new_position",
|
|
Agreement.status == "approved",
|
|
).order_by(AgreementItem.id).first()
|
|
if item.boq_document_id is None:
|
|
return origin[0].source_boq_document_id if origin else None
|
|
source_doc = db.query(boq.BoqDocument).filter(boq.BoqDocument.id == item.boq_document_id).first()
|
|
if source_doc is None or source_doc.project_id != item.project_id:
|
|
raise BaseBoqConfigurationError(f"WorkItem {item.id} has an invalid source BOQ")
|
|
if source_doc.agreement_id is None:
|
|
return source_doc.id
|
|
if origin:
|
|
return origin[0].source_boq_document_id or origin[1].boq_document_id
|
|
return None
|
|
|
|
|
|
def build_effective_plan(db: Session, project_id: int):
|
|
"""Aggregate every base BOQ in a project plus applicable approved agreement deltas."""
|
|
base_docs = _base_documents(db, project_id)
|
|
base_doc_ids = [doc.id for doc in base_docs]
|
|
items = []
|
|
if base_doc_ids:
|
|
items = db.query(boq.WorkItem).filter(
|
|
boq.WorkItem.boq_document_id.in_(base_doc_ids)
|
|
).order_by(boq.WorkItem.id).all()
|
|
|
|
agreements = db.query(Agreement).filter(
|
|
Agreement.project_id == project_id, Agreement.status == "approved"
|
|
).order_by(Agreement.id).all()
|
|
agreement_ids = [agreement.id for agreement in agreements]
|
|
deltas = {}
|
|
new_item_ids = set()
|
|
if agreement_ids:
|
|
lines = db.query(AgreementItem).filter(
|
|
AgreementItem.agreement_id.in_(agreement_ids)
|
|
).order_by(AgreementItem.id).all()
|
|
agreement_by_id = {agreement.id: agreement for agreement in agreements}
|
|
for line in lines:
|
|
agreement = agreement_by_id[line.agreement_id]
|
|
scope_doc = _validate_agreement_scope(db, agreement)
|
|
if line.work_item_id is None:
|
|
raise BaseBoqConfigurationError(f"Approved agreement item {line.id} has no canonical WorkItem")
|
|
item = db.query(boq.WorkItem).filter(
|
|
boq.WorkItem.id == line.work_item_id,
|
|
boq.WorkItem.project_id == project_id,
|
|
).first()
|
|
if item is None:
|
|
raise BaseBoqConfigurationError(f"Agreement item {line.id} references a WorkItem outside its project")
|
|
if scope_doc and line.change_type != "new_position":
|
|
if work_item_scope_document_id(db, item) != scope_doc.id:
|
|
raise BaseBoqConfigurationError(
|
|
f"Agreement item {line.id} targets a WorkItem outside BOQ scope {scope_doc.id}"
|
|
)
|
|
deltas.setdefault(line.work_item_id, [ZERO, ZERO])
|
|
deltas[line.work_item_id][0] += _decimal(line.quantity_delta)
|
|
deltas[line.work_item_id][1] += _decimal(line.amount_delta)
|
|
if line.change_type == "new_position":
|
|
if item.boq_document_id is not None:
|
|
source_doc = db.query(boq.BoqDocument).filter(
|
|
boq.BoqDocument.id == item.boq_document_id,
|
|
boq.BoqDocument.project_id == project_id,
|
|
boq.BoqDocument.agreement_id == agreement.id,
|
|
).first()
|
|
if source_doc is None:
|
|
raise BaseBoqConfigurationError(
|
|
f"New agreement item {line.id} references an invalid source document"
|
|
)
|
|
if line.source_boq_document_id is not None:
|
|
source_boq = db.query(boq.BoqDocument).filter(
|
|
boq.BoqDocument.id == line.source_boq_document_id,
|
|
boq.BoqDocument.project_id == project_id,
|
|
boq.BoqDocument.agreement_id.is_(None),
|
|
).first()
|
|
if source_boq is None:
|
|
raise BaseBoqConfigurationError(
|
|
f"New agreement item {line.id} references a BOQ outside its project"
|
|
)
|
|
if scope_doc and source_boq.id != scope_doc.id:
|
|
raise BaseBoqConfigurationError(
|
|
f"New agreement item {line.id} references a BOQ outside agreement scope"
|
|
)
|
|
new_item_ids.add(line.work_item_id)
|
|
|
|
present = {item.id for item in items}
|
|
if new_item_ids:
|
|
new_items = db.query(boq.WorkItem).filter(
|
|
boq.WorkItem.id.in_(new_item_ids), boq.WorkItem.project_id == project_id
|
|
).order_by(boq.WorkItem.id).all()
|
|
items.extend(item for item in new_items if item.id not in present)
|
|
|
|
rows = []
|
|
for item in items:
|
|
is_agreement_position = item.id in new_item_ids
|
|
base_qty = ZERO if is_agreement_position else _decimal(item.quantity)
|
|
base_amount = ZERO if is_agreement_position else (
|
|
_decimal(item.amount) if item.amount is not None
|
|
else _decimal(item.unit_price) * _decimal(item.quantity)
|
|
)
|
|
qty_delta, amount_delta = deltas.get(item.id, (ZERO, ZERO))
|
|
quantity = base_qty + qty_delta
|
|
amount = base_amount + amount_delta
|
|
if quantity < 0:
|
|
raise ValueError(f"Effective quantity for WorkItem {item.id} is negative")
|
|
rows.append(EffectiveItem(item=item, quantity=quantity, amount=amount))
|
|
|
|
# Kept for the current Dashboard label; no one document is selected when the
|
|
# project contains multiple base BOQs.
|
|
return {
|
|
"base_boq": base_docs[0] if len(base_docs) == 1 else None,
|
|
"base_boq_documents": base_docs,
|
|
"items": rows,
|
|
}
|
|
|
|
|
|
def approve_agreement(db: Session, agreement_id: int):
|
|
"""Approve a draft atomically after validating project/BOQ scope and canonical items."""
|
|
agreement = db.query(Agreement).filter(Agreement.id == agreement_id).with_for_update().first()
|
|
if agreement is None:
|
|
raise ValueError(f"Agreement {agreement_id} not found")
|
|
if agreement.status != "draft":
|
|
raise ValueError("Only draft agreements can be approved")
|
|
try:
|
|
scope_doc = _validate_agreement_scope(db, agreement)
|
|
base_docs = _base_documents(db, agreement.project_id)
|
|
base_doc_ids = [doc.id for doc in base_docs]
|
|
all_project_items = {}
|
|
if base_doc_ids:
|
|
all_project_items = {item.id: item for item in db.query(boq.WorkItem).filter(
|
|
boq.WorkItem.project_id == agreement.project_id,
|
|
boq.WorkItem.boq_document_id.in_(base_doc_ids),
|
|
).all()}
|
|
|
|
approved = db.query(Agreement).filter(
|
|
Agreement.project_id == agreement.project_id, Agreement.status == "approved"
|
|
).all()
|
|
approved_ids = [row.id for row in approved]
|
|
totals = {}
|
|
if approved_ids:
|
|
prior_lines = db.query(AgreementItem).filter(
|
|
AgreementItem.agreement_id.in_(approved_ids)
|
|
).all()
|
|
for line in prior_lines:
|
|
totals.setdefault(line.work_item_id, [ZERO, ZERO])
|
|
totals[line.work_item_id][0] += _decimal(line.quantity_delta)
|
|
totals[line.work_item_id][1] += _decimal(line.amount_delta)
|
|
if line.change_type == "new_position":
|
|
item = db.query(boq.WorkItem).filter(
|
|
boq.WorkItem.id == line.work_item_id,
|
|
boq.WorkItem.project_id == agreement.project_id,
|
|
).first()
|
|
if item:
|
|
all_project_items[item.id] = item
|
|
|
|
lines = db.query(AgreementItem).filter(
|
|
AgreementItem.agreement_id == agreement.id
|
|
).order_by(AgreementItem.id).all()
|
|
if not lines:
|
|
raise ValueError("Agreement has no change lines")
|
|
for line in lines:
|
|
item = db.query(boq.WorkItem).filter(
|
|
boq.WorkItem.id == line.work_item_id,
|
|
boq.WorkItem.project_id == agreement.project_id,
|
|
).first()
|
|
if item is None:
|
|
raise ValueError(f"Agreement item {line.id} does not reference a project WorkItem")
|
|
if line.change_type == "new_position":
|
|
if item.boq_document_id is not None:
|
|
source_doc = db.query(boq.BoqDocument).filter(
|
|
boq.BoqDocument.id == item.boq_document_id,
|
|
boq.BoqDocument.agreement_id == agreement.id,
|
|
boq.BoqDocument.project_id == agreement.project_id,
|
|
).first()
|
|
if source_doc is None:
|
|
raise ValueError(f"New position line {line.id} references an invalid source document")
|
|
if line.source_boq_document_id is not None:
|
|
source_boq = db.query(boq.BoqDocument).filter(
|
|
boq.BoqDocument.id == line.source_boq_document_id,
|
|
boq.BoqDocument.project_id == agreement.project_id,
|
|
boq.BoqDocument.agreement_id.is_(None),
|
|
).first()
|
|
if source_boq is None:
|
|
raise ValueError(f"New position line {line.id} references a BOQ outside its project")
|
|
if agreement.boq_document_id is not None and line.source_boq_document_id not in (None, agreement.boq_document_id):
|
|
raise ValueError(f"New position line {line.id} references a BOQ outside agreement scope")
|
|
if item.quantity not in (None, ZERO) or item.amount not in (None, ZERO):
|
|
raise ValueError(f"New position WorkItem {item.id} must start with zero base quantity and amount")
|
|
all_project_items[item.id] = item
|
|
else:
|
|
canonical = all_project_items.get(item.id)
|
|
if canonical is None:
|
|
raise ValueError(f"Agreement item {line.id} does not reference an existing canonical project item")
|
|
if scope_doc and work_item_scope_document_id(db, item) != scope_doc.id:
|
|
raise ValueError(f"Agreement item {line.id} targets a WorkItem outside its BOQ scope")
|
|
|
|
totals.setdefault(item.id, [ZERO, ZERO])
|
|
totals[item.id][0] += _decimal(line.quantity_delta)
|
|
totals[item.id][1] += _decimal(line.amount_delta)
|
|
initial_qty = ZERO if line.change_type == "new_position" else _decimal(item.quantity)
|
|
if initial_qty + totals[item.id][0] < 0:
|
|
raise ValueError(f"Agreement item {line.id} reduces effective quantity below zero")
|
|
|
|
agreement.status = "approved"
|
|
db.flush()
|
|
db.commit()
|
|
return agreement
|
|
except Exception:
|
|
db.rollback()
|
|
raise
|