All files / src/components/features/admin/monitoring/alerts/AlertConfigForm index.tsx

97.12% Statements 439/452
82.1% Branches 78/95
52.94% Functions 9/17
97.12% Lines 439/452

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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 4531x 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 1x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 4x 4x 4x 1x 1x 4x 4x 1x 1x 4x 4x 1x 1x 4x 4x     4x 4x     4x 4x     4x 4x     4x 4x     4x 4x 4x 47x 47x 47x 4x 4x 1x 47x 47x 47x 2x 2x 2x 2x 2x 2x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 188x 188x 188x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 1x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x   47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 235x 235x 235x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x   47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 47x 47x 47x   47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 2x 2x 2x 2x 47x 1x 45x 44x 47x 47x 47x 47x 47x 47x 1x 1x  
'use client';
 
import { useState } from 'react';
import { cn } from '@/lib/core';
import { Button } from '@/components/ui/Button';
import { Icon } from '@/components/ui/icons';
import type { PerformanceAlertConfig } from '@prisma/client';
 
export interface AlertConfigFormProps {
  /** Initial values for editing */
  initialValues?: Partial<PerformanceAlertConfig>;
  /** Callback when form is submitted */
  onSubmit: (values: AlertConfigFormValues) => Promise<void>;
  /** Callback when form is cancelled */
  onCancel: () => void;
  /** Whether the form is in loading state */
  isLoading?: boolean;
  /** Additional CSS classes */
  className?: string;
}
 
export interface AlertConfigFormValues {
  name: string;
  description?: string;
  metricType: string;
  scope: string;
  warningThreshold: number;
  criticalThreshold: number;
  evaluationWindow: number;
  evaluationInterval: number;
  minSamples: number;
  notifyOnWarning: boolean;
  notifyOnCritical: boolean;
  notificationChannels: string[];
  cooldownMinutes: number;
  enabled: boolean;
}
 
const metricTypes = [
  { value: 'response_time', label: 'Response Time (ms)', unit: 'ms' },
  { value: 'p95_latency', label: 'P95 Latency (ms)', unit: 'ms' },
  { value: 'error_rate', label: 'Error Rate (%)', unit: '%' },
  { value: 'throughput', label: 'Throughput (req/min)', unit: 'req/min' },
];
 
const evaluationWindows = [
  { value: 60, label: '1 minute' },
  { value: 300, label: '5 minutes' },
  { value: 900, label: '15 minutes' },
  { value: 1800, label: '30 minutes' },
  { value: 3600, label: '1 hour' },
];
 
const notificationChannelOptions = [
  { value: 'email', label: 'Email' },
  { value: 'slack', label: 'Slack' },
  { value: 'webhook', label: 'Webhook' },
];
 
/**
 * AlertConfigForm provides a form for creating or editing
 * performance alert configurations.
 */
export function AlertConfigForm({
  initialValues,
  onSubmit,
  onCancel,
  isLoading = false,
  className,
}: AlertConfigFormProps) {
  const [values, setValues] = useState<AlertConfigFormValues>({
    name: initialValues?.name || '',
    description: initialValues?.description || '',
    metricType: initialValues?.metricType || 'response_time',
    scope: initialValues?.scope || 'all',
    warningThreshold: initialValues?.warningThreshold || 500,
    criticalThreshold: initialValues?.criticalThreshold || 1000,
    evaluationWindow: initialValues?.evaluationWindow || 300,
    evaluationInterval: initialValues?.evaluationInterval || 60,
    minSamples: initialValues?.minSamples || 10,
    notifyOnWarning: initialValues?.notifyOnWarning ?? true,
    notifyOnCritical: initialValues?.notifyOnCritical ?? true,
    notificationChannels: (initialValues?.notificationChannels as string[]) || ['email'],
    cooldownMinutes: initialValues?.cooldownMinutes || 15,
    enabled: initialValues?.enabled ?? true,
  });
 
  const [errors, setErrors] = useState<Partial<Record<keyof AlertConfigFormValues, string>>>({});
 
  const selectedMetric = metricTypes.find((m) => m.value === values.metricType);
 
  const validateForm = (): boolean => {
    const newErrors: Partial<Record<keyof AlertConfigFormValues, string>> = {};
 
    if (!values.name.trim()) {
      newErrors.name = 'Name is required';
    }
 
    if (!values.scope.trim()) {
      newErrors.scope = 'Scope is required';
    }
 
    if (values.warningThreshold >= values.criticalThreshold) {
      newErrors.warningThreshold = 'Warning threshold must be less than critical threshold';
    }
 
    if (values.warningThreshold < 0) {
      newErrors.warningThreshold = 'Threshold must be positive';
    }
 
    if (values.criticalThreshold < 0) {
      newErrors.criticalThreshold = 'Threshold must be positive';
    }
 
    if (values.minSamples < 1) {
      newErrors.minSamples = 'Minimum samples must be at least 1';
    }
 
    if (values.cooldownMinutes < 1) {
      newErrors.cooldownMinutes = 'Cooldown must be at least 1 minute';
    }
 
    if (values.notificationChannels.length === 0) {
      newErrors.notificationChannels = 'At least one notification channel is required';
    }
 
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;
    await onSubmit(values);
  };
 
  const handleChannelToggle = (channel: string) => {
    setValues((prev) => ({
      ...prev,
      notificationChannels: prev.notificationChannels.includes(channel)
        ? prev.notificationChannels.filter((c) => c !== channel)
        : [...prev.notificationChannels, channel],
    }));
  };
 
  return (
    <form onSubmit={handleSubmit} className={cn('space-y-6', className)}>
      {/* Basic Information */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900 dark:text-white">Basic Information</h3>
 
        <div>
          <label htmlFor="name" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
            Name *
          </label>
          <input
            type="text"
            id="name"
            value={values.name}
            onChange={(e) => setValues((prev) => ({ ...prev, name: e.target.value }))}
            className={cn(
              'mt-1 block w-full rounded-md border shadow-sm sm:text-sm',
              'bg-white dark:bg-gray-800 text-gray-900 dark:text-white',
              errors.name
                ? 'border-red-300 dark:border-red-700'
                : 'border-gray-300 dark:border-gray-600'
            )}
            placeholder="e.g., API Response Time Alert"
          />
          {errors.name && <p className="mt-1 text-sm text-red-600">{errors.name}</p>}
        </div>
 
        <div>
          <label htmlFor="description" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
            Description
          </label>
          <textarea
            id="description"
            value={values.description}
            onChange={(e) => setValues((prev) => ({ ...prev, description: e.target.value }))}
            rows={2}
            className="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white shadow-sm sm:text-sm"
            placeholder="Optional description of what this alert monitors"
          />
        </div>
      </div>
 
      {/* Metric Configuration */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900 dark:text-white">Metric Configuration</h3>
 
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label htmlFor="metricType" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Metric Type *
            </label>
            <select
              id="metricType"
              value={values.metricType}
              onChange={(e) => setValues((prev) => ({ ...prev, metricType: e.target.value }))}
              className="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white shadow-sm sm:text-sm"
            >
              {metricTypes.map((metric) => (
                <option key={metric.value} value={metric.value}>
                  {metric.label}
                </option>
              ))}
            </select>
          </div>
 
          <div>
            <label htmlFor="scope" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Scope *
            </label>
            <input
              type="text"
              id="scope"
              value={values.scope}
              onChange={(e) => setValues((prev) => ({ ...prev, scope: e.target.value }))}
              className={cn(
                'mt-1 block w-full rounded-md border shadow-sm sm:text-sm',
                'bg-white dark:bg-gray-800 text-gray-900 dark:text-white',
                errors.scope
                  ? 'border-red-300 dark:border-red-700'
                  : 'border-gray-300 dark:border-gray-600'
              )}
              placeholder="all or /api/products"
            />
            {errors.scope && <p className="mt-1 text-sm text-red-600">{errors.scope}</p>}
            <p className="mt-1 text-xs text-gray-500">
              Use &quot;all&quot; for all endpoints or a path prefix like &quot;/api/products&quot;
            </p>
          </div>
        </div>
      </div>
 
      {/* Thresholds */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900 dark:text-white">Thresholds</h3>
 
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label htmlFor="warningThreshold" className="block text-sm font-medium text-yellow-600 dark:text-yellow-400">
              Warning Threshold ({selectedMetric?.unit})
            </label>
            <input
              type="number"
              id="warningThreshold"
              value={values.warningThreshold}
              onChange={(e) => setValues((prev) => ({ ...prev, warningThreshold: parseFloat(e.target.value) || 0 }))}
              min="0"
              step="any"
              className={cn(
                'mt-1 block w-full rounded-md border shadow-sm sm:text-sm',
                'bg-white dark:bg-gray-800 text-gray-900 dark:text-white',
                errors.warningThreshold
                  ? 'border-red-300 dark:border-red-700'
                  : 'border-gray-300 dark:border-gray-600'
              )}
            />
            {errors.warningThreshold && (
              <p className="mt-1 text-sm text-red-600">{errors.warningThreshold}</p>
            )}
          </div>
 
          <div>
            <label htmlFor="criticalThreshold" className="block text-sm font-medium text-red-600 dark:text-red-400">
              Critical Threshold ({selectedMetric?.unit})
            </label>
            <input
              type="number"
              id="criticalThreshold"
              value={values.criticalThreshold}
              onChange={(e) => setValues((prev) => ({ ...prev, criticalThreshold: parseFloat(e.target.value) || 0 }))}
              min="0"
              step="any"
              className={cn(
                'mt-1 block w-full rounded-md border shadow-sm sm:text-sm',
                'bg-white dark:bg-gray-800 text-gray-900 dark:text-white',
                errors.criticalThreshold
                  ? 'border-red-300 dark:border-red-700'
                  : 'border-gray-300 dark:border-gray-600'
              )}
            />
            {errors.criticalThreshold && (
              <p className="mt-1 text-sm text-red-600">{errors.criticalThreshold}</p>
            )}
          </div>
        </div>
      </div>
 
      {/* Evaluation Settings */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900 dark:text-white">Evaluation Settings</h3>
 
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label htmlFor="evaluationWindow" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Evaluation Window
            </label>
            <select
              id="evaluationWindow"
              value={values.evaluationWindow}
              onChange={(e) => setValues((prev) => ({ ...prev, evaluationWindow: parseInt(e.target.value, 10) }))}
              className="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white shadow-sm sm:text-sm"
            >
              {evaluationWindows.map((window) => (
                <option key={window.value} value={window.value}>
                  {window.label}
                </option>
              ))}
            </select>
          </div>
 
          <div>
            <label htmlFor="minSamples" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Minimum Samples
            </label>
            <input
              type="number"
              id="minSamples"
              value={values.minSamples}
              onChange={(e) => setValues((prev) => ({ ...prev, minSamples: parseInt(e.target.value, 10) || 1 }))}
              min="1"
              className={cn(
                'mt-1 block w-full rounded-md border shadow-sm sm:text-sm',
                'bg-white dark:bg-gray-800 text-gray-900 dark:text-white',
                errors.minSamples
                  ? 'border-red-300 dark:border-red-700'
                  : 'border-gray-300 dark:border-gray-600'
              )}
            />
            {errors.minSamples && <p className="mt-1 text-sm text-red-600">{errors.minSamples}</p>}
          </div>
 
          <div>
            <label htmlFor="cooldownMinutes" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Cooldown (minutes)
            </label>
            <input
              type="number"
              id="cooldownMinutes"
              value={values.cooldownMinutes}
              onChange={(e) => setValues((prev) => ({ ...prev, cooldownMinutes: parseInt(e.target.value, 10) || 1 }))}
              min="1"
              className={cn(
                'mt-1 block w-full rounded-md border shadow-sm sm:text-sm',
                'bg-white dark:bg-gray-800 text-gray-900 dark:text-white',
                errors.cooldownMinutes
                  ? 'border-red-300 dark:border-red-700'
                  : 'border-gray-300 dark:border-gray-600'
              )}
            />
            {errors.cooldownMinutes && (
              <p className="mt-1 text-sm text-red-600">{errors.cooldownMinutes}</p>
            )}
          </div>
        </div>
      </div>
 
      {/* Notifications */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900 dark:text-white">Notifications</h3>
 
        <div className="space-y-3">
          <div className="flex items-center gap-4">
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={values.notifyOnWarning}
                onChange={(e) => setValues((prev) => ({ ...prev, notifyOnWarning: e.target.checked }))}
                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">Notify on warning</span>
            </label>
 
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={values.notifyOnCritical}
                onChange={(e) => setValues((prev) => ({ ...prev, notifyOnCritical: e.target.checked }))}
                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">Notify on critical</span>
            </label>
          </div>
 
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Notification Channels
            </label>
            <div className="flex flex-wrap gap-2">
              {notificationChannelOptions.map((channel) => (
                <button
                  key={channel.value}
                  type="button"
                  onClick={() => handleChannelToggle(channel.value)}
                  className={cn(
                    'inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium transition-colors',
                    values.notificationChannels.includes(channel.value)
                      ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400'
                      : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                  )}
                >
                  {channel.label}
                </button>
              ))}
            </div>
            {errors.notificationChannels && (
              <p className="mt-1 text-sm text-red-600">{errors.notificationChannels}</p>
            )}
          </div>
        </div>
      </div>
 
      {/* Enable/Disable */}
      <div className="flex items-center gap-2">
        <input
          type="checkbox"
          id="enabled"
          checked={values.enabled}
          onChange={(e) => setValues((prev) => ({ ...prev, enabled: e.target.checked }))}
          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
        />
        <label htmlFor="enabled" className="text-sm text-gray-700 dark:text-gray-300">
          Enable this alert configuration
        </label>
      </div>
 
      {/* Form Actions */}
      <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
        <Button type="button" variant="outline" onClick={onCancel} disabled={isLoading}>
          Cancel
        </Button>
        <Button type="submit" variant="primary" disabled={isLoading}>
          {isLoading ? (
            <>
              <Icon name="spinner" className="h-4 w-4 animate-spin mr-2" />
              Saving...
            </>
          ) : initialValues?.id ? (
            'Update Configuration'
          ) : (
            'Create Configuration'
          )}
        </Button>
      </div>
    </form>
  );
}
 
export default AlertConfigForm;