wip: start KS-2 implementation
This commit is contained in:
+6
-2
@@ -1,17 +1,18 @@
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from fastapi.templating import Jinja2Templates
|
from fastapi.templating import Jinja2Templates
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Import routers
|
# Import routers
|
||||||
from app.routers import projects, boq as boq_router, daily_reports, agreements
|
from app.routers import projects, boq as boq_router, daily_reports, agreements, ks2
|
||||||
|
|
||||||
# Import models to ensure they're registered
|
# Import models to ensure they're registered
|
||||||
from app.models import project as project_models, boq as boq_models
|
from app.models import project as project_models, boq as boq_models
|
||||||
from app.models import daily_report as daily_report_models
|
from app.models import daily_report as daily_report_models
|
||||||
from app.models import work_journal as work_journal_models
|
from app.models import work_journal as work_journal_models
|
||||||
from app.models import agreement as agreement_models
|
from app.models import agreement as agreement_models
|
||||||
|
from app.models import ks2 as ks2_models
|
||||||
|
|
||||||
# Initialize database
|
# Initialize database
|
||||||
from app.database.database import engine
|
from app.database.database import engine
|
||||||
@@ -41,6 +42,7 @@ app.include_router(projects.router, prefix="/projects", tags=["projects"])
|
|||||||
app.include_router(boq_router.router, prefix="/boq", tags=["boq"])
|
app.include_router(boq_router.router, prefix="/boq", tags=["boq"])
|
||||||
app.include_router(daily_reports.router, prefix="/projects", tags=["daily-reports"])
|
app.include_router(daily_reports.router, prefix="/projects", tags=["daily-reports"])
|
||||||
app.include_router(agreements.router, prefix="/projects", tags=["agreements"])
|
app.include_router(agreements.router, prefix="/projects", tags=["agreements"])
|
||||||
|
app.include_router(ks2.router, prefix="/projects", tags=["ks2"])
|
||||||
|
|
||||||
@app.get("/", include_in_schema=False)
|
@app.get("/", include_in_schema=False)
|
||||||
async def read_root():
|
async def read_root():
|
||||||
@@ -53,3 +55,5 @@ async def health_check():
|
|||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(app, host="127.0.0.1", port=8000)
|
uvicorn.run(app, host="127.0.0.1", port=8000)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
from sqlalchemy import CheckConstraint, Column, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from app.database.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class KS2(Base):
|
||||||
|
__tablename__ = "ks2_documents"
|
||||||
|
__table_args__ = (UniqueConstraint("project_id", "number", name="uq_ks2_project_number"),)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
|
||||||
|
number = Column(String, nullable=False)
|
||||||
|
date = Column(Date, nullable=False, index=True)
|
||||||
|
comment = Column(Text)
|
||||||
|
status = Column(String, nullable=False, default="draft", index=True)
|
||||||
|
created_at = Column(DateTime, nullable=False, server_default=func.now())
|
||||||
|
updated_at = Column(DateTime, nullable=False, server_default=func.now(), onupdate=func.now())
|
||||||
|
|
||||||
|
project = relationship("Project")
|
||||||
|
items = relationship("KS2Item", back_populates="ks2", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class KS2Item(Base):
|
||||||
|
__tablename__ = "ks2_items"
|
||||||
|
__table_args__ = (CheckConstraint("quantity > 0", name="ck_ks2_items_quantity_positive"),)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
ks2_id = Column(Integer, ForeignKey("ks2_documents.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
work_item_id = Column(Integer, ForeignKey("work_items.id"), nullable=False, index=True)
|
||||||
|
quantity = Column(Numeric(15, 4), nullable=False)
|
||||||
|
unit_price = Column(Numeric(18, 12), nullable=False, default=0)
|
||||||
|
amount = Column(Numeric(18, 12), nullable=False, default=0)
|
||||||
|
|
||||||
|
ks2 = relationship("KS2", back_populates="items")
|
||||||
|
work_item = relationship("WorkItem")
|
||||||
|
sources = relationship("KS2ItemSource", back_populates="ks2_item", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class KS2ItemSource(Base):
|
||||||
|
__tablename__ = "ks2_item_sources"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("quantity > 0", name="ck_ks2_item_sources_quantity_positive"),
|
||||||
|
UniqueConstraint("ks2_item_id", "daily_report_item_id", name="uq_ks2_source_item_report_line"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
ks2_item_id = Column(Integer, ForeignKey("ks2_items.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
daily_report_item_id = Column(Integer, ForeignKey("daily_report_items.id"), nullable=False, index=True)
|
||||||
|
quantity = Column(Numeric(15, 4), nullable=False)
|
||||||
|
|
||||||
|
ks2_item = relationship("KS2Item", back_populates="sources")
|
||||||
|
daily_report_item = relationship("DailyReportItem")
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
|
||||||
|
templates.env.filters["money"] = format_money
|
||||||
|
|
||||||
|
|
||||||
|
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(request=request, name="ks2/form.html", context={
|
||||||
|
"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(request=request, name="ks2/list.html", context={
|
||||||
|
"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(""),
|
||||||
|
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)
|
||||||
|
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(request=request, name="ks2/view.html", context={
|
||||||
|
"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(""),
|
||||||
|
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)
|
||||||
|
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)
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.models.boq import WorkItem
|
||||||
|
from app.models.daily_report import DailyReport, DailyReportItem
|
||||||
|
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||||
|
from app.services.effective_plan import build_effective_plan
|
||||||
|
|
||||||
|
ZERO = Decimal("0")
|
||||||
|
|
||||||
|
|
||||||
|
class KS2ValidationError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class WorkItemBalance:
|
||||||
|
item: WorkItem
|
||||||
|
planned_quantity: Decimal
|
||||||
|
actual_quantity: Decimal
|
||||||
|
closed_quantity: Decimal
|
||||||
|
available_quantity: Decimal
|
||||||
|
execution_percent: Decimal
|
||||||
|
|
||||||
|
|
||||||
|
def _decimal(value):
|
||||||
|
try:
|
||||||
|
result = Decimal(str(value)) if value is not None else ZERO
|
||||||
|
except (InvalidOperation, ValueError, TypeError) as exc:
|
||||||
|
raise KS2ValidationError("Количество должно быть числом") from exc
|
||||||
|
if not result.is_finite():
|
||||||
|
raise KS2ValidationError("Количество должно быть конечным числом")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def build_work_item_balances(db: Session, project_id: int):
|
||||||
|
"""Return effective plan, accumulated Daily Report fact and issued KS-2 closure."""
|
||||||
|
plan = build_effective_plan(db, project_id)
|
||||||
|
effective_by_id = {row.item.id: row for row in plan["items"]}
|
||||||
|
if not effective_by_id:
|
||||||
|
return []
|
||||||
|
ids = list(effective_by_id)
|
||||||
|
actual = dict(db.query(DailyReportItem.work_item_id, func.sum(DailyReportItem.completed_quantity))
|
||||||
|
.join(DailyReport, DailyReport.id == DailyReportItem.daily_report_id)
|
||||||
|
.filter(DailyReport.project_id == project_id, DailyReportItem.work_item_id.in_(ids))
|
||||||
|
.group_by(DailyReportItem.work_item_id).all())
|
||||||
|
closed = dict(db.query(KS2Item.work_item_id, func.sum(KS2ItemSource.quantity))
|
||||||
|
.join(KS2ItemSource, KS2ItemSource.ks2_item_id == KS2Item.id)
|
||||||
|
.join(KS2, KS2.id == KS2Item.ks2_id)
|
||||||
|
.filter(KS2.project_id == project_id, KS2.status == "issued", KS2Item.work_item_id.in_(ids))
|
||||||
|
.group_by(KS2Item.work_item_id).all())
|
||||||
|
result = []
|
||||||
|
for item_id, effective in effective_by_id.items():
|
||||||
|
actual_qty = _decimal(actual.get(item_id))
|
||||||
|
closed_qty = _decimal(closed.get(item_id))
|
||||||
|
available = max(actual_qty - closed_qty, ZERO)
|
||||||
|
planned = _decimal(effective.quantity)
|
||||||
|
percent = actual_qty / planned * Decimal("100") if planned else ZERO
|
||||||
|
result.append(WorkItemBalance(effective.item, planned, actual_qty, closed_qty, available, percent))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _validated_entries(db, project_id, entries, excluded_ks2_id=None):
|
||||||
|
balances = {row.item.id: row for row in build_work_item_balances(db, project_id)}
|
||||||
|
normalized = {}
|
||||||
|
for item_id_raw, quantity_raw in entries:
|
||||||
|
try:
|
||||||
|
item_id = int(item_id_raw)
|
||||||
|
except (ValueError, TypeError) as exc:
|
||||||
|
raise KS2ValidationError("Некорректный идентификатор позиции") from exc
|
||||||
|
quantity = _decimal(str(quantity_raw).strip().replace(",", "."))
|
||||||
|
if quantity <= ZERO:
|
||||||
|
raise KS2ValidationError(f"Позиция {item_id}: количество должно быть больше нуля")
|
||||||
|
if item_id not in balances:
|
||||||
|
raise KS2ValidationError(f"Позиция {item_id} не входит в текущий план проекта")
|
||||||
|
if item_id in normalized:
|
||||||
|
raise KS2ValidationError(f"Позиция {item_id} указана несколько раз")
|
||||||
|
available = balances[item_id].available_quantity
|
||||||
|
if quantity > available:
|
||||||
|
raise KS2ValidationError(
|
||||||
|
f"{balances[item_id].item.name}: запрошено {quantity}, доступно к закрытию {available}"
|
||||||
|
)
|
||||||
|
normalized[item_id] = quantity
|
||||||
|
if not normalized:
|
||||||
|
raise KS2ValidationError("Выберите хотя бы одну позицию")
|
||||||
|
return normalized, balances
|
||||||
|
|
||||||
|
|
||||||
|
def save_draft(db: Session, project_id: int, number: str, document_date: date, comment: str | None,
|
||||||
|
entries, ks2_id: int | None = None):
|
||||||
|
"""Create/update a draft and its selected lines in one transaction."""
|
||||||
|
try:
|
||||||
|
number = (number or "").strip()
|
||||||
|
if not number:
|
||||||
|
raise KS2ValidationError("Укажите номер КС-2")
|
||||||
|
conflict = db.query(KS2).filter(KS2.project_id == project_id, KS2.number == number)
|
||||||
|
if ks2_id is not None:
|
||||||
|
conflict = conflict.filter(KS2.id != ks2_id)
|
||||||
|
if conflict.first():
|
||||||
|
raise KS2ValidationError("КС-2 с таким номером уже существует в проекте")
|
||||||
|
normalized, _ = _validated_entries(db, project_id, entries)
|
||||||
|
document = None
|
||||||
|
if ks2_id is not None:
|
||||||
|
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).with_for_update().first()
|
||||||
|
if document is None:
|
||||||
|
raise KS2ValidationError("КС-2 не найден")
|
||||||
|
if document.status != "draft":
|
||||||
|
raise KS2ValidationError("Проведённый КС-2 нельзя редактировать")
|
||||||
|
else:
|
||||||
|
document = KS2(project_id=project_id, status="draft")
|
||||||
|
db.add(document)
|
||||||
|
document.number = number
|
||||||
|
document.date = document_date
|
||||||
|
document.comment = comment.strip() or None if comment else None
|
||||||
|
document.items.clear()
|
||||||
|
for item_id, quantity in normalized.items():
|
||||||
|
item = db.get(WorkItem, item_id)
|
||||||
|
price = _decimal(item.unit_price)
|
||||||
|
document.items.append(KS2Item(work_item_id=item_id, quantity=quantity,
|
||||||
|
unit_price=price, amount=price * quantity))
|
||||||
|
db.commit()
|
||||||
|
db.refresh(document)
|
||||||
|
return document
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def issue_ks2(db: Session, project_id: int, ks2_id: int):
|
||||||
|
"""Revalidate current balances, attribute quantity to DR lines oldest-first, and issue atomically."""
|
||||||
|
try:
|
||||||
|
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).with_for_update().first()
|
||||||
|
if document is None:
|
||||||
|
raise KS2ValidationError("КС-2 не найден")
|
||||||
|
if document.status != "draft":
|
||||||
|
raise KS2ValidationError("Можно провести только черновик КС-2")
|
||||||
|
lines = db.query(KS2Item).filter(KS2Item.ks2_id == document.id).order_by(KS2Item.id).all()
|
||||||
|
if not lines:
|
||||||
|
raise KS2ValidationError("В КС-2 нет позиций")
|
||||||
|
balances = {row.item.id: row for row in build_work_item_balances(db, project_id)}
|
||||||
|
for line in lines:
|
||||||
|
balance = balances.get(line.work_item_id)
|
||||||
|
if balance is None or line.quantity > balance.available_quantity:
|
||||||
|
available = balance.available_quantity if balance else ZERO
|
||||||
|
raise KS2ValidationError(
|
||||||
|
f"{line.work_item.name}: доступный объём изменился; сейчас доступно {available}, "
|
||||||
|
f"в черновике указано {line.quantity}"
|
||||||
|
)
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
source_rows = db.query(DailyReportItem, DailyReport.report_date, DailyReport.id).join(
|
||||||
|
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
|
||||||
|
).filter(DailyReport.project_id == project_id,
|
||||||
|
DailyReportItem.work_item_id == line.work_item_id).order_by(
|
||||||
|
DailyReport.report_date, DailyReport.id, DailyReportItem.id
|
||||||
|
).all()
|
||||||
|
source_ids = [source.id for source, _day, _report_id in source_rows]
|
||||||
|
used = {}
|
||||||
|
if source_ids:
|
||||||
|
used = dict(db.query(KS2ItemSource.daily_report_item_id, func.sum(KS2ItemSource.quantity))
|
||||||
|
.join(KS2Item, KS2Item.id == KS2ItemSource.ks2_item_id)
|
||||||
|
.join(KS2, KS2.id == KS2Item.ks2_id)
|
||||||
|
.filter(KS2.project_id == project_id, KS2.status == "issued",
|
||||||
|
KS2ItemSource.daily_report_item_id.in_(source_ids))
|
||||||
|
.group_by(KS2ItemSource.daily_report_item_id).all())
|
||||||
|
remaining = line.quantity
|
||||||
|
for source, _day, _report_id in source_rows:
|
||||||
|
source_available = max(_decimal(source.completed_quantity) - _decimal(used.get(source.id)), ZERO)
|
||||||
|
allocation = min(source_available, remaining)
|
||||||
|
if allocation > ZERO:
|
||||||
|
line.sources.append(KS2ItemSource(daily_report_item_id=source.id, quantity=allocation))
|
||||||
|
remaining -= allocation
|
||||||
|
if remaining <= ZERO:
|
||||||
|
break
|
||||||
|
if remaining > ZERO:
|
||||||
|
raise KS2ValidationError(
|
||||||
|
f"Не удалось распределить весь объём по источникам Daily Reports для позиции {line.work_item.name}"
|
||||||
|
)
|
||||||
|
document.status = "issued"
|
||||||
|
db.commit()
|
||||||
|
db.refresh(document)
|
||||||
|
return document
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def project_ks2_totals(db: Session, project_id: int):
|
||||||
|
documents = db.query(KS2).filter(KS2.project_id == project_id).order_by(KS2.date.desc(), KS2.id.desc()).all()
|
||||||
|
rows = []
|
||||||
|
for document in documents:
|
||||||
|
rows.append({"document": document, "item_count": len(document.items),
|
||||||
|
"amount": sum((_decimal(line.amount) for line in document.items), ZERO)})
|
||||||
|
return rows
|
||||||
Reference in New Issue
Block a user