Spaces:
Paused

miracle / api /v1 /escalations.py
dushyantsingh0
backend sprint
ecca730
Raw History Blame Contribute Delete
9.77 kB
"""
Escalation management endpoints: Rules and Audit.
"""
from typing import List, Any, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, String, cast, func
from sqlalchemy.orm import joinedload
from core.deps import get_db, get_current_user
from core.permissions import require_roles, WORKSPACE_ADMIN_ROLES, ALL_SC_ROLES, get_effective_context
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 not current_user.is_platform_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"})
)
new_rule.priority_level = new_rule.priority_level.upper()
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: Optional[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: Enforce strict workspace isolation
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
stmt = stmt.where(EscalationRule.workspace_id == target_ws)
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 not current_user.is_platform_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():
if key == "priority_level":
value = value.upper()
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 not current_user.is_platform_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(
workspace_id: Optional[str] = None,
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 with ticket titles."""
from models.ticket import Ticket
# BOLA: Enforce strict workspace isolation
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
stmt = (
select(AuditLog, Ticket.title.label("entity_title"))
.join(Ticket, AuditLog.entity_id == Ticket.id, isouter=True)
.where(
AuditLog.action.in_(["escalation", "status_change"]),
AuditLog.entity_type == "ticket"
)
)
stmt = stmt.where(AuditLog.workspace_id == target_ws)
stmt = stmt.offset(skip).limit(limit).order_by(AuditLog.created_at.desc())
result = await db.execute(stmt)
# Process results to satisfy the Pydantic response model
logs = []
for row in result.all():
log = row[0]
log.entity_title = row[1]
logs.append(log)
return logs
@router.get("/breaches/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def list_active_breaches(
workspace_id: Optional[str] = None,
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, timezone
# BOLA: Enforce strict workspace isolation
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
# 1. Fetch tickets and ACTIVE rules
stmt = (
select(Ticket, EscalationRule.threshold_minutes)
.options(joinedload(Ticket.assignee))
.join(EscalationRule, and_(
EscalationRule.workspace_id == Ticket.workspace_id,
EscalationRule.priority_level == cast(Ticket.priority, String),
EscalationRule.is_active == True
), isouter=True)
.where(
Ticket.deleted_at.is_(None)
)
)
stmt = stmt.where(Ticket.workspace_id == target_ws)
result = await db.execute(stmt)
rows = result.all()
now = datetime.now(timezone.utc)
detected_tickets = []
for ticket, threshold in rows:
# Default to 24h if no active rule exists
limit = threshold or 1440
# Frozen time for resolved/closed tickets
if ticket.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]:
# Use resolved_at if available, fallback to updated_at
end_time = ticket.resolved_at or ticket.updated_at or now
end_time = end_time.replace(tzinfo=timezone.utc)
created_at = ticket.created_at.replace(tzinfo=timezone.utc)
age_mins = (end_time - created_at).total_seconds() / 60
else:
created_at = ticket.created_at.replace(tzinfo=timezone.utc)
age_mins = (now - created_at).total_seconds() / 60
raw_risk_score = (age_mins / limit) * 100
risk_score = min(100.0, round(raw_risk_score, 1))
# NEW: Descriptive Risk Levels for "Mission Management"
if raw_risk_score > 100:
risk_level = "BREACHED"
elif raw_risk_score > 85:
risk_level = "CRITICAL"
elif raw_risk_score > 60:
risk_level = "WARNING"
else:
risk_level = "NOMINAL"
# Report any mission that has used > 50% of its SLA or has a rule
# For resolved/closed tickets, only report if they ACTUALLY breached
is_active = ticket.status in [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]
should_report = raw_risk_score > 50 if is_active else raw_risk_score > 100
if should_report:
detected_tickets.append({
"id": str(ticket.id),
"title": ticket.title,
"priority": ticket.priority,
"status": ticket.status,
"assigned_name": ticket.assignee.full_name if ticket.assignee else "UNASSIGNED",
"age_minutes": round(age_mins, 1),
"threshold": limit,
"risk_score": risk_score,
"risk_level": risk_level,
"overdue_minutes": max(0, round(age_mins - limit, 1)) if raw_risk_score > 100 else 0,
"minutes_remaining": max(0, round(limit - age_mins, 1)) if raw_risk_score <= 100 and is_active else 0,
"is_escalated": ticket.is_escalated is not None,
"is_breached": raw_risk_score > 100
})
# Sort by risk score (highest risk first)
detected_tickets.sort(key=lambda x: x['risk_score'], reverse=True)
return detected_tickets