diff --git a/apps/web/package.json b/apps/web/package.json index e72f55f..0514ab0 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,7 +7,7 @@ "dev": "vite", "build": "tsc --noEmit && vite build", "typecheck": "tsc --noEmit", - "test": "node --test src/api/client.test.ts src/lib/utils.test.ts src/lib/apiErrorCodes.test.ts src/lib/setup.test.ts", + "test": "node --test src/api/client.test.ts src/lib/utils.test.ts src/lib/apiErrorCodes.test.ts src/lib/setup.test.ts src/lib/testEmail.test.ts", "preview": "vite preview" }, "dependencies": { diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index bcd0b8c..d85c5f6 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -726,6 +726,15 @@ export const adminApi = { // Runs the same schema-migration routine as POST /api/setup, keyed to the // admin session (no setup secret required). runSetup: () => request('/admin/setup', { method: 'POST' }), + // Sends a test email through the currently saved email settings. The backend + // reports success as `{ success: true }`; failures carry the status code the + // UI maps to a readable message (400 config/address, 429 with Retry-After, + // 502 send failure). + sendTestEmail: (to: string) => + request<{ success: boolean }>('/admin/email/test', { + method: 'POST', + body: JSON.stringify({ to }), + }), }; // Re-export WebAuthn types used by auth API diff --git a/apps/web/src/i18n/locales/en.ts b/apps/web/src/i18n/locales/en.ts index ee0a837..976d029 100644 --- a/apps/web/src/i18n/locales/en.ts +++ b/apps/web/src/i18n/locales/en.ts @@ -255,6 +255,18 @@ export const en = { runSetup: 'Check & Upgrade Database', runSetupDesc: 'Run pending database migrations. Already-applied migrations are reported as skipped.', + sendTestEmail: 'Send Test Email', + testEmailRecipient: 'Recipient Email', + testEmailNote: + 'The test uses the saved email settings. Save your changes first to test them.', + testEmailSuccess: 'Test email sent successfully', + testEmailErrorBadRequest: + 'Invalid recipient or email not configured. Check the address and save your email settings.', + testEmailErrorTooManyRequests: + 'Too many requests. Try again in {{seconds}}s.', + testEmailErrorSendFailed: + 'Failed to send the test email. Check your email provider settings.', + testEmailErrorGeneric: 'Failed to send the test email. Please try again.', }, toast: { sessionExpired: 'Session expired. Please sign in again.', diff --git a/apps/web/src/i18n/locales/zh-CN.ts b/apps/web/src/i18n/locales/zh-CN.ts index c1809a9..8635191 100644 --- a/apps/web/src/i18n/locales/zh-CN.ts +++ b/apps/web/src/i18n/locales/zh-CN.ts @@ -243,6 +243,15 @@ export const zhCN: Translations = { setupPageDisabled: '已关闭', runSetup: '检查并升级数据库', runSetupDesc: '执行待处理的数据库迁移,已应用的迁移将显示为「已跳过」。', + sendTestEmail: '发送测试邮件', + testEmailRecipient: '收件地址', + testEmailNote: '测试使用已保存的邮件设置,修改后请先保存。', + testEmailSuccess: '测试邮件发送成功', + testEmailErrorBadRequest: + '收件地址无效或邮件未配置,请检查地址并保存邮件设置。', + testEmailErrorTooManyRequests: '请求过于频繁,请在 {{seconds}} 秒后重试。', + testEmailErrorSendFailed: '测试邮件发送失败,请检查邮件服务商配置。', + testEmailErrorGeneric: '测试邮件发送失败,请重试。', }, toast: { sessionExpired: '登录已过期,请重新登录。', diff --git a/apps/web/src/lib/testEmail.test.ts b/apps/web/src/lib/testEmail.test.ts new file mode 100644 index 0000000..829cb69 --- /dev/null +++ b/apps/web/src/lib/testEmail.test.ts @@ -0,0 +1,195 @@ +import assert from 'node:assert/strict'; +import { afterEach, describe, test } from 'node:test'; +import { + ApiRequestError, + adminApi, + SessionExpiredError, +} from '../api/client.ts'; +import { en } from '../i18n/locales/en.ts'; +import { zhCN } from '../i18n/locales/zh-CN.ts'; +import { formatTestEmailError, resolveTestEmailError } from './testEmail.ts'; + +// Admin "send test email" frontend behaviour, pinned down with a stubbed fetch +// and pure helpers (same style as setup.test.ts — no extra test dependencies). +// The AdminSettingsPage component is not rendered here; its error/success +// display logic is extracted into the pure functions asserted below. + +const originalFetch = globalThis.fetch; + +function jsonResponse( + body: unknown, + status = 200, + headers?: Record, +): Response { + return new Response(JSON.stringify(body), { status, headers }); +} + +function mockFetch( + handler: (url: string, init?: RequestInit) => Response | Promise, +): string[] { + const calls: string[] = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + calls.push(url); + return handler(url, init); + }) as typeof fetch; + return calls; +} + +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +describe('adminApi.sendTestEmail', () => { + test('posts the recipient and returns success', async () => { + const calls = mockFetch((url, init) => { + assert.match(url, /\/api\/admin\/email\/test$/); + assert.equal(init?.method, 'POST'); + assert.deepEqual(JSON.parse(String(init?.body)), { to: 'a@example.com' }); + return jsonResponse({ success: true }); + }); + + const result = await adminApi.sendTestEmail('a@example.com'); + + assert.equal(calls.length, 1); + assert.equal(result.success, true); + }); + + test('surfaces the status and Retry-After seconds on a 429', async () => { + mockFetch( + () => + new Response(JSON.stringify({ error: 'Too many requests.' }), { + status: 429, + headers: { 'Retry-After': '30', 'Content-Type': 'application/json' }, + }), + ); + + await assert.rejects( + adminApi.sendTestEmail('a@example.com'), + (error: unknown) => { + assert.ok(error instanceof ApiRequestError); + assert.equal(error.status, 429); + assert.equal(error.retryAfter, 30); + return true; + }, + ); + }); + + test('surfaces the status on a 502 send failure', async () => { + mockFetch(() => jsonResponse({ error: 'Failed to send' }, 502)); + + await assert.rejects( + adminApi.sendTestEmail('a@example.com'), + (error: unknown) => { + assert.ok(error instanceof ApiRequestError); + assert.equal(error.status, 502); + return true; + }, + ); + }); +}); + +describe('resolveTestEmailError', () => { + test('maps 400, 429 and 502 to their status keys', () => { + assert.deepEqual(resolveTestEmailError({ status: 400 }), { + key: 'admin.testEmailErrorBadRequest', + }); + assert.deepEqual(resolveTestEmailError({ status: 502 }), { + key: 'admin.testEmailErrorSendFailed', + }); + }); + + test('maps a 429 with Retry-After to the localized too-many-requests key', () => { + assert.deepEqual(resolveTestEmailError({ status: 429, retryAfter: 45 }), { + key: 'admin.testEmailErrorTooManyRequests', + params: { seconds: 45 }, + }); + }); + + test('falls back to the generic key for unmatched errors', () => { + assert.deepEqual(resolveTestEmailError({ status: 500 }), { + key: 'admin.testEmailErrorGeneric', + }); + assert.deepEqual(resolveTestEmailError(new Error('boom')), { + key: 'admin.testEmailErrorGeneric', + }); + assert.deepEqual(resolveTestEmailError(undefined), { + key: 'admin.testEmailErrorGeneric', + }); + }); + + test('is silent for a session-expired error', () => { + assert.equal(resolveTestEmailError(new SessionExpiredError()), null); + }); +}); + +describe('formatTestEmailError', () => { + function makeT(locale: unknown) { + const resolve = (obj: unknown, path: string): string => { + let curr = obj; + for (const p of path.split('.')) { + curr = (curr as Record)[p]; + } + return String(curr); + }; + return (key: string, params?: Record): string => { + let text = resolve(locale, key); + if (params) { + for (const [k, v] of Object.entries(params)) { + text = text.replace(`{{${k}}}`, String(v)); + } + } + return text; + }; + } + + test('returns null when there is no error to show', () => { + assert.equal(formatTestEmailError(null, makeT(en)), null); + }); + + test('interpolates the Retry-After seconds into the localized message', () => { + const msg = resolveTestEmailError({ status: 429, retryAfter: 45 }); + assert.equal( + formatTestEmailError(msg, makeT(en)), + 'Too many requests. Try again in 45s.', + ); + assert.equal( + formatTestEmailError(msg, makeT(zhCN)), + '请求过于频繁,请在 45 秒后重试。', + ); + }); +}); + +describe('test email i18n keys', () => { + function resolve(obj: unknown, path: string): unknown { + let curr = obj; + for (const p of path.split('.')) { + if (curr == null || typeof curr !== 'object') return undefined; + curr = (curr as Record)[p]; + } + return curr; + } + + test('resolve to non-empty strings in both locales', () => { + const keys = [ + 'admin.sendTestEmail', + 'admin.testEmailRecipient', + 'admin.testEmailNote', + 'admin.testEmailSuccess', + 'admin.testEmailErrorBadRequest', + 'admin.testEmailErrorTooManyRequests', + 'admin.testEmailErrorSendFailed', + 'admin.testEmailErrorGeneric', + ]; + for (const key of keys) { + assert.equal(typeof resolve(en, key), 'string', `${key} (en) is missing`); + assert.equal( + typeof resolve(zhCN, key), + 'string', + `${key} (zh-CN) is missing`, + ); + assert.ok((resolve(en, key) as string).length > 0, `${key} (en) empty`); + assert.ok((resolve(zhCN, key) as string).length > 0, `${key} (zh) empty`); + } + }); +}); diff --git a/apps/web/src/lib/testEmail.ts b/apps/web/src/lib/testEmail.ts new file mode 100644 index 0000000..4f8963c --- /dev/null +++ b/apps/web/src/lib/testEmail.ts @@ -0,0 +1,55 @@ +import type { TFunction, TranslationKey } from '@/i18n'; +import { isSessionExpiredError } from '../api/client.ts'; + +// Pure, testable helpers for the admin "send test email" action. Kept free of +// React so they run under `node --test`; the runtime import below is relative +// (`.ts`) because Node's type stripping does no `@/` alias resolution. + +export type TestEmailErrorMsg = { + key: TranslationKey; + params?: Record; +}; + +// Structural view of what a test-email API error looks like. +export interface TestEmailErrorLike { + status: number; + retryAfter?: number; +} + +// Maps a test-email failure to a localized message. The endpoint returns a +// plain `{ error }` body without a `code`, so the status code drives the +// mapping: 400 is a config/address problem, 429 is rate-limiting (with +// Retry-After seconds), 502 is a send failure, and everything else falls back +// to a generic key rather than leaking an untranslated backend/network string. +// Returns null for a session-expired error so callers stay quiet (AuthProvider +// shows the single global toast). +export function resolveTestEmailError( + error: unknown, +): TestEmailErrorMsg | null { + if (isSessionExpiredError(error)) return null; + if (error && typeof error === 'object') { + const e = error as TestEmailErrorLike; + switch (e.status) { + case 400: + return { key: 'admin.testEmailErrorBadRequest' }; + case 429: + return { + key: 'admin.testEmailErrorTooManyRequests', + params: { seconds: e.retryAfter ?? 0 }, + }; + case 502: + return { key: 'admin.testEmailErrorSendFailed' }; + } + } + return { key: 'admin.testEmailErrorGeneric' }; +} + +// Turns a resolved test-email error into its display string, or null when there +// is nothing to show (no error, or a session-expired error handled elsewhere). +export function formatTestEmailError( + msg: TestEmailErrorMsg | null, + t: TFunction, +): string | null { + if (!msg) return null; + return t(msg.key, msg.params); +} diff --git a/apps/web/src/pages/admin/AdminSettingsPage.tsx b/apps/web/src/pages/admin/AdminSettingsPage.tsx index fdd6245..7add242 100644 --- a/apps/web/src/pages/admin/AdminSettingsPage.tsx +++ b/apps/web/src/pages/admin/AdminSettingsPage.tsx @@ -1,6 +1,6 @@ import { useQuery } from '@tanstack/react-query'; import { ChevronDown } from 'lucide-react'; -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { toast } from 'sonner'; import type { SetupResult } from '@/api/client'; import { adminApi } from '@/api/client'; @@ -17,14 +17,18 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { useAppConfig } from '@/contexts/AppConfigContext'; +import { useAuth } from '@/contexts/AuthContext'; import { useTranslation } from '@/i18n'; import type { SetupErrorMsg } from '@/lib/setup'; import { formatSetupError, resolveSetupError } from '@/lib/setup'; +import type { TestEmailErrorMsg } from '@/lib/testEmail'; +import { formatTestEmailError, resolveTestEmailError } from '@/lib/testEmail'; import { toastApiError } from '@/lib/toast'; export default function AdminSettingsPage() { const { t } = useTranslation(); const { reload: reloadAppConfig } = useAppConfig(); + const { user } = useAuth(); const { data, isLoading } = useQuery({ queryKey: ['admin-settings'], queryFn: adminApi.getSettings, @@ -56,6 +60,15 @@ export default function AdminSettingsPage() { const [resendKeyIsSet, setResendKeyIsSet] = useState(false); const [smtpPassIsSet, setSmtpPassIsSet] = useState(false); + // Send test email + const [testEmailTo, setTestEmailTo] = useState(''); + const [sendingTestEmail, setSendingTestEmail] = useState(false); + const [testEmailError, setTestEmailError] = + useState(null); + // Prefill the recipient with the current admin's email exactly once, so the + // admin's own edits are never overwritten when `user` (re)loads. + const testEmailPrefilled = useRef(false); + // Setup page toggle + "check & upgrade database" action const [setupPageEnabled, setSetupPageEnabled] = useState(true); const [runSetupLoading, setRunSetupLoading] = useState(false); @@ -90,6 +103,13 @@ export default function AdminSettingsPage() { } }, [data]); + useEffect(() => { + if (user?.email && !testEmailPrefilled.current) { + setTestEmailTo(user.email); + testEmailPrefilled.current = true; + } + }, [user?.email]); + const handleRegistrationToggle = async (enabled: boolean) => { setRegistrationEnabled(enabled); try { @@ -164,6 +184,21 @@ export default function AdminSettingsPage() { } }; + const handleSendTestEmail = async () => { + const to = testEmailTo.trim(); + if (!to) return; + setSendingTestEmail(true); + setTestEmailError(null); + try { + await adminApi.sendTestEmail(to); + toast.success(t('admin.testEmailSuccess')); + } catch (err) { + setTestEmailError(resolveTestEmailError(err)); + } finally { + setSendingTestEmail(false); + } + }; + const handleSetupPageToggle = async (enabled: boolean) => { setSetupPageEnabled(enabled); try { @@ -442,6 +477,41 @@ export default function AdminSettingsPage() { + + {/* Send test email (uses the saved settings) */} +
+
+ + setTestEmailTo(e.target.value)} + placeholder="you@example.com" + className="max-w-xs" + /> +
+

+ {t('admin.testEmailNote')} +

+ + {testEmailError && ( +

+ {formatTestEmailError(testEmailError, t)} +

+ )} +