Spaces:
Paused

nexus / frontend /apps /customer /src /components /Analytics.tsx
dushyantsingh0
feat: unified portal migration with local redis and fixed routing
5df0bfe
Raw History Blame Contribute Delete
15.5 kB
import React, { useState } from 'react';
import { StatusBadge, PriorityBadge } from './Badges';
import { useReports, useServiceNarrative, NexusMarkdown } from '@nexus/shared';
import { Skeleton } from './Skeleton';
const COLORS = {
brand: "#1E40AF",
brandLight: "rgba(30, 64, 175, 0.1)",
gray50: "#F9FAFB",
gray100: "#F3F4F6",
gray200: "#E5E7EB",
gray400: "#9CA3AF",
gray500: "#6B7280",
gray700: "#374151",
gray800: "#1F2937",
gray900: "#111827",
};
interface AnalyticsProps {
tickets: any[];
}
const Sparkline: React.FC<{ data: number[], color: string }> = ({ data, color }) => {
if (!data || data.length === 0) return null;
const max = Math.max(...data, 1);
const width = 100;
const height = 30;
const divisor = data.length > 1 ? data.length - 1 : 1;
const points = data.map((v, i) => `${(i / divisor) * width},${height - (v / max) * height}`).join(' ');
return (
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ overflow: 'visible' }}>
<polyline fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" points={points} />
</svg>
);
};
export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {
const { volume, sla, csat, 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 {
setIsResummarizing(false);
}
};
const 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;
return acc;
}, {});
const sortedCategories = Object.entries(categoryCounts).sort((a: any, b: any) => b[1] - a[1]);
const priorityCounts = tickets.reduce((acc: any, t) => {
const rawPrio = (t.priority || "P2").toUpperCase();
const PRIO_MAP: Record<string, string> = { "P0": "URGENT", "P1": "HIGH", "P2": "MEDIUM", "P3": "LOW" };
const prio = PRIO_MAP[rawPrio] || rawPrio;
acc[prio] = (acc[prio] || 0) + 1;
return acc;
}, {});
const resolvedTickets = tickets.filter(t => t.resolved_at && (t.status === "RESOLVED" || t.status === "CLOSED"));
let avgResHours = 0;
if (resolvedTickets.length > 0) {
const totalHours = resolvedTickets.reduce((acc, t) => {
const start = new Date(t.created_at).getTime();
const end = new Date(t.resolved_at!).getTime();
return acc + (end - start) / (1000 * 60 * 60);
}, 0);
avgResHours = 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} /> : (csat ? csat.average_rating.toFixed(1) : "β€”"),
footer: showReportsLoading ? <Skeleton width={100} height={12} /> : (csat?.total_responses ? `${csat.total_responses} Total Ratings` : "No Ratings Yet"),
color: "hsl(38, 92%, 50%)",
icon: "⭐",
viz: showReportsLoading ? <Skeleton width={80} height={11} /> : <div style={{ fontSize: 11, color: "#EAB308" }}>
{"β˜…".repeat(Math.floor(csat?.average_rating || 0)) + "β˜†".repeat(5 - Math.floor(csat?.average_rating || 0))}
</div>
},
].map(s => (
<div key={s.label} style={{
background: "#fff",
border: `1px solid ${COLORS.gray200}`,
borderRadius: 16,
padding: "20px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
height: 140,
boxShadow: "0 1px 3px rgba(0,0,0,0.02)"
}}>
<div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
<span style={{ fontSize: 11, color: COLORS.gray500, fontWeight: 750, textTransform: "uppercase", letterSpacing: "0.05em" }}>{s.label}</span>
<span style={{ fontSize: 16 }}>{s.icon}</span>
</div>
<div style={{ fontSize: 26, fontWeight: 800, color: COLORS.gray900, marginBottom: 4 }}>{s.value}</div>
</div>
<div style={{ height: 40, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
<div style={{ marginBottom: 6 }}>{s.viz}</div>
<div style={{ fontSize: 11, color: COLORS.gray400, fontWeight: 600 }}>{s.footer}</div>
</div>
</div>
))}
</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>
<span style={{ fontSize: 11, color: COLORS.gray400 }}>Distribution Analysis</span>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
{sortedCategories.length > 0 ? sortedCategories.map(([cat, count]: any) => (
<div key={cat}>
<div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 12, fontWeight: 600 }}>
<span style={{ color: COLORS.gray700 }}>{cat}</span>
<span style={{ color: COLORS.gray900 }}>{count}</span>
</div>
<div style={{ height: 6, background: COLORS.gray100, borderRadius: 3 }}>
<div style={{ height: "100%", width: `${(count / total) * 100}%`, background: COLORS.brand, borderRadius: 3, transition: "width 0.5s ease" }} />
</div>
</div>
)) : <div style={{ padding: "40px", textAlign: "center", color: COLORS.gray400, fontSize: 13 }}>No categorical data available</div>}
</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 }}>
{["URGENT", "HIGH", "MEDIUM", "LOW"].map(prio => {
const count = priorityCounts[prio] || 0;
const height = total > 0 ? (count / total) * 140 : 0;
return (
<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"
}} />
<span style={{ fontSize: 10, fontWeight: 700, color: COLORS.gray500 }}>{prio}</span>
<span style={{ fontSize: 12, fontWeight: 800, color: COLORS.gray900 }}>{count}</span>
</div>
);
})}
</div>
</div>
</div>
<div style={{
background: "#fff",
border: `1px solid ${COLORS.gray200}`,
borderRadius: 20,
padding: "32px",
marginBottom: 32,
position: "relative",
boxShadow: "0 10px 40px rgba(0,0,0,0.02)"
}}>
<style>
{`
@keyframes intelligence-shimmer {
0% { color: #6B7280; }
50% { color: #D1D5DB; }
100% { color: #6B7280; }
}
.shimmer-text {
animation: intelligence-shimmer 2s infinite ease-in-out;
}
`}
</style>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
<div style={{ display: "flex", gap: 10, alignItems: "center" }}>
<div style={{ width: 8, height: 8, borderRadius: "50%", background: "#10B981" }} />
<span style={{ fontSize: 12, fontWeight: 800, color: COLORS.gray900, textTransform: "uppercase", letterSpacing: "0.05em" }}>Nexus Workspace Intelligence</span>
</div>
<div style={{ display: "flex", gap: 12, alignItems: "center" }}>
<div style={{ fontSize: 11, color: COLORS.brand, fontWeight: 700, padding: "4px 10px", background: COLORS.brandLight, borderRadius: 20 }}>
AI-Synthesized Report
</div>
<button
onClick={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"
>
<span style={{
fontSize: 16,
display: "inline-block",
animation: isResummarizing ? "spin 1s linear infinite" : "none"
}}>πŸ”„</span>
</button>
</div>
</div>
<div
className={showNarrativeLoading ? "shimmer-text" : ""}
style={{
color: COLORS.gray700,
fontSize: 15,
lineHeight: 1.7,
fontWeight: 500,
opacity: isResummarizing ? 0.5 : 1,
transition: "opacity 0.3s ease"
}}
>
{showNarrativeLoading ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<Skeleton width="100%" height={16} />
<Skeleton width="95%" height={16} />
<Skeleton width="90%" height={16} />
</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>
</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 }}>Operational Activity History</div>
<div style={{ overflowX: "auto" }}>
<table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
<thead>
<tr>
{["Ticket", "Subject", "Status", "Priority", "Duration"].map(h => (
<th key={h} style={{ textAlign: "left", padding: "12px", fontSize: 11, fontWeight: 800, color: COLORS.gray500, borderBottom: `1px solid ${COLORS.gray100}`, textTransform: "uppercase", letterSpacing: "0.05em" }}>{h}</th>
))}
</tr>
</thead>
<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>
<td style={{ padding: "12px", fontSize: 12, color: COLORS.gray500, fontWeight: 600 }}>
{t.resolved_at ? `${Math.round((new Date(t.resolved_at).getTime() - new Date(t.created_at).getTime()) / (1000 * 60 * 60))}h` : "β€”"}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
};