阶段七:完成Notifications React feature化与渠道绑定边界

This commit is contained in:
Christ committed 2026-08-15 01:21:47 +08:00
1 parent b128ce60db
commit 2ec7bec05f
20 files changed
+1338 -1785

No files matched your search

@@ -0,0 +1,11 @@
export {
createNotificationChannel,
deleteNotificationChannel,
getNotificationChannels,
getSystemSettings,
testNotificationChannel,
updateNotificationChannel,
updateSystemSettings,
} from '../../../services/api';
// notifications feature 通过本适配层声明渠道和 SMTP API 的来源。
@@ -0,0 +1,97 @@
import React from 'react';
import { Bell, Edit2, Loader2, Send, Trash2 } from 'lucide-react';
import type { NotificationChannel } from '../../../../types';
import { notificationChannelTypes, notificationEventSummary } from '../state';
// NotificationChannelListProps 描述通知渠道列表的操作边界。
export interface NotificationChannelListProps {
// channels 是当前可展示的通知渠道。
channels: NotificationChannel[];
// testingId 是当前正在测试发送的渠道 ID。
testingId: string;
// onEdit 打开指定渠道的编辑弹窗。
onEdit: (channel: NotificationChannel) => void;
// onDelete 删除指定渠道。
onDelete: (channel: NotificationChannel) => void | Promise<void>;
// onToggleEnabled 切换指定渠道的启用状态。
onToggleEnabled: (channel: NotificationChannel) => void | Promise<void>;
// onTest 发送指定渠道的测试通知。
onTest: (channel: NotificationChannel) => void | Promise<void>;
}
// NotificationChannelList 渲染渠道摘要、启用状态和操作按钮。
export const NotificationChannelList: React.FC<NotificationChannelListProps> = ({ channels, testingId, onEdit, onDelete, onToggleEnabled, onTest }) => {
// findChannel 从按钮数据属性中查找对应渠道。
const findChannel = (event: React.MouseEvent<HTMLButtonElement>): NotificationChannel | null => channels.find(
// channel 是当前待匹配的渠道数据。
channel => channel.id === event.currentTarget.dataset.channelId,
) || null;
// handleToggleClick 处理渠道启用状态按钮点击。
const handleToggleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
// channel 是按钮对应的渠道数据。
const channel = findChannel(event);
if (channel) void onToggleEnabled(channel);
};
// handleTestClick 处理渠道测试按钮点击。
const handleTestClick = (event: React.MouseEvent<HTMLButtonElement>) => {
// channel 是按钮对应的渠道数据。
const channel = findChannel(event);
if (channel) void onTest(channel);
};
// handleEditClick 处理渠道编辑按钮点击。
const handleEditClick = (event: React.MouseEvent<HTMLButtonElement>) => {
// channel 是按钮对应的渠道数据。
const channel = findChannel(event);
if (channel) onEdit(channel);
};
// handleDeleteClick 处理渠道删除按钮点击。
const handleDeleteClick = (event: React.MouseEvent<HTMLButtonElement>) => {
// channel 是按钮对应的渠道数据。
const channel = findChannel(event);
if (channel) void onDelete(channel);
};
// renderChannel 渲染单个通知渠道卡片。
const renderChannel = (channel: NotificationChannel) => {
// meta 是当前渠道类型的静态展示配置。
const meta = notificationChannelTypes[channel.type] || notificationChannelTypes.webhook;
// Icon 是当前渠道类型对应的图标组件。
const Icon = meta.icon;
return (
<div key={channel.id} className="ios-card rounded-xl p-5 bg-white flex items-center gap-4">
<div className="w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0"><Icon className="w-5 h-5 text-gray-600" /></div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-bold text-gray-900 truncate">{channel.name}</span>
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium">{meta.label}</span>
{!channel.enabled && <span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium">已停用</span>}
</div>
<div className="text-xs text-gray-500 mt-1 truncate">
{meta.fields.map(
// field 是当前渠道摘要需要读取的配置字段。
field => channel.config?.[field.key],
).filter(Boolean).map(
// value 是渠道配置中非空的摘要值。
(value, index) => <span key={index} className="mr-3">{String(value).length > 40 ? `${String(value).slice(0, 40)}…` : String(value)}</span>,
)}
</div>
<div className="text-xs text-gray-400 mt-1 truncate">订阅:{notificationEventSummary(channel.event_types)}</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<button data-channel-id={channel.id} onClick={handleToggleClick} className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${channel.enabled ? 'bg-green-50 text-green-700 hover:bg-green-100' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'}`}>
{channel.enabled ? '启用中' : '已停用'}
</button>
<button data-channel-id={channel.id} onClick={handleTestClick} disabled={testingId === channel.id} className="px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50">
{testingId === channel.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <Send className="w-3 h-3" />}测试
</button>
<button data-channel-id={channel.id} onClick={handleEditClick} className="w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors" title="编辑"><Edit2 className="w-4 h-4" /></button>
<button data-channel-id={channel.id} onClick={handleDeleteClick} className="w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors" title="删除"><Trash2 className="w-4 h-4" /></button>
</div>
</div>
);
};
if (channels.length === 0) {
return <div className="ios-card rounded-xl p-12 bg-white text-center"><Bell className="w-12 h-12 text-gray-300 mx-auto mb-4" /><p className="text-gray-500 font-medium">还没有配置任何通知渠道</p><p className="text-gray-400 text-sm mt-1">点击右上角「新建渠道」开始配置</p></div>;
}
return <div className="space-y-3">{channels.map(renderChannel)}</div>;
};
@@ -0,0 +1,153 @@
import React from 'react';
import { createPortal } from 'react-dom';
import { Bell, Check, Eye, EyeOff, Loader2, X } from 'lucide-react';
import { enableCustomSMTP } from '../../../../notificationEmailConfig';
import { notificationChannelTypes } from '../state';
import { NotificationEventSelector } from './NotificationEventSelector';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../types';
import type { NotificationForm } from '../types';
// NotificationChannelModalProps 描述渠道编辑弹窗所需的状态和回调。
export interface NotificationChannelModalProps {
// showModal 表示弹窗是否打开。
showModal: boolean;
// editing 表示当前编辑的渠道,新增时为空。
editing: NotificationChannel | null;
// form 是当前渠道表单值。
form: NotificationForm;
// setForm 更新渠道表单值。
setForm: React.Dispatch<React.SetStateAction<NotificationForm>>;
// smtp 是系统 SMTP 配置,用于填充独立 SMTP 初始值。
smtp: SystemSettings;
// showChannelSmtpPassword 表示是否显示独立 SMTP 密码。
showChannelSmtpPassword: boolean;
// setShowChannelSmtpPassword 切换独立 SMTP 密码显示状态。
setShowChannelSmtpPassword: React.Dispatch<React.SetStateAction<boolean>>;
// saving 表示渠道保存请求是否正在执行。
saving: boolean;
// onClose 关闭弹窗。
onClose: () => void;
// onSave 提交渠道表单。
onSave: () => void | Promise<void>;
}
// NotificationChannelModal 渲染渠道字段、SMTP 覆盖项和事件绑定表单。
export const NotificationChannelModal: React.FC<NotificationChannelModalProps> = ({ showModal, editing, form, setForm, smtp, showChannelSmtpPassword, setShowChannelSmtpPassword, saving, onClose, onSave }) => {
// meta 是当前渠道类型对应的字段和指南。
const meta = notificationChannelTypes[form.type];
// handleNameChange 更新渠道名称。
const handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => setForm(
// nextFormUpdater 使用函数式更新名称字段。
current => ({ ...current, name: event.target.value }),
);
// handleTypeChange 切换渠道类型并清空旧类型配置。
const handleTypeChange = (event: React.MouseEvent<HTMLButtonElement>) => {
// type 是按钮数据属性中的目标渠道类型。
const type = event.currentTarget.dataset.type as NotificationChannelType | undefined;
if (!type) return;
setForm(
// nextFormUpdater 使用函数式更新渠道类型。
current => ({ ...current, type, config: {} }),
);
};
// handleConfigFieldChange 更新普通或独立 SMTP 配置字段。
const handleConfigFieldChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// key 是输入框数据属性中的配置字段名。
const key = event.currentTarget.dataset.field;
if (!key) return;
setForm(
// nextFormUpdater 使用函数式更新配置字段。
current => ({ ...current, config: { ...current.config, [key]: event.target.value } }),
);
};
// handleToggleCustomSMTP 切换邮件渠道是否使用独立 SMTP。
const handleToggleCustomSMTP = () => setForm(
// nextFormUpdater 使用函数式更新 SMTP 来源模式。
current => ({ ...current, config: current.config.use_custom_smtp === true ? { ...current.config, use_custom_smtp: false } : enableCustomSMTP(current.config, smtp) }),
);
// handleChannelTlsChange 切换独立 SMTP 的 STARTTLS 并保持模式互斥。
const handleChannelTlsChange = (event: React.ChangeEvent<HTMLInputElement>) => setForm(
// nextFormUpdater 使用函数式更新独立 SMTP 的 TLS/SSL 互斥字段。
current => ({ ...current, config: { ...current.config, smtp_use_tls: event.target.checked, smtp_use_ssl: event.target.checked ? false : current.config.smtp_use_ssl } }),
);
// handleChannelSslChange 切换独立 SMTP 的 SSL 并保持模式互斥。
const handleChannelSslChange = (event: React.ChangeEvent<HTMLInputElement>) => setForm(
// nextFormUpdater 使用函数式更新独立 SMTP 的 SSL/TLS 互斥字段。
current => ({ ...current, config: { ...current.config, smtp_use_ssl: event.target.checked, smtp_use_tls: event.target.checked ? false : current.config.smtp_use_tls } }),
);
// handleToggleEvent 使用函数式更新切换事件绑定。
const handleToggleEvent = (event: NotificationEventType) => setForm(
// nextFormUpdater 使用函数式更新事件绑定集合。
current => ({ ...current, event_types: current.event_types.includes(event) ? current.event_types.filter(
// item 是待保留的已有事件值。
item => item !== event,
) : [...current.event_types, event] }),
);
// handleToggleEnabled 使用函数式更新切换渠道启用状态。
const handleToggleEnabled = () => setForm(
// nextFormUpdater 使用函数式更新启用状态。
current => ({ ...current, enabled: !current.enabled }),
);
// handleToggleChannelPassword 切换独立 SMTP 密码明文显示。
const handleToggleChannelPassword = () => setShowChannelSmtpPassword(
// nextPasswordState 使用函数式更新密码显示状态。
value => !value,
);
// renderGuideStep 渲染当前渠道指南中的单个步骤。
const renderGuideStep = (step: string, index: number) => <li key={index}>{step}</li>;
if (!showModal) return null;
return createPortal(
<div className="modal-overlay">
<div className="modal-container" style={{ maxWidth: '36rem' }}>
<div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between"><h3 className="text-xl font-extrabold text-gray-900">{editing ? '编辑通知渠道' : '新建通知渠道'}</h3><button onClick={onClose} className="w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center"><X className="w-5 h-5 text-gray-600" /></button></div>
<div className="px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0">
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">渠道名称</label><input type="text" value={form.name} onChange={handleNameChange} placeholder="例如:我的 Bark" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">渠道类型</label>
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
{(Object.keys(notificationChannelTypes) as NotificationChannelType[]).map(
// type 是当前渠道类型选择项。
type => {
// channelMeta 是当前类型的展示元数据。
const channelMeta = notificationChannelTypes[type];
// TypeIcon 是当前类型的图标组件。
const TypeIcon = channelMeta.icon;
// selected 表示当前类型是否已选中。
const selected = form.type === type;
return <button key={type} data-type={type} type="button" onClick={handleTypeChange} className={`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${selected ? 'border-brand bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}><TypeIcon className={`w-5 h-5 ${selected ? 'text-brand' : 'text-gray-500'}`} /><span className={`text-xs font-bold ${selected ? 'text-brand' : 'text-gray-600'}`}>{channelMeta.label}</span></button>;
},
)}
</div>
</div>
<div className="rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2"><div className="flex items-center gap-2"><Bell className="w-4 h-4 text-amber-600" /><span className="text-sm font-bold text-amber-800">如何获取 {meta.label} 配置?</span></div><ol className="space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5">{meta.guide.steps.map(renderGuideStep)}</ol>{meta.guide.urlFormat && <div className="text-xs text-amber-900/90"><span className="font-bold">格式示例:</span><code className="mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]">{meta.guide.urlFormat}</code></div>}{meta.guide.note && <p className="text-xs text-amber-800/80 leading-5 pt-1">💡 {meta.guide.note}</p>}</div>
<div className="space-y-3">
{meta.fields.map(
// field 是当前渠道配置字段。
field => <div key={field.key} className="space-y-2"><label className="block text-sm font-bold text-gray-800">{field.label}{field.required && <span className="text-red-500 ml-1">*</span>}</label><input data-field={field.key} type={field.type === 'password' ? 'password' : field.type === 'number' ? 'number' : 'text'} value={String(form.config[field.key] || '')} onChange={handleConfigFieldChange} placeholder={field.placeholder} className="w-full ios-input px-4 py-3 rounded-xl text-sm" />{field.help && <p className="text-xs text-gray-500">{field.help}</p>}</div>,
)}
</div>
{form.type === 'email' && (
<div className="overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40">
<div className="flex items-center justify-between gap-4 p-4"><div><div className="text-sm font-extrabold text-gray-900">SMTP 来源</div><p className="mt-1 text-xs leading-5 text-gray-500">{form.config.use_custom_smtp === true ? '当前渠道使用一套完整、独立的发件配置。' : '当前渠道完整继承系统 SMTP,只单独设置收件邮箱。'}</p></div><button type="button" onClick={handleToggleCustomSMTP} className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-brand' : 'bg-gray-300'}`} aria-label="使用独立 SMTP"><span className={`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${form.config.use_custom_smtp === true ? 'translate-x-5' : ''}`} /></button></div>
{form.config.use_custom_smtp === true && (
<div className="space-y-4 border-t border-blue-100 bg-white/80 p-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"><div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 服务器 <span className="text-red-500">*</span></label><input data-field="smtp_server" type="text" value={String(form.config.smtp_server || '')} onChange={handleConfigFieldChange} placeholder="smtp.qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div><div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 端口 <span className="text-red-500">*</span></label><input data-field="smtp_port" type="number" value={String(form.config.smtp_port || 587)} onChange={handleConfigFieldChange} placeholder="587" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">登录邮箱 <span className="text-red-500">*</span></label><input data-field="smtp_user" type="email" value={String(form.config.smtp_user || '')} onChange={handleConfigFieldChange} placeholder="[email protected]" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">密码 / 授权码 <span className="text-red-500">*</span></label><div className="relative"><input data-field="smtp_password" type={showChannelSmtpPassword ? 'text' : 'password'} value={String(form.config.smtp_password || '')} onChange={handleConfigFieldChange} placeholder="输入密码或授权码" className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" /><button type="button" onClick={handleToggleChannelPassword} className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600">{showChannelSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}</button></div></div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"><div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label><input data-field="smtp_from_name" type="text" value={String(form.config.smtp_from_name || '')} onChange={handleConfigFieldChange} placeholder="闲鱼自动回复系统" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div><div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱地址 <span className="text-red-500">*</span></label><input data-field="smtp_from_address" type="email" value={String(form.config.smtp_from_address || '')} onChange={handleConfigFieldChange} placeholder="[email protected]" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div></div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2"><label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700"><input type="checkbox" checked={form.config.smtp_use_tls !== false} onChange={handleChannelTlsChange} />STARTTLS(常用于 587)</label><label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700"><input type="checkbox" checked={form.config.smtp_use_ssl === true} onChange={handleChannelSslChange} />SSL/TLS 直连(常用于 465)</label></div>
</div>
)}
</div>
)}
<NotificationEventSelector selectedEvents={form.event_types} onToggleEvent={handleToggleEvent} />
<label className="flex items-center gap-3 cursor-pointer"><button type="button" onClick={handleToggleEnabled} className={`relative w-11 h-6 rounded-full transition-colors ${form.enabled ? 'bg-brand' : 'bg-gray-300'}`}><span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${form.enabled ? 'translate-x-5' : ''}`} /></button><span className="text-sm font-bold text-gray-800">启用此渠道</span></label>
</div>
<div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3"><button onClick={onClose} className="px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors">取消</button><button onClick={onSave} disabled={saving} className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50">{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}{saving ? '保存中...' : '保存'}</button></div>
</div>
</div>,
document.body,
);
};
@@ -0,0 +1,57 @@
import React from 'react';
import { Check } from 'lucide-react';
import { notificationEvents } from '../state';
import type { NotificationEventType } from '../../../../types';
// NotificationEventSelectorProps 描述通知事件绑定组件的输入状态。
export interface NotificationEventSelectorProps {
// selectedEvents 是当前已选择的通知事件。
selectedEvents: NotificationEventType[];
// onToggleEvent 切换指定通知事件的绑定状态。
onToggleEvent: (event: NotificationEventType) => void;
}
// NotificationEventSelector 渲染通知渠道可订阅的事件列表。
export const NotificationEventSelector: React.FC<NotificationEventSelectorProps> = ({ selectedEvents, onToggleEvent }) => {
// handleEventClick 将用户点击的事件传回表单状态。
const handleEventClick = (event: React.MouseEvent<HTMLButtonElement>) => {
// eventValue 是按钮数据属性中的后端事件类型。
const eventValue = event.currentTarget.dataset.event as NotificationEventType | undefined;
if (eventValue) onToggleEvent(eventValue);
};
return (
<div className="space-y-3">
<div>
<label className="block text-sm font-bold text-gray-800">通知内容</label>
<p className="text-xs text-gray-500 mt-1">不选择表示接收全部通知;选择后仅接收勾选类型。</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{notificationEvents.map(
// event 是当前通知事件定义。
event => {
// checked 表示当前事件是否已被选中。
const checked = selectedEvents.includes(event.value);
return (
<button
key={event.value}
type="button"
data-event={event.value}
onClick={handleEventClick}
className={`text-left rounded-xl border px-3 py-2.5 transition-colors ${checked ? 'border-brand bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
>
<div className="flex items-center gap-2">
<span className={`w-4 h-4 rounded border flex items-center justify-center ${checked ? 'bg-brand border-brand' : 'border-gray-300'}`}>
{checked && <Check className="w-3 h-3 text-white" />}
</span>
<span className={`text-sm font-bold ${checked ? 'text-brand' : 'text-gray-800'}`}>{event.label}</span>
</div>
<p className="text-xs text-gray-500 mt-1 pl-6 leading-5">{event.description}</p>
</button>
);
},
)}
</div>
</div>
);
};
@@ -0,0 +1,97 @@
import React from 'react';
import { Eye, EyeOff, Loader2, Mail, Save } from 'lucide-react';
import type { SystemSettings } from '../../../../types';
// NotificationSmtpSettingsProps 描述系统 SMTP 配置面板所需的状态和事件。
export interface NotificationSmtpSettingsProps {
// smtp 是当前系统 SMTP 配置。
smtp: SystemSettings;
// setSmtp 更新 SMTP 配置字段。
setSmtp: React.Dispatch<React.SetStateAction<SystemSettings>>;
// smtpSaving 表示 SMTP 保存请求是否正在执行。
smtpSaving: boolean;
// showPassword 表示是否显示 SMTP 密码明文。
showPassword: boolean;
// setShowPassword 切换 SMTP 密码明文显示。
setShowPassword: React.Dispatch<React.SetStateAction<boolean>>;
// onSave 保存 SMTP 配置。
onSave: () => void | Promise<void>;
}
// NotificationSmtpSettings 渲染管理员可见的系统级 SMTP 设置。
export const NotificationSmtpSettings: React.FC<NotificationSmtpSettingsProps> = ({ smtp, setSmtp, smtpSaving, showPassword, setShowPassword, onSave }) => {
// handleTextChange 更新 SMTP 文本字段。
const handleTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// key 是文本输入框数据属性中的 SMTP 字段名。
const key = event.currentTarget.dataset.field as 'smtp_server' | 'smtp_user' | 'smtp_from_name' | 'smtp_from_address' | undefined;
if (!key) return;
setSmtp(
// nextSettingsUpdater 使用函数式更新避免覆盖并发输入。
current => ({ ...current, [key]: event.target.value }),
);
};
// handlePortChange 更新 SMTP 端口并在非法输入时回退默认端口。
const handlePortChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSmtp(
// nextSettingsUpdater 使用函数式更新端口字段。
current => ({ ...current, smtp_port: parseInt(event.target.value, 10) || 587 }),
);
};
// handleTlsChange 切换 STARTTLS 并保持 TLS 与 SSL 互斥。
const handleTlsChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSmtp(
// nextSettingsUpdater 使用函数式更新 TLS/SSL 互斥字段。
current => ({ ...current, smtp_use_tls: event.target.checked, smtp_use_ssl: event.target.checked ? false : current.smtp_use_ssl }),
);
};
// handleSslChange 切换直连 SSL 并保持 TLS 与 SSL 互斥。
const handleSslChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSmtp(
// nextSettingsUpdater 使用函数式更新 SSL/TLS 互斥字段。
current => ({ ...current, smtp_use_ssl: event.target.checked, smtp_use_tls: event.target.checked ? false : current.smtp_use_tls }),
);
};
// handlePasswordChange 更新系统 SMTP 密码。
const handlePasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSmtp(
// nextSettingsUpdater 使用函数式更新密码字段。
current => ({ ...current, smtp_password: event.target.value }),
);
};
// handleTogglePassword 切换系统 SMTP 密码明文展示。
const handleTogglePassword = () => setShowPassword(
// nextPasswordState 使用函数式更新密码显示状态。
value => !value,
);
return (
<section className="ios-card rounded-xl p-6 bg-white space-y-5">
<div className="flex items-start justify-between">
<div><h3 className="text-lg font-extrabold text-gray-800">SMTP 邮件配置</h3><p className="text-sm text-gray-500 mt-1">系统级邮件发送服务,供邮件通知渠道复用</p></div>
<div className="p-2 rounded-xl bg-blue-50 text-blue-600"><Mail className="w-5 h-5" /></div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 服务器</label><input data-field="smtp_server" type="text" value={smtp.smtp_server || ''} onChange={handleTextChange} placeholder="smtp.qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 端口</label><input type="number" value={smtp.smtp_port || 587} onChange={handlePortChange} placeholder="587" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
</div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱</label><input data-field="smtp_user" type="email" value={smtp.smtp_user || ''} onChange={handleTextChange} placeholder="[email protected]" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">邮箱密码 / 授权码</label>
<div className="relative">
<input type={showPassword ? 'text' : 'password'} value={smtp.smtp_password || ''} onChange={handlePasswordChange} placeholder="输入密码或授权码" className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" />
<button type="button" onClick={handleTogglePassword} className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors">{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}</button>
</div>
<p className="text-xs text-gray-500">QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label><input data-field="smtp_from_name" type="text" value={smtp.smtp_from_name || ''} onChange={handleTextChange} placeholder="闲鱼自动回复系统" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱地址</label><input data-field="smtp_from_address" type="email" value={smtp.smtp_from_address || smtp.smtp_user || ''} onChange={handleTextChange} placeholder="[email protected]" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700"><input type="checkbox" checked={smtp.smtp_use_tls !== false} onChange={handleTlsChange} />STARTTLS(常用于 587 端口)</label>
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700"><input type="checkbox" checked={smtp.smtp_use_ssl === true} onChange={handleSslChange} />SSL/TLS 直连(常用于 465 端口)</label>
</div>
<button onClick={onSave} disabled={smtpSaving} className="ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50">{smtpSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}{smtpSaving ? '保存中...' : '保存 SMTP 配置'}</button>
</section>
);
};
@@ -0,0 +1,344 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../types';
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, notificationErrorMessage, normalizeNotificationForm, validateNotificationForm } from './state';
import type { NotificationForm, NotificationState } from './types';
// useNotifications 统一管理通知渠道、事件订阅和系统 SMTP 的异步状态。
export const useNotifications = (isAdmin: boolean): NotificationState => {
// channels 保存当前用户可用的通知渠道。
const [channels, setChannels] = useState<NotificationChannel[]>([]);
// loading 表示通知渠道列表是否正在加载。
const [loading, setLoading] = useState(true);
// showModal 表示渠道新建或编辑弹窗是否打开。
const [showModal, setShowModal] = useState(false);
// editing 保存当前正在编辑的渠道。
const [editing, setEditing] = useState<NotificationChannel | null>(null);
// saving 表示渠道保存或删除动作是否正在执行。
const [saving, setSaving] = useState(false);
// testingId 保存当前正在测试发送的渠道 ID。
const [testingId, setTestingId] = useState('');
// toast 保存当前短暂操作提示。
const [toast, setToast] = useState<NotificationState['toast']>(null);
// smtp 保存系统级邮件发送配置。
const [smtp, setSmtp] = useState<SystemSettings>({});
// smtpSaving 表示系统 SMTP 保存是否正在执行。
const [smtpSaving, setSmtpSaving] = useState(false);
// showSmtpPassword 控制系统 SMTP 密码是否明文显示。
const [showSmtpPassword, setShowSmtpPassword] = useState(false);
// showChannelSmtpPassword 控制独立 SMTP 密码是否明文显示。
const [showChannelSmtpPassword, setShowChannelSmtpPassword] = useState(false);
// form 保存渠道编辑弹窗的当前表单。
const [form, setForm] = useState<NotificationForm>(emptyNotificationForm);
// channelGeneration 隔离渠道加载和刷新产生的旧响应。
const channelGeneration = useRef(0);
// channelAbort 保存当前渠道列表请求的取消控制器。
const channelAbort = useRef<AbortController | null>(null);
// smtpGeneration 隔离 SMTP 设置切换管理员状态后的旧响应。
const smtpGeneration = useRef(0);
// smtpAbort 保存当前 SMTP 设置请求的取消控制器。
const smtpAbort = useRef<AbortController | null>(null);
// actionGeneration 隔离保存、删除和测试动作的旧响应。
const actionGeneration = useRef(0);
// actionAbort 保存当前渠道变更动作的取消控制器。
const actionAbort = useRef<AbortController | null>(null);
// toastTimer 保存提示自动消失的定时器句柄。
const toastTimer = useRef<number | null>(null);
// showToast 展示短暂提示并清理上一条提示的定时器。
const showToast = useCallback(
// 提示回调写入提示状态并安排自动清理。
(type: NonNullable<NotificationState['toast']>['type'], text: string) => {
setToast({ type, text });
if (toastTimer.current !== null) window.clearTimeout(toastTimer.current);
toastTimer.current = window.setTimeout(
// toastCleanup 在提示展示三秒后清理状态。
() => {
toastTimer.current = null;
setToast(null);
},
3000,
);
},
[],
);
// loadChannels 加载通知渠道并丢弃过期响应。
const loadChannels = useCallback(
// 渠道加载回调读取最新通知渠道列表。
async () => {
// generation 标记本次渠道查询的代次。
const generation = ++channelGeneration.current;
channelAbort.current?.abort();
// controller 允许刷新或卸载时取消渠道请求。
const controller = new AbortController();
channelAbort.current = controller;
setLoading(true);
try {
// result 是当前用户的通知渠道列表响应。
const result = await getNotificationChannels({ signal: controller.signal });
if (!isCurrentNotificationRequest(generation, channelGeneration.current)) return;
setChannels(result.data || []);
} catch (error: unknown /* 渠道加载异常 */) {
if (isCurrentNotificationRequest(generation, channelGeneration.current) && !controller.signal.aborted) {
console.error('加载通知渠道失败', error);
}
} finally {
if (isCurrentNotificationRequest(generation, channelGeneration.current)) setLoading(false);
}
},
[],
);
// loadSmtp 加载管理员可见的系统 SMTP 配置并隔离过期响应。
const loadSmtp = useCallback(
// SMTP 加载回调读取管理员系统设置。
async () => {
// generation 标记本次 SMTP 查询的代次。
const generation = ++smtpGeneration.current;
smtpAbort.current?.abort();
// controller 允许管理员状态变化时取消 SMTP 查询。
const controller = new AbortController();
smtpAbort.current = controller;
try {
// settings 是系统 SMTP 配置快照。
const settings = await getSystemSettings({ signal: controller.signal });
if (isCurrentNotificationRequest(generation, smtpGeneration.current)) setSmtp(settings || {});
} catch (error: unknown /* SMTP 加载异常 */) {
if (isCurrentNotificationRequest(generation, smtpGeneration.current) && !controller.signal.aborted) {
console.error('加载 SMTP 配置失败', error);
}
}
},
[],
);
useEffect(
// 通知数据副作用并行加载渠道和管理员 SMTP 配置。
() => {
void loadChannels();
if (isAdmin) {
void loadSmtp();
} else {
smtpGeneration.current += 1;
smtpAbort.current?.abort();
setSmtp({});
}
return (
// 通知数据清理回调取消渠道和 SMTP 请求。
() => {
channelGeneration.current += 1;
channelAbort.current?.abort();
smtpGeneration.current += 1;
smtpAbort.current?.abort();
}
);
},
[isAdmin, loadChannels, loadSmtp],
);
useEffect(
// 提示清理副作用负责页面卸载时释放自动消失定时器。
() => (
// toastCleanup 在页面卸载时释放定时器。
() => {
if (toastTimer.current !== null) window.clearTimeout(toastTimer.current);
}
),
[],
);
// openCreate 打开新建渠道表单并清理上一次编辑状态。
const openCreate = useCallback(
// 新建回调重置表单并打开渠道弹窗。
() => {
setEditing(null);
setForm(emptyNotificationForm());
setShowChannelSmtpPassword(false);
setShowModal(true);
},
[],
);
// openEdit 打开已有渠道并归一化邮件渠道配置。
const openEdit = useCallback(
// 编辑回调载入渠道配置并打开弹窗。
(channel: NotificationChannel) => {
setEditing(channel);
setForm(normalizeNotificationForm(channel, smtp));
setShowChannelSmtpPassword(false);
setShowModal(true);
},
[smtp],
);
// closeModal 关闭渠道弹窗并取消未完成的保存动作。
const closeModal = useCallback(
// 关闭回调使保存请求失效并隐藏弹窗。
() => {
actionGeneration.current += 1;
actionAbort.current?.abort();
setSaving(false);
setShowModal(false);
},
[],
);
// handleSave 校验并保存当前渠道表单,失败时保留表单供重试。
const handleSave = useCallback(
// 保存回调执行渠道校验、请求和成功刷新。
async () => {
// validationError 是渠道表单预检失败时的用户提示。
const validationError = validateNotificationForm(form);
if (validationError) {
showToast('error', validationError);
return;
}
// generation 标记当前渠道保存动作的代次。
const generation = ++actionGeneration.current;
actionAbort.current?.abort();
// controller 允许关闭弹窗时取消保存请求。
const controller = new AbortController();
actionAbort.current = controller;
setSaving(true);
try {
// payload 是后端渠道接口使用的规范化请求体。
const payload = buildNotificationPayload(form);
if (editing) {
await updateNotificationChannel(editing.id, payload, { signal: controller.signal });
} else {
await createNotificationChannel(payload, { signal: controller.signal });
}
if (!isCurrentNotificationRequest(generation, actionGeneration.current)) return;
setShowModal(false);
await loadChannels();
if (!isCurrentNotificationRequest(generation, actionGeneration.current)) return;
showToast('success', editing ? '已更新' : '已创建');
} catch (error: unknown /* 渠道保存异常 */) {
if (isCurrentNotificationRequest(generation, actionGeneration.current) && !controller.signal.aborted) {
showToast('error', notificationErrorMessage(error, '保存失败'));
}
} finally {
if (isCurrentNotificationRequest(generation, actionGeneration.current)) setSaving(false);
}
},
[editing, form, loadChannels, showToast],
);
// handleDelete 删除渠道并在成功后刷新列表。
const handleDelete = useCallback(
// 删除回调执行渠道删除请求并刷新列表。
async (channel: NotificationChannel) => {
if (!confirm(`确认删除渠道「${channel.name}」吗?已绑定该渠道的账号会自动解绑。`)) return;
// generation 标记当前删除动作的代次。
const generation = ++actionGeneration.current;
actionAbort.current?.abort();
// controller 允许刷新页面时取消删除请求。
const controller = new AbortController();
actionAbort.current = controller;
try {
await deleteNotificationChannel(channel.id, { signal: controller.signal });
if (!isCurrentNotificationRequest(generation, actionGeneration.current)) return;
await loadChannels();
if (!isCurrentNotificationRequest(generation, actionGeneration.current)) return;
showToast('success', '已删除');
} catch (error: unknown /* 渠道删除异常 */) {
if (isCurrentNotificationRequest(generation, actionGeneration.current) && !controller.signal.aborted) {
showToast('error', notificationErrorMessage(error, '删除失败'));
}
}
},
[loadChannels, showToast],
);
// handleToggleEnabled 更新渠道启用状态并采用函数式局部更新。
const handleToggleEnabled = useCallback(
// 启用切换回调更新渠道状态并保留最新响应。
async (channel: NotificationChannel) => {
// generation 标记当前启用状态动作的代次。
const generation = ++actionGeneration.current;
actionAbort.current?.abort();
// controller 允许新的渠道动作取消旧请求。
const controller = new AbortController();
actionAbort.current = controller;
try {
await updateNotificationChannel(channel.id, { enabled: !channel.enabled }, { signal: controller.signal });
if (!isCurrentNotificationRequest(generation, actionGeneration.current)) return;
setChannels(
// nextChannelsUpdater 使用函数式更新渠道列表。
current => current.map(
// item 是当前待更新的渠道项。
item => item.id === channel.id ? { ...item, enabled: !item.enabled } : item,
),
);
} catch (error: unknown /* 渠道状态异常 */) {
if (isCurrentNotificationRequest(generation, actionGeneration.current) && !controller.signal.aborted) {
showToast('error', notificationErrorMessage(error, '切换失败'));
}
}
},
[showToast],
);
// handleTest 发送渠道测试通知并展示结果。
const handleTest = useCallback(
// 测试回调发送测试通知并显示结果。
async (channel: NotificationChannel) => {
setTestingId(channel.id);
// generation 标记当前测试通知动作的代次。
const generation = ++actionGeneration.current;
actionAbort.current?.abort();
// controller 允许新动作取消旧的测试发送。
const controller = new AbortController();
actionAbort.current = controller;
try {
await testNotificationChannel(channel.id, { signal: controller.signal });
if (isCurrentNotificationRequest(generation, actionGeneration.current)) showToast('success', '测试通知已发送,请检查对应渠道');
} catch (error: unknown /* 测试通知异常 */) {
if (isCurrentNotificationRequest(generation, actionGeneration.current) && !controller.signal.aborted) {
showToast('error', notificationErrorMessage(error, '发送失败'));
}
} finally {
if (isCurrentNotificationRequest(generation, actionGeneration.current)) setTestingId('');
}
},
[showToast],
);
// handleSaveSmtp 保存系统 SMTP 配置并支持取消旧保存请求。
const handleSaveSmtp = useCallback(
// SMTP 保存回调提交系统邮件配置。
async () => {
// generation 标记当前 SMTP 保存动作的代次。
const generation = ++smtpGeneration.current;
smtpAbort.current?.abort();
// controller 允许重复保存时取消上一轮请求。
const controller = new AbortController();
smtpAbort.current = controller;
setSmtpSaving(true);
try {
await updateSystemSettings({
smtp_server: smtp.smtp_server || '', smtp_port: smtp.smtp_port || 587, smtp_user: smtp.smtp_user || '',
smtp_password: smtp.smtp_password || '', smtp_from_name: smtp.smtp_from_name || '',
smtp_from_address: smtp.smtp_from_address || smtp.smtp_user || '', smtp_use_tls: smtp.smtp_use_tls !== false,
smtp_use_ssl: smtp.smtp_use_ssl === true,
}, { signal: controller.signal });
if (isCurrentNotificationRequest(generation, smtpGeneration.current)) showToast('success', 'SMTP 配置已保存');
} catch (error: unknown /* SMTP 保存异常 */) {
if (isCurrentNotificationRequest(generation, smtpGeneration.current) && !controller.signal.aborted) {
showToast('error', notificationErrorMessage(error, '保存失败'));
}
} finally {
if (isCurrentNotificationRequest(generation, smtpGeneration.current)) setSmtpSaving(false);
}
},
[showToast, smtp],
);
return {
channels, loading, showModal, editing, saving, testingId, toast, smtp, smtpSaving,
showSmtpPassword, showChannelSmtpPassword, form, setForm, setSmtp, setShowSmtpPassword,
setShowChannelSmtpPassword, loadChannels, openCreate, openEdit, closeModal, showToast,
handleSave, handleDelete, handleToggleEnabled, handleTest, handleSaveSmtp,
};
};
@@ -0,0 +1,31 @@
import { expect, test } from 'vitest';
import type { NotificationForm } from './types';
import { buildNotificationPayload, isCurrentNotificationRequest, notificationEventSummary, validateNotificationForm } from './state';
// createForm 创建通知渠道校验使用的最小表单对象。
const createForm = (overrides: Partial<NotificationForm> = {}): NotificationForm => ({
name: '测试渠道', type: 'bark', enabled: true, config: { server_url: 'https://api.day.app', device_key: 'device-key' }, event_types: [], ...overrides,
});
test('通知渠道校验阻止缺少名称和必填配置',
// 渠道表单测试验证名称、渠道凭据和成功保存请求体。
() => {
expect(validateNotificationForm(createForm({ name: '' }))).toBe('请填写渠道名称');
expect(validateNotificationForm(createForm({ config: {} }))).toContain('Bark 服务器');
expect(validateNotificationForm(createForm())).toBe('');
expect(buildNotificationPayload(createForm({ event_types: ['account_offline'] })).event_types).toEqual(['account_offline']);
});
test('通知事件摘要为空时表示订阅全部事件',
// 事件摘要测试验证空选择和多事件选择的展示语义。
() => {
expect(notificationEventSummary([])).toBe('全部事件');
expect(notificationEventSummary(['account_offline', 'system_error'])).toBe('掉线通知、系统错误');
});
test('通知请求代次拒绝过期响应',
// 过期响应测试验证刷新或取消后旧请求不能覆盖当前状态。
() => {
expect(isCurrentNotificationRequest(5, 5)).toBe(true);
expect(isCurrentNotificationRequest(4, 5)).toBe(false);
});
@@ -0,0 +1,138 @@
import { Bell, Mail, MessageCircle, Send as Telegram, Webhook } from 'lucide-react';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types';
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../../../notificationEmailConfig';
import type { NotificationChannelMeta, NotificationEventMeta, NotificationForm, NotificationPayload } from './types';
// notificationChannelTypes 是所有通知渠道的静态字段、图标和使用指南。
export const notificationChannelTypes: Record<NotificationChannelType, NotificationChannelMeta> = {
bark: {
label: 'Bark', icon: Bell,
fields: [
{ key: 'server_url', label: 'Bark 服务器', placeholder: 'https://api.day.app', required: true },
{ key: 'device_key', label: 'Device Key', placeholder: '你的 Bark 设备 Key', required: true },
{ key: 'title', label: '标题(可选)', placeholder: 'Ydisks闲鱼助手' },
{ key: 'sound', label: '铃声(可选)', placeholder: 'default' },
{ key: 'group', label: '分组(可选)', placeholder: 'xianyu' },
],
guide: { steps: ['App Store 搜索并安装 Bark(免费)', '打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容', 'URL 路径里 <key> 那一段就是 Device Key,复制填入', '服务器地址默认 https://api.day.app,自建服务端则填自建域名'], urlFormat: 'https://api.day.app/<你的key>/测试内容', note: '不需要 secret,Device Key 本身就是唯一凭证。' },
},
dingtalk: {
label: '钉钉机器人', icon: MessageCircle,
fields: [
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://oapi.dingtalk.com/robot/send?access_token=...', required: true },
{ key: 'secret', label: '加签密钥', placeholder: 'SEC...', help: '安全设置勾选「加签」后生成,SEC 开头' },
],
guide: { steps: ['钉钉进入一个群(可建单人群)→ 右上角 群设置', '机器人 → 添加机器人 → 选择「自定义机器人」', '安全设置勾选「加签」', '完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制', 'Webhook URL 填上面,Secret 填加签密钥'], urlFormat: 'https://oapi.dingtalk.com/robot/send?access_token=XXX', note: '加签密钥可选,但强烈建议启用,否则机器人可能被滥用。' },
},
feishu: {
label: '飞书机器人', icon: MessageCircle,
fields: [
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://open.feishu.cn/open-apis/bot/v2/hook/...', required: true },
{ key: 'secret', label: '签名校验密钥', placeholder: 'sec-...', help: '安全设置选「签名校验」后生成' },
],
guide: { steps: ['飞书进入目标群 → 右上角 更多 → 设置', '群机器人 → 添加机器人 → 自定义机器人', '安全设置选择「签名校验」,复制生成的秘钥', '完成会给 Webhook 地址,复制', 'Webhook URL 填上面,秘钥填签名校验密钥'], urlFormat: 'https://open.feishu.cn/open-apis/bot/v2/hook/xxx', note: '签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。' },
},
wechat: {
label: '企业微信机器人', icon: MessageCircle,
fields: [{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...', required: true }],
guide: { steps: ['企业微信进入一个内部群 → 右上角 … → 群设置', '找到「群机器人」(新版可能叫「消息推送」)', '添加 → 选择自定义机器人', '完成给 Webhook 地址(含 ?key=),复制填入'], urlFormat: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX', note: '不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。' },
},
webhook: {
label: '自定义 Webhook', icon: Webhook,
fields: [{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://your-server/notify', required: true }],
guide: { steps: ['仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON', '系统会 POST 这个 URL,Content-Type: application/json', '请求体固定为右侧 JSON 格式,按需解析 message 字段'], urlFormat: '{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}', note: '若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。' },
},
telegram: {
label: 'Telegram', icon: Telegram,
fields: [{ key: 'bot_token', label: 'Bot Token', placeholder: '123456:ABC-DEF...', required: true }, { key: 'chat_id', label: 'Chat ID', placeholder: '-1001234567890 或你的用户 ID', required: true }],
guide: { steps: ['在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token', '把你的 Bot 拉进一个群,或私聊它发一条消息', '浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates', '从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'], urlFormat: 'Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890', note: '群聊需先把 Bot 设为管理员才能发消息。' },
},
email: {
label: '邮件', icon: Mail,
fields: [{ key: 'to_email', label: '收件邮箱', placeholder: '[email protected]', required: true }],
guide: { steps: ['通常先保存页面中的系统 SMTP 配置', '邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP', '只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置'], note: '继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。' },
},
};
// notificationEvents 是可绑定到通知渠道的事件定义。
export const notificationEvents: NotificationEventMeta[] = [
{ value: 'account_offline', label: '掉线通知', description: '账号过期、断线或登录态失效' },
{ value: 'account_recovered', label: '恢复通知', description: '自动恢复成功并重新在线' },
{ value: 'account_disabled', label: '禁用通知', description: '连续失败、账密错误等导致账号停用' },
{ value: 'security_verification', label: '风控验证', description: '滑块、人脸、扫码验证等安全校验' },
{ value: 'delivery_result', label: '交易通知', description: '订单发货、卡密发送等交易结果' },
{ value: 'token_renewal', label: '续期通知', description: 'Cookie/token 续期和自动恢复过程' },
{ value: 'system_error', label: '系统错误', description: '后台任务或系统级异常' },
];
// emptyNotificationForm 返回新建渠道的初始表单。
export const emptyNotificationForm = (): NotificationForm => ({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] });
// notificationEventSummary 将事件值转换为渠道列表中的中文摘要。
export const notificationEventSummary = (events?: NotificationEventType[]): string => {
if (!events || events.length === 0) return '全部事件';
return events.map(
// event 是当前待转换的后端事件值。
event => notificationEvents.find(
// item 是当前事件定义。
item => item.value === event,
)?.label || event,
).join('、');
};
// normalizeNotificationForm 将编辑中的渠道配置复制为独立表单对象。
export const normalizeNotificationForm = (channel: NotificationChannel, smtp: SystemSettings): NotificationForm => {
// normalizedEmailConfig 是邮件渠道的兼容配置副本。
const normalizedEmailConfig = channel.type === 'email' ? normalizeEmailChannelConfig({ ...(channel.config || {}) }) : null;
// config 是编辑表单实际使用的渠道配置。
const config = normalizedEmailConfig
? (normalizedEmailConfig.use_custom_smtp === true ? enableCustomSMTP(normalizedEmailConfig, smtp) : normalizedEmailConfig)
: { ...(channel.config || {}) };
return { name: channel.name, type: channel.type, enabled: channel.enabled, config, event_types: channel.event_types || [] };
};
// validateNotificationForm 校验渠道名称、渠道字段和独立 SMTP 必填项。
export const validateNotificationForm = (form: NotificationForm): string => {
// meta 是当前渠道类型的静态校验配置。
const meta = notificationChannelTypes[form.type];
// missingField 是第一个未填写的渠道必填字段。
const missingField = meta.fields.find(
// field 是当前渠道字段定义。
field => field.required && !String(form.config[field.key] || '').trim(),
);
if (missingField) return `请填写 ${missingField.label}`;
if (!form.name.trim()) return '请填写渠道名称';
if (form.type === 'email') {
// config 是邮件渠道归一化后的提交配置。
const config = buildEmailChannelConfig(form.config);
if (config.use_custom_smtp) {
// requiredFields 是独立 SMTP 模式下必须填写的字段列表。
const requiredFields: Array<[string, string]> = [
['smtp_server', '独立 SMTP 服务器'], ['smtp_port', '独立 SMTP 端口'], ['smtp_user', '独立 SMTP 登录邮箱'],
['smtp_password', '独立 SMTP 密码 / 授权码'], ['smtp_from_address', '独立 SMTP 发件地址'],
];
// missing 是独立 SMTP 模式下第一个缺失字段。
const missing = requiredFields.find(
// field 是字段名和用户可见名称的二元组。
([key]) => !String(config[key] || '').trim(),
);
if (missing) return `请填写 ${missing[1]}`;
}
}
return '';
};
// buildNotificationPayload 将表单转换为通知渠道保存请求。
export const buildNotificationPayload = (form: NotificationForm): NotificationPayload => ({
name: form.name.trim(),
type: form.type,
config: form.type === 'email' ? buildEmailChannelConfig(form.config) : form.config,
event_types: form.event_types,
enabled: form.enabled,
});
// isCurrentNotificationRequest 判断异步通知请求是否仍属于最新代次。
export const isCurrentNotificationRequest = (generation: number, currentGeneration: number): boolean => generation === currentGeneration;
// notificationErrorMessage 将未知异常转换为用户可读的通知错误。
export const notificationErrorMessage = (error: unknown, fallback: string): string => error instanceof Error && error.message ? error.message : fallback;
@@ -0,0 +1,142 @@
import type { Dispatch, ElementType, SetStateAction } from 'react';
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types';
// NotificationField 描述通知渠道表单中的一个配置字段。
export interface NotificationField {
// key 是提交到渠道配置的字段名。
key: string;
// label 是字段在表单中的中文名称。
label: string;
// placeholder 是输入框的示例提示。
placeholder?: string;
// type 是输入控件的 HTML 类型。
type?: 'text' | 'password' | 'number';
// required 表示该字段是否必须填写。
required?: boolean;
// help 是字段下方的补充说明。
help?: string;
}
// NotificationGuide 描述如何获取某类通知渠道凭据。
export interface NotificationGuide {
// steps 是按顺序展示的配置步骤。
steps: string[];
// urlFormat 是可选的 URL 或请求格式示例。
urlFormat?: string;
// note 是渠道配置的额外注意事项。
note?: string;
}
// NotificationChannelMeta 描述通知渠道的静态表单和展示配置。
export interface NotificationChannelMeta {
// label 是渠道类型的中文名称。
label: string;
// icon 是渠道列表和表单中使用的图标组件。
icon: ElementType;
// fields 是渠道配置字段定义。
fields: NotificationField[];
// guide 是渠道凭据获取指南。
guide: NotificationGuide;
}
// NotificationEventMeta 描述可供渠道订阅的一类系统事件。
export interface NotificationEventMeta {
// value 是后端识别的事件类型值。
value: NotificationEventType;
// label 是事件的中文名称。
label: string;
// description 是事件在绑定组件中的说明。
description: string;
}
// NotificationForm 描述新建或编辑通知渠道的表单值。
export interface NotificationForm {
// name 是渠道名称。
name: string;
// type 是当前渠道类型。
type: NotificationChannelType;
// enabled 表示是否启用当前渠道。
enabled: boolean;
// config 保存渠道类型对应的配置值。
config: Record<string, unknown>;
// event_types 保存用户选择的通知事件,空数组表示全部事件。
event_types: NotificationEventType[];
}
// NotificationPayload 描述保存通知渠道时发送给 API 的请求体。
export interface NotificationPayload {
// name 是保存后的渠道名称。
name: string;
// type 是保存后的渠道类型。
type: string;
// config 是归一化后的渠道配置。
config: Record<string, unknown>;
// event_types 是保存后的事件订阅集合。
event_types: NotificationEventType[];
// enabled 是保存后的启用状态。
enabled: boolean;
}
// NotificationToast 描述页面底部的短暂操作提示。
export interface NotificationToast {
// type 决定提示的成功或失败样式。
type: 'success' | 'error';
// text 是提示内容。
text: string;
}
// NotificationState 暴露通知页面的数据、表单和操作边界。
export interface NotificationState {
// channels 是当前用户可用的通知渠道列表。
channels: NotificationChannel[];
// loading 表示渠道列表是否正在加载。
loading: boolean;
// showModal 表示渠道编辑弹窗是否打开。
showModal: boolean;
// editing 是当前正在编辑的渠道,新增时为空。
editing: NotificationChannel | null;
// saving 表示渠道或 SMTP 配置是否正在保存。
saving: boolean;
// testingId 是当前正在发送测试通知的渠道 ID。
testingId: string;
// toast 是当前待展示的操作提示。
toast: NotificationToast | null;
// smtp 是系统级邮件配置。
smtp: SystemSettings;
// smtpSaving 表示系统 SMTP 是否正在保存。
smtpSaving: boolean;
// showSmtpPassword 控制系统 SMTP 密码明文展示。
showSmtpPassword: boolean;
// showChannelSmtpPassword 控制独立 SMTP 密码明文展示。
showChannelSmtpPassword: boolean;
// form 是当前渠道编辑表单值。
form: NotificationForm;
// setForm 更新渠道编辑表单。
setForm: Dispatch<SetStateAction<NotificationForm>>;
// setSmtp 更新系统 SMTP 配置表单。
setSmtp: Dispatch<SetStateAction<SystemSettings>>;
// setShowSmtpPassword 更新系统 SMTP 密码展示状态。
setShowSmtpPassword: Dispatch<SetStateAction<boolean>>;
// setShowChannelSmtpPassword 更新独立 SMTP 密码展示状态。
setShowChannelSmtpPassword: Dispatch<SetStateAction<boolean>>;
// loadChannels 刷新通知渠道列表。
loadChannels: () => Promise<void>;
// openCreate 打开新建渠道弹窗。
openCreate: () => void;
// openEdit 打开已有渠道编辑弹窗。
openEdit: (channel: NotificationChannel) => void;
// closeModal 关闭弹窗并取消当前保存请求。
closeModal: () => void;
// showToast 展示短暂的成功或失败提示。
showToast: (type: NotificationToast['type'], text: string) => void;
// handleSave 保存当前渠道配置。
handleSave: () => Promise<void>;
// handleDelete 删除指定通知渠道。
handleDelete: (channel: NotificationChannel) => Promise<void>;
// handleToggleEnabled 切换指定渠道的启用状态。
handleToggleEnabled: (channel: NotificationChannel) => Promise<void>;
// handleTest 发送指定渠道的测试通知。
handleTest: (channel: NotificationChannel) => Promise<void>;
// handleSaveSmtp 保存系统级 SMTP 配置。
handleSaveSmtp: () => Promise<void>;
}
+20 -877
View File
@@ -1,899 +1,42 @@
import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../types';
import {
getNotificationChannels,
createNotificationChannel,
updateNotificationChannel,
deleteNotificationChannel,
testNotificationChannel,
getSystemSettings,
updateSystemSettings,
} from '../services/api';
import {
Bell, Plus, Edit2, Trash2, X, Send, RefreshCw, Loader2,
Check, MessageCircle, Mail, Webhook, Send as Telegram, Eye, EyeOff, Save,
} from 'lucide-react';
import { normalizeSMTPSettings } from '../smtpSettings';
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../notificationEmailConfig';
type ChannelTypeMeta = {
label: string;
icon: React.ElementType;
fields: { key: string; label: string; placeholder?: string; type?: 'text' | 'password' | 'number'; required?: boolean; help?: string }[];
guide: { steps: string[]; urlFormat?: string; note?: string };
};
const CHANNEL_TYPES: Record<NotificationChannelType, ChannelTypeMeta> = {
bark: {
label: 'Bark',
icon: Bell,
fields: [
{ key: 'server_url', label: 'Bark 服务器', placeholder: 'https://api.day.app', required: true },
{ key: 'device_key', label: 'Device Key', placeholder: '你的 Bark 设备 Key', required: true },
{ key: 'title', label: '标题(可选)', placeholder: 'Ydisks闲鱼助手' },
{ key: 'sound', label: '铃声(可选)', placeholder: 'default' },
{ key: 'group', label: '分组(可选)', placeholder: 'xianyu' },
],
guide: {
steps: [
'App Store 搜索并安装 Bark(免费)',
'打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容',
'URL 路径里 <key> 那一段就是 Device Key,复制填入',
'服务器地址默认 https://api.day.app,自建服务端则填自建域名',
],
urlFormat: 'https://api.day.app/<你的key>/测试内容',
note: '不需要 secret,Device Key 本身就是唯一凭证。',
},
},
dingtalk: {
label: '钉钉机器人',
icon: MessageCircle,
fields: [
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://oapi.dingtalk.com/robot/send?access_token=...', required: true },
{ key: 'secret', label: '加签密钥', placeholder: 'SEC...', help: '安全设置勾选「加签」后生成,SEC 开头' },
],
guide: {
steps: [
'钉钉进入一个群(可建单人群)→ 右上角 群设置',
'机器人 → 添加机器人 → 选择「自定义机器人」',
'安全设置勾选「加签」',
'完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制',
'Webhook URL 填上面,Secret 填加签密钥',
],
urlFormat: 'https://oapi.dingtalk.com/robot/send?access_token=XXX',
note: '加签密钥可选,但强烈建议启用,否则机器人可能被滥用。',
},
},
feishu: {
label: '飞书机器人',
icon: MessageCircle,
fields: [
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://open.feishu.cn/open-apis/bot/v2/hook/...', required: true },
{ key: 'secret', label: '签名校验密钥', placeholder: 'sec-...', help: '安全设置选「签名校验」后生成' },
],
guide: {
steps: [
'飞书进入目标群 → 右上角 更多 → 设置',
'群机器人 → 添加机器人 → 自定义机器人',
'安全设置选择「签名校验」,复制生成的秘钥',
'完成会给 Webhook 地址,复制',
'Webhook URL 填上面,秘钥填签名校验密钥',
],
urlFormat: 'https://open.feishu.cn/open-apis/bot/v2/hook/xxx',
note: '签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。',
},
},
wechat: {
label: '企业微信机器人',
icon: MessageCircle,
fields: [
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...', required: true },
],
guide: {
steps: [
'企业微信进入一个内部群 → 右上角 … → 群设置',
'找到「群机器人」(新版可能叫「消息推送」)',
'添加 → 选择自定义机器人',
'完成给 Webhook 地址(含 ?key=),复制填入',
],
urlFormat: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX',
note: '不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。',
},
},
webhook: {
label: '自定义 Webhook',
icon: Webhook,
fields: [
{ key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://your-server/notify', required: true },
],
guide: {
steps: [
'仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON',
'系统会 POST 这个 URL,Content-Type: application/json',
'请求体固定为右侧 JSON 格式,按需解析 message 字段',
],
urlFormat: '{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',
note: '若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。',
},
},
telegram: {
label: 'Telegram',
icon: Telegram,
fields: [
{ key: 'bot_token', label: 'Bot Token', placeholder: '123456:ABC-DEF...', required: true },
{ key: 'chat_id', label: 'Chat ID', placeholder: '-1001234567890 或你的用户 ID', required: true },
],
guide: {
steps: [
'在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token',
'把你的 Bot 拉进一个群,或私聊它发一条消息',
'浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates',
'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)',
],
urlFormat: 'Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890',
note: '群聊需先把 Bot 设为管理员才能发消息。',
},
},
email: {
label: '邮件',
icon: Mail,
fields: [
{ key: 'to_email', label: '收件邮箱', placeholder: '[email protected]', required: true },
],
guide: {
steps: [
'通常先保存页面中的系统 SMTP 配置',
'邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP',
'只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置',
],
note: '继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。',
},
},
};
const NOTIFICATION_EVENTS: { value: NotificationEventType; label: string; description: string }[] = [
{ value: 'account_offline', label: '掉线通知', description: '账号过期、断线或登录态失效' },
{ value: 'account_recovered', label: '恢复通知', description: '自动恢复成功并重新在线' },
{ value: 'account_disabled', label: '禁用通知', description: '连续失败、账密错误等导致账号停用' },
{ value: 'security_verification', label: '风控验证', description: '滑块、人脸、扫码验证等安全校验' },
{ value: 'delivery_result', label: '交易通知', description: '订单发货、卡密发送等交易结果' },
{ value: 'token_renewal', label: '续期通知', description: 'Cookie/token 续期和自动恢复过程' },
{ value: 'system_error', label: '系统错误', description: '后台任务或系统级异常' },
];
const notificationEventSummary = (events?: NotificationEventType[]) => {
if (!events || events.length === 0) return '全部事件';
const labels = events.map(event => NOTIFICATION_EVENTS.find(item => item.value === event)?.label || event);
return labels.join('、');
};
import React from 'react';
import { Bell, Check, Loader2, Plus, RefreshCw, X } from 'lucide-react';
import { NotificationChannelList } from '../app/features/notifications/components/NotificationChannelList';
import { NotificationChannelModal } from '../app/features/notifications/components/NotificationChannelModal';
import { NotificationSmtpSettings } from '../app/features/notifications/components/NotificationSmtpSettings';
import { useNotifications } from '../app/features/notifications/hooks';
// NotificationsProps 描述通知页面接收的权限上下文。
interface NotificationsProps {
// isAdmin 表示当前用户是否可以查看和保存系统 SMTP 配置。
isAdmin?: boolean;
}
// Notifications 渲染通知渠道列表、SMTP 配置和渠道编辑边界。
const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
const [channels, setChannels] = useState<NotificationChannel[]>([]);
const [loading, setLoading] = useState(true);
const [showModal, setShowModal] = useState(false);
const [editing, setEditing] = useState<NotificationChannel | null>(null);
const [saving, setSaving] = useState(false);
const [testingId, setTestingId] = useState<string>('');
const [toast, setToast] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
// SMTP 系统级邮件配置(从系统设置加载/保存)
const [smtp, setSmtp] = useState<SystemSettings>({});
const [smtpSaving, setSmtpSaving] = useState(false);
const [showSmtpPassword, setShowSmtpPassword] = useState(false);
const [showChannelSmtpPassword, setShowChannelSmtpPassword] = useState(false);
const [form, setForm] = useState({
name: '',
type: 'bark' as NotificationChannelType,
enabled: true,
config: {} as Record<string, unknown>,
event_types: [] as NotificationEventType[],
});
const load = async () => {
setLoading(true);
try {
const res = await getNotificationChannels();
setChannels(res.data || []);
} catch (e) {
console.error('加载通知渠道失败', e);
} finally {
setLoading(false);
}
};
const loadSmtp = async () => {
try {
const s = await getSystemSettings();
setSmtp(normalizeSMTPSettings(s || {}));
} catch (e) {
console.error('加载 SMTP 配置失败', e);
}
};
const handleSaveSmtp = async () => {
setSmtpSaving(true);
try {
await updateSystemSettings({
smtp_server: smtp.smtp_server || '',
smtp_port: smtp.smtp_port || 587,
smtp_user: smtp.smtp_user || '',
smtp_password: smtp.smtp_password || '',
smtp_from_name: smtp.smtp_from_name || '',
smtp_from_address: smtp.smtp_from_address || smtp.smtp_user || '',
smtp_use_tls: smtp.smtp_use_tls !== false,
smtp_use_ssl: smtp.smtp_use_ssl === true,
});
showToast('success', 'SMTP 配置已保存');
} catch (e: any) {
showToast('error', e?.message || '保存失败');
} finally {
setSmtpSaving(false);
}
};
useEffect(() => {
load();
if (isAdmin) {
loadSmtp();
} else {
setSmtp({});
}
}, [isAdmin]);
const showToast = (type: 'success' | 'error', text: string) => {
setToast({ type, text });
window.setTimeout(() => setToast(null), 3000);
};
const openCreate = () => {
setEditing(null);
setForm({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] });
setShowChannelSmtpPassword(false);
setShowModal(true);
};
const openEdit = (ch: NotificationChannel) => {
setEditing(ch);
const normalizedEmailConfig = ch.type === 'email'
? normalizeEmailChannelConfig({ ...(ch.config || {}) })
: null;
const config = normalizedEmailConfig
? (normalizedEmailConfig.use_custom_smtp === true
? enableCustomSMTP(normalizedEmailConfig, smtp)
: normalizedEmailConfig)
: { ...(ch.config || {}) };
setForm({
name: ch.name,
type: ch.type,
enabled: ch.enabled,
config,
event_types: ch.event_types || [],
});
setShowChannelSmtpPassword(false);
setShowModal(true);
};
const handleSave = async () => {
const meta = CHANNEL_TYPES[form.type];
for (const f of meta.fields) {
if (f.required && !String(form.config[f.key] || '').trim()) {
showToast('error', `请填写 ${f.label}`);
return;
}
}
if (!form.name.trim()) {
showToast('error', '请填写渠道名称');
return;
}
let config = form.config;
if (form.type === 'email') {
config = buildEmailChannelConfig(form.config);
if (config.use_custom_smtp) {
const required = [
['smtp_server', '独立 SMTP 服务器'],
['smtp_port', '独立 SMTP 端口'],
['smtp_user', '独立 SMTP 登录邮箱'],
['smtp_password', '独立 SMTP 密码 / 授权码'],
['smtp_from_address', '独立 SMTP 发件地址'],
] as const;
const missing = required.find(([key]) => !String(config[key] || '').trim());
if (missing) {
showToast('error', `请填写 ${missing[1]}`);
return;
}
}
}
setSaving(true);
try {
const payload = { name: form.name.trim(), type: form.type, config, event_types: form.event_types, enabled: form.enabled };
if (editing) {
await updateNotificationChannel(editing.id, payload);
} else {
await createNotificationChannel(payload);
}
setShowModal(false);
await load();
showToast('success', editing ? '已更新' : '已创建');
} catch (e: any) {
console.error('保存失败', e);
showToast('error', e?.message || '保存失败');
} finally {
setSaving(false);
}
};
const handleDelete = async (ch: NotificationChannel) => {
if (!confirm(`确认删除渠道「${ch.name}」吗?已绑定该渠道的账号会自动解绑。`)) return;
try {
await deleteNotificationChannel(ch.id);
await load();
showToast('success', '已删除');
} catch (e: any) {
showToast('error', e?.message || '删除失败');
}
};
const handleToggleEnabled = async (ch: NotificationChannel) => {
try {
await updateNotificationChannel(ch.id, {
enabled: !ch.enabled,
});
setChannels(prev => prev.map(c => c.id === ch.id ? { ...c, enabled: !c.enabled } : c));
} catch (e: any) {
showToast('error', e?.message || '切换失败');
}
};
const handleTest = async (ch: NotificationChannel) => {
setTestingId(ch.id);
try {
await testNotificationChannel(ch.id);
showToast('success', '测试通知已发送,请检查对应渠道');
} catch (e: any) {
showToast('error', e?.message || '发送失败');
} finally {
setTestingId('');
}
};
const meta = CHANNEL_TYPES[form.type];
// notificationState 统一提供通知页面的数据、表单和异步动作。
const notificationState = useNotifications(isAdmin);
return (
<div className="space-y-8 animate-fade-in">
{/* Header */}
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
<div>
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">通知设置</h2>
<p className="text-gray-500 mt-2 font-medium">配置通知渠道,账号异常时主动推送告警</p>
</div>
<div className="flex items-center gap-3">
<button
onClick={load}
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors"
>
<RefreshCw className="w-4 h-4" />
刷新
</button>
<button
onClick={openCreate}
className="ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2"
>
<Plus className="w-4 h-4" />
新建渠道
</button>
<div><h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">通知设置</h2><p className="text-gray-500 mt-2 font-medium">配置通知渠道,账号异常时主动推送告警</p></div>
<div className="flex items-center gap-3">
<button onClick={notificationState.loadChannels} className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors"><RefreshCw className="w-4 h-4" />刷新</button>
<button onClick={notificationState.openCreate} className="ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2"><Plus className="w-4 h-4" />新建渠道</button>
</div>
</div>
{/* 说明 */}
<div className="ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100">
<div className="flex items-start gap-3">
<Bell className="w-5 h-5 text-brand mt-0.5 flex-shrink-0" />
<div className="text-sm text-gray-700 leading-6">
配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:
<ul className="mt-2 space-y-1 text-gray-600">
<li>• <strong>账号 session 失效</strong>:系统正在尝试自动恢复(警告)</li>
<li>• <strong>自动恢复失败</strong>:账号已停止,需人工处理(严重)</li>
<li>• <strong>触发风控验证</strong>:可能需要扫码完成验证(警告)</li>
</ul>
</div>
</div>
<div className="flex items-start gap-3"><Bell className="w-5 h-5 text-brand mt-0.5 flex-shrink-0" /><div className="text-sm text-gray-700 leading-6">配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:<ul className="mt-2 space-y-1 text-gray-600"><li>• <strong>账号 session 失效</strong>:系统正在尝试自动恢复(警告)</li><li>• <strong>自动恢复失败</strong>:账号已停止,需人工处理(严重)</li><li>• <strong>触发风控验证</strong>:可能需要扫码完成验证(警告)</li></ul></div></div>
</div>
{/* 渠道列表 */}
{loading ? (
<div className="flex justify-center py-20">
<Loader2 className="w-8 h-8 text-brand animate-spin" />
</div>
) : channels.length === 0 ? (
<div className="ios-card rounded-xl p-12 bg-white text-center">
<Bell className="w-12 h-12 text-gray-300 mx-auto mb-4" />
<p className="text-gray-500 font-medium">还没有配置任何通知渠道</p>
<p className="text-gray-400 text-sm mt-1">点击右上角「新建渠道」开始配置</p>
</div>
) : (
<div className="space-y-3">
{channels.map(ch => {
const tMeta = CHANNEL_TYPES[ch.type] || CHANNEL_TYPES.webhook;
const Icon = tMeta.icon;
return (
<div key={ch.id} className="ios-card rounded-xl p-5 bg-white flex items-center gap-4">
<div className="w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0">
<Icon className="w-5 h-5 text-gray-600" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-bold text-gray-900 truncate">{ch.name}</span>
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium">{tMeta.label}</span>
{!ch.enabled && (
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium">已停用</span>
)}
</div>
<div className="text-xs text-gray-500 mt-1 truncate">
{tMeta.fields.map(f => ch.config?.[f.key]).filter(Boolean).map((v, i) => (
<span key={i} className="mr-3">{String(v).length > 40 ? String(v).slice(0, 40) + '…' : String(v)}</span>
))}
</div>
<div className="text-xs text-gray-400 mt-1 truncate">
订阅:{notificationEventSummary(ch.event_types)}
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<button
onClick={() => handleToggleEnabled(ch)}
className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${ch.enabled ? 'bg-green-50 text-green-700 hover:bg-green-100' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'}`}
>
{ch.enabled ? '启用中' : '已停用'}
</button>
<button
onClick={() => handleTest(ch)}
disabled={testingId === ch.id}
className="px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50"
>
{testingId === ch.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <Send className="w-3 h-3" />}
测试
</button>
<button
onClick={() => openEdit(ch)}
className="w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors"
title="编辑"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => handleDelete(ch)}
className="w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors"
title="删除"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
);
})}
</div>
)}
{notificationState.loading ? <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 text-brand animate-spin" /></div> : <NotificationChannelList channels={notificationState.channels} testingId={notificationState.testingId} onEdit={notificationState.openEdit} onDelete={notificationState.handleDelete} onToggleEnabled={notificationState.handleToggleEnabled} onTest={notificationState.handleTest} />}
{/* SMTP 邮件配置(系统级,用于邮件通知渠道) */}
{isAdmin && (
<section className="ios-card rounded-xl p-6 bg-white space-y-5">
<div className="flex items-start justify-between">
<div>
<h3 className="text-lg font-extrabold text-gray-800">SMTP 邮件配置</h3>
<p className="text-sm text-gray-500 mt-1">系统级邮件发送服务,供邮件通知渠道复用</p>
</div>
<div className="p-2 rounded-xl bg-blue-50 text-blue-600">
<Mail className="w-5 h-5" />
</div>
</div>
{isAdmin && <NotificationSmtpSettings smtp={notificationState.smtp} setSmtp={notificationState.setSmtp} smtpSaving={notificationState.smtpSaving} showPassword={notificationState.showSmtpPassword} setShowPassword={notificationState.setShowSmtpPassword} onSave={notificationState.handleSaveSmtp} />}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">SMTP 服务器</label>
<input
type="text"
value={smtp.smtp_server || ''}
onChange={e => setSmtp({ ...smtp, smtp_server: e.target.value })}
placeholder="smtp.qq.com"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">SMTP 端口</label>
<input
type="number"
value={smtp.smtp_port || 587}
onChange={e => setSmtp({ ...smtp, smtp_port: parseInt(e.target.value) || 587 })}
placeholder="587"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
</div>
<NotificationChannelModal showModal={notificationState.showModal} editing={notificationState.editing} form={notificationState.form} setForm={notificationState.setForm} smtp={notificationState.smtp} showChannelSmtpPassword={notificationState.showChannelSmtpPassword} setShowChannelSmtpPassword={notificationState.setShowChannelSmtpPassword} saving={notificationState.saving} onClose={notificationState.closeModal} onSave={notificationState.handleSave} />
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件邮箱</label>
<input
type="email"
value={smtp.smtp_user || ''}
onChange={e => setSmtp({ ...smtp, smtp_user: e.target.value })}
placeholder="[email protected]"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">邮箱密码 / 授权码</label>
<div className="relative">
<input
type={showSmtpPassword ? 'text' : 'password'}
value={smtp.smtp_password || ''}
onChange={e => setSmtp({ ...smtp, smtp_password: e.target.value })}
placeholder="输入密码或授权码"
className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"
/>
<button
type="button"
onClick={() => setShowSmtpPassword(!showSmtpPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors"
>
{showSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
<p className="text-xs text-gray-500">QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label>
<input
type="text"
value={smtp.smtp_from_name || ''}
onChange={e => setSmtp({ ...smtp, smtp_from_name: e.target.value })}
placeholder="闲鱼自动回复系统"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件邮箱地址</label>
<input
type="email"
value={smtp.smtp_from_address || smtp.smtp_user || ''}
onChange={e => setSmtp({ ...smtp, smtp_from_address: e.target.value })}
placeholder="[email protected]"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700">
<input
type="checkbox"
checked={smtp.smtp_use_tls !== false}
onChange={e => setSmtp({ ...smtp, smtp_use_tls: e.target.checked, smtp_use_ssl: e.target.checked ? false : smtp.smtp_use_ssl })}
/>
STARTTLS(常用于 587 端口)
</label>
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700">
<input
type="checkbox"
checked={smtp.smtp_use_ssl === true}
onChange={e => setSmtp({ ...smtp, smtp_use_ssl: e.target.checked, smtp_use_tls: e.target.checked ? false : smtp.smtp_use_tls })}
/>
SSL/TLS 直连(常用于 465 端口)
</label>
</div>
<button
onClick={handleSaveSmtp}
disabled={smtpSaving}
className="ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
>
{smtpSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
{smtpSaving ? '保存中...' : '保存 SMTP 配置'}
</button>
</section>
)}
{/* 新建/编辑弹窗 */}
{showModal && createPortal(
<div className="modal-overlay">
<div className="modal-container" style={{ maxWidth: '36rem' }}>
<div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between">
<h3 className="text-xl font-extrabold text-gray-900">{editing ? '编辑通知渠道' : '新建通知渠道'}</h3>
<button
onClick={() => setShowModal(false)}
className="w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center"
>
<X className="w-5 h-5 text-gray-600" />
</button>
</div>
<div className="px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">渠道名称</label>
<input
type="text"
value={form.name}
onChange={e => setForm({ ...form, name: e.target.value })}
placeholder="例如:我的 Bark"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">渠道类型</label>
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
{(Object.keys(CHANNEL_TYPES) as NotificationChannelType[]).map(t => {
const m = CHANNEL_TYPES[t];
const TIcon = m.icon;
const selected = form.type === t;
return (
<button
key={t}
type="button"
onClick={() => setForm({ ...form, type: t, config: {} })}
className={`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${selected ? 'border-brand bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
>
<TIcon className={`w-5 h-5 ${selected ? 'text-brand' : 'text-gray-500'}`} />
<span className={`text-xs font-bold ${selected ? 'text-brand' : 'text-gray-600'}`}>{m.label}</span>
</button>
);
})}
</div>
</div>
{/* 配置指南:选中类型后显示对应获取步骤 */}
<div className="rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2">
<div className="flex items-center gap-2">
<Bell className="w-4 h-4 text-amber-600" />
<span className="text-sm font-bold text-amber-800">如何获取 {meta.label} 配置?</span>
</div>
<ol className="space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5">
{meta.guide.steps.map((step, i) => (
<li key={i}>{step}</li>
))}
</ol>
{meta.guide.urlFormat && (
<div className="text-xs text-amber-900/90">
<span className="font-bold">格式示例:</span>
<code className="mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]">{meta.guide.urlFormat}</code>
</div>
)}
{meta.guide.note && (
<p className="text-xs text-amber-800/80 leading-5 pt-1">💡 {meta.guide.note}</p>
)}
</div>
<div className="space-y-3">
{meta.fields.map(f => (
<div key={f.key} className="space-y-2">
<label className="block text-sm font-bold text-gray-800">
{f.label}
{f.required && <span className="text-red-500 ml-1">*</span>}
</label>
<input
type={f.type === 'password' ? 'password' : f.type === 'number' ? 'number' : 'text'}
value={String(form.config[f.key] || '')}
onChange={e => setForm({ ...form, config: { ...form.config, [f.key]: e.target.value } })}
placeholder={f.placeholder}
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
{f.help && <p className="text-xs text-gray-500">{f.help}</p>}
</div>
))}
</div>
{form.type === 'email' && (
<div className="overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40">
<div className="flex items-center justify-between gap-4 p-4">
<div>
<div className="text-sm font-extrabold text-gray-900">SMTP 来源</div>
<p className="mt-1 text-xs leading-5 text-gray-500">
{form.config.use_custom_smtp === true
? '当前渠道使用一套完整、独立的发件配置。'
: '当前渠道完整继承系统 SMTP,只单独设置收件邮箱。'}
</p>
</div>
<button
type="button"
onClick={() => {
const useCustom = form.config.use_custom_smtp === true;
setForm({
...form,
config: useCustom
? { ...form.config, use_custom_smtp: false }
: enableCustomSMTP(form.config, smtp),
});
}}
className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-brand' : 'bg-gray-300'}`}
aria-label="使用独立 SMTP"
>
<span className={`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${form.config.use_custom_smtp === true ? 'translate-x-5' : ''}`} />
</button>
</div>
{form.config.use_custom_smtp === true && (
<div className="space-y-4 border-t border-blue-100 bg-white/80 p-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">SMTP 服务器 <span className="text-red-500">*</span></label>
<input
type="text"
value={String(form.config.smtp_server || '')}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_server: e.target.value } })}
placeholder="smtp.qq.com"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">SMTP 端口 <span className="text-red-500">*</span></label>
<input
type="number"
value={String(form.config.smtp_port || 587)}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_port: e.target.value } })}
placeholder="587"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">登录邮箱 <span className="text-red-500">*</span></label>
<input
type="email"
value={String(form.config.smtp_user || '')}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_user: e.target.value } })}
placeholder="[email protected]"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">密码 / 授权码 <span className="text-red-500">*</span></label>
<div className="relative">
<input
type={showChannelSmtpPassword ? 'text' : 'password'}
value={String(form.config.smtp_password || '')}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_password: e.target.value } })}
placeholder="输入密码或授权码"
className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"
/>
<button
type="button"
onClick={() => setShowChannelSmtpPassword(value => !value)}
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600"
>
{showChannelSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label>
<input
type="text"
value={String(form.config.smtp_from_name || '')}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_from_name: e.target.value } })}
placeholder="闲鱼自动回复系统"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件邮箱地址 <span className="text-red-500">*</span></label>
<input
type="email"
value={String(form.config.smtp_from_address || '')}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_from_address: e.target.value } })}
placeholder="[email protected]"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700">
<input
type="checkbox"
checked={form.config.smtp_use_tls !== false}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_use_tls: e.target.checked, smtp_use_ssl: e.target.checked ? false : form.config.smtp_use_ssl } })}
/>
STARTTLS(常用于 587)
</label>
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700">
<input
type="checkbox"
checked={form.config.smtp_use_ssl === true}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_use_ssl: e.target.checked, smtp_use_tls: e.target.checked ? false : form.config.smtp_use_tls } })}
/>
SSL/TLS 直连(常用于 465)
</label>
</div>
</div>
)}
</div>
)}
<div className="space-y-3">
<div>
<label className="block text-sm font-bold text-gray-800">通知内容</label>
<p className="text-xs text-gray-500 mt-1">不选择表示接收全部通知;选择后仅接收勾选类型。</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{NOTIFICATION_EVENTS.map(event => {
const checked = form.event_types.includes(event.value);
return (
<button
key={event.value}
type="button"
onClick={() => {
const next = checked
? form.event_types.filter(item => item !== event.value)
: [...form.event_types, event.value];
setForm({ ...form, event_types: next });
}}
className={`text-left rounded-xl border px-3 py-2.5 transition-colors ${checked ? 'border-brand bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
>
<div className="flex items-center gap-2">
<span className={`w-4 h-4 rounded border flex items-center justify-center ${checked ? 'bg-brand border-brand' : 'border-gray-300'}`}>
{checked && <Check className="w-3 h-3 text-white" />}
</span>
<span className={`text-sm font-bold ${checked ? 'text-brand' : 'text-gray-800'}`}>{event.label}</span>
</div>
<p className="text-xs text-gray-500 mt-1 pl-6 leading-5">{event.description}</p>
</button>
);
})}
</div>
</div>
<label className="flex items-center gap-3 cursor-pointer">
<button
type="button"
onClick={() => setForm({ ...form, enabled: !form.enabled })}
className={`relative w-11 h-6 rounded-full transition-colors ${form.enabled ? 'bg-brand' : 'bg-gray-300'}`}
>
<span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${form.enabled ? 'translate-x-5' : ''}`} />
</button>
<span className="text-sm font-bold text-gray-800">启用此渠道</span>
</label>
</div>
<div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3">
<button
onClick={() => setShowModal(false)}
className="px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors"
>
取消
</button>
<button
onClick={handleSave}
disabled={saving}
className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
>
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
{saving ? '保存中...' : '保存'}
</button>
</div>
</div>
</div>,
document.body
)}
{/* Toast */}
{toast && (
<div className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${toast.type === 'success' ? 'bg-success-500' : 'bg-danger-500'}`}>
{toast.type === 'success' ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
{toast.text}
</div>
)}
{notificationState.toast && <div className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${notificationState.toast.type === 'success' ? 'bg-success-500' : 'bg-danger-500'}`}>{notificationState.toast.type === 'success' ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}{notificationState.toast.text}</div>}
</div>
);
};
+7 -5
View File
@@ -80,13 +80,15 @@ describe('frontend navigation routing', () => {
test('email notification config separates system and custom SMTP modes', () => {
const notifications = readFrontendFile('components/Notifications.tsx');
const notificationState = readFrontendFile('app/features/notifications/state.ts');
const notificationModal = readFrontendFile('app/features/notifications/components/NotificationChannelModal.tsx');
expect(notifications).toContain('interface NotificationsProps');
expect(notifications).toContain('isAdmin && (');
expect(notifications).toContain("key: 'to_email'");
expect(notifications).toContain('完整继承系统 SMTP');
expect(notifications).toContain('use_custom_smtp');
expect(notifications).not.toContain("key: 'from'");
expect(notifications).toContain('{isAdmin && <NotificationSmtpSettings');
expect(notificationState).toContain("key: 'to_email'");
expect(notificationModal).toContain('完整继承系统 SMTP');
expect(notificationModal).toContain('use_custom_smtp');
expect(notificationState).not.toContain("key: 'from'");
expect(notifications).not.toContain('注册验证码');
});
+20
View File
@@ -160,6 +160,26 @@ test('订单查询和导入 API 转发外部取消信号', async () => {
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/import', expect.objectContaining({ signal: expect.any(AbortSignal) }));
});
test('通知渠道和 SMTP API 转发外部取消信号', async () => {
// fetchMock 验证渠道读取、保存和 SMTP 读写都支持取消控制。
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse([]))
.mockResolvedValueOnce(jsonResponse({ success: true }))
.mockResolvedValueOnce(jsonResponse({ data: {} }))
.mockResolvedValueOnce(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
// controller 是通知 feature 传给服务 API 的共享取消控制器。
const controller = new AbortController();
await getNotificationChannels({ signal: controller.signal });
await updateNotificationChannel('channel-1', { enabled: false }, { signal: controller.signal });
await getSystemSettings({ signal: controller.signal });
await updateSystemSettings({ smtp_server: 'smtp.example.com' }, { signal: controller.signal });
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/notifications/channels', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/notifications/channels/channel-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/settings/system', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/settings/system', expect.objectContaining({ signal: expect.any(AbortSignal) }));
});
test('getShippingRulesPage sends filters and preserves pagination metadata', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
data: [{ id: 7, name: '付款规则', trigger_type: 'order_paid', enabled: false, actions: [] }],
+12 -12
View File
@@ -880,16 +880,16 @@ export const deleteReplyRule = async (id: string, cookieId: string): Promise<Ope
}
// Settings
export const getSystemSettings = async (): Promise<SystemSettings> => {
const res = await get<{data: SystemSettings}>('/api/v1/settings/system');
export const getSystemSettings = async (options?: RequestControlOptions): Promise<SystemSettings> => {
const res = await get<{data: SystemSettings}>('/api/v1/settings/system', undefined, options);
return normalizeSettings(res.data || res); // handle {success:true, data: {...}} wrapper if exists
};
export const updateSystemSettings = async (settings: Partial<SystemSettings>): Promise<OperationResponse> => {
export const updateSystemSettings = async (settings: Partial<SystemSettings>, options?: RequestControlOptions): Promise<OperationResponse> => {
const payload = Object.fromEntries(
Object.entries(settings).filter(([, value]) => value !== undefined && value !== null),
);
return put('/api/v1/settings/system', payload);
return put('/api/v1/settings/system', payload, options);
};
export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise<AIReplySettingsResponse> => {
@@ -956,15 +956,15 @@ export const getNotificationChannels = async (options?: RequestControlOptions):
return { success: true, data: channels };
}
export const createNotificationChannel = async (data: { name: string; type: string; config: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }): Promise<MutationIDResponse> => {
export const createNotificationChannel = async (data: { name: string; type: string; config: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }, options?: RequestControlOptions): Promise<MutationIDResponse> => {
return post('/api/v1/notifications/channels', {
...data,
config: JSON.stringify(data.config),
event_types: stringifyNotificationEventTypes(data.event_types)
});
}, options);
}
export const updateNotificationChannel = async (channelId: string, data: { name?: string; type?: string; config?: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }): Promise<OperationResponse> => {
export const updateNotificationChannel = async (channelId: string, data: { name?: string; type?: string; config?: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }, options?: RequestControlOptions): Promise<OperationResponse> => {
const payload: Record<string, unknown> = { ...data };
if ('config' in data) {
payload.config = JSON.stringify(data.config);
@@ -972,11 +972,11 @@ export const updateNotificationChannel = async (channelId: string, data: { name?
if ('event_types' in data) {
payload.event_types = stringifyNotificationEventTypes(data.event_types);
}
return put(`/api/v1/notifications/channels/${channelId}`, payload);
return put(`/api/v1/notifications/channels/${channelId}`, payload, options);
}
export const deleteNotificationChannel = async (channelId: string): Promise<OperationResponse> => {
return del(`/api/v1/notifications/channels/${channelId}`);
export const deleteNotificationChannel = async (channelId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
return del(`/api/v1/notifications/channels/${channelId}`, undefined, options);
}
// Message Notifications
@@ -1021,8 +1021,8 @@ export const setAccountBindings = async (cookieId: string, channelIds: number[])
}
// 测试发送
export const testNotificationChannel = async (channelId: string): Promise<OperationResponse> => {
return post(`/api/v1/notifications/channels/${channelId}/test`, {});
export const testNotificationChannel = async (channelId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
return post(`/api/v1/notifications/channels/${channelId}/test`, {}, options);
}
// Default Reply