mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 11:24:43 +00:00
feat(notification): add email notification infrastructure, smtp configuration, and periodic background delivery job (#431)
* feat(notification): add email notification support and dedicated workflow * feat(webui): add team email notification settings and test email dialog * refactor(webui): remove redundant card header from email notification settings * fix(notification): prevent sending notification emails to AI agents * feat(notification): display project, avatar, upload time and resolve mention names in notification emails * refactor(notification): remove uploadDebounceSeconds and naive workflow sleep * refactor(notification): remove temporal notification workflow and keep email infrastructure * fix(team): prevent leaking email notification settings and credentials in team settings * feat(notification): add periodic background job for batched email notification delivery * fix(notification): embed avatars and thumbnails as inline cid attachments
This commit is contained in:
@@ -0,0 +1,239 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { EmailNotificationSettings } from './EmailNotificationSettings'
|
||||
import type { EmailNotificationSettings as Settings } from '@shumai/dtos'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const mockGetSettings = vi.fn()
|
||||
const mockPutSettings = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
notifications: {
|
||||
email: {
|
||||
$get: () => mockGetSettings(),
|
||||
$put: (args: unknown) => mockPutSettings(args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./TestEmailDialog', () => ({
|
||||
TestEmailDialog: ({
|
||||
isOpen,
|
||||
defaultFrom,
|
||||
}: {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
teamId: string
|
||||
defaultFrom?: string
|
||||
}) =>
|
||||
isOpen ? (
|
||||
<div data-testid="mock-test-email-dialog" data-from={defaultFrom}>
|
||||
Test Email Dialog Content
|
||||
</div>
|
||||
) : null,
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('EmailNotificationSettings', () => {
|
||||
const initialSettings: Settings = {
|
||||
enabled: false,
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'smtpuser',
|
||||
password: '••••••••',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: 'Shumai <noreply@example.com>',
|
||||
replyTo: 'support@example.com',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGetSettings.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => initialSettings,
|
||||
})
|
||||
mockPutSettings.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ ...initialSettings, enabled: true }),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
function renderComponent() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<EmailNotificationSettings teamId="team-1" />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
it('renders initial settings properly', async () => {
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/enable email notifications/i)).toBeDefined()
|
||||
})
|
||||
|
||||
expect(screen.getByText(/smtp server settings/i)).toBeDefined()
|
||||
expect(screen.getByText(/sender information/i)).toBeDefined()
|
||||
|
||||
// Host input should have the value from initial settings
|
||||
const hostInput = screen.getByLabelText(/smtp host/i) as HTMLInputElement
|
||||
expect(hostInput.value).toBe('smtp.example.com')
|
||||
expect(hostInput.disabled).toBe(true) // Disabled because enabled is false
|
||||
|
||||
// Buttons
|
||||
expect(screen.getByRole('button', { name: /^save$/i })).toBeDefined()
|
||||
expect(screen.getByRole('button', { name: /save & send test email/i })).toBeDefined()
|
||||
})
|
||||
|
||||
it('enables form inputs when enable switch is toggled', async () => {
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
|
||||
})
|
||||
|
||||
const hostInput = screen.getByLabelText(/smtp host/i) as HTMLInputElement
|
||||
expect(hostInput.disabled).toBe(true)
|
||||
|
||||
// Toggle the enable switch
|
||||
const enableSwitch = screen.getByRole('switch', { name: /enable email notifications/i })
|
||||
fireEvent.click(enableSwitch)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(hostInput.disabled).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
it('saves settings successfully when Save button is clicked', async () => {
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
|
||||
})
|
||||
|
||||
// Enable first
|
||||
const enableSwitch = screen.getByRole('switch', { name: /enable email notifications/i })
|
||||
fireEvent.click(enableSwitch)
|
||||
|
||||
// Edit host
|
||||
const hostInput = screen.getByLabelText(/smtp host/i)
|
||||
fireEvent.change(hostInput, { target: { value: 'mail.mycompany.com' } })
|
||||
|
||||
// Click Save
|
||||
const saveButton = screen.getByRole('button', { name: /^save$/i })
|
||||
fireEvent.click(saveButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPutSettings).toHaveBeenCalledWith({
|
||||
param: { teamId: 'team-1' },
|
||||
json: expect.objectContaining({
|
||||
enabled: true,
|
||||
host: 'mail.mycompany.com',
|
||||
port: 587,
|
||||
}),
|
||||
})
|
||||
expect(toast.success).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('shows error toast when save fails', async () => {
|
||||
mockPutSettings.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => ({ message: 'Invalid SMTP configuration' }),
|
||||
})
|
||||
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
|
||||
})
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /^save$/i })
|
||||
fireEvent.click(saveButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith('Invalid SMTP configuration')
|
||||
})
|
||||
})
|
||||
|
||||
it('saves settings first and opens TestEmailDialog on "Save & Send Test Email"', async () => {
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
|
||||
})
|
||||
|
||||
// Enable switch so button is active
|
||||
const enableSwitch = screen.getByRole('switch', { name: /enable email notifications/i })
|
||||
fireEvent.click(enableSwitch)
|
||||
|
||||
const saveAndTestButton = screen.getByRole('button', { name: /save & send test email/i })
|
||||
fireEvent.click(saveAndTestButton)
|
||||
|
||||
// Should call save first
|
||||
await waitFor(() => {
|
||||
expect(mockPutSettings).toHaveBeenCalled()
|
||||
expect(toast.success).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// Mock dialog should be opened with defaultFrom
|
||||
await waitFor(() => {
|
||||
const dialog = screen.getByTestId('mock-test-email-dialog')
|
||||
expect(dialog).toBeDefined()
|
||||
expect(dialog.getAttribute('data-from')).toBe('Shumai <noreply@example.com>')
|
||||
})
|
||||
})
|
||||
|
||||
it('validates required host when clicking "Save & Send Test Email"', async () => {
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ ...initialSettings, host: '' }),
|
||||
})
|
||||
|
||||
renderComponent()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
|
||||
})
|
||||
|
||||
const enableSwitch = screen.getByRole('switch', { name: /enable email notifications/i })
|
||||
fireEvent.click(enableSwitch)
|
||||
|
||||
const saveAndTestButton = screen.getByRole('button', { name: /save & send test email/i })
|
||||
fireEvent.click(saveAndTestButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/host is required/i))
|
||||
expect(mockPutSettings).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,348 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { Card, CardContent, CardFooter } from '@/ui/components/ui/card'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { EmailNotificationSettings as Settings } from '@shumai/dtos'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { TestEmailDialog } from '@/ui/components/settings/TestEmailDialog'
|
||||
|
||||
interface EmailNotificationSettingsProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export function EmailNotificationSettings({ teamId }: EmailNotificationSettingsProps) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const [formData, setFormData] = useState<Settings>({
|
||||
enabled: false,
|
||||
host: '',
|
||||
port: 587,
|
||||
username: '',
|
||||
password: '',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: '',
|
||||
replyTo: '',
|
||||
})
|
||||
|
||||
const [isTestDialogOpen, setIsTestDialogOpen] = useState(false)
|
||||
|
||||
const {
|
||||
data: settings,
|
||||
isLoading,
|
||||
error,
|
||||
} = useQuery<Settings>({
|
||||
queryKey: ['teams', teamId, 'email-settings'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].notifications.email.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_load_email_settings())
|
||||
return (await res.json()) as Settings
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (settings) {
|
||||
setFormData({
|
||||
enabled: settings.enabled ?? false,
|
||||
host: settings.host ?? '',
|
||||
port: settings.port ?? 587,
|
||||
username: settings.username ?? '',
|
||||
password: '',
|
||||
smtps: settings.smtps ?? false,
|
||||
ignoreCert: settings.ignoreCert ?? false,
|
||||
from: settings.from ?? '',
|
||||
replyTo: settings.replyTo ?? '',
|
||||
})
|
||||
}
|
||||
}, [settings])
|
||||
|
||||
const { mutateAsync: saveSettings, isPending: isSaving } = useMutation({
|
||||
mutationFn: async (dataToSave: Settings) => {
|
||||
const res = await client.api.teams[':teamId'].notifications.email.$put({
|
||||
param: { teamId },
|
||||
json: {
|
||||
enabled: dataToSave.enabled,
|
||||
host: dataToSave.host,
|
||||
port: dataToSave.port,
|
||||
username: dataToSave.username || '',
|
||||
password: dataToSave.password || '',
|
||||
smtps: dataToSave.smtps,
|
||||
ignoreCert: dataToSave.ignoreCert,
|
||||
from: dataToSave.from,
|
||||
replyTo: dataToSave.replyTo || '',
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => null)) as { message?: string } | null
|
||||
throw new Error(err?.message || m.failed_to_save_email_settings())
|
||||
}
|
||||
return (await res.json()) as Settings
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'email-settings'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'settings'] })
|
||||
},
|
||||
})
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await saveSettings(formData)
|
||||
toast.success(m.email_settings_saved())
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_to_save_email_settings())
|
||||
}
|
||||
}
|
||||
|
||||
const handleSaveAndTest = async () => {
|
||||
if (!formData.host.trim()) {
|
||||
toast.error(m.smtp_host_required())
|
||||
return
|
||||
}
|
||||
try {
|
||||
await saveSettings(formData)
|
||||
toast.success(m.email_settings_saved())
|
||||
setIsTestDialogOpen(true)
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_to_save_email_settings())
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="p-8 text-center text-destructive">
|
||||
{error instanceof Error ? error.message : m.failed_to_load_email_settings()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ScrollArea className="h-full">
|
||||
<div className="space-y-6 pr-4 pb-8">
|
||||
<Card>
|
||||
<CardContent className="space-y-6 pt-6">
|
||||
{/* Enable Switch */}
|
||||
<div className="flex items-center justify-between space-x-4 rounded-lg border border-border p-4">
|
||||
<div className="space-y-1">
|
||||
<label
|
||||
htmlFor="enable-email-switch"
|
||||
className="text-sm font-medium leading-none cursor-pointer"
|
||||
>
|
||||
{m.enable_email_notifications()}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{m.enable_email_notifications_description()}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="enable-email-switch"
|
||||
checked={formData.enabled}
|
||||
onCheckedChange={(checked) => setFormData({ ...formData, enabled: checked })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* SMTP Server Settings */}
|
||||
<div className="space-y-4 pt-2">
|
||||
<h4 className="text-sm font-semibold text-foreground">{m.smtp_settings()}</h4>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<label
|
||||
htmlFor="smtp-host-input"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
{m.smtp_host()}
|
||||
</label>
|
||||
<Input
|
||||
id="smtp-host-input"
|
||||
value={formData.host}
|
||||
onChange={(e) => setFormData({ ...formData, host: e.target.value })}
|
||||
placeholder={m.smtp_host_placeholder()}
|
||||
disabled={!formData.enabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="smtp-port-input"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
{m.smtp_port()}
|
||||
</label>
|
||||
<Input
|
||||
id="smtp-port-input"
|
||||
type="number"
|
||||
value={formData.port}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
port: parseInt(e.target.value, 10) || 587,
|
||||
})
|
||||
}
|
||||
disabled={!formData.enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="smtp-username-input"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
{m.smtp_username()}
|
||||
</label>
|
||||
<Input
|
||||
id="smtp-username-input"
|
||||
value={formData.username || ''}
|
||||
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
||||
placeholder={m.smtp_username_placeholder()}
|
||||
disabled={!formData.enabled}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="smtp-password-input"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
{m.smtp_password()}
|
||||
</label>
|
||||
<Input
|
||||
id="smtp-password-input"
|
||||
type="password"
|
||||
value={formData.password || ''}
|
||||
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||
placeholder={
|
||||
settings?.password
|
||||
? m.smtp_password_keep_placeholder()
|
||||
: m.smtp_password_placeholder()
|
||||
}
|
||||
disabled={!formData.enabled}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
|
||||
<div className="flex items-center justify-between space-x-4 rounded-lg border border-border p-4">
|
||||
<div className="space-y-1">
|
||||
<label
|
||||
htmlFor="smtps-switch"
|
||||
className="text-sm font-medium leading-none cursor-pointer"
|
||||
>
|
||||
{m.smtp_secure()}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground">{m.smtp_secure_description()}</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="smtps-switch"
|
||||
checked={formData.smtps}
|
||||
onCheckedChange={(checked) => setFormData({ ...formData, smtps: checked })}
|
||||
disabled={!formData.enabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between space-x-4 rounded-lg border border-border p-4">
|
||||
<div className="space-y-1">
|
||||
<label
|
||||
htmlFor="ignore-cert-switch"
|
||||
className="text-sm font-medium leading-none cursor-pointer"
|
||||
>
|
||||
{m.smtp_ignore_cert()}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{m.smtp_ignore_cert_description()}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="ignore-cert-switch"
|
||||
checked={formData.ignoreCert}
|
||||
onCheckedChange={(checked) =>
|
||||
setFormData({ ...formData, ignoreCert: checked })
|
||||
}
|
||||
disabled={!formData.enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sender Information */}
|
||||
<div className="space-y-4 pt-4 border-t border-border">
|
||||
<h4 className="text-sm font-semibold text-foreground">{m.sender_settings()}</h4>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="sender-from-input"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
{m.sender_from()}
|
||||
</label>
|
||||
<Input
|
||||
id="sender-from-input"
|
||||
value={formData.from}
|
||||
onChange={(e) => setFormData({ ...formData, from: e.target.value })}
|
||||
placeholder="Shumai <noreply@example.com>"
|
||||
disabled={!formData.enabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{m.sender_from_description()}</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="sender-reply-to-input"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
{m.sender_reply_to()}
|
||||
</label>
|
||||
<Input
|
||||
id="sender-reply-to-input"
|
||||
value={formData.replyTo || ''}
|
||||
onChange={(e) => setFormData({ ...formData, replyTo: e.target.value })}
|
||||
placeholder="noreply@example.com"
|
||||
disabled={!formData.enabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{m.sender_reply_to_description()}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="flex flex-col sm:flex-row items-center justify-end gap-3 border-t border-border p-6 bg-muted/20">
|
||||
<Button variant="outline" onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
|
||||
{m.save()}
|
||||
</Button>
|
||||
<Button onClick={handleSaveAndTest} disabled={isSaving || !formData.enabled}>
|
||||
{isSaving && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
|
||||
{m.save_and_send_test_email()}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<TestEmailDialog
|
||||
isOpen={isTestDialogOpen}
|
||||
onClose={() => setIsTestDialogOpen(false)}
|
||||
teamId={teamId}
|
||||
defaultFrom={formData.from}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { TestEmailDialog } from './TestEmailDialog'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const mockPostTestEmail = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
notifications: {
|
||||
email: {
|
||||
test: {
|
||||
$post: (args: unknown) => mockPostTestEmail(args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('TestEmailDialog', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockPostTestEmail.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ success: true, messageId: '<msg-123@example.com>' }),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
function renderDialog(props?: Partial<React.ComponentProps<typeof TestEmailDialog>>) {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TestEmailDialog
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
teamId="team-1"
|
||||
defaultFrom="Shumai <noreply@example.com>"
|
||||
{...props}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
it('renders dialog title, description and pre-filled from address', () => {
|
||||
renderDialog()
|
||||
|
||||
expect(screen.getByRole('heading', { name: /send test email/i })).toBeDefined()
|
||||
expect(
|
||||
screen.getByText(
|
||||
/Sender email address, for example: "Shumai <noreply@example\.com>"\. Make sure to use an address you're allowed to send emails from\./i,
|
||||
),
|
||||
).toBeDefined()
|
||||
|
||||
const input = screen.getByLabelText(/from address/i) as HTMLInputElement
|
||||
expect(input.value).toBe('Shumai <noreply@example.com>')
|
||||
})
|
||||
|
||||
it('validates from address when empty', async () => {
|
||||
renderDialog({ defaultFrom: '' })
|
||||
|
||||
const sendBtn = screen.getByRole('button', { name: /send test email/i })
|
||||
fireEvent.click(sendBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/from address is required/i))
|
||||
expect(mockPostTestEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('sends test email successfully and calls onClose', async () => {
|
||||
renderDialog()
|
||||
|
||||
const input = screen.getByLabelText(/from address/i)
|
||||
fireEvent.change(input, { target: { value: 'Admin <admin@test.com>' } })
|
||||
|
||||
const sendBtn = screen.getByRole('button', { name: /send test email/i })
|
||||
fireEvent.click(sendBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPostTestEmail).toHaveBeenCalledWith({
|
||||
param: { teamId: 'team-1' },
|
||||
json: { from: 'Admin <admin@test.com>' },
|
||||
})
|
||||
expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/test email sent/i))
|
||||
expect(mockOnClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('handles send test email API error', async () => {
|
||||
mockPostTestEmail.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => ({ message: 'SMTP verification failed: Connection refused' }),
|
||||
})
|
||||
|
||||
renderDialog()
|
||||
|
||||
const sendBtn = screen.getByRole('button', { name: /send test email/i })
|
||||
fireEvent.click(sendBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith('SMTP verification failed: Connection refused')
|
||||
expect(mockOnClose).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('calls onClose when Cancel button is clicked', () => {
|
||||
renderDialog()
|
||||
|
||||
const cancelBtn = screen.getByRole('button', { name: /cancel/i })
|
||||
fireEvent.click(cancelBtn)
|
||||
|
||||
expect(mockOnClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Loader2, Send } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
export interface TestEmailDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
teamId: string
|
||||
defaultFrom?: string
|
||||
}
|
||||
|
||||
export function TestEmailDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
teamId,
|
||||
defaultFrom = '',
|
||||
}: TestEmailDialogProps) {
|
||||
const [fromAddress, setFromAddress] = useState(defaultFrom)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setFromAddress(defaultFrom)
|
||||
}
|
||||
}, [defaultFrom, isOpen])
|
||||
|
||||
const { mutateAsync: sendTestEmail, isPending: isSending } = useMutation({
|
||||
mutationFn: async (from: string) => {
|
||||
const res = await client.api.teams[':teamId'].notifications.email.test.$post({
|
||||
param: { teamId },
|
||||
json: { from },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => null)) as { message?: string } | null
|
||||
throw new Error(err?.message || m.failed_to_send_test_email())
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!fromAddress.trim()) {
|
||||
toast.error(m.from_address_required())
|
||||
return
|
||||
}
|
||||
try {
|
||||
await sendTestEmail(fromAddress.trim())
|
||||
toast.success(m.test_email_sent_successfully())
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_to_send_test_email())
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Send className="w-5 h-5 text-primary" />
|
||||
<DialogTitle>{m.send_test_email()}</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription>{m.send_test_email_dialog_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="test-dialog-from-input" className="text-sm font-medium text-foreground">
|
||||
{m.sender_from()}
|
||||
</label>
|
||||
<Input
|
||||
id="test-dialog-from-input"
|
||||
value={fromAddress}
|
||||
onChange={(e) => setFromAddress(e.target.value)}
|
||||
placeholder="Shumai <noreply@example.com>"
|
||||
disabled={isSending}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2 sm:gap-0">
|
||||
<Button variant="outline" onClick={onClose} disabled={isSending}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button onClick={handleSend} disabled={isSending}>
|
||||
{isSending && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
|
||||
{m.send_test_email()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user