feat: add agreement workflow and project-scoped work items
This commit is contained in:
@@ -0,0 +1,392 @@
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database.database import SessionLocal
|
||||
from app.models import boq, project
|
||||
from app.models.agreement import Agreement, AgreementItem
|
||||
from app.services.agreement_items import (
|
||||
add_existing_item,
|
||||
add_new_item,
|
||||
available_work_items,
|
||||
delete_draft_item,
|
||||
update_draft_item,
|
||||
)
|
||||
from app.services.effective_plan import (
|
||||
BaseBoqConfigurationError,
|
||||
approve_agreement,
|
||||
build_effective_plan,
|
||||
work_item_scope_document_id,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def _project(db, project_id):
|
||||
result = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||
if result is None:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return result
|
||||
|
||||
|
||||
def _agreement(db, project_id, agreement_id):
|
||||
result = db.query(Agreement).filter(
|
||||
Agreement.id == agreement_id, Agreement.project_id == project_id
|
||||
).first()
|
||||
if result is None:
|
||||
raise HTTPException(status_code=404, detail="Agreement not found")
|
||||
return result
|
||||
|
||||
|
||||
def _base_docs(db, project_id):
|
||||
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 _scope_label(agreement, docs):
|
||||
if agreement.boq_document_id is None:
|
||||
return "Весь проект"
|
||||
doc = next((doc for doc in docs if doc.id == agreement.boq_document_id), None)
|
||||
return doc.name if doc else f"Ведомость #{agreement.boq_document_id}"
|
||||
|
||||
|
||||
def _parse_scope(db, project_id, scope):
|
||||
if scope == "project":
|
||||
return None
|
||||
if not scope.startswith("boq:"):
|
||||
raise ValueError("Select project scope or a project BOQ")
|
||||
try:
|
||||
document_id = int(scope.split(":", 1)[1])
|
||||
except ValueError as exc:
|
||||
raise ValueError("Invalid BOQ scope") from exc
|
||||
document = db.query(boq.BoqDocument).filter(
|
||||
boq.BoqDocument.id == document_id,
|
||||
boq.BoqDocument.project_id == project_id,
|
||||
boq.BoqDocument.agreement_id.is_(None),
|
||||
).first()
|
||||
if document is None:
|
||||
raise ValueError("Selected BOQ does not belong to this project")
|
||||
return document.id
|
||||
|
||||
|
||||
def _detail_response(request, db, project_obj, agreement, error=None, status_code=200):
|
||||
docs = _base_docs(db, project_obj.id)
|
||||
plan = build_effective_plan(db, project_obj.id)
|
||||
plan_by_id = {row.item.id: row for row in plan["items"]}
|
||||
lines = db.query(AgreementItem).filter(
|
||||
AgreementItem.agreement_id == agreement.id
|
||||
).order_by(AgreementItem.id).all()
|
||||
line_rows = []
|
||||
for line in lines:
|
||||
item = line.work_item
|
||||
if line.change_type == "new_position":
|
||||
before = 0
|
||||
else:
|
||||
effective = plan_by_id.get(item.id)
|
||||
before = effective.quantity if effective else item.quantity
|
||||
line_rows.append({
|
||||
"line": line,
|
||||
"item": item,
|
||||
"before_quantity": before or 0,
|
||||
"after_quantity": (before or 0) + line.quantity_delta,
|
||||
"amount_delta": line.amount_delta,
|
||||
})
|
||||
selectable = []
|
||||
systems = []
|
||||
sections = []
|
||||
if agreement.status == "draft":
|
||||
selectable = available_work_items(db, agreement)
|
||||
systems = db.query(boq.System).filter(
|
||||
boq.System.project_id == project_obj.id
|
||||
).order_by(boq.System.sort_order, boq.System.id).all()
|
||||
system_ids = [row.id for row in systems]
|
||||
if system_ids:
|
||||
sections = db.query(boq.Section).filter(
|
||||
boq.Section.system_id.in_(system_ids)
|
||||
).order_by(boq.Section.system_id, boq.Section.sort_order, boq.Section.id).all()
|
||||
return request.app.templates.TemplateResponse("agreements/detail.html", {
|
||||
"request": request,
|
||||
"project": project_obj,
|
||||
"agreement": agreement,
|
||||
"scope_label": _scope_label(agreement, docs),
|
||||
"boq_documents": docs,
|
||||
"line_rows": line_rows,
|
||||
"selectable_items": selectable,
|
||||
"systems": systems,
|
||||
"sections": sections,
|
||||
"error": error,
|
||||
"change_amount": sum((line.amount_delta for line in lines), start=0),
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
@router.get("/{project_id}/agreements")
|
||||
async def list_agreements(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
project_obj = _project(db, project_id)
|
||||
docs = _base_docs(db, project_id)
|
||||
agreements = db.query(Agreement).filter(
|
||||
Agreement.project_id == project_id
|
||||
).order_by(Agreement.date.desc(), Agreement.id.desc()).all()
|
||||
rows = [{
|
||||
"agreement": item,
|
||||
"scope_label": _scope_label(item, docs),
|
||||
"item_count": db.query(AgreementItem.id).filter(AgreementItem.agreement_id == item.id).count(),
|
||||
"amount_delta": sum((line.amount_delta for line in item.items), start=0),
|
||||
} for item in agreements]
|
||||
return request.app.templates.TemplateResponse("agreements/list.html", {
|
||||
"request": request, "project": project_obj, "rows": rows,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{project_id}/agreements/new")
|
||||
async def new_agreement(request: Request, project_id: int, db: Session = Depends(get_db)):
|
||||
return request.app.templates.TemplateResponse("agreements/new.html", {
|
||||
"request": request, "project": _project(db, project_id),
|
||||
"boq_documents": _base_docs(db, project_id), "error": None,
|
||||
"today": date.today().isoformat(),
|
||||
})
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements")
|
||||
async def create_agreement(request: Request, project_id: int,
|
||||
number: str = Form(...), agreement_date: str = Form(...),
|
||||
title: str = Form(...), description: str = Form(""),
|
||||
scope: str = Form(...), db: Session = Depends(get_db)):
|
||||
project_obj = _project(db, project_id)
|
||||
try:
|
||||
parsed_date = date.fromisoformat(agreement_date)
|
||||
number, title = number.strip(), title.strip()
|
||||
if not number or not title:
|
||||
raise ValueError("Number and title are required")
|
||||
scope_document_id = _parse_scope(db, project_id, scope)
|
||||
item = Agreement(project_id=project_id, boq_document_id=scope_document_id,
|
||||
number=number, date=parsed_date, title=title,
|
||||
description=description.strip() or None, status="draft")
|
||||
db.add(item)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
return RedirectResponse(f"/projects/{project_id}/agreements/{item.id}", status_code=303)
|
||||
except ValueError as exc:
|
||||
db.rollback()
|
||||
return request.app.templates.TemplateResponse("agreements/new.html", {
|
||||
"request": request, "project": project_obj,
|
||||
"boq_documents": _base_docs(db, project_id), "error": str(exc),
|
||||
"today": date.today().isoformat(),
|
||||
}, status_code=400)
|
||||
except IntegrityError as exc:
|
||||
db.rollback()
|
||||
return request.app.templates.TemplateResponse("agreements/new.html", {
|
||||
"request": request, "project": project_obj,
|
||||
"boq_documents": _base_docs(db, project_id), "error": "Agreement number already exists",
|
||||
"today": date.today().isoformat(),
|
||||
}, status_code=409)
|
||||
|
||||
|
||||
@router.get("/{project_id}/agreements/{agreement_id}")
|
||||
async def view_agreement(request: Request, project_id: int, agreement_id: int,
|
||||
db: Session = Depends(get_db)):
|
||||
return _detail_response(request, db, _project(db, project_id),
|
||||
_agreement(db, project_id, agreement_id))
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements/{agreement_id}/update")
|
||||
async def update_agreement(project_id: int, agreement_id: int,
|
||||
number: str = Form(...), agreement_date: str = Form(...),
|
||||
title: str = Form(...), description: str = Form(""),
|
||||
scope: str = Form(...), request: Request = None,
|
||||
db: Session = Depends(get_db)):
|
||||
project_obj = _project(db, project_id)
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
if agreement.status != "draft":
|
||||
raise HTTPException(status_code=409, detail="Approved agreements are read-only")
|
||||
try:
|
||||
parsed_date = date.fromisoformat(agreement_date)
|
||||
scope_document_id = _parse_scope(db, project_id, scope)
|
||||
number, title = number.strip(), title.strip()
|
||||
if not number or not title:
|
||||
raise ValueError("Number and title are required")
|
||||
for line in agreement.items:
|
||||
if line.change_type != "new_position" and scope_document_id is not None:
|
||||
if work_item_scope_document_id(db, line.work_item) != scope_document_id:
|
||||
raise ValueError("Remove positions outside the selected BOQ before changing scope")
|
||||
agreement.number = number
|
||||
agreement.date = parsed_date
|
||||
agreement.title = title
|
||||
agreement.description = description.strip() or None
|
||||
agreement.boq_document_id = scope_document_id
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303)
|
||||
except ValueError as exc:
|
||||
db.rollback()
|
||||
return _detail_response(request, db, project_obj, agreement, str(exc), 400)
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
return _detail_response(request, db, project_obj, agreement, "Agreement number already exists", 409)
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements/{agreement_id}/items/existing")
|
||||
async def add_existing(project_id: int, agreement_id: int,
|
||||
work_item_id: int = Form(...), quantity_delta: str = Form(...),
|
||||
request: Request = None, db: Session = Depends(get_db)):
|
||||
project_obj = _project(db, project_id)
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
try:
|
||||
add_existing_item(db, agreement, work_item_id, quantity_delta)
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303)
|
||||
except (ValueError, BaseBoqConfigurationError) as exc:
|
||||
db.rollback()
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
return _detail_response(request, db, project_obj, agreement, str(exc), 400)
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements/{agreement_id}/systems")
|
||||
async def create_agreement_system(project_id: int, agreement_id: int,
|
||||
name: str = Form(...), db: Session = Depends(get_db)):
|
||||
_project(db, project_id)
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
if agreement.status != "draft":
|
||||
raise HTTPException(status_code=409, detail="Approved agreements are read-only")
|
||||
name = name.strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="System name is required")
|
||||
duplicate = db.query(boq.System).filter(
|
||||
boq.System.project_id == project_id,
|
||||
func.lower(boq.System.name) == name.lower(),
|
||||
).first()
|
||||
if duplicate:
|
||||
raise HTTPException(status_code=409, detail="A system with this name already exists")
|
||||
sort_order = db.query(func.max(boq.System.sort_order)).filter(
|
||||
boq.System.project_id == project_id
|
||||
).scalar() or 0
|
||||
system = boq.System(project_id=project_id, name=name, sort_order=sort_order + 1)
|
||||
db.add(system)
|
||||
db.commit()
|
||||
db.refresh(system)
|
||||
return JSONResponse({"id": system.id, "name": system.name})
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements/{agreement_id}/sections")
|
||||
async def create_agreement_section(project_id: int, agreement_id: int,
|
||||
system_id: int = Form(...), name: str = Form(...),
|
||||
db: Session = Depends(get_db)):
|
||||
_project(db, project_id)
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
if agreement.status != "draft":
|
||||
raise HTTPException(status_code=409, detail="Approved agreements are read-only")
|
||||
system = db.query(boq.System).filter(
|
||||
boq.System.id == system_id, boq.System.project_id == project_id
|
||||
).first()
|
||||
if system is None:
|
||||
raise HTTPException(status_code=400, detail="System does not belong to this project")
|
||||
name = name.strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="Section name is required")
|
||||
duplicate = db.query(boq.Section).filter(
|
||||
boq.Section.system_id == system_id,
|
||||
func.lower(boq.Section.name) == name.lower(),
|
||||
).first()
|
||||
if duplicate:
|
||||
raise HTTPException(status_code=409, detail="A section with this name already exists")
|
||||
sort_order = db.query(func.max(boq.Section.sort_order)).filter(
|
||||
boq.Section.system_id == system_id
|
||||
).scalar() or 0
|
||||
section = boq.Section(system_id=system_id, name=name, sort_order=sort_order + 1)
|
||||
db.add(section)
|
||||
db.commit()
|
||||
db.refresh(section)
|
||||
return JSONResponse({"id": section.id, "name": section.name, "system_id": system_id})
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements/{agreement_id}/items/new")
|
||||
async def add_new(project_id: int, agreement_id: int,
|
||||
name: str = Form(...), model: str = Form(""), manufacturer: str = Form(""),
|
||||
unit: str = Form(""), quantity_delta: str = Form(...), unit_price: str = Form(...),
|
||||
system_id: int | None = Form(None), section_id: int | None = Form(None),
|
||||
source_boq_document_id: int | None = Form(None),
|
||||
request: Request = None, db: Session = Depends(get_db)):
|
||||
project_obj = _project(db, project_id)
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
try:
|
||||
add_new_item(db, agreement, name=name, model=model, manufacturer=manufacturer,
|
||||
unit=unit, quantity_delta=quantity_delta, unit_price=unit_price,
|
||||
system_id=system_id, section_id=section_id,
|
||||
source_boq_document_id=source_boq_document_id)
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303)
|
||||
except (ValueError, BaseBoqConfigurationError) as exc:
|
||||
db.rollback()
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
return _detail_response(request, db, project_obj, agreement, str(exc), 400)
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements/{agreement_id}/items/{line_id}/edit")
|
||||
async def edit_item(project_id: int, agreement_id: int, line_id: int,
|
||||
quantity_delta: str = Form(...), unit_price: str = Form(""),
|
||||
name: str = Form(""), model: str = Form(""), manufacturer: str = Form(""),
|
||||
unit: str = Form(""), system_id: int = Form(None), section_id: int = Form(None),
|
||||
request: Request = None, db: Session = Depends(get_db)):
|
||||
project_obj = _project(db, project_id)
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
line = db.query(AgreementItem).filter(
|
||||
AgreementItem.id == line_id, AgreementItem.agreement_id == agreement_id
|
||||
).first()
|
||||
if line is None:
|
||||
raise HTTPException(status_code=404, detail="Agreement item not found")
|
||||
try:
|
||||
update_draft_item(db, agreement, line, quantity_delta=quantity_delta,
|
||||
unit_price=unit_price if line.change_type == "new_position" else None,
|
||||
name=name, model=model, manufacturer=manufacturer,
|
||||
unit=unit, system_id=system_id, section_id=section_id)
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303)
|
||||
except (ValueError, BaseBoqConfigurationError) as exc:
|
||||
db.rollback()
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
return _detail_response(request, db, project_obj, agreement, str(exc), 400)
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements/{agreement_id}/items/{line_id}/delete")
|
||||
async def remove_item(project_id: int, agreement_id: int, line_id: int,
|
||||
request: Request, db: Session = Depends(get_db)):
|
||||
project_obj = _project(db, project_id)
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
line = db.query(AgreementItem).filter(
|
||||
AgreementItem.id == line_id, AgreementItem.agreement_id == agreement_id
|
||||
).first()
|
||||
if line is None:
|
||||
raise HTTPException(status_code=404, detail="Agreement item not found")
|
||||
try:
|
||||
delete_draft_item(db, agreement, line)
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303)
|
||||
except ValueError as exc:
|
||||
db.rollback()
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
return _detail_response(request, db, project_obj, agreement, str(exc), 409)
|
||||
|
||||
|
||||
@router.post("/{project_id}/agreements/{agreement_id}/approve")
|
||||
async def confirm_approval(project_id: int, agreement_id: int, request: Request,
|
||||
db: Session = Depends(get_db)):
|
||||
agreement = _agreement(db, project_id, agreement_id)
|
||||
try:
|
||||
approve_agreement(db, agreement.id)
|
||||
return RedirectResponse(f"/projects/{project_id}/agreements/{agreement_id}", status_code=303)
|
||||
except (ValueError, BaseBoqConfigurationError) as exc:
|
||||
db.rollback()
|
||||
return _detail_response(request, db, _project(db, project_id),
|
||||
_agreement(db, project_id, agreement_id), str(exc), 400)
|
||||
Reference in New Issue
Block a user