"""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