Spaces:
Paused

File size: 16,102 Bytes
5eb4857
 
b7980f7
5eb4857
 
b7980f7
5eb4857
 
b7980f7
f3a5b2f
5eb4857
b7980f7
5eb4857
 
 
 
 
b7980f7
 
5eb4857
db51981
 
5eb4857
db51981
5eb4857
e58f87e
5eb4857
 
ca7df66
5eb4857
 
 
ca7df66
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
b7980f7
5eb4857
d9319de
dfcbb7c
 
d9319de
dfcbb7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
5eb4857
b7980f7
5eb4857
 
 
 
 
 
 
5e26742
 
b7980f7
5eb4857
 
 
 
 
 
 
 
d02993d
 
b7980f7
 
d02993d
b7980f7
 
d02993d
 
b7980f7
 
 
 
d02993d
b7980f7
5eb4857
 
5e26742
b7980f7
 
5eb4857
b7980f7
5eb4857
b7980f7
 
e9a2d53
b7980f7
5eb4857
b7980f7
5eb4857
 
 
 
b7980f7
 
d96521a
 
b7980f7
d96521a
5eb4857
 
 
 
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
e9a2d53
 
 
 
 
 
 
5eb4857
 
b7980f7
 
 
e9a2d53
b7980f7
 
ca7df66
 
 
b7980f7
 
5eb4857
e58f87e
5eb4857
 
 
 
b7980f7
 
 
5eb4857
 
b7980f7
 
 
 
f3a5b2f
 
5eb4857
 
 
 
 
 
 
 
 
b7980f7
5eb4857
b7980f7
 
5eb4857
 
e58f87e
5eb4857
 
ca7df66
5eb4857
 
 
b7980f7
ca7df66
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
5eb4857
b7980f7
 
5eb4857
 
b7980f7
dfcbb7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
b7980f7
 
 
 
f3a5b2f
 
5eb4857
 
 
 
 
 
 
 
 
 
 
b7980f7
5eb4857
b7980f7
ca7df66
 
 
 
 
 
5eb4857
 
e58f87e
5eb4857
 
ca7df66
5eb4857
 
 
ca7df66
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
b7980f7
5eb4857
b7980f7
 
 
 
f3a5b2f
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7df66
d96521a
 
 
ca7df66
d96521a
 
 
 
5eb4857
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
 
b7980f7
5eb4857
 
 
 
 
7645bba
 
 
 
 
 
 
5eb4857
7645bba
 
 
ca7df66
7645bba
 
 
ca7df66
 
 
 
 
5eb4857
7645bba
5eb4857
7645bba
5eb4857
 
 
 
 
 
b7980f7
e58f87e
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
"""
Dashboard endpoints for summary stats and activity.
# v2.1 SYNC
"""

from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, or_, Float, desc
from sqlalchemy.orm import joinedload

from core.deps import get_db, get_current_user, get_arq_pool
from core.llm import get_llm
from langchain_core.prompts import ChatPromptTemplate
from models.user import User, UserRole
from models.ticket import Ticket, TicketStatus

from schemas.ticket import TicketResponse, TicketInternalResponse
from typing import Any, Dict, List, Optional, Union

from core.logging import get_logger

router = APIRouter()
logger = get_logger(__name__)

@router.get("/stats/")
async def get_dashboard_stats(
    workspace_id: str = None,
    refresh: bool = False,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    from core.cache import get_cached_search, set_cached_search, delete_cached_search
    
    # Cache lookup
    target_ws = workspace_id or str(current_user.workspace_id)
    cache_key = f"dashboard:stats:{target_ws}:{current_user.id}"
    
    if refresh:
        await delete_cached_search(cache_key)
    else:
        cached_data = await get_cached_search(cache_key)
        if cached_data:
            return cached_data

    from datetime import datetime
    is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
    
    # Identify target workspace
    target_ws = current_user.workspace_id
    is_super_admin = (current_user.role == UserRole.SC_ADMIN)
    is_global = False
    
    if workspace_id:
        if is_super_admin and workspace_id == "all":
            is_global = True
        else:
            # Multi-workspace Agent/Lead Check: Ensure they are authorized for the requested workspace
            if is_super_admin:
                target_ws = workspace_id
            else:
                from models.user_workspace import UserWorkspace
                ws_check = await db.execute(
                    select(UserWorkspace).where(
                        UserWorkspace.user_id == current_user.id,
                        UserWorkspace.workspace_id == workspace_id
                    )
                )
                if ws_check.scalar_one_or_none():
                    target_ws = workspace_id
                else:
                    # Silently fallback to primary if not authorized, or raise 403
                    pass 
    now = datetime.utcnow()

    # 1. Basic Status Counts (Optimized SQL)
    stmt = (
        select(Ticket.status, func.count(Ticket.id))
        .where(Ticket.deleted_at.is_(None))
    )
    if not is_global:
        stmt = stmt.where(Ticket.workspace_id == target_ws)
        
    if current_user.role == UserRole.CUSTOMER_USER:
        # Regular customers see ONLY their own tickets' statuses
        stmt = stmt.where(Ticket.created_by == current_user.id)
    
    stmt = stmt.group_by(Ticket.status)
    counts_res = await db.execute(stmt)
    counts = {row[0]: row[1] for row in counts_res.all()}
    for s in TicketStatus:
        if s not in counts: counts[s] = 0
    total = sum(counts.values())

    from models.feedback import Feedback
    
    # 2. Advanced Metrics (High-Performance SQL Aggregations)
    # Resolution Time: AVG(resolved - created) 
    # CSAT: Join with Feedback table for user ratings
    metrics_stmt = select(
        func.avg(func.extract('epoch', Ticket.resolved_at - Ticket.created_at) / 3600).label("avg_res"),
        func.avg(func.cast(Feedback.rating, Float)).label("avg_csat"),
        func.count(Feedback.id).label("rated_count"),
        func.count(Ticket.id).filter(
            (Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED])) & 
            (Ticket.sla_deadline < now)
        ).label("breached_count")
    ).outerjoin(Feedback, Ticket.id == Feedback.ticket_id).where(Ticket.deleted_at.is_(None))

    if not is_global:
        metrics_stmt = metrics_stmt.where(Ticket.workspace_id == target_ws)
    if current_user.role == UserRole.CUSTOMER_USER:
        metrics_stmt = metrics_stmt.where(Ticket.created_by == current_user.id)
        
    metrics_res = await db.execute(metrics_stmt)
    m_row = metrics_res.fetchone()
    
    avg_res = m_row.avg_res or 0.0
    avg_csat = m_row.avg_csat or 0.0
    rated_count = m_row.rated_count or 0
    breach_count = m_row.breached_count or 0

    # 3. Personalized Open Count
    my_open_stmt = select(func.count(Ticket.id)).where(
        Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]),
        Ticket.deleted_at.is_(None)
    )
    if is_staff:
        my_open_stmt = my_open_stmt.where(Ticket.assigned_to == current_user.id)
    elif current_user.role == UserRole.CUSTOMER_USER:
        # Regular customers see only their own open tickets
        my_open_stmt = my_open_stmt.where(Ticket.created_by == current_user.id)
    # Else: CUSTOMER_ADMIN sees all open tickets in their workspace
    if not is_global:
        my_open_stmt = my_open_stmt.where(Ticket.workspace_id == target_ws)
    my_open_res = await db.execute(my_open_stmt)
    my_open_count = my_open_res.scalar() or 0

    # 4. Personnel Load (Join Optimization)
    personnel_stmt = (
        select(User.full_name, func.count(Ticket.id))
        .join(Ticket, Ticket.assigned_to == User.id)
        .where(
            Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]),
            Ticket.deleted_at.is_(None)
        )
    )
    if not is_global:
        personnel_stmt = personnel_stmt.where(Ticket.workspace_id == target_ws)
        
    personnel_stmt = personnel_stmt.group_by(User.full_name)
    p_res = await db.execute(personnel_stmt)
    personnel_load = [{"name": row[0], "count": row[1]} for row in p_res.all()]
    
    # 5. Final Sanitization (Nexus Privacy Layer)
    response = {
        "total_tickets": total,
        "by_status": counts,
        "workspace_id": target_ws,
        "my_open_count": my_open_count,
        "performance": {
            "avg_resolution_hours": round(avg_res, 1),
            "csat_score": round(avg_csat, 1),
            "rated_count": rated_count,
            "sla_breached_count": breach_count
        }
    }

    if is_staff:
        # Staff get the full forensic payload
        response.update({
            "personnel_load": personnel_load
        })
    
    # Store in cache (60s TTL for stats)
    await set_cached_search(cache_key, response, ttl=60)
    
    return response


@router.get("/my-tickets/", response_model=List[Union[TicketInternalResponse, TicketResponse]])
async def get_my_tickets(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """Get tickets identified with the current user (Created or Assigned). Sanitized for Customers."""
    from sqlalchemy.orm import joinedload
    from api.v1.tickets import sanitize_ticket_response

    stmt = (
        select(Ticket)
        .options(
            joinedload(Ticket.creator),
            joinedload(Ticket.assignee),
            joinedload(Ticket.resolver),
            joinedload(Ticket.feedback)
        )
        .where(
            ((Ticket.created_by == current_user.id) | (Ticket.assigned_to == current_user.id)),
            Ticket.workspace_id == current_user.workspace_id,
            Ticket.deleted_at.is_(None)
        )
        .order_by(Ticket.updated_at.desc())
    )
    result = await db.execute(stmt)
    tickets = result.scalars().all()
    
    # Process each ticket through the role-based sanitizer
    return [await sanitize_ticket_response(t, current_user, db) for t in tickets]


@router.get("/agent-queue/", response_model=List[Union[TicketInternalResponse, TicketResponse]])
async def get_agent_queue(
    workspace_id: str = None,
    refresh: bool = False,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """Get the active ticket queue. Restricted to internal staff only."""
    from core.cache import get_cached_search, set_cached_search, delete_cached_search
    
    # 0. Cache lookup
    target_ws = workspace_id or str(current_user.workspace_id)
    cache_key = f"dashboard:queue:{target_ws}:{current_user.id}"
    
    if refresh:
        await delete_cached_search(cache_key)
    else:
        cached_data = await get_cached_search(cache_key)
        if cached_data:
            return cached_data

    from fastapi import HTTPException
    from sqlalchemy.orm import joinedload
    from api.v1.tickets import sanitize_ticket_response

    is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
    if not is_staff:
        raise HTTPException(status_code=403, detail="Operational Access: Staff privilege required")
    
    target_ws = current_user.workspace_id
    is_super_admin = (current_user.role == UserRole.SC_ADMIN)
    is_global = False

    if is_super_admin and workspace_id == "all":
        is_global = True
    elif workspace_id:
        if is_super_admin:
            target_ws = workspace_id
        else:
            from models.user_workspace import UserWorkspace
            ws_check = await db.execute(
                select(UserWorkspace).where(
                    UserWorkspace.user_id == current_user.id,
                    UserWorkspace.workspace_id == workspace_id
                )
            )
            if ws_check.scalar_one_or_none():
                target_ws = workspace_id

    stmt = (
        select(Ticket)
        .options(
            joinedload(Ticket.creator),
            joinedload(Ticket.assignee),
            joinedload(Ticket.resolver),
            joinedload(Ticket.feedback)
        )
        .where(
            Ticket.deleted_at.is_(None)
        )
    )
    
    if not is_global:
        stmt = stmt.where(Ticket.workspace_id == target_ws)
        
    stmt = stmt.order_by(Ticket.priority.asc(), Ticket.created_at.asc())
    result = await db.execute(stmt)
    tickets = result.scalars().all()
    
    # Process each through sanitizer (will return full forensic view for staff)
    res_data = [await sanitize_ticket_response(t, current_user, db) for t in tickets]
    
    # Store in cache (60s TTL)
    await set_cached_search(cache_key, res_data, ttl=60)
    
    return res_data


@router.get("/ai-insights/")
async def get_ai_insights(
    workspace_id: str = None,
    refresh: bool = False,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    from core.cache import get_cached_search, set_cached_search, delete_cached_search
    
    target_ws = workspace_id or str(current_user.workspace_id)
    cache_key = f"dashboard:insights:{target_ws}:{current_user.id}"
    
    if refresh:
        await delete_cached_search(cache_key)
    else:
        cached_data = await get_cached_search(cache_key)
        if cached_data:
            return cached_data

    """
    Generates a live AI summary and suggested actions for the landing screen.
    Special Mode: For Super-Admins, returns the cached global platform strategic analysis.
    """
    from models.platform_insight import PlatformInsight
    from sqlalchemy import desc
    
    is_super_admin = (current_user.role == UserRole.SC_ADMIN)
    is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
    is_global = (is_super_admin and workspace_id == "all")
    
    # 1. Global Tactical Mode (Super-Admin Only)
    if is_global:
        stmt = select(PlatformInsight).order_by(desc(PlatformInsight.updated_at)).limit(1)
        res = await db.execute(stmt)
        insight = res.scalar_one_or_none()
        
        if insight:
            return {
                "summary": insight.summary,
                "trends": insight.trends,
                "type": "GLOBAL_FORENSIC_SNAPSHOT",
                "last_updated": insight.updated_at.isoformat()
            }
        else:
            return {
                "summary": "Platform-wide strategic analysis is being initialized. Check back shortly.",
                "trends": {},
                "type": "GLOBAL_PENDING"
            }
            
    # 2. Standard Workspace Mode (Isolated)
    # Gather context
    stats = await get_dashboard_stats(workspace_id, refresh=refresh, current_user=current_user, db=db)
    
    # Context varies by role: Staff get the full Queue, Customers get their recent activity
    if is_staff:
        queue = await get_agent_queue(workspace_id, refresh=refresh, current_user=current_user, db=db)
    else:
        # Fallback for CUSTOMER_ADMIN/USER: Get their workspace-visible tickets
        from api.v1.tickets import list_tickets
        queue = await list_tickets(limit=5, current_user=current_user, db=db)
    
    # Prepare Prompt
    llm = get_llm()
    prompt = ChatPromptTemplate.from_template("""
        You are the Nexus Workspace Intelligence Engine. 
        Analyze the following workspace operational data and provide:
        1. A concise, professional "Mission Summary" (2-3 sentences).
        2. Exactly 3 "Suggested Actions" for the lead agent.
        
        DATA:
        - Total Active Tickets: {total}
        - Breached/Urgent: {breached}
        - Distribution: {status_dist}
        - Personnel: {agents}
        
        TICKET SAMPLE:
        {ticket_sample}
        
        Respond in JSON format:
        {{
            "summary": "...",
            "actions": ["...", "...", "..."]
        }}
    """)
    
    # Format ticket sample for context (using dictionary access for sanitized data)
    sample = "\n".join([f"- {t['title']} ({t['priority']}, {t['status']})" for t in queue[:5]])
    
    chain = prompt | llm
    try:
        response = await chain.ainvoke({
            "total": stats["total_tickets"],
            "breached": any(t["priority"] == "P0" for t in queue), 
            "status_dist": stats["by_status"],
            "agents": len(queue),
            "ticket_sample": sample
        })
        
        # Robustly clean LLM response
        text = response.content if hasattr(response, 'content') else str(response)
        text = text.strip()
        if not text:
            raise ValueError("Empty LLM response")
            
        json_str = text.replace("```json", "").replace("```", "").strip()
        import json
        insights = json.loads(json_str)
        
        # Ensure schema compliance
        result = {
            "summary": insights.get("summary", "Analysis complete."),
            "actions": insights.get("actions", ["Review unassigned tickets", "Check SLA trends", "Balance personnel load"])[:3]
        }
        
        # Store in cache (300s TTL for insights)
        await set_cached_search(cache_key, result, ttl=300)
        
        return result
    except Exception as e:
        logger.error(f"AI Insights Failure: {e}")
        return {
            "summary": f"Workspace stabilization in progress. {stats['total_tickets']} active tickets identified.",
            "actions": [
                "Review unassigned P0 tickets in the Operational Board",
                "Perform load balance check across active personnel",
                "Analyze SLA trends for potential breach risks"
            ]
        }

@router.post("/refresh-global/")
async def refresh_global_insights(
    current_user: User = Depends(get_current_user),
    arq_pool = Depends(get_arq_pool)
) -> Any:
    """
    Manually triggers a platform-wide forensic diagnostic cycle.
    Strictly gate to Super-Admins only.
    """
    if current_user.role != UserRole.SC_ADMIN:
        from fastapi import HTTPException
        raise HTTPException(status_code=403, detail="Strategic Refresh: Super-Admin Privilege Required")
    
    await arq_pool.enqueue_job("generate_global_insight", _job_id="global_insight_refresh")
    return {"status": "SUCCESS", "message": "Global strategic analysis enqueued for background processing."}