from decimal import Decimal, InvalidOperation from sqlalchemy import func from app.models import boq from app.models.agreement import Agreement, AgreementItem from app.services.effective_plan import ( BaseBoqConfigurationError, build_effective_plan, work_item_scope_document_id, ) ZERO = Decimal("0") def decimal_value(value, label): try: result = Decimal(str(value).strip().replace(",", ".")) except (InvalidOperation, ValueError, AttributeError) as exc: raise ValueError(f"Invalid {label}") from exc if not result.is_finite(): raise ValueError(f"Invalid {label}") return result def _require_draft(agreement): if agreement.status != "draft": raise ValueError("Only draft agreements can be changed") def available_work_items(db, agreement): _require_draft(agreement) plan = build_effective_plan(db, agreement.project_id) existing_ids = {row[0] for row in db.query(AgreementItem.work_item_id).filter( AgreementItem.agreement_id == agreement.id ).all()} result = [] for row in plan["items"]: if row.item.id in existing_ids: continue if agreement.boq_document_id is not None: if work_item_scope_document_id(db, row.item) != agreement.boq_document_id: continue result.append(row) return result def _unit_rate(row): item = row.item if item.unit_price is not None: rate = Decimal(str(item.unit_price)) elif row.quantity: rate = row.amount / row.quantity else: raise ValueError(f"WorkItem {item.id} has no usable unit price") if rate < 0: raise ValueError(f"WorkItem {item.id} has a negative unit price") return rate def add_existing_item(db, agreement, work_item_id, quantity_delta): _require_draft(agreement) plan_rows = available_work_items(db, agreement) row = next((entry for entry in plan_rows if entry.item.id == work_item_id), None) if row is None: raise ValueError("WorkItem is already added or outside this agreement scope") delta = decimal_value(quantity_delta, "quantity delta") if delta == 0: raise ValueError("Quantity delta cannot be zero") if row.quantity + delta < 0: raise ValueError("Effective quantity cannot become negative") rate = _unit_rate(row) line = AgreementItem( agreement_id=agreement.id, work_item_id=row.item.id, change_type="increase" if delta > 0 else "decrease", quantity_delta=delta, amount_delta=delta * rate, source_number=row.item.source_number, source_name=row.item.name, source_model=row.item.model, source_manufacturer=row.item.manufacturer, source_unit=row.item.unit, source_unit_price=rate, source_system_id=row.item.system_id, source_section_id=row.item.section_id, ) db.add(line) db.flush() return line def _validate_system_section(db, project_id, system_id, section_id): if system_id is None: if section_id is not None: raise ValueError("A section requires a selected system") return system = db.query(boq.System).filter( boq.System.id == system_id, boq.System.project_id == project_id ).first() if system is None: raise ValueError("System does not belong to this project") if section_id is not None: section = db.query(boq.Section).filter( boq.Section.id == section_id, boq.Section.system_id == system_id ).first() if section is None: raise ValueError("Section does not belong to the selected system") def _validate_source_document(db, project_id, document_id): if document_id is None: return None document = db.query(boq.BoqDocument).filter( boq.BoqDocument.id == document_id, boq.BoqDocument.project_id == project_id, boq.BoqDocument.agreement_id.is_(None), ).first() if document is None: raise ValueError("BOQ document does not belong to this project") return document.id def add_new_item(db, agreement, *, name, model, manufacturer, unit, quantity_delta, unit_price, system_id=None, section_id=None, source_boq_document_id=None): _require_draft(agreement) name = (name or "").strip() if not name: raise ValueError("Position name is required") delta = decimal_value(quantity_delta, "quantity delta") price = decimal_value(unit_price, "unit price") if delta <= 0: raise ValueError("New position quantity must be greater than zero") if price < 0: raise ValueError("Unit price cannot be negative") _validate_system_section(db, agreement.project_id, system_id, section_id) source_boq_document_id = _validate_source_document( db, agreement.project_id, source_boq_document_id ) if agreement.boq_document_id is not None and source_boq_document_id not in (None, agreement.boq_document_id): raise ValueError("Position BOQ must match the agreement scope") item = boq.WorkItem( project_id=agreement.project_id, boq_document_id=None, system_id=system_id, section_id=section_id, name=name, model=(model or "").strip() or None, manufacturer=(manufacturer or "").strip() or None, unit=(unit or "").strip() or None, quantity=Decimal("0"), amount=Decimal("0"), unit_price=price, ) db.add(item) db.flush() line = AgreementItem( agreement_id=agreement.id, work_item_id=item.id, change_type="new_position", quantity_delta=delta, amount_delta=delta * price, source_name=item.name, source_model=item.model, source_manufacturer=item.manufacturer, source_unit=item.unit, source_unit_price=price, source_system_id=system_id, source_section_id=section_id, source_boq_document_id=source_boq_document_id, ) db.add(line) db.flush() return line def update_draft_item(db, agreement, line, *, quantity_delta, unit_price=None, name=None, model=None, manufacturer=None, unit=None, system_id=None, section_id=None): _require_draft(agreement) delta = decimal_value(quantity_delta, "quantity delta") if delta == 0 or (line.change_type == "new_position" and delta < 0): raise ValueError("Invalid quantity delta") item = db.query(boq.WorkItem).filter( boq.WorkItem.id == line.work_item_id, boq.WorkItem.project_id == agreement.project_id, ).first() if item is None: raise ValueError("WorkItem not found in this project") if line.change_type == "new_position": price = decimal_value(unit_price, "unit price") if price < 0: raise ValueError("Unit price cannot be negative") name = (name or "").strip() if not name: raise ValueError("Position name is required") _validate_system_section(db, agreement.project_id, system_id, section_id) item.name = name item.model = (model or "").strip() or None item.manufacturer = (manufacturer or "").strip() or None item.unit = (unit or "").strip() or None item.system_id = system_id item.section_id = section_id item.unit_price = price line.source_name = item.name line.source_model = item.model line.source_manufacturer = item.manufacturer line.source_unit = item.unit line.source_unit_price = price line.source_system_id = system_id line.source_section_id = section_id else: plan = build_effective_plan(db, agreement.project_id) row = next((entry for entry in plan["items"] if entry.item.id == item.id), None) if row is None: raise ValueError("WorkItem is not part of the current effective plan") if agreement.boq_document_id is not None and work_item_scope_document_id(db, item) != agreement.boq_document_id: raise ValueError("WorkItem is outside this agreement scope") if row.quantity + delta < 0: raise ValueError("Effective quantity cannot become negative") rate = _unit_rate(row) line.change_type = "increase" if delta > 0 else "decrease" line.source_unit_price = rate line.quantity_delta = delta price = decimal_value(line.source_unit_price, "unit price") line.amount_delta = delta * price db.flush() return line def delete_draft_item(db, agreement, line): _require_draft(agreement) item = line.work_item is_new = line.change_type == "new_position" db.delete(line) db.flush() if is_new and item is not None: db.delete(item) db.flush() document = item.boq_document if document is not None and document.agreement_id == agreement.id and not db.query(boq.WorkItem.id).filter( boq.WorkItem.boq_document_id == document.id ).first(): db.delete(document) db.flush() def _work_item_is_orphan_for_draft(db, item, agreement) -> bool: """True when this WorkItem exists only because of the given draft agreement.""" if item is None: return False if item.boq_document_id is not None: return False other_lines = db.query(AgreementItem.id).filter( AgreementItem.work_item_id == item.id, AgreementItem.agreement_id != agreement.id, ).first() if other_lines is not None: return False from app.models.daily_report import DailyReportItem from app.models.ks2 import KS2Item, KS2ItemSource if db.query(DailyReportItem.id).filter(DailyReportItem.work_item_id == item.id).first(): return False if db.query(KS2Item.id).filter(KS2Item.work_item_id == item.id).first(): return False return True def delete_draft_agreement(db, agreement): """ Delete a draft Agreement and its items atomically. Orphan WorkItems created solely for this draft (new_position) are removed. Base WorkItems are never deleted. Approved agreements are rejected. """ try: if agreement is None: raise ValueError("Agreement not found") _require_draft(agreement) lines = list(agreement.items) orphan_items = [] for line in lines: if line.change_type == "new_position" and _work_item_is_orphan_for_draft( db, line.work_item, agreement ): orphan_items.append(line.work_item) for item in orphan_items: db.delete(item) db.flush() document = item.boq_document if ( document is not None and document.agreement_id == agreement.id and not db.query(boq.WorkItem.id) .filter(boq.WorkItem.boq_document_id == document.id) .first() ): db.delete(document) db.flush() # ORM cascade on Agreement.items removes AgreementItem rows. db.delete(agreement) db.commit() except ValueError: db.rollback() raise except Exception as exc: db.rollback() raise ValueError(f"Failed to delete agreement: {exc}") from exc def _closed_quantity_for_work_item(db, work_item_id: int) -> Decimal: """Sum of KS2ItemSource quantities for a work item, excluding cancelled KS-2.""" from app.models.ks2 import KS2, KS2Item, KS2ItemSource total = db.query(func.coalesce(func.sum(KS2ItemSource.quantity), ZERO)).join( KS2Item, KS2Item.id == KS2ItemSource.ks2_item_id ).join( KS2, KS2.id == KS2Item.ks2_id ).filter( KS2Item.work_item_id == work_item_id, KS2.status != "cancelled", ).scalar() return Decimal(str(total or 0)) def _agreement_item_used_volume(db, agreement, line: AgreementItem) -> Decimal: """ Return how much of *this* AgreementItem's positive delta is consumed by non-cancelled KS-2 closings, using FIFO layering. Layers are stacked bottom-up: base BOQ quantity first, then each approved AgreementItem's quantity_delta in (Agreement.id, AgreementItem.id) order. Closed volume fills from the bottom. For an increase / new_position line the "used" part is the portion of closed volume that falls inside *that* line's positive delta window. For ``decrease`` lines the semantics of "used" are ambiguous (a decrease only shrinks the plan), so we keep the pre-existing conservative rule: any closed volume on the WorkItem blocks cancellation. """ if line.change_type == "decrease": closed = _closed_quantity_for_work_item(db, line.work_item_id) return closed if closed > ZERO else ZERO item = db.query(boq.WorkItem).filter(boq.WorkItem.id == line.work_item_id).first() base_qty = ZERO if line.change_type == "new_position" else ( Decimal(str(item.quantity)) if item and item.quantity is not None else ZERO ) # All approved AgreementItems on this WorkItem, FIFO order. all_lines = ( db.query(AgreementItem) .join(Agreement, Agreement.id == AgreementItem.agreement_id) .filter( AgreementItem.work_item_id == line.work_item_id, Agreement.status == "approved", ) .order_by(Agreement.id, AgreementItem.id) .all() ) prior_delta = ZERO for aline in all_lines: if aline.id == line.id: break prior_delta += Decimal(str(aline.quantity_delta)) floor = base_qty + prior_delta closed = _closed_quantity_for_work_item(db, line.work_item_id) delta = Decimal(str(line.quantity_delta)) return max(ZERO, min(closed - floor, delta)) def agreement_cancel_block_reason(db, agreement) -> str | None: """Return why an approved agreement cannot be cancelled, or None.""" if agreement.status == "draft": return "Черновик нельзя отменить. Сначала утвердите ДС." if agreement.status == "cancelled": return "ДС уже отменено." for line in agreement.items: used = _agreement_item_used_volume(db, agreement, line) if used > ZERO: return "Нельзя отменить ДС: его объём уже использован в закрытых КС-2." return None def cancel_agreement(db, agreement): """ Cancel an approved agreement atomically. The agreement becomes cancelled and drops out of the effective plan. AgreementItems, WorkItems and history are preserved. """ try: reason = agreement_cancel_block_reason(db, agreement) if reason is not None: raise ValueError(reason) # Re-check status inside the transaction if agreement.status != "approved": raise ValueError("Отменить можно только утверждённое ДС") agreement.status = "cancelled" db.commit() db.refresh(agreement) return agreement except ValueError: db.rollback() raise except Exception as exc: db.rollback() raise ValueError(f"Не удалось отменить ДС: {exc}") from exc