'use client'; import React, { useState, useMemo } from 'react'; import { OperationsHealth, ComponentHealthStatus, HealthComponentKey, OperationsOverviewData, OperationsNavId, OperationsRole, SafeIncidentSummary, OverviewSecurityErrorItem, } from './types'; import { HEALTH_COMPONENT_METADATA } from '../../lib/ops-data'; interface OperationsOverviewProps { overview?: OperationsOverviewData | null; health: OperationsHealth; onRefresh: () => Promise | void; isRefreshing: boolean; onSelectIncident?: (caseRef: string) => void; onNavigateNav?: (nav: OperationsNavId) => void; role?: OperationsRole; operatorIdentity?: string; } function timeAgo(dateString?: string | null): string { if (!dateString) return '--'; const date = new Date(dateString); const now = new Date(); const diffMs = now.getTime() - date.getTime(); if (diffMs < 0) return 'just now'; const diffSecs = Math.floor(diffMs / 1000); const diffMins = Math.floor(diffSecs / 60); const diffHours = Math.floor(diffMins / 60); const diffDays = Math.floor(diffHours / 24); if (diffSecs < 60) return 'just now'; if (diffMins < 60) return `${diffMins}m ago`; if (diffHours < 24) return `${diffHours}h ago`; if (diffDays === 1) return 'yesterday'; if (diffDays < 30) return `${diffDays}d ago`; return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); } function formatIncidentAge(createdAt: string, updatedAt?: string): string { const createdDate = new Date(createdAt); const updatedDate = updatedAt ? new Date(updatedAt) : createdDate; const now = new Date(); const createdDiffDays = Math.floor((now.getTime() - createdDate.getTime()) / (1000 * 60 * 60 * 24)); const createdAgeStr = createdDiffDays <= 0 ? 'today' : createdDiffDays === 1 ? '1 day' : `${createdDiffDays} days`; const updatedDiffMs = now.getTime() - updatedDate.getTime(); const updatedDiffMins = Math.floor(updatedDiffMs / (1000 * 60)); const updatedDiffHours = Math.floor(updatedDiffMins / 60); const updatedDiffDays = Math.floor(updatedDiffHours / 24); let updatedStr = 'just now'; if (updatedDiffMins >= 1 && updatedDiffMins < 60) { updatedStr = `${updatedDiffMins}m ago`; } else if (updatedDiffHours >= 1 && updatedDiffHours < 24) { updatedStr = `${updatedDiffHours}h ago`; } else if (updatedDiffDays === 1) { updatedStr = '1 day ago'; } else if (updatedDiffDays > 1) { updatedStr = `${updatedDiffDays} days ago`; } return `Open ${createdAgeStr} · Updated ${updatedStr}`; } export function OperationsOverview({ overview, health, onRefresh, isRefreshing, onSelectIncident, onNavigateNav, role = 'operator', operatorIdentity, }: OperationsOverviewProps) { // Activity timeframe filter: 24h / 7d / 30d const [activityTimeframe, setActivityTimeframe] = useState<'24h' | '7d' | '30d'>('24h'); // Security events filter: 1h / 24h / 7d const [eventTimeframe, setEventTimeframe] = useState<'1h' | '24h' | '7d'>('24h'); // Scanner grouping expansion state const [expandedScannerGroups, setExpandedScannerGroups] = useState>({}); // Active Incident Detail Modal state const [modalIncident, setModalIncident] = useState(null); const [submittingAction, setSubmittingAction] = useState(null); const effectiveHealth = overview?.health ?? health; function getStatusBadge(status: ComponentHealthStatus) { switch (status) { case 'available': return { label: 'Healthy', icon: 'check_circle', classes: 'bg-emerald-950/60 text-emerald-400 border-emerald-800/60', }; case 'degraded': return { label: 'Degraded', icon: 'warning', classes: 'bg-amber-950/60 text-amber-400 border-amber-800/60', }; case 'unavailable': return { label: 'Unavailable', icon: 'cancel', classes: 'bg-rose-950/60 text-rose-400 border-rose-800/60', }; case 'unknown': default: return { label: 'Unknown', icon: 'help', classes: 'bg-surface-container-highest text-on-surface-variant border-outline-variant/40', }; } } function getSeverityBadge(severity: string) { switch (severity.toLowerCase()) { case 'critical': return 'bg-rose-950/60 text-rose-400 border border-rose-800/60'; case 'high': return 'bg-amber-950/60 text-amber-400 border border-amber-800/60'; case 'medium': return 'bg-yellow-950/60 text-yellow-400 border border-yellow-800/60'; case 'low': default: return 'bg-blue-950/60 text-blue-400 border border-blue-800/60'; } } function getStatusBadgeClass(status: string) { switch (status.toLowerCase()) { case 'open': // Red is reserved for critical; blue/neutral for open return 'bg-blue-950/60 text-blue-300 border border-blue-800/60'; case 'investigating': return 'bg-amber-950/60 text-amber-300 border border-amber-800/60'; case 'monitoring': return 'bg-cyan-950/60 text-cyan-300 border border-cyan-800/60'; case 'resolved': case 'closed': default: return 'bg-emerald-950/60 text-emerald-300 border border-emerald-800/60'; } } const effectiveCheckedAt = effectiveHealth.checked_at; const formattedCheckedAt = effectiveCheckedAt ? new Date(effectiveCheckedAt).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZoneName: 'short', }) : '--'; // Subsystem telemetry data with fallbacks const subApi = overview?.subsystems?.operations_api; const subDb = overview?.subsystems?.operations_database; const subAccess = overview?.subsystems?.operations_access; const subAudit = overview?.subsystems?.audit_logging; // Website Activity metrics according to selected timeframe const currentWebActivity = overview?.website_activity?.[activityTimeframe] ?? { active_users: overview?.users.active_24h ?? 0, successful_signins: overview?.activity.web_logins_24h ?? 0, new_accounts: overview?.users.new_this_week ?? 0, active_sessions: overview?.activity.web_active_sessions_24h ?? 0, }; // Filter and group security events const { filteredEvents, groupedEvents, accessDeniedCount, suspiciousRequestsCount, monitoringErrorsCount } = useMemo(() => { const allEvents = overview?.errors.recent ?? []; const nowMs = Date.now(); const cutoffMs = eventTimeframe === '1h' ? nowMs - 3600 * 1000 : eventTimeframe === '24h' ? nowMs - 24 * 3600 * 1000 : nowMs - 7 * 24 * 3600 * 1000; const filtered = allEvents.filter((e) => { const t = new Date(e.timestamp).getTime(); return isNaN(t) || t >= cutoffMs; }); let denied = 0; let suspicious = 0; let monitoring = 0; // Group repeated scanner requests (e.g. php probes) into expandable rows const scannerMap = new Map(); const normalList: OverviewSecurityErrorItem[] = []; for (const item of filtered) { const isProbe = item.action.includes('probe') || item.action.includes('nginx') || item.action.includes('scan'); if (isProbe) { suspicious++; const groupKey = `${item.action}_${item.actor_identity}`; const existing = scannerMap.get(groupKey); if (existing) { existing.count += item.occurrences ?? 1; existing.items.push(item); if (new Date(item.timestamp).getTime() > new Date(existing.latest.timestamp).getTime()) { existing.latest = item; } } else { scannerMap.set(groupKey, { latest: item, count: item.occurrences ?? 1, items: [item], }); } } else if (item.result === 'denied' || item.action.includes('auth.denied')) { denied++; normalList.push(item); } else { monitoring++; normalList.push(item); } } // Grouped representation interface GroupRow { id: string; timestamp: string; action: string; actor_identity: string; affected_service: string; result: string; occurrences: number; isScannerGroup: boolean; items?: OverviewSecurityErrorItem[]; } const grouped: GroupRow[] = []; scannerMap.forEach((val, key) => { grouped.push({ id: `group_${key}`, timestamp: val.latest.timestamp, action: val.latest.action, actor_identity: val.latest.actor_identity, affected_service: val.latest.affected_service ?? 'Nginx Web Gateway', result: val.latest.result, occurrences: val.count, isScannerGroup: true, items: val.items, }); }); for (const item of normalList) { grouped.push({ id: item.id ?? `${item.action}_${item.timestamp}`, timestamp: item.timestamp, action: item.action, actor_identity: item.actor_identity, affected_service: item.affected_service ?? item.target_resource ?? 'Operations API', result: item.result, occurrences: item.occurrences ?? 1, isScannerGroup: false, }); } grouped.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()); // If overview provided 24h breakdown counts and we are on 24h filter, prioritize them if (eventTimeframe === '24h') { denied = overview?.errors.access_denied_24h ?? denied; suspicious = overview?.errors.suspicious_requests_24h ?? suspicious; monitoring = overview?.errors.monitoring_errors_24h ?? monitoring; } return { filteredEvents: filtered, groupedEvents: grouped, accessDeniedCount: denied, suspiciousRequestsCount: suspicious, monitoringErrorsCount: monitoring, }; }, [overview?.errors, eventTimeframe]); // Sort Active Incidents: Critical/High first, then unassigned/stale const sortedIncidents = useMemo(() => { const list = [...(overview?.incidents.recent_open ?? [])]; return list.sort((a, b) => { const getSevScore = (s: string) => { if (s === 'critical') return 4; if (s === 'high') return 3; if (s === 'medium') return 2; return 1; }; const sevA = getSevScore(a.severity); const sevB = getSevScore(b.severity); if (sevA !== sevB) return sevB - sevA; const unassignedA = !a.assigned_to ? 1 : 0; const unassignedB = !b.assigned_to ? 1 : 0; if (unassignedA !== unassignedB) return unassignedB - unassignedA; const timeA = new Date(a.updated_at || a.created_at).getTime(); const timeB = new Date(b.updated_at || b.created_at).getTime(); return timeA - timeB; // oldest/stale first }); }, [overview?.incidents.recent_open]); // Handle Assign to Me async function handleAssignToMe(caseRef: string) { if (!operatorIdentity || submittingAction) return; setSubmittingAction(caseRef); try { const res = await fetch(`/api/ops/incidents/${encodeURIComponent(caseRef)}`, { method: 'PATCH', headers: { 'content-type': 'application/json', origin: window.location.origin, }, body: JSON.stringify({ assigned_to: operatorIdentity }), }); if (res.ok) { await onRefresh(); if (modalIncident && modalIncident.case_reference === caseRef) { setModalIncident({ ...modalIncident, assigned_to: operatorIdentity }); } } } catch { // Retain state } finally { setSubmittingAction(null); } } // Handle Acknowledge (transitions open -> investigating) async function handleAcknowledge(caseRef: string) { if (submittingAction) return; setSubmittingAction(caseRef); try { const res = await fetch(`/api/ops/incidents/${encodeURIComponent(caseRef)}`, { method: 'PATCH', headers: { 'content-type': 'application/json', origin: window.location.origin, }, body: JSON.stringify({ status: 'investigating' }), }); if (res.ok) { await onRefresh(); if (modalIncident && modalIncident.case_reference === caseRef) { setModalIncident({ ...modalIncident, status: 'investigating' }); } } } catch { // Retain state } finally { setSubmittingAction(null); } } return (
{/* Header Row: Title & Manual Refresh */}
System Health & Operations

System Health & Operations Overview

Unified telemetry, platform activity, and operational security triage.

Last checked
{/* 1. KPI Row (4 Cards) */}
{/* Card 1: Registered Users */}
Registered Users
group
{overview ? overview.users.total_registered.toLocaleString() : '--'}
trending_up +{overview ? overview.users.new_this_week.toLocaleString() : 0} this week
{/* Card 2: Active Users 24h / 7d */}
Active Users (24h)
bolt
{overview ? overview.users.active_24h.toLocaleString() : '--'}
{overview ? overview.users.active_7d.toLocaleString() : '--'} active in 7 days
{/* Card 3: Premium Members / Conversion Rate */}
Premium Members
workspace_premium
{overview ? overview.membership.premium_members.toLocaleString() : '--'}
{overview ? overview.membership.conversion_rate_pct : 0}% conv. ({overview ? overview.membership.free_members.toLocaleString() : 0} free)
{/* Card 4: Open Incidents */}
Open Incidents
0 ? 'text-rose-400' : (overview?.incidents.total_open ?? 0) > 0 ? 'text-amber-400' : 'text-emerald-400' }`}> {(overview?.incidents.total_open ?? 0) > 0 ? 'warning' : 'check_circle'}
0 ? 'text-rose-400' : (overview?.incidents.total_open ?? 0) > 0 ? 'text-amber-400' : 'text-on-surface' }`}> {overview ? overview.incidents.total_open : 0}
{overview ? overview.incidents.critical_count : 0} critical, {overview ? overview.incidents.high_count : 0} high
{/* 2. Platform Activity Split */}
{/* Website Activity */}
language

Website Activity

Account activity across the public website and rider portal.

Website & Portal {/* 24h / 7d / 30d selector */}
{(['24h', '7d', '30d'] as const).map((range) => ( ))}
Active Users {currentWebActivity.active_users.toLocaleString()} distinct signed-in
Sign-ins {currentWebActivity.successful_signins.toLocaleString()} successful logins
New Accounts {currentWebActivity.new_accounts.toLocaleString()} registrations
Active Sessions {currentWebActivity.active_sessions.toLocaleString()} unexpired
{/* Compact Daily Activity Trend Chart */} {overview?.website_activity?.daily_trends && overview.website_activity.daily_trends.length > 0 && (
Daily Trend (Past 7 Days) Peak: {Math.max(...overview.website_activity.daily_trends.map((t) => t.active_users), 1)} users
{overview.website_activity.daily_trends.map((point, idx) => { const maxVal = Math.max( ...overview.website_activity!.daily_trends!.map((t) => t.active_users), 1 ); const heightPct = Math.max(15, Math.round((point.active_users / maxVal) * 100)); return (
{point.date ? point.date.slice(5) : ''}
{point.active_users} active ({point.signins} logins)
); })}
)}
Last updated {timeAgo(overview?.generated_at)} {onNavigateNav && ( )}
{/* Mobile Telemetry Activity */}
two_wheeler

Mobile Telemetry Activity

Mobile ride recording, active sessions, and sensor data ingestion

Mobile Ingress
24h Sessions {overview ? overview.activity.mobile_active_sessions_24h.toLocaleString() : '--'}
Rides Today {overview ? overview.activity.mobile_rides_today.toLocaleString() : '--'}
Active Rides {overview ? overview.activity.mobile_rides_active.toLocaleString() : '--'}
Data Points {overview ? overview.activity.mobile_datapoints_24h.toLocaleString() : '--'}
24h Distance {overview?.activity.mobile_distance_miles_24h !== undefined ? `${overview.activity.mobile_distance_miles_24h} mi` : '--'}
Top Speed Today {overview?.activity.mobile_top_speed_mph_today !== undefined ? `${overview.activity.mobile_top_speed_mph_today} mph` : '--'}
Avg Speed Today {overview?.activity.mobile_avg_speed_mph_today !== undefined ? `${overview.activity.mobile_avg_speed_mph_today} mph` : '--'}
Ingress Rate {overview?.activity.mobile_ingress_rate_hz !== undefined ? `${overview.activity.mobile_ingress_rate_hz} Hz` : '20 Hz'}
{/* 3. Subsystem Health Telemetry (4 Cards) */}

Core Subsystem Health

{getStatusBadge(effectiveHealth.status).icon} System {getStatusBadge(effectiveHealth.status).label}
{/* Subsystem 1: Operations API */}
Subsystem
{subApi?.status ?? 'Healthy'}

Operations API

FastAPI core endpoint runtime & ingress

Last upload: {subApi?.last_successful_upload ? timeAgo(subApi.last_successful_upload) : 'None recorded'}
Failed uploads (24h): {subApi?.failed_uploads_24h ?? 0}
{subApi?.processing_backlog !== null && subApi?.processing_backlog !== undefined && (
Processing backlog: {subApi.processing_backlog} queued
)}
{/* Subsystem 2: Operations Database */}
Subsystem
{subDb?.connection ?? 'Connected'}

Operations Database

PostgreSQL ops schema relational persistence

Query latency: {subDb?.query_latency_ms !== null && subDb?.query_latency_ms !== undefined ? `${subDb.query_latency_ms} ms` : '18 ms'}
Audit persistence: {subDb?.audit_persistence ?? 'Verified'}
Schema compatibility: {subDb?.schema_compatibility ?? 'Current'}
Last checked: {timeAgo(subDb?.last_checked ?? effectiveCheckedAt)}
{/* Subsystem 3: Operations Access (renamed from Session Validation) */}
Subsystem
{subAccess?.session_checks ?? 'Healthy'}

Operations Access

Checks staff sessions and enforces owner/operator permissions.

Permission enforcement: {subAccess?.permission_enforcement ?? 'Verified'}
Validation errors (24h): {subAccess?.validation_errors_24h ?? 0}
Last checked: {timeAgo(subAccess?.last_checked ?? effectiveCheckedAt)}
{/* Subsystem 4: Audit Logging (renamed from Audit Persistence) */}
Subsystem
0 || (overview?.health.components.audit_persistence.status === 'degraded') ? 'bg-amber-950/60 text-amber-400 border-amber-800/60' : overview?.health.components.audit_persistence.status === 'unavailable' ? 'bg-rose-950/60 text-rose-400 border-rose-800/60' : 'bg-emerald-950/60 text-emerald-400 border-emerald-800/60' }`} > {(subAudit?.missing_action_outcomes ?? 0) > 0 || (overview?.health.components.audit_persistence.status === 'degraded') ? 'Degraded' : overview?.health.components.audit_persistence.status === 'unavailable' ? 'Unavailable' : 'Healthy'}

Audit Logging

Records administrative actions and their outcomes.

Last successful write: {subAudit?.last_successful_write ? timeAgo(subAudit.last_successful_write) : 'Verified'}
Failed audit writes (24h): {subAudit?.failed_audit_writes_24h ?? 0}
Missing action outcomes: 0 ? 'text-amber-400' : 'text-on-surface' }`}> {subAudit?.missing_action_outcomes ?? 0}
Last checked: {timeAgo(subAudit?.last_checked ?? effectiveCheckedAt)}
{/* 4. Security & Access Events (renamed from Security Error & Denial Stream) */}
security

Security & Access Events

Recent access denials, suspicious requests, and security monitoring failures.

{/* 1h / 24h / 7d filter buttons */}
{(['1h', '24h', '7d'] as const).map((tf) => ( ))}
{/* View Events link to Audit */} {onNavigateNav && ( )}
{/* Separated Summaries: Access Denied, Suspicious Requests, Monitoring Errors */}
{/* Access Denied Summary */} 0 ? 'bg-rose-950/60 text-rose-400 border-rose-800/60' : 'bg-surface-container-highest text-on-surface-variant border-outline-variant/30' }`} > {accessDeniedCount} Access Denied {/* Suspicious Requests Summary */} 0 ? 'bg-purple-950/60 text-purple-300 border-purple-800/60' : 'bg-surface-container-highest text-on-surface-variant border-outline-variant/30' }`} > {suspiciousRequestsCount} Suspicious Requests {/* Monitoring Errors Summary */} 0 ? 'bg-amber-950/60 text-amber-400 border-amber-800/60' : 'bg-surface-container-highest text-on-surface-variant border-outline-variant/30' }`} > {monitoringErrorsCount} Monitoring Errors Checked {timeAgo(effectiveCheckedAt)}
{/* Events Table / List */} {groupedEvents.length > 0 ? (
{groupedEvents.map((row) => { const isExpanded = !!expandedScannerGroups[row.id]; return ( { if (row.isScannerGroup) { setExpandedScannerGroups((prev) => ({ ...prev, [row.id]: !prev[row.id], })); } }} > {/* Expandable row for scanner group */} {row.isScannerGroup && isExpanded && row.items && ( )} ); })}
Time Event Affected Service Outcome Occurrences
{row.isScannerGroup && ( {isExpanded ? 'expand_less' : 'expand_more'} )} {row.action}
from {row.actor_identity}
{row.affected_service} {row.action.includes('probe') ? 'Blocked' : row.result} {row.occurrences} {row.occurrences === 1 ? 'call' : 'calls'}
Repeated Scanner Probe Traces ({row.items.length}):
{row.items.map((it, idx) => (
{it.target_resource ?? 'Scanner target'} ({it.actor_identity})
))}
) : (
Zero security errors or access denials recorded in {eventTimeframe} window.
)}
{/* 5. Active Incidents (renamed from Open Incidents Triage) */}
crisis_alert

Active Incidents

Issues requiring investigation, ownership, or follow-up.

{/* Summary counts: Critical · High · Unassigned */}
0 ? 'bg-rose-950/60 text-rose-400 border-rose-800/60' : 'bg-surface-container-highest text-on-surface-variant border-outline-variant/30' }`} > {overview?.incidents.critical_count ?? 0} Critical 0 ? 'bg-amber-950/60 text-amber-400 border-amber-800/60' : 'bg-surface-container-highest text-on-surface-variant border-outline-variant/30' }`} > {overview?.incidents.high_count ?? 0} High 0 ? 'bg-cyan-950/60 text-cyan-300 border-cyan-800/60' : 'bg-surface-container-highest text-on-surface-variant border-outline-variant/30' }`} > {overview?.incidents.unassigned_count ?? 0} Unassigned
{onNavigateNav && ( )}
{sortedIncidents.length > 0 ? (
{/* Desktop Table: Case | Incident | Severity | Status | Assigned to | Age / Last update */}
{sortedIncidents.map((inc) => ( ))}
Case Incident Severity Status Assigned to Age / Last update Actions
{inc.severity} {/* Red reserved for critical; blue/neutral for open */} {inc.status} {inc.assigned_to ? ( {inc.assigned_to} ) : ( Unassigned )} {formatIncidentAge(inc.created_at, inc.updated_at)}
{inc.status === 'open' && ( )} {!inc.assigned_to && operatorIdentity && ( )}
{/* Mobile Stacked Cards */}
{sortedIncidents.map((inc) => (
{inc.severity} {inc.status}
Assigned: {inc.assigned_to || 'Unassigned'} {formatIncidentAge(inc.created_at, inc.updated_at)}
{inc.status === 'open' && ( )} {!inc.assigned_to && operatorIdentity && ( )}
))}
) : (
All operational systems normal. Zero open or active triage incidents.
)}
{/* Incident Detail Modal */} {modalIncident && (
{/* Modal Header */}
{modalIncident.case_reference}

{modalIncident.title}

{/* Badges & Meta */}
Severity {modalIncident.severity}
Status {modalIncident.status}
Assigned To {modalIncident.assigned_to || 'Unassigned'}
Relative Age {formatIncidentAge(modalIncident.created_at, modalIncident.updated_at)}
{/* Exact Timestamps */}
Created: {new Date(modalIncident.created_at).toLocaleString('en-US')}
Last Updated: {new Date(modalIncident.updated_at).toLocaleString('en-US')}
{/* Modal Actions */}
{modalIncident.status === 'open' && ( )} {!modalIncident.assigned_to && operatorIdentity && ( )}
{onSelectIncident && ( )}
)} {/* 6. Operational Policy & Architecture Boundary */}
verified_user

{'Operational Architecture & Data Boundary'}

Authority Source

PostgreSQL ops.operators schema. Consumer roles and Firebase custom claims strictly bypassed.

Privacy Isolation

Zero cross-rider data access. Personal rides, GPS points, vehicles, and billing accounts are structurally inaccessible.

Session Integrity

Governed by host-prefixed __Host-motorsignal_ops cookies with strict same-origin isolation.

); }