feat: add KS-3/payments, tech debt fixes, UI polish, and KS-2 Excel/Word export

Tasks 008-016: KS-6a journal, KS-3 documents, payments with allocations,
tech debt cleanup, financial privacy, document tree, storno mechanism,
row-click UI, BOQ collapse/sticky header, and KS-2 export to Excel/Word
via shared DTO architecture.
This commit is contained in:
Арсентьев Александр
2026-09-27 13:38:45 +03:00
parent 6c608a8779
commit 9cfb341774
57 changed files with 7163 additions and 50 deletions
+65 -1
View File
@@ -1,9 +1,10 @@
from fastapi import APIRouter, Depends, HTTPException, Request, Form, UploadFile, File
from fastapi.responses import RedirectResponse
from sqlalchemy.orm import Session
from app.database import database
from app.models import project, boq
from app.models.daily_report import DailyReport, DailyReportItem
from app.importer import excel_importer
from typing import List
import os
from decimal import Decimal
from pathlib import Path
@@ -11,6 +12,19 @@ from pathlib import Path
router = APIRouter()
UPLOAD_DIR = Path(__file__).resolve().parents[1] / "uploads"
def _completed_quantities(db, project_id, items):
item_ids = [item.id for item in items]
if not item_ids:
return {}
rows = db.query(DailyReportItem.work_item_id, DailyReportItem.completed_quantity).join(
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
).filter(DailyReport.project_id == project_id, DailyReportItem.work_item_id.in_(item_ids)).all()
totals = {}
for wid, qty in rows:
totals[wid] = totals.get(wid, Decimal("0")) + Decimal(str(qty or 0))
return totals
# Dependency
def get_db():
db = database.SessionLocal()
@@ -79,8 +93,58 @@ async def view_boq_document(request: Request, project_id: int, document_id: int,
"document_title": document_title,
"systems": tree, "total": total,
"unassigned_items": [item for item in items if item.system_id is None or item.section_id is None],
"completed_by_item": _completed_quantities(db, project_id, items),
"has_history": _has_history(db, items),
})
def _has_history(db, items):
"""Check if BOQ items participate in DailyReports / KS2 / KS3 / Payments."""
item_ids = [i.id for i in items]
if not item_ids:
return False
if db.query(DailyReportItem).filter(DailyReportItem.work_item_id.in_(item_ids)).first():
return True
from app.models.ks2 import KS2Item
if db.query(KS2Item).filter(KS2Item.work_item_id.in_(item_ids)).first():
return True
return False
@router.post("/{project_id}/documents/{document_id}/delete")
async def delete_boq_document(project_id: int, document_id: int, db: Session = Depends(get_db)):
document = db.query(boq.BoqDocument).filter(
boq.BoqDocument.id == document_id, boq.BoqDocument.project_id == project_id
).first()
if document is None:
raise HTTPException(status_code=404, detail="Document not found")
items = db.query(boq.WorkItem).filter(boq.WorkItem.boq_document_id == document_id).all()
if _has_history(db, items):
raise HTTPException(status_code=400, detail="Cannot delete document with history. Archive it instead.")
try:
for item in items:
db.delete(item)
db.delete(document)
db.commit()
except Exception:
db.rollback()
raise HTTPException(status_code=400, detail="Cannot delete document with related data")
return RedirectResponse(f"/boq/{project_id}", status_code=303)
@router.post("/{project_id}/documents/{document_id}/archive")
async def archive_boq_document(project_id: int, document_id: int, db: Session = Depends(get_db)):
document = db.query(boq.BoqDocument).filter(
boq.BoqDocument.id == document_id, boq.BoqDocument.project_id == project_id
).first()
if document is None:
raise HTTPException(status_code=404, detail="Document not found")
if document.version == "archived":
raise HTTPException(status_code=400, detail="Already archived")
document.version = "archived"
db.commit()
return RedirectResponse(f"/boq/{project_id}/documents/{document_id}", status_code=303)
@router.post("/{project_id}/import/upload")
async def upload_excel_file(
request: Request,
+30
View File
@@ -9,6 +9,7 @@ from sqlalchemy.orm import Session
from app.database.database import SessionLocal
from app.models import boq, project
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.ks2 import KS2ItemSource
from app.services.effective_plan import build_effective_plan
router = APIRouter()
@@ -207,6 +208,15 @@ async def update_daily_report(request: Request, project_id: int, report_id: int,
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)
closed_ids = _ks2_closed_item_ids(db, report.id)
if closed_ids:
existing = {line.id: line for line in report.items}
for line_id in closed_ids:
line = existing.get(line_id)
if line and line.work_item_id not in quantities:
raise HTTPException(status_code=400, detail="Cannot remove quantity closed in KS-2")
if line and quantities.get(line.work_item_id) != line.completed_quantity:
raise HTTPException(status_code=400, detail="Cannot change quantity closed in KS-2")
report.system_id = system_id
report.notes = notes.strip() or None
db.query(DailyReportItem).filter(DailyReportItem.daily_report_id == report.id).delete()
@@ -242,3 +252,23 @@ def _validate_work_items(db, project_id, system_id, quantities):
if row.item.system_id == system_id}
if effective_ids.intersection(quantities) != set(quantities):
raise HTTPException(status_code=400, detail="One or more work items are not part of the selected system effective plan")
def _ks2_closed_item_ids(db, report_id):
"""Return DailyReportItem ids already closed via KS-2 for this report."""
rows = db.query(KS2ItemSource.daily_report_item_id).join(
DailyReportItem, DailyReportItem.id == KS2ItemSource.daily_report_item_id
).filter(DailyReportItem.daily_report_id == report_id).distinct().all()
return {r[0] for r in rows}
@router.post("/{project_id}/daily-reports/{report_id}/delete")
async def delete_daily_report(project_id: int, report_id: int, db: Session = Depends(get_db)):
_project_or_404(db, project_id)
report = _report_or_404(db, project_id, report_id)
closed_ids = _ks2_closed_item_ids(db, report.id)
if closed_ids:
raise HTTPException(status_code=400, detail="Cannot delete daily report with quantities closed in KS-2")
db.delete(report)
db.commit()
return RedirectResponse(f"/projects/{project_id}/daily-reports", status_code=303)
+56 -2
View File
@@ -1,9 +1,10 @@
from datetime import date
from decimal import Decimal
from pathlib import Path
import re
from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi.responses import RedirectResponse
from fastapi.responses import RedirectResponse, Response
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session, joinedload
@@ -147,4 +148,57 @@ async def ks2_issue(project_id: int, ks2_id: int, db: Session = Depends(get_db))
issue_ks2(db, project_id, ks2_id)
except KS2ValidationError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
@router.post("/{project_id}/ks2/{ks2_id}/cancel")
async def ks2_cancel(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
from app.models.ks2 import KS2
doc = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).first()
if doc is None:
raise HTTPException(status_code=404, detail="KS-2 not found")
if doc.status == "cancelled":
raise HTTPException(status_code=400, detail="KS-2 already cancelled")
doc.status = "cancelled"
db.commit()
return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303)
def _safe_filename(number: str, dt) -> str:
raw = f"КС-2 №{number} от {dt.strftime('%d.%m.%Y')}"
return re.sub(r'[<>:"/\\|?*]', "_", raw)
def _content_disposition(filename: str) -> str:
from urllib.parse import quote
return f"attachment; filename*=UTF-8''{quote(filename)}"
@router.get("/{project_id}/ks2/{ks2_id}/export/excel")
async def ks2_export_excel(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
document = _document(db, project_id, ks2_id)
from app.exporters.ks2_dto import build_ks2_export_dto
from app.exporters.excel.ks2_renderer import render_ks2_excel
dto = build_ks2_export_dto(db, document)
data = render_ks2_excel(dto)
filename = _safe_filename(document.number, document.date) + ".xlsx"
return Response(
content=data,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": _content_disposition(filename)},
)
@router.get("/{project_id}/ks2/{ks2_id}/export/word")
async def ks2_export_word(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
document = _document(db, project_id, ks2_id)
from app.exporters.ks2_dto import build_ks2_export_dto
from app.exporters.word.ks2_renderer import render_ks2_word
dto = build_ks2_export_dto(db, document)
data = render_ks2_word(dto)
filename = _safe_filename(document.number, document.date) + ".docx"
return Response(
content=data,
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
headers={"Content-Disposition": _content_disposition(filename)},
)
+167
View File
@@ -0,0 +1,167 @@
from datetime import date
from decimal import Decimal
from pathlib import Path
from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session, joinedload
from app.database.database import get_db
from app.models.project import Project
from app.models.ks2 import KS2
from app.models.ks3 import KS3, KS3KS2
from app.services.ks3_service import (
KS3ValidationError, available_ks2, issue_ks3, project_ks3_totals, save_draft,
)
from app.utils.formatters import format_money
def _quantity2(value):
try:
return f"{Decimal(str(value if value is not None else 0)):.2f}"
except Exception:
return "0.00"
router = APIRouter()
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
templates.env.filters["money"] = format_money
templates.env.filters["quantity2"] = _quantity2
def _project(db, project_id):
obj = db.query(Project).filter(Project.id == project_id).first()
if obj is None:
raise HTTPException(status_code=404, detail="Проект не найден")
return obj
def _document(db, project_id, ks3_id):
doc = db.query(KS3).options(
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
if doc is None:
raise HTTPException(status_code=404, detail="КС-3 не найден")
return doc
def _ks2_total(ks2):
return sum(Decimal(str(item.amount or 0)) for item in ks2.items)
def _render_form(request, db, project, document=None, error=None, status_code=200):
available = available_ks2(db, project.id)
selected_ids = {link.ks2_id for link in document.links} if document else set()
return templates.TemplateResponse(name="ks3/form.html", context={
"request": request, "project": project, "document": document,
"available_ks2": available, "selected_ids": selected_ids, "error": error,
}, status_code=status_code)
@router.get("/{project_id}/ks3")
async def ks3_list(request: Request, project_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
rows = project_ks3_totals(db, project_id)
return templates.TemplateResponse(name="ks3/list.html", context={
"request": request, "project": project, "rows": rows,
})
@router.get("/{project_id}/ks3/new")
async def ks3_new(request: Request, project_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
return _render_form(request, db, project)
@router.post("/{project_id}/ks3")
async def ks3_create(request: Request, project_id: int,
number: str = Form(...), document_date: str = Form(...),
comment: str = Form(""),
reporting_period_from: str = Form(""), reporting_period_to: str = Form(""),
db: Session = Depends(get_db)):
project = _project(db, project_id)
form = await request.form()
ks2_ids = [int(v) for k, v in form.multi_items() if k == "ks2_ids"]
try:
parsed_date = date.fromisoformat(document_date)
document = save_draft(
db, project_id, number, parsed_date, comment, ks2_ids,
reporting_period_from=reporting_period_from or None,
reporting_period_to=reporting_period_to or None,
)
except ValueError as exc:
return _render_form(request, db, project, error=str(exc), status_code=400)
return RedirectResponse(f"/projects/{project_id}/ks3/{document.id}", status_code=303)
@router.get("/{project_id}/ks3/{ks3_id}")
async def ks3_view(request: Request, project_id: int, ks3_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
document = _document(db, project_id, ks3_id)
total = Decimal("0")
ks2_rows = []
for link in document.links:
if link.ks2:
ks2_total = _ks2_total(link.ks2)
total += ks2_total
ks2_rows.append({"ks2": link.ks2, "total": ks2_total})
return templates.TemplateResponse(name="ks3/view.html", context={
"request": request, "project": project, "document": document,
"ks2_rows": ks2_rows, "total": total,
})
@router.get("/{project_id}/ks3/{ks3_id}/edit")
async def ks3_edit(request: Request, project_id: int, ks3_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
document = _document(db, project_id, ks3_id)
if document.status != "draft":
raise HTTPException(status_code=409, detail="Проведённый КС-3 нельзя редактировать")
return _render_form(request, db, project, document)
@router.post("/{project_id}/ks3/{ks3_id}/edit")
async def ks3_update(request: Request, project_id: int, ks3_id: int,
number: str = Form(...), document_date: str = Form(...),
comment: str = Form(""),
reporting_period_from: str = Form(""), reporting_period_to: str = Form(""),
db: Session = Depends(get_db)):
project = _project(db, project_id)
form = await request.form()
ks2_ids = [int(v) for k, v in form.multi_items() if k == "ks2_ids"]
try:
parsed_date = date.fromisoformat(document_date)
document = save_draft(
db, project_id, number, parsed_date, comment, ks2_ids,
reporting_period_from=reporting_period_from or None,
reporting_period_to=reporting_period_to or None,
ks3_id=ks3_id,
)
except ValueError as exc:
db.expire_all()
document = _document(db, project_id, ks3_id)
return _render_form(request, db, project, document=document, error=str(exc), status_code=400)
return RedirectResponse(f"/projects/{project_id}/ks3/{document.id}", status_code=303)
@router.post("/{project_id}/ks3/{ks3_id}/issue")
async def ks3_issue(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
try:
issue_ks3(db, project_id, ks3_id)
except KS3ValidationError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
@router.post("/{project_id}/ks3/{ks3_id}/cancel")
async def ks3_cancel(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
from app.models.ks3 import KS3
doc = db.query(KS3).filter(KS3.id == ks3_id, KS3.project_id == project_id).first()
if doc is None:
raise HTTPException(status_code=404, detail="KS-3 not found")
if doc.status == "cancelled":
raise HTTPException(status_code=400, detail="KS-3 already cancelled")
doc.status = "cancelled"
db.commit()
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
+104
View File
@@ -0,0 +1,104 @@
from datetime import date
from decimal import Decimal
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session, joinedload
from app.database.database import get_db
from app.models.boq import System, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.project import Project
def _quantity2(value):
try:
return f"{Decimal(str(value if value is not None else 0)):.2f}"
except Exception:
return "0.00"
router = APIRouter()
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
templates.env.filters["quantity2"] = _quantity2
def _project(db, project_id):
obj = db.query(Project).filter(Project.id == project_id).first()
if obj is None:
raise HTTPException(status_code=404, detail="Проект не найден")
return obj
@router.get("/{project_id}/ks6a")
async def ks6a_journal(
request: Request,
project_id: int,
date_from: str = "",
date_to: str = "",
system_id: str = "",
db: Session = Depends(get_db),
):
project = _project(db, project_id)
systems = db.query(System).filter(
System.project_id == project_id
).order_by(System.sort_order, System.id).all()
rows = []
total_count = 0
parsed_from = None
parsed_to = None
error = None
if date_from and date_to:
try:
parsed_from = date.fromisoformat(date_from)
parsed_to = date.fromisoformat(date_to)
except ValueError:
error = "Неверный формат даты"
else:
if parsed_to < parsed_from:
error = "Дата окончания не может быть раньше даты начала"
if parsed_from and parsed_to and not error:
query = db.query(DailyReportItem).join(
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
).join(
WorkItem, WorkItem.id == DailyReportItem.work_item_id
).options(
joinedload(DailyReportItem.work_item),
joinedload(DailyReportItem.report),
).filter(
DailyReport.project_id == project_id,
DailyReport.report_date >= parsed_from,
DailyReport.report_date <= parsed_to,
)
if system_id and system_id != "all":
try:
sid = int(system_id)
except (ValueError, TypeError):
error = "Некорректный идентификатор системы"
else:
query = query.filter(WorkItem.system_id == sid)
if not error:
rows = query.order_by(
DailyReport.report_date,
DailyReport.id,
DailyReportItem.id,
).all()
total_count = len(rows)
return templates.TemplateResponse(name="ks6a/journal.html", context={
"request": request,
"project": project,
"systems": systems,
"rows": rows,
"total_count": total_count,
"date_from": date_from,
"date_to": date_to,
"system_id": system_id,
"error": error,
})
+176
View File
@@ -0,0 +1,176 @@
from datetime import date
from decimal import Decimal
from pathlib import Path
from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session, joinedload
from app.database.database import get_db
from app.models.project import Project
from app.models.payment import Payment, PaymentAllocation
from app.services.payment_service import (
PaymentValidationError, available_ks3_for_payment, delete_payment,
project_payments, save_payment,
)
from app.utils.formatters import format_money
def _quantity2(value):
try:
return f"{Decimal(str(value if value is not None else 0)):.2f}"
except Exception:
return "0.00"
router = APIRouter()
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
templates.env.filters["money"] = format_money
templates.env.filters["quantity2"] = _quantity2
def _project(db, project_id):
obj = db.query(Project).filter(Project.id == project_id).first()
if obj is None:
raise HTTPException(status_code=404, detail="Проект не найден")
return obj
def _payment(db, project_id, payment_id):
p = db.query(Payment).options(
joinedload(Payment.allocations).joinedload(PaymentAllocation.ks3)
).filter(Payment.id == payment_id, Payment.project_id == project_id).first()
if p is None:
raise HTTPException(status_code=404, detail="Платёж не найден")
return p
def _render_form(request, db, project, payment=None, error=None, status_code=200):
available = available_ks3_for_payment(db, project.id, exclude_payment_id=payment.id if payment else None)
current_allocs = {a.ks3_id: Decimal(str(a.amount)) for a in payment.allocations} if payment else {}
return templates.TemplateResponse(name="payments/form.html", context={
"request": request, "project": project, "payment": payment,
"available_ks3": available, "current_allocs": current_allocs, "error": error,
}, status_code=status_code)
@router.get("/{project_id}/payments")
async def payment_list(request: Request, project_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
rows = project_payments(db, project_id)
return templates.TemplateResponse(name="payments/list.html", context={
"request": request, "project": project, "rows": rows,
})
@router.get("/{project_id}/payments/new")
async def payment_new(request: Request, project_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
return _render_form(request, db, project)
@router.post("/{project_id}/payments")
async def payment_create(request: Request, project_id: int,
payment_date: str = Form(...),
document_number: str = Form(""),
amount: str = Form(...), currency: str = Form("RUB"),
comment: str = Form(""),
db: Session = Depends(get_db)):
project = _project(db, project_id)
form = await request.form()
allocations = []
for k, v in form.multi_items():
if k.startswith("alloc_") and v.strip():
try:
ks3_id = int(k.removeprefix("alloc_"))
alloc_amount = Decimal(v.strip().replace(",", "."))
if alloc_amount > 0:
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
except (ValueError, TypeError):
pass
try:
parsed_date = date.fromisoformat(payment_date)
parsed_amount = Decimal(amount.strip().replace(",", "."))
payment = save_payment(
db, project_id, parsed_date, parsed_amount, currency, comment,
allocations, document_number=document_number or None,
)
except ValueError as exc:
return _render_form(request, db, project, error=str(exc), status_code=400)
return RedirectResponse(f"/projects/{project_id}/payments/{payment.id}", status_code=303)
@router.get("/{project_id}/payments/{payment_id}")
async def payment_view(request: Request, project_id: int, payment_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
payment = _payment(db, project_id, payment_id)
allocated = sum(Decimal(str(a.amount)) for a in payment.allocations)
unallocated = max(Decimal(str(payment.amount)) - allocated, Decimal("0"))
return templates.TemplateResponse(name="payments/view.html", context={
"request": request, "project": project, "payment": payment,
"allocated": allocated, "unallocated": unallocated,
})
@router.get("/{project_id}/payments/{payment_id}/edit")
async def payment_edit(request: Request, project_id: int, payment_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
payment = _payment(db, project_id, payment_id)
return _render_form(request, db, project, payment)
@router.post("/{project_id}/payments/{payment_id}/edit")
async def payment_update(request: Request, project_id: int, payment_id: int,
payment_date: str = Form(...),
document_number: str = Form(""),
amount: str = Form(...), currency: str = Form("RUB"),
comment: str = Form(""),
db: Session = Depends(get_db)):
project = _project(db, project_id)
form = await request.form()
allocations = []
for k, v in form.multi_items():
if k.startswith("alloc_") and v.strip():
try:
ks3_id = int(k.removeprefix("alloc_"))
alloc_amount = Decimal(v.strip().replace(",", "."))
if alloc_amount > 0:
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
except (ValueError, TypeError):
pass
try:
parsed_date = date.fromisoformat(payment_date)
parsed_amount = Decimal(amount.strip().replace(",", "."))
payment = save_payment(
db, project_id, parsed_date, parsed_amount, currency, comment,
allocations, document_number=document_number or None,
payment_id=payment_id,
)
except ValueError as exc:
db.expire_all()
payment = _payment(db, project_id, payment_id)
return _render_form(request, db, project, payment=payment, error=str(exc), status_code=400)
return RedirectResponse(f"/projects/{project_id}/payments/{payment.id}", status_code=303)
@router.post("/{project_id}/payments/{payment_id}/delete")
async def payment_delete(project_id: int, payment_id: int, db: Session = Depends(get_db)):
try:
delete_payment(db, project_id, payment_id)
except PaymentValidationError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return RedirectResponse(f"/projects/{project_id}/payments", status_code=303)
@router.post("/{project_id}/payments/{payment_id}/cancel")
async def payment_cancel(project_id: int, payment_id: int, db: Session = Depends(get_db)):
from app.models.payment import Payment
doc = db.query(Payment).filter(Payment.id == payment_id, Payment.project_id == project_id).first()
if doc is None:
raise HTTPException(status_code=404, detail="Payment not found")
if doc.status == "cancelled":
raise HTTPException(status_code=400, detail="Payment already cancelled")
doc.status = "cancelled"
db.commit()
return RedirectResponse(f"/projects/{project_id}/payments/{payment_id}", status_code=303)
+66
View File
@@ -8,6 +8,8 @@ from app.services.project_dashboard import build_project_dashboard
from app.services.effective_plan import BaseBoqConfigurationError
from app.models.daily_report import DailyReport
from app.models.ks2 import KS2
from app.models.ks3 import KS3
from app.models.payment import Payment
from app.models.work_journal import WorkJournalEntry
from typing import List
import os
@@ -114,6 +116,24 @@ async def read_project(request: Request, project_id: int, db: Session = Depends(
raise HTTPException(status_code=409, detail=str(exc)) from exc
daily_reports = db.query(DailyReport).filter(DailyReport.project_id == project_id).count()
ks2_count = db.query(KS2).filter(KS2.project_id == project_id).count()
ks3_count = db.query(KS3).filter(KS3.project_id == project_id).count()
payments_count = db.query(Payment).filter(Payment.project_id == project_id).count()
from app.models.agreement import Agreement
agreements_count = db.query(Agreement).filter(Agreement.project_id == project_id).count()
from app.services.payment_service import ks3_payment_summary
payment_summary = ks3_payment_summary(db, project_id)
# Build document tree: base BOQ docs with scoped agreements + project-wide agreements
all_agreements = db.query(Agreement).filter(
Agreement.project_id == project_id
).order_by(Agreement.id).all()
base_docs = [d for d in boq_docs if d.agreement_id is None]
doc_tree = []
for doc in base_docs:
scoped = [a for a in all_agreements if a.boq_document_id == doc.id]
doc_tree.append({"doc": doc, "agreements": scoped})
project_wide = [a for a in all_agreements if a.boq_document_id is None]
journal_tasks = db.query(WorkJournalEntry).filter(
WorkJournalEntry.project_id == project_id,
WorkJournalEntry.type == "task",
@@ -131,8 +151,14 @@ async def read_project(request: Request, project_id: int, db: Session = Depends(
"boq_docs": boq_docs,
"daily_reports_count": daily_reports,
"ks2_count": ks2_count,
"ks3_count": ks3_count,
"payments_count": payments_count,
"agreements_count": agreements_count,
"payment_summary": payment_summary,
"journal_tasks": journal_tasks,
"journal_notes": journal_notes,
"doc_tree": doc_tree,
"project_wide_agreements": project_wide,
**dashboard,
})
@@ -242,3 +268,43 @@ async def import_boq(request: Request, project_id: int, db: Session = Depends(ge
"request": request,
"project": db_project
})
def _has_financial_history(db, project_id):
"""Check if project has issued KS-2/KS-3 or payments."""
from app.models.ks2 import KS2
from app.models.ks3 import KS3
from app.models.payment import Payment
if db.query(KS2).filter(KS2.project_id == project_id, KS2.status == "issued").first():
return True
if db.query(KS3).filter(KS3.project_id == project_id, KS3.status == "issued").first():
return True
if db.query(Payment).filter(Payment.project_id == project_id).first():
return True
return False
@router.post("/{project_id}/delete")
async def delete_project(project_id: int, db: Session = Depends(get_db)):
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
if db_project is None:
raise HTTPException(status_code=404, detail="Project not found")
if _has_financial_history(db, project_id):
raise HTTPException(status_code=400, detail="Cannot delete project with financial history. Archive it instead.")
try:
db.delete(db_project)
db.commit()
except Exception:
db.rollback()
raise HTTPException(status_code=400, detail="Cannot delete project with related data")
return RedirectResponse(url="/projects/", status_code=303)
@router.post("/{project_id}/archive")
async def archive_project(project_id: int, db: Session = Depends(get_db)):
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
if db_project is None:
raise HTTPException(status_code=404, detail="Project not found")
db_project.status = "archived"
db.commit()
return RedirectResponse(url=f"/projects/{project_id}", status_code=303)