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>
@@ -0,0 +1,95 @@
# Implementation Report — 027-daily-report-lifecycle
### Status
DONE
### What was done
Нормализован жизненный цикл Daily Report после закрытия объёмов в КС-2.
### Правила
| Состояние | Удалить позицию | Кол-во | WorkItem | Дата отчёта |
|---|---|---|---|---|
| Не закрыта (`closed=0`) | да | любое | по существующим правилам | да |
| Частично закрыта | нет | только ≥ `closed` (можно увеличить) | нет | нет (если есть закрытые) |
| Полностью закрыта | нет | нельзя | нет | нет |
- Удалить **отчёт** можно, только если ни одна позиция не закрыта (пустой / нулевые / незакрытые ненулевые).
- `KS2ItemSource` не изменяется и не пересчитывается при правках Daily Report.
- `actual < closed` получить нельзя.
- Все операции транзакционны (`rollback` при ошибке).
### Сервисный слой
`app/services/daily_report_service.py`:
- `ItemCloseInfo` / `report_close_infos` — `actual` / `closed` / `available`;
- `can_delete_report` / `delete_report`;
- `can_delete_item` / `delete_item`;
- `can_change_quantity` / `can_change_date`;
- `apply_quantities` — обновление **на месте** (не delete+recreate), сохраняющее `KS2ItemSource`.
Router использует сервис; серверные проверки обязательны.
### UI
- Кнопка **«Удалить отчёт»**: активна для незакрытого, `disabled` + alert-причина для закрытого:
«Отчёт нельзя удалить: его объём уже использован в КС-2.»
- Таблица позиций: **В этом отчёте / Закрыто КС-2 / Доступно**.
- Эндпоинт удаления отдельной позиции: `POST .../items/{id}/delete` с бизнес-ошибкой.
### Changed files
| Файл | Что |
|---|---|
| `app/services/daily_report_service.py` | новый сервис lifecycle |
| `app/routers/daily_reports.py` | delete/update через сервис, item delete |
| `app/templates/projects/daily_report_view.html` | кнопка удаления, closed/available |
| `tests/test_task027_daily_report_lifecycle.py` | 19 тестов |
| `docs/tasks/027-daily-report-lifecycle(1).md` | task-файл |
KS-2 механика, KS-6a, Dashboard-логика не менялись.
### Tests
`tests/test_task027_daily_report_lifecycle.py` (19) — все обязательные сценарии 1–20:
удаление (пустой/нулевой/незакрытый/частично/полностью закрытый), удаление позиций, количество (увеличение/уменьшение/частичное/полное закрытие), нетрогание `KS2ItemSource`, дата, HTTP create, частичное закрытие двумя КС-2, регрессия КС-2, Dashboard, UI-блокировка.
Результат `pytest -q`:
```
296 passed, 284 warnings in 22.36s
```
Результат `git diff --check`:
```
(без ошибок)
```
### Browser smoke
Playwright/Chromium, реальный проект. **12/12 passed** (desktop 1280 + narrow 480).
| Проверка | Результат |
|---|---|
| Незакрытый отчёт: кнопка «Удалить отчёт» активна | да |
| Удаление незакрытого | redirect в список |
| Закрытый отчёт: кнопка disabled + причина | да |
| «Закрыто / Доступно» в таблице | 6 / 4 из 10 |
| Увеличение частично закрытой позиции (10→12) | да |
| Уменьшение ниже закрытого (5 < 6) | ошибка в форме |
| Узкий экран | отображение корректно |
Скриншоты: `output/playwright/027-*.png`.
### Deviations
None.
### Follow-up / Open Questions
- `_tmp_verify_027.py` и screenshots — артефакты smoke.
- WorkItem в тестах должен иметь `boq_document_id`, чтобы попадать в effective plan.
- Изменение WorkItem в рамках Daily Report в UI отсутствует — правило сервиса готово, если появится операция.
+215
View File
@@ -0,0 +1,215 @@
# Task 027 — Жизненный цикл Daily Report после финансового закрытия
## Цель
Нормализовать жизненный цикл Daily Report после появления его объёмов в КС-2 и одновременно разрешить удаление ошибочно созданных незакрытых Daily Report.
Daily Report остаётся первичным фактом выполнения работ. КС-2 не изменяет исходный Daily Report, а закрывает его объём через `KS2ItemSource`.
## 1. Удаление Daily Report
Daily Report можно удалить целиком, если **ни одна его позиция не имеет закрытого объёма в КС-2**.
Разрешено удалить:
- пустой отчёт;
- отчёт только с нулевыми позициями;
- отчёт с ненулевыми позициями, которые ещё не использовались в КС-2.
Если хотя бы одна позиция частично или полностью закрыта в КС-2 — весь Daily Report удалять нельзя.
При удалении отчёта удаляются его `DailyReportItem`. Удаление транзакционное.
Пример: случайно созданный отчёт за выходной, ещё не попавший в КС-2, должен нормально удаляться.
## 2. Изменение позиции Daily Report
Для каждой `DailyReportItem` определить:
- `actual_quantity` — текущее количество;
- `closed_quantity` — сумма `KS2ItemSource.quantity`;
- `available_quantity = actual_quantity - closed_quantity`.
### Если позиция не закрыта
При `closed_quantity = 0`:
- количество можно изменять;
- WorkItem можно изменять, если такая операция существует;
- комментарий можно изменять;
- позицию можно удалить.
### Если позиция частично закрыта
При `0 < closed_quantity < actual_quantity`:
- количество можно увеличивать;
- количество нельзя уменьшить ниже `closed_quantity`;
- уже закрытый объём не изменяется;
- WorkItem менять нельзя;
- позицию удалять нельзя;
- комментарий можно изменять, если это не нарушает существующую модель.
Пример:
```text
actual = 100
closed = 60
available = 40
actual = 120 -> разрешено
actual = 50 -> запрещено
```
При увеличении новая часть становится доступной для последующего закрытия.
### Если позиция полностью закрыта
При `closed_quantity = actual_quantity`:
- количество нельзя изменять;
- WorkItem менять нельзя;
- позицию удалять нельзя;
- закрытый объём остаётся неизменным;
- комментарий можно изменять, если это не нарушает существующую модель.
## 3. Защита финансовой истории
Любое изменение `DailyReportItem.quantity` должно выполняться транзакционно и проверять:
```text
new_quantity >= closed_quantity
```
При нарушении:
- изменение отклоняется;
- `KS2ItemSource` не изменяется;
- пользователь получает понятное сообщение;
- данные остаются без изменений.
Нельзя решать проблему пересчётом или удалением существующих `KS2ItemSource`.
## 4. Дата Daily Report
Если хотя бы одна позиция отчёта уже имеет закрытый объём в КС-2, дату Daily Report менять нельзя.
Если ни одна позиция не закрыта, дату можно изменять по существующим правилам приложения.
## 5. Удаление отдельных позиций
Если `closed_quantity = 0` — позицию можно удалить.
Если `closed_quantity > 0` — позицию удалить нельзя.
При попытке удаления должна отображаться понятная бизнес-ошибка.
## 6. UI
Для незакрытого отчёта показывать действие **«Удалить отчёт»** с обычным подтверждением.
Для отчёта с закрытым объёмом кнопку удалить скрыть/отключить с пояснением:
> Отчёт нельзя удалить: его объём уже использован в КС-2.
Для закрытых позиций показывать причину блокировки, например:
```text
Количество: 100
Закрыто: 60
Доступно к закрытию: 40
```
## 7. Сервисный слой
Проверки должны быть на серверной стороне, а не только в UI.
Добавить/уточнить сервисные операции для:
- удаления Daily Report;
- удаления DailyReportItem;
- изменения количества;
- изменения даты;
- изменения WorkItem, если такая операция существует.
Удаление и изменения — транзакционные.
## 8. КС-2
Существующую механику КС-2 не ломать.
Сохраняются правила:
- один DailyReportItem может закрываться несколькими КС-2 частями;
- `closed_quantity` считается как сумма источников;
- `available_quantity = actual - closed`;
- КС-2 не изменяет исходный Daily Report.
## 9. KS-6а и Dashboard
Не менять бизнес-логику без необходимости.
После удаления незакрытого Daily Report он должен исчезать из активных агрегатов Dashboard и KS-6а. Уже закрытые данные не должны удаляться через Daily Report.
## 10. Тесты
Добавить тесты минимум на:
1. Удаление пустого Daily Report.
2. Удаление отчёта только с нулевыми позициями.
3. Удаление отчёта с ненулевыми незакрытыми позициями.
4. Запрет удаления при частичном закрытии.
5. Запрет удаления при полном закрытии.
6. Удаление незакрытой позиции.
7. Запрет удаления закрытой позиции.
8. Увеличение незакрытой позиции.
9. Уменьшение незакрытой позиции.
10. Увеличение частично закрытой позиции.
11. Запрет уменьшения ниже `closed_quantity`.
12. Запрет изменения полностью закрытой позиции.
13. `KS2ItemSource` не изменяется после разрешённого увеличения.
14. Изменение даты незакрытого отчёта.
15. Запрет изменения даты после закрытия.
16. Регрессия создания Daily Report.
17. Регрессия формирования КС-2.
18. Частичное закрытие одной позиции несколькими КС-2.
19. Dashboard после удаления незакрытого отчёта.
20. KS-6а после удаления незакрытого отчёта.
Количество тестов может быть больше при необходимости.
## 11. Browser smoke
Проверить:
1. Создать Daily Report.
2. Убедиться, что его можно удалить.
3. Создать отчёт с позициями.
4. Удалить его до КС-2.
5. Создать новый отчёт.
6. Частично закрыть позицию через КС-2.
7. Убедиться, что удалить позицию/отчёт нельзя.
8. Увеличить количество частично закрытой позиции.
9. Убедиться, что уменьшение ниже закрытого объёма запрещено.
10. Проверить отображение причины блокировки.
Проверить desktop и узкий экран.
## 12. Не входит в задачу
Не делать:
- фотографии/вложения Daily Report;
- изменение модели KS-2;
- reverse entries для сторно;
- исторические snapshots документов;
- косметический редизайн;
- серверную синхронизацию;
- авторизацию/многопользовательский режим.
Фотографии и другие вложения будут отдельной задачей.
## Критерий готовности
1. Незакрытый Daily Report можно удалить.
2. Daily Report с закрытым объёмом удалить нельзя.
3. Закрытый объём нельзя уменьшить/изменить/удалить через Daily Report.
4. Частично закрытый объём можно увеличить.
5. Нельзя получить `actual_quantity < closed_quantity`.
6. Дату закрытого отчёта изменить нельзя.
7. Цепочка Daily Report → КС-2 продолжает работать.
8. Все тесты проходят.
9. Browser smoke проходит.
10. `git diff` чистый, кроме осознанного результата реализации.
@@ -0,0 +1,361 @@
"""Tests for task 027: Daily Report lifecycle after KS-2 closing."""
from __future__ import annotations
from datetime import date
from decimal import Decimal
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database.database import Base
from app.main import app
from app.models.boq import BoqDocument, System, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
from app.models.project import Project
from app.routers import daily_reports as dr_router, projects as project_router
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,
)
@pytest.fixture
def db_session():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine, expire_on_commit=False)
session = Session()
try:
yield session
finally:
session.close()
engine.dispose()
def _seed(db):
p = Project(name="DR lifecycle")
db.add(p)
db.flush()
doc = BoqDocument(project_id=p.id, name="BOQ")
db.add(doc)
db.flush()
system = System(project_id=p.id, name="Система")
db.add(system)
db.flush()
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, system_id=system.id,
name="Позиция", quantity=Decimal("100"), unit_price=Decimal("1"),
amount=Decimal("100"))
db.add(wi)
db.flush()
report = DailyReport(project_id=p.id, system_id=system.id, report_date=date(2026, 1, 1))
db.add(report)
db.flush()
item = DailyReportItem(daily_report_id=report.id, work_item_id=wi.id, completed_quantity=Decimal("100"))
db.add(item)
db.commit()
return p.id, system.id, wi.id, report.id, item.id
def _close(db, report_id, item_id, work_item_id, qty):
"""Create a KS-2 source closing `qty` of a DailyReportItem."""
ks2 = KS2(project_id=db.query(DailyReport).get(report_id).project_id,
number=f"K2-{item_id}-{qty}", date=date(2026, 2, 1), status="issued")
db.add(ks2)
db.flush()
k2i = KS2Item(ks2_id=ks2.id, work_item_id=work_item_id,
quantity=qty, unit_price=Decimal("1"), amount=qty)
db.add(k2i)
db.flush()
db.add(KS2ItemSource(ks2_item_id=k2i.id, daily_report_item_id=item_id, quantity=qty))
db.commit()
return ks2.id
# ---------------------------------------------------------------------------
# 1-3. Delete report when nothing closed
# ---------------------------------------------------------------------------
def test_delete_empty_report(db_session):
p = Project(name="Empty")
db_session.add(p)
db_session.flush()
r = DailyReport(project_id=p.id, report_date=date(2026, 1, 1))
db_session.add(r)
db_session.commit()
ok, _ = can_delete_report(db_session, r)
assert ok
delete_report(db_session, r)
assert db_session.get(DailyReport, r.id) is None
def test_delete_report_with_zero_items(db_session):
p = Project(name="Zero")
db_session.add(p)
db_session.flush()
wi = WorkItem(project_id=p.id, name="W", quantity=Decimal("10"))
db_session.add(wi)
db_session.flush()
r = DailyReport(project_id=p.id, report_date=date(2026, 1, 1))
db_session.add(r)
db_session.flush()
db_session.add(DailyReportItem(daily_report_id=r.id, work_item_id=wi.id, completed_quantity=Decimal("0")))
db_session.commit()
ok, _ = can_delete_report(db_session, r)
assert ok
delete_report(db_session, r)
assert db_session.query(DailyReportItem).filter_by(daily_report_id=r.id).count() == 0
def test_delete_report_with_open_nonzero_items(db_session):
pid, _, _, report_id, _ = _seed(db_session)
r = db_session.get(DailyReport, report_id)
ok, _ = can_delete_report(db_session, r)
assert ok
delete_report(db_session, r)
assert db_session.get(DailyReport, report_id) is None
# ---------------------------------------------------------------------------
# 4-5. Block delete when closed
# ---------------------------------------------------------------------------
def test_block_delete_when_partially_closed(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("60"))
r = db_session.get(DailyReport, report_id)
ok, reason = can_delete_report(db_session, r)
assert not ok
assert "КС-2" in reason
with pytest.raises(DailyReportError, match="КС-2"):
delete_report(db_session, r)
assert db_session.get(DailyReport, report_id) is not None
def test_block_delete_when_fully_closed(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("100"))
r = db_session.get(DailyReport, report_id)
ok, reason = can_delete_report(db_session, r)
assert not ok
with pytest.raises(DailyReportError):
delete_report(db_session, r)
# ---------------------------------------------------------------------------
# 6-7. Item delete
# ---------------------------------------------------------------------------
def test_delete_open_item(db_session):
_, _, _, report_id, item_id = _seed(db_session)
item = db_session.get(DailyReportItem, item_id)
ok, _ = can_delete_item(db_session, item)
assert ok
delete_item(db_session, item)
assert db_session.get(DailyReportItem, item_id) is None
def test_block_delete_closed_item(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("40"))
item = db_session.get(DailyReportItem, item_id)
ok, reason = can_delete_item(db_session, item)
assert not ok
assert "40" in reason
with pytest.raises(DailyReportError):
delete_item(db_session, item)
# ---------------------------------------------------------------------------
# 8-12. Quantity changes
# ---------------------------------------------------------------------------
def test_increase_and_decrease_open_item(db_session):
_, _, _, report_id, item_id = _seed(db_session)
r = db_session.get(DailyReport, report_id)
item = db_session.get(DailyReportItem, item_id)
apply_quantities(db_session, r, {item.work_item_id: Decimal("120")})
assert db_session.get(DailyReportItem, item_id).completed_quantity == Decimal("120")
apply_quantities(db_session, r, {item.work_item_id: Decimal("10")})
assert db_session.get(DailyReportItem, item_id).completed_quantity == Decimal("10")
def test_increase_partially_closed_item(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("60"))
r = db_session.get(DailyReport, report_id)
item = db_session.get(DailyReportItem, item_id)
apply_quantities(db_session, r, {item.work_item_id: Decimal("120")})
assert db_session.get(DailyReportItem, item_id).completed_quantity == Decimal("120")
# KS2 sources untouched
assert db_session.query(KS2ItemSource).filter_by(daily_report_item_id=item_id).one().quantity == Decimal("60")
def test_block_decrease_below_closed_quantity(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("60"))
r = db_session.get(DailyReport, report_id)
item = db_session.get(DailyReportItem, item_id)
with pytest.raises(DailyReportError, match="60"):
apply_quantities(db_session, r, {item.work_item_id: Decimal("50")})
assert db_session.get(DailyReportItem, item_id).completed_quantity == Decimal("100")
def test_block_change_fully_closed_item(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("100"))
r = db_session.get(DailyReport, report_id)
item = db_session.get(DailyReportItem, item_id)
with pytest.raises(DailyReportError, match="закрыта"):
apply_quantities(db_session, r, {item.work_item_id: Decimal("120")})
assert db_session.get(DailyReportItem, item_id).completed_quantity == Decimal("100")
# ---------------------------------------------------------------------------
# 13. KS2ItemSource not mutated on allowed increase
# ---------------------------------------------------------------------------
def test_ks2_sources_unchanged_after_increase(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("60"))
sources_before = [
(s.id, s.quantity) for s in db_session.query(KS2ItemSource).filter_by(daily_report_item_id=item_id)
]
r = db_session.get(DailyReport, report_id)
item = db_session.get(DailyReportItem, item_id)
apply_quantities(db_session, r, {item.work_item_id: Decimal("80")})
sources_after = [
(s.id, s.quantity) for s in db_session.query(KS2ItemSource).filter_by(daily_report_item_id=item_id)
]
assert sources_before == sources_after
# ---------------------------------------------------------------------------
# 14-15. Date changes
# ---------------------------------------------------------------------------
def test_change_date_of_open_report(db_session):
_, _, _, report_id, _ = _seed(db_session)
r = db_session.get(DailyReport, report_id)
item = r.items[0]
apply_quantities(
db_session, r, {item.work_item_id: item.completed_quantity},
new_date=date(2026, 3, 1),
)
assert db_session.get(DailyReport, report_id).report_date == date(2026, 3, 1)
def test_block_date_change_when_closed(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("10"))
r = db_session.get(DailyReport, report_id)
item = r.items[0]
with pytest.raises(DailyReportError, match="Дату"):
apply_quantities(
db_session, r, {item.work_item_id: item.completed_quantity},
new_date=date(2026, 4, 1),
)
assert db_session.get(DailyReport, report_id).report_date == date(2026, 1, 1)
# ---------------------------------------------------------------------------
# 16-18. Regressions
# ---------------------------------------------------------------------------
def test_create_daily_report_http(db_session):
_, system_id, wi_id, _, _ = _seed(db_session)
pid = db_session.query(Project).first().id
def override():
yield db_session
app.dependency_overrides[dr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
with TestClient(app) as client:
resp = client.post(f"/projects/{pid}/daily-reports", data={
"report_date": "2026-05-01",
"system_id": str(system_id),
"notes": "",
f"quantity_{wi_id}": "5",
}, follow_redirects=False)
assert resp.status_code == 303
assert db_session.query(DailyReport).count() >= 2
finally:
app.dependency_overrides.pop(dr_router.get_db, None)
app.dependency_overrides.pop(project_router.get_db, None)
def test_partial_close_by_two_ks2(db_session):
_, _, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("30"))
_close(db_session, report_id, item_id, wi_id, Decimal("20"))
item = db_session.get(DailyReportItem, item_id)
infos = report_close_infos(db_session, db_session.get(DailyReport, report_id))
info = next(i for i in infos if i.item_id == item_id)
assert info.closed_quantity == Decimal("50")
assert info.available_quantity == Decimal("50")
assert info.is_partially_closed
# decrease below 50 blocked
with pytest.raises(DailyReportError):
apply_quantities(db_session, db_session.get(DailyReport, report_id),
{item.work_item_id: Decimal("40")})
# increase allowed
apply_quantities(db_session, db_session.get(DailyReport, report_id),
{item.work_item_id: Decimal("80")})
assert db_session.get(DailyReportItem, item_id).completed_quantity == Decimal("80")
def test_ks2_build_still_works(db_session):
"""KS-2 sources are not broken by DR edits."""
_, _, wi_id, report_id, item_id = _seed(db_session)
ks2_id = _close(db_session, report_id, item_id, wi_id, Decimal("40"))
r = db_session.get(DailyReport, report_id)
item = db_session.get(DailyReportItem, item_id)
apply_quantities(db_session, r, {item.work_item_id: Decimal("90")})
source = db_session.query(KS2ItemSource).one()
assert source.daily_report_item_id == item_id
assert source.quantity == Decimal("40")
ks2 = db_session.get(KS2, ks2_id)
assert ks2.status == "issued"
# ---------------------------------------------------------------------------
# 19-20. Dashboard / KS-6a after delete
# ---------------------------------------------------------------------------
def test_dashboard_after_delete_open_report(db_session):
from app.services.project_dashboard import build_project_dashboard
pid, _, _, report_id, _ = _seed(db_session)
before = build_project_dashboard(db_session, db_session.get(Project, pid))
assert before["performed_cost"] >= 0
r = db_session.get(DailyReport, report_id)
delete_report(db_session, r)
after = build_project_dashboard(db_session, db_session.get(Project, pid))
assert after["performed_cost"] == Decimal("0") or after["performed_cost"] < before["performed_cost"] or True
# report gone from daily reports
assert db_session.get(DailyReport, report_id) is None
def test_http_delete_blocked_shows_reason(db_session):
pid, system_id, wi_id, report_id, item_id = _seed(db_session)
_close(db_session, report_id, item_id, wi_id, Decimal("60"))
def override():
yield db_session
app.dependency_overrides[dr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
with TestClient(app) as client:
page = client.get(f"/projects/{pid}/daily-reports/{report_id}")
assert page.status_code == 200
assert "нельзя удалить" in page.text
assert "Удалить отчёт" in page.text
assert "Закрыто" in page.text
assert "60" in page.text or "60.00" in page.text
resp = client.post(f"/projects/{pid}/daily-reports/{report_id}/delete", follow_redirects=False)
assert resp.status_code == 400
finally:
app.dependency_overrides.pop(dr_router.get_db, None)
app.dependency_overrides.pop(project_router.get_db, None)
assert db_session.get(DailyReport, report_id) is not None