import React, { useState, useEffect, useCallback } from 'react'; import { Upload, Building2, ChevronLeft, Loader, AlertCircle, BarChart3 } from 'lucide-react'; import { useAuth } from '../../contexts/AuthContext'; import { PieChart, Pie, Cell, ComposedChart, Bar, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ReferenceLine, ResponsiveContainer } from 'recharts'; import MultiVerticalUploadModal from './MultiVerticalUploadModal'; const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api'; const TEAL = '#14B8A6'; const PURPLE = '#A78BFA'; // --------------------------------------------------------------------------- // Styles // --------------------------------------------------------------------------- const PAGE_STYLE = { padding: '1.5rem 2rem', minHeight: '100vh', fontFamily: "'JetBrains Mono', 'Fira Code', monospace", }; const CARD_STYLE = { background: 'rgba(15, 23, 42, 0.6)', border: '1px solid rgba(167, 139, 250, 0.2)', borderRadius: '0.75rem', padding: '1.25rem', }; const STAT_CARD_STYLE = { ...CARD_STYLE, textAlign: 'center', flex: 1, minWidth: '140px', }; const TABLE_STYLE = { width: '100%', borderCollapse: 'collapse', fontSize: '0.8rem', }; const TH_STYLE = { padding: '0.75rem 1rem', textAlign: 'left', color: '#94A3B8', fontWeight: '600', fontSize: '0.7rem', textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: '1px solid rgba(255,255,255,0.08)', }; const TD_STYLE = { padding: '0.75rem 1rem', color: '#E2E8F0', borderBottom: '1px solid rgba(255,255,255,0.04)', }; // --------------------------------------------------------------------------- // Stats Bar // --------------------------------------------------------------------------- function StatsBar({ stats }) { if (!stats) return null; const items = [ { label: 'Total Devices', value: stats.total_devices.toLocaleString(), color: '#94A3B8' }, { label: 'Compliant', value: stats.compliant.toLocaleString(), color: '#10B981' }, { label: 'Non-Compliant', value: stats.non_compliant.toLocaleString(), color: '#EF4444' }, { label: 'Current %', value: `${stats.compliance_pct}%`, color: stats.compliance_pct >= stats.target_pct ? '#10B981' : '#F59E0B' }, { label: 'Target %', value: `${stats.target_pct}%`, color: PURPLE }, ]; return (
{items.map(({ label, value, color }) => (
{label}
{value}
))}
); } // --------------------------------------------------------------------------- // Donut Chart // --------------------------------------------------------------------------- function DonutChart({ donut }) { if (!donut) return null; const data = [ { name: 'Blocked', count: donut.blocked.count, color: '#EF4444' }, { name: 'In-Progress', count: donut.in_progress.count, color: '#F59E0B' }, ]; const total = donut.blocked.count + donut.in_progress.count; return (
Non-Compliant Status
{data.map((entry, i) => )}
{total}
Total Non-Compliant
Blocked: {donut.blocked.count} ({donut.blocked.pct}%)
In-Progress: {donut.in_progress.count} ({donut.in_progress.pct}%)
); } // --------------------------------------------------------------------------- // Trend Chart // --------------------------------------------------------------------------- function TrendChart({ months }) { if (!months || months.length === 0) return (
No trend data yet. Upload compliance data to generate trends.
); return (
Compliance Trend
); } // --------------------------------------------------------------------------- // Vertical Breakdown Table // --------------------------------------------------------------------------- function VerticalTable({ breakdown, onSelectVertical }) { if (!breakdown || breakdown.length === 0) return null; return (
Vertical Breakdown
{breakdown.map(v => { const pctColor = v.compliance_pct >= 95 ? '#10B981' : v.compliance_pct >= 80 ? '#F59E0B' : '#EF4444'; return ( onSelectVertical(v.vertical)} style={{ cursor: 'pointer', transition: 'background 0.15s' }} onMouseEnter={e => e.currentTarget.style.background = 'rgba(167, 139, 250, 0.08)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'} > ); })}
Vertical Total Compliant Non-Compliant Compliance % Blockers Last Upload
{v.vertical} {v.total_devices.toLocaleString()} {v.compliant.toLocaleString()} {v.non_compliant.toLocaleString()} {v.compliance_pct}% 0 ? '#EF4444' : '#64748B' }}>{v.blockers} {v.last_upload || '—'}
); } // --------------------------------------------------------------------------- // Vertical Detail View (metric drill-down) // --------------------------------------------------------------------------- function VerticalDetailView({ vertical, onBack, onSelectMetric }) { const [metrics, setMetrics] = useState(null); const [categories, setCategories] = useState(null); const [burndown, setBurndown] = useState(null); const [loading, setLoading] = useState(true); // ⚠️ CONVENTION: No error state — catch silently swallows errors without displaying them to the user useEffect(() => { setLoading(true); Promise.all([ fetch(`${API_BASE}/compliance/vcl-multi/vertical/${encodeURIComponent(vertical)}/metrics`, { credentials: 'include' }).then(r => r.json()), fetch(`${API_BASE}/compliance/vcl-multi/vertical/${encodeURIComponent(vertical)}/burndown`, { credentials: 'include' }).then(r => r.json()), ]).then(([metricsData, burndownData]) => { setMetrics(metricsData.metrics || []); setCategories(metricsData.categories || []); setBurndown(burndownData); setLoading(false); }).catch(() => setLoading(false)); }, [vertical]); if (loading) return
Loading...
; return (

{vertical}

{/* Burndown summary */} {burndown && (
Non-Compliant
{burndown.total}
With Dates
{burndown.with_dates}
Blockers
{burndown.blockers}
{burndown.projected_clear_date && (
Projected Clear
{burndown.projected_clear_date}
)}
)} {/* Burndown chart */} {burndown && burndown.monthly && Object.keys(burndown.monthly).length > 0 && (
Burndown Forecast
a.localeCompare(b)).map(([month, count]) => ({ month, count }))}>
)} {/* Category summary */} {categories && categories.length > 0 && (
By Category
{categories.map(c => (
{c.category}
= 95 ? '#10B981' : c.compliance_pct >= 80 ? '#F59E0B' : '#EF4444' }}> {c.compliance_pct}%
{c.non_compliant} non-compliant
))}
)} {/* Metrics table */}
Metrics
{metrics && metrics.map((m, i) => { const pctColor = m.compliance_pct >= m.target ? '#10B981' : m.compliance_pct >= (m.target * 0.85) ? '#F59E0B' : '#EF4444'; return ( onSelectMetric(m.metric_id)} style={{ cursor: 'pointer', transition: 'background 0.15s' }} onMouseEnter={e => e.currentTarget.style.background = 'rgba(167, 139, 250, 0.06)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'} > ); })}
Metric Description Category Compliant Non-Compliant Total % Target
{m.metric_id} {m.metric_desc} {m.category} {m.compliant} {m.non_compliant} {m.total} {Number(m.compliance_pct).toFixed(1)}% {Number(m.target).toFixed(0)}%
); } // --------------------------------------------------------------------------- // Metric Device List (deepest drill-down) // --------------------------------------------------------------------------- function MetricDeviceList({ vertical, metricId, onBack }) { const [devices, setDevices] = useState(null); const [loading, setLoading] = useState(true); // ⚠️ CONVENTION: No error state — catch silently swallows errors without displaying them to the user useEffect(() => { setLoading(true); fetch(`${API_BASE}/compliance/vcl-multi/vertical/${encodeURIComponent(vertical)}/metric/${encodeURIComponent(metricId)}/devices`, { credentials: 'include' }) .then(r => r.json()) .then(data => { setDevices(data.devices || []); setLoading(false); }) .catch(() => setLoading(false)); }, [vertical, metricId]); if (loading) return
Loading...
; return (

{vertical} / Metric {metricId} — {devices ? devices.length : 0} non-compliant devices

{devices && devices.map((d, i) => ( ))} {devices && devices.length === 0 && ( )}
Hostname IP Address Type Team Seen Count First Seen Last Seen Resolution Date Remediation Plan
{d.hostname} {d.ip_address || '—'} {d.device_type || '—'} {d.team || '—'} {d.seen_count} {d.first_seen || '—'} {d.last_seen || '—'} {d.resolution_date || 'Not set'} {d.remediation_plan || '—'}
No devices found
); } // --------------------------------------------------------------------------- // Main Page Component // --------------------------------------------------------------------------- export default function CCPMetricsPage() { const { isAdmin, isEditor } = useAuth(); const [stats, setStats] = useState(null); const [trend, setTrend] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [showUpload, setShowUpload] = useState(false); // Drill-down state const [selectedVertical, setSelectedVertical] = useState(null); const [selectedMetric, setSelectedMetric] = useState(null); const fetchData = useCallback(() => { setLoading(true); setError(null); Promise.all([ fetch(`${API_BASE}/compliance/vcl-multi/stats`, { credentials: 'include' }).then(r => { if (!r.ok) throw new Error('Failed to load stats'); return r.json(); }), fetch(`${API_BASE}/compliance/vcl-multi/trend`, { credentials: 'include' }).then(r => { if (!r.ok) throw new Error('Failed to load trend'); return r.json(); }), ]).then(([statsData, trendData]) => { setStats(statsData); setTrend(trendData); setLoading(false); }).catch(err => { setError(err.message); setLoading(false); }); }, []); useEffect(() => { fetchData(); }, [fetchData]); const handleUploadComplete = () => { setShowUpload(false); fetchData(); }; // Render drill-down views if (selectedMetric && selectedVertical) { return (
setSelectedMetric(null)} />
); } if (selectedVertical) { return (
setSelectedVertical(null)} onSelectMetric={(metricId) => setSelectedMetric(metricId)} />
); } // Main overview return (
{/* Header */}

CCP Metrics — Multi-Vertical VCL

Cross-organizational compliance posture across all verticals

{(isAdmin() || isEditor()) && ( )}
{/* Loading / Error states */} {loading && (
Loading compliance data...
)} {error && (
{error}
)} {!loading && !error && stats && ( <> {/* Stats bar */} {/* Charts row */}
{/* Vertical breakdown table */} {/* Last upload info */} {stats.last_upload_date && (
Last upload: {stats.last_upload_date}
)} )} {!loading && !error && (!stats || !stats.vertical_breakdown || stats.vertical_breakdown.length === 0) && (
No multi-vertical data yet
Upload per-vertical compliance xlsx files to generate cross-organizational reports.
{(isAdmin() || isEditor()) && ( )}
)} {/* Upload Modal */} {showUpload && ( setShowUpload(false)} onUploadComplete={handleUploadComplete} /> )}
); }