Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
ad4fe35
1
Parent(s): 4e16b54
backend stabilization
Browse filesFiles changed (23)
- agents/nexus_customer.py+14-6
- agents/nexus_master.py+73-27
- agents/prompts.py+1-1
- api/v1/attachments.py+12-7
- api/v1/kb.py+5-1
- api/v1/nexus_stream.py+28-4
- core/cache.py+8
- frontend/apps/customer/src/App.tsx+8-4
- frontend/apps/customer/src/components/Analytics.tsx+31-62
- frontend/apps/customer/src/components/Dashboard.tsx+23-41
- frontend/apps/customer/src/components/TicketList.tsx+1-1
- frontend/apps/internal/src/App.tsx+7-4
- frontend/apps/internal/src/components/AnalyticsDashboard.tsx+2-1
- frontend/apps/internal/src/components/KanbanBoard.module.css+51
- frontend/apps/internal/src/components/KanbanBoard.tsx+67-44
- frontend/apps/internal/src/components/KnowledgeBase.tsx+3-3
- frontend/apps/internal/src/components/TicketBoard.tsx+1
- frontend/apps/internal/src/components/TicketGrid.tsx+1-1
- frontend/packages/shared/src/components/NexusMarkdown.tsx+7-1
- frontend/packages/shared/src/hooks/useDashboard.ts+104-35
- frontend/packages/shared/src/hooks/useTickets.ts+104-35
- frontend/packages/shared/src/hooks/useUsers.ts+36-15
- frontend/packages/shared/src/hooks/useWorkspaces.ts+35-11
24 unmodified lines252627282930162 unmodified lines19319419519619719819920020120220320420520620720820921021121224 unmodified linesfrom agents.nexus_master import (NexusState,ResponderOutput,nexus_vision_gatherer,nexus_context_hydrator,nexus_input_guard,162 unmodified linesworkflow = StateGraph(NexusState)checkpointer = SQLAlchemySaver()workflow.add_node("vision", nexus_vision_gatherer)workflow.add_node("hydrator", nexus_context_hydrator)workflow.add_node("input_guard", nexus_input_guard)workflow.add_node("router", nexus_customer_router)workflow.add_node("executor", nexus_customer_executor)# NO APPOVAL NODEworkflow.add_node("responder", nexus_customer_responder)workflow.add_node("pruner", nexus_history_pruner)workflow.add_node("output_guard", nexus_output_guard)workflow.add_node("auditor", nexus_forensic_auditor)workflow.set_entry_point("vision")workflow.add_edge("vision", "hydrator")workflow.add_edge("hydrator", "input_guard")def route_after_router(state: NexusState) -> str:last_msg = state["messages"][-1]24 unmodified lines2526272829303132162 unmodified lines19519619719819920020120220320420520620720820921021121221321421521621721821922024 unmodified linesfrom agents.nexus_master import (NexusState,ResponderOutput,nexus_pre_processor,nexus_gatekeeper,nexus_vision_gatherer,nexus_context_hydrator,nexus_input_guard,162 unmodified linesworkflow = StateGraph(NexusState)checkpointer = SQLAlchemySaver()workflow.add_node("pre_processor", nexus_pre_processor)workflow.add_node("gatekeeper", nexus_gatekeeper)workflow.add_node("input_guard", nexus_input_guard)workflow.add_node("router", nexus_customer_router)workflow.add_node("executor", nexus_customer_executor)# NO APPROVAL NODEworkflow.add_node("responder", nexus_customer_responder)workflow.add_node("pruner", nexus_history_pruner)workflow.add_node("output_guard", nexus_output_guard)workflow.add_node("auditor", nexus_forensic_auditor)workflow.set_entry_point("pre_processor")workflow.add_edge("pre_processor", "gatekeeper")def route_after_gatekeeper(state: NexusState) -> str:if state.get("current_tool_output") == "GATEKEEPER_RESPONSE":return "pruner"return "input_guard"workflow.add_conditional_edges("gatekeeper", route_after_gatekeeper, {"input_guard": "input_guard", "pruner": "pruner"})def route_after_router(state: NexusState) -> str:last_msg = state["messages"][-1]
83 unmodified lines8485868788899091929394959697989910010110210310 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114239 unmodified lines182183184185186187188189190191348 unmodified lines5405415425435445455465473 unmodified lines5515525535545555565575585595605615625635641 unmodified line56656756856957057157283 unmodified lines"""Extracts visual context (images) from ticket attachments."""if not state.get("ticket_id"):return {"vision_context": []}async with async_session_factory() as db:# We look for images in the last human message or the ticket itselflast_msg = state["messages"][-1].contentvision_context = await extract_visual_context(db, state["workspace_id"], last_msg)return {"vision_context": vision_context}async def nexus_context_hydrator(state: NexusState) -> Dict[str, Any]:"""Hydrates the state with full technical context if a ticket_id is present.Ensures the LLM "sees" the description and findings without needing a tool call."""t_id = safe_uuid(state.get("ticket_id"))if not t_id:10 unmodified linesif not ticket:return {"ticket_context": "Ticket context provided but record not found."}# Format the context blockfindings = ticket.ai_metadata.get("processed_steps", [])findings_str = "\n".join([f"- {s.get('name')}: {s.get('status')}" for s in findings])context = f"""TICKET_CONTEXT:ID: {ticket.id}TITLE: {ticket.title}STATUS: {ticket.status}PRIORITY: {ticket.priority}DESCRIPTION:{ticket.description}AI_FINDINGS_LOG:{findings_str or 'No autonomous findings yet.'}INTERNAL_SUMMARY:{ticket.ai_metadata.get('summaries', {}).get('internal_summary', 'None')}"""return {"ticket_context": context.strip()}async def nexus_input_guard(state: NexusState) -> Dict[str, Any]:"""Scans the user query for prompt injection and ill intent.39 unmodified lines"ticket_context": state.get("ticket_context", "None")})# Fast-Path: If NO tool calls but very short message, bypass responder loop if needed?# Actually, LangGraph's router node works best by just returning the message with tool_calls.# 5. Extract Native Tool Callsreturn {"messages": [response]}import asyncio348 unmodified linesworkflow = StateGraph(NexusState)checkpointer = SQLAlchemySaver()workflow.add_node("vision", nexus_vision_gatherer)workflow.add_node("hydrator", nexus_context_hydrator)workflow.add_node("input_guard", nexus_input_guard)workflow.add_node("router", nexus_router)workflow.add_node("executor", nexus_tool_executor)3 unmodified linesworkflow.add_node("output_guard", nexus_output_guard)workflow.add_node("auditor", nexus_forensic_auditor)workflow.set_entry_point("vision")workflow.add_edge("vision", "hydrator")workflow.add_edge("hydrator", "input_guard")def route_after_router(state: NexusState) -> str:last_msg = state["messages"][-1]if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:return "executor"return "responder"def should_continue(state: NexusState) -> str:if state.get("current_tool_output") == "SAFETY_BLOCK":1 unmodified linereturn "router"workflow.add_conditional_edges("input_guard", should_continue, {"router": "router", "auditor": "auditor"})workflow.add_conditional_edges("router", route_after_router, {"executor": "executor", "responder": "responder"})def check_approval(state: NexusState) -> str:if state.get("pending_actions") and not state.get("action_approved"):83 unmodified lines8485868788899091929394959697989910010110210310 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617739 unmodified lines217218219220221222223224225226227228229348 unmodified lines5785795805815825835845853 unmodified lines5895905915925935945955965975985996006016026036046056066076086096101 unmodified line61261361461561661761883 unmodified lines"""Extracts visual context (images) from ticket attachments."""if "images" not in state["messages"][-1].content and "![" not in state["messages"][-1].content:return {"vision_context": []}if not state.get("ticket_id"):return {"vision_context": []}async with async_session_factory() as db:last_msg = state["messages"][-1].contentvision_context = await extract_visual_context(db, state["workspace_id"], last_msg)return {"vision_context": vision_context}async def nexus_context_hydrator(state: NexusState) -> Dict[str, Any]:"""Hydrates the state with full technical context if a ticket_id is present."""t_id = safe_uuid(state.get("ticket_id"))if not t_id:10 unmodified linesif not ticket:return {"ticket_context": "Ticket context provided but record not found."}findings = ticket.ai_metadata.get("processed_steps", [])findings_str = "\n".join([f"- {s.get('name')}: {s.get('status')}" for s in findings])context = f"""TICKET_CONTEXT:ID: {ticket.id} | TITLE: {ticket.title} | STATUS: {ticket.status}DESCRIPTION: {ticket.description}AI_FINDINGS: {findings_str or 'None'}"""return {"ticket_context": context.strip()}async def nexus_pre_processor(state: NexusState) -> Dict[str, Any]:"""Runs vision gathering and ticket hydration in parallel to reduce time-to-first-token."""results = await asyncio.gather(nexus_vision_gatherer(state),nexus_context_hydrator(state))# Merge result dictscombined = {}for r in results:combined.update(r)return combinedasync def nexus_gatekeeper(state: NexusState) -> Dict[str, Any]:"""Handles simple conversational turns (greetings, thanks) using state context.Short-circuits the graph to avoid heavy LLM calls while maintaining memory."""last_msg = state["messages"][-1].content.strip().lower()user_name = state.get("user_name", "there")summary = state.get("internal_summary", "")# 1. Fast Path: Greetings/Closinggreetings = ["hi", "hello", "hey", "good morning", "good afternoon", "good evening", "yo"]thanks = ["thanks", "thank you", "thx", "cool", "awesome", "great"]is_greeting = any(last_msg == g or last_msg.startswith(g + " ") for g in greetings)is_thanks = any(last_msg == t or last_msg.startswith(t + " ") for t in thanks)if (is_greeting or is_thanks) and len(last_msg) < 30:if is_greeting:response = f"Hello {user_name}! "if summary:response += f"I'm ready to help you continue with your work on {summary}. What's on your mind?"else:response += "How can I help you within your workspace today?"else:response = f"You're very welcome, {user_name}! I'm here if you need more assistance with your projects."msg = AIMessage(content=response)msg.id = str(uuid4())return {"messages": [msg], "current_tool_output": "GATEKEEPER_RESPONSE"}return {"current_tool_output": "PROCEED"}async def nexus_input_guard(state: NexusState) -> Dict[str, Any]:"""Scans the user query for prompt injection and ill intent.39 unmodified lines"ticket_context": state.get("ticket_context", "None")})# 5. Extract Native Tool Calls# OPTIMIZATION: If the router produced a direct text response (common in CONVERSE or direct answers),# we can mark it so we skip the responder node.if not hasattr(response, "tool_calls") or not response.tool_calls:if response.content and len(response.content) > 1:return {"messages": [response], "current_tool_output": "DIRECT_RESPONSE"}return {"messages": [response]}import asyncio348 unmodified linesworkflow = StateGraph(NexusState)checkpointer = SQLAlchemySaver()workflow.add_node("pre_processor", nexus_pre_processor)workflow.add_node("gatekeeper", nexus_gatekeeper)workflow.add_node("input_guard", nexus_input_guard)workflow.add_node("router", nexus_router)workflow.add_node("executor", nexus_tool_executor)3 unmodified linesworkflow.add_node("output_guard", nexus_output_guard)workflow.add_node("auditor", nexus_forensic_auditor)workflow.set_entry_point("pre_processor")workflow.add_edge("pre_processor", "gatekeeper")def route_after_gatekeeper(state: NexusState) -> str:if state.get("current_tool_output") == "GATEKEEPER_RESPONSE":return "pruner" # Skip everythingreturn "input_guard"workflow.add_conditional_edges("gatekeeper", route_after_gatekeeper, {"input_guard": "input_guard", "pruner": "pruner"})def route_after_router(state: NexusState) -> str:last_msg = state["messages"][-1]if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:return "executor"if state.get("current_tool_output") == "DIRECT_RESPONSE":return "pruner" # Short-circuit responderreturn "responder"def should_continue(state: NexusState) -> str:if state.get("current_tool_output") == "SAFETY_BLOCK":1 unmodified linereturn "router"workflow.add_conditional_edges("input_guard", should_continue, {"router": "router", "auditor": "auditor"})workflow.add_conditional_edges("router", route_after_router, {"executor": "executor", "responder": "responder", "pruner": "pruner"})def check_approval(state: NexusState) -> str:if state.get("pending_actions") and not state.get("action_approved"):
66 unmodified lines6768697071727366 unmodified linesTICKET_DATA (AUTOMATICALLY LOADED):{ticket_context}Respond ONLY with the tool call. If the request requires no specialized data, respond with CONVERSE."""RESPONDER_SYSTEM_PROMPT_V1 = """66 unmodified lines6768697071727366 unmodified linesTICKET_DATA (AUTOMATICALLY LOADED):{ticket_context}Respond ONLY with the tool call. If the request requires no specialized data (e.g. conversational greetings, simple acknowledgments, or direct factual answers based on provided context), provide a direct, concise response in the content field. If you are unsure and need to clarify, respond with CONVERSE."""RESPONDER_SYSTEM_PROMPT_V1 = """
143 unmodified lines1441451461471481491501511521531541551 unmodified line157158159160161162163164165166167168169170143 unmodified linesis_staff = current_user.role in ALL_SC_ROLES# Fetch attachment and join with Ticket to verify workspace contextstmt = (select(Attachment, Ticket).join(Ticket, Attachment.ticket_id == Ticket.id).where(Attachment.id == attachment_id,Attachment.workspace_id == current_user.workspace_id,Attachment.deleted_at.is_(None)))1 unmodified lineresult = await db.execute(stmt)row = result.fetchone()if not row:raise HTTPException(status_code=404, detail="Attachment not found or access denied")attachment, ticket = row[0], row[1]# Workspace-wide visibility: If they can see the ticket, they can see the attachment# (Matches get_ticket BOLA)if not is_staff and ticket.workspace_id != current_user.workspace_id:raise HTTPException(status_code=403, detail="Not authorized to download this attachment")storage = get_storage_provider()if attachment.storage_backend == "s3":143 unmodified lines1441451461471481491501511521531541551 unmodified line157158159160161162163164165166167168169170171172173174175143 unmodified linesis_staff = current_user.role in ALL_SC_ROLES# Fetch attachment and join with Ticket to verify workspace context# Use outerjoin to support generic attachments (e.g. uploaded but not yet linked to a ticket)stmt = (select(Attachment, Ticket).outerjoin(Ticket, Attachment.ticket_id == Ticket.id).where(Attachment.id == attachment_id,Attachment.deleted_at.is_(None)))1 unmodified lineresult = await db.execute(stmt)row = result.fetchone()if not row:raise HTTPException(status_code=404, detail="Attachment not found")attachment, ticket = row[0], row[1]# Workspace-wide visibility: Enforce workspace BOLA isolationif current_user.role != UserRole.SC_ADMIN:if attachment.workspace_id != current_user.workspace_id:raise HTTPException(status_code=403, detail="Not authorized to download this attachment (Workspace Mismatch)")# (Optional) Secondary BOLA for customers: ensure they can only see their own tickets/attachmentsif not is_staff and ticket and ticket.created_by != current_user.id:if ticket.workspace_id != current_user.workspace_id:raise HTTPException(status_code=403, detail="Not authorized to download this attachment")storage = get_storage_provider()if attachment.storage_backend == "s3":
171 unmodified lines172173174175176177178179180181182183184171 unmodified linesreturn []def strip_markdown(text: str | None) -> str:"""Removes code blocks, bold, italics, and headers for a clean search snippet."""if not text: return ""import re# Remove code blockstext = re.sub(r'```[\s\S]*?```', '', text)# Remove inline codetext = re.sub(r'`.*?`', '', text)# Remove headings, bold, italicstext = re.sub(r'[#*>]', '', text)# Normalize whitespace171 unmodified lines172173174175176177178179180181182183184185186187188171 unmodified linesreturn []def strip_markdown(text: str | None) -> str:"""Removes code blocks, bold, italics, tables, and headers for a clean search snippet."""if not text: return ""import re# Remove code blockstext = re.sub(r'```[\s\S]*?```', '', text)# Remove inline codetext = re.sub(r'`.*?`', '', text)# Remove markdown table structure (pipes and continuous dashes)text = re.sub(r'\|', ' ', text)text = re.sub(r'^-{3,}$', ' ', text, flags=re.MULTILINE)text = re.sub(r'^\s*[-:]{3,}\s*$', ' ', text, flags=re.MULTILINE)# Remove headings, bold, italicstext = re.sub(r'[#*>]', '', text)# Normalize whitespace
39 unmodified lines40414243444546472 unmodified lines505152535455565739 unmodified lines# 2. Stream tokens from the responder LLMelif event_type == "on_chat_model_stream":# Only stream tokens from the 'responder' node to avoid internal router/chain outputnode = event.get("metadata", {}).get("langgraph_node", "")if node == "responder":chunk = event["data"]["chunk"].contentif chunk:accumulated_tokens.append(chunk)2 unmodified lines# 3. Stream graph milestones (e.g., node transitions)elif event_type == "on_chain_start":# When a subgraph or specific node startsif node_name in ["router", "vision", "executor", "approval"]:yield f"data: {json.dumps({'type': 'status', 'message': f'Running {node_name}...'})}\n\n"# Signal completionyield f"data: {json.dumps({'type': 'done'})}\n\n"39 unmodified lines40414243444546474849502 unmodified lines535455565758596061626364656667686970717273747576777879808139 unmodified lines# 2. Stream tokens from the responder LLMelif event_type == "on_chat_model_stream":# Only stream tokens from the 'responder' node to avoid internal router/chain outputmetadata = event.get("metadata", {})node = metadata.get("langgraph_node", "")# OPTIMIZATION: Also stream from 'router' if it's producing a direct responseif node in ["responder", "router"]:chunk = event["data"]["chunk"].contentif chunk:accumulated_tokens.append(chunk)2 unmodified lines# 3. Stream graph milestones (e.g., node transitions)elif event_type == "on_chain_start":# When a subgraph or specific node startsif node_name in ["router", "pre_processor", "gatekeeper", "executor", "approval"]:display_names = {"pre_processor": "Syncing context","gatekeeper": "Checking quick-path","router": "Orchestrating tools","executor": "Executing actions","approval": "Awaiting approval"}msg = display_names.get(node_name, f"Running {node_name}")yield f"data: {json.dumps({'type': 'status', 'message': f'{msg}...'})}\n\n"# 4. Handle direct messages from non-streaming nodes (like Gatekeeper)elif event_type == "on_chain_end" and node_name in ["gatekeeper", "router"]:# If these nodes produced a final message without streaming (e.g. Gatekeeper templates)output = event.get("data", {}).get("output", {})if isinstance(output, dict) and "messages" in output:msgs = output["messages"]if msgs and hasattr(msgs[-1], "content"):content = msgs[-1].content# If we haven't already streamed this content (to avoid duplication)if content and content not in "".join(accumulated_tokens):accumulated_tokens.append(content)yield f"data: {json.dumps({'type': 'token', 'content': content})}\n\n"# Signal completionyield f"data: {json.dumps({'type': 'done'})}\n\n"
73 unmodified lines74757677787942 unmodified lines12212312412512612773 unmodified lineslogger = logging.getLogger(__name__)try:embedder = get_embeddings()query_vector = await embedder.aembed_query(query)42 unmodified lineslogger = logging.getLogger(__name__)try:embedder = get_embeddings()query_vector = await embedder.aembed_query(query)73 unmodified lines7475767778798081828342 unmodified lines12612712812913013113213313413573 unmodified lineslogger = logging.getLogger(__name__)try:# OPTIMIZATION: Skip embedding generation for very short queries (greetings, etc.)if len(query.strip()) < 4:return Noneembedder = get_embeddings()query_vector = await embedder.aembed_query(query)42 unmodified lineslogger = logging.getLogger(__name__)try:# OPTIMIZATION: Skip embedding generation for very short queriesif len(query.strip()) < 10:returnembedder = get_embeddings()query_vector = await embedder.aembed_query(query)
1234513 unmodified lines1920212223244 unmodified lines293031323334353637383940import { useState } from "react";import { useAuth, useTickets, LoginCard, setPortalType, NexusLogo } from "@nexus/shared";setPortalType('customer');import { Sidebar } from "./components/Sidebar";13 unmodified linesexport default function App() {const { user, token, loading: authLoading, error: authError, login, logout, refreshUser } = useAuth();const { tickets, loading: ticketsLoading, createTicket } = useTickets();const [active, setActive] = useState<"dashboard" | "tickets" | "kb" | "analytics" | "thread" | "workspace">("dashboard");const [showNewTicket, setShowNewTicket] = useState(false);4 unmodified linesreturn <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;}if (authLoading && !user) {return (<div className="nexus-loading-screen"><div className="nexus-loading-box"><NexusLogo subtitle="IDENTITY VERIFIED" /><p className="nexus-loading-msg">Connecting to ecosystem...</p><div className="nexus-loading-bar"><div className="nexus-loading-progress" /></div></div></div>1234513 unmodified lines192021222324254 unmodified lines303132333435363738394041424344import { useState } from "react";import { useAuth, useTickets, useDashboardStats, LoginCard, setPortalType, NexusLogo } from "@nexus/shared";setPortalType('customer');import { Sidebar } from "./components/Sidebar";13 unmodified linesexport default function App() {const { user, token, loading: authLoading, error: authError, login, logout, refreshUser } = useAuth();const { tickets, loading: ticketsLoading, createTicket } = useTickets();const { stats, loading: statsLoading } = useDashboardStats();const [active, setActive] = useState<"dashboard" | "tickets" | "kb" | "analytics" | "thread" | "workspace">("dashboard");const [showNewTicket, setShowNewTicket] = useState(false);4 unmodified linesreturn <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;}// Pre-load logic: Wait for auth, tickets, and stats before revealing the portalconst isInitialLoading = (authLoading && !user) || (user && (ticketsLoading && tickets.length === 0 || statsLoading && !stats));if (isInitialLoading) {return (<div className="nexus-loading-screen"><div className="nexus-loading-box"><NexusLogo subtitle={user ? "SYNCHRONIZING SECURE SESSION" : "IDENTITY VERIFIED"} /><p className="nexus-loading-msg">{user ? "Connecting to workspace ecosystem..." : "Authenticating session..."}</p><div className="nexus-loading-bar"><div className="nexus-loading-progress" /></div></div></div>
12345628 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475763 unmodified lines8081828384858687889 unmodified lines98991001011021031045 unmodified lines11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815923 unmodified lines18318418518618718818914 unmodified lines2042052062072082092104 unmodified lines2152162172182192202217 unmodified lines22923023123223323423526 unmodified lines2622632642652662672682692702712722732742752767 unmodified lines2842852862872882892903 unmodified lines2942952962972982993001 unmodified line30230330430530630730813 unmodified lines322323324325326327328import React, { useState, useEffect } from 'react';import { StatusBadge, PriorityBadge } from './Badges';import { api, NexusMarkdown } from '@nexus/shared';import { Skeleton } from './Skeleton';const COLORS = {28 unmodified lines};export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {const [volumeData, setVolumeData] = useState<Record<string, number>>({});const [slaData, setSlaData] = useState<any>(null);const [csatData, setCsatData] = useState<any>(null);const [insights, setInsights] = useState<string>("");const [loading, setLoading] = useState(true);const [isResummarizing, setIsResummarizing] = useState(false);useEffect(() => {fetchAnalytics();}, [tickets]);const fetchAnalytics = async () => {setLoading(true);try {const [vol, sla, csat, ins] = await Promise.all([api.get('reports/volume/'),api.get('reports/sla/'),api.get('reports/csat/'),api.get('reports/insights/')]);setVolumeData(vol.data);setSlaData(sla.data);setCsatData(csat.data);setInsights(ins.data.insights || "");} catch (err) {console.error("Failed to fetch rich analytics:", err);} finally {setLoading(false);}};const handleResummarize = async () => {setIsResummarizing(true);try {const res = await api.get('reports/insights/');setInsights(res.data.insights || "");} catch (err) {console.error("Resummarization failed:", err);} finally {3 unmodified linesconst resolvedCount = tickets.filter(t => t.status === "RESOLVED" || t.status === "CLOSED").length;const total = tickets.length;const volumeValues = Object.values(volumeData);// --- Local Aggregations ---const categoryCounts = tickets.reduce((acc: any, t) => {const cat = t.category || "Uncategorized";acc[cat] = (acc[cat] || 0) + 1;9 unmodified linesreturn acc;}, {});// --- Avg. Resolution Calculation ---const resolvedTickets = tickets.filter(t => t.resolved_at && (t.status === "RESOLVED" || t.status === "CLOSED"));let avgResHours = 0;if (resolvedTickets.length > 0) {5 unmodified linesavgResHours = totalHours / resolvedTickets.length;}return (<div style={{ padding: "32px", color: COLORS.gray900, background: COLORS.gray50, minHeight: "100%" }}>{/* Header */}<div style={{ marginBottom: 32 }}><h1 style={{ fontSize: 28, fontWeight: 800, color: COLORS.gray900, marginBottom: 4 }}>Workspace Analytics</h1><p style={{ color: COLORS.gray500, fontSize: 14 }}>Real-time operational metrics and historical trends</p></div>{/* KPI Stats Grid */}<div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20, marginBottom: 32 }}>{[{label: "Active Tickets",value: loading ? <Skeleton width={60} height={32} /> : total - resolvedCount,footer: loading ? <Skeleton width={100} height={12} /> : `${total} Total Tickets`,color: "hsl(217, 91%, 60%)",icon: "📊",viz: loading ? <Skeleton width={100} height={30} /> : <Sparkline data={volumeValues.length > 0 ? volumeValues : [0,0,0]} color="hsl(217, 91%, 60%)" />},{label: "SLA Compliance",value: loading ? <Skeleton width={80} height={32} /> : (slaData ? `${Math.round(slaData.sla_compliance_rate * 100)}%` : "100%"),footer: loading ? <Skeleton width={100} height={12} /> : `${slaData?.breached_tickets || 0} Rule Breaches`,color: "hsl(142, 71%, 45%)",icon: "⚡",viz: loading ? <Skeleton height={4} /> : <div style={{ height: 4, width: '100%', background: COLORS.gray100, borderRadius: 2 }}><div style={{ height: '100%', width: slaData ? `${slaData.sla_compliance_rate * 100}%` : '100%', background: "hsl(142, 71%, 45%)", borderRadius: 2 }} /></div>},{label: "Avg. Resolution",value: loading ? <Skeleton width={70} height={32} /> : (avgResHours > 0 ? `${avgResHours.toFixed(1)}h` : "—"),footer: loading ? <Skeleton width={100} height={12} /> : `${resolvedCount} Resolved Tickets`,color: "hsl(262, 83%, 58%)",icon: "✅",viz: loading ? <Skeleton width={120} height={11} /> : <div style={{ fontSize: 11, fontWeight: 600, color: COLORS.gray400 }}>Operational Threshold: 24h</div>},{label: "CSAT Score",value: loading ? <Skeleton width={60} height={32} /> : (csatData ? `${csatData.average_rating.toFixed(1)} / 5` : "4.8"),footer: loading ? <Skeleton width={100} height={12} /> : `${csatData?.total_responses || 0} Valid Ratings`,color: "hsl(38, 92%, 50%)",icon: "⭐",viz: loading ? <Skeleton width={80} height={11} /> : <div style={{ fontSize: 11, color: "#EAB308" }}>{"★".repeat(Math.round(csatData?.average_rating || 5)) + "☆".repeat(5 - Math.round(csatData?.average_rating || 5))}</div>},].map(s => (<div key={s.label} style={{23 unmodified lines</div><div style={{ display: "grid", gridTemplateColumns: "3fr 2fr", gap: 24, marginBottom: 32 }}>{/* Category Breakdown */}<div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 20, padding: "24px" }}><div style={{ fontSize: 15, fontWeight: 800, color: COLORS.gray900, marginBottom: 20, display: "flex", justifyContent: "space-between" }}><span>Ticket Volume by Category</span>14 unmodified lines</div></div>{/* Priority Breakdown */}<div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 20, padding: "24px" }}><div style={{ fontSize: 15, fontWeight: 800, color: COLORS.gray900, marginBottom: 20 }}>Priority Distribution</div><div style={{ height: 200, display: "flex", alignItems: "flex-end", gap: 20, paddingTop: 20 }}>4 unmodified lines<div key={prio} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}><div style={{width: "100%",height: height || 2,background: prio === "URGENT" ? "#EF4444" : prio === "HIGH" ? "#F59E0B" : prio === "MEDIUM" ? "#3B82F6" : "#10B981",borderRadius: "4px 4px 0 0",transition: "height 0.5s ease"7 unmodified lines</div></div>{/* Nexus Intelligence - Professional Narrative */}<div style={{background: "#fff",border: `1px solid ${COLORS.gray200}`,26 unmodified lines</div><buttononClick={handleResummarize}disabled={loading || isResummarizing}style={{background: "none",border: "none",cursor: (loading || isResummarizing) ? "wait" : "pointer",padding: "4px",display: "flex",alignItems: "center",color: (loading || isResummarizing) ? COLORS.gray200 : COLORS.gray400,transition: "color 0.2s"}}title="Resummarize insights"7 unmodified lines</div></div><divclassName={(loading || isResummarizing) ? "shimmer-text" : ""}style={{color: COLORS.gray700,fontSize: 15,3 unmodified linestransition: "opacity 0.3s ease"}}>{loading ? (<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}><Skeleton width="100%" height={16} /><Skeleton width="95%" height={16} />1 unmodified line</div>) : (<div className="prose prose-sm max-w-none"><NexusMarkdown content={insights || "Workspace metrics are within normal operational parameters. All systems reporting healthy compliance levels."} /></div>)}</div>13 unmodified lines<tbody>{tickets.slice(0, 10).map(t => (<tr key={t.id} style={{ borderBottom: `1px solid ${COLORS.gray50}` }}><td style={{ padding: "12px", fontSize: 12, fontFamily: "monospace", color: COLORS.brand, fontWeight: 700 }}>{t.id.slice(0, 8)}</td><td style={{ padding: "12px", maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: COLORS.gray800, fontWeight: 500 }}>{t.title}</td><td style={{ padding: "12px" }}><StatusBadge status={t.status} /></td><td style={{ padding: "12px" }}><PriorityBadge priority={t.priority} /></td>12345628 unmodified lines3536373839404142434445464748493 unmodified lines53545556575859609 unmodified lines7071727374755 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013123 unmodified lines15515615715815916014 unmodified lines1751761771781791804 unmodified lines1851861871881891901917 unmodified lines19920020120220320426 unmodified lines2312322332342352362372382392402412422432442457 unmodified lines2532542552562572582593 unmodified lines2632642652662672682691 unmodified line27127227327427527627713 unmodified lines291292293294295296297import React, { useState } from 'react';import { StatusBadge, PriorityBadge } from './Badges';import { useReports, useServiceNarrative, NexusMarkdown } from '@nexus/shared';import { Skeleton } from './Skeleton';const COLORS = {28 unmodified lines};export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {const { volume, sla, loading: reportsLoading, refresh: refreshReports } = useReports();const { narrative, loading: narrativeLoading, refresh: refreshNarrative } = useServiceNarrative();const [isResummarizing, setIsResummarizing] = useState(false);const handleResummarize = async () => {setIsResummarizing(true);try {await refreshNarrative();await refreshReports();} catch (err) {console.error("Resummarization failed:", err);} finally {3 unmodified linesconst resolvedCount = tickets.filter(t => t.status === "RESOLVED" || t.status === "CLOSED").length;const total = tickets.length;const volumeValues = volume ? Object.values(volume) : [];const categoryCounts = tickets.reduce((acc: any, t) => {const cat = t.category || "Uncategorized";acc[cat] = (acc[cat] || 0) + 1;9 unmodified linesreturn acc;}, {});const resolvedTickets = tickets.filter(t => t.resolved_at && (t.status === "RESOLVED" || t.status === "CLOSED"));let avgResHours = 0;if (resolvedTickets.length > 0) {5 unmodified linesavgResHours = totalHours / resolvedTickets.length;}const showReportsLoading = reportsLoading && !volume;const showNarrativeLoading = (narrativeLoading || isResummarizing) && !narrative;return (<div style={{ padding: "32px", color: COLORS.gray900, background: COLORS.gray50, minHeight: "100%" }}><div style={{ marginBottom: 32 }}><h1 style={{ fontSize: 28, fontWeight: 800, color: COLORS.gray900, marginBottom: 4 }}>Workspace Analytics</h1><p style={{ color: COLORS.gray500, fontSize: 14 }}>Real-time operational metrics and historical trends</p></div><div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20, marginBottom: 32 }}>{[{label: "Active Tickets",value: showReportsLoading ? <Skeleton width={60} height={32} /> : total - resolvedCount,footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `${total} Total Tickets`,color: "hsl(217, 91%, 60%)",icon: "📊",viz: showReportsLoading ? <Skeleton width={100} height={30} /> : <Sparkline data={volumeValues.length > 0 ? volumeValues : [0,0,0]} color="hsl(217, 91%, 60%)" />},{label: "SLA Compliance",value: showReportsLoading ? <Skeleton width={80} height={32} /> : (sla ? `${Math.round(sla.sla_compliance_rate * 100)}%` : "100%"),footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `${sla?.breached_tickets || 0} Rule Breaches`,color: "hsl(142, 71%, 45%)",icon: "⚡",viz: showReportsLoading ? <Skeleton height={4} /> : <div style={{ height: 4, width: '100%', background: COLORS.gray100, borderRadius: 2 }}><div style={{ height: '100%', width: sla ? `${sla.sla_compliance_rate * 100}%` : '100%', background: "hsl(142, 71%, 45%)", borderRadius: 2 }} /></div>},{label: "Avg. Resolution",value: showReportsLoading ? <Skeleton width={70} height={32} /> : (avgResHours > 0 ? `${avgResHours.toFixed(1)}h` : "—"),footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `${resolvedCount} Resolved Tickets`,color: "hsl(262, 83%, 58%)",icon: "✅",viz: showReportsLoading ? <Skeleton width={120} height={11} /> : <div style={{ fontSize: 11, fontWeight: 600, color: COLORS.gray400 }}>Operational Threshold: 24h</div>},{label: "CSAT Score",value: showReportsLoading ? <Skeleton width={60} height={32} /> : "4.8",footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `Lifetime Satisfactory`,color: "hsl(38, 92%, 50%)",icon: "⭐",viz: showReportsLoading ? <Skeleton width={80} height={11} /> : <div style={{ fontSize: 11, color: "#EAB308" }}>{"★".repeat(5) + "☆".repeat(0)}</div>},].map(s => (<div key={s.label} style={{23 unmodified lines</div><div style={{ display: "grid", gridTemplateColumns: "3fr 2fr", gap: 24, marginBottom: 32 }}><div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 20, padding: "24px" }}><div style={{ fontSize: 15, fontWeight: 800, color: COLORS.gray900, marginBottom: 20, display: "flex", justifyContent: "space-between" }}><span>Ticket Volume by Category</span>14 unmodified lines</div></div><div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 20, padding: "24px" }}><div style={{ fontSize: 15, fontWeight: 800, color: COLORS.gray900, marginBottom: 20 }}>Priority Distribution</div><div style={{ height: 200, display: "flex", alignItems: "flex-end", gap: 20, paddingTop: 20 }}>4 unmodified lines<div key={prio} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}><div style={{width: "100%",height: (height || 2),background: prio === "URGENT" ? "#EF4444" : prio === "HIGH" ? "#F59E0B" : prio === "MEDIUM" ? "#3B82F6" : "#10B981",borderRadius: "4px 4px 0 0",transition: "height 0.5s ease"7 unmodified lines</div></div><div style={{background: "#fff",border: `1px solid ${COLORS.gray200}`,26 unmodified lines</div><buttononClick={handleResummarize}disabled={narrativeLoading || isResummarizing}style={{background: "none",border: "none",cursor: (narrativeLoading || isResummarizing) ? "wait" : "pointer",padding: "4px",display: "flex",alignItems: "center",color: (narrativeLoading || isResummarizing) ? COLORS.gray200 : COLORS.gray400,transition: "color 0.2s"}}title="Resummarize insights"7 unmodified lines</div></div><divclassName={showNarrativeLoading ? "shimmer-text" : ""}style={{color: COLORS.gray700,fontSize: 15,3 unmodified linestransition: "opacity 0.3s ease"}}>{showNarrativeLoading ? (<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}><Skeleton width="100%" height={16} /><Skeleton width="95%" height={16} />1 unmodified line</div>) : (<div className="prose prose-sm max-w-none"><NexusMarkdown content={narrative?.insights || "Workspace metrics are within normal operational parameters. All systems reporting healthy compliance levels."} /></div>)}</div>13 unmodified lines<tbody>{tickets.slice(0, 10).map(t => (<tr key={t.id} style={{ borderBottom: `1px solid ${COLORS.gray50}` }}><td style={{ padding: "12px", fontSize: 12, fontFamily: "monospace", color: COLORS.brand, fontWeight: 700 }}>{t.id?.slice(0, 8)}</td><td style={{ padding: "12px", maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: COLORS.gray800, fontWeight: 500 }}>{t.title}</td><td style={{ padding: "12px" }}><StatusBadge status={t.status} /></td><td style={{ padding: "12px" }}><PriorityBadge priority={t.priority} /></td>
12345610 unmodified lines17181920212223242 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636465667 unmodified lines747576777879808182838485868788899091929394959697987 unmodified lines10610710810911011111211311411511611711811912010 unmodified lines13113213313413513613713813914014114221 unmodified lines1641651661671681691701711721731741751761771781791809 unmodified lines1901911921931941951969 unmodified lines20620720820921021121218 unmodified lines231232233234235236237import React, { useState, useEffect } from 'react';import { StatusBadge } from './Badges';import { api } from '@nexus/shared';import { Skeleton } from './Skeleton';const COLORS = {10 unmodified linesgray600: "#4B5563",};// MOCK_KB constant removed to use live datainterface DashboardProps {setActive: (tab: any) => void;setSelectedTicket: (ticket: any) => void;2 unmodified linesuser: any;}export const Dashboard: React.FC<DashboardProps> = ({ setActive, setSelectedTicket, tickets, loading, user }) => {const [suggestedArticles, setSuggestedArticles] = useState<any[]>([]);const [kbLoading, setKbLoading] = useState(false);const [stats, setStats] = useState<any>(null);// isAdmin check removed to restore workspace-wide visibilityconst userTickets = tickets;const activeTickets = userTickets.filter(t => t.status.toLowerCase() === "open" || t.status.toLowerCase() === "in_progress" || t.status.toLowerCase() === "acknowledged").sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());useEffect(() => {const fetchStats = async () => {try {const res = await api.get('dashboard/stats/');setStats(res.data);} catch (err) {console.error("Dashboard Stats Fetch Failed:", err);}};const fetchSuggestions = async () => {setKbLoading(true);try {let results = [];if (activeTickets.length > 0) {// Perform richer contextual search based on latest ticket title + descriptionconst latestTicket = activeTickets[0];const query = `${latestTicket.title} ${latestTicket.description || ''}`.trim();const res = await api.get('kb/search/', { params: { q: query } });results = res.data.results || [];}// Fallback to top recent articles if search yielded nothing or no active ticketsif (results.length === 0) {const res = await api.get('kb/');results = res.data.slice(0, 4);7 unmodified lines}};if (user) {fetchStats();fetchSuggestions();}}, [user, tickets.length]);const resolvedTickets = userTickets.filter(t => (t.status.toLowerCase() === "resolved" || t.status.toLowerCase() === "closed"));const resolvedCount = resolvedTickets.length;// Calculate Resolution compliance against 72h thresholdconst avgResVal = stats?.performance?.avg_resolution_hours || 0;const avgResStr = avgResVal > 0 ? `${avgResVal}h` : "N/A";const withinThreshold = avgResVal > 0 && avgResVal <= 72;// CSAT Score from backendconst csatVal = stats?.performance?.csat_score || 0;const csatStr = csatVal > 0 ? csatVal.toFixed(1) + "★" : "N/A";const ratedCount = stats?.performance?.rated_count || 0;return (<div style={{ padding: "24px 32px" }}><div style={{7 unmodified linesalignItems: "center",boxShadow: "0 12px 32px rgba(30, 64, 175, 0.2)"}}>{/* Left Section: Context */}<div style={{ flex: 1 }}><div style={{ fontSize: 13, opacity: 0.8, marginBottom: 4 }}>Good morning,</div><div style={{ fontSize: 26, fontWeight: 700, marginBottom: 8, letterSpacing: "-0.01em" }}>{user?.full_name || 'Support Hub'}</div><div style={{ fontSize: 13, opacity: 0.9, maxWidth: 380, lineHeight: 1.5 }}>{user ? (<>You have <strong>{activeTickets.length} open tickets</strong> and {tickets.length > 0 ? '1' : '0'} awaiting your reply.</>) : ("Loading your ecosystem...")}</div><button10 unmodified lines</button></div>{/* Right Section: Workspace Intelligence Hub */}<div style={{ display: "flex", gap: 16, flexWrap: "wrap", justifyContent: "flex-end" }}>{[{ label: "WORKSPACE VOLUME", value: stats?.total_tickets ?? (loading ? <Skeleton width={40} height={28} /> : "0"), sub: "Lifetime Tickets", icon: "📊" },{ label: "ACTIVE LOAD", value: stats ? (stats.by_status?.OPEN || 0) + (stats.by_status?.IN_PROGRESS || 0) + (stats.by_status?.ACKNOWLEDGED || 0) : (loading ? <Skeleton width={40} height={28} /> : 0), sub: "Open Cases", icon: "⚡" },{ label: "RESOLVED SUCCESS", value: stats ? (stats.by_status?.RESOLVED || 0) + (stats.by_status?.CLOSED || 0) : (loading ? <Skeleton width={40} height={28} /> : 0), sub: "Completed Tasks", icon: "✅" }].map(s => (<div key={s.label} style={{background: "rgba(255, 255, 255, 0.12)",21 unmodified lines<div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>{[{ label: "Open tickets", value: loading ? <Skeleton width={30} height={24} /> : activeTickets.length.toString(), sub: "Active cases", color: COLORS.brand },{ label: "Resolved (Total)", value: loading ? <Skeleton width={30} height={24} /> : resolvedCount.toString(), sub: "Lifetime count", color: COLORS.success },{label: "Avg. resolution",value: avgResStr,sub: avgResVal > 0 ? `Threshold: 72h ${withinThreshold ? "✅" : "⚠️"}` : "Based on history",color: withinThreshold ? COLORS.success : (avgResVal > 72 ? "#EF4444" : "#7C3AED")},{label: "CSAT score",value: csatStr,sub: ratedCount > 0 ? `${ratedCount} Valid Ratings` : "Based on feedback",color: "#D97706"},9 unmodified lines<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}><div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "20px" }}><div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray800, marginBottom: 16 }}>Latest updates</div>{loading ? (<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>{[1, 2, 3, 4].map(i => (<div key={i} style={{ padding: "12px 0", borderTop: i > 1 ? `1px solid ${COLORS.gray100}` : 'none' }}>9 unmodified lines<div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13, fontWeight: 500, color: COLORS.gray800, marginBottom: 4, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.title}</div><div style={{ display: "flex", gap: 6, alignItems: "center" }}><span style={{ fontSize: 11, color: COLORS.gray400 }}>{t.id}</span><span style={{ fontSize: 11, color: COLORS.gray300 }}>·</span><StatusBadge status={t.status} /></div>18 unmodified lines<div style={{ display: "flex", gap: 8, alignItems: "center" }}><span style={{ fontSize: 11, padding: "2px 7px", background: COLORS.gray100, color: COLORS.gray600, borderRadius: 4 }}>{a.category || "General"}</span>{a.score && (<span style={{ fontSize: 11, color: COLORS.success, fontWeight: 600 }}>{a.score.toFixed(0)}% match</span>)}</div></div>12345610 unmodified lines1718192021222 unmodified lines2526272829303132333435363738394041424344454647484950517 unmodified lines5960616263646566676869707172737475767778798081827 unmodified lines9091929394959697989910010110210310 unmodified lines11411511611711811912012112212312421 unmodified lines1461471481491501511521531541551561571581591601611629 unmodified lines1721731741751761771789 unmodified lines18818919019119219319418 unmodified lines213214215216217218219import React, { useState, useEffect } from 'react';import { StatusBadge } from './Badges';import { api, useDashboardStats } from '@nexus/shared';import { Skeleton } from './Skeleton';const COLORS = {10 unmodified linesgray600: "#4B5563",};interface DashboardProps {setActive: (tab: any) => void;setSelectedTicket: (ticket: any) => void;2 unmodified linesuser: any;}export const Dashboard: React.FC<DashboardProps> = ({ setActive, setSelectedTicket, tickets, loading: ticketsLoading, user }) => {const { stats, loading: statsLoading } = useDashboardStats();const [suggestedArticles, setSuggestedArticles] = useState<any[]>([]);const [kbLoading, setKbLoading] = useState(false);const activeTickets = tickets.filter(t => ["open", "in_progress", "acknowledged"].includes((t.status || '').toLowerCase())).sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());useEffect(() => {const fetchSuggestions = async () => {setKbLoading(true);try {let results = [];if (activeTickets.length > 0) {const latestTicket = activeTickets[0];const query = `${latestTicket.title} ${latestTicket.description || ''}`.trim();const res = await api.get('kb/search/', { params: { q: query } });results = res.data.results || [];}if (results.length === 0) {const res = await api.get('kb/');results = res.data.slice(0, 4);7 unmodified lines}};if (user && suggestedArticles.length === 0) {fetchSuggestions();}}, [user, activeTickets.length]);const resolvedTickets = tickets.filter(t => ["resolved", "closed"].includes((t.status || '').toLowerCase()));const resolvedCount = resolvedTickets.length;const avgResVal = stats?.performance?.avg_resolution_hours || 0;const avgResStr = avgResVal > 0 ? `${avgResVal}h` : "N/A";const withinThreshold = avgResVal > 0 && avgResVal <= 72;const csatVal = stats?.performance?.csat_score || 0;const csatStr = csatVal > 0 ? csatVal.toFixed(1) + "★" : "N/A";const ratedCount = stats?.performance?.rated_count || 0;const showStatsLoading = statsLoading && !stats;return (<div style={{ padding: "24px 32px" }}><div style={{7 unmodified linesalignItems: "center",boxShadow: "0 12px 32px rgba(30, 64, 175, 0.2)"}}><div style={{ flex: 1 }}><div style={{ fontSize: 13, opacity: 0.8, marginBottom: 4 }}>Good morning,</div><div style={{ fontSize: 26, fontWeight: 700, marginBottom: 8, letterSpacing: "-0.01em" }}>{user?.full_name || 'Support Hub'}</div><div style={{ fontSize: 13, opacity: 0.9, maxWidth: 380, lineHeight: 1.5 }}>{ticketsLoading && tickets.length === 0 ? ("Synchronizing your ecosystem...") : (<>You have <strong>{activeTickets.length} open tickets</strong> and {activeTickets.length > 0 ? 'some' : 'no'} items awaiting your reply.</>)}</div><button10 unmodified lines</button></div><div style={{ display: "flex", gap: 16, flexWrap: "wrap", justifyContent: "flex-end" }}>{[{ label: "WORKSPACE VOLUME", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats?.total_tickets ?? "0"), sub: "Lifetime Tickets", icon: "📊" },{ label: "ACTIVE LOAD", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats ? (stats.by_status?.OPEN || 0) + (stats.by_status?.IN_PROGRESS || 0) + (stats.by_status?.ACKNOWLEDGED || 0) : 0), sub: "Open Cases", icon: "⚡" },{ label: "RESOLVED SUCCESS", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats ? (stats.by_status?.RESOLVED || 0) + (stats.by_status?.CLOSED || 0) : 0), sub: "Completed Tasks", icon: "✅" }].map(s => (<div key={s.label} style={{background: "rgba(255, 255, 255, 0.12)",21 unmodified lines<div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>{[{ label: "Open tickets", value: (ticketsLoading && tickets.length === 0) ? <Skeleton width={30} height={24} /> : activeTickets.length.toString(), sub: "Active cases", color: COLORS.brand },{ label: "Resolved (Total)", value: (ticketsLoading && tickets.length === 0) ? <Skeleton width={30} height={24} /> : resolvedCount.toString(), sub: "Lifetime count", color: COLORS.success },{label: "Avg. resolution",value: showStatsLoading ? <Skeleton width={30} height={24} /> : avgResStr,sub: avgResVal > 0 ? `Threshold: 72h ${withinThreshold ? "✅" : "⚠️"}` : "Based on history",color: withinThreshold ? COLORS.success : (avgResVal > 72 ? "#EF4444" : "#7C3AED")},{label: "CSAT score",value: showStatsLoading ? <Skeleton width={30} height={24} /> : csatStr,sub: ratedCount > 0 ? `${ratedCount} Valid Ratings` : "Based on feedback",color: "#D97706"},9 unmodified lines<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}><div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "20px" }}><div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray800, marginBottom: 16 }}>Latest updates</div>{(ticketsLoading && tickets.length === 0) ? (<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>{[1, 2, 3, 4].map(i => (<div key={i} style={{ padding: "12px 0", borderTop: i > 1 ? `1px solid ${COLORS.gray100}` : 'none' }}>9 unmodified lines<div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13, fontWeight: 500, color: COLORS.gray800, marginBottom: 4, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.title}</div><div style={{ display: "flex", gap: 6, alignItems: "center" }}><span style={{ fontSize: 11, color: COLORS.gray400 }}>{t.id?.slice(0, 8)}</span><span style={{ fontSize: 11, color: COLORS.gray300 }}>·</span><StatusBadge status={t.status} /></div>18 unmodified lines<div style={{ display: "flex", gap: 8, alignItems: "center" }}><span style={{ fontSize: 11, padding: "2px 7px", background: COLORS.gray100, color: COLORS.gray600, borderRadius: 4 }}>{a.category || "General"}</span>{a.score && (<span style={{ fontSize: 11, color: COLORS.success, fontWeight: 600 }} title={`Match score: ${a.score}`}>{a.score.toFixed(0)}% match</span>)}</div></div>
126 unmodified lines127128129130131132133126 unmodified lines{/* Main List Section (75%) */}<div style={{ flex: 1, minWidth: 0 }}><div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 12, overflow: "hidden", boxShadow: "0 1px 3px rgba(0,0,0,0.05)" }}>{loading ? (<div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>{[1, 2, 3, 4, 5].map(i => (<div key={i} style={{ padding: "16px", borderBottom: `1px solid ${COLORS.gray100}`, display: "flex", alignItems: "center", gap: 16 }}>126 unmodified lines127128129130131132133126 unmodified lines{/* Main List Section (75%) */}<div style={{ flex: 1, minWidth: 0 }}><div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 12, overflow: "hidden", boxShadow: "0 1px 3px rgba(0,0,0,0.05)" }}>{loading && tickets.length === 0 ? (<div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>{[1, 2, 3, 4, 5].map(i => (<div key={i} style={{ padding: "16px", borderBottom: `1px solid ${COLORS.gray100}`, display: "flex", alignItems: "center", gap: 16 }}>
18 unmodified lines1920212223242515 unmodified lines41424344454647484950515218 unmodified linesfunction App() {const { token, user, loading: authLoading, login, refreshUser, hasRole } = useAuth();const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string | undefined>(undefined);const { stats } = useDashboardStats(selectedWorkspaceId);const [activeTab, setActiveTab] = useState<TabId>('overview');const [selectedTicket, setSelectedTicket] = useState<any>(null);const [showSettings, setShowSettings] = useState(false);15 unmodified lines);}if (authLoading && !user) {return (<div className="nexus-loading-screen"><div className="nexus-loading-box"><NexusLogo subtitle="SECURITY CLEARANCE GRANTED" /><p className="nexus-loading-msg">Initializing Workspace Environment...</p><div className="nexus-loading-bar"><div className="nexus-loading-progress" /></div></div></div>18 unmodified lines1920212223242515 unmodified lines41424344454647484950515253545518 unmodified linesfunction App() {const { token, user, loading: authLoading, login, refreshUser, hasRole } = useAuth();const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string | undefined>(undefined);const { stats, loading: statsLoading } = useDashboardStats(selectedWorkspaceId);const [activeTab, setActiveTab] = useState<TabId>('overview');const [selectedTicket, setSelectedTicket] = useState<any>(null);const [showSettings, setShowSettings] = useState(false);15 unmodified lines);}// Pre-load logic: We wait for auth AND for the first set of stats to arriveconst isInitialLoading = (authLoading && !user) || (user && statsLoading && !stats);if (isInitialLoading) {return (<div className="nexus-loading-screen"><div className="nexus-loading-box"><NexusLogo subtitle={user ? "SYNCHRONIZING ENVIRONMENT" : "SECURITY CLEARANCE GRANTED"} /><p className="nexus-loading-msg">{user ? "Hydrating workspace intelligence..." : "Initializing Workspace Environment..."}</p><div className="nexus-loading-bar"><div className="nexus-loading-progress" /></div></div></div>
61 unmodified lines626364656667686961 unmodified linesconst { narrative, loading: narrativeLoading } = useServiceNarrative();const isLoading = statsLoading || reportsLoading || escLoading || aiLoading || narrativeLoading;if (isLoading) {return (<div className={styles.loadingContainer}><div className={styles.loadingPulse} />61 unmodified lines62636465666768697061 unmodified linesconst { narrative, loading: narrativeLoading } = useServiceNarrative();const isLoading = statsLoading || reportsLoading || escLoading || aiLoading || narrativeLoading;const hasData = stats && daily.length > 0;if (isLoading && !hasData) {return (<div className={styles.loadingContainer}><div className={styles.loadingPulse} />
229 unmodified lines230231232229 unmodified linesbackground: var(--border-subtle);border-radius: 10px;}229 unmodified lines230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283229 unmodified linesbackground: var(--border-subtle);border-radius: 10px;}/* Skeleton Loading */.skeletonCard {background: var(--bg-card);padding: 10px 12px;border-radius: var(--radius-md);border: 1px solid var(--border-subtle);display: flex;flex-direction: column;gap: 12px;height: 100px;position: relative;overflow: hidden;}.skeletonPulse {background: linear-gradient(90deg,var(--bg-hover) 25%,var(--border-subtle) 50%,var(--bg-hover) 75%);background-size: 200% 100%;animation: pulse 1.5s infinite;border-radius: 4px;}.skeletonId {width: 60px;height: 12px;}.skeletonTitle {width: 90%;height: 20px;}.skeletonFooter {width: 100%;height: 16px;margin-top: auto;}@keyframes pulse {0% {background-position: 200% 0;}100% {background-position: -200% 0;}}
6 unmodified lines78910111227 unmodified lines4041424344454623 unmodified lines7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211226 unmodified linestickets: Ticket[];onSelect?: (ticket: Ticket) => void;statuses: string[];}const statusConfig: Record<string, { icon: string; color: string }> = {27 unmodified lines.join(' ');};export const KanbanBoard: React.FC<KanbanBoardProps> = ({ tickets, onSelect, statuses }) => {const columns = useMemo(() => {return statuses.map(s => ({id: s,23 unmodified lines<div className={styles.columnContent}><AnimatePresence mode="popLayout">{colTickets.map((t, i) => (<motion.divkey={t.id}layoutinitial={{ opacity: 0, scale: 0.95, y: 10 }}animate={{ opacity: 1, scale: 1, y: 0 }}exit={{ opacity: 0, scale: 0.95, y: -10 }}transition={{ duration: 0.2, delay: i * 0.03 }}className={styles.card}onClick={() => onSelect?.(t)}><div className={styles.cardGlow} style={{ background: priorityColor[t.priority] || 'var(--text3)' }} /><div className={styles.cardHeader}><div className={styles.headerLeft}><span className={styles.id}>#{t.id?.slice(0, 8).toUpperCase()}</span><spanclassName={styles.priorityBadge}style={{background: `${priorityColor[t.priority]}15`,color: priorityColor[t.priority]}}>{t.priority}</span></div>{t.ai_metadata?.ai_score && (<span className={styles.aiBadge}>AI {t.ai_metadata.ai_score}%</span>)}</div><div className={styles.title}>{t.title}</div><div className={styles.cardFooter}><div className={styles.customerInfo}><span className={styles.sentiment}>{t.ai_metadata?.sentiment === 'Negative' ? '🔴' : '⚪'}</span><span className={styles.customerName}>{toCamelCase(t.creator_name || 'System')}</span></div><div className={styles.assignee}><div className={styles.avatar} title={t.assigned_name}>{t.assigned_name ? t.assigned_name.slice(0, 2).toUpperCase() : '??'}</div></div></div></motion.div>))}</AnimatePresence>{colTickets.length === 0 && (<div className={styles.emptyCol}>No tickets</div>)}</div>6 unmodified lines7891011121327 unmodified lines41424344454647484950515253545523 unmodified lines7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441456 unmodified linestickets: Ticket[];onSelect?: (ticket: Ticket) => void;statuses: string[];loading?: boolean;}const statusConfig: Record<string, { icon: string; color: string }> = {27 unmodified lines.join(' ');};const SkeletonCard: React.FC = () => (<div className={styles.skeletonCard}><div className={`${styles.skeletonId} ${styles.skeletonPulse}`} /><div className={`${styles.skeletonTitle} ${styles.skeletonPulse}`} /><div className={`${styles.skeletonFooter} ${styles.skeletonPulse}`} /></div>);export const KanbanBoard: React.FC<KanbanBoardProps> = ({ tickets, onSelect, statuses, loading }) => {const columns = useMemo(() => {return statuses.map(s => ({id: s,23 unmodified lines<div className={styles.columnContent}><AnimatePresence mode="popLayout">{loading && tickets.length === 0 ? (Array.from({ length: 3 }).map((_, i) => (<motion.divkey={`skeleton-${col.id}-${i}`}initial={{ opacity: 0 }}animate={{ opacity: 1 }}exit={{ opacity: 0 }}transition={{ duration: 0.2, delay: i * 0.05 }}><SkeletonCard /></motion.div>))) : (colTickets.map((t, i) => (<motion.divkey={t.id}layoutinitial={{ opacity: 0, scale: 0.95, y: 10 }}animate={{ opacity: 1, scale: 1, y: 0 }}exit={{ opacity: 0, scale: 0.95, y: -10 }}transition={{ duration: 0.2, delay: i * 0.03 }}className={styles.card}onClick={() => onSelect?.(t)}><div className={styles.cardGlow} style={{ background: priorityColor[t.priority] || 'var(--text3)' }} /><div className={styles.cardHeader}><div className={styles.headerLeft}><span className={styles.id}>#{t.id?.slice(0, 8).toUpperCase()}</span><spanclassName={styles.priorityBadge}style={{background: `${priorityColor[t.priority]}15`,color: priorityColor[t.priority]}}>{t.priority}</span></div>{t.ai_metadata?.ai_score && (<span className={styles.aiBadge}>AI {t.ai_metadata.ai_score}%</span>)}</div><div className={styles.title}>{t.title}</div><div className={styles.cardFooter}><div className={styles.customerInfo}><span className={styles.sentiment}>{t.ai_metadata?.sentiment === 'Negative' ? '🔴' : '⚪'}</span><span className={styles.customerName}>{toCamelCase(t.creator_name || 'System')}</span></div><div className={styles.assignee}><div className={styles.avatar} title={t.assigned_name}>{t.assigned_name ? t.assigned_name.slice(0, 2).toUpperCase() : '??'}</div></div></div></motion.div>)))}</AnimatePresence>{tickets.length > 0 && colTickets.length === 0 && (<div className={styles.emptyCol}>No tickets</div>)}</div>
504 unmodified lines505506507508509510511512513514515516517518158 unmodified lines677678679680681682683504 unmodified lines<span className={styles.catBadge}>{article.category}</span><h3>{article.title}</h3><p className={styles.snippet}>{article.snippet || article.content.replace(/[#*`]/g, '').slice(0, 140)}...</p></div><div className={styles.cardFooter}><div className={styles.telemetry}><span>TELEMETRY: {new Date(article.updated_at).toLocaleDateString()}</span>{article.score && <span>MATCH: {Math.round(article.score * 100)}%</span>}</div></div></motion.div>158 unmodified lines</div><div className={styles.telItem}><label>MATCH SCORE</label><span>{selectedArticle?.score ? `${Math.round(selectedArticle.score * 100)}%` : 'STATIC'}</span></div></div>504 unmodified lines505506507508509510511512513514515516517518158 unmodified lines677678679680681682683504 unmodified lines<span className={styles.catBadge}>{article.category}</span><h3>{article.title}</h3><p className={styles.snippet}>{article.snippet || article.content.replace(/[#*`|>\-]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 140)}...</p></div><div className={styles.cardFooter}><div className={styles.telemetry}><span>TELEMETRY: {new Date(article.updated_at).toLocaleDateString()}</span>{article.score && <span>MATCH: {Math.round(article.score)}%</span>}</div></div></motion.div>158 unmodified lines</div><div className={styles.telItem}><label>MATCH SCORE</label><span>{selectedArticle?.score ? `${Math.round(selectedArticle.score)}%` : 'STATIC'}</span></div></div>
184 unmodified lines185186187188189190184 unmodified linestickets={filteredTickets}onSelect={onSelect}statuses={['OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED']}/>) : (<TicketGrid tickets={filteredTickets} onSelect={onSelect} loading={loading} />184 unmodified lines185186187188189190191184 unmodified linestickets={filteredTickets}onSelect={onSelect}statuses={['OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED']}loading={loading}/>) : (<TicketGrid tickets={filteredTickets} onSelect={onSelect} loading={loading} />
45 unmodified lines4647484950515245 unmodified lines});}, [tickets, sortKey]);if (loading) {return <div className={styles.loading}>Synchronizing scrum board...</div>;}45 unmodified lines4647484950515245 unmodified lines});}, [tickets, sortKey]);if (loading && tickets.length === 0) {return <div className={styles.loading}>Synchronizing scrum board...</div>;}
223 unmodified lines224225226227228229230223 unmodified linesreturn (<ahref={decoratedHref}style={{ color: COLORS.brand, fontWeight: 600, textDecoration: 'none', borderBottom: `1px solid ${COLORS.gray200}` }}target={isDownload ? "_blank" : "_self"}rel={isDownload ? "noopener noreferrer" : undefined}{...props}223 unmodified lines224225226227228229230231232233234235236223 unmodified linesreturn (<ahref={decoratedHref}style={{color: isMe ? '#fff' : COLORS.brand,fontWeight: 600,textDecoration: 'none',borderBottom: `1px solid ${isMe ? 'rgba(255,255,255,0.3)' : COLORS.gray200}`,opacity: 1}}target={isDownload ? "_blank" : "_self"}rel={isDownload ? "noopener noreferrer" : undefined}{...props}
101 unmodified lines10210310410510610710810911011111211311411511611 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511524 unmodified lines15715815916016116215 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152161 unmodified line2182192202212222232242252262271 unmodified line2292302312322332342352362372381 unmodified line240241242243244245246247248249250101 unmodified lines};};export const useReports = (workspaceId?: string) => {const [volume, setVolume] = useState<VolumeTrend | null>(null);const [daily, setDaily] = useState<DailyStat[]>([]);const [sla, setSla] = useState<SLAMetrics | null>(null);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchReports = useCallback(async (force: boolean = false) => {setLoading(true);try {let volUrl = workspaceId ? `reports/volume/?workspace_id=${workspaceId}` : 'reports/volume/';let slaUrl = workspaceId ? `reports/sla/?workspace_id=${workspaceId}` : 'reports/sla/';11 unmodified linesapi.get(slaUrl),api.get(dailyUrl)]);setVolume(volRes.data);setSla(slaRes.data);setDaily(dRes.data);setError(null);} catch (err: any) {setError(err.response?.data?.detail || 'Failed to fetch reports');} finally {setLoading(false);}}, [workspaceId]);useEffect(() => {const token = localStorage.getItem('token');if (token) {fetchReports();}}, [fetchReports]);return { volume, daily, sla, loading, error, refresh: () => fetchReports(true) };};export interface Breach {4 unmodified linesage_minutes: number;threshold: number;is_escalated: boolean;}export interface AuditEntry {15 unmodified linesis_active: boolean;}export const useEscalations = () => {const [rules, setRules] = useState<EscalationRule[]>([]);const [breaches, setBreaches] = useState<Breach[]>([]);const [audit, setAudit] = useState<AuditEntry[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchData = useCallback(async () => {setLoading(true);try {const [rRes, bRes, aRes] = await Promise.all([api.get('escalations/rules/'),api.get('escalations/breaches/'),api.get('escalations/audit/')]);setRules(rRes.data);setBreaches(bRes.data);setAudit(aRes.data);setError(null);} catch (err: any) {setError(err.response?.data?.detail || 'Failed to fetch escalation data');} finally {setLoading(false);}}, []);const createRule = async (data: any) => {try {await api.post('escalations/rules/', data);await fetchData();return true;} catch (err: any) {setError(err.response?.data?.detail || 'Failed to create rule');return false;}};1 unmodified lineconst updateRule = async (id: string, data: any) => {try {await api.patch(`escalations/rules/${id}`, data);await fetchData();return true;} catch (err: any) {setError(err.response?.data?.detail || 'Failed to update rule');return false;}};1 unmodified lineconst deleteRule = async (id: string) => {try {await api.delete(`escalations/rules/${id}`);await fetchData();return true;} catch (err: any) {setError(err.response?.data?.detail || 'Failed to delete rule');return false;}};1 unmodified lineuseEffect(() => {const token = localStorage.getItem('token');if (token) {fetchData();}}, [fetchData]);return { rules, breaches, audit, loading, error, refresh: fetchData, createRule, updateRule, deleteRule };};export interface AIInsights {101 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114211 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821834 unmodified lines18818919019119219319419519615 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802811 unmodified line2832842852862872882892902912922931 unmodified line2952962972982993003013023033043051 unmodified line307308309310311312313314315316317318319101 unmodified lines};};// Global state for reportslet globalReports: {volume: VolumeTrend | null;daily: DailyStat[];sla: SLAMetrics | null;} = { volume: null, daily: [], sla: null };let globalReportsLoading = false;let globalReportsError: string | null = null;const reportsListeners = new Set<(r: typeof globalReports, l: boolean, e: string | null) => void>();const notifyReports = () => reportsListeners.forEach(l => l(globalReports, globalReportsLoading, globalReportsError));export const useReports = (workspaceId?: string) => {const [localReports, setLocalReports] = useState(globalReports);const [loading, setLoading] = useState(globalReportsLoading);const [error, setError] = useState(globalReportsError);useEffect(() => {const listener = (r: typeof globalReports, l: boolean, e: string | null) => {setLocalReports(r);setLoading(l);setError(e);};reportsListeners.add(listener);return () => {reportsListeners.delete(listener);};}, []);const fetchReports = useCallback(async (force: boolean = false) => {// If not forced and we already have data, skip initial loading stateif (!force && globalReports.volume) return;globalReportsLoading = true;notifyReports();try {let volUrl = workspaceId ? `reports/volume/?workspace_id=${workspaceId}` : 'reports/volume/';let slaUrl = workspaceId ? `reports/sla/?workspace_id=${workspaceId}` : 'reports/sla/';11 unmodified linesapi.get(slaUrl),api.get(dailyUrl)]);globalReports = {volume: volRes.data,sla: slaRes.data,daily: dRes.data};globalReportsError = null;} catch (err: any) {globalReportsError = err.response?.data?.detail || 'Failed to fetch reports';} finally {globalReportsLoading = false;notifyReports();}}, [workspaceId]);useEffect(() => {const token = localStorage.getItem('token');if (token) {if (!globalReports.volume) {fetchReports();}}}, [fetchReports]);return { ...localReports, loading, error, refresh: () => fetchReports(true) };};export interface Breach {4 unmodified linesage_minutes: number;threshold: number;is_escalated: boolean;minutes_remaining: number;risk_score: number;is_breached: boolean;}export interface AuditEntry {15 unmodified linesis_active: boolean;}// Global state for escalationslet globalEscalations: {rules: EscalationRule[];breaches: Breach[];audit: AuditEntry[];} = { rules: [], breaches: [], audit: [] };let globalEscalationsLoading = false;let globalEscalationsError: string | null = null;const escalationsListeners = new Set<(e: typeof globalEscalations, l: boolean, err: string | null) => void>();const notifyEscalations = () => escalationsListeners.forEach(l => l(globalEscalations, globalEscalationsLoading, globalEscalationsError));export const useEscalations = () => {const [localEsc, setLocalEsc] = useState(globalEscalations);const [loading, setLoading] = useState(globalEscalationsLoading);const [error, setError] = useState(globalEscalationsError);useEffect(() => {const listener = (e: typeof globalEscalations, l: boolean, err: string | null) => {setLocalEsc(e);setLoading(l);setError(err);};escalationsListeners.add(listener);return () => {escalationsListeners.delete(listener);};}, []);const fetchData = useCallback(async (force: boolean = false) => {if (!force && (globalEscalations.rules.length > 0 || globalEscalations.breaches.length > 0)) {return;}globalEscalationsLoading = true;notifyEscalations();try {const [rRes, bRes, aRes] = await Promise.all([api.get('escalations/rules/'),api.get('escalations/breaches/'),api.get('escalations/audit/')]);globalEscalations = {rules: rRes.data,breaches: bRes.data,audit: aRes.data};globalEscalationsError = null;} catch (err: any) {globalEscalationsError = err.response?.data?.detail || 'Failed to fetch escalation data';} finally {globalEscalationsLoading = false;notifyEscalations();}}, []);const createRule = async (data: any) => {try {await api.post('escalations/rules/', data);await fetchData(true);return true;} catch (err: any) {globalEscalationsError = err.response?.data?.detail || 'Failed to create rule';notifyEscalations();return false;}};1 unmodified lineconst updateRule = async (id: string, data: any) => {try {await api.patch(`escalations/rules/${id}`, data);await fetchData(true);return true;} catch (err: any) {globalEscalationsError = err.response?.data?.detail || 'Failed to update rule';notifyEscalations();return false;}};1 unmodified lineconst deleteRule = async (id: string) => {try {await api.delete(`escalations/rules/${id}`);await fetchData(true);return true;} catch (err: any) {globalEscalationsError = err.response?.data?.detail || 'Failed to delete rule';notifyEscalations();return false;}};1 unmodified lineuseEffect(() => {const token = localStorage.getItem('token');if (token) {if (globalEscalations.rules.length === 0 && globalEscalations.breaches.length === 0) {fetchData();}}}, [fetchData]);return { ...localEsc, loading, error, refresh: () => fetchData(true), createRule, updateRule, deleteRule };};export interface AIInsights {
24 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758595 unmodified lines6566676869707172737475767778798081828384854 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713824 unmodified linesmetadata?: any;}export const useTickets = () => {const [tickets, setTickets] = useState<Ticket[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchTickets = useCallback(async () => {setLoading(true);try {const response = await api.get('tickets/');setTickets(response.data);setError(null);} catch (err: any) {if (err.response?.status === 401) {setTickets([]);}setError(err.response?.data?.detail || 'Failed to fetch tickets');} finally {setLoading(false);}}, []);const createTicket = async (data: any) => {try {const response = await api.post('tickets/', data);await fetchTickets();return response.data;} catch (err: any) {if (err.response?.status === 422) {// Detailed Pydantic error loggingconst details = err.response.data.detail;const msg = Array.isArray(details) ? details.map((d: any) => `${d.loc.join('.')}: ${d.msg}`).join(' | ') : 'Validation error';console.error("VALIDATION ERROR DETAIL:", details);5 unmodified linesuseEffect(() => {const token = localStorage.getItem('token');if (token) {fetchTickets();}}, [fetchTickets]);return { tickets, loading, error, refresh: fetchTickets, createTicket };};export const useAgentQueue = (workspaceId?: string) => {const [tickets, setTickets] = useState<Ticket[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchQueue = useCallback(async (force: boolean = false) => {setLoading(true);try {let url = workspaceId? `dashboard/agent-queue/?workspace_id=${workspaceId}`4 unmodified lines}const response = await api.get(url);setTickets(response.data);setError(null);} catch (err: any) {setError(err.response?.data?.detail || 'Failed to fetch agent queue');} finally {setLoading(false);}}, [workspaceId]);useEffect(() => {const token = localStorage.getItem('token');if (token) {fetchQueue();}}, [fetchQueue]);return { tickets, loading, error, refresh: () => fetchQueue(true) };};export const useTicketStatuses = () => {const [statuses, setStatuses] = useState<string[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchStatuses = useCallback(async () => {setLoading(true);try {const response = await api.get('tickets/statuses/');setStatuses(response.data);setError(null);} catch (err: any) {setError(err.response?.data?.detail || 'Failed to fetch statuses');} finally {setLoading(false);}}, []);useEffect(() => {const token = localStorage.getItem('token');if (token) {fetchStatuses();}}, [fetchStatuses]);return { statuses, loading, error, refresh: fetchStatuses };};24 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081825 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291304 unmodified lines13513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620724 unmodified linesmetadata?: any;}// Global singletonslet globalTickets: Ticket[] = [];let globalTicketsLoading = false;let globalTicketsError: string | null = null;const ticketsListeners = new Set<(t: Ticket[], l: boolean, e: string | null) => void>();const notifyTickets = () => ticketsListeners.forEach(l => l(globalTickets, globalTicketsLoading, globalTicketsError));export const useTickets = () => {const [localTickets, setLocalTickets] = useState(globalTickets);const [loading, setLoading] = useState(globalTicketsLoading);const [error, setError] = useState(globalTicketsError);useEffect(() => {const listener = (t: Ticket[], l: boolean, e: string | null) => {setLocalTickets(t);setLoading(l);setError(e);};ticketsListeners.add(listener);return () => {ticketsListeners.delete(listener);};}, []);const fetchTickets = useCallback(async (force: boolean = false) => {if (!force && globalTickets.length > 0) return;globalTicketsLoading = true;notifyTickets();try {const response = await api.get('tickets/');globalTickets = response.data;globalTicketsError = null;} catch (err: any) {if (err.response?.status === 401) {globalTickets = [];}globalTicketsError = err.response?.data?.detail || 'Failed to fetch tickets';} finally {globalTicketsLoading = false;notifyTickets();}}, []);const createTicket = async (data: any) => {try {const response = await api.post('tickets/', data);await fetchTickets(true);return response.data;} catch (err: any) {if (err.response?.status === 422) {const details = err.response.data.detail;const msg = Array.isArray(details) ? details.map((d: any) => `${d.loc.join('.')}: ${d.msg}`).join(' | ') : 'Validation error';console.error("VALIDATION ERROR DETAIL:", details);5 unmodified linesuseEffect(() => {const token = localStorage.getItem('token');if (token && globalTickets.length === 0) {fetchTickets();}}, [fetchTickets]);return { tickets: localTickets, loading, error, refresh: () => fetchTickets(true), createTicket };};let globalQueue: Ticket[] = [];let globalQueueLoading = false;let globalQueueError: string | null = null;const queueListeners = new Set<(t: Ticket[], l: boolean, e: string | null) => void>();const notifyQueue = () => queueListeners.forEach(l => l(globalQueue, globalQueueLoading, globalQueueError));export const useAgentQueue = (workspaceId?: string) => {const [localQueue, setLocalQueue] = useState(globalQueue);const [loading, setLoading] = useState(globalQueueLoading);const [error, setError] = useState(globalQueueError);useEffect(() => {const listener = (t: Ticket[], l: boolean, e: string | null) => {setLocalQueue(t);setLoading(l);setError(e);};queueListeners.add(listener);return () => {queueListeners.delete(listener);};}, []);const fetchQueue = useCallback(async (force: boolean = false) => {if (!force && globalQueue.length > 0) return;globalQueueLoading = true;notifyQueue();try {let url = workspaceId? `dashboard/agent-queue/?workspace_id=${workspaceId}`4 unmodified lines}const response = await api.get(url);globalQueue = response.data;globalQueueError = null;} catch (err: any) {globalQueueError = err.response?.data?.detail || 'Failed to fetch agent queue';} finally {globalQueueLoading = false;notifyQueue();}}, [workspaceId]);useEffect(() => {const token = localStorage.getItem('token');if (token && globalQueue.length === 0) {fetchQueue();}}, [fetchQueue]);return { tickets: localQueue, loading, error, refresh: () => fetchQueue(true) };};let globalStatuses: string[] = [];let globalStatusesLoading = false;let globalStatusesError: string | null = null;const statusesListeners = new Set<(s: string[], l: boolean, e: string | null) => void>();const notifyStatuses = () => statusesListeners.forEach(l => l(globalStatuses, globalStatusesLoading, globalStatusesError));export const useTicketStatuses = () => {const [localStatuses, setLocalStatuses] = useState(globalStatuses);const [loading, setLoading] = useState(globalStatusesLoading);const [error, setError] = useState(globalStatusesError);useEffect(() => {const listener = (s: string[], l: boolean, e: string | null) => {setLocalStatuses(s);setLoading(l);setError(e);};statusesListeners.add(listener);return () => {statusesListeners.delete(listener);};}, []);const fetchStatuses = useCallback(async (force: boolean = false) => {if (!force && globalStatuses.length > 0) return;globalStatusesLoading = true;notifyStatuses();try {const response = await api.get('tickets/statuses/');globalStatuses = response.data;globalStatusesError = null;} catch (err: any) {globalStatusesError = err.response?.data?.detail || 'Failed to fetch statuses';} finally {globalStatusesLoading = false;notifyStatuses();}}, []);useEffect(() => {const token = localStorage.getItem('token');if (token && globalStatuses.length === 0) {fetchStatuses();}}, [fetchStatuses]);return { statuses: localStatuses, loading, error, refresh: () => fetchStatuses(true) };};
9 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354559 unmodified linesavatar_url?: string;}export const useUsers = (workspaceId?: string) => {const [users, setUsers] = useState<User[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchUsers = useCallback(async () => {setLoading(true);try {const url = workspaceId ? `users/?workspace_id=${workspaceId}` : 'users/';const response = await api.get(url);setUsers(response.data);setError(null);} catch (err: any) {setError(err.response?.data?.detail || 'Failed to fetch users');} finally {setLoading(false);}}, [workspaceId]);const addUser = async (payload: any) => {setLoading(true);try {const response = await api.post('users/', payload);await fetchUsers();return response.data;} catch (err: any) {const detail = err.response?.data?.detail;const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join(', ') : detail;throw new Error(msg || 'Failed to add user');} finally {setLoading(false);}};useEffect(() => {const token = localStorage.getItem('token');if (token) {fetchUsers();}}, [fetchUsers]);return { users, loading, error, refresh: fetchUsers, addUser };};9 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475769 unmodified linesavatar_url?: string;}// Global singleton for user listlet globalUsers: User[] = [];let globalUsersLoading = false;let globalUsersError: string | null = null;const usersListeners = new Set<(u: User[], l: boolean, e: string | null) => void>();const notifyUsers = () => usersListeners.forEach(l => l(globalUsers, globalUsersLoading, globalUsersError));export const useUsers = (workspaceId?: string) => {const [localUsers, setLocalUsers] = useState(globalUsers);const [loading, setLoading] = useState(globalUsersLoading);const [error, setError] = useState(globalUsersError);useEffect(() => {const listener = (u: User[], l: boolean, e: string | null) => {setLocalUsers(u);setLoading(l);setError(e);};usersListeners.add(listener);return () => {usersListeners.delete(listener);};}, []);const fetchUsers = useCallback(async (force: boolean = false) => {if (!force && globalUsers.length > 0) return;globalUsersLoading = true;notifyUsers();try {const url = workspaceId ? `users/?workspace_id=${workspaceId}` : 'users/';const response = await api.get(url);globalUsers = response.data;globalUsersError = null;} catch (err: any) {globalUsersError = err.response?.data?.detail || 'Failed to fetch users';} finally {globalUsersLoading = false;notifyUsers();}}, [workspaceId]);const addUser = async (payload: any) => {try {const response = await api.post('users/', payload);await fetchUsers(true);return response.data;} catch (err: any) {const detail = err.response?.data?.detail;const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join(', ') : detail;throw new Error(msg || 'Failed to add user');}};useEffect(() => {const token = localStorage.getItem('token');if (token && globalUsers.length === 0) {fetchUsers();}}, [fetchUsers]);return { users: localUsers, loading, error, refresh: () => fetchUsers(true), addUser };};
7 unmodified lines89101112131415161718192021222324252627282930313233343536377 unmodified linesbranding?: any;}export const useWorkspaces = () => {const [workspaces, setWorkspaces] = useState<Workspace[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchWorkspaces = useCallback(async () => {setLoading(true);try {const response = await api.get('workspace/list/');setWorkspaces(response.data);setError(null);} catch (err: any) {setError(err.response?.data?.detail || 'Failed to fetch workspaces');} finally {setLoading(false);}}, []);useEffect(() => {const token = localStorage.getItem('token');if (token) {fetchWorkspaces();}}, [fetchWorkspaces]);return { workspaces, loading, error, refresh: fetchWorkspaces };};7 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960617 unmodified linesbranding?: any;}// Global singleton for workspaceslet globalWorkspaces: Workspace[] = [];let globalWorkspacesLoading = false;let globalWorkspacesError: string | null = null;const workspacesListeners = new Set<(w: Workspace[], l: boolean, e: string | null) => void>();const notifyWorkspaces = () => workspacesListeners.forEach(l => l(globalWorkspaces, globalWorkspacesLoading, globalWorkspacesError));export const useWorkspaces = () => {const [localWorkspaces, setLocalWorkspaces] = useState(globalWorkspaces);const [loading, setLoading] = useState(globalWorkspacesLoading);const [error, setError] = useState(globalWorkspacesError);useEffect(() => {const listener = (w: Workspace[], l: boolean, e: string | null) => {setLocalWorkspaces(w);setLoading(l);setError(e);};workspacesListeners.add(listener);return () => {workspacesListeners.delete(listener);};}, []);const fetchWorkspaces = useCallback(async (force: boolean = false) => {if (!force && globalWorkspaces.length > 0) return;globalWorkspacesLoading = true;notifyWorkspaces();try {const response = await api.get('workspace/list/');globalWorkspaces = response.data;globalWorkspacesError = null;} catch (err: any) {globalWorkspacesError = err.response?.data?.detail || 'Failed to fetch workspaces';} finally {globalWorkspacesLoading = false;notifyWorkspaces();}}, []);useEffect(() => {const token = localStorage.getItem('token');if (token && globalWorkspaces.length === 0) {fetchWorkspaces();}}, [fetchWorkspaces]);return { workspaces: localWorkspaces, loading, error, refresh: () => fetchWorkspaces(true) };};
agents/nexus_customer.py+14-6
agents/nexus_master.py+73-27
agents/prompts.py+1-1
api/v1/attachments.py+12-7
api/v1/kb.py+5-1
api/v1/nexus_stream.py+28-4
core/cache.py+8
frontend/apps/customer/src/App.tsx+8-4
frontend/apps/customer/src/components/Analytics.tsx+31-62
frontend/apps/customer/src/components/Dashboard.tsx+23-41
frontend/apps/customer/src/components/TicketList.tsx+1-1
frontend/apps/internal/src/App.tsx+7-4
frontend/apps/internal/src/components/AnalyticsDashboard.tsx+2-1
frontend/apps/internal/src/components/KanbanBoard.module.css+51
frontend/apps/internal/src/components/KanbanBoard.tsx+67-44
frontend/apps/internal/src/components/KnowledgeBase.tsx+3-3
frontend/apps/internal/src/components/TicketBoard.tsx+1
frontend/apps/internal/src/components/TicketGrid.tsx+1-1
frontend/packages/shared/src/components/NexusMarkdown.tsx+7-1
frontend/packages/shared/src/hooks/useDashboard.ts+104-35
frontend/packages/shared/src/hooks/useTickets.ts+104-35
frontend/packages/shared/src/hooks/useUsers.ts+36-15
frontend/packages/shared/src/hooks/useWorkspaces.ts+35-11