diff --git a/app/database/migrations.py b/app/database/migrations.py
index 7330185..5d6f77d 100644
--- a/app/database/migrations.py
+++ b/app/database/migrations.py
@@ -5,6 +5,8 @@ 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"
+WORK_ITEM_OPTIONAL_BOQ_MIGRATION = "20260925_work_item_optional_boq"
+DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION = "20260925_daily_report_optional_system"
def run_migrations(engine):
@@ -101,6 +103,72 @@ def run_migrations(engine):
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()))
+ if WORK_ITEM_OPTIONAL_BOQ_MIGRATION not in applied:
+ work_item_cols = {row[1]: row[3] for row in connection.execute("PRAGMA table_info(work_items)")}
+ if work_item_cols.get("boq_document_id", 0):
+ connection.execute("""CREATE TABLE work_items_new (
+ id INTEGER NOT NULL PRIMARY KEY,
+ project_id INTEGER NOT NULL REFERENCES projects(id),
+ boq_document_id INTEGER REFERENCES boq_documents(id),
+ system_id INTEGER REFERENCES systems(id),
+ section_id INTEGER REFERENCES sections(id),
+ source_number VARCHAR,
+ name VARCHAR NOT NULL,
+ model VARCHAR,
+ manufacturer VARCHAR,
+ unit VARCHAR,
+ quantity NUMERIC(15, 4),
+ unit_price NUMERIC(18, 12),
+ amount NUMERIC(18, 12),
+ created_at DATETIME,
+ updated_at DATETIME
+ )""")
+ connection.execute("""INSERT INTO work_items_new (
+ id, project_id, boq_document_id, system_id, section_id, source_number,
+ name, model, manufacturer, unit, quantity, unit_price, amount, created_at, updated_at
+ ) SELECT id, project_id, boq_document_id, system_id, section_id, source_number,
+ name, model, manufacturer, unit, quantity, unit_price, amount, created_at, updated_at
+ FROM work_items""")
+ connection.execute("DROP TABLE work_items")
+ connection.execute("ALTER TABLE work_items_new RENAME TO work_items")
+ connection.execute("CREATE INDEX IF NOT EXISTS ix_work_items_id ON work_items (id)")
+ agreement_item_cols = {row[1] for row in connection.execute("PRAGMA table_info(agreement_items)")}
+ if "source_boq_document_id" not in agreement_item_cols:
+ connection.execute("ALTER TABLE agreement_items ADD COLUMN source_boq_document_id INTEGER REFERENCES boq_documents(id)")
+ # Older agreement-created positions live in an agreement document. Keep their
+ # source BOQ scope where one was explicitly selected on the Agreement.
+ connection.execute("""UPDATE agreement_items
+ SET source_boq_document_id = (
+ SELECT agreements.boq_document_id FROM agreements
+ WHERE agreements.id = agreement_items.agreement_id
+ )
+ WHERE change_type = 'new_position' AND source_boq_document_id IS NULL""")
+ connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
+ (WORK_ITEM_OPTIONAL_BOQ_MIGRATION, datetime.now(timezone.utc).isoformat()))
+ if DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION not in applied:
+ report_cols = {row[1]: row[3] for row in connection.execute("PRAGMA table_info(daily_reports)")}
+ if report_cols.get("system_id", 0):
+ connection.execute("""CREATE TABLE daily_reports_new (
+ id INTEGER NOT NULL PRIMARY KEY,
+ project_id INTEGER NOT NULL REFERENCES projects(id),
+ system_id INTEGER REFERENCES systems(id),
+ report_date DATE NOT NULL,
+ notes TEXT,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
+ )""")
+ connection.execute("""INSERT INTO daily_reports_new (
+ id, project_id, system_id, report_date, notes, created_at, updated_at
+ ) SELECT id, project_id, system_id, report_date, notes, created_at, updated_at
+ FROM daily_reports""")
+ connection.execute("DROP TABLE daily_reports")
+ connection.execute("ALTER TABLE daily_reports_new RENAME TO daily_reports")
+ connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_id ON daily_reports (id)")
+ connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_project_id ON daily_reports (project_id)")
+ connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_system_id ON daily_reports (system_id)")
+ connection.execute("CREATE INDEX IF NOT EXISTS ix_daily_reports_report_date ON daily_reports (report_date)")
+ connection.execute("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
+ (DAILY_REPORT_OPTIONAL_SYSTEM_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]}")
diff --git a/app/main.py b/app/main.py
index 84bb19c..156b830 100644
--- a/app/main.py
+++ b/app/main.py
@@ -5,7 +5,7 @@ from fastapi.responses import RedirectResponse
from pathlib import Path
# Import routers
-from app.routers import projects, boq as boq_router, daily_reports
+from app.routers import projects, boq as boq_router, daily_reports, agreements
# Import models to ensure they're registered
from app.models import project as project_models, boq as boq_models
@@ -40,6 +40,7 @@ app.templates = templates
app.include_router(projects.router, prefix="/projects", tags=["projects"])
app.include_router(boq_router.router, prefix="/boq", tags=["boq"])
app.include_router(daily_reports.router, prefix="/projects", tags=["daily-reports"])
+app.include_router(agreements.router, prefix="/projects", tags=["agreements"])
@app.get("/", include_in_schema=False)
async def read_root():
diff --git a/app/models/agreement.py b/app/models/agreement.py
index 5bdadaf..69e1ac5 100644
--- a/app/models/agreement.py
+++ b/app/models/agreement.py
@@ -49,6 +49,7 @@ class AgreementItem(Base):
source_manufacturer = Column(String)
source_unit = Column(String)
source_unit_price = Column(Numeric(18, 12))
+ source_boq_document_id = Column(Integer, ForeignKey("boq_documents.id"), nullable=True)
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())
@@ -58,3 +59,4 @@ class AgreementItem(Base):
work_item = relationship("WorkItem")
source_system = relationship("System")
source_section = relationship("Section")
+ source_boq_document = relationship("BoqDocument", foreign_keys=[source_boq_document_id])
diff --git a/app/models/boq.py b/app/models/boq.py
index c4c8853..b963cf7 100644
--- a/app/models/boq.py
+++ b/app/models/boq.py
@@ -60,7 +60,7 @@ class WorkItem(Base):
id = Column(Integer, primary_key=True, index=True)
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
- boq_document_id = Column(Integer, ForeignKey("boq_documents.id"), nullable=False)
+ boq_document_id = Column(Integer, ForeignKey("boq_documents.id"), nullable=True)
system_id = Column(Integer, ForeignKey("systems.id"))
section_id = Column(Integer, ForeignKey("sections.id"))
source_number = Column(String)
diff --git a/app/models/daily_report.py b/app/models/daily_report.py
index 4fb1207..b746b10 100644
--- a/app/models/daily_report.py
+++ b/app/models/daily_report.py
@@ -10,7 +10,7 @@ class DailyReport(Base):
id = Column(Integer, primary_key=True, index=True)
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
- system_id = Column(Integer, ForeignKey("systems.id"), nullable=False, index=True)
+ system_id = Column(Integer, ForeignKey("systems.id"), nullable=True, index=True)
report_date = Column(Date, nullable=False, index=True)
notes = Column(Text)
created_at = Column(DateTime, nullable=False, server_default=func.now())
diff --git a/app/routers/agreements.py b/app/routers/agreements.py
new file mode 100644
index 0000000..fa173a4
--- /dev/null
+++ b/app/routers/agreements.py
@@ -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)
diff --git a/app/routers/daily_reports.py b/app/routers/daily_reports.py
index 12dd133..4800816 100644
--- a/app/routers/daily_reports.py
+++ b/app/routers/daily_reports.py
@@ -38,7 +38,7 @@ def _report_or_404(db: Session, project_id: int, report_id: int):
return report
-def _report_rows(db: Session, project_id: int, system_id: int, exclude_report_id=None):
+def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_report_id=None):
totals = db.query(
DailyReportItem.work_item_id.label("work_item_id"),
func.sum(DailyReportItem.completed_quantity).label("completed"),
@@ -61,6 +61,9 @@ def _report_rows(db: Session, project_id: int, system_id: int, exclude_report_id
def _render_form(request, db, project_obj, system_id=None, report=None, errors=None):
+ effective = build_effective_plan(db, project_obj.id)["items"]
+ token = "unclassified" if system_id == "unclassified" else (str(system_id) if system_id not in (None, "") else None)
+ unclassified = [row for row in effective if row.item.system_id is None]
systems = db.query(boq.System).filter(
boq.System.project_id == project_obj.id,
boq.System.id.in_(db.query(boq.WorkItem.system_id).filter(
@@ -68,27 +71,48 @@ def _render_form(request, db, project_obj, system_id=None, report=None, errors=N
boq.WorkItem.system_id.is_not(None),
).distinct()),
).order_by(boq.System.sort_order, boq.System.id).all()
+ unclassified_selected = token == "unclassified" or (report is not None and report.system_id is None and token is None)
selected_system = None
rows = []
- current_quantities = {line.work_item_id: line.completed_quantity for line in report.items} if report else {}
- exclude_id = report.id if report else None
- if system_id:
- selected_system = next((s for s in systems if s.id == system_id), None)
- if selected_system is None:
- raise HTTPException(status_code=400, detail="System does not belong to this project")
- 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["planned_quantity"]
- current = Decimal(str(row["current_quantity"] or 0))
- row["over_plan"] = row["accumulated"] + current > planned
+ if token is not None:
+ if token == "unclassified":
+ if not unclassified:
+ raise HTTPException(status_code=400, detail="No unclassified effective work items")
+ selected_id = None
+ else:
+ try:
+ selected_id = int(token)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail="Invalid system selection") from exc
+ selected_system = next((row for row in systems if row.id == selected_id), None)
+ if selected_system is None:
+ raise HTTPException(status_code=400, detail="System does not belong to this project effective plan")
+ rows = _report_rows(db, project_obj.id, selected_id, report.id if report else None)
+ current = {line.work_item_id: line.completed_quantity for line in report.items} if report else {}
+ for row in rows:
+ row["current_quantity"] = current.get(row["item"].id)
+ row["over_plan"] = row["accumulated"] + Decimal(str(row["current_quantity"] or 0)) > row["planned_quantity"]
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,
- "errors": errors or [],
+ "has_unclassified_items": bool(unclassified), "unclassified_selected": unclassified_selected,
+ "selected_system": selected_system, "rows": rows, "report": report, "errors": errors or [],
})
+def _parse_system_selection(db, project_id, token):
+ if token == "unclassified":
+ if not any(row.item.system_id is None for row in build_effective_plan(db, project_id)["items"]):
+ raise HTTPException(status_code=400, detail="No unclassified effective work items")
+ return None
+ try:
+ system_id = int(token)
+ except (ValueError, TypeError) as exc:
+ raise HTTPException(status_code=400, detail="Select a system or unclassified positions") from exc
+ if not db.query(boq.System.id).filter(boq.System.id == system_id, boq.System.project_id == project_id).first():
+ raise HTTPException(status_code=400, detail="System does not belong to this project")
+ return system_id
+
+
@router.get("/{project_id}/daily-reports")
async def list_daily_reports(request: Request, project_id: int, db: Session = Depends(get_db)):
project_obj = _project_or_404(db, project_id)
@@ -101,29 +125,26 @@ async def list_daily_reports(request: Request, project_id: int, db: Session = De
@router.get("/{project_id}/daily-reports/new")
-async def new_daily_report(request: Request, project_id: int, system_id: int = None,
+async def new_daily_report(request: Request, project_id: int, system_id: str = None,
db: Session = Depends(get_db)):
return _render_form(request, db, _project_or_404(db, project_id), system_id)
@router.post("/{project_id}/daily-reports")
async def create_daily_report(request: Request, project_id: int,
- report_date: str = Form(...), system_id: int = Form(...),
+ report_date: str = Form(...), system_id: str = Form(...),
notes: str = Form(""), db: Session = Depends(get_db)):
project_obj = _project_or_404(db, project_id)
try:
parsed_date = date.fromisoformat(report_date)
except ValueError as exc:
raise HTTPException(status_code=400, detail="Invalid report date") from exc
- 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")
+ system_id = _parse_system_selection(db, project_id, system_id)
form = await request.form()
quantities, errors = _quantities_from_form(form)
if errors:
- return _render_form(request, db, project_obj, system_id, errors=errors)
+ selection = "unclassified" if system_id is None else system_id
+ return _render_form(request, db, project_obj, selection, errors=errors)
_validate_work_items(db, project_id, system_id, quantities)
report = DailyReport(project_id=project_id, system_id=system_id, report_date=parsed_date,
notes=notes.strip() or None)
@@ -165,12 +186,13 @@ async def edit_daily_report(request: Request, project_id: int, report_id: int,
db: Session = Depends(get_db)):
project_obj = _project_or_404(db, project_id)
report = _report_or_404(db, project_id, report_id)
- return _render_form(request, db, project_obj, report.system_id, report)
+ return _render_form(request, db, project_obj,
+ report.system_id if report.system_id is not None else "unclassified", report)
@router.post("/{project_id}/daily-reports/{report_id}/edit")
async def update_daily_report(request: Request, project_id: int, report_id: int,
- report_date: str = Form(...), system_id: int = Form(...),
+ report_date: str = Form(...), system_id: str = Form(...),
notes: str = Form(""), db: Session = Depends(get_db)):
project_obj = _project_or_404(db, project_id)
report = _report_or_404(db, project_id, report_id)
@@ -178,15 +200,12 @@ async def update_daily_report(request: Request, project_id: int, report_id: int,
report.report_date = date.fromisoformat(report_date)
except ValueError as exc:
raise HTTPException(status_code=400, detail="Invalid report date") from exc
- 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")
+ system_id = _parse_system_selection(db, project_id, system_id)
form = await request.form()
quantities, errors = _quantities_from_form(form)
if errors:
- return _render_form(request, db, project_obj, report.system_id, report, errors)
+ selection = "unclassified" if system_id is None else system_id
+ return _render_form(request, db, project_obj, selection, report, errors)
_validate_work_items(db, project_id, system_id, quantities)
report.system_id = system_id
report.notes = notes.strip() or None
diff --git a/app/services/agreement_items.py b/app/services/agreement_items.py
new file mode 100644
index 0000000..597e480
--- /dev/null
+++ b/app/services/agreement_items.py
@@ -0,0 +1,241 @@
+from decimal import Decimal, InvalidOperation
+
+from app.models import boq
+from app.models.agreement import Agreement, AgreementItem
+from app.services.effective_plan import (
+ BaseBoqConfigurationError,
+ build_effective_plan,
+ work_item_scope_document_id,
+)
+
+
+def decimal_value(value, label):
+ try:
+ result = Decimal(str(value).strip().replace(",", "."))
+ except (InvalidOperation, ValueError, AttributeError) as exc:
+ raise ValueError(f"Invalid {label}") from exc
+ if not result.is_finite():
+ raise ValueError(f"Invalid {label}")
+ return result
+
+
+def _require_draft(agreement):
+ if agreement.status != "draft":
+ raise ValueError("Only draft agreements can be changed")
+
+
+def available_work_items(db, agreement):
+ _require_draft(agreement)
+ plan = build_effective_plan(db, agreement.project_id)
+ existing_ids = {row[0] for row in db.query(AgreementItem.work_item_id).filter(
+ AgreementItem.agreement_id == agreement.id
+ ).all()}
+ result = []
+ for row in plan["items"]:
+ if row.item.id in existing_ids:
+ continue
+ if agreement.boq_document_id is not None:
+ if work_item_scope_document_id(db, row.item) != agreement.boq_document_id:
+ continue
+ result.append(row)
+ return result
+
+
+def _unit_rate(row):
+ item = row.item
+ if item.unit_price is not None:
+ rate = Decimal(str(item.unit_price))
+ elif row.quantity:
+ rate = row.amount / row.quantity
+ else:
+ raise ValueError(f"WorkItem {item.id} has no usable unit price")
+ if rate < 0:
+ raise ValueError(f"WorkItem {item.id} has a negative unit price")
+ return rate
+
+
+def add_existing_item(db, agreement, work_item_id, quantity_delta):
+ _require_draft(agreement)
+ plan_rows = available_work_items(db, agreement)
+ row = next((entry for entry in plan_rows if entry.item.id == work_item_id), None)
+ if row is None:
+ raise ValueError("WorkItem is already added or outside this agreement scope")
+ delta = decimal_value(quantity_delta, "quantity delta")
+ if delta == 0:
+ raise ValueError("Quantity delta cannot be zero")
+ if row.quantity + delta < 0:
+ raise ValueError("Effective quantity cannot become negative")
+ rate = _unit_rate(row)
+ line = AgreementItem(
+ agreement_id=agreement.id,
+ work_item_id=row.item.id,
+ change_type="increase" if delta > 0 else "decrease",
+ quantity_delta=delta,
+ amount_delta=delta * rate,
+ source_number=row.item.source_number,
+ source_name=row.item.name,
+ source_model=row.item.model,
+ source_manufacturer=row.item.manufacturer,
+ source_unit=row.item.unit,
+ source_unit_price=rate,
+ source_system_id=row.item.system_id,
+ source_section_id=row.item.section_id,
+ )
+ db.add(line)
+ db.flush()
+ return line
+
+
+def _validate_system_section(db, project_id, system_id, section_id):
+ if system_id is None:
+ if section_id is not None:
+ raise ValueError("A section requires a selected system")
+ return
+ system = db.query(boq.System).filter(
+ boq.System.id == system_id, boq.System.project_id == project_id
+ ).first()
+ if system is None:
+ raise ValueError("System does not belong to this project")
+ if section_id is not None:
+ section = db.query(boq.Section).filter(
+ boq.Section.id == section_id, boq.Section.system_id == system_id
+ ).first()
+ if section is None:
+ raise ValueError("Section does not belong to the selected system")
+
+
+def _validate_source_document(db, project_id, document_id):
+ if document_id is None:
+ return None
+ 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("BOQ document does not belong to this project")
+ return document.id
+
+
+def add_new_item(db, agreement, *, name, model, manufacturer, unit, quantity_delta,
+ unit_price, system_id=None, section_id=None, source_boq_document_id=None):
+ _require_draft(agreement)
+ name = (name or "").strip()
+ if not name:
+ raise ValueError("Position name is required")
+ delta = decimal_value(quantity_delta, "quantity delta")
+ price = decimal_value(unit_price, "unit price")
+ if delta <= 0:
+ raise ValueError("New position quantity must be greater than zero")
+ if price < 0:
+ raise ValueError("Unit price cannot be negative")
+ _validate_system_section(db, agreement.project_id, system_id, section_id)
+ source_boq_document_id = _validate_source_document(
+ db, agreement.project_id, source_boq_document_id
+ )
+ if agreement.boq_document_id is not None and source_boq_document_id not in (None, agreement.boq_document_id):
+ raise ValueError("Position BOQ must match the agreement scope")
+ item = boq.WorkItem(
+ project_id=agreement.project_id,
+ boq_document_id=None,
+ system_id=system_id,
+ section_id=section_id,
+ name=name,
+ model=(model or "").strip() or None,
+ manufacturer=(manufacturer or "").strip() or None,
+ unit=(unit or "").strip() or None,
+ quantity=Decimal("0"),
+ amount=Decimal("0"),
+ unit_price=price,
+ )
+ db.add(item)
+ db.flush()
+ line = AgreementItem(
+ agreement_id=agreement.id,
+ work_item_id=item.id,
+ change_type="new_position",
+ quantity_delta=delta,
+ amount_delta=delta * price,
+ source_name=item.name,
+ source_model=item.model,
+ source_manufacturer=item.manufacturer,
+ source_unit=item.unit,
+ source_unit_price=price,
+ source_system_id=system_id,
+ source_section_id=section_id,
+ source_boq_document_id=source_boq_document_id,
+ )
+ db.add(line)
+ db.flush()
+ return line
+
+
+def update_draft_item(db, agreement, line, *, quantity_delta, unit_price=None,
+ name=None, model=None, manufacturer=None, unit=None,
+ system_id=None, section_id=None):
+ _require_draft(agreement)
+ delta = decimal_value(quantity_delta, "quantity delta")
+ if delta == 0 or (line.change_type == "new_position" and delta < 0):
+ raise ValueError("Invalid quantity delta")
+ 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("WorkItem not found in this project")
+ if line.change_type == "new_position":
+ price = decimal_value(unit_price, "unit price")
+ if price < 0:
+ raise ValueError("Unit price cannot be negative")
+ name = (name or "").strip()
+ if not name:
+ raise ValueError("Position name is required")
+ _validate_system_section(db, agreement.project_id, system_id, section_id)
+ item.name = name
+ item.model = (model or "").strip() or None
+ item.manufacturer = (manufacturer or "").strip() or None
+ item.unit = (unit or "").strip() or None
+ item.system_id = system_id
+ item.section_id = section_id
+ item.unit_price = price
+ line.source_name = item.name
+ line.source_model = item.model
+ line.source_manufacturer = item.manufacturer
+ line.source_unit = item.unit
+ line.source_unit_price = price
+ line.source_system_id = system_id
+ line.source_section_id = section_id
+ else:
+ plan = build_effective_plan(db, agreement.project_id)
+ row = next((entry for entry in plan["items"] if entry.item.id == item.id), None)
+ if row is None:
+ raise ValueError("WorkItem is not part of the current effective plan")
+ if agreement.boq_document_id is not None and work_item_scope_document_id(db, item) != agreement.boq_document_id:
+ raise ValueError("WorkItem is outside this agreement scope")
+ if row.quantity + delta < 0:
+ raise ValueError("Effective quantity cannot become negative")
+ rate = _unit_rate(row)
+ line.change_type = "increase" if delta > 0 else "decrease"
+ line.source_unit_price = rate
+ line.quantity_delta = delta
+ price = decimal_value(line.source_unit_price, "unit price")
+ line.amount_delta = delta * price
+ db.flush()
+ return line
+
+
+def delete_draft_item(db, agreement, line):
+ _require_draft(agreement)
+ item = line.work_item
+ is_new = line.change_type == "new_position"
+ db.delete(line)
+ db.flush()
+ if is_new and item is not None:
+ 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()
diff --git a/app/services/effective_plan.py b/app/services/effective_plan.py
index 8fd8119..986f314 100644
--- a/app/services/effective_plan.py
+++ b/app/services/effective_plan.py
@@ -46,20 +46,24 @@ def _validate_agreement_scope(db: Session, agreement: Agreement):
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
+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",
- ).first()
- return origin[1].boq_document_id if origin else None
+ ).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):
@@ -95,7 +99,7 @@ def build_effective_plan(db: Session, project_id: int):
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:
+ 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}"
)
@@ -103,10 +107,30 @@ def build_effective_plan(db: Session, project_id: int):
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"
- )
+ 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}
@@ -192,13 +216,24 @@ def approve_agreement(db: Session, agreement_id: int):
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.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
@@ -206,7 +241,7 @@ def approve_agreement(db: Session, agreement_id: int):
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:
+ 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])
diff --git a/app/services/project_dashboard.py b/app/services/project_dashboard.py
index 070704f..6db667c 100644
--- a/app/services/project_dashboard.py
+++ b/app/services/project_dashboard.py
@@ -90,7 +90,7 @@ def build_project_dashboard(db, project_obj):
system_names = sorted({item.system.name for _line, item in report_lines if item.system})
recent_report_rows.append({
"report": report,
- "systems": system_names or ([report.system.name] if report.system else []),
+ "systems": system_names or ([report.system.name] if report.system else ["??????? ??? ???????"]),
"item_count": len(report_lines),
"volume": report_volume,
})
diff --git a/app/templates/agreements/detail.html b/app/templates/agreements/detail.html
new file mode 100644
index 0000000..19a326f
--- /dev/null
+++ b/app/templates/agreements/detail.html
@@ -0,0 +1,24 @@
+
ДС №{{ agreement.number }} — {{ project.name }}
+
+{% if error %}{{ error }}
{% endif %}
+ДС №{{ agreement.number }} — {{ agreement.title }}
{{ agreement.date.strftime('%d.%m.%Y') }} · {{ scope_label }}
К списку{% if agreement.status == 'approved' %}
Утверждено{% else %}
Черновик{% endif %}
+{% if agreement.status == 'draft' %}
+
+{% else %}Номер: {{ agreement.number }}
Дата: {{ agreement.date.strftime('%d.%m.%Y') }}
Область: {{ scope_label }}
Описание: {{ agreement.description or '—' }}
{% endif %}
+
+{% if agreement.status == 'draft' %}
+
+
+ДС №{{ agreement.number }}
Область: {{ scope_label }}
Количество позиций: {{ line_rows|length }}
После утверждения изменения нельзя редактировать.
+{% else %}ДС утверждено. Изменения недоступны.
{% endif %}
+
diff --git a/app/templates/agreements/list.html b/app/templates/agreements/list.html
new file mode 100644
index 0000000..adf4b35
--- /dev/null
+++ b/app/templates/agreements/list.html
@@ -0,0 +1,5 @@
+Дополнительные соглашения — {{ project.name }}
+
+Дополнительные соглашения
{{ project.name }}
+ Создать ДС
+| Номер | Дата | Наименование | Область | Статус | Позиций | |
+{% for row in rows %}| {{ row.agreement.number }} | {{ row.agreement.date.strftime('%d.%m.%Y') }} | {{ row.agreement.title }} | {{ row.scope_label }} | {% if row.agreement.status == 'approved' %}Утверждено{% else %}Черновик{% endif %} | {{ row.item_count }} | Открыть |
{% else %}| ДС пока нет. |
{% endfor %}
diff --git a/app/templates/agreements/new.html b/app/templates/agreements/new.html
new file mode 100644
index 0000000..ab82c61
--- /dev/null
+++ b/app/templates/agreements/new.html
@@ -0,0 +1,6 @@
+Новое ДС — {{ project.name }}
+Создать ДС
+{% if error %}{{ error }}
{% endif %}
diff --git a/app/templates/projects/daily_report_form.html b/app/templates/projects/daily_report_form.html
index cbcb98f..622f64a 100644
--- a/app/templates/projects/daily_report_form.html
+++ b/app/templates/projects/daily_report_form.html
@@ -16,13 +16,14 @@
{% if report %}При смене системы сначала нажмите «Показать позиции»; несохранённые изменения формы будут сброшены.
{% endif %}
- {% if selected_system %}
+ {% if selected_system or unclassified_selected %}