Spaces:
Paused

File size: 7,576 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
 
5eb4857
 
 
 
 
 
e58f87e
5eb4857
b7980f7
5eb4857
 
 
 
b7980f7
 
 
 
 
 
 
 
 
5eb4857
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
b7980f7
5eb4857
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
b7980f7
5eb4857
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
b7980f7
 
 
 
 
5eb4857
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
21080cb
5eb4857
 
 
 
21080cb
 
 
 
 
 
5eb4857
 
 
 
 
 
21080cb
 
 
 
5eb4857
 
21080cb
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""
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