mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 19:34:38 +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>
|
||||
)
|
||||
}
|
||||
@@ -295,6 +295,39 @@
|
||||
"kanban_comments": "Kanban Comments",
|
||||
"when_kanban_task_commented": "When someone comments on a task",
|
||||
|
||||
"email_notifications": "Email Notifications",
|
||||
"email_notifications_description": "Configure SMTP settings for sending email notifications to team members.",
|
||||
"enable_email_notifications": "Enable Email Notifications",
|
||||
"enable_email_notifications_description": "Send email notifications for comments, mentions, uploads, and other team activity.",
|
||||
"smtp_settings": "SMTP Server Settings",
|
||||
"smtp_host": "SMTP Host",
|
||||
"smtp_host_placeholder": "e.g. smtp.example.com",
|
||||
"smtp_port": "SMTP Port",
|
||||
"smtp_username": "Username",
|
||||
"smtp_username_placeholder": "e.g. user@example.com",
|
||||
"smtp_password": "Password",
|
||||
"smtp_password_placeholder": "Enter SMTP password",
|
||||
"smtp_password_keep_placeholder": "•••••••• (Leave blank to keep current)",
|
||||
"smtp_secure": "SSL / TLS (SMTPS)",
|
||||
"smtp_secure_description": "Connect directly over SSL/TLS (commonly used with port 465).",
|
||||
"smtp_ignore_cert": "Ignore Certificate Errors",
|
||||
"smtp_ignore_cert_description": "Allow self-signed or unverified SSL/TLS certificates.",
|
||||
"sender_settings": "Sender Information",
|
||||
"sender_from": "From Address",
|
||||
"sender_from_description": "Sender email address, for example: \"Shumai <noreply@example.com>\". Make sure to use an address you're allowed to send emails from.",
|
||||
"sender_reply_to": "Reply-To Address",
|
||||
"sender_reply_to_description": "Optional address where replies to notifications should be directed.",
|
||||
"save_and_send_test_email": "Save & Send Test Email",
|
||||
"send_test_email": "Send Test Email",
|
||||
"send_test_email_dialog_description": "Sender email address, for example: \"Shumai <noreply@example.com>\". Make sure to use an address you're allowed to send emails from.",
|
||||
"test_email_sent_successfully": "Test email sent successfully",
|
||||
"failed_to_send_test_email": "Failed to send test email",
|
||||
"email_settings_saved": "Email settings saved successfully",
|
||||
"failed_to_save_email_settings": "Failed to save email settings",
|
||||
"failed_to_load_email_settings": "Failed to load email settings",
|
||||
"smtp_host_required": "SMTP Host is required",
|
||||
"from_address_required": "From address is required",
|
||||
|
||||
"api_tokens": "API Tokens",
|
||||
"api_tokens_description": "Generate and manage API tokens. These tokens allow you or your agents to run terminal commands via shumai-cli.",
|
||||
"developer_settings": "Developer Settings",
|
||||
|
||||
@@ -295,6 +295,39 @@
|
||||
"kanban_comments": "看板评论",
|
||||
"when_kanban_task_commented": "当有人在任务中发表评论时",
|
||||
|
||||
"email_notifications": "邮件通知",
|
||||
"email_notifications_description": "配置用于向团队成员发送邮件通知的 SMTP 设置。",
|
||||
"enable_email_notifications": "启用邮件通知",
|
||||
"enable_email_notifications_description": "当有评论、提及、上传及其他团队活动时发送邮件通知。",
|
||||
"smtp_settings": "SMTP 服务器设置",
|
||||
"smtp_host": "SMTP 主机",
|
||||
"smtp_host_placeholder": "例如 smtp.example.com",
|
||||
"smtp_port": "SMTP 端口",
|
||||
"smtp_username": "用户名",
|
||||
"smtp_username_placeholder": "例如 user@example.com",
|
||||
"smtp_password": "密码",
|
||||
"smtp_password_placeholder": "输入 SMTP 密码",
|
||||
"smtp_password_keep_placeholder": "••••••••(留空以保持当前密码)",
|
||||
"smtp_secure": "SSL / TLS (SMTPS)",
|
||||
"smtp_secure_description": "直接使用 SSL/TLS 连接(通常用于 465 端口)。",
|
||||
"smtp_ignore_cert": "忽略证书错误",
|
||||
"smtp_ignore_cert_description": "允许自签名或未验证的 SSL/TLS 证书。",
|
||||
"sender_settings": "发件人信息",
|
||||
"sender_from": "发件人地址",
|
||||
"sender_from_description": "发件人邮箱地址,例如:“Shumai <noreply@example.com>”。请确保使用您有权使用的邮箱地址进行发送。",
|
||||
"sender_reply_to": "回复地址",
|
||||
"sender_reply_to_description": "通知邮件回复时指向的可选邮箱地址。",
|
||||
"save_and_send_test_email": "保存并发送测试邮件",
|
||||
"send_test_email": "发送测试邮件",
|
||||
"send_test_email_dialog_description": "发件人邮箱地址,例如:“Shumai <noreply@example.com>”。请确保使用您有权使用的邮箱地址进行发送。",
|
||||
"test_email_sent_successfully": "测试邮件发送成功",
|
||||
"failed_to_send_test_email": "发送测试邮件失败",
|
||||
"email_settings_saved": "邮件设置已保存",
|
||||
"failed_to_save_email_settings": "保存邮件设置失败",
|
||||
"failed_to_load_email_settings": "加载邮件设置失败",
|
||||
"smtp_host_required": "必须提供 SMTP 主机",
|
||||
"from_address_required": "必须提供发件人地址",
|
||||
|
||||
"api_tokens": "API 令牌",
|
||||
"api_tokens_description": "生成和管理 API 令牌。这些令牌允许您或您的智能体通过 shumai-cli 运行终端命令。",
|
||||
"developer_settings": "开发者设置",
|
||||
|
||||
@@ -15,6 +15,7 @@ import { NotificationSettings } from '@/ui/components/settings/NotificationSetti
|
||||
import { DeveloperSettings } from '@/ui/components/settings/DeveloperSettings'
|
||||
import { QuotasSettings } from '@/ui/components/settings/QuotasSettings'
|
||||
import { AppearanceSettings } from '@/ui/components/settings/AppearanceSettings'
|
||||
import { EmailNotificationSettings } from '@/ui/components/settings/EmailNotificationSettings'
|
||||
import { ImageVideoGenerationSettings } from '@/ui/components/settings/ImageVideoGenerationSettings'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { Slider } from '@/ui/components/ui/slider'
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
Cpu,
|
||||
Film,
|
||||
Loader2,
|
||||
Mail,
|
||||
Puzzle,
|
||||
Server,
|
||||
Shield,
|
||||
@@ -57,6 +59,7 @@ type SettingsTab =
|
||||
| 'transcode'
|
||||
| 'quotas'
|
||||
| 'appearance'
|
||||
| 'email'
|
||||
| 'skills'
|
||||
| 'mcp'
|
||||
| 'providers'
|
||||
@@ -71,6 +74,7 @@ const VALID_SETTINGS_TABS: readonly SettingsTab[] = [
|
||||
'transcode',
|
||||
'quotas',
|
||||
'appearance',
|
||||
'email',
|
||||
'skills',
|
||||
'mcp',
|
||||
'providers',
|
||||
@@ -173,6 +177,7 @@ function TeamSettingsPage() {
|
||||
'transcode',
|
||||
'quotas',
|
||||
'appearance',
|
||||
'email',
|
||||
'providers',
|
||||
'image-video',
|
||||
'skills',
|
||||
@@ -468,6 +473,22 @@ function TeamSettingsPage() {
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleTabChange('email')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'email'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Mail className="w-5 h-5" />
|
||||
{m.email_notifications()}
|
||||
{activeTab === 'email' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -588,6 +609,7 @@ function TeamSettingsPage() {
|
||||
{activeTab === 'transcode' && m.media_processing()}
|
||||
{activeTab === 'quotas' && m.resource_quotas()}
|
||||
{activeTab === 'appearance' && m.appearance_settings()}
|
||||
{activeTab === 'email' && m.email_notifications()}
|
||||
{activeTab === 'skills' && m.skills_management()}
|
||||
{activeTab === 'mcp' && m.mcp_servers()}
|
||||
{activeTab === 'providers' && m.ai_providers()}
|
||||
@@ -602,6 +624,7 @@ function TeamSettingsPage() {
|
||||
{activeTab === 'transcode' && m.transcode_description()}
|
||||
{activeTab === 'quotas' && m.resource_quotas_description()}
|
||||
{activeTab === 'appearance' && m.appearance_settings_description()}
|
||||
{activeTab === 'email' && m.email_notifications_description()}
|
||||
{activeTab === 'skills' && m.skills_description()}
|
||||
{activeTab === 'mcp' && m.mcp_servers_description()}
|
||||
{activeTab === 'providers' && m.providers_description()}
|
||||
@@ -908,6 +931,8 @@ function TeamSettingsPage() {
|
||||
{activeTab === 'quotas' && <QuotasSettings teamId={teamId} />}
|
||||
|
||||
{activeTab === 'appearance' && <AppearanceSettings teamId={teamId} />}
|
||||
|
||||
{activeTab === 'email' && <EmailNotificationSettings teamId={teamId} />}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
Reference in New Issue
Block a user