Spaces:
Paused

File size: 9,570 Bytes
4777084
 
 
 
d8744fd
4777084
d8744fd
 
4777084
 
 
 
 
 
fb01f3e
 
4777084
 
 
 
 
 
548b54e
 
 
 
 
 
 
 
 
 
 
 
4777084
 
 
 
 
 
 
d8744fd
 
4777084
 
 
 
 
 
d8744fd
 
4777084
 
 
 
 
d8744fd
1e6a00d
 
 
 
 
 
 
d8744fd
 
4777084
 
1e6a00d
 
 
d8744fd
1e6a00d
 
 
 
 
 
4777084
 
d8744fd
1e6a00d
4777084
1e6a00d
 
 
 
 
 
 
4777084
 
6cdfafa
 
 
 
 
 
 
 
 
1e6a00d
6cdfafa
1e6a00d
 
 
6cdfafa
 
1e6a00d
 
 
 
6cdfafa
 
1e6a00d
 
94afd06
 
 
 
 
 
 
 
 
 
6cdfafa
 
 
 
 
 
 
 
 
 
 
 
1e6a00d
6cdfafa
 
1e6a00d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548b54e
 
 
1e6a00d
548b54e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e6a00d
4777084
1e6a00d
4777084
 
1e6a00d
 
 
 
 
548b54e
1e6a00d
 
4777084
1e6a00d
 
 
 
 
07b09f1
 
 
 
 
 
 
d8744fd
07b09f1
 
 
 
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
"""
Analytics and personnel-related background tasks.
"""

from typing import Optional, Dict
from uuid import UUID
from datetime import datetime, timezone, timedelta
from sqlalchemy import select

from core.database import async_session_factory
from core.logging import get_logger
from core.llm import get_llm
from models.user import User, UserRole
from models.user_workspace import UserWorkspace
from models.ticket import Ticket, TicketStatus
from models.escalation_rule import EscalationRule
from models.message import Message
from tasks.system import check_cron_lock
from langchain_core.prompts import ChatPromptTemplate

logger = get_logger(__name__)

def _compute_tier(compliance: int, resolved: int, active_load: int) -> str:
    if compliance >= 90 and resolved >= 8:
        return "TOP"
    elif compliance >= 75 and resolved >= 3:
        return "STRONG"
    elif compliance >= 55:
        return "STEADY"
    elif compliance >= 30:
        return "AT_RISK"
    else:
        return "CRITICAL"

async def harvest_expertise_task(ctx, ticket_id: UUID, **kwargs):
    """Analyze a resolved ticket and harvest skills for the agent."""
    from agents.staff_profiler import harvest_agent_skills
    async with async_session_factory() as db:
        try:
            stmt = select(Ticket).where(Ticket.id == ticket_id)
            ticket = (await db.execute(stmt)).scalar_one_or_none()
            if not ticket or not ticket.assigned_to:
                return

            msg_stmt = select(Message).where(Message.ticket_id == ticket_id).order_by(Message.created_at.asc())
            msgs = (await db.execute(msg_stmt)).scalars().all()

            agent_stmt = select(User).where(User.id == ticket.assigned_to)
            agent = (await db.execute(agent_stmt)).scalar_one_or_none()
            if not agent:
                return

            await harvest_agent_skills(db, ticket, msgs, agent)
        except Exception as e:
            logger.error(f"Expertise Harvesting failed: {e}")

async def generate_nightly_personnel_analytics(ctx, workspace_id: Optional[str] = None, user_id: Optional[UUID] = None, **kwargs):
    """
    Gathers user activity metrics and generates an AI narrative.
    If workspace_id is provided, it targets only that workspace.
    If user_id is provided, it targets only that user.
    """
    # Only check cron lock if this is a nightly run (no workspace_id/user_id)
    if not workspace_id and not user_id:
        if not await check_cron_lock(ctx, "generate_nightly_personnel_analytics"):
            return

    async with async_session_factory() as db:
        # 1. Fetch memberships to process
        stmt = select(UserWorkspace).where(
            UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), 
            UserWorkspace.is_active
        )
        if workspace_id:
            stmt = stmt.where(UserWorkspace.workspace_id == UUID(workspace_id))
        if user_id:
            stmt = stmt.where(UserWorkspace.user_id == user_id)
            
        memberships = (await db.execute(stmt)).scalars().all()
        
        now = datetime.now(timezone.utc)
        last_30d = now - timedelta(days=30)
        
        # 2. Fetch escalation rules (workspace-aware)
        rules_res = await db.execute(select(EscalationRule))
        all_rules = rules_res.scalars().all()
        rules_map = {}
        for r in all_rules:
            rules_map.setdefault(str(r.workspace_id), {})[r.priority_level.upper()] = r.threshold_minutes

        for uw in memberships:
            try:
                # 2. GATHER INTELLIGENCE (Sync with API Forensic Logic)
                from sqlalchemy import or_
                tracked_stmt = select(Ticket).where(
                    Ticket.workspace_id == uw.workspace_id,
                    Ticket.deleted_at.is_(None),
                    or_(
                        (Ticket.resolved_by == uw.user_id) & (Ticket.resolved_at >= last_30d),
                        (Ticket.assigned_to == uw.user_id) & (Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]))
                    )
                )
                tracked_tickets = (await db.execute(tracked_stmt)).scalars().all()
                
                ws_rules = rules_map.get(str(uw.workspace_id), {})
                
                res_count = 0
                active_count = 0
                breached = 0
                categories = {}
                total_res_time = 0
                
                for t in tracked_tickets:
                    # Robust priority lookup
                    p_val = t.priority.value if hasattr(t.priority, 'value') else str(t.priority)
                    limit = ws_rules.get(str(p_val).upper(), 1440)

                    # Normalize DB timestamps to UTC-aware (stored naive, Python now() is aware)
                    def _utc(dt):
                        if dt is None:
                            return None
                        return dt if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc)

                    end_time = _utc(t.resolved_at) or now
                    created_at = _utc(t.created_at)
                    duration_mins = (end_time - created_at).total_seconds() / 60
                    
                    if t.resolved_at:
                        res_count += 1
                        total_res_time += duration_mins
                        # Category count (only for resolved)
                        cat = (t.category or "General").title()
                        categories[cat] = categories.get(cat, 0) + 1
                    else:
                        active_count += 1
                    
                    if duration_mins > limit:
                        breached += 1

                total_tracked = len(tracked_tickets)
                compliance = round((total_tracked - breached) / total_tracked * 100) if total_tracked > 0 else 100
                avg_res_h = round(total_res_time / res_count / 60, 1) if res_count > 0 else 0
                
                # Generate AI Narrative
                llm = get_llm(timeout=45)
                
                # Dynamic context for prompt
                metrics_summary = f"""
                - Resolved (30d): {res_count}
                - Active Load: {active_count}
                - SLA Compliance: {compliance}%
                - Avg Resolution Time: {avg_res_h} hours
                - Primary Expertise: {', '.join([f"{k} ({v})" for k, v in sorted(categories.items(), key=lambda x: x[1], reverse=True)[:3]])}
                """
                
                prompt = ChatPromptTemplate.from_template("""
                You are a service operations analyst. Generate ONE concise, insight-driven sentence about this support agent's performance pattern β€” focus on what the data implies, not what it says.

                Metrics (do NOT restate these numbers directly):
                {metrics}

                Rules:
                - Do NOT start with "The agent", "Over the past 30 days", "The staff member", or any similar opener
                - Start directly with the core finding, risk, or strength
                - Highlight the most significant signal: bottleneck, throughput gap, SLA risk, or standout pattern
                - If Resolved is 0, flag the throughput gap; if SLA is below 50%, flag the compliance risk
                - Be specific and actionable β€” no generic observations

                Good examples:
                - "Backlog pressure is intensifying β€” 7 unresolved cases with no recent throughput signals capacity saturation."
                - "High throughput combined with 9.9h average resolution suggests complex-case specialization rather than general volume handling."
                - "Zero resolutions despite active load indicates potential assignment-pipeline misalignment or escalation dependency."
                - "SLA compliance at 14% signals systemic delays β€” active cases are consistently breaching agreed response windows."

                Output ONLY the single insight sentence.
                """)
                
                narrative_res = await (prompt | llm).ainvoke({"metrics": metrics_summary})
                
                uw.ai_narrative = narrative_res.content.strip()
                uw.activity_summary = {
                    "resolved_30d": res_count,
                    "compliance": compliance,
                    "avg_res_h": avg_res_h,
                    "active_load": active_count,
                    "tier": _compute_tier(compliance, res_count, active_count),
                    "last_calculated": now.isoformat()
                }
                db.add(uw)
                # Commit frequently to avoid massive transactions if processing many users
                await db.commit()
            except Exception as e:
                logger.error(f"Failed to generate narrative for user {uw.user_id}: {e}")
                continue

        # 3. Broadcast Sync Signal
        from core.websockets import manager
        if workspace_id:
            try:
                await manager.broadcast_to_workspace(UUID(workspace_id), {
                    "type": "PERSONNEL_ANALYTICS_READY",
                    "workspace_id": workspace_id
                })
                logger.info(f"βœ… Personnel analytics ready signal broadcasted for workspace: {workspace_id}")
            except Exception as broadcast_err:
                logger.error(f"Failed to broadcast personnel analytics signal: {broadcast_err}")