from decimal import Decimal, InvalidOperation 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, ) 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()