6c608a8779
- 004: KS-2 UI (list, create, edit, view, issue) with integration tests - 005: navigation buttons, financial column alignment, button layout - 006: reporting_period_from/to fields with migration, validation, display - 007: fixed table layout with colgroup, quantity2 filter, stable column widths
150 lines
6.5 KiB
Python
150 lines
6.5 KiB
Python
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, KS2Item
|
|
from app.services.ks2_service import (
|
|
KS2ValidationError, build_work_item_balances, issue_ks2, project_ks2_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):
|
|
project = db.query(Project).filter(Project.id == project_id).first()
|
|
if project is None:
|
|
raise HTTPException(status_code=404, detail="Проект не найден")
|
|
return project
|
|
|
|
|
|
def _document(db, project_id, ks2_id):
|
|
doc = db.query(KS2).options(joinedload(KS2.items).joinedload(KS2Item.work_item)).filter(
|
|
KS2.id == ks2_id, KS2.project_id == project_id
|
|
).first()
|
|
if doc is None:
|
|
raise HTTPException(status_code=404, detail="КС-2 не найден")
|
|
return doc
|
|
|
|
|
|
def _entries_from_form(form):
|
|
entries = []
|
|
for key, values in form.multi_items():
|
|
if key.startswith("include_") and values in ("1", "on", "true"):
|
|
item_id = key.removeprefix("include_")
|
|
entries.append((item_id, form.get(f"quantity_{item_id}", "")))
|
|
return entries
|
|
|
|
|
|
def _render_selection(request, db, project, document=None, error=None, status_code=200):
|
|
balances = build_work_item_balances(db, project.id)
|
|
selected = {line.work_item_id: line.quantity for line in document.items} if document else {}
|
|
visible = [row for row in balances if row.available_quantity > 0 or row.item.id in selected]
|
|
return templates.TemplateResponse(name="ks2/form.html", context={
|
|
"request": request, "project": project, "document": document, "balances": visible,
|
|
"selected": selected, "error": error,
|
|
}, status_code=status_code)
|
|
|
|
|
|
@router.get("/{project_id}/ks2")
|
|
async def ks2_list(request: Request, project_id: int, db: Session = Depends(get_db)):
|
|
project = _project(db, project_id)
|
|
rows = project_ks2_totals(db, project_id)
|
|
return templates.TemplateResponse(name="ks2/list.html", context={
|
|
"request": request, "project": project, "rows": rows,
|
|
})
|
|
|
|
|
|
@router.get("/{project_id}/ks2/new")
|
|
async def ks2_new(request: Request, project_id: int, db: Session = Depends(get_db)):
|
|
project = _project(db, project_id)
|
|
return _render_selection(request, db, project)
|
|
|
|
|
|
@router.post("/{project_id}/ks2")
|
|
async def ks2_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()
|
|
entries = _entries_from_form(form)
|
|
try:
|
|
parsed_date = date.fromisoformat(document_date)
|
|
document = save_draft(db, project_id, number, parsed_date, comment, entries,
|
|
reporting_period_from=reporting_period_from or None,
|
|
reporting_period_to=reporting_period_to or None)
|
|
except ValueError as exc:
|
|
return _render_selection(request, db, project, error=str(exc), status_code=400)
|
|
return RedirectResponse(f"/projects/{project_id}/ks2/{document.id}", status_code=303)
|
|
|
|
|
|
@router.get("/{project_id}/ks2/{ks2_id}")
|
|
async def ks2_view(request: Request, project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
|
project = _project(db, project_id)
|
|
document = _document(db, project_id, ks2_id)
|
|
total = sum((Decimal(str(line.amount)) for line in document.items), Decimal("0"))
|
|
for line in document.items:
|
|
line.sources.sort(key=lambda source: (source.daily_report_item.report.report_date,
|
|
source.daily_report_item.report.id,
|
|
source.daily_report_item.id))
|
|
return templates.TemplateResponse(name="ks2/view.html", context={
|
|
"request": request, "project": project, "document": document, "total": total,
|
|
})
|
|
|
|
|
|
@router.get("/{project_id}/ks2/{ks2_id}/edit")
|
|
async def ks2_edit(request: Request, project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
|
project = _project(db, project_id)
|
|
document = _document(db, project_id, ks2_id)
|
|
if document.status != "draft":
|
|
raise HTTPException(status_code=409, detail="Проведённый КС-2 нельзя редактировать")
|
|
return _render_selection(request, db, project, document)
|
|
|
|
|
|
@router.post("/{project_id}/ks2/{ks2_id}/edit")
|
|
async def ks2_update(request: Request, project_id: int, ks2_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)
|
|
document = _document(db, project_id, ks2_id)
|
|
form = await request.form()
|
|
try:
|
|
parsed_date = date.fromisoformat(document_date)
|
|
document = save_draft(db, project_id, number, parsed_date, comment,
|
|
_entries_from_form(form), ks2_id=ks2_id,
|
|
reporting_period_from=reporting_period_from or None,
|
|
reporting_period_to=reporting_period_to or None)
|
|
except ValueError as exc:
|
|
db.expire_all()
|
|
document = _document(db, project_id, ks2_id)
|
|
return _render_selection(request, db, project, document=document, error=str(exc), status_code=400)
|
|
return RedirectResponse(f"/projects/{project_id}/ks2/{document.id}", status_code=303)
|
|
|
|
|
|
@router.post("/{project_id}/ks2/{ks2_id}/issue")
|
|
async def ks2_issue(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
|
try:
|
|
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) |