feat: add agreements foundation

This commit is contained in:
Александр Арсентьев
2026-09-25 18:41:08 +03:00
parent 2376778828
commit d0b5745f8f
14 changed files with 697 additions and 61 deletions
+225
View File
@@ -0,0 +1,225 @@
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 _item_scope_document_id(db: Session, item: boq.WorkItem):
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 no valid source BOQ")
if source_doc.agreement_id is None:
return source_doc.id
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",
).first()
return origin[1].boq_document_id if origin else 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 _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.agreement_id != agreement.id:
raise BaseBoqConfigurationError(
f"New agreement item {line.id} is not backed by its agreement source document"
)
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":
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} must reference an item from its agreement document")
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 _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
+19 -32
View File
@@ -2,6 +2,7 @@ from decimal import Decimal, ROUND_HALF_UP
from app.models import boq
from app.models.daily_report import DailyReport, DailyReportItem
from app.services.effective_plan import build_effective_plan
ZERO = Decimal("0.00")
@@ -14,14 +15,6 @@ def _round_money(value):
return value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def _item_plan_cost(item):
if item.amount is not None:
return _money(item.amount)
if item.unit_price is not None and item.quantity is not None:
return _money(item.unit_price) * _money(item.quantity)
return ZERO
def _performed_cost(item, quantity):
if item.unit_price is None:
return ZERO
@@ -29,22 +22,15 @@ def _performed_cost(item, quantity):
def build_project_dashboard(db, project_obj):
"""Build project dashboard aggregates from persisted BOQ and daily report rows."""
current_boq = db.query(boq.BoqDocument).filter(
boq.BoqDocument.project_id == project_obj.id
).order_by(boq.BoqDocument.created_at.desc(), boq.BoqDocument.id.desc()).first()
"""Build plan from base BOQ + approved changes; keep daily-report facts canonical."""
effective = build_effective_plan(db, project_obj.id)
planned_items = effective["items"]
items = [row.item for row in planned_items]
item_by_id = {item.id: item for item in items}
systems = db.query(boq.System).filter(
boq.System.project_id == project_obj.id
).order_by(boq.System.sort_order, boq.System.id).all()
items = []
if current_boq:
items = db.query(boq.WorkItem).filter(
boq.WorkItem.boq_document_id == current_boq.id
).order_by(boq.WorkItem.id).all()
item_by_id = {item.id: item for item in items}
completed_by_item = {}
if item_by_id:
lines = db.query(DailyReportItem, DailyReport).join(
@@ -58,7 +44,7 @@ def build_project_dashboard(db, project_obj):
completed_by_item.get(line.work_item_id, ZERO) + _money(line.completed_quantity)
)
planned_total = _round_money(sum((_item_plan_cost(item) for item in items), ZERO))
planned_total = _round_money(sum((row.amount for row in planned_items), ZERO))
performed_total = _round_money(sum((
_performed_cost(item, completed_by_item.get(item.id, ZERO)) for item in items
), ZERO))
@@ -67,10 +53,10 @@ def build_project_dashboard(db, project_obj):
system_progress = []
for system in systems:
system_items = [item for item in items if item.system_id == system.id]
plan = sum((_item_plan_cost(item) for item in system_items), ZERO)
actual = sum((_performed_cost(item, completed_by_item.get(item.id, ZERO))
for item in system_items), ZERO)
system_rows = [row for row in planned_items if row.item.system_id == system.id]
plan = sum((row.amount for row in system_rows), ZERO)
actual = sum((_performed_cost(row.item, completed_by_item.get(row.item.id, ZERO))
for row in system_rows), ZERO)
percent = actual / plan * Decimal("100") if plan else ZERO
system_progress.append({
"system": system, "planned_cost": plan, "performed_cost": actual,
@@ -78,17 +64,17 @@ def build_project_dashboard(db, project_obj):
})
over_plan_items = []
for item in items:
for row in planned_items:
item = row.item
actual_quantity = completed_by_item.get(item.id, ZERO)
if item.quantity is not None and actual_quantity > _money(item.quantity):
if actual_quantity > row.quantity:
over_plan_items.append({
"item": item,
"system": item.system,
"planned_quantity": _money(item.quantity),
"planned_quantity": row.quantity,
"actual_quantity": actual_quantity,
"excess_quantity": actual_quantity - _money(item.quantity),
"excess_quantity": actual_quantity - row.quantity,
})
warning_count = len(over_plan_items)
recent_reports = db.query(DailyReport).filter(
DailyReport.project_id == project_obj.id
@@ -110,13 +96,14 @@ def build_project_dashboard(db, project_obj):
})
return {
"current_boq": current_boq,
"current_boq": effective["base_boq"],
"base_boq_documents": effective["base_boq_documents"],
"planned_cost": planned_total,
"performed_cost": performed_total,
"remaining_cost": remaining_total,
"completion_percent": completion_percent,
"system_progress": system_progress,
"recent_reports": recent_report_rows,
"over_plan_count": warning_count,
"over_plan_count": len(over_plan_items),
"over_plan_items": over_plan_items,
}