""" Escalation management endpoints: Rules and Audit. """ from typing import List, Any from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, and_, String, cast from core.deps import get_db, get_current_user from core.permissions import require_roles, WORKSPACE_ADMIN_ROLES, ALL_SC_ROLES from models.user import User, UserRole from models.escalation_rule import EscalationRule from models.audit_log import AuditLog from schemas.escalation import EscalationRuleCreate, EscalationRuleUpdate, EscalationRuleResponse, AuditLogResponse router = APIRouter() @router.post("/rules/", response_model=EscalationRuleResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))]) async def create_escalation_rule( payload: EscalationRuleCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """Admin only: Create an escalation rule.""" # BOLA: Only SC_ADMIN can set up rules for a different workspace target_ws = payload.workspace_id or current_user.workspace_id if payload.workspace_id and current_user.role != UserRole.SC_ADMIN and payload.workspace_id != current_user.workspace_id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="BOLA: Workspace rule assignment restricted to Super Admins." ) # NEW: Validate that the workspace exists to prevent IntegrityError from models.workspace import Workspace ws_check = await db.get(Workspace, target_ws) if not ws_check: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Workspace not found: {target_ws}" ) new_rule = EscalationRule( workspace_id=target_ws, **payload.model_dump(exclude={"workspace_id"}) ) db.add(new_rule) await db.commit() await db.refresh(new_rule) return new_rule @router.get("/rules/", response_model=List[EscalationRuleResponse], dependencies=[Depends(require_roles(ALL_SC_ROLES))]) async def list_escalation_rules( workspace_id: UUID = None, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """Service Center roles: List escalation rules.""" stmt = select(EscalationRule).order_by(EscalationRule.priority_level.asc()) # BOLA: Non-SuperAdmin must be restricted to their own workspace if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(EscalationRule.workspace_id == current_user.workspace_id) elif workspace_id: # SuperAdmins can filter by a target workspace stmt = stmt.where(EscalationRule.workspace_id == workspace_id) result = await db.execute(stmt) return result.scalars().all() @router.patch("/rules/{rule_id}/", response_model=EscalationRuleResponse, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))]) async def update_escalation_rule( rule_id: UUID, payload: EscalationRuleUpdate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """Admin only: Update an escalation rule or toggle its active state.""" stmt = select(EscalationRule).where( EscalationRule.id == rule_id ) if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(EscalationRule.workspace_id == current_user.workspace_id) result = await db.execute(stmt) rule = result.scalar_one_or_none() if not rule: raise HTTPException(status_code=404, detail="Rule not found") update_data = payload.model_dump(exclude_unset=True) for key, value in update_data.items(): setattr(rule, key, value) await db.commit() await db.refresh(rule) return rule @router.delete("/rules/{rule_id}/", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))]) async def delete_escalation_rule( rule_id: UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> None: """Admin only: Remove an escalation rule.""" stmt = select(EscalationRule).where( EscalationRule.id == rule_id ) if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(EscalationRule.workspace_id == current_user.workspace_id) result = await db.execute(stmt) rule = result.scalar_one_or_none() if not rule: raise HTTPException(status_code=404, detail="Rule not found") await db.delete(rule) await db.commit() return None @router.get("/audit/", response_model=List[AuditLogResponse], dependencies=[Depends(require_roles(ALL_SC_ROLES))]) async def view_escalation_audit( skip: int = 0, limit: int = 100, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """View audit trail of escalations and status changes.""" stmt = select(AuditLog).where( AuditLog.action.in_(["escalation", "status_change"]) ) if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(AuditLog.workspace_id == current_user.workspace_id) stmt = stmt.offset(skip).limit(limit).order_by(AuditLog.created_at.desc()) result = await db.execute(stmt) return result.scalars().all() @router.get("/breaches/", dependencies=[Depends(require_roles(ALL_SC_ROLES))]) async def list_active_breaches( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """Get all tickets that are currently in BREACH status based on ACTIVE rules.""" from models.ticket import Ticket, TicketStatus from datetime import datetime # 1. Fetch tickets and ACTIVE rules stmt = ( select(Ticket, EscalationRule.threshold_minutes) .join(EscalationRule, and_( EscalationRule.workspace_id == Ticket.workspace_id, EscalationRule.priority_level == cast(Ticket.priority, String), EscalationRule.is_active == True ), isouter=True) .where( Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), Ticket.deleted_at.is_(None) ) ) if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id) result = await db.execute(stmt) rows = result.all() now = datetime.utcnow() detected_tickets = [] for ticket, threshold in rows: # Default to 24h if no active rule exists limit = threshold or 1440 age_mins = (now - ticket.created_at).total_seconds() / 60 risk_score = (age_mins / limit) * 100 # Include if breached (>100) OR at risk (>75) if risk_score > 75: detected_tickets.append({ "id": str(ticket.id), "title": ticket.title, "priority": ticket.priority, "status": ticket.status, "age_minutes": round(age_mins, 1), "threshold": limit, "risk_score": round(risk_score, 1), "minutes_remaining": max(0, round(limit - age_mins, 1)), "is_escalated": ticket.is_escalated is not None, "is_breached": risk_score > 100 }) # Sort by risk score (highest risk first) detected_tickets.sort(key=lambda x: x['risk_score'], reverse=True) return detected_tickets