feat: add agreement workflow and project-scoped work items

This commit is contained in:
Александр Арсентьев
2026-09-25 20:33:07 +03:00
parent d0b5745f8f
commit e72ba68cad
20 changed files with 1155 additions and 68 deletions
+68
View File
@@ -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]}")
+2 -1
View File
@@ -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():
+2
View File
@@ -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])
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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())
+392
View File
@@ -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)
+48 -29
View File
@@ -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 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")
rows = _report_rows(db, project_obj.id, system_id, exclude_id)
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_quantities.get(row["item"].id)
planned = row["planned_quantity"]
current = Decimal(str(row["current_quantity"] or 0))
row["over_plan"] = row["accumulated"] + current > planned
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
+241
View File
@@ -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()
+48 -13
View File
@@ -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,9 +107,29 @@ 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:
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} is not backed by its agreement source document"
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)
@@ -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":
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} must reference an item from its agreement document")
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])
+1 -1
View File
@@ -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,
})
+24
View File
@@ -0,0 +1,24 @@
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>ДС №{{ agreement.number }} — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>.numeric{font-variant-numeric:tabular-nums;white-space:nowrap}.item-name{min-width:16rem}</style></head><body class="bg-light"><main class="container-fluid container-xxl py-4">
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1099;</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">&#1044;&#1057;</a></li><li class="breadcrumb-item active">&#8470;{{ agreement.number }}</li></ol></nav>
{% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %}
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4"><div><h1 class="h2 mb-1">&#1044;&#1057; &#8470;{{ agreement.number }} — {{ agreement.title }}</h1><div class="text-muted">{{ agreement.date.strftime('%d.%m.%Y') }} · {{ scope_label }}</div></div><div class="d-flex gap-2"><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">&#1050; &#1089;&#1087;&#1080;&#1089;&#1082;&#1091;</a>{% if agreement.status == 'approved' %}<span class="badge text-bg-success align-self-center">&#1059;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1086;</span>{% else %}<span class="badge text-bg-secondary align-self-center">&#1063;&#1077;&#1088;&#1085;&#1086;&#1074;&#1080;&#1082;</span>{% endif %}</div></header>
{% if agreement.status == 'draft' %}
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white"><h2 class="h5 mb-0">&#1056;&#1077;&#1082;&#1074;&#1080;&#1079;&#1080;&#1090;&#1099; &#1044;&#1057;</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/update"><div class="card-body row g-3">
<div class="col-md-3"><label class="form-label">&#1053;&#1086;&#1084;&#1077;&#1088;</label><input class="form-control" name="number" value="{{ agreement.number }}" required></div><div class="col-md-3"><label class="form-label">&#1044;&#1072;&#1090;&#1072;</label><input class="form-control" type="date" name="agreement_date" value="{{ agreement.date.isoformat() }}" required></div><div class="col-md-6"><label class="form-label">&#1053;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;</label><input class="form-control" name="title" value="{{ agreement.title }}" required></div><div class="col-12"><label class="form-label">&#1054;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1077;</label><textarea class="form-control" name="description" rows="2">{{ agreement.description or '' }}</textarea></div>
<div class="col-md-7"><label class="form-label">&#1054;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100; &#1087;&#1088;&#1080;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103;</label><select class="form-select" name="scope" required><option value="project" {% if agreement.boq_document_id is none %}selected{% endif %}>&#1042;&#1077;&#1089;&#1100; &#1087;&#1088;&#1086;&#1077;&#1082;&#1090;</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.name }}</option>{% endfor %}</select></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary" type="submit">&#1057;&#1086;&#1093;&#1088;&#1072;&#1085;&#1080;&#1090;&#1100; &#1088;&#1077;&#1082;&#1074;&#1080;&#1079;&#1080;&#1090;&#1099;</button></div></form></section>
{% else %}<section class="card border-0 shadow-sm mb-4"><div class="card-body row g-3"><div class="col-md-3"><span class="text-muted">&#1053;&#1086;&#1084;&#1077;&#1088;:</span> <strong>{{ agreement.number }}</strong></div><div class="col-md-3"><span class="text-muted">&#1044;&#1072;&#1090;&#1072;:</span> {{ agreement.date.strftime('%d.%m.%Y') }}</div><div class="col-md-6"><span class="text-muted">&#1054;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;:</span> {{ scope_label }}</div><div class="col-12"><span class="text-muted">&#1054;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1077;:</span> {{ agreement.description or '—' }}</div></div></section>{% endif %}
<section class="card border-0 shadow-sm mb-4"><div class="card-header bg-white d-flex justify-content-between"><h2 class="h5 mb-0">&#1055;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1044;&#1057;</h2><span>{{ line_rows|length }} &#1087;&#1086;&#1079;.</span></div><div class="table-responsive"><table class="table table-hover align-middle mb-0"><thead><tr><th>&#1058;&#1080;&#1087;</th><th>&#8470; / &#1055;&#1086;&#1079;&#1080;&#1094;&#1080;&#1103;</th><th>&#1045;&#1076;.</th><th class="text-end">&#1041;&#1072;&#1079;&#1086;&#1074;&#1086;&#1077; / &#1090;&#1077;&#1082;&#1091;&#1097;&#1077;&#1077;</th><th class="text-end">&#1048;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1077;</th><th class="text-end">&#1055;&#1086;&#1089;&#1083;&#1077; &#1044;&#1057;</th><th class="text-end">&#1057;&#1091;&#1084;&#1084;&#1072; &#1080;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103;</th><th></th></tr></thead><tbody>
{% for row in line_rows %}<tr><td>{% if row.line.change_type == 'new_position' %}<span class="badge text-bg-info">&#1053;&#1086;&#1074;&#1072;&#1103;</span>{% elif row.line.change_type == 'decrease' %}<span class="badge text-bg-warning">&#1059;&#1084;&#1077;&#1085;&#1100;&#1096;&#1077;&#1085;&#1080;&#1077;</span>{% else %}<span class="badge text-bg-primary">&#1059;&#1074;&#1077;&#1083;&#1080;&#1095;&#1077;&#1085;&#1080;&#1077;</span>{% endif %}</td><td class="item-name"><div class="fw-semibold">{{ row.item.source_number or '' }} {{ row.item.name }}</div><small class="text-muted">{{ row.item.model or '' }}{% if row.item.manufacturer %} · {{ row.item.manufacturer }}{% endif %}</small></td><td>{{ row.item.unit or '—' }}</td><td class="text-end numeric">{{ row.before_quantity }}</td><td class="text-end numeric">{{ row.line.quantity_delta }}</td><td class="text-end numeric">{{ row.after_quantity }}</td><td class="text-end numeric">{{ row.amount_delta|money(project.currency) }}</td><td class="text-end">{% if agreement.status == 'draft' %}<button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#edit-line-{{ row.line.id }}">&#1055;&#1088;&#1072;&#1074;&#1080;&#1090;&#1100;</button><form class="d-inline" method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/{{ row.line.id }}/delete" onsubmit="return confirm('Удалить позицию из черновика?')"><button class="btn btn-sm btn-outline-danger">&times;</button></form>{% endif %}</td></tr>
{% if agreement.status == 'draft' %}<tr class="collapse" id="edit-line-{{ row.line.id }}"><td colspan="8"><form class="row g-2" method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/{{ row.line.id }}/edit"><div class="col-md-2"><label class="form-label">&#916; &#1082;&#1086;&#1083;-&#1074;&#1086;</label><input class="form-control" type="number" step="0.0001" name="quantity_delta" value="{{ row.line.quantity_delta }}" required></div>{% if row.line.change_type == 'new_position' %}<div class="col-md-2"><label class="form-label">&#1048;&#1084;&#1103;</label><input class="form-control" name="name" value="{{ row.item.name }}" required></div><div class="col-md-2"><label class="form-label">&#1052;&#1086;&#1076;&#1077;&#1083;&#1100;</label><input class="form-control" name="model" value="{{ row.item.model or '' }}"></div><div class="col-md-2"><label class="form-label">&#1055;&#1088;&#1086;&#1080;&#1079;&#1074;.</label><input class="form-control" name="manufacturer" value="{{ row.item.manufacturer or '' }}"></div><div class="col-md-2"><label class="form-label">&#1045;&#1076;.</label><input class="form-control" name="unit" value="{{ row.item.unit or '' }}"></div><div class="col-md-2"><label class="form-label">&#1062;&#1077;&#1085;&#1072;</label><input class="form-control" type="number" step="0.000000000001" name="unit_price" value="{{ row.item.unit_price }}" required></div><div class="col-md-3"><label class="form-label">&#1057;&#1080;&#1089;&#1090;&#1077;&#1084;&#1072;</label><select class="form-select system-select" name="system_id" required>{% for system in systems %}<option value="{{ system.id }}" {% if row.item.system_id == system.id %}selected{% endif %}>{{ system.name }}</option>{% endfor %}</select></div><div class="col-md-3"><label class="form-label">&#1056;&#1072;&#1079;&#1076;&#1077;&#1083;</label><select class="form-select section-select" name="section_id" required>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}" {% if row.item.section_id == section.id %}selected{% endif %}>{{ section.name }}</option>{% endfor %}</select></div>{% endif %}<div class="col-md-2 align-self-end"><button class="btn btn-primary">&#1057;&#1086;&#1093;&#1088;&#1072;&#1085;&#1080;&#1090;&#1100;</button></div></form></td></tr>{% endif %}
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">&#1055;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1077;&#1097;&#1105; &#1085;&#1077; &#1076;&#1086;&#1073;&#1072;&#1074;&#1083;&#1077;&#1085;&#1099;.</td></tr>{% endfor %}</tbody></table></div><div class="card-footer bg-white d-flex justify-content-between"><span class="text-muted">&#1057;&#1091;&#1084;&#1084;&#1072; &#1080;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103; &#1087;&#1083;&#1072;&#1085;&#1072;</span><strong>{{ change_amount|money(project.currency) }}</strong></div></section>
{% if agreement.status == 'draft' %}<div class="row g-4"><div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">&#1044;&#1086;&#1073;&#1072;&#1074;&#1080;&#1090;&#1100; &#1089;&#1091;&#1097;&#1077;&#1089;&#1090;&#1074;&#1091;&#1102;&#1097;&#1091;&#1102; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1102;</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/existing"><div class="card-body"><div class="mb-3 position-relative" data-position-picker><label class="form-label" for="existing-position-search">&#1055;&#1086;&#1079;&#1080;&#1094;&#1080;&#1103; &#1087;&#1088;&#1086;&#1077;&#1082;&#1090;&#1072;</label><div class="input-group"><input id="existing-position-search" class="form-control" type="search" autocomplete="off" placeholder="&#1055;&#1086;&#1080;&#1089;&#1082; &#1087;&#1086; &#1085;&#1086;&#1084;&#1077;&#1088;&#1091;, &#1085;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1102;, &#1084;&#1086;&#1076;&#1077;&#1083;&#1080;, &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1077;..." aria-expanded="false" aria-controls="existing-position-results" required><button class="btn btn-outline-secondary" type="button" data-clear-position>&#1054;&#1095;&#1080;&#1089;&#1090;&#1080;&#1090;&#1100;</button></div><input type="hidden" name="work_item_id" data-work-item-id><div class="form-text" data-selected-position aria-live="polite">&#1055;&#1086;&#1079;&#1080;&#1094;&#1080;&#1103; &#1085;&#1077; &#1074;&#1099;&#1073;&#1088;&#1072;&#1085;&#1072;</div><div id="existing-position-results" class="list-group position-absolute shadow bg-white" role="listbox" style="z-index:1050;max-height:18rem;overflow-y:auto;min-width:min(100%,40rem);display:none">{% for row in selectable_items %}<button type="button" class="list-group-item list-group-item-action autocomplete-position" role="option" data-id="{{ row.item.id }}" data-search="{{ row.item.source_number or '' }} {{ row.item.name }} {{ row.item.model or '' }} {{ row.item.manufacturer or '' }} {{ row.item.system.name if row.item.system else '' }} {{ row.item.section.name if row.item.section else '' }}" data-label="{{ row.item.system.name if row.item.system else '' }} ? {{ row.item.section.name if row.item.section else '' }} ? ?{{ row.item.source_number or '' }} ? {{ row.item.name }}{% if row.item.model %} ? {{ row.item.model }}{% endif %} ? {{ row.quantity }} {{ row.item.unit or '' }}"><span class="fw-semibold">{{ row.item.system.name if row.item.system else '' }} ? {{ row.item.section.name if row.item.section else '' }} ? ?{{ row.item.source_number or '?' }}</span><br>{{ row.item.name }}{% if row.item.model %} ? {{ row.item.model }}{% endif %}<small class="d-block text-muted">{{ row.item.manufacturer or '' }}{% if row.item.manufacturer %} ? {% endif %}{{ row.quantity }} {{ row.item.unit or '' }}</small></button>{% endfor %}<div class="list-group-item text-muted d-none" data-no-results>&#1053;&#1080;&#1095;&#1077;&#1075;&#1086; &#1085;&#1077; &#1085;&#1072;&#1081;&#1076;&#1077;&#1085;&#1086;.</div><div class="list-group-item text-muted d-none" data-more-results>&#1055;&#1086;&#1082;&#1072;&#1079;&#1072;&#1085;&#1099; &#1087;&#1077;&#1088;&#1074;&#1099;&#1077; 20 &#1088;&#1077;&#1079;&#1091;&#1083;&#1100;&#1090;&#1072;&#1090;&#1086;&#1074;. &#1059;&#1090;&#1086;&#1095;&#1085;&#1080;&#1090;&#1077; &#1087;&#1086;&#1080;&#1089;&#1082;.</div></div></div><div class="mb-3"><label class="form-label">&#916; &#1082;&#1086;&#1083;&#1080;&#1095;&#1077;&#1089;&#1090;&#1074;&#1086; (+ / −)</label><input class="form-control" type="number" step="0.0001" name="quantity_delta" required><div class="form-text">&#1044;&#1083;&#1103; &#1091;&#1084;&#1077;&#1085;&#1100;&#1096;&#1077;&#1085;&#1080;&#1103; &#1091;&#1082;&#1072;&#1078;&#1080;&#1090;&#1077; &#1086;&#1090;&#1088;&#1080;&#1094;&#1072;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;&#1077; &#1095;&#1080;&#1089;&#1083;&#1086;. &#1057;&#1091;&#1084;&#1084;&#1072; &#1088;&#1072;&#1089;&#1089;&#1095;&#1080;&#1090;&#1072;&#1077;&#1090;&#1089;&#1103; &#1087;&#1086; &#1094;&#1077;&#1085;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080;.</div></div>{% if not selectable_items %}<div class="text-muted small mb-3">&#1042; &#1101;&#1090;&#1086;&#1081; &#1086;&#1073;&#1083;&#1072;&#1089;&#1090;&#1080; &#1085;&#1077;&#1090; &#1085;&#1077;&#1076;&#1086;&#1073;&#1072;&#1074;&#1083;&#1077;&#1085;&#1085;&#1099;&#1093; &#1087;&#1086;&#1079;&#1080;&#1094;.</div>{% endif %}</div><div class="card-footer bg-white"><button class="btn btn-outline-primary" {% if not selectable_items %}disabled{% endif %}>&#1044;&#1086;&#1073;&#1072;&#1074;&#1080;&#1090;&#1100; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1102;</button></div></form></section></div>
<div class="col-xl-6"><section class="card border-0 shadow-sm h-100"><div class="card-header bg-white"><h2 class="h5 mb-0">&#1044;&#1086;&#1073;&#1072;&#1074;&#1080;&#1090;&#1100; &#1085;&#1086;&#1074;&#1091;&#1102; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1102;</h2></div><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/items/new" data-new-item-form data-system-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/systems" data-section-url="/projects/{{ project.id }}/agreements/{{ agreement.id }}/sections"><div class="card-body row g-3"><div class="col-12"><label class="form-label">&#1042;&#1077;&#1076;&#1086;&#1084;&#1086;&#1089;&#1090;&#1100; (&#1085;&#1077;&#1086;&#1073;&#1103;&#1079;&#1072;&#1090;&#1077;&#1083;&#1100;&#1085;&#1086;)</label><select class="form-select" name="source_boq_document_id"><option value="">&#1041;&#1077;&#1079; &#1074;&#1077;&#1076;&#1086;&#1084;&#1086;&#1089;&#1090;&#1080;</option>{% for doc in boq_documents %}<option value="{{ doc.id }}" {% if agreement.boq_document_id == doc.id %}selected{% endif %}>{{ doc.name }}</option>{% endfor %}</select></div><div class="col-md-6"><label class="form-label">&#1053;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;</label><input class="form-control" name="name" required></div><div class="col-md-6"><label class="form-label">&#1052;&#1086;&#1076;&#1077;&#1083;&#1100; / &#1072;&#1088;&#1090;&#1080;&#1082;&#1091;&#1083;</label><input class="form-control" name="model"></div><div class="col-md-6"><label class="form-label">&#1055;&#1088;&#1086;&#1080;&#1079;&#1074;&#1086;&#1076;&#1080;&#1090;&#1077;&#1083;&#1100;</label><input class="form-control" name="manufacturer"></div><div class="col-md-3"><label class="form-label">&#1045;&#1076;&#1080;&#1085;&#1080;&#1094;&#1072;</label><input class="form-control" name="unit"></div><div class="col-md-3"><label class="form-label">&#916; &#1082;&#1086;&#1083;-&#1074;&#1086;</label><input class="form-control" type="number" min="0.0001" step="0.0001" name="quantity_delta" required></div><div class="col-md-6"><label class="form-label">&#1062;&#1077;&#1085;&#1072; &#1079;&#1072; &#1077;&#1076;&#1080;&#1085;&#1080;&#1094;&#1091;</label><input class="form-control" type="number" min="0" step="0.000000000001" name="unit_price" required></div><div class="col-md-6"><label class="form-label">&#1057;&#1080;&#1089;&#1090;&#1077;&#1084;&#1072;</label><select class="form-select system-select" name="system_id" data-system-select><option value="">&#1041;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;</option>{% for system in systems %}<option value="{{ system.id }}">{{ system.name }}</option>{% endfor %}<option value="__new__">+ &#1053;&#1086;&#1074;&#1072;&#1103; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1072;...</option></select><div class="input-group mt-2 d-none" data-new-system-panel><input class="form-control" maxlength="255" placeholder="&#1053;&#1072;&#1079;&#1074;&#1072;&#1085;&#1080;&#1077; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;"><button type="button" class="btn btn-outline-primary" data-create-system>&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100;</button></div></div><div class="col-md-6"><label class="form-label">&#1056;&#1072;&#1079;&#1076;&#1077;&#1083;</label><select class="form-select section-select" name="section_id" data-section-select><option value="">&#1041;&#1077;&#1079; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;&#1072;</option>{% for section in sections %}<option value="{{ section.id }}" data-system="{{ section.system_id }}">{{ section.name }}</option>{% endfor %}<option value="__new__">+ &#1053;&#1086;&#1074;&#1099;&#1081; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;...</option></select><div class="input-group mt-2 d-none" data-new-section-panel><input class="form-control" maxlength="255" placeholder="&#1053;&#1072;&#1079;&#1074;&#1072;&#1085;&#1080;&#1077; &#1088;&#1072;&#1079;&#1076;&#1077;&#1083;&#1072;"><button type="button" class="btn btn-outline-primary" data-create-section>&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100;</button></div></div><div class="col-12 text-danger small" data-association-error role="alert"></div></div><div class="card-footer bg-white"><button class="btn btn-outline-primary">&#1044;&#1086;&#1073;&#1072;&#1074;&#1080;&#1090;&#1100; &#1085;&#1086;&#1074;&#1091;&#1102; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1102;</button></div></form></section></div></div>
<section class="d-flex justify-content-end mt-4"><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#approveModal" {% if not line_rows %}disabled{% endif %}>&#1059;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1100;</button></section>
<div class="modal fade" id="approveModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 class="modal-title fs-5">&#1055;&#1086;&#1076;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1077; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1080;&#1077;</h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div><strong>&#1044;&#1057; &#8470;{{ agreement.number }}</strong></div><div>&#1054;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;: {{ scope_label }}</div><div>&#1050;&#1086;&#1083;&#1080;&#1095;&#1077;&#1089;&#1090;&#1074;&#1086; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1081;: {{ line_rows|length }}</div><p class="text-warning mt-3 mb-0">&#1055;&#1086;&#1089;&#1083;&#1077; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1080;&#1103; &#1080;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103; &#1085;&#1077;&#1083;&#1100;&#1079;&#1103; &#1088;&#1077;&#1076;&#1072;&#1082;&#1090;&#1080;&#1088;&#1086;&#1074;&#1072;&#1090;&#1100;.</p></div><div class="modal-footer"><button class="btn btn-outline-secondary" data-bs-dismiss="modal">&#1054;&#1090;&#1084;&#1077;&#1085;&#1072;</button><form method="post" action="/projects/{{ project.id }}/agreements/{{ agreement.id }}/approve"><button class="btn btn-success">&#1059;&#1090;&#1074;&#1077;&#1088;&#1076;&#1080;&#1090;&#1100; &#1044;&#1057;</button></form></div></div></div></div>
{% else %}<div class="alert alert-info">&#1044;&#1057; &#1091;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1086;. &#1048;&#1079;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103; &#1085;&#1077;&#1076;&#1086;&#1089;&#1090;&#1091;&#1087;&#1085;&#1099;.</div>{% endif %}
</main><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script><script>
document.querySelectorAll('.system-select').forEach(systemSelect=>{const form=systemSelect.closest('form');const section=form.querySelector('.section-select');if(!section)return;const filter=()=>{const value=systemSelect.value;[...section.options].forEach(option=>{if(!option.dataset.system)return;option.hidden=!!value&&value!=='__new__'&&option.dataset.system!==value;});const selected=section.selectedOptions[0];if(selected&&selected.dataset.system&&selected.hidden)section.value='';};systemSelect.addEventListener('change',filter);filter();});
const makeOption=(select,id,name,attributes={})=>{const option=document.createElement('option');option.value=id;option.textContent=name;Object.entries(attributes).forEach(([key,value])=>option.dataset[key]=value);const createOption=[...select.options].find(item=>item.value==='__new__');select.insertBefore(option,createOption||null);select.value=String(id);};
document.querySelectorAll('[data-new-item-form]').forEach(form=>{const system=form.querySelector('[data-system-select]');const section=form.querySelector('[data-section-select]');const systemPanel=form.querySelector('[data-new-system-panel]');const sectionPanel=form.querySelector('[data-new-section-panel]');const error=form.querySelector('[data-association-error]');const showError=message=>{error.textContent=message||'';};const filterSections=()=>{const selected=system.value;[...section.options].forEach(option=>{if(option.dataset.system)option.hidden=!selected||selected==='__new__'||option.dataset.system!==selected;});};system.addEventListener('change',()=>{section.value='';sectionPanel.classList.add('d-none');systemPanel.classList.toggle('d-none',system.value!=='__new__');if(system.value==='__new__'){section.value='';section.disabled=true;}else{section.disabled=!system.value;filterSections();}});section.addEventListener('change',()=>sectionPanel.classList.toggle('d-none',section.value!=='__new__'));const createEntity=async(url,values)=>{showError('');const response=await fetch(url,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(values)});const payload=await response.json();if(!response.ok)throw new Error(payload.detail||'?? ??????? ???????');return payload;};form.querySelector('[data-create-system]').addEventListener('click',async()=>{const input=systemPanel.querySelector('input');try{const entity=await createEntity(form.dataset.systemUrl,{name:input.value});makeOption(system,entity.id,entity.name);systemPanel.classList.add('d-none');system.disabled=false;section.disabled=false;section.value='';filterSections();input.value='';}catch(errorValue){showError(errorValue.message);}});form.querySelector('[data-create-section]').addEventListener('click',async()=>{const input=sectionPanel.querySelector('input');if(!system.value||system.value==='__new__'){showError('??????? ???????? ??? ???????? ???????');return;}try{const entity=await createEntity(form.dataset.sectionUrl,{system_id:system.value,name:input.value});makeOption(section,entity.id,entity.name,{system:entity.system_id});sectionPanel.classList.add('d-none');input.value='';}catch(errorValue){showError(errorValue.message);}});form.addEventListener('submit',event=>{if(system.value==='__new__'||section.value==='__new__'){event.preventDefault();showError('??????? ????????? ????? ??????? ??? ??????');}});});
document.querySelectorAll('[data-position-picker]').forEach(picker=>{const input=picker.querySelector('input[type="search"]');const hidden=picker.querySelector('[data-work-item-id]');const menu=picker.querySelector('[role="listbox"]');const options=[...picker.querySelectorAll('.autocomplete-position')];const selected=picker.querySelector('[data-selected-position]');const noResults=picker.querySelector('[data-no-results]');const more=picker.querySelector('[data-more-results]');const normalize=value=>value.toLocaleLowerCase().trim().replace(/\s+/g,' ');const close=()=>{menu.style.display='none';input.setAttribute('aria-expanded','false');};const render=()=>{const query=normalize(input.value);let shown=0;let matches=0;options.forEach(option=>{const match=!query||normalize(option.dataset.search).includes(query);if(match){matches++;option.hidden=shown>=20;if(!option.hidden)shown++;}else option.hidden=true;});noResults.classList.toggle('d-none',matches!==0);more.classList.toggle('d-none',matches<=20);menu.style.display='block';input.setAttribute('aria-expanded','true');};input.addEventListener('focus',render);input.addEventListener('input',()=>{hidden.value='';selected.textContent='\u041f\u043e\u0437\u0438\u0446\u0438\u044f \u043d\u0435 \u0432\u044b\u0431\u0440\u0430\u043d\u0430';input.setCustomValidity('\u0412\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u043f\u043e\u0437\u0438\u0446\u0438\u044e \u0438\u0437 \u0441\u043f\u0438\u0441\u043a\u0430');render();});options.forEach(option=>option.addEventListener('click',()=>{hidden.value=option.dataset.id;input.value=option.dataset.label;selected.textContent='\u0412\u044b\u0431\u0440\u0430\u043d\u043e: '+option.dataset.label;input.setCustomValidity('');close();}));picker.querySelector('[data-clear-position]').addEventListener('click',()=>{hidden.value='';input.value='';selected.textContent='\u041f\u043e\u0437\u0438\u0446\u0438\u044f \u043d\u0435 \u0432\u044b\u0431\u0440\u0430\u043d\u0430';input.setCustomValidity('\u0412\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u043f\u043e\u0437\u0438\u0446\u0438\u044e \u0438\u0437 \u0441\u043f\u0438\u0441\u043a\u0430');input.focus();render();});picker.closest('form').addEventListener('submit',event=>{if(!hidden.value){input.setCustomValidity('\u0412\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u043f\u043e\u0437\u0438\u0446\u0438\u044e \u0438\u0437 \u0441\u043f\u0438\u0441\u043a\u0430');input.reportValidity();event.preventDefault();}});document.addEventListener('click',event=>{if(!picker.contains(event.target))close();});});
</script></body></html>
+5
View File
@@ -0,0 +1,5 @@
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>&#1044;&#1086;&#1087;&#1086;&#1083;&#1085;&#1080;&#1090;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077; &#1089;&#1086;&#1075;&#1083;&#1072;&#1096;&#1077;&#1085;&#1080;&#1103; — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light"><main class="container py-4">
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1099;</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item active">&#1044;&#1086;&#1087;&#1086;&#1083;&#1085;&#1080;&#1090;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077; &#1089;&#1086;&#1075;&#1083;&#1072;&#1096;&#1077;&#1085;&#1080;&#1103;</li></ol></nav>
<header class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4"><div><h1 class="h2 mb-1">&#1044;&#1086;&#1087;&#1086;&#1083;&#1085;&#1080;&#1090;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077; &#1089;&#1086;&#1075;&#1083;&#1072;&#1096;&#1077;&#1085;&#1080;&#1103;</h1><div class="text-muted">{{ project.name }}</div></div><a class="btn btn-primary" href="/projects/{{ project.id }}/agreements/new">+ &#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100; &#1044;&#1057;</a></header>
<section class="card border-0 shadow-sm"><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>&#1053;&#1086;&#1084;&#1077;&#1088;</th><th>&#1044;&#1072;&#1090;&#1072;</th><th>&#1053;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;</th><th>&#1054;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;</th><th>&#1057;&#1090;&#1072;&#1090;&#1091;&#1089;</th><th class="text-end">&#1055;&#1086;&#1079;&#1080;&#1094;&#1080;&#1081;</th><th></th></tr></thead><tbody>
{% for row in rows %}<tr><td class="fw-semibold">{{ row.agreement.number }}</td><td>{{ row.agreement.date.strftime('%d.%m.%Y') }}</td><td>{{ row.agreement.title }}</td><td>{{ row.scope_label }}</td><td>{% if row.agreement.status == 'approved' %}<span class="badge text-bg-success">&#1059;&#1090;&#1074;&#1077;&#1088;&#1078;&#1076;&#1077;&#1085;&#1086;</span>{% else %}<span class="badge text-bg-secondary">&#1063;&#1077;&#1088;&#1085;&#1086;&#1074;&#1080;&#1082;</span>{% endif %}</td><td class="text-end">{{ row.item_count }}</td><td class="text-end"><a class="btn btn-sm btn-outline-primary" href="/projects/{{ project.id }}/agreements/{{ row.agreement.id }}">&#1054;&#1090;&#1082;&#1088;&#1099;&#1090;&#1100;</a></td></tr>{% else %}<tr><td colspan="7" class="text-center text-muted py-5">&#1044;&#1057; &#1087;&#1086;&#1082;&#1072; &#1085;&#1077;&#1090;.</td></tr>{% endfor %}</tbody></table></div></section></main></body></html>
+6
View File
@@ -0,0 +1,6 @@
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>&#1053;&#1086;&#1074;&#1086;&#1077; &#1044;&#1057; — {{ project.name }}</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light"><main class="container py-4">
<nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1099;</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/agreements">&#1044;&#1057;</a></li><li class="breadcrumb-item active">&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100;</li></ol></nav><h1 class="h2 mb-4">&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100; &#1044;&#1057;</h1>
{% if error %}<div class="alert alert-danger">{{ error }}</div>{% endif %}<form class="card border-0 shadow-sm" method="post" action="/projects/{{ project.id }}/agreements"><div class="card-body row g-3">
<div class="col-md-4"><label class="form-label" for="number">&#1053;&#1086;&#1084;&#1077;&#1088;</label><input class="form-control" id="number" name="number" required maxlength="100"></div><div class="col-md-4"><label class="form-label" for="agreement_date">&#1044;&#1072;&#1090;&#1072;</label><input class="form-control" type="date" id="agreement_date" name="agreement_date" value="{{ today }}" required></div><div class="col-md-4"><label class="form-label" for="title">&#1053;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;</label><input class="form-control" id="title" name="title" required maxlength="255"></div>
<div class="col-12"><label class="form-label" for="description">&#1054;&#1087;&#1080;&#1089;&#1072;&#1085;&#1080;&#1077;</label><textarea class="form-control" id="description" name="description" rows="3"></textarea></div><div class="col-md-7"><label class="form-label" for="scope">&#1054;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100; &#1087;&#1088;&#1080;&#1084;&#1077;&#1085;&#1077;&#1085;&#1080;&#1103;</label><select class="form-select" id="scope" name="scope" required><option value="project">&#1042;&#1077;&#1089;&#1100; &#1087;&#1088;&#1086;&#1077;&#1082;&#1090;</option>{% for doc in boq_documents %}<option value="boq:{{ doc.id }}">{{ doc.name }}</option>{% endfor %}</select></div>
{% if not boq_documents %}<div class="col-12"><div class="alert alert-warning mb-0">&#1042; &#1087;&#1088;&#1086;&#1077;&#1082;&#1090;&#1077; &#1085;&#1077;&#1090; &#1042;&#1077;&#1076;&#1086;&#1084;&#1086;&#1089;&#1090;&#1077;&#1081;. &#1052;&#1086;&#1078;&#1085;&#1086; &#1074;&#1099;&#1073;&#1088;&#1072;&#1090;&#1100; &#1086;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100; &laquo;&#1042;&#1077;&#1089;&#1100; &#1087;&#1088;&#1086;&#1077;&#1082;&#1090;&raquo;.</div></div>{% endif %}</div><div class="card-footer bg-white d-flex gap-2"><button class="btn btn-primary" type="submit">&#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100; &#1095;&#1077;&#1088;&#1085;&#1086;&#1074;&#1080;&#1082;</button><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/agreements">&#1054;&#1090;&#1084;&#1077;&#1085;&#1072;</a></div></form></main></body></html>
@@ -16,13 +16,14 @@
<div class="d-flex gap-2"><select id="system-picker" name="system_id" class="form-select" required>
<option value="">Выберите систему</option>
{% for system in systems %}<option value="{{ system.id }}" {% if selected_system and selected_system.id == system.id %}selected{% endif %}>{{ system.name }}</option>{% endfor %}
{% if has_unclassified_items %}<option value="unclassified" {% if unclassified_selected %}selected{% endif %}>&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1085;&#1099;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1073;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;</option>{% endif %}
</select><button class="btn btn-outline-primary" type="submit">Показать позиции</button></div>
{% if report %}<div class="form-text">При смене системы сначала нажмите «Показать позиции»; несохранённые изменения формы будут сброшены.</div>{% endif %}
</form>
{% if selected_system %}
{% if selected_system or unclassified_selected %}
<form method="post" action="{% if report %}/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit{% else %}/projects/{{ project.id }}/daily-reports{% endif %}">
<input type="hidden" name="system_id" value="{{ selected_system.id }}">
<input type="hidden" name="system_id" value="{{ selected_system.id if selected_system else 'unclassified' }}">
<div class="card card-body mb-3">
<div class="row g-3">
<div class="col-md-4"><label for="report-date" class="form-label">Дата отчёта</label><input id="report-date" class="form-control" type="date" name="report_date" required value="{{ report.report_date.isoformat() if report else '' }}"></div>
@@ -30,7 +31,7 @@
</div>
</div>
<div class="card">
<div class="card-header"><strong>{{ selected_system.name }}</strong> — укажите фактическое количество хотя бы для одной позиции</div>
<div class="card-header"><strong>{{ selected_system.name if selected_system else '&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1085;&#1099;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1073;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;' }}</strong> — укажите фактическое количество хотя бы для одной позиции</div>
<div class="p-3 border-bottom">
<label class="form-label" for="position-search">Поиск позиций</label>
<input id="position-search" class="form-control" type="search" autocomplete="off" placeholder="Номер, наименование, модель или производитель">
@@ -8,7 +8,7 @@
<body class="bg-light">
<main class="container py-4">
<nav class="mb-3"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/daily-reports">Daily Reports</a></li><li class="breadcrumb-item active">{{ report.report_date.strftime('%d.%m.%Y') }}</li></ol></nav>
<div class="d-flex justify-content-between align-items-start mb-4"><div><h1>Daily Report</h1><div class="text-muted">{{ report.report_date.strftime('%d.%m.%Y') }} · {{ report.system.name }}</div>{% if report.notes %}<p class="mt-2">{{ report.notes }}</p>{% endif %}</div><a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit">Редактировать</a></div>
<div class="d-flex justify-content-between align-items-start mb-4"><div><h1>Daily Report</h1><div class="text-muted">{{ report.report_date.strftime('%d.%m.%Y') }} · {{ report.system.name if report.system else '&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1085;&#1099;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1073;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;' }}</div>{% if report.notes %}<p class="mt-2">{{ report.notes }}</p>{% endif %}</div><a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit">Редактировать</a></div>
{% if warnings %}<div class="alert alert-warning"><strong>Превышен план по {{ warnings|length }} позициям.</strong> Фактическое выполнение сохранено.</div>{% endif %}
<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>
+1 -1
View File
@@ -13,7 +13,7 @@
<div class="list-group shadow-sm">
{% for report in reports %}
<a href="/projects/{{ project.id }}/daily-reports/{{ report.id }}" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
<span><strong>{{ report.report_date.strftime('%d.%m.%Y') }}</strong> — {{ report.system.name }}{% if report.notes %}<br><small class="text-muted">{{ report.notes }}</small>{% endif %}</span>
<span><strong>{{ report.report_date.strftime('%d.%m.%Y') }}</strong> — {{ report.system.name if report.system else '&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1085;&#1099;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1073;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;' }}{% if report.notes %}<br><small class="text-muted">{{ report.notes }}</small>{% endif %}</span>
<span class="badge text-bg-primary rounded-pill">{{ report.items|length }} поз.</span>
</a>
{% endfor %}
+1
View File
@@ -32,6 +32,7 @@
<div class="d-flex flex-wrap gap-2">
<a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/edit">Редактировать</a>
<a class="btn btn-outline-primary" href="/boq/{{ project.id }}">Ведомости</a>
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/agreements">&#1044;&#1086;&#1087;&#1086;&#1083;&#1085;&#1080;&#1090;&#1077;&#1083;&#1100;&#1085;&#1099;&#1077; &#1089;&#1086;&#1075;&#1083;&#1072;&#1096;&#1077;&#1085;&#1080;&#1103;</a>
<a class="btn btn-outline-primary" href="/projects/{{ project.id }}/daily-reports">Daily Reports{% if daily_reports_count %} ({{ daily_reports_count }}){% endif %}</a>
<a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/new">Создать Daily Report</a>
</div>
+287
View File
@@ -0,0 +1,287 @@
from datetime import date
from decimal import Decimal
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database.database import Base
from app.main import app
from app.models.project import Project
from app.models import boq
from app.models.agreement import Agreement, AgreementItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.routers import projects as project_router, daily_reports, agreements as agreement_router
from app.services.effective_plan import build_effective_plan
def test_agreement_ui_draft_then_approval_updates_plan_and_daily_reports():
from app.models import work_journal as work_journal_models
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
TestingSession = sessionmaker(bind=engine, expire_on_commit=False)
with TestingSession() as db:
project = Project(name="Agreement UI project")
db.add(project); db.flush()
system = boq.System(project_id=project.id, name="System A", sort_order=1)
db.add(system); db.flush()
section = boq.Section(system_id=system.id, name="Section A")
db.add(section); db.flush()
doc = boq.BoqDocument(project_id=project.id, name="Base BOQ")
db.add(doc); db.flush()
base_item = boq.WorkItem(project_id=project.id, boq_document_id=doc.id,
system_id=system.id, section_id=section.id,
source_number="1", name="Existing item", unit="pcs",
quantity=100, unit_price=10, amount=1000)
db.add(base_item); db.commit()
project_id, doc_id = project.id, doc.id
system_id, section_id, base_item_id = system.id, section.id, base_item.id
def override_db():
db = TestingSession()
try:
yield db
finally:
db.close()
for dependency in (project_router.get_db, daily_reports.get_db, agreement_router.get_db):
app.dependency_overrides[dependency] = override_db
try:
with TestClient(app) as client:
assert client.get(f"/projects/{project_id}/agreements").status_code == 200
form = client.get(f"/projects/{project_id}/agreements/new")
assert form.status_code == 200 and f"boq:{doc_id}" in form.text
created = client.post(f"/projects/{project_id}/agreements", data={
"number": "A-1", "agreement_date": "2026-09-25", "title": "Scope test",
"description": "UI workflow", "scope": f"boq:{doc_id}",
}, follow_redirects=False)
assert created.status_code == 303
detail_url = created.headers["location"]
detail = client.get(detail_url)
assert detail.status_code == 200 and "approveModal" in detail.text
assert "data-position-picker" in detail.text
assert 'name="work_item_id"' in detail.text
assert f'data-id="{base_item_id}"' in detail.text
assert "data-search=" in detail.text and "Existing item" in detail.text
assert "replace(/\\s+/g,' ')" in detail.text and "shown>=20" in detail.text
agreement_id = int(detail_url.rsplit("/", 1)[1])
existing = client.post(f"{detail_url}/items/existing", data={
"work_item_id": base_item_id, "quantity_delta": "5",
}, follow_redirects=False)
assert existing.status_code == 303
existing_line = db.query(AgreementItem).filter_by(agreement_id=agreement_id).one()
edited_existing = client.post(f"{detail_url}/items/{existing_line.id}/edit", data={
"quantity_delta": "6",
}, follow_redirects=False)
assert edited_existing.status_code == 303
edited_meta = client.post(f"{detail_url}/update", data={
"number": "A-1", "agreement_date": "2026-09-25", "title": "Scope test edited",
"description": "Edited description", "scope": f"boq:{doc_id}",
}, follow_redirects=False)
assert edited_meta.status_code == 303
with TestingSession() as db:
draft_plan = build_effective_plan(db, project_id)
assert next(row for row in draft_plan["items"] if row.item.id == base_item_id).quantity == Decimal("100.0000")
assert db.query(boq.WorkItem).filter_by(project_id=project_id).count() == 1
added_new = client.post(f"{detail_url}/items/new", data={
"name": "New draft item", "model": "M-1", "manufacturer": "Maker",
"unit": "pcs", "quantity_delta": "2", "unit_price": "3.5",
"system_id": system_id, "section_id": section_id,
}, follow_redirects=False)
assert added_new.status_code == 303
with TestingSession() as db:
line = db.query(AgreementItem).filter_by(agreement_id=agreement_id,
change_type="new_position").one()
new_line_id = line.id
draft_item_id = line.work_item_id
edited_new = client.post(f"{detail_url}/items/{new_line_id}/edit", data={
"quantity_delta": "3", "unit_price": "4.5", "name": "New draft item edited",
"model": "M-2", "manufacturer": "Maker 2", "unit": "pcs",
"system_id": system_id, "section_id": section_id,
}, follow_redirects=False)
assert edited_new.status_code == 303
with TestingSession() as db:
assert db.get(boq.WorkItem, draft_item_id) is not None
plan_ids = {row.item.id for row in build_effective_plan(db, project_id)["items"]}
assert draft_item_id not in plan_ids
assert "New draft item" not in client.get(
f"/projects/{project_id}/daily-reports/new?system_id={system_id}"
).text
blocked = client.post(f"/projects/{project_id}/daily-reports", data={
"report_date": "2026-09-25", "system_id": system_id,
f"quantity_{draft_item_id}": "1",
})
assert blocked.status_code == 400
approval = client.post(f"{detail_url}/approve", follow_redirects=False)
assert approval.status_code == 303
with TestingSession() as db:
plan = build_effective_plan(db, project_id)
plan_rows = {row.item.id: row for row in plan["items"]}
assert plan_rows[base_item_id].quantity == Decimal("106.0000")
assert plan_rows[draft_item_id].quantity == Decimal("3.0000")
assert plan_rows[draft_item_id].amount == Decimal("13.500000000000")
assert db.query(boq.WorkItem).filter_by(project_id=project_id).count() == 2
assert db.query(Agreement).filter_by(id=agreement_id).one().status == "approved"
dr_form = client.get(f"/projects/{project_id}/daily-reports/new?system_id={system_id}")
assert dr_form.status_code == 200 and "New draft item" in dr_form.text
saved_fact = client.post(f"/projects/{project_id}/daily-reports", data={
"report_date": "2026-09-25", "system_id": system_id,
f"quantity_{draft_item_id}": "1",
}, follow_redirects=False)
assert saved_fact.status_code == 303
assert client.get(f"/projects/{project_id}").status_code == 200
assert client.get(detail_url).status_code == 200
readonly = client.post(f"{detail_url}/update", data={
"number": "A-1", "agreement_date": "2026-09-25", "title": "Changed",
"description": "", "scope": f"boq:{doc_id}",
})
assert readonly.status_code == 409
project_scope = client.post(f"/projects/{project_id}/agreements", data={
"number": "A-2", "agreement_date": "2026-09-25", "title": "Project scope",
"description": "", "scope": "project",
}, follow_redirects=False)
assert project_scope.status_code == 303
with TestingSession() as db:
project_agreement = db.query(Agreement).filter_by(number="A-2").one()
assert project_agreement.boq_document_id is None
scope_detail = client.get(project_scope.headers["location"])
assert scope_detail.status_code == 200
assert "\u0412\u0435\u0441\u044c \u043f\u0440\u043e\u0435\u043a\u0442" in scope_detail.text
finally:
for dependency in (project_router.get_db, daily_reports.get_db, agreement_router.get_db):
app.dependency_overrides.pop(dependency, None)
engine.dispose()
def test_project_wide_agreement_can_create_project_system_section_and_unlinked_work_item():
from app.models import work_journal as work_journal_models
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
TestingSession = sessionmaker(bind=engine, expire_on_commit=False)
with TestingSession() as db:
project = Project(name="Project-wide agreement")
db.add(project); db.flush()
scud_boq = boq.BoqDocument(project_id=project.id, name="BOQ SCUD")
ops_boq = boq.BoqDocument(project_id=project.id, name="BOQ OPS")
db.add_all([scud_boq, ops_boq]); db.commit()
project_id, scud_boq_id, ops_boq_id = project.id, scud_boq.id, ops_boq.id
def override_db():
db = TestingSession()
try:
yield db
finally:
db.close()
for dependency in (project_router.get_db, daily_reports.get_db, agreement_router.get_db):
app.dependency_overrides[dependency] = override_db
try:
with TestClient(app) as client:
response = client.post(f"/projects/{project_id}/agreements", data={
"number": "PW-1", "agreement_date": "2026-09-25", "title": "Repair",
"description": "", "scope": "project",
}, follow_redirects=False)
assert response.status_code == 303
detail_url = response.headers["location"]
agreement_id = int(detail_url.rsplit("/", 1)[1])
created_system = client.post(f"{detail_url}/systems", data={"name": "\u0421\u0430\u043d\u0442\u0435\u0445\u043d\u0438\u043a\u0430"})
assert created_system.status_code == 200
system_data = created_system.json()
created_section = client.post(f"{detail_url}/sections", data={
"system_id": system_data["id"], "name": "\u0421\u0430\u043d\u0442\u0435\u0445\u043d\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u0440\u0430\u0431\u043e\u0442\u044b",
})
assert created_section.status_code == 200
section_data = created_section.json()
assert section_data["system_id"] == system_data["id"]
added = client.post(f"{detail_url}/items/new", data={
"name": "\u0420\u0435\u043c\u043e\u043d\u0442 \u0443\u043d\u0438\u0442\u0430\u0437\u0430", "model": "", "manufacturer": "", "unit": "\u0448\u0442",
"quantity_delta": "1", "unit_price": "1250.00",
"system_id": system_data["id"], "section_id": section_data["id"],
"source_boq_document_id": scud_boq_id,
}, follow_redirects=False)
assert added.status_code == 303, added.text
ops_added = client.post(f"{detail_url}/items/new", data={
"name": "OPS position", "unit": "pcs", "quantity_delta": "2", "unit_price": "20",
"system_id": system_data["id"], "section_id": section_data["id"],
"source_boq_document_id": ops_boq_id,
}, follow_redirects=False)
assert ops_added.status_code == 303, ops_added.text
unclassified = client.post(f"{detail_url}/items/new", data={
"name": "\u041d\u0435\u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u0430\u044f \u0440\u0430\u0431\u043e\u0442\u0430",
"unit": "\u0448\u0442", "quantity_delta": "1", "unit_price": "1250",
"system_id": "", "section_id": "", "source_boq_document_id": "",
}, follow_redirects=False)
assert unclassified.status_code == 303, unclassified.text
with TestingSession() as db:
agreement = db.query(Agreement).filter_by(id=agreement_id).one()
new_lines = db.query(AgreementItem).filter_by(
agreement_id=agreement_id, change_type="new_position"
).order_by(AgreementItem.id).all()
assert len(new_lines) == 3
item = next(db.get(boq.WorkItem, line.work_item_id) for line in new_lines
if db.get(boq.WorkItem, line.work_item_id).name == "\u0420\u0435\u043c\u043e\u043d\u0442 \u0443\u043d\u0438\u0442\u0430\u0437\u0430")
unclassified_item = next(db.get(boq.WorkItem, line.work_item_id) for line in new_lines
if db.get(boq.WorkItem, line.work_item_id).system_id is None)
assert unclassified_item.boq_document_id is None
unclassified_id = unclassified_item.id
ops_id = new_lines[1].work_item_id
assert new_lines[0].source_boq_document_id == scud_boq_id
assert new_lines[1].source_boq_document_id == ops_boq_id
assert new_lines[2].source_boq_document_id is None
assert all(line.work_item.boq_document_id is None for line in new_lines)
assert agreement.boq_document_id is None
assert item.project_id == project_id and item.boq_document_id is None
assert item.system_id == system_data["id"] and item.section_id == section_data["id"]
assert db.get(boq.System, system_data["id"]).project_id == project_id
assert db.get(boq.System, system_data["id"]).name == "\u0421\u0430\u043d\u0442\u0435\u0445\u043d\u0438\u043a\u0430"
assert db.get(boq.Section, section_data["id"]).system_id == system_data["id"]
assert db.get(boq.Section, section_data["id"]).name == "\u0421\u0430\u043d\u0442\u0435\u0445\u043d\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u0440\u0430\u0431\u043e\u0442\u044b"
assert item.name == "\u0420\u0435\u043c\u043e\u043d\u0442 \u0443\u043d\u0438\u0442\u0430\u0437\u0430"
item_id = item.id
draft_ids = {row.item.id for row in build_effective_plan(db, project_id)["items"]}
assert item_id not in draft_ids and unclassified_id not in draft_ids
before = client.get(f"/projects/{project_id}/daily-reports/new?system_id={system_data['id']}")
assert before.status_code == 200 and "\u0420\u0435\u043c\u043e\u043d\u0442 \u0443\u043d\u0438\u0442\u0430\u0437\u0430" not in before.text
approved = client.post(f"{detail_url}/approve", follow_redirects=False)
assert approved.status_code == 303, approved.text
with TestingSession() as db:
effective = {row.item.id: row for row in build_effective_plan(db, project_id)["items"]}
assert effective[item_id].quantity == Decimal("1.0000")
assert effective[item_id].amount == Decimal("1250.000000000000")
assert len(effective) == 3
assert all(work_item_id in effective for work_item_id in (item_id, ops_id, unclassified_id))
assert effective[unclassified_id].quantity == Decimal("1.0000")
assert effective[unclassified_id].item.system_id is None
assert effective[unclassified_id].item.section_id is None
report_form = client.get(f"/projects/{project_id}/daily-reports/new?system_id=unclassified")
assert report_form.status_code == 200 and "\u041d\u0435\u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u0430\u044f \u0440\u0430\u0431\u043e\u0442\u0430" in report_form.text
saved = client.post(f"/projects/{project_id}/daily-reports", data={
"report_date": "2026-09-25", "system_id": "unclassified",
f"quantity_{unclassified_id}": "0.5",
}, follow_redirects=False)
assert saved.status_code == 303
view = client.get(saved.headers["location"])
assert view.status_code == 200 and "\u041d\u0435\u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u0430\u044f \u0440\u0430\u0431\u043e\u0442\u0430" in view.text
assert client.get(f"/projects/{project_id}/daily-reports").status_code == 200
dashboard = client.get(f"/projects/{project_id}")
assert dashboard.status_code == 200
with TestingSession() as db:
assert db.query(DailyReportItem).filter_by(work_item_id=unclassified_id).one().completed_quantity == Decimal("0.5000")
from app.services.project_dashboard import build_project_dashboard
dashboard_data = build_project_dashboard(db, db.get(Project, project_id))
assert dashboard_data["performed_cost"] == Decimal("625.00")
assert db.query(DailyReport).one().system_id is None
from app.utils.formatters import format_money
assert format_money(Decimal("625.00"), "RUB") in dashboard.text
finally:
for dependency in (project_router.get_db, daily_reports.get_db, agreement_router.get_db):
app.dependency_overrides.pop(dependency, None)
engine.dispose()
+6 -4
View File
@@ -12,6 +12,7 @@ from app.models.boq import BoqDocument, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.routers import daily_reports, projects
from app.services.project_dashboard import build_project_dashboard
from app.utils.formatters import format_money
def test_real_project_dashboard_with_daily_report_and_overrun(tmp_path):
@@ -32,7 +33,8 @@ def test_real_project_dashboard_with_daily_report_and_overrun(tmp_path):
project = session.get(Project, 2)
assert project is not None
before = build_project_dashboard(session, project)
assert before["planned_cost"] == Decimal("18600000.00")
expected_plan = before["planned_cost"]
assert expected_plan > 0
assert before["performed_cost"] >= 0
assert before["completion_percent"] >= 0
assert len(before["system_progress"]) == 11
@@ -65,7 +67,7 @@ def test_real_project_dashboard_with_daily_report_and_overrun(tmp_path):
with TestClient(app) as client:
dashboard_response = client.get(f"/projects/{project_id}")
assert dashboard_response.status_code == 200
assert "18 600 000,00 ₽" in dashboard_response.text
assert format_money(expected_plan, "RUB") in dashboard_response.text
assert baseline_actual.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
assert " ₽" in dashboard_response.text
@@ -83,12 +85,12 @@ def test_real_project_dashboard_with_daily_report_and_overrun(tmp_path):
assert expected_actual > 0
assert "system-progress-table .money-cell" in after_response.text
assert "white-space: nowrap" in after_response.text
assert "18 600 000,00" in after_response.text
assert format_money(expected_plan, "RUB").split(" ?")[0] in after_response.text
with TestingSession() as session:
after = build_project_dashboard(session, session.get(Project, project_id))
assert after["performed_cost"] > baseline_actual
assert after["remaining_cost"] == Decimal("18600000.00") - after["performed_cost"]
assert after["remaining_cost"] == expected_plan - after["performed_cost"]
assert after["completion_percent"] > 0
assert after["over_plan_count"] == baseline_warning_count + 1
assert len(after["recent_reports"]) == min(5, baseline_recent_count + 1)
+6 -3
View File
@@ -13,6 +13,8 @@ from app.models.daily_report import DailyReport
from app.models.project import Project
from app.routers import boq as boq_router
from app.routers import daily_reports, projects
from app.services.project_dashboard import build_project_dashboard
from app.utils.formatters import format_money
def test_project_edit_real_file_import_and_daily_report_flow(tmp_path):
@@ -41,7 +43,9 @@ def test_project_edit_real_file_import_and_daily_report_flow(tmp_path):
assert client.get("/projects/").status_code == 200
dashboard = client.get("/projects/2")
assert dashboard.status_code == 200
assert "18 600 000,00 ₽" in dashboard.text
with TestingSession() as session:
expected_dashboard_plan = build_project_dashboard(session, session.get(Project, 2))["planned_cost"]
assert format_money(expected_dashboard_plan, "RUB") in dashboard.text
with TestingSession() as session:
existing_system_id = session.query(WorkItem.system_id).filter(
@@ -110,7 +114,7 @@ def test_project_edit_real_file_import_and_daily_report_flow(tmp_path):
document_page = client.get(f"/boq/2/documents/{latest_document_id}")
assert document_page.status_code == 200
assert "18 600 000,00 ₽" in document_page.text
assert format_money(stored_amount, "RUB") in document_page.text
assert client.get("/projects/2/daily-reports/1").status_code == 200
created_report = client.post("/projects/2/daily-reports", data={
@@ -122,7 +126,6 @@ def test_project_edit_real_file_import_and_daily_report_flow(tmp_path):
with TestingSession() as session:
assert session.query(DailyReport).filter_by(project_id=2).count() == daily_report_count_before_new + 1
with TestingSession() as session:
from app.services.project_dashboard import build_project_dashboard
project = session.get(Project, 2)
expected_percent = build_project_dashboard(session, project)["completion_percent"]
updated_dashboard = client.get("/projects/2")