from fastapi import APIRouter, Depends, HTTPException, Query, Request, Form, UploadFile, File from fastapi.responses import RedirectResponse, Response from sqlalchemy.orm import Session from app.config import import_uploads_dir from app.database import database from app.models import project from app.models import boq from app.services.project_dashboard import build_project_dashboard from app.services.effective_plan import BaseBoqConfigurationError from app.models.daily_report import DailyReport from app.models.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 import secrets from pathlib import Path router = APIRouter() IMPORT_UPLOAD_DIR = import_uploads_dir() def _journal_entry_or_404(db: Session, project_id: int, entry_id: int): entry = db.query(WorkJournalEntry).filter( WorkJournalEntry.id == entry_id, WorkJournalEntry.project_id == project_id, ).first() if entry is None: raise HTTPException(status_code=404, detail="Journal entry not found") return entry def _journal_values(entry_type: str, entry_text: str, due_date: str | None): from datetime import date entry_type = entry_type.strip() entry_text = entry_text.strip() if entry_type not in {"task", "note"}: raise HTTPException(status_code=422, detail="Type must be task or note") if not entry_text: raise HTTPException(status_code=422, detail="Text is required") if entry_type == "note": return entry_type, entry_text, None, None try: parsed_due_date = date.fromisoformat(due_date) if due_date else None except ValueError as exc: raise HTTPException(status_code=422, detail="Due date must use YYYY-MM-DD format") from exc return entry_type, entry_text, "open", parsed_due_date # Dependency def get_db(): db = database.SessionLocal() try: yield db finally: db.close() @router.get("/") async def read_projects(request: Request, db: Session = Depends(get_db)): projects = db.query(project.Project).order_by(project.Project.created_at.desc()).all() return request.app.templates.TemplateResponse("projects/index.html", { "request": request, "projects": projects }) @router.get("/new") async def new_project(request: Request): return request.app.templates.TemplateResponse("projects/new.html", {"request": request}) @router.get("/import") async def project_import_form(request: Request): return request.app.templates.TemplateResponse("projects/import_project.html", { "request": request, "error": None, }) @router.get("/settings/database-reset") async def database_reset_form(request: Request, db: Session = Depends(get_db)): from app.services.database_reset import count_project_data counts = count_project_data(db) return request.app.templates.TemplateResponse("projects/database_reset.html", { "request": request, "counts": counts, "error": None, }) @router.post("/settings/database-reset") async def database_reset_submit(request: Request, db: Session = Depends(get_db)): from app.services.database_reset import DatabaseResetError, count_project_data, reset_database form = await request.form() confirmation = (form.get("confirmation") or "").strip() if confirmation != "УДАЛИТЬ ВСЕ ДАННЫЕ": counts = count_project_data(db) return request.app.templates.TemplateResponse("projects/database_reset.html", { "request": request, "counts": counts, "error": "Ввод не совпадает с подтверждением. Данные не удалены.", }, status_code=400) try: result = reset_database(db) except DatabaseResetError as exc: counts = count_project_data(db) return request.app.templates.TemplateResponse("projects/database_reset.html", { "request": request, "counts": counts, "error": str(exc), }, status_code=500) if result.storage_error: # DB is clean but FS cleanup failed — still a partial success return RedirectResponse( url=f"/projects/?reset=1&storage_error=1", status_code=303 ) return RedirectResponse(url="/projects/?reset=1", status_code=303) @router.post("/import/upload") async def project_import_upload( request: Request, file: UploadFile = File(...), db: Session = Depends(get_db), ): from app.exporters.project_import import ProjectImportError, validate_archive data = (file.file.read() or b"") try: preview = validate_archive(data) except ProjectImportError as exc: return request.app.templates.TemplateResponse("projects/import_project.html", { "request": request, "error": str(exc), }, status_code=400) token = secrets.token_hex(16) IMPORT_UPLOAD_DIR.mkdir(parents=True, exist_ok=True) stored = IMPORT_UPLOAD_DIR / f"{token}.wvt.zip" stored.write_bytes(data) counts = preview["counts"] return request.app.templates.TemplateResponse("projects/import_project_preview.html", { "request": request, "token": token, "project_name": preview["project_name"], "project": preview["project"], "manifest": preview["manifest"], "counts": counts, }) @router.post("/import/confirm") async def project_import_confirm( request: Request, token: str = Form(...), db: Session = Depends(get_db), ): from app.exporters.project_import import ProjectImportError, import_project safe_token = Path(token).name stored = IMPORT_UPLOAD_DIR / f"{safe_token}.wvt.zip" if not stored.exists(): raise HTTPException(status_code=400, detail="Файл импорта не найден. Загрузите архив заново.") data = stored.read_bytes() try: imported = import_project(db, data) except ProjectImportError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc finally: try: stored.unlink() except OSError: pass return RedirectResponse(url=f"/projects/{imported.id}?imported=1", status_code=303) @router.post("/create") async def create_project( request: Request, db: Session = Depends(get_db), name: str = Form(...), contract_number: str = Form(None), contract_date: str = Form(None), customer: str = Form(None), currency: str = Form("RUB"), start_date: str = Form(None), end_date: str = Form(None), status: str = Form("active") ): # Convert string dates to date objects if provided from datetime import datetime contract_date_obj = datetime.strptime(contract_date, "%Y-%m-%d").date() if contract_date else None start_date_obj = datetime.strptime(start_date, "%Y-%m-%d").date() if start_date else None end_date_obj = datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else None db_project = project.Project( name=name, contract_number=contract_number, contract_date=contract_date_obj, customer=customer, currency=currency, start_date=start_date_obj, end_date=end_date_obj, status=status ) db.add(db_project) db.commit() db.refresh(db_project) return RedirectResponse(url=f"/projects/{db_project.id}", status_code=303) @router.get("/{project_id}") async def read_project(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") # Get BOQ documents for this project boq_docs = db.query(boq.BoqDocument).filter( boq.BoqDocument.project_id == project_id ).order_by(boq.BoqDocument.created_at.desc(), boq.BoqDocument.id.desc()).all() try: dashboard = build_project_dashboard(db, db_project) except BaseBoqConfigurationError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc daily_reports = db.query(DailyReport).filter(DailyReport.project_id == project_id).count() 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", WorkJournalEntry.status != "done", ).order_by(WorkJournalEntry.due_date.is_(None), WorkJournalEntry.due_date, WorkJournalEntry.created_at.desc()).all() journal_notes = db.query(WorkJournalEntry).filter( WorkJournalEntry.project_id == project_id, WorkJournalEntry.type == "note", ).order_by(WorkJournalEntry.created_at.desc(), WorkJournalEntry.id.desc()).limit(5).all() return request.app.templates.TemplateResponse("projects/detail.html", { "request": request, "project": db_project, "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, }) @router.post("/{project_id}/journal") async def create_journal_entry( project_id: int, entry_type: str = Form(..., alias="type"), entry_text: str = Form(..., alias="text"), due_date: str = Form(""), db: Session = Depends(get_db), ): if db.query(project.Project.id).filter(project.Project.id == project_id).first() is None: raise HTTPException(status_code=404, detail="Project not found") entry_type, entry_text, status, parsed_due_date = _journal_values(entry_type, entry_text, due_date) db.add(WorkJournalEntry(project_id=project_id, type=entry_type, text=entry_text, status=status, due_date=parsed_due_date)) db.commit() return {"ok": True} @router.post("/{project_id}/journal/{entry_id}") async def update_journal_entry( project_id: int, entry_id: int, entry_type: str = Form(..., alias="type"), entry_text: str = Form(..., alias="text"), due_date: str = Form(""), db: Session = Depends(get_db), ): entry = _journal_entry_or_404(db, project_id, entry_id) entry_type, entry_text, next_status, parsed_due_date = _journal_values(entry_type, entry_text, due_date) entry.type = entry_type entry.text = entry_text entry.due_date = parsed_due_date entry.status = next_status if entry_type == "task" else None db.commit() return {"ok": True} @router.post("/{project_id}/journal/{entry_id}/toggle") async def toggle_journal_task(project_id: int, entry_id: int, db: Session = Depends(get_db)): entry = _journal_entry_or_404(db, project_id, entry_id) if entry.type != "task": raise HTTPException(status_code=400, detail="Only tasks have a status") entry.status = "done" if entry.status != "done" else "open" db.commit() return {"ok": True, "status": entry.status} @router.post("/{project_id}/journal/{entry_id}/delete") async def delete_journal_entry(project_id: int, entry_id: int, db: Session = Depends(get_db)): entry = _journal_entry_or_404(db, project_id, entry_id) db.delete(entry) db.commit() return {"ok": True} @router.get("/{project_id}/edit") async def edit_project(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") return request.app.templates.TemplateResponse("projects/edit.html", { "request": request, "project": db_project, }) @router.post("/{project_id}/edit") async def update_project( project_id: int, name: str = Form(...), contract_number: str = Form(None), contract_date: str = Form(None), customer: str = Form(None), currency: str = Form("RUB"), start_date: str = Form(None), end_date: str = Form(None), status: str = Form("active"), investor_name: str = Form(None), customer_name: str = Form(None), contractor_name: str = Form(None), construction_name: str = Form(None), object_name: str = Form(None), contract_amount: str = Form(None), contractor_signer_name: str = Form(None), contractor_signer_position: str = Form(None), customer_signer_name: str = Form(None), customer_signer_position: str = Form(None), 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") from datetime import datetime from decimal import Decimal, InvalidOperation try: db_project.contract_date = datetime.strptime(contract_date, "%Y-%m-%d").date() if contract_date else None db_project.start_date = datetime.strptime(start_date, "%Y-%m-%d").date() if start_date else None db_project.end_date = datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else None except ValueError as exc: raise HTTPException(status_code=400, detail="Dates must use YYYY-MM-DD format") from exc db_project.name = name.strip() db_project.contract_number = contract_number.strip() if contract_number else None # customer_name is the domain field; customer is kept in sync for compatibility resolved_customer = (customer_name or customer or "").strip() or None db_project.customer_name = resolved_customer db_project.customer = resolved_customer db_project.currency = currency.strip() if currency else "RUB" db_project.status = status db_project.investor_name = investor_name.strip() if investor_name else None db_project.contractor_name = contractor_name.strip() if contractor_name else None db_project.construction_name = construction_name.strip() if construction_name else None db_project.object_name = object_name.strip() if object_name else None db_project.contractor_signer_name = contractor_signer_name.strip() if contractor_signer_name else None db_project.contractor_signer_position = contractor_signer_position.strip() if contractor_signer_position else None db_project.customer_signer_name = customer_signer_name.strip() if customer_signer_name else None db_project.customer_signer_position = customer_signer_position.strip() if customer_signer_position else None if contract_amount: try: db_project.contract_amount = Decimal(contract_amount.strip().replace(",", ".")) except InvalidOperation: raise HTTPException(status_code=400, detail="Сумма договора должна быть числом") else: db_project.contract_amount = None db.commit() return RedirectResponse(url=f"/projects/{project_id}", status_code=303) @router.get("/{project_id}/import") async def import_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") return request.app.templates.TemplateResponse("projects/import.html", { "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) @router.get("/{project_id}/export/package") async def export_document_package( project_id: int, date_from: str = "", date_to: str = "", include: list[str] = Query(default=[]), export_format: str = Query("both", alias="format"), 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") from app.exporters.package_service import ( PackageEmptyError, PackageValidationError, build_document_package, parse_package_params, ) try: parsed_from, parsed_to, selected, export_format = parse_package_params( date_from, date_to, include, export_format ) except PackageValidationError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc try: data, filename = build_document_package( db, db_project, parsed_from, parsed_to, selected, export_format ) except PackageEmptyError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc from app.exporters import content_disposition return Response( content=data, media_type="application/zip", headers={"Content-Disposition": content_disposition(filename)}, ) @router.get("/{project_id}/export/project") async def export_project_archive(project_id: int, db: Session = Depends(get_db)): from app.exporters.project_export import ProjectExportError, export_project from app.exporters import content_disposition try: data, filename = export_project(db, project_id) except ProjectExportError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc return Response( content=data, media_type="application/zip", headers={"Content-Disposition": content_disposition(filename)}, )