266 lines
12 KiB
Python
266 lines
12 KiB
Python
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 _parse_date(value, label):
|
||
if value is None:
|
||
return None
|
||
if isinstance(value, date):
|
||
return value
|
||
try:
|
||
return date.fromisoformat(str(value).strip())
|
||
except (ValueError, TypeError) as exc:
|
||
raise KS2ValidationError(f"{label}: неверный формат даты") from exc
|
||
|
||
|
||
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,
|
||
reporting_period_from=None, reporting_period_to=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)
|
||
|
||
period_from = _parse_date(reporting_period_from, "Период с")
|
||
period_to = _parse_date(reporting_period_to, "Период по")
|
||
if ks2_id is None:
|
||
if period_from is None:
|
||
raise KS2ValidationError("Укажите дату начала периода")
|
||
if period_to is None:
|
||
raise KS2ValidationError("Укажите дату окончания периода")
|
||
if period_from is not None and period_to is not None and period_to < period_from:
|
||
raise KS2ValidationError("Дата окончания периода не может быть раньше даты начала")
|
||
|
||
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.reporting_period_from = period_from
|
||
document.reporting_period_to = period_to
|
||
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
|
||
|
||
|
||
def ks2_cancel_block_reason(db: Session, project_id: int, ks2_id: int) -> str | None:
|
||
"""Return why KS-2 cannot be cancelled, or None if cancellation is allowed."""
|
||
from app.models.ks3 import KS3, KS3KS2
|
||
|
||
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).first()
|
||
if document is None:
|
||
return "КС-2 не найден"
|
||
if document.status == "cancelled":
|
||
return "КС-2 уже сторнирован"
|
||
active_link = db.query(KS3KS2).join(KS3, KS3.id == KS3KS2.ks3_id).filter(
|
||
KS3KS2.ks2_id == ks2_id,
|
||
KS3.project_id == project_id,
|
||
KS3.status == "issued",
|
||
).first()
|
||
if active_link is not None:
|
||
ks3_doc = db.query(KS3).filter(KS3.id == active_link.ks3_id).first()
|
||
number = ks3_doc.number if ks3_doc else active_link.ks3_id
|
||
return f"КС-2 включён в действующий КС-3 №{number}. Сначала сторнируйте КС-3."
|
||
return None
|
||
|
||
|
||
def cancel_ks2(db: Session, project_id: int, ks2_id: int):
|
||
"""Cancel a KS-2 atomically. Blocked when linked to an issued KS-3."""
|
||
try:
|
||
reason = ks2_cancel_block_reason(db, project_id, ks2_id)
|
||
if reason is not None:
|
||
raise KS2ValidationError(reason)
|
||
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 == "cancelled":
|
||
raise KS2ValidationError("КС-2 уже сторнирован")
|
||
document.status = "cancelled"
|
||
db.commit()
|
||
db.refresh(document)
|
||
return document
|
||
except Exception:
|
||
db.rollback()
|
||
raise |