from fastapi import APIRouter, Depends, HTTPException, Request, Form, UploadFile, File from fastapi.responses import RedirectResponse from sqlalchemy.orm import Session from app.config import uploads_dir 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 import os from datetime import date from decimal import Decimal from pathlib import Path router = APIRouter() UPLOAD_DIR = uploads_dir() 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() try: yield db finally: db.close() @router.get("/{project_id}") async def list_project_boq(request: Request, 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") documents = db.query(boq.BoqDocument).filter( boq.BoqDocument.project_id == project_id ).order_by(boq.BoqDocument.created_at.desc(), boq.BoqDocument.id.desc()).all() return request.app.templates.TemplateResponse("projects/boq_list.html", { "request": request, "project": db_project, "documents": documents, }) @router.get("/{project_id}/documents/{document_id}") async def view_boq_document(request: Request, project_id: int, document_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") 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="BOQ document not found") document_title = document.display_name items = db.query(boq.WorkItem).filter( boq.WorkItem.boq_document_id == document_id, ).order_by(boq.WorkItem.id).all() system_ids = {item.system_id for item in items if item.system_id is not None} systems = db.query(boq.System).filter( boq.System.project_id == project_id, boq.System.id.in_(system_ids) if system_ids else False, ).order_by(boq.System.sort_order, boq.System.id).all() tree = [] total = Decimal("0.00") for system in systems: system_sections = db.query(boq.Section).filter( boq.Section.system_id == system.id, ).order_by(boq.Section.sort_order, boq.Section.id).all() section_nodes = [] system_total = Decimal("0.00") for section in system_sections: section_items = [item for item in items if item.section_id == section.id] section_total = sum((item.amount or Decimal("0.00") for item in section_items), Decimal("0.00")) section_nodes.append({"section": section, "items": section_items, "total": section_total}) system_total += section_total # Keep system rows represented even if currently empty. tree.append({"system": system, "sections": section_nodes, "total": system_total}) total += system_total return request.app.templates.TemplateResponse("projects/boq_document.html", { "request": request, "project": db_project, "document": document, "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, project_id: int, file: UploadFile = File(...), document_name: str = Form(""), document_number: str = Form(""), document_date: str = Form(""), contract: str = Form(""), 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") # Save the uploaded file filename = Path(file.filename or "upload.xlsx").name UPLOAD_DIR.mkdir(parents=True, exist_ok=True) file_location = UPLOAD_DIR / filename with open(file_location, "wb+") as file_object: file_object.write(file.file.read()) # Get the sheets from the Excel file sheets = excel_importer.get_excel_sheets(file_location) return request.app.templates.TemplateResponse("projects/import_sheet_selection.html", { "request": request, "project": db_project, "project_id": project_id, "filename": filename, "sheets": sheets, "document_name": document_name, "document_number": document_number, "document_date": document_date, "contract": contract, }) @router.post("/{project_id}/import/preview") async def preview_import( request: Request, project_id: int, filename: str = Form(...), sheet_name: str = Form(...), header_row: int = Form(...), start_row: int = Form(...), document_name: str = Form(""), document_number: str = Form(""), document_date: str = Form(""), contract: str = Form(""), db: Session = Depends(get_db) ): # Get the file path file_path = UPLOAD_DIR / Path(filename).name # Import and preview data try: preview_data = excel_importer.preview_excel_data(file_path, sheet_name, header_row, start_row) except (ValueError, OSError) as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc # Get project 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") return request.app.templates.TemplateResponse("projects/import_preview.html", { "request": request, "project": db_project, "preview_data": preview_data, "filename": filename, "sheet_name": sheet_name, "header_row": header_row, "start_row": start_row, "document_name": document_name or sheet_name, "document_number": document_number, "document_date": document_date, "contract": contract or (db_project.contract_number or ""), }) def _parse_optional_date(value: str): value = (value or "").strip() if not value: return None return date.fromisoformat(value) @router.post("/{project_id}/import/confirm") async def confirm_import( request: Request, project_id: int, filename: str = Form(...), sheet_name: str = Form(...), header_row: int = Form(...), start_row: int = Form(...), document_name: str = Form(""), document_number: str = Form(""), document_date: str = Form(""), contract: str = Form(""), db: Session = Depends(get_db) ): # Get the file path file_path = UPLOAD_DIR / Path(filename).name # Import data into database 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") try: parsed_date = _parse_optional_date(document_date) except ValueError as exc: raise HTTPException(status_code=400, detail="Дата ведомости должна быть в формате ГГГГ-ММ-ДД") from exc try: result = excel_importer.import_excel_data( db, file_path, sheet_name, header_row, start_row, project_id, document_name=document_name, document_number=document_number, document_date=parsed_date, contract=contract, ) except (ValueError, OSError) as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc # Get project return request.app.templates.TemplateResponse("projects/import_confirm.html", { "request": request, "project": db_project, "import_result": result, "filename": filename, "sheet_name": sheet_name })