All files / src/components/features/admin/monitoring/SLOTrend index.tsx

83.33% Statements 280/336
85.71% Branches 18/21
40% Functions 2/5
83.33% Lines 280/336

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 3371x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x           1x 1x 1x 1x                         1x 1x 1x 1x                                                                           1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 55x 55x 13x 13x 13x 13x 13x 13x 11x 11x 11x 11x 11x 11x 11x 13x 13x 13x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 13x 4x 4x 4x 4x 4x 4x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 13x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 13x 13x 13x 13x 13x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 13x 13x 13x 13x 1x 1x  
'use client';
 
import React, { useMemo } from 'react';
import {
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ReferenceLine,
  ResponsiveContainer,
  Area,
  ComposedChart,
} from 'recharts';
 
/**
 * Data point for trend chart
 */
export interface TrendDataPoint {
  timestamp: string;
  value: number;
  status: string;
}
 
/**
 * Summary statistics
 */
export interface TrendSummary {
  avgValue: number;
  minValue: number;
  maxValue: number;
  breachCount: number;
  uptimePercentage: number;
  dataPointCount: number;
}
 
export interface SLOTrendProps {
  /** SLO name for display */
  sloName: string;
  /** Target percentage */
  target: number;
  /** Trend data points */
  data: TrendDataPoint[];
  /** Summary statistics */
  summary?: TrendSummary;
  /** Time range label */
  periodLabel?: string;
  /** Show area fill under the line */
  showArea?: boolean;
  /** Chart height */
  height?: number;
  /** Loading state */
  isLoading?: boolean;
  /** Compact mode (hides summary) */
  compact?: boolean;
  /** Additional CSS classes */
  className?: string;
}
 
/**
 * Format timestamp for display
 */
function formatTimestamp(timestamp: string, showTime: boolean = true): string {
  const date = new Date(timestamp);
  if (showTime) {
    return date.toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  }
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
  });
}
 
/**
 * Get status color
 */
function getStatusColor(status: string): string {
  switch (status) {
    case 'healthy':
      return '#22c55e'; // green-500
    case 'warning':
      return '#eab308'; // yellow-500
    case 'critical':
      return '#ef4444'; // red-500
    default:
      return '#6b7280'; // gray-500
  }
}
 
/**
 * Custom tooltip component
 */
function CustomTooltip({
  active,
  payload,
  label,
  target,
}: {
  active?: boolean;
  payload?: Array<{ value: number; payload: TrendDataPoint }>;
  label?: string;
  target: number;
}) {
  if (!active || !payload || !payload.length) return null;

  const data = payload[0];
  const value = data.value;
  const status = data.payload.status;
  const isMeetingTarget = value >= target;

  return (
    <div className="bg-white dark:bg-gray-800 p-3 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700">
      <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">
        {formatTimestamp(label || '')}
      </p>
      <p className="text-lg font-bold" style={{ color: getStatusColor(status) }}>
        {value.toFixed(2)}%
      </p>
      <p className="text-xs text-gray-500 dark:text-gray-400">
        Target: {target}%
        {isMeetingTarget ? (
          <span className="ml-2 text-green-500">Meeting target</span>
        ) : (
          <span className="ml-2 text-red-500">Below target</span>
        )}
      </p>
    </div>
  );
}
 
/**
 * SLOTrend Component
 *
 * Displays historical SLO performance as a line chart with target reference line.
 */
export function SLOTrend({
  sloName,
  target,
  data,
  summary,
  periodLabel = 'Last 7 Days',
  showArea = true,
  height = 300,
  isLoading = false,
  compact = false,
  className = '',
}: SLOTrendProps) {
  // Prepare chart data
  const chartData = useMemo(() => {
    return data.map((point) => ({
      ...point,
      formattedTime: formatTimestamp(point.timestamp, data.length <= 48),
    }));
  }, [data]);
 
  // Calculate y-axis domain
  const yDomain = useMemo(() => {
    if (data.length === 0) return [95, 100];
    const values = data.map((d) => d.value);
    const min = Math.min(...values, target);
    const max = Math.max(...values);
    // Round down min and up max to nice values
    const roundedMin = Math.floor(min - 1);
    const roundedMax = Math.ceil(max + 0.5);
    return [Math.max(0, roundedMin), Math.min(100, roundedMax)];
  }, [data, target]);
 
  if (isLoading) {
    return (
      <div
        className={`bg-white dark:bg-gray-800 rounded-lg shadow p-4 ${className}`}
        data-testid="slo-trend"
      >
        <div className="h-6 w-48 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-4" />
        <div
          className="bg-gray-200 dark:bg-gray-700 rounded animate-pulse"
          style={{ height: `${height}px` }}
        />
      </div>
    );
  }
 
  return (
    <div
      className={`bg-white dark:bg-gray-800 rounded-lg shadow ${className}`}
      data-testid="slo-trend"
    >
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
              {sloName}
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Target: {target}% | {periodLabel}
            </p>
          </div>
          {summary && !compact && (
            <div className="text-right">
              <p className="text-2xl font-bold text-gray-900 dark:text-white">
                {summary.avgValue.toFixed(2)}%
              </p>
              <p className="text-xs text-gray-500 dark:text-gray-400">Average</p>
            </div>
          )}
        </div>
      </div>
 
      {/* Chart */}
      <div className="p-4" style={{ height: `${height}px` }}>
        {data.length === 0 ? (
          <div className="flex items-center justify-center h-full text-gray-500 dark:text-gray-400">
            No historical data available
          </div>
        ) : (
          <ResponsiveContainer width="100%" height="100%">
            <ComposedChart data={chartData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-gray-200 dark:stroke-gray-700" />
              <XAxis
                dataKey="formattedTime"
                tick={{ fontSize: 11 }}
                tickLine={false}
                axisLine={false}
                className="text-gray-500 dark:text-gray-400"
                interval="preserveStartEnd"
              />
              <YAxis
                domain={yDomain}
                tick={{ fontSize: 11 }}
                tickLine={false}
                axisLine={false}
                className="text-gray-500 dark:text-gray-400"
                tickFormatter={(v) => `${v}%`}
              />
              <Tooltip content={<CustomTooltip target={target} />} />
              <ReferenceLine
                y={target}
                stroke="#ef4444"
                strokeDasharray="5 5"
                strokeWidth={2}
                label={{
                  value: `Target: ${target}%`,
                  position: 'right',
                  fontSize: 11,
                  fill: '#ef4444',
                }}
              />
              {showArea && (
                <Area
                  type="monotone"
                  dataKey="value"
                  fill="url(#colorGradient)"
                  stroke="none"
                />
              )}
              <Line
                type="monotone"
                dataKey="value"
                stroke="#3b82f6"
                strokeWidth={2}
                dot={false}
                activeDot={{ r: 6, fill: '#3b82f6' }}
              />
              <defs>
                <linearGradient id="colorGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
                  <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                </linearGradient>
              </defs>
            </ComposedChart>
          </ResponsiveContainer>
        )}
      </div>
 
      {/* Summary stats */}
      {summary && !compact && (
        <div className="px-4 pb-4">
          <div className="grid grid-cols-4 gap-4 p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">Min</p>
              <p
                className={`text-lg font-semibold ${
                  summary.minValue >= target
                    ? 'text-green-600 dark:text-green-400'
                    : 'text-red-600 dark:text-red-400'
                }`}
              >
                {summary.minValue.toFixed(2)}%
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">Max</p>
              <p className="text-lg font-semibold text-green-600 dark:text-green-400">
                {summary.maxValue.toFixed(2)}%
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">Breaches</p>
              <p
                className={`text-lg font-semibold ${
                  summary.breachCount === 0
                    ? 'text-green-600 dark:text-green-400'
                    : 'text-red-600 dark:text-red-400'
                }`}
              >
                {summary.breachCount}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">SLO Compliance</p>
              <p
                className={`text-lg font-semibold ${
                  summary.uptimePercentage >= 99
                    ? 'text-green-600 dark:text-green-400'
                    : summary.uptimePercentage >= 95
                      ? 'text-yellow-600 dark:text-yellow-400'
                      : 'text-red-600 dark:text-red-400'
                }`}
              >
                {summary.uptimePercentage.toFixed(1)}%
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
 
export default SLOTrend;