Spaces:
Paused

nexus / frontend /apps /internal /src /components /AnalyticsDashboard.tsx
dushyantsingh0
backend stabilization
837cc5f
Raw History Blame Contribute Delete
13.7 kB
import React from 'react';
import {
useDashboardStats,
useReports,
useEscalations,
useAIInsights,
useServiceNarrative
} from '@nexus/shared';
import {
Terminal,
Activity,
Shield,
Clock,
MessageSquare,
Cpu,
AlertTriangle,
TrendingUp
} from 'lucide-react';
import { motion } from 'framer-motion';
import ReactMarkdown from 'react-markdown';
import styles from './AnalyticsDashboard.module.css';
interface AnalyticsDashboardProps {
workspaceId?: string;
onTicketSelect?: (ticket: any) => void;
readOnly?: boolean;
}
const MiniTrend = ({ data, color }: { data: number[], color: string }) => {
if (data.length < 2) return null;
const min = Math.min(...data);
const max = Math.max(...data);
const range = max - min || 1;
const width = 60;
const height = 24;
const points = data.map((val, i) => {
const x = (i / (data.length - 1)) * width;
const y = height - ((val - min) / range) * height;
return `${x},${y}`;
}).join(' ');
return (
<div className={styles.miniTrendContainer}>
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
<polyline
fill="none"
stroke={color}
strokeWidth="1.5"
points={points}
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
);
};
export const AnalyticsDashboard: React.FC<AnalyticsDashboardProps> = ({ workspaceId, onTicketSelect, readOnly }) => {
const { stats, loading: statsLoading } = useDashboardStats(workspaceId);
const { daily, sla, loading: reportsLoading } = useReports(workspaceId);
const { breaches, audit, loading: escLoading } = useEscalations(workspaceId);
const { insights, loading: aiLoading } = useAIInsights(workspaceId);
const { narrative, loading: narrativeLoading } = useServiceNarrative(workspaceId);
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} />
<span>Initializing Neural Analytics Suite...</span>
</div>
);
}
// 1. Process Daily Stats for Category Intensity & Trends
const dailyVolumes = daily.map(d => d.total);
const categories = daily.reduce((acc: any, day: any, index: number) => {
Object.entries(day.categories).forEach(([cat, count]: [string, any]) => {
if (!acc[cat]) acc[cat] = { total: 0, weekly: 0, previous: 0 };
acc[cat].total += count;
// Velocity check: Last 7 days vs previous 23
if (index >= daily.length - 7) {
acc[cat].weekly += count;
} else {
acc[cat].previous += count;
}
});
return acc;
}, {});
const sortedCategories = Object.entries(categories)
.map(([name, data]: any) => {
const weeklyAvg = data.weekly / 7;
const prevAvg = data.previous / 23;
const ratio = prevAvg > 0 ? weeklyAvg / prevAvg : (data.weekly > 0 ? 2 : 1);
let velocity: 'surge' | 'stable' | 'declining' = 'stable';
if (ratio > 1.25) velocity = 'surge';
else if (ratio < 0.75) velocity = 'declining';
return { name, count: data.total, velocity, ratio };
})
.sort((a, b) => b.count - a.count)
.slice(0, 5);
const maxCatCount = Math.max(...sortedCategories.map(c => c.count), 1);
// 2. Performance Vitals
const vitals = [
{
label: "TOTAL TICKETS (30D)",
value: stats?.total_tickets || 0,
sub: "Active Stream",
icon: <Activity />,
color: "#3B82F6",
trend: dailyVolumes
},
{
label: "SLA COMPLIANCE",
value: `${((sla?.sla_compliance_rate || 0) * 100).toFixed(0)}%`,
sub: `${sla?.on_time_tickets} On Time`,
icon: <Shield />,
color: "#10B981"
},
{
label: "AVG RESOLUTION",
value: `${stats?.performance?.avg_resolution_hours || 0}h`,
sub: "Lead Time",
icon: <Clock />,
color: "#8B5CF6"
},
{
label: "SERVICE CSAT",
value: stats?.performance?.csat_score ?? 0.0,
sub: "User Sentiment",
icon: <MessageSquare />,
color: "#F59E0B"
},
];
return (
<div className={styles.container}>
{/* 1. Global Vitals Row */}
<div className={styles.vitalsRow}>
{vitals.map(v => (
<div key={v.label} className={styles.vitalCard}>
<div className={styles.vitalIcon} style={{ background: `${v.color}20`, color: v.color }}>
{v.icon}
</div>
<div className={styles.vitalMeta}>
<span className={styles.vitalLabel}>{v.label}</span>
<span className={styles.vitalValue}>{v.value}</span>
<span className={styles.vitalSub}>{v.sub}</span>
</div>
{v.trend && (
<div style={{ marginLeft: 'auto' }}>
<MiniTrend data={v.trend} color={v.color} />
</div>
)}
</div>
))}
</div>
<div className={styles.mainGrid}>
{/* 2. AI Sentinel Section */}
<div className={styles.sentinelArea}>
<div className={styles.cardHeader}>
<Cpu className={styles.headerIcon} />
<div className={styles.headerText}>
<h3>SENTINEL AI INSIGHTS</h3>
<span>Autonomous Narrative Analysis</span>
</div>
{aiLoading && <div className={styles.miniSpinner} />}
</div>
<div className={styles.sentinelContent}>
<div className={styles.narrativeBox}>
<ReactMarkdown>
{narrative?.insights || "Analyzing service patterns... neural pathways converging."}
</ReactMarkdown>
</div>
{!readOnly && (
<div className={styles.actionGrid}>
<label>STRATEGIC ACTIONS</label>
{insights?.actions.map((action: string, i: number) => (
<div key={i} className={styles.actionItem}>
<div className={styles.actionBullet}>{i + 1}</div>
<p>{action}</p>
</div>
))}
</div>
)}
</div>
</div>
{/* 3. Categorical Intensity (Internal Sidebar) */}
<div className={styles.intensityArea}>
<div className={styles.cardHeader}>
<TrendingUp className={styles.headerIcon} />
<div className={styles.headerText}>
<h3>OPERATIONAL INTENSITY</h3>
<span>Category Mix (30D)</span>
</div>
</div>
<div className={styles.categoryChart}>
<div className={styles.volumeWaveContainer}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
<label style={{ fontSize: 9, fontWeight: 900, color: '#3B82F6' }}>VOLUME TREND (30D)</label>
<label style={{ fontSize: 9, fontWeight: 900, color: '#64748B' }}>
PEAK: {Math.max(...dailyVolumes)}
</label>
</div>
<div style={{ height: 50 }}>
<svg width="100%" height="50" viewBox={`0 0 300 50`} preserveAspectRatio="none">
<motion.path
d={`M ${dailyVolumes.map((v, i) => `${(i / 29) * 300},${50 - (v / Math.max(...dailyVolumes, 1)) * 50}`).join(' L ')}`}
fill="none"
stroke="#3B82F6"
strokeWidth="2"
initial={{ pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 1.5, ease: "easeInOut" }}
/>
<motion.path
d={`M ${dailyVolumes.map((v, i) => `${(i / 29) * 300},${50 - (v / Math.max(...dailyVolumes, 1)) * 50}`).join(' L ')} L 300,50 L 0,50 Z`}
fill="rgba(59, 130, 246, 0.1)"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 1, duration: 1 }}
/>
</svg>
</div>
</div>
{sortedCategories.map(c => (
<div key={c.name} className={styles.categoryBarRow}>
<div className={styles.categoryLabel}>
<div style={{ display: 'flex', alignItems: 'center' }}>
<span>{c.name}</span>
<span className={`${styles.velocityBadge} ${styles[c.velocity]}`}>
{c.velocity}
</span>
</div>
<label>{c.count}</label>
</div>
<div className={styles.barContainer}>
<div
className={styles.barFill}
style={{ width: `${(c.count / maxCatCount) * 100}%` }}
/>
</div>
</div>
))}
</div>
</div>
{/* 4. Operational Audit Ledger */}
<div className={styles.auditArea}>
<div className={styles.cardHeader}>
<Terminal className={styles.headerIcon} />
<div className={styles.headerText}>
<h3>STRATEGIC AUDIT LEDGER</h3>
<span>Recent Escalations & Shifts</span>
</div>
</div>
<div className={styles.auditList}>
{audit.slice(0, 8).map((entry: any) => (
<div key={entry.id} className={styles.auditEntry}>
<div className={styles.auditTime}>
{new Date(entry.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</div>
<div className={styles.auditContent}>
<span className={styles.auditAction}>{entry.action.replace('_', ' ').toUpperCase()}</span>
<p>Ticket ref: {entry.entity_id.slice(0, 8)}...</p>
</div>
</div>
))}
</div>
</div>
{/* 5. SLA Risk & Breach Matrix (Wide Bottom) */}
<div className={styles.riskArea}>
<div className={styles.cardHeader}>
<AlertTriangle className={styles.headerIcon} style={{ color: '#F59E0B' }} />
<div className={styles.headerText}>
<h3>SLA RISK & BREACH MATRIX</h3>
<span>Autonomous Early Warning System</span>
</div>
</div>
<div className={styles.tableWrapper}>
<table className={styles.breachTable}>
<thead>
<tr>
<th>URGENCY</th>
<th>PRIORITY</th>
<th>TICKET ID</th>
<th>TITLE</th>
<th>TIME STATUS</th>
</tr>
</thead>
<tbody>
{breaches.length > 0 ? (
breaches.map((b: any) => (
<tr
key={b.id}
className={`${b.is_breached ? styles.breachRow : styles.atRiskRow} ${b.is_breached ? styles.pulseRed : styles.pulseAmber}`}
onClick={() => onTicketSelect?.(b)}
>
<td>
<div className={styles.riskMeterWrapper}>
<div className={styles.riskMeterTrack}>
<div
className={styles.riskMeterFill}
style={{
width: `${Math.min(b.risk_score, 100)}%`,
background: b.is_breached ? '#EF4444' : '#F59E0B'
}}
/>
</div>
<div className={styles.riskValueBox}>
<span>RISK: {b.risk_score}%</span>
</div>
</div>
</td>
<td>
<span className={styles.priorityBadge} data-priority={b.priority}>
{b.priority}
</span>
</td>
<td className={styles.refCell}>#{b.id.slice(0, 8).toUpperCase()}</td>
<td className={styles.titleCell} style={{ color: b.is_breached ? '#991B1B' : '#92400E' }}>
{b.title}
</td>
<td className={styles.timeCell} style={{ color: b.is_breached ? '#EF4444' : '#F59E0B' }}>
{b.is_breached ? (
`OVERDUE ${Math.round(b.age_minutes - b.threshold)}m`
) : (
<span className={styles.timeToBreach}>
BREACH IN {Math.round(b.minutes_remaining)}m
</span>
)}
</td>
</tr>
))
) : (
<tr>
<td colSpan={5} className={styles.emptyCell}>
<Shield className={styles.shieldIcon} />
Global Compliance Maintained
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
};