All files / web/src/app/admin/notifications page.tsx

0% Statements 0/601
0% Branches 0/1
0% Functions 0/1
0% Lines 0/601

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 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
'use client'

import { useCallback, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { PageWithNav } from '@/components/PageWithNav'
import { AdminNav } from '@/components/AdminNav'
import { useTheme } from '@/contexts/ThemeContext'
import { api } from '@/lib/queryClient'
import {
  registerServiceWorker,
  subscribeToPush,
  pushSubscriptionToJson,
} from '@/lib/notifications/register-sw'
import { css } from '../../../../styled-system/css'

interface NotificationChannelsConfig {
  webPush: { enabled: boolean }
  email: { enabled: boolean; fromName?: string; replyTo?: string }
  inApp: { enabled: boolean }
}

interface ChannelStatus {
  operational: boolean
  reason?: string
}

interface NotificationsApiResponse {
  config: NotificationChannelsConfig
  status: Record<string, ChannelStatus>
  vapidPublicKey: string | null
}

const configKeys = {
  all: ['admin-notifications'] as const,
  config: () => [...configKeys.all, 'config'] as const,
}

async function fetchNotifications(): Promise<NotificationsApiResponse> {
  const res = await api('admin/notifications')
  if (!res.ok) throw new Error('Failed to fetch notification config')
  return res.json()
}

async function updateConfig(
  config: NotificationChannelsConfig
): Promise<NotificationChannelsConfig> {
  const res = await api('admin/notifications', {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(config),
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: 'Unknown error' }))
    throw new Error(err.error || 'Failed to update config')
  }
  return res.json()
}

async function sendTest(body: {
  channel: string
  targetEmail?: string
  pushSubscription?: { endpoint: string; keys: { p256dh: string; auth: string } }
}): Promise<{ success: boolean; error?: string }> {
  const res = await api('admin/notifications/test', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  return res.json()
}

export default function AdminNotificationsPage() {
  const { resolvedTheme } = useTheme()
  const isDark = resolvedTheme === 'dark'
  const queryClient = useQueryClient()

  const { data, isLoading } = useQuery({
    queryKey: configKeys.config(),
    queryFn: fetchNotifications,
    staleTime: 5 * 60 * 1000,
  })

  const config = data?.config
  const channelStatuses = data?.status

  // Local form state
  const [localConfig, setLocalConfig] = useState<NotificationChannelsConfig | null>(null)
  const [initialized, setInitialized] = useState(false)
  const [testEmail, setTestEmail] = useState('')
  const [testResult, setTestResult] = useState<{ channel: string; message: string } | null>(null)

  if (config && !initialized) {
    setLocalConfig(config)
    setInitialized(true)
  }

  const mutation = useMutation({
    mutationFn: updateConfig,
    onSuccess: (updatedConfig) => {
      queryClient.setQueryData(configKeys.config(), (prev: NotificationsApiResponse | undefined) =>
        prev ? { ...prev, config: updatedConfig } : prev
      )
      setLocalConfig(updatedConfig)
    },
  })

  const testMutation = useMutation({
    mutationFn: sendTest,
    onSuccess: (result, variables) => {
      setTestResult({
        channel: variables.channel,
        message: result.success ? 'Test sent!' : `Failed: ${result.error}`,
      })
    },
    onError: (err, variables) => {
      setTestResult({
        channel: variables.channel,
        message: `Error: ${err instanceof Error ? err.message : 'Unknown error'}`,
      })
    },
  })

  const hasChanges = config && localConfig && JSON.stringify(config) !== JSON.stringify(localConfig)

  const handleToggle = useCallback(
    (channel: 'webPush' | 'email' | 'inApp') => {
      if (!localConfig) return
      setLocalConfig({
        ...localConfig,
        [channel]: {
          ...localConfig[channel],
          enabled: !localConfig[channel].enabled,
        },
      })
    },
    [localConfig]
  )

  const handleEmailField = useCallback(
    (field: 'fromName' | 'replyTo', value: string) => {
      if (!localConfig) return
      setLocalConfig({
        ...localConfig,
        email: {
          ...localConfig.email,
          [field]: value || undefined,
        },
      })
    },
    [localConfig]
  )

  const handleSave = useCallback(() => {
    if (localConfig) mutation.mutate(localConfig)
  }, [localConfig, mutation])

  const handleReset = useCallback(() => {
    if (config) setLocalConfig(config)
  }, [config])

  const handleTest = useCallback(
    async (channel: 'webPush' | 'email' | 'inApp') => {
      setTestResult(null)

      if (channel === 'webPush') {
        try {
          if (!('Notification' in window)) {
            setTestResult({
              channel,
              message: 'Failed: Notifications API not supported in this browser',
            })
            return
          }

          setTestResult({ channel, message: 'Requesting permission...' })
          const permission = await Notification.requestPermission()
          if (permission !== 'granted') {
            setTestResult({
              channel,
              message: `Failed: Permission ${permission}. Check browser notification settings for this site.`,
            })
            return
          }

          setTestResult({ channel, message: 'Registering service worker...' })
          const registration = await registerServiceWorker()
          if (!registration) {
            setTestResult({ channel, message: 'Failed: Service worker not supported' })
            return
          }

          setTestResult({ channel, message: 'Subscribing to push...' })
          const vapidPublicKey = data?.vapidPublicKey
          if (!vapidPublicKey) {
            setTestResult({ channel, message: 'Failed: VAPID public key not configured on server' })
            return
          }
          const browserSub = await subscribeToPush(registration, vapidPublicKey)
          const pushSub = pushSubscriptionToJson(browserSub)

          setTestResult({ channel, message: 'Sending test push...' })
          testMutation.mutate({ channel, pushSubscription: pushSub })
        } catch (err) {
          setTestResult({
            channel,
            message: `Failed: ${err instanceof Error ? err.message : String(err)}`,
          })
        }
        return
      }

      testMutation.mutate({
        channel,
        targetEmail: channel === 'email' ? testEmail : undefined,
      })
    },
    [testEmail, testMutation]
  )

  const cardStyle = css({
    backgroundColor: isDark ? 'gray.800' : 'white',
    borderRadius: '12px',
    border: '1px solid',
    borderColor: isDark ? 'gray.700' : 'gray.200',
    padding: '1.5rem',
    marginBottom: '1.5rem',
  })

  const labelStyle = css({
    fontWeight: '600',
    color: isDark ? 'white' : 'gray.800',
  })

  const secondaryText = css({
    fontSize: '0.875rem',
    color: isDark ? 'gray.400' : 'gray.600',
  })

  return (
    <PageWithNav>
      <AdminNav />
      <main
        data-component="admin-notifications"
        className={css({
          minHeight: 'calc(100vh - 110px)',
          backgroundColor: isDark ? 'gray.900' : 'gray.50',
          padding: '2rem',
        })}
      >
        <div className={css({ maxWidth: '600px', margin: '0 auto' })}>
          <header className={css({ marginBottom: '2rem' })}>
            <h1
              className={css({
                fontSize: '1.5rem',
                fontWeight: 'bold',
                color: isDark ? 'white' : 'gray.800',
              })}
            >
              Notification Channels
            </h1>
            <p className={css({ color: isDark ? 'gray.400' : 'gray.600', marginTop: '0.5rem' })}>
              Enable or disable notification channels globally. Disabled channels will not deliver
              notifications even if subscribers have them enabled.
            </p>
          </header>

          {isLoading || !localConfig ? (
            <p className={css({ color: isDark ? 'gray.500' : 'gray.500' })}>Loading...</p>
          ) : (
            <>
              {/* Channel toggles */}
              {(['webPush', 'email', 'inApp'] as const).map((channel) => {
                const labels: Record<string, { title: string; desc: string }> = {
                  webPush: {
                    title: 'Web Push',
                    desc: 'Browser push notifications via VAPID. Requires VAPID keys to be configured.',
                  },
                  email: {
                    title: 'Email',
                    desc: 'Email notifications via Nodemailer/SMTP. Uses the EMAIL_SERVER env var.',
                  },
                  inApp: {
                    title: 'In-App',
                    desc: 'Real-time toast notifications via Socket.IO for users with the app open.',
                  },
                }
                const { title, desc } = labels[channel]
                const enabled = localConfig[channel].enabled
                const status = channelStatuses?.[channel]

                return (
                  <div key={channel} data-element={`channel-${channel}`} className={cardStyle}>
                    <div
                      className={css({
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        marginBottom: '0.5rem',
                      })}
                    >
                      <div
                        className={css({
                          display: 'flex',
                          alignItems: 'center',
                          gap: '0.5rem',
                        })}
                      >
                        <span className={labelStyle}>{title}</span>
                        {status && (
                          <span
                            data-element={`status-${channel}`}
                            className={css({
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '4px',
                              fontSize: '0.6875rem',
                              fontWeight: '500',
                              padding: '2px 8px',
                              borderRadius: '9999px',
                              backgroundColor: status.operational
                                ? isDark
                                  ? 'rgba(35, 134, 54, 0.2)'
                                  : 'green.50'
                                : isDark
                                  ? 'rgba(218, 54, 51, 0.2)'
                                  : 'red.50',
                              color: status.operational
                                ? isDark
                                  ? 'green.400'
                                  : 'green.700'
                                : isDark
                                  ? 'red.400'
                                  : 'red.700',
                            })}
                          >
                            <span
                              className={css({
                                width: '6px',
                                height: '6px',
                                borderRadius: '50%',
                                backgroundColor: status.operational
                                  ? isDark
                                    ? 'green.400'
                                    : 'green.500'
                                  : isDark
                                    ? 'red.400'
                                    : 'red.500',
                              })}
                            />
                            {status.operational ? 'Operational' : 'Not configured'}
                          </span>
                        )}
                      </div>
                      <button
                        type="button"
                        onClick={() => handleToggle(channel)}
                        data-action={`toggle-${channel}`}
                        className={css({
                          position: 'relative',
                          width: '44px',
                          height: '24px',
                          borderRadius: '12px',
                          border: 'none',
                          cursor: 'pointer',
                          backgroundColor: enabled ? '#238636' : isDark ? '#30363d' : '#d1d5db',
                          transition: 'background-color 0.2s',
                        })}
                      >
                        <span
                          className={css({
                            position: 'absolute',
                            top: '2px',
                            left: enabled ? '22px' : '2px',
                            width: '20px',
                            height: '20px',
                            borderRadius: '50%',
                            backgroundColor: 'white',
                            transition: 'left 0.2s',
                          })}
                        />
                      </button>
                    </div>
                    <p className={secondaryText}>{desc}</p>

                    {/* Show reason when not operational */}
                    {status && !status.operational && (
                      <p
                        data-element={`status-reason-${channel}`}
                        className={css({
                          fontSize: '0.75rem',
                          color: isDark ? 'red.400' : 'red.600',
                          marginTop: '0.375rem',
                          fontFamily: 'monospace',
                        })}
                      >
                        {status.reason}
                      </p>
                    )}

                    {/* Email-specific fields */}
                    {channel === 'email' && enabled && (
                      <div className={css({ marginTop: '1rem' })}>
                        <div className={css({ marginBottom: '0.75rem' })}>
                          <label className={css({ display: 'block', marginBottom: '0.25rem' })}>
                            <span className={secondaryText}>From Name (optional)</span>
                          </label>
                          <input
                            type="text"
                            placeholder="Abaci One"
                            value={(localConfig.email as { fromName?: string }).fromName ?? ''}
                            onChange={(e) => handleEmailField('fromName', e.target.value)}
                            data-element="email-from-name"
                            className={css({
                              width: '100%',
                              padding: '0.5rem 0.75rem',
                              borderRadius: '6px',
                              border: '1px solid',
                              borderColor: isDark ? 'gray.600' : 'gray.300',
                              backgroundColor: isDark ? 'gray.700' : 'white',
                              color: isDark ? 'white' : 'gray.800',
                              fontSize: '0.875rem',
                            })}
                          />
                        </div>
                        <div>
                          <label className={css({ display: 'block', marginBottom: '0.25rem' })}>
                            <span className={secondaryText}>Reply-To (optional)</span>
                          </label>
                          <input
                            type="email"
                            placeholder="hallock@gmail.com"
                            value={(localConfig.email as { replyTo?: string }).replyTo ?? ''}
                            onChange={(e) => handleEmailField('replyTo', e.target.value)}
                            data-element="email-reply-to"
                            className={css({
                              width: '100%',
                              padding: '0.5rem 0.75rem',
                              borderRadius: '6px',
                              border: '1px solid',
                              borderColor: isDark ? 'gray.600' : 'gray.300',
                              backgroundColor: isDark ? 'gray.700' : 'white',
                              color: isDark ? 'white' : 'gray.800',
                              fontSize: '0.875rem',
                            })}
                          />
                        </div>
                      </div>
                    )}

                    {/* Test button */}
                    {enabled && (
                      <div className={css({ marginTop: '1rem' })}>
                        {channel === 'email' && (
                          <div className={css({ marginBottom: '0.5rem' })}>
                            <input
                              type="email"
                              placeholder="Test email address"
                              value={testEmail}
                              onChange={(e) => setTestEmail(e.target.value)}
                              data-element="test-email-input"
                              className={css({
                                width: '100%',
                                padding: '0.5rem 0.75rem',
                                borderRadius: '6px',
                                border: '1px solid',
                                borderColor: isDark ? 'gray.600' : 'gray.300',
                                backgroundColor: isDark ? 'gray.700' : 'white',
                                color: isDark ? 'white' : 'gray.800',
                                fontSize: '0.875rem',
                              })}
                            />
                          </div>
                        )}
                        <button
                          type="button"
                          onClick={() => handleTest(channel)}
                          disabled={testMutation.isPending || (channel === 'email' && !testEmail)}
                          data-action={`test-${channel}`}
                          className={css({
                            padding: '0.375rem 0.75rem',
                            fontSize: '0.8125rem',
                            borderRadius: '6px',
                            border: '1px solid',
                            borderColor: isDark ? 'gray.600' : 'gray.300',
                            backgroundColor: isDark ? '#21262d' : 'gray.100',
                            color: isDark ? '#c9d1d9' : 'gray.700',
                            cursor: 'pointer',
                            _hover: {
                              backgroundColor: isDark ? '#30363d' : 'gray.200',
                            },
                          })}
                        >
                          {testMutation.isPending ? 'Sending...' : `Send Test ${title}`}
                        </button>
                        {testResult?.channel === channel && (
                          <span
                            className={css({
                              marginLeft: '0.75rem',
                              fontSize: '0.8125rem',
                              color: testResult.message.startsWith('Test')
                                ? 'green.500'
                                : testResult.message.startsWith('Failed')
                                  ? 'red.400'
                                  : isDark
                                    ? 'gray.400'
                                    : 'gray.500',
                            })}
                          >
                            {testResult.message}
                          </span>
                        )}
                      </div>
                    )}
                  </div>
                )
              })}

              {/* Save / Reset */}
              <div
                className={css({
                  display: 'flex',
                  gap: '0.75rem',
                  alignItems: 'center',
                })}
              >
                <button
                  type="button"
                  onClick={handleSave}
                  disabled={!hasChanges || mutation.isPending}
                  data-action="save-config"
                  className={css({
                    padding: '0.5rem 1rem',
                    backgroundColor: hasChanges ? 'blue.500' : isDark ? 'gray.700' : 'gray.300',
                    color: hasChanges ? 'white' : isDark ? 'gray.500' : 'gray.500',
                    borderRadius: '6px',
                    border: 'none',
                    fontWeight: '600',
                    cursor: hasChanges ? 'pointer' : 'not-allowed',
                    _hover: hasChanges ? { backgroundColor: 'blue.600' } : {},
                  })}
                >
                  {mutation.isPending ? 'Saving...' : 'Save'}
                </button>
                {hasChanges && (
                  <button
                    type="button"
                    onClick={handleReset}
                    data-action="reset-config"
                    className={css({
                      padding: '0.5rem 1rem',
                      backgroundColor: 'transparent',
                      color: isDark ? 'gray.400' : 'gray.600',
                      borderRadius: '6px',
                      border: '1px solid',
                      borderColor: isDark ? 'gray.600' : 'gray.300',
                      cursor: 'pointer',
                      _hover: { borderColor: isDark ? 'gray.500' : 'gray.400' },
                    })}
                  >
                    Reset
                  </button>
                )}
                {hasChanges && (
                  <span className={css({ fontSize: '0.875rem', color: 'orange.500' })}>
                    Unsaved changes
                  </span>
                )}
              </div>

              {mutation.isError && (
                <p
                  className={css({
                    color: 'red.500',
                    fontSize: '0.875rem',
                    marginTop: '0.75rem',
                  })}
                >
                  {mutation.error instanceof Error
                    ? mutation.error.message
                    : 'Failed to update config'}
                </p>
              )}

              {mutation.isSuccess && !hasChanges && (
                <p
                  className={css({
                    color: 'green.500',
                    fontSize: '0.875rem',
                    marginTop: '0.75rem',
                  })}
                >
                  Configuration saved.
                </p>
              )}
            </>
          )}
        </div>
      </main>
    </PageWithNav>
  )
}