wip: start KS-2 implementation
This commit is contained in:
@@ -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