feat: enforce Daily Report lifecycle rules around KS-2 closed volume

This commit is contained in:
Арсентьев Александр
2026-09-28 19:30:10 +03:00
parent fac2816622
commit 2821208c65
6 changed files with 961 additions and 24 deletions
+47 -21
View File
@@ -10,6 +10,16 @@ from app.database.database import SessionLocal
from app.models import boq, project
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.ks2 import KS2ItemSource
from app.services.daily_report_service import (
DailyReportError,
apply_quantities,
can_delete_item,
can_delete_report,
delete_item,
delete_report,
has_closed_volume,
report_close_infos,
)
from app.services.effective_plan import build_effective_plan
router = APIRouter()
@@ -176,9 +186,17 @@ async def view_daily_report(request: Request, project_id: int, report_id: int,
if row["over_plan"]:
warnings.append(row)
displayed.append(row)
infos = report_close_infos(db, report)
info_by_work = {info.work_item_id: info for info in infos}
for row in displayed:
info = info_by_work.get(row["item"].id)
row["closed_quantity"] = info.closed_quantity if info else Decimal("0")
row["available_quantity"] = info.available_quantity if info else row["current_quantity"]
can_del, del_reason = can_delete_report(db, report)
return request.app.templates.TemplateResponse("projects/daily_report_view.html", {
"request": request, "project": project_obj, "report": report,
"rows": displayed, "warnings": warnings,
"can_delete_report": can_del, "delete_blocked_reason": del_reason,
})
@@ -198,7 +216,7 @@ async def update_daily_report(request: Request, project_id: int, report_id: int,
project_obj = _project_or_404(db, project_id)
report = _report_or_404(db, project_id, report_id)
try:
report.report_date = date.fromisoformat(report_date)
parsed_date = date.fromisoformat(report_date)
except ValueError as exc:
raise HTTPException(status_code=400, detail="Invalid report date") from exc
system_id = _parse_system_selection(db, project_id, system_id)
@@ -208,21 +226,14 @@ async def update_daily_report(request: Request, project_id: int, report_id: int,
selection = "unclassified" if system_id is None else system_id
return _render_form(request, db, project_obj, selection, report, errors)
_validate_work_items(db, project_id, system_id, quantities)
closed_ids = _ks2_closed_item_ids(db, report.id)
if closed_ids:
existing = {line.id: line for line in report.items}
for line_id in closed_ids:
line = existing.get(line_id)
if line and line.work_item_id not in quantities:
raise HTTPException(status_code=400, detail="Cannot remove quantity closed in KS-2")
if line and quantities.get(line.work_item_id) != line.completed_quantity:
raise HTTPException(status_code=400, detail="Cannot change quantity closed in KS-2")
report.system_id = system_id
report.notes = notes.strip() or None
db.query(DailyReportItem).filter(DailyReportItem.daily_report_id == report.id).delete()
report.items = [DailyReportItem(work_item_id=item_id, completed_quantity=quantity)
for item_id, quantity in quantities.items()]
db.commit()
try:
apply_quantities(
db, report, quantities,
new_date=parsed_date, system_id=system_id, notes=notes.strip() or None,
)
except DailyReportError as exc:
selection = "unclassified" if system_id is None else system_id
return _render_form(request, db, project_obj, selection, report, [str(exc)])
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
@@ -266,9 +277,24 @@ def _ks2_closed_item_ids(db, report_id):
async def delete_daily_report(project_id: int, report_id: int, db: Session = Depends(get_db)):
_project_or_404(db, project_id)
report = _report_or_404(db, project_id, report_id)
closed_ids = _ks2_closed_item_ids(db, report.id)
if closed_ids:
raise HTTPException(status_code=400, detail="Cannot delete daily report with quantities closed in KS-2")
db.delete(report)
db.commit()
try:
delete_report(db, report)
except DailyReportError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return RedirectResponse(f"/projects/{project_id}/daily-reports", status_code=303)
@router.post("/{project_id}/daily-reports/{report_id}/items/{item_id}/delete")
async def delete_daily_report_item(
project_id: int, report_id: int, item_id: int, db: Session = Depends(get_db)
):
_project_or_404(db, project_id)
report = _report_or_404(db, project_id, report_id)
item = next((i for i in report.items if i.id == item_id), None)
if item is None:
raise HTTPException(status_code=404, detail="Daily report item not found")
try:
delete_item(db, item)
except DailyReportError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return RedirectResponse(f"/projects/{project_id}/daily-reports/{report.id}", status_code=303)
+210
View File
@@ -0,0 +1,210 @@
"""Daily Report lifecycle rules tied to KS-2 closing via KS2ItemSource."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.ks2 import KS2ItemSource
ZERO = Decimal("0")
_UNSET = object()
class DailyReportError(ValueError):
"""Business rule violation in Daily Report lifecycle."""
@dataclass
class ItemCloseInfo:
item_id: int
work_item_id: int
actual_quantity: Decimal
closed_quantity: Decimal
@property
def available_quantity(self) -> Decimal:
return self.actual_quantity - self.closed_quantity
@property
def is_closed(self) -> bool:
return self.closed_quantity >= self.actual_quantity and self.actual_quantity > 0
@property
def is_partially_closed(self) -> bool:
return ZERO < self.closed_quantity < self.actual_quantity
@property
def is_open(self) -> bool:
return self.closed_quantity == ZERO
def closed_quantity(db: Session, daily_report_item_id: int) -> Decimal:
value = db.query(func.coalesce(func.sum(KS2ItemSource.quantity), ZERO)).filter(
KS2ItemSource.daily_report_item_id == daily_report_item_id,
).scalar()
return Decimal(str(value or 0))
def item_close_info(db: Session, item: DailyReportItem) -> ItemCloseInfo:
return ItemCloseInfo(
item_id=item.id,
work_item_id=item.work_item_id,
actual_quantity=Decimal(str(item.completed_quantity)),
closed_quantity=closed_quantity(db, item.id),
)
def report_close_infos(db: Session, report: DailyReport) -> list[ItemCloseInfo]:
return [item_close_info(db, item) for item in report.items]
def has_closed_volume(db: Session, report: DailyReport) -> bool:
"""True when any item of the report has any KS-2 closed volume."""
for info in report_close_infos(db, report):
if info.closed_quantity > ZERO:
return True
return False
def can_delete_report(db: Session, report: DailyReport) -> tuple[bool, str]:
if has_closed_volume(db, report):
return False, "Отчёт нельзя удалить: его объём уже использован в КС-2."
return True, ""
def delete_report(db: Session, report: DailyReport) -> None:
"""Delete report + items atomically. Blocked when any item is closed in KS-2."""
try:
ok, reason = can_delete_report(db, report)
if not ok:
raise DailyReportError(reason)
# ORM cascade on DailyReport.items removes DailyReportItem rows.
db.delete(report)
db.commit()
except DailyReportError:
db.rollback()
raise
except Exception as exc:
db.rollback()
raise DailyReportError(f"Не удалось удалить отчёт: {exc}") from exc
def can_delete_item(db: Session, item: DailyReportItem) -> tuple[bool, str]:
closed = closed_quantity(db, item.id)
if closed > ZERO:
return False, (
f"Позицию нельзя удалить: в КС-2 уже закрыто {closed}. "
f"Изменение закрытого объёма недопустимо."
)
return True, ""
def delete_item(db: Session, item: DailyReportItem) -> None:
try:
ok, reason = can_delete_item(db, item)
if not ok:
raise DailyReportError(reason)
db.delete(item)
db.commit()
except DailyReportError:
db.rollback()
raise
except Exception as exc:
db.rollback()
raise DailyReportError(f"Не удалось удалить позицию: {exc}") from exc
def can_change_quantity(info: ItemCloseInfo, new_quantity: Decimal) -> tuple[bool, str]:
if new_quantity < ZERO:
return False, "Количество не может быть отрицательным."
if info.closed_quantity == ZERO:
return True, ""
if new_quantity < info.closed_quantity:
return False, (
f"Количество нельзя уменьшить ниже закрытого в КС-2 объёма "
f"({info.closed_quantity}). Доступно к изменению от {info.closed_quantity}."
)
if info.closed_quantity >= info.actual_quantity and new_quantity != info.actual_quantity:
return False, (
f"Позиция полностью закрыта в КС-2 ({info.closed_quantity}). "
f"Количество изменить нельзя."
)
return True, ""
def can_change_date(db: Session, report: DailyReport) -> tuple[bool, str]:
if has_closed_volume(db, report):
return False, "Дату отчёта нельзя изменить: его объём уже использован в КС-2."
return True, ""
def apply_quantities(
db: Session,
report: DailyReport,
quantities: dict[int, Decimal],
*,
new_date: date | None = None,
system_id: int | None | object = _UNSET,
notes: str | None = None,
) -> None:
"""
Update report items in place, preserving KS2ItemSource links.
- open items: quantity may change freely; item may be removed;
- partially closed: quantity may only stay or increase (>= closed);
- fully closed: quantity is frozen; item cannot be removed;
- date: changeable only when nothing is closed.
"""
try:
if new_date is not None and new_date != report.report_date:
ok, reason = can_change_date(db, report)
if not ok:
raise DailyReportError(reason)
report.report_date = new_date
if system_id is not _UNSET:
report.system_id = system_id
infos = {info.work_item_id: info for info in report_close_infos(db, report)}
existing_by_work = {item.work_item_id: item for item in report.items}
seen_work_ids = set(quantities)
for work_item_id, item in list(existing_by_work.items()):
info = infos[work_item_id]
if work_item_id not in seen_work_ids:
if info.closed_quantity > ZERO:
raise DailyReportError(
f"Позицию нельзя удалить: в КС-2 уже закрыто {info.closed_quantity}."
)
db.delete(item)
continue
new_qty = Decimal(str(quantities[work_item_id]))
ok, reason = can_change_quantity(info, new_qty)
if not ok:
raise DailyReportError(reason)
if new_qty != info.actual_quantity:
item.completed_quantity = new_qty
for work_item_id, new_qty in quantities.items():
if work_item_id not in existing_by_work:
if new_qty < ZERO:
raise DailyReportError("Количество не может быть отрицательным.")
report.items.append(DailyReportItem(
work_item_id=work_item_id, completed_quantity=new_qty,
))
if notes is not None:
report.notes = notes.strip() or None
db.commit()
except DailyReportError:
db.rollback()
raise
except Exception as exc:
db.rollback()
raise DailyReportError(f"Не удалось обновить отчёт: {exc}") from exc
+33 -3
View File
@@ -8,12 +8,42 @@
<body class="bg-light">
<main class="container py-4">
<nav class="mb-3"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}">{{ project.name }}</a></li><li class="breadcrumb-item"><a href="/projects/{{ project.id }}/daily-reports">Daily Reports</a></li><li class="breadcrumb-item active">{{ report.report_date.strftime('%d.%m.%Y') }}</li></ol></nav>
<div class="d-flex justify-content-between align-items-start mb-4"><div><h1>Daily Report</h1><div class="text-muted">{{ report.report_date.strftime('%d.%m.%Y') }} · {{ report.system.name if report.system else '&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1085;&#1099;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1073;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;' }}</div>{% if report.notes %}<p class="mt-2">{{ report.notes }}</p>{% endif %}</div><a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit">Редактировать</a></div>
<div class="d-flex justify-content-between align-items-start mb-4 gap-3 flex-wrap">
<div>
<h1>Daily Report</h1>
<div class="text-muted">{{ report.report_date.strftime('%d.%m.%Y') }} · {{ report.system.name if report.system else 'Проектные позиции без системы' }}</div>
{% if report.notes %}<p class="mt-2">{{ report.notes }}</p>{% endif %}
</div>
<div class="d-flex gap-2">
<a class="btn btn-primary" href="/projects/{{ project.id }}/daily-reports/{{ report.id }}/edit">Редактировать</a>
{% if can_delete_report %}
<form method="post" action="/projects/{{ project.id }}/daily-reports/{{ report.id }}/delete" class="d-inline">
<button type="submit" class="btn btn-outline-danger"
onclick="return confirm('Удалить Daily Report? Действие необратимо.')">Удалить отчёт</button>
</form>
{% else %}
<button type="button" class="btn btn-outline-danger" disabled
title="{{ delete_blocked_reason }}">Удалить отчёт</button>
{% endif %}
</div>
</div>
{% if not can_delete_report %}
<div class="alert alert-warning" role="alert">{{ delete_blocked_reason }}</div>
{% endif %}
{% if warnings %}<div class="alert alert-warning"><strong>Превышен план по {{ warnings|length }} позициям.</strong> Фактическое выполнение сохранено.</div>{% endif %}
<div class="card"><div class="table-responsive"><table class="table table-hover align-middle mb-0">
<thead><tr><th>Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th class="text-end">План</th><th class="text-end">Накоплено до отчёта</th><th class="text-end">В этом отчёте</th><th class="text-end">Накоплено</th></tr></thead>
<thead><tr><th>Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th class="text-end">План</th><th class="text-end">В этом отчёте</th><th class="text-end">Закрыто КС-2</th><th class="text-end">Доступно</th></tr></thead>
<tbody>{% for row in rows %}
<tr class="{% if row.over_plan %}table-warning{% endif %}"><td>{{ row.item.section.name if row.item.section else '—' }}</td><td>{{ row.item.source_number or '' }}</td><td>{{ row.item.name }}</td><td>{{ row.item.unit or '' }}</td><td class="text-end">{{ row.planned_quantity if row.planned_quantity is not none else '—' }}</td><td class="text-end">{{ row.accumulated }}</td><td class="text-end">{{ row.current_quantity }}</td><td class="text-end">{{ row.accumulated + row.current_quantity }}</td></tr>
<tr class="{% if row.over_plan %}table-warning{% endif %}">
<td>{{ row.item.section.name if row.item.section else '—' }}</td>
<td>{{ row.item.source_number or '' }}</td>
<td>{{ row.item.name }}</td>
<td>{{ row.item.unit or '' }}</td>
<td class="text-end">{{ row.planned_quantity if row.planned_quantity is not none else '—' }}</td>
<td class="text-end">{{ row.current_quantity }}</td>
<td class="text-end">{{ row.closed_quantity }}</td>
<td class="text-end">{{ row.available_quantity }}</td>
</tr>
{% else %}<tr><td colspan="8" class="text-center text-muted py-4">В отчёте нет рабочих позиций.</td></tr>{% endfor %}</tbody>
</table></div></div>
<div class="mt-3"><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-outline-secondary">К списку отчётов</a></div>