feat: add agreements foundation
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
import sqlite3
|
||||
from datetime import datetime, timezone
|
||||
|
||||
MIGRATION = "20260925_agreement_boq_fk"
|
||||
BASE_LINK_MIGRATION = "20260925_agreement_base_boq"
|
||||
SCOPE_MIGRATION = "20260925_agreement_scope_boq"
|
||||
ITEM_WORK_ITEM_MIGRATION = "20260925_agreement_item_work_item_required"
|
||||
|
||||
|
||||
def run_migrations(engine):
|
||||
if engine.dialect.name != "sqlite":
|
||||
return
|
||||
path = engine.url.database
|
||||
connection = sqlite3.connect(path, isolation_level=None)
|
||||
try:
|
||||
connection.execute("PRAGMA foreign_keys=OFF")
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
connection.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TEXT NOT NULL)")
|
||||
applied = {row[0] for row in connection.execute("SELECT version FROM schema_migrations")}
|
||||
if MIGRATION not in applied:
|
||||
cols = [row[1] for row in connection.execute("PRAGMA table_info(boq_documents)")]
|
||||
if "agreement_id" not in cols:
|
||||
raise RuntimeError("boq_documents.agreement_id is missing; refusing an unsafe migration")
|
||||
connection.execute("""CREATE TABLE boq_documents_new (
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id),
|
||||
agreement_id INTEGER REFERENCES agreements(id),
|
||||
name VARCHAR NOT NULL,
|
||||
version VARCHAR,
|
||||
source_file VARCHAR,
|
||||
created_at DATETIME
|
||||
)""")
|
||||
connection.execute("""INSERT INTO boq_documents_new
|
||||
(id, project_id, agreement_id, name, version, source_file, created_at)
|
||||
SELECT id, project_id, agreement_id, name, version, source_file, created_at
|
||||
FROM boq_documents""")
|
||||
connection.execute("DROP TABLE boq_documents")
|
||||
connection.execute("ALTER TABLE boq_documents_new RENAME TO boq_documents")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_boq_documents_id ON boq_documents (id)")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_boq_documents_agreement_id ON boq_documents (agreement_id)")
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
if BASE_LINK_MIGRATION not in applied:
|
||||
agreement_cols = [row[1] for row in connection.execute("PRAGMA table_info(agreements)")]
|
||||
if "base_boq_document_id" not in agreement_cols and "boq_document_id" not in agreement_cols:
|
||||
connection.execute("ALTER TABLE agreements ADD COLUMN boq_document_id INTEGER REFERENCES boq_documents(id)")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_boq_document_id ON agreements (boq_document_id)")
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(BASE_LINK_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
if SCOPE_MIGRATION not in applied:
|
||||
agreement_cols = [row[1] for row in connection.execute("PRAGMA table_info(agreements)")]
|
||||
if "base_boq_document_id" in agreement_cols and "boq_document_id" not in agreement_cols:
|
||||
connection.execute("ALTER TABLE agreements RENAME COLUMN base_boq_document_id TO boq_document_id")
|
||||
elif "boq_document_id" not in agreement_cols:
|
||||
connection.execute("ALTER TABLE agreements ADD COLUMN boq_document_id INTEGER REFERENCES boq_documents(id)")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_agreements_boq_document_id ON agreements (boq_document_id)")
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(SCOPE_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
if ITEM_WORK_ITEM_MIGRATION not in applied:
|
||||
item_cols = {row[1]: row[3] for row in connection.execute("PRAGMA table_info(agreement_items)")}
|
||||
if not item_cols.get("work_item_id", 0):
|
||||
null_items = connection.execute("SELECT COUNT(*) FROM agreement_items WHERE work_item_id IS NULL").fetchone()[0]
|
||||
if null_items:
|
||||
raise RuntimeError(f"Cannot require AgreementItem.work_item_id: {null_items} rows have no canonical WorkItem")
|
||||
connection.execute("""CREATE TABLE agreement_items_new (
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
agreement_id INTEGER NOT NULL REFERENCES agreements(id),
|
||||
work_item_id INTEGER NOT NULL REFERENCES work_items(id),
|
||||
change_type VARCHAR NOT NULL CHECK (change_type IN ('increase','decrease','new_position')),
|
||||
quantity_delta NUMERIC(15,4) NOT NULL,
|
||||
amount_delta NUMERIC(18,12) NOT NULL,
|
||||
source_row INTEGER,
|
||||
source_number VARCHAR,
|
||||
source_name VARCHAR,
|
||||
source_model VARCHAR,
|
||||
source_manufacturer VARCHAR,
|
||||
source_unit VARCHAR,
|
||||
source_unit_price NUMERIC(18,12),
|
||||
source_system_id INTEGER REFERENCES systems(id),
|
||||
source_section_id INTEGER REFERENCES sections(id),
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT ck_agreement_items_quantity_sign CHECK (
|
||||
(change_type = 'increase' AND quantity_delta > 0) OR
|
||||
(change_type = 'decrease' AND quantity_delta < 0) OR
|
||||
(change_type = 'new_position' AND quantity_delta > 0)
|
||||
)
|
||||
)""")
|
||||
connection.execute("""INSERT INTO agreement_items_new (
|
||||
id, agreement_id, work_item_id, change_type, quantity_delta, amount_delta,
|
||||
source_row, source_number, source_name, source_model, source_manufacturer,
|
||||
source_unit, source_unit_price, source_system_id, source_section_id, created_at, updated_at
|
||||
) SELECT id, agreement_id, work_item_id, change_type, quantity_delta, amount_delta,
|
||||
source_row, source_number, source_name, source_model, source_manufacturer,
|
||||
source_unit, source_unit_price, source_system_id, source_section_id, created_at, updated_at
|
||||
FROM agreement_items""")
|
||||
connection.execute("DROP TABLE agreement_items")
|
||||
connection.execute("ALTER TABLE agreement_items_new RENAME TO agreement_items")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_agreement_items_id ON agreement_items (id)")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_agreement_items_agreement_id ON agreement_items (agreement_id)")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS ix_agreement_items_work_item_id ON agreement_items (work_item_id)")
|
||||
connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
||||
(ITEM_WORK_ITEM_MIGRATION, datetime.now(timezone.utc).isoformat()))
|
||||
violations = connection.execute("PRAGMA foreign_key_check").fetchall()
|
||||
if violations:
|
||||
raise RuntimeError(f"Foreign key violations after agreement migration: {violations[:10]}")
|
||||
connection.commit()
|
||||
except Exception:
|
||||
connection.rollback()
|
||||
raise
|
||||
finally:
|
||||
connection.execute("PRAGMA foreign_keys=ON")
|
||||
connection.close()
|
||||
@@ -11,11 +11,14 @@ from app.routers import projects, boq as boq_router, daily_reports
|
||||
from app.models import project as project_models, boq as boq_models
|
||||
from app.models import daily_report as daily_report_models
|
||||
from app.models import work_journal as work_journal_models
|
||||
from app.models import agreement as agreement_models
|
||||
|
||||
# Initialize database
|
||||
from app.database.database import engine
|
||||
from app.database.database import Base
|
||||
Base.metadata.create_all(bind=engine)
|
||||
from app.database.migrations import run_migrations
|
||||
run_migrations(engine)
|
||||
|
||||
app = FastAPI(
|
||||
title="Work Volume Tracker",
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, CheckConstraint, UniqueConstraint
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.database.database import Base
|
||||
|
||||
|
||||
class Agreement(Base):
|
||||
__tablename__ = "agreements"
|
||||
__table_args__ = (
|
||||
CheckConstraint("status IN ('draft', 'approved')", name="ck_agreements_status"),
|
||||
UniqueConstraint("project_id", "number", name="uq_agreements_project_number"),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||
boq_document_id = Column(Integer, ForeignKey("boq_documents.id"), nullable=True, index=True)
|
||||
number = Column(String, nullable=False)
|
||||
date = Column(Date, nullable=False)
|
||||
title = Column(String, nullable=False)
|
||||
description = Column(Text)
|
||||
status = Column(String, nullable=False, default="draft", server_default="draft")
|
||||
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||
updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now())
|
||||
|
||||
project = relationship("Project", back_populates="agreements")
|
||||
items = relationship("AgreementItem", back_populates="agreement", cascade="all, delete-orphan")
|
||||
boq_documents = relationship("BoqDocument", back_populates="agreement", foreign_keys="BoqDocument.agreement_id")
|
||||
scoped_boq_document = relationship("BoqDocument", foreign_keys=[boq_document_id])
|
||||
|
||||
|
||||
class AgreementItem(Base):
|
||||
__tablename__ = "agreement_items"
|
||||
__table_args__ = (
|
||||
CheckConstraint("change_type IN ('increase', 'decrease', 'new_position')", name="ck_agreement_items_type"),
|
||||
CheckConstraint("(change_type = 'increase' AND quantity_delta > 0) OR (change_type = 'decrease' AND quantity_delta < 0) OR (change_type = 'new_position' AND quantity_delta > 0)", name="ck_agreement_items_quantity_sign"),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
agreement_id = Column(Integer, ForeignKey("agreements.id"), nullable=False, index=True)
|
||||
work_item_id = Column(Integer, ForeignKey("work_items.id"), nullable=False, index=True)
|
||||
change_type = Column(String, nullable=False)
|
||||
quantity_delta = Column(Numeric(15, 4), nullable=False)
|
||||
amount_delta = Column(Numeric(18, 12), nullable=False)
|
||||
source_row = Column(Integer)
|
||||
source_number = Column(String)
|
||||
source_name = Column(String)
|
||||
source_model = Column(String)
|
||||
source_manufacturer = Column(String)
|
||||
source_unit = Column(String)
|
||||
source_unit_price = Column(Numeric(18, 12))
|
||||
source_system_id = Column(Integer, ForeignKey("systems.id"))
|
||||
source_section_id = Column(Integer, ForeignKey("sections.id"))
|
||||
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||
updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now())
|
||||
|
||||
agreement = relationship("Agreement", back_populates="items")
|
||||
work_item = relationship("WorkItem")
|
||||
source_system = relationship("System")
|
||||
source_section = relationship("Section")
|
||||
+2
-1
@@ -10,7 +10,7 @@ class BoqDocument(Base):
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
|
||||
agreement_id = Column(Integer) # nullable
|
||||
agreement_id = Column(Integer, ForeignKey("agreements.id"), nullable=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
version = Column(String)
|
||||
source_file = Column(String)
|
||||
@@ -18,6 +18,7 @@ class BoqDocument(Base):
|
||||
|
||||
# Relationship to project
|
||||
project = relationship("Project", back_populates="boq_documents")
|
||||
agreement = relationship("Agreement", back_populates="boq_documents", foreign_keys=[agreement_id])
|
||||
|
||||
def __repr__(self):
|
||||
return f"<BoqDocument(id={self.id}, name='{self.name}')>"
|
||||
|
||||
@@ -23,6 +23,7 @@ class Project(Base):
|
||||
# Relationships
|
||||
boq_documents = relationship("BoqDocument", back_populates="project")
|
||||
systems = relationship("System", back_populates="project")
|
||||
agreements = relationship("Agreement", back_populates="project", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Project(id={self.id}, name='{self.name}')>"
|
||||
return f"<Project(id={self.id}, name='{self.name}')>"
|
||||
|
||||
@@ -9,6 +9,7 @@ from sqlalchemy.orm import Session
|
||||
from app.database.database import SessionLocal
|
||||
from app.models import boq, project
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.services.effective_plan import build_effective_plan
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -46,14 +47,17 @@ def _report_rows(db: Session, project_id: int, system_id: int, exclude_report_id
|
||||
)
|
||||
if exclude_report_id is not None:
|
||||
totals = totals.filter(DailyReport.id != exclude_report_id)
|
||||
totals = totals.group_by(DailyReportItem.work_item_id).subquery()
|
||||
items = db.query(boq.WorkItem, func.coalesce(totals.c.completed, 0)).outerjoin(
|
||||
totals, totals.c.work_item_id == boq.WorkItem.id
|
||||
).filter(
|
||||
boq.WorkItem.project_id == project_id,
|
||||
boq.WorkItem.system_id == system_id,
|
||||
).order_by(boq.WorkItem.section_id, boq.WorkItem.id).all()
|
||||
return [{"item": item, "accumulated": Decimal(str(completed or 0))} for item, completed in items]
|
||||
totals = {item_id: Decimal(str(value or 0)) for item_id, value in
|
||||
totals.group_by(DailyReportItem.work_item_id).all()}
|
||||
plan = build_effective_plan(db, project_id)
|
||||
rows = []
|
||||
for planned in plan["items"]:
|
||||
item = planned.item
|
||||
if item.system_id == system_id:
|
||||
rows.append({"item": item, "planned_quantity": planned.quantity,
|
||||
"accumulated": totals.get(item.id, Decimal("0"))})
|
||||
rows.sort(key=lambda row: (row["item"].section_id or 0, row["item"].id))
|
||||
return rows
|
||||
|
||||
|
||||
def _render_form(request, db, project_obj, system_id=None, report=None, errors=None):
|
||||
@@ -75,9 +79,9 @@ def _render_form(request, db, project_obj, system_id=None, report=None, errors=N
|
||||
rows = _report_rows(db, project_obj.id, system_id, exclude_id)
|
||||
for row in rows:
|
||||
row["current_quantity"] = current_quantities.get(row["item"].id)
|
||||
planned = row["item"].quantity
|
||||
planned = row["planned_quantity"]
|
||||
current = Decimal(str(row["current_quantity"] or 0))
|
||||
row["over_plan"] = planned is not None and row["accumulated"] + current > Decimal(str(planned))
|
||||
row["over_plan"] = row["accumulated"] + current > planned
|
||||
return request.app.templates.TemplateResponse("projects/daily_report_form.html", {
|
||||
"request": request, "project": project_obj, "systems": systems,
|
||||
"selected_system": selected_system, "rows": rows, "report": report,
|
||||
@@ -144,9 +148,9 @@ async def view_daily_report(request: Request, project_id: int, report_id: int,
|
||||
if line is None:
|
||||
continue
|
||||
quantity = Decimal(str(line.completed_quantity))
|
||||
planned = row["item"].quantity
|
||||
planned = row["planned_quantity"]
|
||||
row.update(current_quantity=quantity,
|
||||
over_plan=planned is not None and row["accumulated"] + quantity > Decimal(str(planned)))
|
||||
over_plan=row["accumulated"] + quantity > planned)
|
||||
if row["over_plan"]:
|
||||
warnings.append(row)
|
||||
displayed.append(row)
|
||||
@@ -215,10 +219,7 @@ def _quantities_from_form(form):
|
||||
|
||||
|
||||
def _validate_work_items(db, project_id, system_id, quantities):
|
||||
valid_ids = {row[0] for row in db.query(boq.WorkItem.id).filter(
|
||||
boq.WorkItem.project_id == project_id,
|
||||
boq.WorkItem.system_id == system_id,
|
||||
boq.WorkItem.id.in_(quantities.keys()),
|
||||
).all()}
|
||||
if valid_ids != set(quantities):
|
||||
raise HTTPException(status_code=400, detail="Одна или несколько позиций не принадлежат выбранной системе проекта")
|
||||
effective_ids = {row.item.id for row in build_effective_plan(db, project_id)["items"]
|
||||
if row.item.system_id == system_id}
|
||||
if effective_ids.intersection(quantities) != set(quantities):
|
||||
raise HTTPException(status_code=400, detail="One or more work items are not part of the selected system effective plan")
|
||||
|
||||
@@ -5,6 +5,7 @@ from app.database import database
|
||||
from app.models import project
|
||||
from app.models import boq
|
||||
from app.services.project_dashboard import build_project_dashboard
|
||||
from app.services.effective_plan import BaseBoqConfigurationError
|
||||
from app.models.daily_report import DailyReport
|
||||
from app.models.work_journal import WorkJournalEntry
|
||||
from typing import List
|
||||
@@ -106,7 +107,10 @@ async def read_project(request: Request, project_id: int, db: Session = Depends(
|
||||
boq_docs = db.query(boq.BoqDocument).filter(
|
||||
boq.BoqDocument.project_id == project_id
|
||||
).order_by(boq.BoqDocument.created_at.desc(), boq.BoqDocument.id.desc()).all()
|
||||
dashboard = build_project_dashboard(db, db_project)
|
||||
try:
|
||||
dashboard = build_project_dashboard(db, db_project)
|
||||
except BaseBoqConfigurationError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
daily_reports = db.query(DailyReport).filter(DailyReport.project_id == project_id).count()
|
||||
journal_tasks = db.query(WorkJournalEntry).filter(
|
||||
WorkJournalEntry.project_id == project_id,
|
||||
|
||||
@@ -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
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
{% for row in rows %}
|
||||
<tr class="position-row {% if row.over_plan %}table-warning{% endif %}" data-number="{{ row.item.source_number or '' }}" data-name="{{ row.item.name or '' }}" data-model="{{ row.item.model or '' }}" data-manufacturer="{{ row.item.manufacturer or '' }}">
|
||||
<td>{{ row.item.section.name if row.item.section else '—' }}</td><td>{{ row.item.source_number or '' }}</td><td>{{ row.item.name }}</td><td>{{ row.item.unit or '' }}</td>
|
||||
<td class="text-end">{{ row.item.quantity if row.item.quantity is not none else '—' }}</td><td class="text-end">{{ row.accumulated }}</td>
|
||||
<td class="text-end">{{ row.planned_quantity if row.planned_quantity is not none else '—' }}</td><td class="text-end">{{ row.accumulated }}</td>
|
||||
<td><input class="form-control form-control-sm" type="number" min="0" step="0.0001" name="quantity_{{ row.item.id }}" value="{{ row.current_quantity if row.current_quantity is not none else '' }}" aria-label="Выполнено: {{ row.item.name }}"></td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="7" class="text-center text-muted py-4">В этой системе нет рабочих позиций ведомости.</td></tr>{% endfor %}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<div class="card"><div class="table-responsive"><table class="table table-hover align-middle mb-0">
|
||||
<thead><tr><th>Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th class="text-end">План</th><th class="text-end">Накоплено до отчёта</th><th class="text-end">В этом отчёте</th><th class="text-end">Накоплено</th></tr></thead>
|
||||
<tbody>{% for row in rows %}
|
||||
<tr class="{% if row.over_plan %}table-warning{% endif %}"><td>{{ row.item.section.name if row.item.section else '—' }}</td><td>{{ row.item.source_number or '' }}</td><td>{{ row.item.name }}</td><td>{{ row.item.unit or '' }}</td><td class="text-end">{{ row.item.quantity if row.item.quantity is not none else '—' }}</td><td class="text-end">{{ row.accumulated }}</td><td class="text-end">{{ row.current_quantity }}</td><td class="text-end">{{ row.accumulated + row.current_quantity }}</td></tr>
|
||||
<tr class="{% if row.over_plan %}table-warning{% endif %}"><td>{{ row.item.section.name if row.item.section else '—' }}</td><td>{{ row.item.source_number or '' }}</td><td>{{ row.item.name }}</td><td>{{ row.item.unit or '' }}</td><td class="text-end">{{ row.planned_quantity if row.planned_quantity is not none else '—' }}</td><td class="text-end">{{ row.accumulated }}</td><td class="text-end">{{ row.current_quantity }}</td><td class="text-end">{{ row.accumulated + row.current_quantity }}</td></tr>
|
||||
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">В отчёте нет рабочих позиций.</td></tr>{% endfor %}</tbody>
|
||||
</table></div></div>
|
||||
<div class="mt-3"><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-outline-secondary">К списку отчётов</a></div>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<span>Период: <strong class="text-dark">{{ project.start_date.strftime('%d.%m.%Y') if project.start_date else '—' }} — {{ project.end_date.strftime('%d.%m.%Y') if project.end_date else '—' }}</strong></span>
|
||||
<span>Статус: <span class="badge text-bg-secondary">{{ project.status or 'не указан' }}</span></span>
|
||||
</div>
|
||||
{% if current_boq %}<div class="small text-muted mt-2">Текущая ведомость: {{ current_boq.name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}</div>{% endif %}
|
||||
{% if base_boq_documents|length == 1 %}<div class="small text-muted mt-2">Ведомость проекта: {{ base_boq_documents[0].name.replace('BOQ Import - ', 'Импорт ведомости — ').replace('BOQ Import — ', 'Импорт ведомости — ') }}</div>{% elif base_boq_documents|length > 1 %}<div class="small text-muted mt-2">Ведомостей проекта: {{ base_boq_documents|length }}</div>{% endif %}
|
||||
</div>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/edit">Редактировать</a>
|
||||
@@ -46,12 +46,12 @@
|
||||
<section class="mb-4" aria-labelledby="kpi-heading">
|
||||
<h2 id="kpi-heading" class="h5 mb-3">План и выполнение</h2>
|
||||
<div class="row g-3">
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Плановая стоимость</div><div class="fs-3 fw-semibold">{{ planned_cost|money(project.currency) }}</div><div class="small text-muted">текущая ведомость</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Плановая стоимость</div><div class="fs-3 fw-semibold">{{ planned_cost|money(project.currency) }}</div><div class="small text-muted">по ведомостям проекта</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнено по Daily Reports</div><div class="fs-3 fw-semibold text-success">{{ performed_cost|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Остаток</div><div class="fs-3 fw-semibold {% if remaining_cost < 0 %}text-danger{% endif %}">{{ remaining_cost|money(project.currency) }}</div></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card h-100 border-0 shadow-sm"><div class="card-body"><div class="text-muted small">Выполнение</div><div class="fs-3 fw-semibold">{{ '%.4f'|format(completion_percent) }}%</div><div class="progress mt-2" role="progressbar" aria-valuenow="{{ '%.4f'|format(completion_percent) }}" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar {% if completion_percent > 100 %}bg-warning{% endif %}" style="width: {{ 100 if completion_percent > 100 else completion_percent }}%"></div></div></div></article></div>
|
||||
</div>
|
||||
{% if not current_boq %}<div class="alert alert-info mt-3 mb-0">Сначала импортируйте ведомость, чтобы сформировать план.</div>{% endif %}
|
||||
{% if not base_boq_documents %}<div class="alert alert-info mt-3 mb-0">Сначала импортируйте ведомость, чтобы сформировать план.</div>{% endif %}
|
||||
</section>
|
||||
|
||||
<div class="row g-4">
|
||||
|
||||
Reference in New Issue
Block a user